udpgw.c 42 KB

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