tun2socks.c 43 KB

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