tun2socks.c 46 KB

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