PageRenderTime 63ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/jni/badvpn/tun2socks/tun2socks.c

https://bitbucket.org/madeye/shadowsocks-android
C | 1985 lines | 1450 code | 313 blank | 222 comment | 269 complexity | c2e6613831b35247150fdae58db67c64 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file