tun2socks.c 44 KB

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