tun2socks.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. /**
  2. * @file tun2socks.c
  3. * @author Ambroz Bizjak <[email protected]>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stdint.h>
  30. #include <stdio.h>
  31. #include <stddef.h>
  32. #include <string.h>
  33. #include <misc/version.h>
  34. #include <misc/loggers_string.h>
  35. #include <misc/loglevel.h>
  36. #include <misc/minmax.h>
  37. #include <misc/offset.h>
  38. #include <misc/dead.h>
  39. #include <misc/ipv4_proto.h>
  40. #include <misc/udp_proto.h>
  41. #include <misc/byteorder.h>
  42. #include <misc/balloc.h>
  43. #include <misc/open_standard_streams.h>
  44. #include <misc/read_file.h>
  45. #include <structure/LinkedList1.h>
  46. #include <base/BLog.h>
  47. #include <system/BReactor.h>
  48. #include <system/BSignal.h>
  49. #include <system/BAddr.h>
  50. #include <system/BNetwork.h>
  51. #include <flow/SinglePacketBuffer.h>
  52. #include <socksclient/BSocksClient.h>
  53. #include <tuntap/BTap.h>
  54. #include <lwip/init.h>
  55. #include <lwip/tcp_impl.h>
  56. #include <lwip/netif.h>
  57. #include <lwip/tcp.h>
  58. #include <tun2socks/SocksUdpGwClient.h>
  59. #ifndef BADVPN_USE_WINAPI
  60. #include <base/BLog_syslog.h>
  61. #endif
  62. #include <tun2socks/tun2socks.h>
  63. #include <generated/blog_channel_tun2socks.h>
  64. #define LOGGER_STDOUT 1
  65. #define LOGGER_SYSLOG 2
  66. #define SYNC_DECL \
  67. BPending sync_mark; \
  68. #define SYNC_FROMHERE \
  69. BPending_Init(&sync_mark, BReactor_PendingGroup(&ss), NULL, NULL); \
  70. BPending_Set(&sync_mark);
  71. #define SYNC_BREAK \
  72. BPending_Free(&sync_mark);
  73. #define SYNC_COMMIT \
  74. BReactor_Synchronize(&ss, &sync_mark.base); \
  75. BPending_Free(&sync_mark);
  76. // command-line options
  77. struct {
  78. int help;
  79. int version;
  80. int logger;
  81. #ifndef BADVPN_USE_WINAPI
  82. char *logger_syslog_facility;
  83. char *logger_syslog_ident;
  84. #endif
  85. int loglevel;
  86. int loglevels[BLOG_NUM_CHANNELS];
  87. char *tundev;
  88. char *netif_ipaddr;
  89. char *netif_netmask;
  90. char *socks_server_addr;
  91. char *username;
  92. char *password;
  93. char *password_file;
  94. char *udpgw_remote_server_addr;
  95. int udpgw_max_connections;
  96. int udpgw_connection_buffer_size;
  97. } options;
  98. // TCP client
  99. struct tcp_client {
  100. dead_t dead;
  101. dead_t dead_client;
  102. LinkedList1Node list_node;
  103. BAddr local_addr;
  104. BAddr remote_addr;
  105. struct tcp_pcb *pcb;
  106. int client_closed;
  107. uint8_t buf[TCP_WND];
  108. int buf_used;
  109. BSocksClient socks_client;
  110. int socks_up;
  111. int socks_closed;
  112. StreamPassInterface *socks_send_if;
  113. StreamRecvInterface *socks_recv_if;
  114. uint8_t socks_recv_buf[CLIENT_SOCKS_RECV_BUF_SIZE];
  115. int socks_recv_buf_used;
  116. int socks_recv_buf_sent;
  117. int socks_recv_waiting;
  118. int socks_recv_tcp_pending;
  119. };
  120. // IP address of netif
  121. BIPAddr netif_ipaddr;
  122. // netmask of netif
  123. BIPAddr netif_netmask;
  124. // SOCKS server address
  125. BAddr socks_server_addr;
  126. // allocated password file contents
  127. uint8_t *password_file_contents;
  128. // SOCKS authentication information
  129. struct BSocksClient_auth_info socks_auth_info[2];
  130. size_t socks_num_auth_info;
  131. // remote udpgw server addr, if provided
  132. BAddr udpgw_remote_server_addr;
  133. // reactor
  134. BReactor ss;
  135. // set to 1 by terminate
  136. int quitting;
  137. // TUN device
  138. BTap device;
  139. // device write buffer
  140. uint8_t *device_write_buf;
  141. // device reading
  142. SinglePacketBuffer device_read_buffer;
  143. PacketPassInterface device_read_interface;
  144. // udpgw client
  145. SocksUdpGwClient udpgw_client;
  146. int udp_mtu;
  147. // TCP timer
  148. BTimer tcp_timer;
  149. // job for initializing lwip
  150. BPending lwip_init_job;
  151. // lwip netif
  152. int have_netif;
  153. struct netif netif;
  154. // lwip TCP listener
  155. struct tcp_pcb *listener;
  156. // TCP clients
  157. LinkedList1 tcp_clients;
  158. // number of clients
  159. int num_clients;
  160. static void terminate (void);
  161. static void print_help (const char *name);
  162. static void print_version (void);
  163. static int parse_arguments (int argc, char *argv[]);
  164. static int process_arguments (void);
  165. static void signal_handler (void *unused);
  166. static void lwip_init_job_hadler (void *unused);
  167. static void tcp_timer_handler (void *unused);
  168. static void device_error_handler (void *unused);
  169. static void device_read_handler_send (void *unused, uint8_t *data, int data_len);
  170. static int process_device_udp_packet (uint8_t *data, int data_len);
  171. static err_t netif_init_func (struct netif *netif);
  172. static err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr);
  173. static void client_logfunc (struct tcp_client *client);
  174. static void client_log (struct tcp_client *client, int level, const char *fmt, ...);
  175. static err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err);
  176. static void client_handle_freed_client (struct tcp_client *client, int was_abrt);
  177. static int client_free_client (struct tcp_client *client);
  178. static void client_abort_client (struct tcp_client *client);
  179. static void client_free_socks (struct tcp_client *client);
  180. static void client_murder (struct tcp_client *client);
  181. static void client_dealloc (struct tcp_client *client);
  182. static void client_err_func (void *arg, err_t err);
  183. static err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err);
  184. static void client_socks_handler (struct tcp_client *client, int event);
  185. static void client_send_to_socks (struct tcp_client *client);
  186. static void client_socks_send_handler_done (struct tcp_client *client, int data_len);
  187. static void client_socks_recv_initiate (struct tcp_client *client);
  188. static void client_socks_recv_handler_done (struct tcp_client *client, int data_len);
  189. static int client_socks_recv_send_out (struct tcp_client *client);
  190. static err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len);
  191. static void udpgw_client_handler_received (void *unused, BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len);
  192. int main (int argc, char **argv)
  193. {
  194. if (argc <= 0) {
  195. return 1;
  196. }
  197. // open standard streams
  198. open_standard_streams();
  199. // parse command-line arguments
  200. if (!parse_arguments(argc, argv)) {
  201. fprintf(stderr, "Failed to parse arguments\n");
  202. print_help(argv[0]);
  203. goto fail0;
  204. }
  205. // handle --help and --version
  206. if (options.help) {
  207. print_version();
  208. print_help(argv[0]);
  209. return 0;
  210. }
  211. if (options.version) {
  212. print_version();
  213. return 0;
  214. }
  215. // initialize logger
  216. switch (options.logger) {
  217. case LOGGER_STDOUT:
  218. BLog_InitStdout();
  219. break;
  220. #ifndef BADVPN_USE_WINAPI
  221. case LOGGER_SYSLOG:
  222. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  223. fprintf(stderr, "Failed to initialize syslog logger\n");
  224. goto fail0;
  225. }
  226. break;
  227. #endif
  228. default:
  229. ASSERT(0);
  230. }
  231. // configure logger channels
  232. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  233. if (options.loglevels[i] >= 0) {
  234. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  235. }
  236. else if (options.loglevel >= 0) {
  237. BLog_SetChannelLoglevel(i, options.loglevel);
  238. }
  239. }
  240. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  241. // clear password contents pointer
  242. password_file_contents = NULL;
  243. // initialize network
  244. if (!BNetwork_GlobalInit()) {
  245. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  246. goto fail1;
  247. }
  248. // process arguments
  249. if (!process_arguments()) {
  250. BLog(BLOG_ERROR, "Failed to process arguments");
  251. goto fail1;
  252. }
  253. // init time
  254. BTime_Init();
  255. // init reactor
  256. if (!BReactor_Init(&ss)) {
  257. BLog(BLOG_ERROR, "BReactor_Init failed");
  258. goto fail1;
  259. }
  260. // set not quitting
  261. quitting = 0;
  262. // setup signal handler
  263. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  264. BLog(BLOG_ERROR, "BSignal_Init failed");
  265. goto fail2;
  266. }
  267. // init TUN device
  268. if (!BTap_Init(&device, &ss, options.tundev, device_error_handler, NULL, 1)) {
  269. BLog(BLOG_ERROR, "BTap_Init failed");
  270. goto fail3;
  271. }
  272. // NOTE: the order of the following is important:
  273. // first device writing must evaluate,
  274. // then lwip (so it can send packets to the device),
  275. // then device reading (so it can pass received packets to lwip).
  276. // init device reading
  277. PacketPassInterface_Init(&device_read_interface, BTap_GetMTU(&device), device_read_handler_send, NULL, BReactor_PendingGroup(&ss));
  278. if (!SinglePacketBuffer_Init(&device_read_buffer, BTap_GetOutput(&device), &device_read_interface, BReactor_PendingGroup(&ss))) {
  279. BLog(BLOG_ERROR, "SinglePacketBuffer_Init failed");
  280. goto fail4;
  281. }
  282. if (options.udpgw_remote_server_addr) {
  283. // compute UDP mtu
  284. udp_mtu = BTap_GetMTU(&device) - (int)(sizeof(struct ipv4_header) + sizeof(struct udp_header));
  285. int udpgw_mtu = udpgw_compute_mtu(udp_mtu);
  286. if (udpgw_mtu < 0 || udpgw_mtu > PACKETPROTO_MAXPAYLOAD) {
  287. BLog(BLOG_ERROR, "bad device MTU for UDP");
  288. goto fail4a;
  289. }
  290. // init udpgw client
  291. if (!SocksUdpGwClient_Init(&udpgw_client, udp_mtu, DEFAULT_UDPGW_MAX_CONNECTIONS, options.udpgw_connection_buffer_size, UDPGW_KEEPALIVE_TIME,
  292. socks_server_addr, socks_auth_info, socks_num_auth_info,
  293. udpgw_remote_server_addr, UDPGW_RECONNECT_TIME, &ss, NULL, udpgw_client_handler_received
  294. )) {
  295. BLog(BLOG_ERROR, "SocksUdpGwClient_Init failed");
  296. goto fail4a;
  297. }
  298. }
  299. // init lwip init job
  300. BPending_Init(&lwip_init_job, BReactor_PendingGroup(&ss), lwip_init_job_hadler, NULL);
  301. BPending_Set(&lwip_init_job);
  302. // init device write buffer
  303. if (!(device_write_buf = (uint8_t *)BAlloc(BTap_GetMTU(&device)))) {
  304. BLog(BLOG_ERROR, "BAlloc failed");
  305. goto fail5;
  306. }
  307. // init TCP timer
  308. // it won't trigger before lwip is initialized, becuase the lwip init is a job
  309. BTimer_Init(&tcp_timer, TCP_TMR_INTERVAL, tcp_timer_handler, NULL);
  310. BReactor_SetTimer(&ss, &tcp_timer);
  311. // set no netif
  312. have_netif = 0;
  313. // set no listener
  314. listener = NULL;
  315. // init clients list
  316. LinkedList1_Init(&tcp_clients);
  317. // init number of clients
  318. num_clients = 0;
  319. // enter event loop
  320. BLog(BLOG_NOTICE, "entering event loop");
  321. BReactor_Exec(&ss);
  322. // free clients
  323. LinkedList1Node *node;
  324. while (node = LinkedList1_GetFirst(&tcp_clients)) {
  325. struct tcp_client *client = UPPER_OBJECT(node, struct tcp_client, list_node);
  326. client_murder(client);
  327. }
  328. // free listener
  329. if (listener) {
  330. tcp_close(listener);
  331. }
  332. // free netif
  333. if (have_netif) {
  334. netif_remove(&netif);
  335. }
  336. BReactor_RemoveTimer(&ss, &tcp_timer);
  337. BFree(device_write_buf);
  338. fail5:
  339. BPending_Free(&lwip_init_job);
  340. if (options.udpgw_remote_server_addr) {
  341. SocksUdpGwClient_Free(&udpgw_client);
  342. }
  343. fail4a:
  344. SinglePacketBuffer_Free(&device_read_buffer);
  345. fail4:
  346. PacketPassInterface_Free(&device_read_interface);
  347. BTap_Free(&device);
  348. fail3:
  349. BSignal_Finish();
  350. fail2:
  351. BReactor_Free(&ss);
  352. fail1:
  353. BFree(password_file_contents);
  354. BLog(BLOG_NOTICE, "exiting");
  355. BLog_Free();
  356. fail0:
  357. DebugObjectGlobal_Finish();
  358. return 1;
  359. }
  360. void terminate (void)
  361. {
  362. ASSERT(!quitting)
  363. BLog(BLOG_NOTICE, "tearing down");
  364. // set quitting
  365. quitting = 1;
  366. // exit event loop
  367. BReactor_Quit(&ss, 1);
  368. }
  369. void print_help (const char *name)
  370. {
  371. printf(
  372. "Usage:\n"
  373. " %s\n"
  374. " [--help]\n"
  375. " [--version]\n"
  376. " [--logger <"LOGGERS_STRING">]\n"
  377. #ifndef BADVPN_USE_WINAPI
  378. " (logger=syslog?\n"
  379. " [--syslog-facility <string>]\n"
  380. " [--syslog-ident <string>]\n"
  381. " )\n"
  382. #endif
  383. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  384. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  385. " [--tundev <name>]\n"
  386. " --netif-ipaddr <ipaddr>\n"
  387. " --netif-netmask <ipnetmask>\n"
  388. " --socks-server-addr <addr>\n"
  389. " [--username <username>]\n"
  390. " [--password <password>]\n"
  391. " [--password-file <file>]\n"
  392. " [--udpgw-remote-server-addr <addr>]\n"
  393. " [--udpgw-max-connections <number>]\n"
  394. " [--udpgw-connection-buffer-size <number>]\n"
  395. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  396. name
  397. );
  398. }
  399. void print_version (void)
  400. {
  401. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  402. }
  403. int parse_arguments (int argc, char *argv[])
  404. {
  405. if (argc <= 0) {
  406. return 0;
  407. }
  408. options.help = 0;
  409. options.version = 0;
  410. options.logger = LOGGER_STDOUT;
  411. #ifndef BADVPN_USE_WINAPI
  412. options.logger_syslog_facility = "daemon";
  413. options.logger_syslog_ident = argv[0];
  414. #endif
  415. options.loglevel = -1;
  416. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  417. options.loglevels[i] = -1;
  418. }
  419. options.tundev = NULL;
  420. options.netif_ipaddr = NULL;
  421. options.netif_netmask = NULL;
  422. options.socks_server_addr = NULL;
  423. options.username = NULL;
  424. options.password = NULL;
  425. options.password_file = NULL;
  426. options.udpgw_remote_server_addr = NULL;
  427. options.udpgw_max_connections = DEFAULT_UDPGW_MAX_CONNECTIONS;
  428. options.udpgw_connection_buffer_size = DEFAULT_UDPGW_CONNECTION_BUFFER_SIZE;
  429. int i;
  430. for (i = 1; i < argc; i++) {
  431. char *arg = argv[i];
  432. if (!strcmp(arg, "--help")) {
  433. options.help = 1;
  434. }
  435. else if (!strcmp(arg, "--version")) {
  436. options.version = 1;
  437. }
  438. else if (!strcmp(arg, "--logger")) {
  439. if (1 >= argc - i) {
  440. fprintf(stderr, "%s: requires an argument\n", arg);
  441. return 0;
  442. }
  443. char *arg2 = argv[i + 1];
  444. if (!strcmp(arg2, "stdout")) {
  445. options.logger = LOGGER_STDOUT;
  446. }
  447. #ifndef BADVPN_USE_WINAPI
  448. else if (!strcmp(arg2, "syslog")) {
  449. options.logger = LOGGER_SYSLOG;
  450. }
  451. #endif
  452. else {
  453. fprintf(stderr, "%s: wrong argument\n", arg);
  454. return 0;
  455. }
  456. i++;
  457. }
  458. #ifndef BADVPN_USE_WINAPI
  459. else if (!strcmp(arg, "--syslog-facility")) {
  460. if (1 >= argc - i) {
  461. fprintf(stderr, "%s: requires an argument\n", arg);
  462. return 0;
  463. }
  464. options.logger_syslog_facility = argv[i + 1];
  465. i++;
  466. }
  467. else if (!strcmp(arg, "--syslog-ident")) {
  468. if (1 >= argc - i) {
  469. fprintf(stderr, "%s: requires an argument\n", arg);
  470. return 0;
  471. }
  472. options.logger_syslog_ident = argv[i + 1];
  473. i++;
  474. }
  475. #endif
  476. else if (!strcmp(arg, "--loglevel")) {
  477. if (1 >= argc - i) {
  478. fprintf(stderr, "%s: requires an argument\n", arg);
  479. return 0;
  480. }
  481. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  482. fprintf(stderr, "%s: wrong argument\n", arg);
  483. return 0;
  484. }
  485. i++;
  486. }
  487. else if (!strcmp(arg, "--channel-loglevel")) {
  488. if (2 >= argc - i) {
  489. fprintf(stderr, "%s: requires two arguments\n", arg);
  490. return 0;
  491. }
  492. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  493. if (channel < 0) {
  494. fprintf(stderr, "%s: wrong channel argument\n", arg);
  495. return 0;
  496. }
  497. int loglevel = parse_loglevel(argv[i + 2]);
  498. if (loglevel < 0) {
  499. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  500. return 0;
  501. }
  502. options.loglevels[channel] = loglevel;
  503. i += 2;
  504. }
  505. else if (!strcmp(arg, "--tundev")) {
  506. if (1 >= argc - i) {
  507. fprintf(stderr, "%s: requires an argument\n", arg);
  508. return 0;
  509. }
  510. options.tundev = argv[i + 1];
  511. i++;
  512. }
  513. else if (!strcmp(arg, "--netif-ipaddr")) {
  514. if (1 >= argc - i) {
  515. fprintf(stderr, "%s: requires an argument\n", arg);
  516. return 0;
  517. }
  518. options.netif_ipaddr = argv[i + 1];
  519. i++;
  520. }
  521. else if (!strcmp(arg, "--netif-netmask")) {
  522. if (1 >= argc - i) {
  523. fprintf(stderr, "%s: requires an argument\n", arg);
  524. return 0;
  525. }
  526. options.netif_netmask = argv[i + 1];
  527. i++;
  528. }
  529. else if (!strcmp(arg, "--socks-server-addr")) {
  530. if (1 >= argc - i) {
  531. fprintf(stderr, "%s: requires an argument\n", arg);
  532. return 0;
  533. }
  534. options.socks_server_addr = argv[i + 1];
  535. i++;
  536. }
  537. else if (!strcmp(arg, "--username")) {
  538. if (1 >= argc - i) {
  539. fprintf(stderr, "%s: requires an argument\n", arg);
  540. return 0;
  541. }
  542. options.username = argv[i + 1];
  543. i++;
  544. }
  545. else if (!strcmp(arg, "--password")) {
  546. if (1 >= argc - i) {
  547. fprintf(stderr, "%s: requires an argument\n", arg);
  548. return 0;
  549. }
  550. options.password = argv[i + 1];
  551. i++;
  552. }
  553. else if (!strcmp(arg, "--password-file")) {
  554. if (1 >= argc - i) {
  555. fprintf(stderr, "%s: requires an argument\n", arg);
  556. return 0;
  557. }
  558. options.password_file = argv[i + 1];
  559. i++;
  560. }
  561. else if (!strcmp(arg, "--udpgw-remote-server-addr")) {
  562. if (1 >= argc - i) {
  563. fprintf(stderr, "%s: requires an argument\n", arg);
  564. return 0;
  565. }
  566. options.udpgw_remote_server_addr = argv[i + 1];
  567. i++;
  568. }
  569. else if (!strcmp(arg, "--udpgw-max-connections")) {
  570. if (1 >= argc - i) {
  571. fprintf(stderr, "%s: requires an argument\n", arg);
  572. return 0;
  573. }
  574. if ((options.udpgw_max_connections = atoi(argv[i + 1])) <= 0) {
  575. fprintf(stderr, "%s: wrong argument\n", arg);
  576. return 0;
  577. }
  578. i++;
  579. }
  580. else if (!strcmp(arg, "--udpgw-connection-buffer-size")) {
  581. if (1 >= argc - i) {
  582. fprintf(stderr, "%s: requires an argument\n", arg);
  583. return 0;
  584. }
  585. if ((options.udpgw_connection_buffer_size = atoi(argv[i + 1])) <= 0) {
  586. fprintf(stderr, "%s: wrong argument\n", arg);
  587. return 0;
  588. }
  589. i++;
  590. }
  591. else {
  592. fprintf(stderr, "unknown option: %s\n", arg);
  593. return 0;
  594. }
  595. }
  596. if (options.help || options.version) {
  597. return 1;
  598. }
  599. if (!options.netif_ipaddr) {
  600. fprintf(stderr, "--netif-ipaddr is required\n");
  601. return 0;
  602. }
  603. if (!options.netif_netmask) {
  604. fprintf(stderr, "--netif-netmask is required\n");
  605. return 0;
  606. }
  607. if (!options.socks_server_addr) {
  608. fprintf(stderr, "--socks-server-addr is required\n");
  609. return 0;
  610. }
  611. if (options.username) {
  612. if (!options.password && !options.password_file) {
  613. fprintf(stderr, "username given but password not given\n");
  614. return 0;
  615. }
  616. if (options.password && options.password_file) {
  617. fprintf(stderr, "--password and --password-file cannot both be given\n");
  618. return 0;
  619. }
  620. }
  621. return 1;
  622. }
  623. int process_arguments (void)
  624. {
  625. ASSERT(!password_file_contents)
  626. // resolve netif ipaddr
  627. if (!BIPAddr_Resolve(&netif_ipaddr, options.netif_ipaddr, 0)) {
  628. BLog(BLOG_ERROR, "netif ipaddr: BIPAddr_Resolve failed");
  629. return 0;
  630. }
  631. if (netif_ipaddr.type != BADDR_TYPE_IPV4) {
  632. BLog(BLOG_ERROR, "netif ipaddr: must be an IPv4 address");
  633. return 0;
  634. }
  635. // resolve netif netmask
  636. if (!BIPAddr_Resolve(&netif_netmask, options.netif_netmask, 0)) {
  637. BLog(BLOG_ERROR, "netif netmask: BIPAddr_Resolve failed");
  638. return 0;
  639. }
  640. if (netif_netmask.type != BADDR_TYPE_IPV4) {
  641. BLog(BLOG_ERROR, "netif netmask: must be an IPv4 address");
  642. return 0;
  643. }
  644. // resolve SOCKS server address
  645. if (!BAddr_Parse2(&socks_server_addr, options.socks_server_addr, NULL, 0, 0)) {
  646. BLog(BLOG_ERROR, "socks server addr: BAddr_Parse2 failed");
  647. return 0;
  648. }
  649. // add none socks authentication method
  650. socks_auth_info[0] = BSocksClient_auth_none();
  651. socks_num_auth_info = 1;
  652. // add password socks authentication method
  653. if (options.username) {
  654. const char *password;
  655. size_t password_len;
  656. if (options.password) {
  657. password = options.password;
  658. password_len = strlen(options.password);
  659. } else {
  660. if (!read_file(options.password_file, &password_file_contents, &password_len)) {
  661. BLog(BLOG_ERROR, "failed to read password file");
  662. return 0;
  663. }
  664. password = (char *)password_file_contents;
  665. }
  666. socks_auth_info[socks_num_auth_info++] = BSocksClient_auth_password(
  667. options.username, strlen(options.username),
  668. password, password_len
  669. );
  670. }
  671. // resolve remote udpgw server address
  672. if (options.udpgw_remote_server_addr) {
  673. if (!BAddr_Parse2(&udpgw_remote_server_addr, options.udpgw_remote_server_addr, NULL, 0, 0)) {
  674. BLog(BLOG_ERROR, "remote udpgw server addr: BAddr_Parse2 failed");
  675. return 0;
  676. }
  677. }
  678. return 1;
  679. }
  680. void signal_handler (void *unused)
  681. {
  682. ASSERT(!quitting)
  683. BLog(BLOG_NOTICE, "termination requested");
  684. terminate();
  685. }
  686. void lwip_init_job_hadler (void *unused)
  687. {
  688. ASSERT(!quitting)
  689. ASSERT(netif_ipaddr.type == BADDR_TYPE_IPV4)
  690. ASSERT(netif_netmask.type == BADDR_TYPE_IPV4)
  691. ASSERT(!have_netif)
  692. ASSERT(!listener)
  693. BLog(BLOG_DEBUG, "lwip init");
  694. // NOTE: the device may fail during this, but there's no harm in not checking
  695. // for that at every step
  696. // init lwip
  697. lwip_init();
  698. // make addresses for netif
  699. ip_addr_t addr;
  700. addr.addr = netif_ipaddr.ipv4;
  701. ip_addr_t netmask;
  702. netmask.addr = netif_netmask.ipv4;
  703. ip_addr_t gw;
  704. ip_addr_set_any(&gw);
  705. // init netif
  706. if (!netif_add(&netif, &addr, &netmask, &gw, NULL, netif_init_func, ip_input)) {
  707. BLog(BLOG_ERROR, "netif_add failed");
  708. goto fail;
  709. }
  710. have_netif = 1;
  711. // set netif up
  712. netif_set_up(&netif);
  713. // set netif pretend TCP
  714. netif_set_pretend_tcp(&netif, 1);
  715. // set netif default
  716. netif_set_default(&netif);
  717. // init listener
  718. struct tcp_pcb *l = tcp_new();
  719. if (!l) {
  720. BLog(BLOG_ERROR, "tcp_new failed");
  721. goto fail;
  722. }
  723. // bind listener
  724. if (tcp_bind_to_netif(l, "ho0") != ERR_OK) {
  725. BLog(BLOG_ERROR, "tcp_bind_to_netif failed");
  726. tcp_close(l);
  727. goto fail;
  728. }
  729. // listen listener
  730. if (!(listener = tcp_listen(l))) {
  731. BLog(BLOG_ERROR, "tcp_listen failed");
  732. tcp_close(l);
  733. goto fail;
  734. }
  735. // setup listener accept handler
  736. tcp_accept(listener, listener_accept_func);
  737. return;
  738. fail:
  739. if (!quitting) {
  740. terminate();
  741. }
  742. }
  743. void tcp_timer_handler (void *unused)
  744. {
  745. ASSERT(!quitting)
  746. BLog(BLOG_DEBUG, "TCP timer");
  747. // schedule next timer
  748. // TODO: calculate timeout so we don't drift
  749. BReactor_SetTimer(&ss, &tcp_timer);
  750. tcp_tmr();
  751. return;
  752. }
  753. void device_error_handler (void *unused)
  754. {
  755. ASSERT(!quitting)
  756. BLog(BLOG_ERROR, "device error");
  757. terminate();
  758. return;
  759. }
  760. void device_read_handler_send (void *unused, uint8_t *data, int data_len)
  761. {
  762. ASSERT(!quitting)
  763. BLog(BLOG_DEBUG, "device: received packet");
  764. // accept packet
  765. PacketPassInterface_Done(&device_read_interface);
  766. // process UDP directly
  767. if (process_device_udp_packet(data, data_len)) {
  768. return;
  769. }
  770. // obtain pbuf
  771. struct pbuf *p = pbuf_alloc(PBUF_RAW, data_len, PBUF_POOL);
  772. if (!p) {
  773. BLog(BLOG_WARNING, "device read: pbuf_alloc failed");
  774. return;
  775. }
  776. // write packet to pbuf
  777. ASSERT_FORCE(pbuf_take(p, data, data_len) == ERR_OK)
  778. // pass pbuf to input
  779. if (netif.input(p, &netif) != ERR_OK) {
  780. BLog(BLOG_WARNING, "device read: input failed");
  781. pbuf_free(p);
  782. }
  783. }
  784. int process_device_udp_packet (uint8_t *data, int data_len)
  785. {
  786. // do nothing if we don't have udpgw
  787. if (!options.udpgw_remote_server_addr) {
  788. goto fail;
  789. }
  790. // ignore non-UDP packets
  791. if (data_len < sizeof(struct ipv4_header) || ((struct ipv4_header *)data)->protocol != IPV4_PROTOCOL_UDP) {
  792. goto fail;
  793. }
  794. // parse IPv4 header
  795. struct ipv4_header *ipv4_header;
  796. if (!ipv4_check(data, data_len, &ipv4_header, &data, &data_len)) {
  797. goto fail;
  798. }
  799. // parse UDP header
  800. if (data_len < sizeof(struct udp_header)) {
  801. goto fail;
  802. }
  803. struct udp_header *udp_header = (struct udp_header *)data;
  804. data += sizeof(*udp_header);
  805. data_len -= sizeof(*udp_header);
  806. // verify UDP payload
  807. int udp_length = ntoh16(udp_header->length);
  808. if (udp_length < sizeof(*udp_header)) {
  809. goto fail;
  810. }
  811. if (udp_length > sizeof(*udp_header) + data_len) {
  812. goto fail;
  813. }
  814. // ignore stray data
  815. data_len = udp_length - sizeof(*udp_header);
  816. // check payload length
  817. if (data_len > udp_mtu) {
  818. goto fail;
  819. }
  820. // verify UDP checksum
  821. uint16_t checksum_in_packet = udp_header->checksum;
  822. udp_header->checksum = 0;
  823. uint16_t checksum_computed = udp_checksum((uint8_t *)udp_header, udp_length, ipv4_header->source_address, ipv4_header->destination_address);
  824. udp_header->checksum = checksum_in_packet;
  825. if (checksum_in_packet != checksum_computed) {
  826. goto fail;
  827. }
  828. BLog(BLOG_INFO, "UDP: from device %d bytes", data_len);
  829. // construct addresses
  830. BAddr local_addr;
  831. BAddr_InitIPv4(&local_addr, ipv4_header->source_address, udp_header->source_port);
  832. BAddr remote_addr;
  833. BAddr_InitIPv4(&remote_addr, ipv4_header->destination_address, udp_header->dest_port);
  834. // submit packet to udpgw
  835. SocksUdpGwClient_SubmitPacket(&udpgw_client, local_addr, remote_addr, data, data_len);
  836. return 1;
  837. fail:
  838. return 0;
  839. }
  840. err_t netif_init_func (struct netif *netif)
  841. {
  842. BLog(BLOG_DEBUG, "netif func init");
  843. netif->name[0] = 'h';
  844. netif->name[1] = 'o';
  845. netif->output = netif_output_func;
  846. return ERR_OK;
  847. }
  848. err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr)
  849. {
  850. SYNC_DECL
  851. BLog(BLOG_DEBUG, "device write: send packet");
  852. if (quitting) {
  853. return ERR_OK;
  854. }
  855. // if there is just one chunk, send it directly, else via buffer
  856. if (!p->next) {
  857. if (p->len > BTap_GetMTU(&device)) {
  858. BLog(BLOG_WARNING, "netif func output: no space left");
  859. goto out;
  860. }
  861. SYNC_FROMHERE
  862. BTap_Send(&device, (uint8_t *)p->payload, p->len);
  863. SYNC_COMMIT
  864. } else {
  865. int len = 0;
  866. do {
  867. if (p->len > BTap_GetMTU(&device) - len) {
  868. BLog(BLOG_WARNING, "netif func output: no space left");
  869. goto out;
  870. }
  871. memcpy(device_write_buf + len, p->payload, p->len);
  872. len += p->len;
  873. } while (p = p->next);
  874. SYNC_FROMHERE
  875. BTap_Send(&device, device_write_buf, len);
  876. SYNC_COMMIT
  877. }
  878. out:
  879. return ERR_OK;
  880. }
  881. void client_logfunc (struct tcp_client *client)
  882. {
  883. char local_addr_s[BADDR_MAX_PRINT_LEN];
  884. BAddr_Print(&client->local_addr, local_addr_s);
  885. char remote_addr_s[BADDR_MAX_PRINT_LEN];
  886. BAddr_Print(&client->remote_addr, remote_addr_s);
  887. BLog_Append("%05d (%s %s): ", num_clients, local_addr_s, remote_addr_s);
  888. }
  889. void client_log (struct tcp_client *client, int level, const char *fmt, ...)
  890. {
  891. va_list vl;
  892. va_start(vl, fmt);
  893. BLog_LogViaFuncVarArg((BLog_logfunc)client_logfunc, client, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  894. va_end(vl);
  895. }
  896. err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err)
  897. {
  898. ASSERT(listener)
  899. ASSERT(err == ERR_OK)
  900. // signal accepted
  901. tcp_accepted(listener);
  902. // allocate client structure
  903. struct tcp_client *client = (struct tcp_client *)malloc(sizeof(*client));
  904. if (!client) {
  905. BLog(BLOG_ERROR, "listener accept: malloc failed");
  906. return ERR_MEM;
  907. }
  908. SYNC_DECL
  909. SYNC_FROMHERE
  910. // init SOCKS
  911. BAddr addr;
  912. BAddr_InitIPv4(&addr, newpcb->local_ip.addr, hton16(newpcb->local_port));
  913. #ifdef OVERRIDE_DEST_ADDR
  914. ASSERT_FORCE(BAddr_Parse2(&addr, OVERRIDE_DEST_ADDR, NULL, 0, 1))
  915. #endif
  916. if (!BSocksClient_Init(&client->socks_client, socks_server_addr, socks_auth_info, socks_num_auth_info,
  917. addr, (BSocksClient_handler)client_socks_handler, client, &ss)) {
  918. BLog(BLOG_ERROR, "listener accept: BSocksClient_Init failed");
  919. SYNC_BREAK
  920. free(client);
  921. return ERR_MEM;
  922. }
  923. // init dead vars
  924. DEAD_INIT(client->dead);
  925. DEAD_INIT(client->dead_client);
  926. // add to linked list
  927. LinkedList1_Append(&tcp_clients, &client->list_node);
  928. // increment counter
  929. ASSERT(num_clients >= 0)
  930. num_clients++;
  931. // set pcb
  932. client->pcb = newpcb;
  933. // set client not closed
  934. client->client_closed = 0;
  935. // read addresses
  936. BAddr_InitIPv4(&client->local_addr, client->pcb->local_ip.addr, hton16(client->pcb->local_port));
  937. BAddr_InitIPv4(&client->remote_addr, client->pcb->remote_ip.addr, hton16(client->pcb->remote_port));
  938. // setup handler argument
  939. tcp_arg(client->pcb, client);
  940. // setup handlers
  941. tcp_err(client->pcb, client_err_func);
  942. tcp_recv(client->pcb, client_recv_func);
  943. // setup buffer
  944. client->buf_used = 0;
  945. // set SOCKS not up, not closed
  946. client->socks_up = 0;
  947. client->socks_closed = 0;
  948. client_log(client, BLOG_INFO, "accepted");
  949. DEAD_ENTER(client->dead_client)
  950. SYNC_COMMIT
  951. DEAD_LEAVE2(client->dead_client)
  952. if (DEAD_KILLED == -1) {
  953. return ERR_ABRT;
  954. }
  955. return ERR_OK;
  956. }
  957. void client_handle_freed_client (struct tcp_client *client, int was_abrt)
  958. {
  959. ASSERT(!client->client_closed)
  960. ASSERT(was_abrt == 0 || was_abrt == 1)
  961. // pcb was taken care of by the caller
  962. // kill client dead var
  963. DEAD_KILL_WITH(client->dead_client, (was_abrt ? -1 : 1));
  964. // set client closed
  965. client->client_closed = 1;
  966. // if we have data to be sent to SOCKS and can send it, keep sending
  967. if (client->buf_used > 0 && !client->socks_closed) {
  968. client_log(client, BLOG_INFO, "waiting untill buffered data is sent to SOCKS");
  969. } else {
  970. if (!client->socks_closed) {
  971. client_free_socks(client);
  972. } else {
  973. client_dealloc(client);
  974. }
  975. }
  976. }
  977. int client_free_client (struct tcp_client *client)
  978. {
  979. ASSERT(!client->client_closed)
  980. int was_abrt = 0;
  981. // remove callbacks
  982. tcp_err(client->pcb, NULL);
  983. tcp_recv(client->pcb, NULL);
  984. tcp_sent(client->pcb, NULL);
  985. // free pcb
  986. err_t err = tcp_close(client->pcb);
  987. if (err != ERR_OK) {
  988. client_log(client, BLOG_ERROR, "tcp_close failed (%d)", err);
  989. tcp_abort(client->pcb);
  990. was_abrt = 1;
  991. }
  992. client_handle_freed_client(client, was_abrt);
  993. return was_abrt;
  994. }
  995. void client_abort_client (struct tcp_client *client)
  996. {
  997. ASSERT(!client->client_closed)
  998. // remove callbacks
  999. tcp_err(client->pcb, NULL);
  1000. tcp_recv(client->pcb, NULL);
  1001. tcp_sent(client->pcb, NULL);
  1002. // free pcb
  1003. tcp_abort(client->pcb);
  1004. client_handle_freed_client(client, 1);
  1005. }
  1006. void client_free_socks (struct tcp_client *client)
  1007. {
  1008. ASSERT(!client->socks_closed)
  1009. // stop sending to SOCKS
  1010. if (client->socks_up) {
  1011. // stop receiving from client
  1012. if (!client->client_closed) {
  1013. tcp_recv(client->pcb, NULL);
  1014. }
  1015. }
  1016. // free SOCKS
  1017. BSocksClient_Free(&client->socks_client);
  1018. // set SOCKS closed
  1019. client->socks_closed = 1;
  1020. // if we have data to be sent to the client and we can send it, keep sending
  1021. if (client->socks_up && (client->socks_recv_buf_used >= 0 || client->socks_recv_tcp_pending > 0) && !client->client_closed) {
  1022. client_log(client, BLOG_INFO, "waiting until buffered data is sent to client");
  1023. } else {
  1024. if (!client->client_closed) {
  1025. client_free_client(client);
  1026. } else {
  1027. client_dealloc(client);
  1028. }
  1029. }
  1030. }
  1031. void client_murder (struct tcp_client *client)
  1032. {
  1033. // free client
  1034. if (!client->client_closed) {
  1035. // remove callbacks
  1036. tcp_err(client->pcb, NULL);
  1037. tcp_recv(client->pcb, NULL);
  1038. tcp_sent(client->pcb, NULL);
  1039. // abort
  1040. tcp_abort(client->pcb);
  1041. // kill client dead var
  1042. DEAD_KILL_WITH(client->dead_client, -1);
  1043. // set client closed
  1044. client->client_closed = 1;
  1045. }
  1046. // free SOCKS
  1047. if (!client->socks_closed) {
  1048. // free SOCKS
  1049. BSocksClient_Free(&client->socks_client);
  1050. // set SOCKS closed
  1051. client->socks_closed = 1;
  1052. }
  1053. // dealloc entry
  1054. client_dealloc(client);
  1055. }
  1056. void client_dealloc (struct tcp_client *client)
  1057. {
  1058. ASSERT(client->client_closed)
  1059. ASSERT(client->socks_closed)
  1060. // decrement counter
  1061. ASSERT(num_clients > 0)
  1062. num_clients--;
  1063. // remove client entry
  1064. LinkedList1_Remove(&tcp_clients, &client->list_node);
  1065. // kill dead var
  1066. DEAD_KILL(client->dead);
  1067. // free memory
  1068. free(client);
  1069. }
  1070. void client_err_func (void *arg, err_t err)
  1071. {
  1072. struct tcp_client *client = (struct tcp_client *)arg;
  1073. ASSERT(!client->client_closed)
  1074. client_log(client, BLOG_INFO, "client error (%d)", (int)err);
  1075. // the pcb was taken care of by the caller
  1076. client_handle_freed_client(client, 0);
  1077. }
  1078. err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  1079. {
  1080. struct tcp_client *client = (struct tcp_client *)arg;
  1081. ASSERT(!client->client_closed)
  1082. ASSERT(err == ERR_OK) // checked in lwIP source. Otherwise, I've no idea what should
  1083. // be done with the pbuf in case of an error.
  1084. if (!p) {
  1085. client_log(client, BLOG_INFO, "client closed");
  1086. int ret = client_free_client(client);
  1087. return (ret ? ERR_ABRT : ERR_OK);
  1088. }
  1089. ASSERT(p->tot_len > 0)
  1090. // check if we have enough buffer
  1091. if (p->tot_len > sizeof(client->buf) - client->buf_used) {
  1092. client_log(client, BLOG_ERROR, "no buffer for data !?!");
  1093. return ERR_MEM;
  1094. }
  1095. // copy data to buffer
  1096. ASSERT_EXECUTE(pbuf_copy_partial(p, client->buf + client->buf_used, p->tot_len, 0) == p->tot_len)
  1097. client->buf_used += p->tot_len;
  1098. // if there was nothing in the buffer before, and SOCKS is up, start send data
  1099. if (client->buf_used == p->tot_len && client->socks_up) {
  1100. ASSERT(!client->socks_closed) // this callback is removed when SOCKS is closed
  1101. SYNC_DECL
  1102. SYNC_FROMHERE
  1103. client_send_to_socks(client);
  1104. DEAD_ENTER(client->dead_client)
  1105. SYNC_COMMIT
  1106. DEAD_LEAVE2(client->dead_client)
  1107. if (DEAD_KILLED == -1) {
  1108. return ERR_ABRT;
  1109. }
  1110. }
  1111. // free pbuff
  1112. pbuf_free(p);
  1113. return ERR_OK;
  1114. }
  1115. void client_socks_handler (struct tcp_client *client, int event)
  1116. {
  1117. ASSERT(!client->socks_closed)
  1118. switch (event) {
  1119. case BSOCKSCLIENT_EVENT_ERROR: {
  1120. client_log(client, BLOG_INFO, "SOCKS error");
  1121. client_free_socks(client);
  1122. } break;
  1123. case BSOCKSCLIENT_EVENT_UP: {
  1124. ASSERT(!client->socks_up)
  1125. client_log(client, BLOG_INFO, "SOCKS up");
  1126. // init sending
  1127. client->socks_send_if = BSocksClient_GetSendInterface(&client->socks_client);
  1128. StreamPassInterface_Sender_Init(client->socks_send_if, (StreamPassInterface_handler_done)client_socks_send_handler_done, client);
  1129. // init receiving
  1130. client->socks_recv_if = BSocksClient_GetRecvInterface(&client->socks_client);
  1131. StreamRecvInterface_Receiver_Init(client->socks_recv_if, (StreamRecvInterface_handler_done)client_socks_recv_handler_done, client);
  1132. client->socks_recv_buf_used = -1;
  1133. client->socks_recv_tcp_pending = 0;
  1134. tcp_sent(client->pcb, client_sent_func);
  1135. // set up
  1136. client->socks_up = 1;
  1137. // start sending data if there is any
  1138. if (client->buf_used > 0) {
  1139. client_send_to_socks(client);
  1140. }
  1141. // start receiving data if client is still up
  1142. if (!client->client_closed) {
  1143. client_socks_recv_initiate(client);
  1144. }
  1145. } break;
  1146. case BSOCKSCLIENT_EVENT_ERROR_CLOSED: {
  1147. ASSERT(client->socks_up)
  1148. client_log(client, BLOG_INFO, "SOCKS closed");
  1149. client_free_socks(client);
  1150. } break;
  1151. default:
  1152. ASSERT(0);
  1153. }
  1154. }
  1155. void client_send_to_socks (struct tcp_client *client)
  1156. {
  1157. ASSERT(!client->socks_closed)
  1158. ASSERT(client->socks_up)
  1159. ASSERT(client->buf_used > 0)
  1160. // schedule sending
  1161. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  1162. }
  1163. void client_socks_send_handler_done (struct tcp_client *client, int data_len)
  1164. {
  1165. ASSERT(!client->socks_closed)
  1166. ASSERT(client->socks_up)
  1167. ASSERT(client->buf_used > 0)
  1168. ASSERT(data_len > 0)
  1169. ASSERT(data_len <= client->buf_used)
  1170. // remove sent data from buffer
  1171. memmove(client->buf, client->buf + data_len, client->buf_used - data_len);
  1172. client->buf_used -= data_len;
  1173. if (!client->client_closed) {
  1174. // confirm sent data
  1175. tcp_recved(client->pcb, data_len);
  1176. }
  1177. if (client->buf_used > 0) {
  1178. // send any further data
  1179. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  1180. }
  1181. else if (client->client_closed) {
  1182. // client was closed we've sent everything we had buffered; we're done with it
  1183. client_log(client, BLOG_INFO, "removing after client went down");
  1184. client_free_socks(client);
  1185. }
  1186. }
  1187. void client_socks_recv_initiate (struct tcp_client *client)
  1188. {
  1189. ASSERT(!client->client_closed)
  1190. ASSERT(!client->socks_closed)
  1191. ASSERT(client->socks_up)
  1192. ASSERT(client->socks_recv_buf_used == -1)
  1193. StreamRecvInterface_Receiver_Recv(client->socks_recv_if, client->socks_recv_buf, sizeof(client->socks_recv_buf));
  1194. }
  1195. void client_socks_recv_handler_done (struct tcp_client *client, int data_len)
  1196. {
  1197. ASSERT(data_len > 0)
  1198. ASSERT(data_len <= sizeof(client->socks_recv_buf))
  1199. ASSERT(!client->socks_closed)
  1200. ASSERT(client->socks_up)
  1201. ASSERT(client->socks_recv_buf_used == -1)
  1202. // if client was closed, stop receiving
  1203. if (client->client_closed) {
  1204. return;
  1205. }
  1206. // set amount of data in buffer
  1207. client->socks_recv_buf_used = data_len;
  1208. client->socks_recv_buf_sent = 0;
  1209. client->socks_recv_waiting = 0;
  1210. // send to client
  1211. if (client_socks_recv_send_out(client) < 0) {
  1212. return;
  1213. }
  1214. // continue receiving if needed
  1215. if (client->socks_recv_buf_used == -1) {
  1216. client_socks_recv_initiate(client);
  1217. }
  1218. }
  1219. int client_socks_recv_send_out (struct tcp_client *client)
  1220. {
  1221. ASSERT(!client->client_closed)
  1222. ASSERT(client->socks_up)
  1223. ASSERT(client->socks_recv_buf_used > 0)
  1224. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  1225. ASSERT(!client->socks_recv_waiting)
  1226. // return value -1 means tcp_abort() was done,
  1227. // 0 means it wasn't and the client (pcb) is still up
  1228. do {
  1229. int to_write = bmin_int(client->socks_recv_buf_used - client->socks_recv_buf_sent, tcp_sndbuf(client->pcb));
  1230. if (to_write == 0) {
  1231. break;
  1232. }
  1233. err_t err = tcp_write(client->pcb, client->socks_recv_buf + client->socks_recv_buf_sent, to_write, TCP_WRITE_FLAG_COPY);
  1234. if (err != ERR_OK) {
  1235. if (err == ERR_MEM) {
  1236. break;
  1237. }
  1238. client_log(client, BLOG_INFO, "tcp_write failed (%d)", (int)err);
  1239. client_abort_client(client);
  1240. return -1;
  1241. }
  1242. client->socks_recv_buf_sent += to_write;
  1243. client->socks_recv_tcp_pending += to_write;
  1244. } while (client->socks_recv_buf_sent < client->socks_recv_buf_used);
  1245. // start sending now
  1246. err_t err = tcp_output(client->pcb);
  1247. if (err != ERR_OK) {
  1248. client_log(client, BLOG_INFO, "tcp_output failed (%d)", (int)err);
  1249. client_abort_client(client);
  1250. return -1;
  1251. }
  1252. // more data to queue?
  1253. if (client->socks_recv_buf_sent < client->socks_recv_buf_used) {
  1254. if (client->socks_recv_tcp_pending == 0) {
  1255. client_log(client, BLOG_ERROR, "can't queue data, but all data was confirmed !?!");
  1256. client_abort_client(client);
  1257. return -1;
  1258. }
  1259. // set waiting, continue in client_sent_func
  1260. client->socks_recv_waiting = 1;
  1261. return 0;
  1262. }
  1263. // everything was queued
  1264. client->socks_recv_buf_used = -1;
  1265. return 0;
  1266. }
  1267. err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len)
  1268. {
  1269. struct tcp_client *client = (struct tcp_client *)arg;
  1270. ASSERT(!client->client_closed)
  1271. ASSERT(client->socks_up)
  1272. ASSERT(len > 0)
  1273. ASSERT(len <= client->socks_recv_tcp_pending)
  1274. // decrement pending
  1275. client->socks_recv_tcp_pending -= len;
  1276. // continue queuing
  1277. if (client->socks_recv_buf_used > 0) {
  1278. ASSERT(client->socks_recv_waiting)
  1279. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  1280. // set not waiting
  1281. client->socks_recv_waiting = 0;
  1282. // possibly send more data
  1283. if (client_socks_recv_send_out(client) < 0) {
  1284. return ERR_ABRT;
  1285. }
  1286. // we just queued some data, so it can't have been confirmed yet
  1287. ASSERT(client->socks_recv_tcp_pending > 0)
  1288. // continue receiving if needed
  1289. if (client->socks_recv_buf_used == -1 && !client->socks_closed) {
  1290. SYNC_DECL
  1291. SYNC_FROMHERE
  1292. client_socks_recv_initiate(client);
  1293. DEAD_ENTER(client->dead)
  1294. SYNC_COMMIT
  1295. DEAD_LEAVE2(client->dead)
  1296. if (DEAD_KILLED) {
  1297. return ERR_ABRT;
  1298. }
  1299. }
  1300. return ERR_OK;
  1301. }
  1302. // have we sent everything after SOCKS was closed?
  1303. if (client->socks_closed && client->socks_recv_tcp_pending == 0) {
  1304. client_log(client, BLOG_INFO, "removing after SOCKS went down");
  1305. int ret = client_free_client(client);
  1306. return (ret ? ERR_ABRT : ERR_OK);
  1307. }
  1308. return ERR_OK;
  1309. }
  1310. void udpgw_client_handler_received (void *unused, BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len)
  1311. {
  1312. ASSERT(options.udpgw_remote_server_addr)
  1313. ASSERT(data_len >= 0)
  1314. ASSERT(data_len <= udp_mtu)
  1315. BLog(BLOG_INFO, "UDP: from udpgw %d bytes", data_len);
  1316. // write IP header
  1317. struct ipv4_header *iph = (struct ipv4_header *)device_write_buf;
  1318. iph->version4_ihl4 = IPV4_MAKE_VERSION_IHL(sizeof(*iph));
  1319. iph->ds = hton8(0);
  1320. iph->total_length = hton16(sizeof(*iph) + sizeof(struct udp_header) + data_len);
  1321. iph->identification = hton16(0);
  1322. iph->flags3_fragmentoffset13 = hton16(0);
  1323. iph->ttl = hton8(64);
  1324. iph->protocol = hton8(IPV4_PROTOCOL_UDP);
  1325. iph->checksum = hton16(0);
  1326. iph->source_address = remote_addr.ipv4.ip;
  1327. iph->destination_address = local_addr.ipv4.ip;
  1328. // compute and write IP header checksum
  1329. uint32_t checksum = ipv4_checksum((uint8_t *)iph, sizeof(*iph));
  1330. iph->checksum = checksum;
  1331. // write UDP header
  1332. struct udp_header *udph = (struct udp_header *)(device_write_buf + sizeof(*iph));
  1333. udph->source_port = remote_addr.ipv4.port;
  1334. udph->dest_port = local_addr.ipv4.port;
  1335. udph->length = hton16(sizeof(*udph) + data_len);
  1336. udph->checksum = hton16(0);
  1337. // write data
  1338. memcpy(device_write_buf + sizeof(*iph) + sizeof(struct udp_header), data, data_len);
  1339. // compute checksum
  1340. checksum = udp_checksum((uint8_t *)udph, sizeof(*udph) + data_len, iph->source_address, iph->destination_address);
  1341. udph->checksum = checksum;
  1342. // submit packet
  1343. BTap_Send(&device, device_write_buf, sizeof(*iph) + sizeof(*udph) + data_len);
  1344. }