udpgw.c 41 KB

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