tun2socks.c 59 KB

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