tun2socks.c 58 KB

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