udpgw.c 41 KB

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