PageRenderTime 22ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Android/badvpn/tun2socks/tun2socks.c

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

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