tun2socks.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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 <structure/LinkedList2.h>
  33. #include <system/BLog.h>
  34. #include <system/BReactor.h>
  35. #include <system/BSocket.h>
  36. #include <system/BSignal.h>
  37. #include <system/BAddr.h>
  38. #include <flow/PacketBuffer.h>
  39. #include <flow/BufferWriter.h>
  40. #include <flow/SinglePacketBuffer.h>
  41. #include <socksclient/BSocksClient.h>
  42. #include <tuntap/BTap.h>
  43. #include <lwip/init.h>
  44. #include <lwip/tcp_impl.h>
  45. #include <lwip/netif.h>
  46. #include <lwip/tcp.h>
  47. #ifndef BADVPN_USE_WINAPI
  48. #include <system/BLog_syslog.h>
  49. #endif
  50. #include <tun2socks/tun2socks.h>
  51. #include <generated/blog_channel_tun2socks.h>
  52. #define LOGGER_STDOUT 1
  53. #define LOGGER_SYSLOG 2
  54. #define SYNC_DECL \
  55. BPending sync_mark; \
  56. #define SYNC_FROMHERE \
  57. BPending_Init(&sync_mark, BReactor_PendingGroup(&ss), NULL, NULL); \
  58. BPending_Set(&sync_mark);
  59. #define SYNC_BREAK \
  60. BPending_Free(&sync_mark);
  61. #define SYNC_COMMIT \
  62. BReactor_Synchronize(&ss, &sync_mark); \
  63. BPending_Free(&sync_mark);
  64. // command-line options
  65. struct {
  66. int help;
  67. int version;
  68. int logger;
  69. #ifndef BADVPN_USE_WINAPI
  70. char *logger_syslog_facility;
  71. char *logger_syslog_ident;
  72. #endif
  73. int loglevel;
  74. int loglevels[BLOG_NUM_CHANNELS];
  75. char *tapdev;
  76. char *netif_ipaddr;
  77. char *netif_netmask;
  78. char *socks_server_addr;
  79. } options;
  80. // TCP client
  81. struct tcp_client {
  82. dead_t dead;
  83. LinkedList2Node list_node;
  84. BAddr local_addr;
  85. BAddr remote_addr;
  86. struct tcp_pcb *pcb;
  87. uint8_t buf[TCP_WND];
  88. int buf_used;
  89. BPending recv_confirm_job;
  90. BSocksClient socks_client;
  91. int socks_up;
  92. int socks_closed;
  93. StreamPassInterface *socks_send_if;
  94. int socks_send_prev_buf_used;
  95. StreamRecvInterface *socks_recv_if;
  96. uint8_t socks_recv_buf[CLIENT_SOCKS_RECV_BUF_SIZE];
  97. int socks_recv_buf_used;
  98. int socks_recv_buf_sent;
  99. int socks_recv_waiting;
  100. int socks_recv_tcp_pending;
  101. };
  102. // IP address of netif
  103. BIPAddr netif_ipaddr;
  104. // netmask of netif
  105. BIPAddr netif_netmask;
  106. // SOCKS server address
  107. BAddr socks_server_addr;
  108. // reactor
  109. BReactor ss;
  110. // set to 1 by terminate
  111. int quitting;
  112. // TUN device
  113. BTap device;
  114. // device writing
  115. BufferWriter device_write_writer;
  116. PacketBuffer device_write_buffer;
  117. // device reading
  118. SinglePacketBuffer device_read_buffer;
  119. PacketPassInterface device_read_interface;
  120. // TCP timer
  121. BTimer tcp_timer;
  122. // job for initializing lwip
  123. BPending lwip_init_job;
  124. // lwip netif
  125. int have_netif;
  126. struct netif netif;
  127. // lwip TCP listener
  128. struct tcp_pcb *listener;
  129. // TCP clients
  130. LinkedList2 tcp_clients;
  131. static void terminate (void);
  132. static void print_help (const char *name);
  133. static void print_version (void);
  134. static int parse_arguments (int argc, char *argv[]);
  135. static int process_arguments (void);
  136. static void signal_handler (void *unused);
  137. static void lwip_init_job_hadler (void *unused);
  138. static void tcp_timer_handler (void *unused);
  139. static void device_error_handler (void *unused);
  140. static void device_read_handler_send (void *unused, uint8_t *data, int data_len);
  141. static err_t netif_init_func (struct netif *netif);
  142. static err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr);
  143. static void client_log (struct tcp_client *client, int level, const char *fmt, ...);
  144. static err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err);
  145. static void client_dealloc (struct tcp_client *client);
  146. static void client_close (struct tcp_client *client);
  147. static void client_err_func (void *arg, err_t err);
  148. static err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err);
  149. static void client_socks_handler (struct tcp_client *client, int event);
  150. static void client_send_to_socks (struct tcp_client *client);
  151. static void client_socks_send_handler_done (struct tcp_client *client, int data_len);
  152. static void client_recv_confirm_job_handler (struct tcp_client *client);
  153. static int client_force_send_to_socks (struct tcp_client *client);
  154. static void client_socks_recv_initiate (struct tcp_client *client);
  155. static void client_socks_recv_handler_done (struct tcp_client *client, int data_len);
  156. static int client_socks_recv_send_out (struct tcp_client *client);
  157. static err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len);
  158. int main (int argc, char **argv)
  159. {
  160. if (argc <= 0) {
  161. return 1;
  162. }
  163. // parse command-line arguments
  164. if (!parse_arguments(argc, argv)) {
  165. fprintf(stderr, "Failed to parse arguments\n");
  166. print_help(argv[0]);
  167. goto fail0;
  168. }
  169. // handle --help and --version
  170. if (options.help) {
  171. print_version();
  172. print_help(argv[0]);
  173. return 0;
  174. }
  175. if (options.version) {
  176. print_version();
  177. return 0;
  178. }
  179. // initialize logger
  180. switch (options.logger) {
  181. case LOGGER_STDOUT:
  182. BLog_InitStdout();
  183. break;
  184. #ifndef BADVPN_USE_WINAPI
  185. case LOGGER_SYSLOG:
  186. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  187. fprintf(stderr, "Failed to initialize syslog logger\n");
  188. goto fail0;
  189. }
  190. break;
  191. #endif
  192. default:
  193. ASSERT(0);
  194. }
  195. // configure logger channels
  196. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  197. if (options.loglevels[i] >= 0) {
  198. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  199. }
  200. else if (options.loglevel >= 0) {
  201. BLog_SetChannelLoglevel(i, options.loglevel);
  202. }
  203. }
  204. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  205. // initialize sockets
  206. if (BSocket_GlobalInit() < 0) {
  207. BLog(BLOG_ERROR, "BSocket_GlobalInit failed");
  208. goto fail1;
  209. }
  210. // process arguments
  211. if (!process_arguments()) {
  212. BLog(BLOG_ERROR, "Failed to process arguments");
  213. goto fail1;
  214. }
  215. // init time
  216. BTime_Init();
  217. // init reactor
  218. if (!BReactor_Init(&ss)) {
  219. BLog(BLOG_ERROR, "BReactor_Init failed");
  220. goto fail1;
  221. }
  222. // set not quitting
  223. quitting = 0;
  224. // setup signal handler
  225. if (!BSignal_Init()) {
  226. BLog(BLOG_ERROR, "BSignal_Init failed");
  227. goto fail2;
  228. }
  229. BSignal_Capture();
  230. if (!BSignal_SetHandler(&ss, signal_handler, NULL)) {
  231. BLog(BLOG_ERROR, "BSignal_SetHandler failed");
  232. goto fail2;
  233. }
  234. // init TUN device
  235. if (!BTap_Init(&device, &ss, options.tapdev, device_error_handler, NULL, 1)) {
  236. BLog(BLOG_ERROR, "BTap_Init failed");
  237. goto fail3;
  238. }
  239. // NOTE: the order of the following is important:
  240. // first device writing must evaluate,
  241. // then lwip (so it can send packets to the device),
  242. // then device reading (so it can pass received packets to lwip).
  243. // init device reading
  244. PacketPassInterface_Init(&device_read_interface, BTap_GetMTU(&device), device_read_handler_send, NULL, BReactor_PendingGroup(&ss));
  245. if (!SinglePacketBuffer_Init(&device_read_buffer, BTap_GetOutput(&device), &device_read_interface, BReactor_PendingGroup(&ss))) {
  246. BLog(BLOG_ERROR, "SinglePacketBuffer_Init failed");
  247. goto fail4;
  248. }
  249. // init lwip init job
  250. BPending_Init(&lwip_init_job, BReactor_PendingGroup(&ss), lwip_init_job_hadler, NULL);
  251. BPending_Set(&lwip_init_job);
  252. // init device writing
  253. BufferWriter_Init(&device_write_writer, BTap_GetMTU(&device), BReactor_PendingGroup(&ss));
  254. if (!PacketBuffer_Init(&device_write_buffer, BufferWriter_GetOutput(&device_write_writer), BTap_GetInput(&device), DEVICE_WRITE_BUFFER_SIZE, BReactor_PendingGroup(&ss))) {
  255. BLog(BLOG_ERROR, "PacketBuffer_Init failed");
  256. goto fail5;
  257. }
  258. // init TCP timer
  259. // it won't trigger before lwip is initialized, becuase the lwip init is a job
  260. BTimer_Init(&tcp_timer, TCP_TMR_INTERVAL, tcp_timer_handler, NULL);
  261. BReactor_SetTimer(&ss, &tcp_timer);
  262. // set no netif
  263. have_netif = 0;
  264. // set no listener
  265. listener = NULL;
  266. // init clients list
  267. LinkedList2_Init(&tcp_clients);
  268. goto event_loop;
  269. fail5:
  270. BufferWriter_Free(&device_write_writer);
  271. BPending_Free(&lwip_init_job);
  272. SinglePacketBuffer_Free(&device_read_buffer);
  273. fail4:
  274. PacketPassInterface_Free(&device_read_interface);
  275. BTap_Free(&device);
  276. fail3:
  277. BSignal_RemoveHandler();
  278. fail2:
  279. BReactor_Free(&ss);
  280. fail1:
  281. BLog(BLOG_ERROR, "initialization failed");
  282. BLog_Free();
  283. fail0:
  284. // finish objects
  285. DebugObjectGlobal_Finish();
  286. return 1;
  287. event_loop:
  288. // enter event loop
  289. BLog(BLOG_NOTICE, "entering event loop");
  290. int ret = BReactor_Exec(&ss);
  291. // free clients
  292. LinkedList2Node *node;
  293. while (node = LinkedList2_GetFirst(&tcp_clients)) {
  294. struct tcp_client *client = UPPER_OBJECT(node, struct tcp_client, list_node);
  295. client_log(client, BLOG_INFO, "freeing");
  296. tcp_abort(client->pcb);
  297. }
  298. // free listener
  299. if (listener) {
  300. tcp_close(listener);
  301. }
  302. // free netif
  303. if (have_netif) {
  304. netif_remove(&netif);
  305. }
  306. // free reactor
  307. BReactor_Free(&ss);
  308. // free logger
  309. BLog(BLOG_NOTICE, "exiting");
  310. BLog_Free();
  311. // finish objects
  312. DebugObjectGlobal_Finish();
  313. return ret;
  314. }
  315. void terminate (void)
  316. {
  317. ASSERT(!quitting)
  318. BLog(BLOG_NOTICE, "tearing down");
  319. // free TCP timer
  320. BReactor_RemoveTimer(&ss, &tcp_timer);
  321. // free device writing
  322. PacketBuffer_Free(&device_write_buffer);
  323. BufferWriter_Free(&device_write_writer);
  324. // free lwip init job
  325. BPending_Free(&lwip_init_job);
  326. // free device reading
  327. SinglePacketBuffer_Free(&device_read_buffer);
  328. PacketPassInterface_Free(&device_read_interface);
  329. // free device
  330. BTap_Free(&device);
  331. // remove signal handler
  332. BSignal_RemoveHandler();
  333. // set quitting
  334. quitting = 1;
  335. // exit reactor
  336. BReactor_Quit(&ss, 1);
  337. }
  338. void print_help (const char *name)
  339. {
  340. printf(
  341. "Usage:\n"
  342. " %s\n"
  343. " [--help]\n"
  344. " [--version]\n"
  345. " [--logger <"LOGGERS_STRING">]\n"
  346. #ifndef BADVPN_USE_WINAPI
  347. " (logger=syslog?\n"
  348. " [--syslog-facility <string>]\n"
  349. " [--syslog-ident <string>]\n"
  350. " )\n"
  351. #endif
  352. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  353. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  354. " [--tapdev <name>]\n"
  355. " --netif-ipaddr <ipaddr>\n"
  356. " --netif-netmask <ipnetmask>\n"
  357. " --socks-server-addr <addr>\n"
  358. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  359. name
  360. );
  361. }
  362. void print_version (void)
  363. {
  364. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  365. }
  366. int parse_arguments (int argc, char *argv[])
  367. {
  368. if (argc <= 0) {
  369. return 0;
  370. }
  371. options.help = 0;
  372. options.version = 0;
  373. options.logger = LOGGER_STDOUT;
  374. #ifndef BADVPN_USE_WINAPI
  375. options.logger_syslog_facility = "daemon";
  376. options.logger_syslog_ident = argv[0];
  377. #endif
  378. options.loglevel = -1;
  379. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  380. options.loglevels[i] = -1;
  381. }
  382. options.tapdev = NULL;
  383. options.netif_ipaddr = NULL;
  384. options.netif_netmask = NULL;
  385. options.socks_server_addr = NULL;
  386. int have_fragmentation_latency = 0;
  387. int i;
  388. for (i = 1; i < argc; i++) {
  389. char *arg = argv[i];
  390. if (!strcmp(arg, "--help")) {
  391. options.help = 1;
  392. }
  393. else if (!strcmp(arg, "--version")) {
  394. options.version = 1;
  395. }
  396. else if (!strcmp(arg, "--logger")) {
  397. if (1 >= argc - i) {
  398. fprintf(stderr, "%s: requires an argument\n", arg);
  399. return 0;
  400. }
  401. char *arg2 = argv[i + 1];
  402. if (!strcmp(arg2, "stdout")) {
  403. options.logger = LOGGER_STDOUT;
  404. }
  405. #ifndef BADVPN_USE_WINAPI
  406. else if (!strcmp(arg2, "syslog")) {
  407. options.logger = LOGGER_SYSLOG;
  408. }
  409. #endif
  410. else {
  411. fprintf(stderr, "%s: wrong argument\n", arg);
  412. return 0;
  413. }
  414. i++;
  415. }
  416. #ifndef BADVPN_USE_WINAPI
  417. else if (!strcmp(arg, "--syslog-facility")) {
  418. if (1 >= argc - i) {
  419. fprintf(stderr, "%s: requires an argument\n", arg);
  420. return 0;
  421. }
  422. options.logger_syslog_facility = argv[i + 1];
  423. i++;
  424. }
  425. else if (!strcmp(arg, "--syslog-ident")) {
  426. if (1 >= argc - i) {
  427. fprintf(stderr, "%s: requires an argument\n", arg);
  428. return 0;
  429. }
  430. options.logger_syslog_ident = argv[i + 1];
  431. i++;
  432. }
  433. #endif
  434. else if (!strcmp(arg, "--loglevel")) {
  435. if (1 >= argc - i) {
  436. fprintf(stderr, "%s: requires an argument\n", arg);
  437. return 0;
  438. }
  439. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  440. fprintf(stderr, "%s: wrong argument\n", arg);
  441. return 0;
  442. }
  443. i++;
  444. }
  445. else if (!strcmp(arg, "--channel-loglevel")) {
  446. if (2 >= argc - i) {
  447. fprintf(stderr, "%s: requires two arguments\n", arg);
  448. return 0;
  449. }
  450. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  451. if (channel < 0) {
  452. fprintf(stderr, "%s: wrong channel argument\n", arg);
  453. return 0;
  454. }
  455. int loglevel = parse_loglevel(argv[i + 2]);
  456. if (loglevel < 0) {
  457. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  458. return 0;
  459. }
  460. options.loglevels[channel] = loglevel;
  461. i += 2;
  462. }
  463. else if (!strcmp(arg, "--tapdev")) {
  464. if (1 >= argc - i) {
  465. fprintf(stderr, "%s: requires an argument\n", arg);
  466. return 0;
  467. }
  468. options.tapdev = argv[i + 1];
  469. i++;
  470. }
  471. else if (!strcmp(arg, "--netif-ipaddr")) {
  472. if (1 >= argc - i) {
  473. fprintf(stderr, "%s: requires an argument\n", arg);
  474. return 0;
  475. }
  476. options.netif_ipaddr = argv[i + 1];
  477. i++;
  478. }
  479. else if (!strcmp(arg, "--netif-netmask")) {
  480. if (1 >= argc - i) {
  481. fprintf(stderr, "%s: requires an argument\n", arg);
  482. return 0;
  483. }
  484. options.netif_netmask = argv[i + 1];
  485. i++;
  486. }
  487. else if (!strcmp(arg, "--socks-server-addr")) {
  488. if (1 >= argc - i) {
  489. fprintf(stderr, "%s: requires an argument\n", arg);
  490. return 0;
  491. }
  492. options.socks_server_addr = argv[i + 1];
  493. i++;
  494. }
  495. else {
  496. fprintf(stderr, "unknown option: %s\n", arg);
  497. return 0;
  498. }
  499. }
  500. if (options.help || options.version) {
  501. return 1;
  502. }
  503. if (!options.netif_ipaddr) {
  504. fprintf(stderr, "--netif-ipaddr is required\n");
  505. return 0;
  506. }
  507. if (!options.netif_netmask) {
  508. fprintf(stderr, "--netif-netmask is required\n");
  509. return 0;
  510. }
  511. if (!options.socks_server_addr) {
  512. fprintf(stderr, "--socks-server-addr is required\n");
  513. return 0;
  514. }
  515. return 1;
  516. }
  517. int process_arguments (void)
  518. {
  519. // resolve netif ipaddr
  520. if (!BIPAddr_Resolve(&netif_ipaddr, options.netif_ipaddr, 0)) {
  521. BLog(BLOG_ERROR, "netif ipaddr: BIPAddr_Resolve failed");
  522. return 0;
  523. }
  524. if (netif_ipaddr.type != BADDR_TYPE_IPV4) {
  525. BLog(BLOG_ERROR, "netif ipaddr: must be an IPv4 address");
  526. return 0;
  527. }
  528. // resolve netif netmask
  529. if (!BIPAddr_Resolve(&netif_netmask, options.netif_netmask, 0)) {
  530. BLog(BLOG_ERROR, "netif netmask: BIPAddr_Resolve failed");
  531. return 0;
  532. }
  533. if (netif_netmask.type != BADDR_TYPE_IPV4) {
  534. BLog(BLOG_ERROR, "netif netmask: must be an IPv4 address");
  535. return 0;
  536. }
  537. // resolve SOCKS server address
  538. if (!BAddr_Parse2(&socks_server_addr, options.socks_server_addr, NULL, 0, 0)) {
  539. BLog(BLOG_ERROR, "socks server addr: BAddr_Parse2 failed");
  540. return 0;
  541. }
  542. return 1;
  543. }
  544. void signal_handler (void *unused)
  545. {
  546. ASSERT(!quitting)
  547. BLog(BLOG_NOTICE, "termination requested");
  548. terminate();
  549. return;
  550. }
  551. void lwip_init_job_hadler (void *unused)
  552. {
  553. ASSERT(!quitting)
  554. ASSERT(netif_ipaddr.type == BADDR_TYPE_IPV4)
  555. ASSERT(netif_netmask.type == BADDR_TYPE_IPV4)
  556. ASSERT(!have_netif)
  557. BLog(BLOG_DEBUG, "lwip init");
  558. // NOTE: the device may fail during this, but there's no harm in not checking
  559. // for that at every step
  560. int res;
  561. // init lwip
  562. lwip_init();
  563. // make addresses for netif
  564. ip_addr_t addr;
  565. addr.addr = netif_ipaddr.ipv4;
  566. ip_addr_t netmask;
  567. netmask.addr = netif_netmask.ipv4;
  568. ip_addr_t gw;
  569. ip_addr_set_any(&gw);
  570. // init netif
  571. if (!netif_add(&netif, &addr, &netmask, &gw, NULL, netif_init_func, ip_input)) {
  572. BLog(BLOG_ERROR, "netif_add failed");
  573. goto fail;
  574. }
  575. have_netif = 1;
  576. // set netif up
  577. netif_set_up(&netif);
  578. // set netif pretend TCP
  579. netif_set_pretend_tcp(&netif, 1);
  580. // init listener
  581. struct tcp_pcb *l = tcp_new();
  582. if (!l) {
  583. BLog(BLOG_ERROR, "tcp_new failed");
  584. goto fail;
  585. }
  586. // bind listener
  587. if (tcp_bind_to_netif(l, "ho0") != ERR_OK) {
  588. BLog(BLOG_ERROR, "tcp_bind_to_netif failed");
  589. tcp_close(l);
  590. goto fail;
  591. }
  592. // listen listener
  593. struct tcp_pcb *l2 = tcp_listen(l);
  594. if (!l2) {
  595. BLog(BLOG_ERROR, "tcp_listen failed");
  596. tcp_close(l);
  597. goto fail;
  598. }
  599. listener = l2;
  600. // setup accept handler
  601. tcp_accept(listener, listener_accept_func);
  602. return;
  603. fail:
  604. if (!quitting) {
  605. terminate();
  606. }
  607. }
  608. void tcp_timer_handler (void *unused)
  609. {
  610. ASSERT(!quitting)
  611. BLog(BLOG_DEBUG, "TCP timer");
  612. // schedule next timer
  613. // TODO: calculate timeout so we don't drift
  614. BReactor_SetTimer(&ss, &tcp_timer);
  615. tcp_tmr();
  616. return;
  617. }
  618. void device_error_handler (void *unused)
  619. {
  620. ASSERT(!quitting)
  621. BLog(BLOG_ERROR, "device error");
  622. terminate();
  623. return;
  624. }
  625. void device_read_handler_send (void *unused, uint8_t *data, int data_len)
  626. {
  627. ASSERT(!quitting)
  628. BLog(BLOG_DEBUG, "device: received packet");
  629. // accept packet
  630. PacketPassInterface_Done(&device_read_interface);
  631. // obtain pbuf
  632. struct pbuf *p = pbuf_alloc(PBUF_RAW, data_len, PBUF_POOL);
  633. if (!p) {
  634. BLog(BLOG_WARNING, "device read: pbuf_alloc failed");
  635. return;
  636. }
  637. // write packet to pbuf
  638. ASSERT_FORCE(pbuf_take(p, data, data_len) == ERR_OK)
  639. // pass pbuf to input
  640. if (netif.input(p, &netif) != ERR_OK) {
  641. BLog(BLOG_WARNING, "device read: input failed");
  642. pbuf_free(p);
  643. }
  644. }
  645. err_t netif_init_func (struct netif *netif)
  646. {
  647. BLog(BLOG_DEBUG, "netif func init");
  648. netif->name[0] = 'h';
  649. netif->name[1] = 'o';
  650. netif->output = netif_output_func;
  651. return ERR_OK;
  652. }
  653. err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr)
  654. {
  655. SYNC_DECL
  656. BLog(BLOG_DEBUG, "device write: send packet");
  657. if (quitting) {
  658. return ERR_OK;
  659. }
  660. uint8_t *out;
  661. if (!BufferWriter_StartPacket(&device_write_writer, &out)) {
  662. DEBUG("netif func output: BufferWriter_StartPacket failed");
  663. return ERR_OK;
  664. }
  665. int len = 0;
  666. while (p) {
  667. int remain = BTap_GetMTU(&device) - len;
  668. if (p->len > remain) {
  669. BLog(BLOG_WARNING, "netif func output: no space left");
  670. break;
  671. }
  672. memcpy(out + len, p->payload, p->len);
  673. len += p->len;
  674. p = p->next;
  675. }
  676. SYNC_FROMHERE
  677. BufferWriter_EndPacket(&device_write_writer, len);
  678. SYNC_COMMIT
  679. return ERR_OK;
  680. }
  681. void client_log (struct tcp_client *client, int level, const char *fmt, ...)
  682. {
  683. va_list vl;
  684. va_start(vl, fmt);
  685. char local_addr_s[BADDR_MAX_PRINT_LEN];
  686. BAddr_Print(&client->local_addr, local_addr_s);
  687. char remote_addr_s[BADDR_MAX_PRINT_LEN];
  688. BAddr_Print(&client->remote_addr, remote_addr_s);
  689. BLog_Append("(%s %s): ", local_addr_s, remote_addr_s);
  690. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  691. va_end(vl);
  692. }
  693. #define CLIENT_SYNC_START \
  694. BPending sync_mark; \
  695. BPending_Init(&sync_mark, BReactor_PendingGroup(&ss), NULL, NULL); \
  696. BPending_Set(&sync_mark); \
  697. err_t sync_err = ERR_OK;
  698. #define CLIENT_SYNC_BREAK \
  699. BPending_Free(&sync_mark);
  700. #define CLIENT_SYNC_OUT_WITH(err) \
  701. sync_err = (err); \
  702. goto sync_out;
  703. #define CLIENT_SYNC_OUT \
  704. goto sync_out;
  705. #define CLIENT_SYNC_RETURN \
  706. sync_out:; \
  707. DEAD_ENTER(client->dead) \
  708. BReactor_Synchronize(&ss, &sync_mark); \
  709. BPending_Free(&sync_mark); \
  710. if (DEAD_LEAVE(client->dead)) { \
  711. return ERR_ABRT; \
  712. } \
  713. return sync_err;
  714. err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err)
  715. {
  716. ASSERT(listener)
  717. ASSERT(err == ERR_OK)
  718. // signal accepted
  719. tcp_accepted(listener);
  720. // allocate client structure
  721. struct tcp_client *client = malloc(sizeof(*client));
  722. if (!client) {
  723. BLog(BLOG_ERROR, "listener accept: malloc failed");
  724. return ERR_MEM;
  725. }
  726. CLIENT_SYNC_START
  727. // init SOCKS
  728. BAddr addr;
  729. BAddr_InitIPv4(&addr, newpcb->local_ip.addr, hton16(newpcb->local_port));
  730. #ifdef OVERRIDE_DEST_ADDR
  731. ASSERT_FORCE(BAddr_Parse2(&addr, OVERRIDE_DEST_ADDR, NULL, 0, 1))
  732. #endif
  733. if (!BSocksClient_Init(&client->socks_client, socks_server_addr, addr, (BSocksClient_handler)client_socks_handler, client, &ss)) {
  734. BLog(BLOG_ERROR, "listener accept: BSocksClient_Init failed");
  735. CLIENT_SYNC_BREAK
  736. free(client);
  737. return ERR_MEM;
  738. }
  739. // init dead var
  740. DEAD_INIT(client->dead);
  741. // init client
  742. LinkedList2_Append(&tcp_clients, &client->list_node);
  743. client->pcb = newpcb;
  744. // read addresses
  745. BAddr_InitIPv4(&client->local_addr, client->pcb->local_ip.addr, hton16(client->pcb->local_port));
  746. BAddr_InitIPv4(&client->remote_addr, client->pcb->remote_ip.addr, hton16(client->pcb->remote_port));
  747. // setup handler argument
  748. tcp_arg(client->pcb, client);
  749. // setup handlers
  750. tcp_err(client->pcb, client_err_func);
  751. tcp_recv(client->pcb, client_recv_func);
  752. // setup buffer
  753. client->buf_used = 0;
  754. // init recv confirm job
  755. BPending_Init(&client->recv_confirm_job, BReactor_PendingGroup(&ss), (BPending_handler)client_recv_confirm_job_handler, client);
  756. // set SOCKS not up
  757. client->socks_up = 0;
  758. client_log(client, BLOG_INFO, "accepted");
  759. CLIENT_SYNC_RETURN
  760. }
  761. void client_dealloc (struct tcp_client *client)
  762. {
  763. // NOTE: the pcb must have been taked care of
  764. // free recv confirm job
  765. BPending_Free(&client->recv_confirm_job);
  766. // remove client entry
  767. LinkedList2_Remove(&tcp_clients, &client->list_node);
  768. // kill dead var
  769. DEAD_KILL(client->dead);
  770. // free SOCKS
  771. if (!client->socks_up || (client->socks_up && !client->socks_closed)) {
  772. BSocksClient_Free(&client->socks_client);
  773. }
  774. // free memory
  775. free(client);
  776. }
  777. void client_close (struct tcp_client *client)
  778. {
  779. // remove callbacks from PCB
  780. tcp_err(client->pcb, NULL);
  781. tcp_recv(client->pcb, NULL);
  782. tcp_sent(client->pcb, NULL);
  783. // close pcb
  784. err_t err = tcp_close(client->pcb);
  785. if (err != ERR_OK) {
  786. BLog(BLOG_ERROR, "tcp_close failed");
  787. tcp_abort(client->pcb);
  788. }
  789. // dealloc client
  790. client_dealloc(client);
  791. }
  792. void client_err_func (void *arg, err_t err)
  793. {
  794. struct tcp_client *client = arg;
  795. client_log(client, BLOG_INFO, "destroying (error %d)", (int)err);
  796. // the pcb was taken by the caller
  797. client_dealloc(client);
  798. }
  799. err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  800. {
  801. struct tcp_client *client = arg;
  802. if (err != ERR_OK) {
  803. client_log(client, BLOG_INFO, "recv error (%d)", (int)err);
  804. tcp_abort(client->pcb);
  805. return ERR_ABRT;
  806. }
  807. if (!p) {
  808. client_log(client, BLOG_INFO, "connection closed");
  809. tcp_abort(client->pcb);
  810. return ERR_ABRT;
  811. }
  812. ASSERT(p->tot_len > 0)
  813. // check if we have enough buffer
  814. if (p->tot_len > sizeof(client->buf) - client->buf_used) {
  815. client_log(client, BLOG_WARNING, "no buffer for data");
  816. return ERR_MEM;
  817. }
  818. // copy data to buffer
  819. ASSERT_EXECUTE(pbuf_copy_partial(p, client->buf + client->buf_used, p->tot_len, 0) == p->tot_len)
  820. client->buf_used += p->tot_len;
  821. // if there was nothing in the buffer before, and SOCKS is up, start send data
  822. if (client->buf_used == p->tot_len && client->socks_up) {
  823. ASSERT(!client->socks_closed) // this callback is removed when SOCKS is closed
  824. if (client_force_send_to_socks(client) < 0) {
  825. return ERR_ABRT;
  826. }
  827. }
  828. pbuf_free(p);
  829. return ERR_OK;
  830. }
  831. void client_socks_handler (struct tcp_client *client, int event)
  832. {
  833. switch (event) {
  834. case BSOCKSCLIENT_EVENT_ERROR: {
  835. client_log(client, BLOG_INFO, "SOCKS error");
  836. // abort client
  837. tcp_abort(client->pcb);
  838. } break;
  839. case BSOCKSCLIENT_EVENT_UP: {
  840. ASSERT(!client->socks_up)
  841. client_log(client, BLOG_INFO, "SOCKS up");
  842. // init sending
  843. client->socks_send_if = BSocksClient_GetSendInterface(&client->socks_client);
  844. StreamPassInterface_Sender_Init(client->socks_send_if, (StreamPassInterface_handler_done)client_socks_send_handler_done, client);
  845. client->socks_send_prev_buf_used = -1;
  846. // init receiving
  847. client->socks_recv_if = BSocksClient_GetRecvInterface(&client->socks_client);
  848. StreamRecvInterface_Receiver_Init(client->socks_recv_if, (StreamRecvInterface_handler_done)client_socks_recv_handler_done, client);
  849. client->socks_recv_buf_used = -1;
  850. client->socks_recv_tcp_pending = 0;
  851. tcp_sent(client->pcb, client_sent_func);
  852. // set up, not closed
  853. client->socks_up = 1;
  854. client->socks_closed = 0;
  855. // start sending data if there is any
  856. if (client->buf_used > 0) {
  857. client_send_to_socks(client);
  858. }
  859. // start receiving data
  860. client_socks_recv_initiate(client);
  861. } break;
  862. case BSOCKSCLIENT_EVENT_ERROR_CLOSED: {
  863. ASSERT(client->socks_up)
  864. ASSERT(!client->socks_closed)
  865. // close now if all was sent
  866. if (client->socks_recv_buf_used == -1 && client->socks_recv_tcp_pending == 0) {
  867. client_log(client, BLOG_INFO, "SOCKS closed, closing client now");
  868. client_close(client);
  869. return;
  870. }
  871. // wait for everything to be sent
  872. client_log(client, BLOG_INFO, "SOCKS closed, closing client later");
  873. // free SOCKS
  874. BSocksClient_Free(&client->socks_client);
  875. // remove recv callback
  876. tcp_recv(client->pcb, NULL);
  877. // set closed
  878. client->socks_closed = 1;
  879. } break;
  880. default:
  881. ASSERT(0);
  882. }
  883. }
  884. void client_send_to_socks (struct tcp_client *client)
  885. {
  886. ASSERT(client->socks_up)
  887. ASSERT(!client->socks_closed)
  888. ASSERT(client->buf_used > 0)
  889. ASSERT(client->socks_send_prev_buf_used == -1)
  890. // schedule confirm
  891. client->socks_send_prev_buf_used = client->buf_used;
  892. BPending_Set(&client->recv_confirm_job);
  893. // schedule sending
  894. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  895. }
  896. void client_socks_send_handler_done (struct tcp_client *client, int data_len)
  897. {
  898. ASSERT(client->socks_up)
  899. ASSERT(!client->socks_closed)
  900. ASSERT(client->buf_used > 0)
  901. ASSERT(data_len > 0)
  902. ASSERT(data_len <= client->buf_used)
  903. // remove data from buffer
  904. memmove(client->buf, client->buf + data_len, client->buf_used - data_len);
  905. client->buf_used -= data_len;
  906. // send any further data
  907. if (client->buf_used > 0) {
  908. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  909. }
  910. }
  911. void client_recv_confirm_job_handler (struct tcp_client *client)
  912. {
  913. ASSERT(client->socks_up)
  914. ASSERT(!client->socks_closed)
  915. ASSERT(client->socks_send_prev_buf_used > 0)
  916. ASSERT(client->buf_used <= client->socks_send_prev_buf_used)
  917. // calculate how much data was sent
  918. int sent = client->socks_send_prev_buf_used - client->buf_used;
  919. // set no prev buf used
  920. client->socks_send_prev_buf_used = -1;
  921. // confirm sent data
  922. if (sent > 0) {
  923. tcp_recved(client->pcb, sent);
  924. }
  925. }
  926. int client_force_send_to_socks (struct tcp_client *client)
  927. {
  928. ASSERT(client->socks_up)
  929. ASSERT(!client->socks_closed)
  930. ASSERT(client->buf_used > 0)
  931. ASSERT(client->socks_send_prev_buf_used == -1)
  932. SYNC_DECL
  933. SYNC_FROMHERE
  934. client_send_to_socks(client);
  935. DEAD_ENTER(client->dead)
  936. SYNC_COMMIT
  937. if (DEAD_LEAVE(client->dead)) {
  938. return -1;
  939. }
  940. return 0;
  941. }
  942. void client_socks_recv_initiate (struct tcp_client *client)
  943. {
  944. ASSERT(client->socks_up)
  945. ASSERT(!client->socks_closed)
  946. ASSERT(client->socks_recv_buf_used == -1)
  947. StreamRecvInterface_Receiver_Recv(client->socks_recv_if, client->socks_recv_buf, sizeof(client->socks_recv_buf));
  948. }
  949. void client_socks_recv_handler_done (struct tcp_client *client, int data_len)
  950. {
  951. ASSERT(data_len > 0)
  952. ASSERT(data_len <= sizeof(client->socks_recv_buf))
  953. ASSERT(client->socks_up)
  954. ASSERT(!client->socks_closed)
  955. ASSERT(client->socks_recv_buf_used == -1)
  956. // set amount of data in buffer
  957. client->socks_recv_buf_used = data_len;
  958. client->socks_recv_buf_sent = 0;
  959. client->socks_recv_waiting = 0;
  960. // send to client
  961. if (client_socks_recv_send_out(client) < 0) {
  962. return;
  963. }
  964. // continue receiving if needed
  965. if (client->socks_recv_buf_used == -1 && !client->socks_closed) {
  966. client_socks_recv_initiate(client);
  967. }
  968. }
  969. int client_socks_recv_send_out (struct tcp_client *client)
  970. {
  971. ASSERT(client->socks_up)
  972. ASSERT(client->socks_recv_buf_used > 0)
  973. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  974. ASSERT(!client->socks_recv_waiting)
  975. do {
  976. int to_write = BMIN(client->socks_recv_buf_used - client->socks_recv_buf_sent, tcp_sndbuf(client->pcb));
  977. if (to_write == 0) {
  978. break;
  979. }
  980. err_t err = tcp_write(client->pcb, client->socks_recv_buf + client->socks_recv_buf_sent, to_write, TCP_WRITE_FLAG_COPY);
  981. if (err != ERR_OK) {
  982. if (err == ERR_MEM) {
  983. break;
  984. }
  985. client_log(client, BLOG_INFO, "tcp_write failed (%d)", (int)err);
  986. tcp_abort(client->pcb);
  987. return -1;
  988. }
  989. client->socks_recv_buf_sent += to_write;
  990. client->socks_recv_tcp_pending += to_write;
  991. } while (client->socks_recv_buf_sent < client->socks_recv_buf_used);
  992. // start sending now
  993. err_t err = tcp_output(client->pcb);
  994. if (err != ERR_OK) {
  995. client_log(client, BLOG_INFO, "tcp_output failed (%d)", (int)err);
  996. tcp_abort(client->pcb);
  997. return -1;
  998. }
  999. // more data to queue?
  1000. if (client->socks_recv_buf_sent < client->socks_recv_buf_used) {
  1001. if (client->socks_recv_tcp_pending == 0) {
  1002. client_log(client, BLOG_ERROR, "can't queue data, but all data was confirmed!?!");
  1003. tcp_abort(client->pcb);
  1004. return -1;
  1005. }
  1006. // continue in client_sent_func
  1007. client->socks_recv_waiting = 1;
  1008. return 0;
  1009. }
  1010. // everything was queued
  1011. client->socks_recv_buf_used = -1;
  1012. // we just queued some data, so it can't have been confirmed yet
  1013. ASSERT(client->socks_recv_tcp_pending > 0)
  1014. return 0;
  1015. }
  1016. err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len)
  1017. {
  1018. struct tcp_client *client = arg;
  1019. ASSERT(client->socks_up)
  1020. ASSERT(len > 0)
  1021. ASSERT(len <= client->socks_recv_tcp_pending)
  1022. // decrement pending
  1023. client->socks_recv_tcp_pending -= len;
  1024. // continue queuing
  1025. if (client->socks_recv_buf_used > 0) {
  1026. ASSERT(client->socks_recv_waiting)
  1027. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  1028. client->socks_recv_waiting = 0;
  1029. // send more data
  1030. if (client_socks_recv_send_out(client) < 0) {
  1031. return ERR_ABRT;
  1032. }
  1033. // continue receiving if needed
  1034. if (client->socks_recv_buf_used == -1 && !client->socks_closed) {
  1035. SYNC_DECL
  1036. SYNC_FROMHERE
  1037. client_socks_recv_initiate(client);
  1038. DEAD_ENTER(client->dead)
  1039. SYNC_COMMIT
  1040. if (DEAD_LEAVE(client->dead)) {
  1041. return ERR_ABRT;
  1042. }
  1043. }
  1044. return ERR_OK;
  1045. }
  1046. // have we sent everything after SOCKS was closed?
  1047. if (client->socks_closed && client->socks_recv_tcp_pending == 0) {
  1048. client_log(client, BLOG_INFO, "finally closing");
  1049. client_close(client);
  1050. return ERR_ABRT;
  1051. }
  1052. return ERR_OK;
  1053. }