tun2socks.c 56 KB

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