udpgw.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  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 <stdio.h>
  29. #include <string.h>
  30. #include <stdarg.h>
  31. #include <stdlib.h>
  32. #include <limits.h>
  33. #include <protocol/udpgw_proto.h>
  34. #include <misc/debug.h>
  35. #include <misc/version.h>
  36. #include <misc/loggers_string.h>
  37. #include <misc/loglevel.h>
  38. #include <misc/offset.h>
  39. #include <misc/byteorder.h>
  40. #include <misc/bsize.h>
  41. #include <misc/open_standard_streams.h>
  42. #include <misc/balloc.h>
  43. #include <misc/compare.h>
  44. #include <misc/print_macros.h>
  45. #include <structure/LinkedList1.h>
  46. #include <structure/BAVL.h>
  47. #include <base/BLog.h>
  48. #include <system/BReactor.h>
  49. #include <system/BNetwork.h>
  50. #include <system/BConnection.h>
  51. #include <system/BDatagram.h>
  52. #include <system/BSignal.h>
  53. #include <flow/PacketProtoDecoder.h>
  54. #include <flow/PacketPassFairQueue.h>
  55. #include <flow/PacketStreamSender.h>
  56. #include <flow/PacketProtoFlow.h>
  57. #include <flow/SinglePacketBuffer.h>
  58. #ifndef BADVPN_USE_WINAPI
  59. #include <base/BLog_syslog.h>
  60. #include <arpa/nameser.h>
  61. #include <resolv.h>
  62. #endif
  63. #include <udpgw/udpgw.h>
  64. #include <generated/blog_channel_udpgw.h>
  65. #define LOGGER_STDOUT 1
  66. #define LOGGER_SYSLOG 2
  67. #define DNS_UPDATE_TIME 2000
  68. struct client {
  69. BConnection con;
  70. BAddr addr;
  71. BTimer disconnect_timer;
  72. PacketProtoDecoder recv_decoder;
  73. PacketPassInterface recv_if;
  74. PacketPassFairQueue send_queue;
  75. PacketStreamSender send_sender;
  76. BAVL connections_tree;
  77. LinkedList1 connections_list;
  78. int num_connections;
  79. LinkedList1 closing_connections_list;
  80. LinkedList1Node clients_list_node;
  81. };
  82. struct connection {
  83. struct client *client;
  84. uint16_t conid;
  85. BAddr addr;
  86. BAddr orig_addr;
  87. const uint8_t *first_data;
  88. int first_data_len;
  89. btime_t last_use_time;
  90. int closing;
  91. BPending first_job;
  92. BufferWriter *send_if;
  93. PacketProtoFlow send_ppflow;
  94. PacketPassFairQueueFlow send_qflow;
  95. union {
  96. struct {
  97. BDatagram udp_dgram;
  98. int local_port_index;
  99. BufferWriter udp_send_writer;
  100. PacketBuffer udp_send_buffer;
  101. SinglePacketBuffer udp_recv_buffer;
  102. PacketPassInterface udp_recv_if;
  103. BAVLNode connections_tree_node;
  104. LinkedList1Node connections_list_node;
  105. };
  106. struct {
  107. LinkedList1Node closing_connections_list_node;
  108. };
  109. };
  110. };
  111. // command-line options
  112. struct {
  113. int help;
  114. int version;
  115. int logger;
  116. #ifndef BADVPN_USE_WINAPI
  117. char *logger_syslog_facility;
  118. char *logger_syslog_ident;
  119. #endif
  120. int loglevel;
  121. int loglevels[BLOG_NUM_CHANNELS];
  122. char *listen_addrs[MAX_LISTEN_ADDRS];
  123. int num_listen_addrs;
  124. int udp_mtu;
  125. int max_clients;
  126. int max_connections_for_client;
  127. int client_socket_sndbuf;
  128. int local_udp_num_ports;
  129. char *local_udp_addr;
  130. int local_udp_ip6_num_ports;
  131. char *local_udp_ip6_addr;
  132. int unique_local_ports;
  133. } options;
  134. // MTUs
  135. int udpgw_mtu;
  136. int pp_mtu;
  137. // listen addresses
  138. BAddr listen_addrs[MAX_LISTEN_ADDRS];
  139. int num_listen_addrs;
  140. // local UDP port range, if options.local_udp_num_ports>=0
  141. BAddr local_udp_addr;
  142. // local UDP/IPv6 port range, if options.local_udp_ip6_num_ports>=0
  143. BAddr local_udp_ip6_addr;
  144. // DNS forwarding
  145. BAddr dns_addr;
  146. btime_t last_dns_update_time;
  147. // reactor
  148. BReactor ss;
  149. // listeners
  150. BListener listeners[MAX_LISTEN_ADDRS];
  151. int num_listeners;
  152. // clients
  153. LinkedList1 clients_list;
  154. int num_clients;
  155. static void print_help (const char *name);
  156. static void print_version (void);
  157. static int parse_arguments (int argc, char *argv[]);
  158. static int process_arguments (void);
  159. static void signal_handler (void *unused);
  160. static void listener_handler (BListener *listener);
  161. static void client_free (struct client *client);
  162. static void client_logfunc (struct client *client);
  163. static void client_log (struct client *client, int level, const char *fmt, ...);
  164. static void client_disconnect_timer_handler (struct client *client);
  165. static void client_connection_handler (struct client *client, int event);
  166. static void client_decoder_handler_error (struct client *client);
  167. static void client_recv_if_handler_send (struct client *client, uint8_t *data, int data_len);
  168. static int get_local_num_ports (int addr_type);
  169. static BAddr get_local_addr (int addr_type);
  170. static uint8_t * build_port_usage_array_and_find_least_used_connection (BAddr remote_addr, struct connection **out_con);
  171. static void connection_init (struct client *client, uint16_t conid, BAddr addr, BAddr orig_addr, const uint8_t *data, int data_len);
  172. static void connection_free (struct connection *con);
  173. static void connection_logfunc (struct connection *con);
  174. static void connection_log (struct connection *con, int level, const char *fmt, ...);
  175. static void connection_free_udp (struct connection *con);
  176. static void connection_first_job_handler (struct connection *con);
  177. static void connection_send_to_client (struct connection *con, uint8_t flags, const uint8_t *data, int data_len);
  178. static int connection_send_to_udp (struct connection *con, const uint8_t *data, int data_len);
  179. static void connection_close (struct connection *con);
  180. static void connection_send_qflow_busy_handler (struct connection *con);
  181. static void connection_dgram_handler_event (struct connection *con, int event);
  182. static void connection_udp_recv_if_handler_send (struct connection *con, uint8_t *data, int data_len);
  183. static struct connection * find_connection (struct client *client, uint16_t conid);
  184. static int uint16_comparator (void *unused, uint16_t *v1, uint16_t *v2);
  185. static void maybe_update_dns (void);
  186. int main (int argc, char **argv)
  187. {
  188. if (argc <= 0) {
  189. return 1;
  190. }
  191. // open standard streams
  192. open_standard_streams();
  193. // parse command-line arguments
  194. if (!parse_arguments(argc, argv)) {
  195. fprintf(stderr, "Failed to parse arguments\n");
  196. print_help(argv[0]);
  197. goto fail0;
  198. }
  199. // handle --help and --version
  200. if (options.help) {
  201. print_version();
  202. print_help(argv[0]);
  203. return 0;
  204. }
  205. if (options.version) {
  206. print_version();
  207. return 0;
  208. }
  209. // initialize logger
  210. switch (options.logger) {
  211. case LOGGER_STDOUT:
  212. BLog_InitStdout();
  213. break;
  214. #ifndef BADVPN_USE_WINAPI
  215. case LOGGER_SYSLOG:
  216. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  217. fprintf(stderr, "Failed to initialize syslog logger\n");
  218. goto fail0;
  219. }
  220. break;
  221. #endif
  222. default:
  223. ASSERT(0);
  224. }
  225. // configure logger channels
  226. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  227. if (options.loglevels[i] >= 0) {
  228. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  229. }
  230. else if (options.loglevel >= 0) {
  231. BLog_SetChannelLoglevel(i, options.loglevel);
  232. }
  233. }
  234. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  235. // initialize network
  236. if (!BNetwork_GlobalInit()) {
  237. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  238. goto fail1;
  239. }
  240. // process arguments
  241. if (!process_arguments()) {
  242. BLog(BLOG_ERROR, "Failed to process arguments");
  243. goto fail1;
  244. }
  245. // compute MTUs
  246. udpgw_mtu = udpgw_compute_mtu(options.udp_mtu);
  247. if (udpgw_mtu < 0 || udpgw_mtu > PACKETPROTO_MAXPAYLOAD) {
  248. udpgw_mtu = PACKETPROTO_MAXPAYLOAD;
  249. }
  250. pp_mtu = udpgw_mtu + sizeof(struct packetproto_header);
  251. // init time
  252. BTime_Init();
  253. // init DNS forwarding
  254. BAddr_InitNone(&dns_addr);
  255. last_dns_update_time = INT64_MIN;
  256. maybe_update_dns();
  257. // init reactor
  258. if (!BReactor_Init(&ss)) {
  259. BLog(BLOG_ERROR, "BReactor_Init failed");
  260. goto fail1;
  261. }
  262. // setup signal handler
  263. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  264. BLog(BLOG_ERROR, "BSignal_Init failed");
  265. goto fail2;
  266. }
  267. // initialize listeners
  268. num_listeners = 0;
  269. while (num_listeners < num_listen_addrs) {
  270. if (!BListener_Init(&listeners[num_listeners], listen_addrs[num_listeners], &ss, &listeners[num_listeners], (BListener_handler)listener_handler)) {
  271. BLog(BLOG_ERROR, "Listener_Init failed");
  272. goto fail3;
  273. }
  274. num_listeners++;
  275. }
  276. // init clients list
  277. LinkedList1_Init(&clients_list);
  278. num_clients = 0;
  279. // enter event loop
  280. BLog(BLOG_NOTICE, "entering event loop");
  281. BReactor_Exec(&ss);
  282. // free clients
  283. while (!LinkedList1_IsEmpty(&clients_list)) {
  284. struct client *client = UPPER_OBJECT(LinkedList1_GetFirst(&clients_list), struct client, clients_list_node);
  285. client_free(client);
  286. }
  287. fail3:
  288. // free listeners
  289. while (num_listeners > 0) {
  290. num_listeners--;
  291. BListener_Free(&listeners[num_listeners]);
  292. }
  293. // finish signal handling
  294. BSignal_Finish();
  295. fail2:
  296. // free reactor
  297. BReactor_Free(&ss);
  298. fail1:
  299. // free logger
  300. BLog(BLOG_NOTICE, "exiting");
  301. BLog_Free();
  302. fail0:
  303. // finish debug objects
  304. DebugObjectGlobal_Finish();
  305. return 1;
  306. }
  307. void print_help (const char *name)
  308. {
  309. printf(
  310. "Usage:\n"
  311. " %s\n"
  312. " [--help]\n"
  313. " [--version]\n"
  314. " [--logger <"LOGGERS_STRING">]\n"
  315. #ifndef BADVPN_USE_WINAPI
  316. " (logger=syslog?\n"
  317. " [--syslog-facility <string>]\n"
  318. " [--syslog-ident <string>]\n"
  319. " )\n"
  320. #endif
  321. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  322. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  323. " [--listen-addr <addr>] ...\n"
  324. " [--udp-mtu <bytes>]\n"
  325. " [--max-clients <number>]\n"
  326. " [--max-connections-for-client <number>]\n"
  327. " [--client-socket-sndbuf <bytes / 0>]\n"
  328. " [--local-udp-addrs <addr> <num_ports>]\n"
  329. " [--local-udp-ip6-addrs <addr> <num_ports>]\n"
  330. " [--unique-local-ports]\n"
  331. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  332. name
  333. );
  334. }
  335. void print_version (void)
  336. {
  337. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  338. }
  339. int parse_arguments (int argc, char *argv[])
  340. {
  341. if (argc <= 0) {
  342. return 0;
  343. }
  344. options.help = 0;
  345. options.version = 0;
  346. options.logger = LOGGER_STDOUT;
  347. #ifndef BADVPN_USE_WINAPI
  348. options.logger_syslog_facility = "daemon";
  349. options.logger_syslog_ident = argv[0];
  350. #endif
  351. options.loglevel = -1;
  352. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  353. options.loglevels[i] = -1;
  354. }
  355. options.num_listen_addrs = 0;
  356. options.udp_mtu = DEFAULT_UDP_MTU;
  357. options.max_clients = DEFAULT_MAX_CLIENTS;
  358. options.max_connections_for_client = DEFAULT_MAX_CONNECTIONS_FOR_CLIENT;
  359. options.client_socket_sndbuf = CLIENT_DEFAULT_SOCKET_SEND_BUFFER;
  360. options.local_udp_num_ports = -1;
  361. options.local_udp_ip6_num_ports = -1;
  362. options.unique_local_ports = 0;
  363. int i;
  364. for (i = 1; i < argc; i++) {
  365. char *arg = argv[i];
  366. if (!strcmp(arg, "--help")) {
  367. options.help = 1;
  368. }
  369. else if (!strcmp(arg, "--version")) {
  370. options.version = 1;
  371. }
  372. else if (!strcmp(arg, "--logger")) {
  373. if (1 >= argc - i) {
  374. fprintf(stderr, "%s: requires an argument\n", arg);
  375. return 0;
  376. }
  377. char *arg2 = argv[i + 1];
  378. if (!strcmp(arg2, "stdout")) {
  379. options.logger = LOGGER_STDOUT;
  380. }
  381. #ifndef BADVPN_USE_WINAPI
  382. else if (!strcmp(arg2, "syslog")) {
  383. options.logger = LOGGER_SYSLOG;
  384. }
  385. #endif
  386. else {
  387. fprintf(stderr, "%s: wrong argument\n", arg);
  388. return 0;
  389. }
  390. i++;
  391. }
  392. #ifndef BADVPN_USE_WINAPI
  393. else if (!strcmp(arg, "--syslog-facility")) {
  394. if (1 >= argc - i) {
  395. fprintf(stderr, "%s: requires an argument\n", arg);
  396. return 0;
  397. }
  398. options.logger_syslog_facility = argv[i + 1];
  399. i++;
  400. }
  401. else if (!strcmp(arg, "--syslog-ident")) {
  402. if (1 >= argc - i) {
  403. fprintf(stderr, "%s: requires an argument\n", arg);
  404. return 0;
  405. }
  406. options.logger_syslog_ident = argv[i + 1];
  407. i++;
  408. }
  409. #endif
  410. else if (!strcmp(arg, "--loglevel")) {
  411. if (1 >= argc - i) {
  412. fprintf(stderr, "%s: requires an argument\n", arg);
  413. return 0;
  414. }
  415. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  416. fprintf(stderr, "%s: wrong argument\n", arg);
  417. return 0;
  418. }
  419. i++;
  420. }
  421. else if (!strcmp(arg, "--channel-loglevel")) {
  422. if (2 >= argc - i) {
  423. fprintf(stderr, "%s: requires two arguments\n", arg);
  424. return 0;
  425. }
  426. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  427. if (channel < 0) {
  428. fprintf(stderr, "%s: wrong channel argument\n", arg);
  429. return 0;
  430. }
  431. int loglevel = parse_loglevel(argv[i + 2]);
  432. if (loglevel < 0) {
  433. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  434. return 0;
  435. }
  436. options.loglevels[channel] = loglevel;
  437. i += 2;
  438. }
  439. else if (!strcmp(arg, "--listen-addr")) {
  440. if (1 >= argc - i) {
  441. fprintf(stderr, "%s: requires an argument\n", arg);
  442. return 0;
  443. }
  444. if (options.num_listen_addrs == MAX_LISTEN_ADDRS) {
  445. fprintf(stderr, "%s: too many\n", arg);
  446. return 0;
  447. }
  448. options.listen_addrs[options.num_listen_addrs] = argv[i + 1];
  449. options.num_listen_addrs++;
  450. i++;
  451. }
  452. else if (!strcmp(arg, "--udp-mtu")) {
  453. if (1 >= argc - i) {
  454. fprintf(stderr, "%s: requires an argument\n", arg);
  455. return 0;
  456. }
  457. if ((options.udp_mtu = atoi(argv[i + 1])) < 0) {
  458. fprintf(stderr, "%s: wrong argument\n", arg);
  459. return 0;
  460. }
  461. i++;
  462. }
  463. else if (!strcmp(arg, "--max-clients")) {
  464. if (1 >= argc - i) {
  465. fprintf(stderr, "%s: requires an argument\n", arg);
  466. return 0;
  467. }
  468. if ((options.max_clients = atoi(argv[i + 1])) <= 0) {
  469. fprintf(stderr, "%s: wrong argument\n", arg);
  470. return 0;
  471. }
  472. i++;
  473. }
  474. else if (!strcmp(arg, "--max-connections-for-client")) {
  475. if (1 >= argc - i) {
  476. fprintf(stderr, "%s: requires an argument\n", arg);
  477. return 0;
  478. }
  479. if ((options.max_connections_for_client = atoi(argv[i + 1])) <= 0) {
  480. fprintf(stderr, "%s: wrong argument\n", arg);
  481. return 0;
  482. }
  483. i++;
  484. }
  485. else if (!strcmp(arg, "--client-socket-sndbuf")) {
  486. if (1 >= argc - i) {
  487. fprintf(stderr, "%s: requires an argument\n", arg);
  488. return 0;
  489. }
  490. if ((options.client_socket_sndbuf = atoi(argv[i + 1])) < 0) {
  491. fprintf(stderr, "%s: wrong argument\n", arg);
  492. return 0;
  493. }
  494. i++;
  495. }
  496. else if (!strcmp(arg, "--local-udp-addrs")) {
  497. if (2 >= argc - i) {
  498. fprintf(stderr, "%s: requires two arguments\n", arg);
  499. return 0;
  500. }
  501. options.local_udp_addr = argv[i + 1];
  502. if ((options.local_udp_num_ports = atoi(argv[i + 2])) < 0) {
  503. fprintf(stderr, "%s: wrong argument\n", arg);
  504. return 0;
  505. }
  506. i += 2;
  507. }
  508. else if (!strcmp(arg, "--local-udp-ip6-addrs")) {
  509. if (2 >= argc - i) {
  510. fprintf(stderr, "%s: requires two arguments\n", arg);
  511. return 0;
  512. }
  513. options.local_udp_ip6_addr = argv[i + 1];
  514. if ((options.local_udp_ip6_num_ports = atoi(argv[i + 2])) < 0) {
  515. fprintf(stderr, "%s: wrong argument\n", arg);
  516. return 0;
  517. }
  518. i += 2;
  519. }
  520. else if (!strcmp(arg, "--unique-local-ports")) {
  521. options.unique_local_ports = 1;
  522. }
  523. else {
  524. fprintf(stderr, "unknown option: %s\n", arg);
  525. return 0;
  526. }
  527. }
  528. if (options.help || options.version) {
  529. return 1;
  530. }
  531. return 1;
  532. }
  533. int process_arguments (void)
  534. {
  535. // resolve listen addresses
  536. num_listen_addrs = 0;
  537. while (num_listen_addrs < options.num_listen_addrs) {
  538. if (!BAddr_Parse(&listen_addrs[num_listen_addrs], options.listen_addrs[num_listen_addrs], NULL, 0)) {
  539. BLog(BLOG_ERROR, "listen addr: BAddr_Parse failed");
  540. return 0;
  541. }
  542. num_listen_addrs++;
  543. }
  544. // resolve local UDP address
  545. if (options.local_udp_num_ports >= 0) {
  546. if (!BAddr_Parse(&local_udp_addr, options.local_udp_addr, NULL, 0)) {
  547. BLog(BLOG_ERROR, "local udp addr: BAddr_Parse failed");
  548. return 0;
  549. }
  550. if (local_udp_addr.type != BADDR_TYPE_IPV4) {
  551. BLog(BLOG_ERROR, "local udp addr: must be an IPv4 address");
  552. return 0;
  553. }
  554. }
  555. // resolve local UDP/IPv6 address
  556. if (options.local_udp_ip6_num_ports >= 0) {
  557. if (!BAddr_Parse(&local_udp_ip6_addr, options.local_udp_ip6_addr, NULL, 0)) {
  558. BLog(BLOG_ERROR, "local udp ip6 addr: BAddr_Parse failed");
  559. return 0;
  560. }
  561. if (local_udp_ip6_addr.type != BADDR_TYPE_IPV6) {
  562. BLog(BLOG_ERROR, "local udp ip6 addr: must be an IPv6 address");
  563. return 0;
  564. }
  565. }
  566. return 1;
  567. }
  568. void signal_handler (void *unused)
  569. {
  570. BLog(BLOG_NOTICE, "termination requested");
  571. // exit event loop
  572. BReactor_Quit(&ss, 1);
  573. }
  574. void listener_handler (BListener *listener)
  575. {
  576. if (num_clients == options.max_clients) {
  577. BLog(BLOG_ERROR, "maximum number of clients reached");
  578. goto fail0;
  579. }
  580. // allocate structure
  581. struct client *client = (struct client *)malloc(sizeof(*client));
  582. if (!client) {
  583. BLog(BLOG_ERROR, "malloc failed");
  584. goto fail0;
  585. }
  586. // accept client
  587. if (!BConnection_Init(&client->con, BConnection_source_listener(listener, &client->addr), &ss, client, (BConnection_handler)client_connection_handler)) {
  588. BLog(BLOG_ERROR, "BConnection_Init failed");
  589. goto fail1;
  590. }
  591. // limit socket send buffer, else our scheduling is pointless
  592. if (options.client_socket_sndbuf > 0) {
  593. if (!BConnection_SetSendBuffer(&client->con, options.client_socket_sndbuf)) {
  594. BLog(BLOG_WARNING, "BConnection_SetSendBuffer failed");
  595. }
  596. }
  597. // init connection interfaces
  598. BConnection_SendAsync_Init(&client->con);
  599. BConnection_RecvAsync_Init(&client->con);
  600. // init disconnect timer
  601. BTimer_Init(&client->disconnect_timer, CLIENT_DISCONNECT_TIMEOUT, (BTimer_handler)client_disconnect_timer_handler, client);
  602. BReactor_SetTimer(&ss, &client->disconnect_timer);
  603. // init recv interface
  604. PacketPassInterface_Init(&client->recv_if, udpgw_mtu, (PacketPassInterface_handler_send)client_recv_if_handler_send, client, BReactor_PendingGroup(&ss));
  605. // init recv decoder
  606. if (!PacketProtoDecoder_Init(&client->recv_decoder, BConnection_RecvAsync_GetIf(&client->con), &client->recv_if, BReactor_PendingGroup(&ss), client,
  607. (PacketProtoDecoder_handler_error)client_decoder_handler_error
  608. )) {
  609. BLog(BLOG_ERROR, "PacketProtoDecoder_Init failed");
  610. goto fail2;
  611. }
  612. // init send sender
  613. PacketStreamSender_Init(&client->send_sender, BConnection_SendAsync_GetIf(&client->con), pp_mtu, BReactor_PendingGroup(&ss));
  614. // init send queue
  615. if (!PacketPassFairQueue_Init(&client->send_queue, PacketStreamSender_GetInput(&client->send_sender), BReactor_PendingGroup(&ss), 0, 1)) {
  616. BLog(BLOG_ERROR, "PacketPassFairQueue_Init failed");
  617. goto fail3;
  618. }
  619. // init connections tree
  620. BAVL_Init(&client->connections_tree, OFFSET_DIFF(struct connection, conid, connections_tree_node), (BAVL_comparator)uint16_comparator, NULL);
  621. // init connections list
  622. LinkedList1_Init(&client->connections_list);
  623. // set zero connections
  624. client->num_connections = 0;
  625. // init closing connections list
  626. LinkedList1_Init(&client->closing_connections_list);
  627. // insert to clients list
  628. LinkedList1_Append(&clients_list, &client->clients_list_node);
  629. num_clients++;
  630. client_log(client, BLOG_INFO, "connected");
  631. return;
  632. fail3:
  633. PacketStreamSender_Free(&client->send_sender);
  634. PacketProtoDecoder_Free(&client->recv_decoder);
  635. fail2:
  636. PacketPassInterface_Free(&client->recv_if);
  637. BReactor_RemoveTimer(&ss, &client->disconnect_timer);
  638. BConnection_RecvAsync_Free(&client->con);
  639. BConnection_SendAsync_Free(&client->con);
  640. BConnection_Free(&client->con);
  641. fail1:
  642. free(client);
  643. fail0:
  644. return;
  645. }
  646. void client_free (struct client *client)
  647. {
  648. // allow freeing send queue flows
  649. PacketPassFairQueue_PrepareFree(&client->send_queue);
  650. // free connections
  651. while (!LinkedList1_IsEmpty(&client->connections_list)) {
  652. struct connection *con = UPPER_OBJECT(LinkedList1_GetFirst(&client->connections_list), struct connection, connections_list_node);
  653. connection_free(con);
  654. }
  655. // free closing connections
  656. while (!LinkedList1_IsEmpty(&client->closing_connections_list)) {
  657. struct connection *con = UPPER_OBJECT(LinkedList1_GetFirst(&client->closing_connections_list), struct connection, closing_connections_list_node);
  658. connection_free(con);
  659. }
  660. // remove from clients list
  661. LinkedList1_Remove(&clients_list, &client->clients_list_node);
  662. num_clients--;
  663. // free send queue
  664. PacketPassFairQueue_Free(&client->send_queue);
  665. // free send sender
  666. PacketStreamSender_Free(&client->send_sender);
  667. // free recv decoder
  668. PacketProtoDecoder_Free(&client->recv_decoder);
  669. // free recv interface
  670. PacketPassInterface_Free(&client->recv_if);
  671. // free disconnect timer
  672. BReactor_RemoveTimer(&ss, &client->disconnect_timer);
  673. // free connection interfaces
  674. BConnection_RecvAsync_Free(&client->con);
  675. BConnection_SendAsync_Free(&client->con);
  676. // free connection
  677. BConnection_Free(&client->con);
  678. // free structure
  679. free(client);
  680. }
  681. void client_logfunc (struct client *client)
  682. {
  683. char addr[BADDR_MAX_PRINT_LEN];
  684. BAddr_Print(&client->addr, addr);
  685. BLog_Append("client (%s): ", addr);
  686. }
  687. void client_log (struct client *client, int level, const char *fmt, ...)
  688. {
  689. va_list vl;
  690. va_start(vl, fmt);
  691. BLog_LogViaFuncVarArg((BLog_logfunc)client_logfunc, client, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  692. va_end(vl);
  693. }
  694. void client_disconnect_timer_handler (struct client *client)
  695. {
  696. client_log(client, BLOG_INFO, "timed out, disconnecting");
  697. // free client
  698. client_free(client);
  699. }
  700. void client_connection_handler (struct client *client, int event)
  701. {
  702. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  703. client_log(client, BLOG_INFO, "client closed");
  704. } else {
  705. client_log(client, BLOG_INFO, "client error");
  706. }
  707. // free client
  708. client_free(client);
  709. }
  710. void client_decoder_handler_error (struct client *client)
  711. {
  712. client_log(client, BLOG_ERROR, "decoder error");
  713. // free client
  714. client_free(client);
  715. }
  716. void client_recv_if_handler_send (struct client *client, uint8_t *data, int data_len)
  717. {
  718. ASSERT(data_len >= 0)
  719. ASSERT(data_len <= udpgw_mtu)
  720. // accept packet
  721. PacketPassInterface_Done(&client->recv_if);
  722. // parse header
  723. if (data_len < sizeof(struct udpgw_header)) {
  724. client_log(client, BLOG_ERROR, "missing header");
  725. return;
  726. }
  727. struct udpgw_header header;
  728. memcpy(&header, data, sizeof(header));
  729. data += sizeof(header);
  730. data_len -= sizeof(header);
  731. uint8_t flags = ltoh8(header.flags);
  732. uint16_t conid = ltoh16(header.conid);
  733. // reset disconnect timer
  734. BReactor_SetTimer(&ss, &client->disconnect_timer);
  735. // if this is keepalive, ignore any payload
  736. if ((flags & UDPGW_CLIENT_FLAG_KEEPALIVE)) {
  737. client_log(client, BLOG_DEBUG, "received keepalive");
  738. return;
  739. }
  740. // parse address
  741. BAddr orig_addr;
  742. if ((flags & UDPGW_CLIENT_FLAG_IPV6)) {
  743. if (data_len < sizeof(struct udpgw_addr_ipv6)) {
  744. client_log(client, BLOG_ERROR, "missing ipv6 address");
  745. return;
  746. }
  747. struct udpgw_addr_ipv6 addr_ipv6;
  748. memcpy(&addr_ipv6, data, sizeof(addr_ipv6));
  749. data += sizeof(addr_ipv6);
  750. data_len -= sizeof(addr_ipv6);
  751. BAddr_InitIPv6(&orig_addr, addr_ipv6.addr_ip, addr_ipv6.addr_port);
  752. } else {
  753. if (data_len < sizeof(struct udpgw_addr_ipv4)) {
  754. client_log(client, BLOG_ERROR, "missing ipv4 address");
  755. return;
  756. }
  757. struct udpgw_addr_ipv4 addr_ipv4;
  758. memcpy(&addr_ipv4, data, sizeof(addr_ipv4));
  759. data += sizeof(addr_ipv4);
  760. data_len -= sizeof(addr_ipv4);
  761. BAddr_InitIPv4(&orig_addr, addr_ipv4.addr_ip, addr_ipv4.addr_port);
  762. }
  763. // check payload length
  764. if (data_len > options.udp_mtu) {
  765. client_log(client, BLOG_ERROR, "too much data");
  766. return;
  767. }
  768. // find connection
  769. struct connection *con = find_connection(client, conid);
  770. ASSERT(!con || !con->closing)
  771. // if connection exists, close it if needed
  772. if (con && ((flags & UDPGW_CLIENT_FLAG_REBIND) || !BAddr_Compare(&con->orig_addr, &orig_addr))) {
  773. connection_log(con, BLOG_DEBUG, "close old");
  774. connection_close(con);
  775. con = NULL;
  776. }
  777. // if connection doesn't exists, create it
  778. if (!con) {
  779. // check number of connections
  780. if (client->num_connections == options.max_connections_for_client) {
  781. // close least recently used connection
  782. con = UPPER_OBJECT(LinkedList1_GetFirst(&client->connections_list), struct connection, connections_list_node);
  783. connection_close(con);
  784. }
  785. // if this is DNS, replace actual address, but keep still remember the orig_addr
  786. BAddr addr = orig_addr;
  787. if ((flags & UDPGW_CLIENT_FLAG_DNS)) {
  788. maybe_update_dns();
  789. if (dns_addr.type == BADDR_TYPE_NONE) {
  790. client_log(client, BLOG_WARNING, "received DNS packet, but no DNS server available");
  791. } else {
  792. client_log(client, BLOG_DEBUG, "received DNS");
  793. addr = dns_addr;
  794. }
  795. }
  796. // create new connection
  797. connection_init(client, conid, addr, orig_addr, data, data_len);
  798. } else {
  799. // submit packet to existing connection
  800. connection_send_to_udp(con, data, data_len);
  801. }
  802. }
  803. int get_local_num_ports (int addr_type)
  804. {
  805. switch (addr_type) {
  806. case BADDR_TYPE_IPV4: return options.local_udp_num_ports;
  807. case BADDR_TYPE_IPV6: return options.local_udp_ip6_num_ports;
  808. default: ASSERT(0); return 0;
  809. }
  810. }
  811. BAddr get_local_addr (int addr_type)
  812. {
  813. ASSERT(get_local_num_ports(addr_type) >= 0)
  814. switch (addr_type) {
  815. case BADDR_TYPE_IPV4: return local_udp_addr;
  816. case BADDR_TYPE_IPV6: return local_udp_ip6_addr;
  817. default: ASSERT(0); return BAddr_MakeNone();
  818. }
  819. }
  820. uint8_t * build_port_usage_array_and_find_least_used_connection (BAddr remote_addr, struct connection **out_con)
  821. {
  822. ASSERT(remote_addr.type == BADDR_TYPE_IPV4 || remote_addr.type == BADDR_TYPE_IPV6)
  823. ASSERT(get_local_num_ports(remote_addr.type) >= 0)
  824. int local_num_ports = get_local_num_ports(remote_addr.type);
  825. // allocate port usage array
  826. uint8_t *port_usage = (uint8_t *)BAllocSize(bsize_fromint(local_num_ports));
  827. if (!port_usage) {
  828. return NULL;
  829. }
  830. // zero array
  831. memset(port_usage, 0, local_num_ports);
  832. struct connection *least_con = NULL;
  833. // flag inappropriate ports (those with the same remote address)
  834. for (LinkedList1Node *ln = LinkedList1_GetFirst(&clients_list); ln; ln = LinkedList1Node_Next(ln)) {
  835. struct client *client = UPPER_OBJECT(ln, struct client, clients_list_node);
  836. for (LinkedList1Node *ln2 = LinkedList1_GetFirst(&client->connections_list); ln2; ln2 = LinkedList1Node_Next(ln2)) {
  837. struct connection *con = UPPER_OBJECT(ln2, struct connection, connections_list_node);
  838. ASSERT(con->client == client)
  839. ASSERT(!con->closing)
  840. if (con->addr.type != remote_addr.type || con->local_port_index < 0) {
  841. continue;
  842. }
  843. ASSERT(con->local_port_index < local_num_ports)
  844. if (options.unique_local_ports) {
  845. BIPAddr ip1;
  846. BIPAddr ip2;
  847. BAddr_GetIPAddr(&con->addr, &ip1);
  848. BAddr_GetIPAddr(&remote_addr, &ip2);
  849. if (!BIPAddr_Compare(&ip1, &ip2)) {
  850. continue;
  851. }
  852. } else {
  853. if (!BAddr_Compare(&con->addr, &remote_addr)) {
  854. continue;
  855. }
  856. }
  857. port_usage[con->local_port_index] = 1;
  858. if (!PacketPassFairQueueFlow_IsBusy(&con->send_qflow)) {
  859. if (!least_con || con->last_use_time < least_con->last_use_time) {
  860. least_con = con;
  861. }
  862. }
  863. }
  864. }
  865. *out_con = least_con;
  866. return port_usage;
  867. }
  868. void connection_init (struct client *client, uint16_t conid, BAddr addr, BAddr orig_addr, const uint8_t *data, int data_len)
  869. {
  870. ASSERT(client->num_connections < options.max_connections_for_client)
  871. ASSERT(!find_connection(client, conid))
  872. BAddr_Assert(&addr);
  873. ASSERT(addr.type == BADDR_TYPE_IPV4 || addr.type == BADDR_TYPE_IPV6)
  874. ASSERT(orig_addr.type == BADDR_TYPE_IPV4 || orig_addr.type == BADDR_TYPE_IPV6)
  875. ASSERT(data_len >= 0)
  876. ASSERT(data_len <= options.udp_mtu)
  877. // allocate structure
  878. struct connection *con = (struct connection *)malloc(sizeof(*con));
  879. if (!con) {
  880. client_log(client, BLOG_ERROR, "malloc failed");
  881. goto fail0;
  882. }
  883. // init arguments
  884. con->client = client;
  885. con->conid = conid;
  886. con->addr = addr;
  887. con->orig_addr = orig_addr;
  888. con->first_data = data;
  889. con->first_data_len = data_len;
  890. // set last use time
  891. con->last_use_time = btime_gettime();
  892. // set not closing
  893. con->closing = 0;
  894. // init first job
  895. BPending_Init(&con->first_job, BReactor_PendingGroup(&ss), (BPending_handler)connection_first_job_handler, con);
  896. BPending_Set(&con->first_job);
  897. // init send queue flow
  898. PacketPassFairQueueFlow_Init(&con->send_qflow, &client->send_queue);
  899. // init send PacketProtoFlow
  900. if (!PacketProtoFlow_Init(&con->send_ppflow, udpgw_mtu, CONNECTION_CLIENT_BUFFER_SIZE, PacketPassFairQueueFlow_GetInput(&con->send_qflow), BReactor_PendingGroup(&ss))) {
  901. client_log(client, BLOG_ERROR, "PacketProtoFlow_Init failed");
  902. goto fail1;
  903. }
  904. con->send_if = PacketProtoFlow_GetInput(&con->send_ppflow);
  905. // init UDP dgram
  906. if (!BDatagram_Init(&con->udp_dgram, addr.type, &ss, con, (BDatagram_handler)connection_dgram_handler_event)) {
  907. client_log(client, BLOG_ERROR, "BDatagram_Init failed");
  908. goto fail2;
  909. }
  910. con->local_port_index = -1;
  911. int local_num_ports = get_local_num_ports(addr.type);
  912. if (local_num_ports >= 0) {
  913. // build port usage array, find least used connection
  914. struct connection *least_con;
  915. uint8_t *port_usage = build_port_usage_array_and_find_least_used_connection(addr, &least_con);
  916. if (!port_usage) {
  917. client_log(client, BLOG_ERROR, "build_port_usage_array failed");
  918. goto failed;
  919. }
  920. // set SO_REUSEADDR
  921. if (!BDatagram_SetReuseAddr(&con->udp_dgram, 1)) {
  922. client_log(client, BLOG_ERROR, "set SO_REUSEADDR failed");
  923. goto failed;
  924. }
  925. // get starting local address
  926. BAddr local_addr = get_local_addr(addr.type);
  927. // try different ports
  928. for (int i = 0; i < local_num_ports; i++) {
  929. // skip inappropriate ports
  930. if (port_usage[i]) {
  931. continue;
  932. }
  933. BAddr bind_addr = local_addr;
  934. BAddr_SetPort(&bind_addr, hton16(ntoh16(BAddr_GetPort(&bind_addr)) + (uint16_t)i));
  935. if (BDatagram_Bind(&con->udp_dgram, bind_addr)) {
  936. // remember which port we're using
  937. con->local_port_index = i;
  938. goto cont;
  939. }
  940. }
  941. // try closing an unused connection with the same remote addr
  942. if (!least_con) {
  943. goto failed;
  944. }
  945. ASSERT(least_con->addr.type == addr.type)
  946. ASSERT(least_con->local_port_index >= 0)
  947. ASSERT(least_con->local_port_index < local_num_ports)
  948. ASSERT(!PacketPassFairQueueFlow_IsBusy(&least_con->send_qflow))
  949. int i = least_con->local_port_index;
  950. BLog(BLOG_INFO, "closing connection for its remote address");
  951. // close the offending connection
  952. connection_close(least_con);
  953. // try binding to its port
  954. BAddr bind_addr = local_addr;
  955. BAddr_SetPort(&bind_addr, hton16(ntoh16(BAddr_GetPort(&bind_addr)) + (uint16_t)i));
  956. if (BDatagram_Bind(&con->udp_dgram, bind_addr)) {
  957. // remember which port we're using
  958. con->local_port_index = i;
  959. goto cont;
  960. }
  961. failed:
  962. client_log(client, BLOG_WARNING, "failed to bind to any local address; proceeding regardless");
  963. cont:;
  964. BFree(port_usage);
  965. }
  966. // set UDP dgram send address
  967. BIPAddr ipaddr;
  968. BIPAddr_InitInvalid(&ipaddr);
  969. BDatagram_SetSendAddrs(&con->udp_dgram, addr, ipaddr);
  970. // init UDP dgram interfaces
  971. BDatagram_SendAsync_Init(&con->udp_dgram, options.udp_mtu);
  972. BDatagram_RecvAsync_Init(&con->udp_dgram, options.udp_mtu);
  973. // init UDP writer
  974. BufferWriter_Init(&con->udp_send_writer, options.udp_mtu, BReactor_PendingGroup(&ss));
  975. // init UDP buffer
  976. if (!PacketBuffer_Init(&con->udp_send_buffer, BufferWriter_GetOutput(&con->udp_send_writer), BDatagram_SendAsync_GetIf(&con->udp_dgram), CONNECTION_UDP_BUFFER_SIZE, BReactor_PendingGroup(&ss))) {
  977. client_log(client, BLOG_ERROR, "PacketBuffer_Init failed");
  978. goto fail4;
  979. }
  980. // init UDP recv interface
  981. PacketPassInterface_Init(&con->udp_recv_if, options.udp_mtu, (PacketPassInterface_handler_send)connection_udp_recv_if_handler_send, con, BReactor_PendingGroup(&ss));
  982. // init UDP recv buffer
  983. if (!SinglePacketBuffer_Init(&con->udp_recv_buffer, BDatagram_RecvAsync_GetIf(&con->udp_dgram), &con->udp_recv_if, BReactor_PendingGroup(&ss))) {
  984. client_log(client, BLOG_ERROR, "SinglePacketBuffer_Init failed");
  985. goto fail5;
  986. }
  987. // insert to client's connections tree
  988. ASSERT_EXECUTE(BAVL_Insert(&client->connections_tree, &con->connections_tree_node, NULL))
  989. // insert to client's connections list
  990. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  991. // increment number of connections
  992. client->num_connections++;
  993. connection_log(con, BLOG_DEBUG, "initialized");
  994. return;
  995. fail5:
  996. PacketPassInterface_Free(&con->udp_recv_if);
  997. PacketBuffer_Free(&con->udp_send_buffer);
  998. fail4:
  999. BufferWriter_Free(&con->udp_send_writer);
  1000. BDatagram_RecvAsync_Free(&con->udp_dgram);
  1001. BDatagram_SendAsync_Free(&con->udp_dgram);
  1002. BDatagram_Free(&con->udp_dgram);
  1003. fail2:
  1004. PacketProtoFlow_Free(&con->send_ppflow);
  1005. fail1:
  1006. PacketPassFairQueueFlow_Free(&con->send_qflow);
  1007. BPending_Free(&con->first_job);
  1008. free(con);
  1009. fail0:
  1010. return;
  1011. }
  1012. void connection_free (struct connection *con)
  1013. {
  1014. struct client *client = con->client;
  1015. PacketPassFairQueueFlow_AssertFree(&con->send_qflow);
  1016. if (con->closing) {
  1017. // remove from client's closing connections list
  1018. LinkedList1_Remove(&client->closing_connections_list, &con->closing_connections_list_node);
  1019. } else {
  1020. // decrement number of connections
  1021. client->num_connections--;
  1022. // remove from client's connections list
  1023. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1024. // remove from client's connections tree
  1025. BAVL_Remove(&client->connections_tree, &con->connections_tree_node);
  1026. // free UDP
  1027. connection_free_udp(con);
  1028. }
  1029. // free send PacketProtoFlow
  1030. PacketProtoFlow_Free(&con->send_ppflow);
  1031. // free send queue flow
  1032. PacketPassFairQueueFlow_Free(&con->send_qflow);
  1033. // free first job
  1034. BPending_Free(&con->first_job);
  1035. // free structure
  1036. free(con);
  1037. }
  1038. void connection_logfunc (struct connection *con)
  1039. {
  1040. client_logfunc(con->client);
  1041. if (con->closing) {
  1042. BLog_Append("old connection %"PRIu16": ", con->conid);
  1043. } else {
  1044. BLog_Append("connection %"PRIu16": ", con->conid);
  1045. }
  1046. }
  1047. void connection_log (struct connection *con, int level, const char *fmt, ...)
  1048. {
  1049. va_list vl;
  1050. va_start(vl, fmt);
  1051. BLog_LogViaFuncVarArg((BLog_logfunc)connection_logfunc, con, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1052. va_end(vl);
  1053. }
  1054. void connection_free_udp (struct connection *con)
  1055. {
  1056. // free UDP receive buffer
  1057. SinglePacketBuffer_Free(&con->udp_recv_buffer);
  1058. // free UDP receive interface
  1059. PacketPassInterface_Free(&con->udp_recv_if);
  1060. // free UDP buffer
  1061. PacketBuffer_Free(&con->udp_send_buffer);
  1062. // free UDP writer
  1063. BufferWriter_Free(&con->udp_send_writer);
  1064. // free UDP dgram interfaces
  1065. BDatagram_RecvAsync_Free(&con->udp_dgram);
  1066. BDatagram_SendAsync_Free(&con->udp_dgram);
  1067. // free UDP dgram
  1068. BDatagram_Free(&con->udp_dgram);
  1069. }
  1070. void connection_first_job_handler (struct connection *con)
  1071. {
  1072. ASSERT(!con->closing)
  1073. connection_send_to_udp(con, con->first_data, con->first_data_len);
  1074. }
  1075. void connection_send_to_client (struct connection *con, uint8_t flags, const uint8_t *data, int data_len)
  1076. {
  1077. ASSERT(data_len >= 0)
  1078. ASSERT(data_len <= options.udp_mtu)
  1079. size_t addr_len = (con->orig_addr.type == BADDR_TYPE_IPV6) ? sizeof(struct udpgw_addr_ipv6) :
  1080. (con->orig_addr.type == BADDR_TYPE_IPV4) ? sizeof(struct udpgw_addr_ipv4) : 0;
  1081. if (data_len > udpgw_mtu - (int)(sizeof(struct udpgw_header) + addr_len)) {
  1082. connection_log(con, BLOG_WARNING, "packet is too large, cannot send to client");
  1083. return;
  1084. }
  1085. // get buffer location
  1086. uint8_t *out;
  1087. if (!BufferWriter_StartPacket(con->send_if, &out)) {
  1088. connection_log(con, BLOG_ERROR, "out of client buffer");
  1089. return;
  1090. }
  1091. int out_pos = 0;
  1092. if (con->orig_addr.type == BADDR_TYPE_IPV6) {
  1093. flags |= UDPGW_CLIENT_FLAG_IPV6;
  1094. }
  1095. // write header
  1096. struct udpgw_header header;
  1097. header.flags = htol8(flags);
  1098. header.conid = htol16(con->conid);
  1099. memcpy(out + out_pos, &header, sizeof(header));
  1100. out_pos += sizeof(header);
  1101. // write address
  1102. switch (con->orig_addr.type) {
  1103. case BADDR_TYPE_IPV4: {
  1104. struct udpgw_addr_ipv4 addr_ipv4;
  1105. addr_ipv4.addr_ip = con->orig_addr.ipv4.ip;
  1106. addr_ipv4.addr_port = con->orig_addr.ipv4.port;
  1107. memcpy(out + out_pos, &addr_ipv4, sizeof(addr_ipv4));
  1108. out_pos += sizeof(addr_ipv4);
  1109. } break;
  1110. case BADDR_TYPE_IPV6: {
  1111. struct udpgw_addr_ipv6 addr_ipv6;
  1112. memcpy(addr_ipv6.addr_ip, con->orig_addr.ipv6.ip, sizeof(addr_ipv6.addr_ip));
  1113. addr_ipv6.addr_port = con->orig_addr.ipv6.port;
  1114. memcpy(out + out_pos, &addr_ipv6, sizeof(addr_ipv6));
  1115. out_pos += sizeof(addr_ipv6);
  1116. } break;
  1117. }
  1118. // write message
  1119. memcpy(out + out_pos, data, data_len);
  1120. out_pos += data_len;
  1121. // submit written message
  1122. ASSERT(out_pos <= udpgw_mtu)
  1123. BufferWriter_EndPacket(con->send_if, out_pos);
  1124. }
  1125. int connection_send_to_udp (struct connection *con, const uint8_t *data, int data_len)
  1126. {
  1127. struct client *client = con->client;
  1128. ASSERT(!con->closing)
  1129. ASSERT(data_len >= 0)
  1130. ASSERT(data_len <= options.udp_mtu)
  1131. connection_log(con, BLOG_DEBUG, "from client %d bytes", data_len);
  1132. // set last use time
  1133. con->last_use_time = btime_gettime();
  1134. // move connection to front
  1135. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1136. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  1137. // get buffer location
  1138. uint8_t *out;
  1139. if (!BufferWriter_StartPacket(&con->udp_send_writer, &out)) {
  1140. connection_log(con, BLOG_ERROR, "out of UDP buffer");
  1141. return 0;
  1142. }
  1143. // write message
  1144. memcpy(out, data, data_len);
  1145. // submit written message
  1146. BufferWriter_EndPacket(&con->udp_send_writer, data_len);
  1147. return 1;
  1148. }
  1149. void connection_close (struct connection *con)
  1150. {
  1151. struct client *client = con->client;
  1152. ASSERT(!con->closing)
  1153. // if possible, free connection immediately
  1154. if (!PacketPassFairQueueFlow_IsBusy(&con->send_qflow)) {
  1155. connection_free(con);
  1156. return;
  1157. }
  1158. connection_log(con, BLOG_DEBUG, "closing later");
  1159. // decrement number of connections
  1160. client->num_connections--;
  1161. // remove from client's connections list
  1162. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1163. // remove from client's connections tree
  1164. BAVL_Remove(&client->connections_tree, &con->connections_tree_node);
  1165. // free UDP
  1166. connection_free_udp(con);
  1167. // insert to client's closing connections list
  1168. LinkedList1_Append(&client->closing_connections_list, &con->closing_connections_list_node);
  1169. // set busy handler
  1170. PacketPassFairQueueFlow_SetBusyHandler(&con->send_qflow, (PacketPassFairQueue_handler_busy)connection_send_qflow_busy_handler, con);
  1171. // unset first job
  1172. BPending_Unset(&con->first_job);
  1173. // set closing
  1174. con->closing = 1;
  1175. }
  1176. void connection_send_qflow_busy_handler (struct connection *con)
  1177. {
  1178. ASSERT(con->closing)
  1179. PacketPassFairQueueFlow_AssertFree(&con->send_qflow);
  1180. connection_log(con, BLOG_DEBUG, "closing finally");
  1181. // free connection
  1182. connection_free(con);
  1183. }
  1184. void connection_dgram_handler_event (struct connection *con, int event)
  1185. {
  1186. ASSERT(!con->closing)
  1187. connection_log(con, BLOG_INFO, "UDP error");
  1188. // close connection
  1189. connection_close(con);
  1190. }
  1191. void connection_udp_recv_if_handler_send (struct connection *con, uint8_t *data, int data_len)
  1192. {
  1193. struct client *client = con->client;
  1194. ASSERT(!con->closing)
  1195. ASSERT(data_len >= 0)
  1196. ASSERT(data_len <= options.udp_mtu)
  1197. connection_log(con, BLOG_DEBUG, "from UDP %d bytes", data_len);
  1198. // set last use time
  1199. con->last_use_time = btime_gettime();
  1200. // move connection to front
  1201. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1202. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  1203. // accept packet
  1204. PacketPassInterface_Done(&con->udp_recv_if);
  1205. // send packet to client
  1206. connection_send_to_client(con, 0, data, data_len);
  1207. }
  1208. struct connection * find_connection (struct client *client, uint16_t conid)
  1209. {
  1210. BAVLNode *tree_node = BAVL_LookupExact(&client->connections_tree, &conid);
  1211. if (!tree_node) {
  1212. return NULL;
  1213. }
  1214. struct connection *con = UPPER_OBJECT(tree_node, struct connection, connections_tree_node);
  1215. ASSERT(con->conid == conid)
  1216. ASSERT(!con->closing)
  1217. return con;
  1218. }
  1219. int uint16_comparator (void *unused, uint16_t *v1, uint16_t *v2)
  1220. {
  1221. return B_COMPARE(*v1, *v2);
  1222. }
  1223. void maybe_update_dns (void)
  1224. {
  1225. #ifndef BADVPN_USE_WINAPI
  1226. btime_t now = btime_gettime();
  1227. if (now < btime_add(last_dns_update_time, DNS_UPDATE_TIME)) {
  1228. return;
  1229. }
  1230. last_dns_update_time = now;
  1231. BLog(BLOG_DEBUG, "update dns");
  1232. if (res_init() != 0) {
  1233. BLog(BLOG_ERROR, "res_init failed");
  1234. goto fail;
  1235. }
  1236. if (_res.nscount == 0) {
  1237. BLog(BLOG_ERROR, "no name servers available");
  1238. goto fail;
  1239. }
  1240. BAddr addr;
  1241. BAddr_InitIPv4(&addr, _res.nsaddr_list[0].sin_addr.s_addr, hton16(53));
  1242. if (!BAddr_Compare(&addr, &dns_addr)) {
  1243. char str[BADDR_MAX_PRINT_LEN];
  1244. BAddr_Print(&addr, str);
  1245. BLog(BLOG_INFO, "using DNS server %s", str);
  1246. }
  1247. dns_addr = addr;
  1248. return;
  1249. fail:
  1250. BAddr_InitNone(&dns_addr);
  1251. #endif
  1252. }