udpgw.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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 = (struct udpgw_header *)data;
  687. data += sizeof(*header);
  688. data_len -= sizeof(*header);
  689. uint8_t flags = ltoh8(header->flags);
  690. uint16_t conid = ltoh16(header->conid);
  691. // reset disconnect timer
  692. BReactor_SetTimer(&ss, &client->disconnect_timer);
  693. // if this is keepalive, ignore any payload
  694. if ((flags & UDPGW_CLIENT_FLAG_KEEPALIVE)) {
  695. client_log(client, BLOG_DEBUG, "received keepalive");
  696. return;
  697. }
  698. // check payload length
  699. if (data_len > options.udp_mtu) {
  700. client_log(client, BLOG_ERROR, "too much data");
  701. return;
  702. }
  703. // find connection
  704. struct connection *con = find_connection(client, conid);
  705. ASSERT(!con || !con->closing)
  706. // if connection exists, close it if needed
  707. if (con && ((flags & UDPGW_CLIENT_FLAG_REBIND) || con->addr.ipv4.ip != header->addr_ip || con->addr.ipv4.port != header->addr_port)) {
  708. connection_log(con, BLOG_DEBUG, "close old");
  709. connection_close(con);
  710. con = NULL;
  711. }
  712. // if connection doesn't exists, create it
  713. if (!con) {
  714. // check number of connections
  715. if (client->num_connections == options.max_connections_for_client) {
  716. // close least recently used connection
  717. con = UPPER_OBJECT(LinkedList1_GetFirst(&client->connections_list), struct connection, connections_list_node);
  718. connection_close(con);
  719. }
  720. // read address
  721. BAddr addr;
  722. BAddr_InitIPv4(&addr, header->addr_ip, header->addr_port);
  723. // create new connection
  724. connection_init(client, conid, addr, data, data_len);
  725. } else {
  726. // submit packet to existing connection
  727. connection_send_to_udp(con, data, data_len);
  728. }
  729. }
  730. uint8_t * build_port_usage_array_and_find_least_used_connection (BAddr remote_addr, struct connection **out_con)
  731. {
  732. ASSERT(options.local_udp_num_ports >= 0)
  733. ASSERT(remote_addr.type == BADDR_TYPE_IPV4)
  734. // allocate port usage array
  735. uint8_t *port_usage = (uint8_t *)BAllocSize(bsize_fromint(options.local_udp_num_ports));
  736. if (!port_usage) {
  737. return NULL;
  738. }
  739. // zero array
  740. memset(port_usage, 0, options.local_udp_num_ports);
  741. struct connection *least_con = NULL;
  742. // flag inappropriate ports (those with the same remote address)
  743. for (LinkedList1Node *ln = LinkedList1_GetFirst(&clients_list); ln; ln = LinkedList1Node_Next(ln)) {
  744. struct client *client = UPPER_OBJECT(ln, struct client, clients_list_node);
  745. for (LinkedList1Node *ln2 = LinkedList1_GetFirst(&client->connections_list); ln2; ln2 = LinkedList1Node_Next(ln2)) {
  746. struct connection *con = UPPER_OBJECT(ln2, struct connection, connections_list_node);
  747. ASSERT(con->client == client)
  748. ASSERT(!con->closing)
  749. ASSERT(con->local_port_index < options.local_udp_num_ports)
  750. if (con->local_port_index < 0) {
  751. continue;
  752. }
  753. if (options.unique_local_ports) {
  754. if (con->addr.ipv4.ip != remote_addr.ipv4.ip) {
  755. continue;
  756. }
  757. } else {
  758. if (!BAddr_Compare(&con->addr, &remote_addr)) {
  759. continue;
  760. }
  761. }
  762. port_usage[con->local_port_index] = 1;
  763. if (!PacketPassFairQueueFlow_IsBusy(&con->send_qflow)) {
  764. if (!least_con || con->last_use_time < least_con->last_use_time) {
  765. least_con = con;
  766. }
  767. }
  768. }
  769. }
  770. *out_con = least_con;
  771. return port_usage;
  772. }
  773. void connection_init (struct client *client, uint16_t conid, BAddr addr, const uint8_t *data, int data_len)
  774. {
  775. ASSERT(client->num_connections < options.max_connections_for_client)
  776. ASSERT(!find_connection(client, conid))
  777. BAddr_Assert(&addr);
  778. ASSERT(addr.type == BADDR_TYPE_IPV4)
  779. ASSERT(data_len >= 0)
  780. ASSERT(data_len <= options.udp_mtu)
  781. // allocate structure
  782. struct connection *con = (struct connection *)malloc(sizeof(*con));
  783. if (!con) {
  784. client_log(client, BLOG_ERROR, "malloc failed");
  785. goto fail0;
  786. }
  787. // init arguments
  788. con->client = client;
  789. con->conid = conid;
  790. con->addr = addr;
  791. con->first_data = data;
  792. con->first_data_len = data_len;
  793. // set last use time
  794. con->last_use_time = btime_gettime();
  795. // set not closing
  796. con->closing = 0;
  797. // init first job
  798. BPending_Init(&con->first_job, BReactor_PendingGroup(&ss), (BPending_handler)connection_first_job_handler, con);
  799. BPending_Set(&con->first_job);
  800. // init send queue flow
  801. PacketPassFairQueueFlow_Init(&con->send_qflow, &client->send_queue);
  802. // init send PacketProtoFlow
  803. if (!PacketProtoFlow_Init(&con->send_ppflow, udpgw_mtu, CONNECTION_CLIENT_BUFFER_SIZE, PacketPassFairQueueFlow_GetInput(&con->send_qflow), BReactor_PendingGroup(&ss))) {
  804. client_log(client, BLOG_ERROR, "PacketProtoFlow_Init failed");
  805. goto fail1;
  806. }
  807. con->send_if = PacketProtoFlow_GetInput(&con->send_ppflow);
  808. // init UDP dgram
  809. if (!BDatagram_Init(&con->udp_dgram, addr.type, &ss, con, (BDatagram_handler)connection_dgram_handler_event)) {
  810. client_log(client, BLOG_ERROR, "BDatagram_Init failed");
  811. goto fail2;
  812. }
  813. con->local_port_index = -1;
  814. if (options.local_udp_num_ports >= 0) {
  815. // build port usage array, find least used connection
  816. struct connection *least_con;
  817. uint8_t *port_usage = build_port_usage_array_and_find_least_used_connection(addr, &least_con);
  818. if (!port_usage) {
  819. client_log(client, BLOG_ERROR, "build_port_usage_array failed");
  820. goto failed;
  821. }
  822. // set SO_REUSEADDR
  823. if (!BDatagram_SetReuseAddr(&con->udp_dgram, 1)) {
  824. client_log(client, BLOG_ERROR, "set SO_REUSEADDR failed");
  825. goto failed;
  826. }
  827. // try different ports
  828. for (int i = 0; i < options.local_udp_num_ports; i++) {
  829. // skip inappropriate ports
  830. if (port_usage[i]) {
  831. continue;
  832. }
  833. BAddr bind_addr = local_udp_addr;
  834. BAddr_SetPort(&bind_addr, hton16(ntoh16(BAddr_GetPort(&bind_addr)) + (uint16_t)i));
  835. if (BDatagram_Bind(&con->udp_dgram, bind_addr)) {
  836. // remember which port we're using
  837. con->local_port_index = i;
  838. goto cont;
  839. }
  840. }
  841. // try closing an unused connection with the same remote addr
  842. if (!least_con) {
  843. goto failed;
  844. }
  845. ASSERT(least_con->local_port_index >= 0)
  846. ASSERT(least_con->local_port_index < options.local_udp_num_ports)
  847. ASSERT(!PacketPassFairQueueFlow_IsBusy(&least_con->send_qflow))
  848. int i = least_con->local_port_index;
  849. BLog(BLOG_INFO, "closing connection for its remote address");
  850. // close the offending connection
  851. connection_close(least_con);
  852. // try binding to its port
  853. BAddr bind_addr = local_udp_addr;
  854. BAddr_SetPort(&bind_addr, hton16(ntoh16(BAddr_GetPort(&bind_addr)) + (uint16_t)i));
  855. if (BDatagram_Bind(&con->udp_dgram, bind_addr)) {
  856. // remember which port we're using
  857. con->local_port_index = i;
  858. goto cont;
  859. }
  860. failed:
  861. client_log(client, BLOG_WARNING, "failed to bind to any local address; proceeding regardless");
  862. cont:;
  863. BFree(port_usage);
  864. }
  865. // set UDP dgram send address
  866. BIPAddr ipaddr;
  867. BIPAddr_InitInvalid(&ipaddr);
  868. BDatagram_SetSendAddrs(&con->udp_dgram, addr, ipaddr);
  869. // init UDP dgram interfaces
  870. BDatagram_SendAsync_Init(&con->udp_dgram, options.udp_mtu);
  871. BDatagram_RecvAsync_Init(&con->udp_dgram, options.udp_mtu);
  872. // init UDP writer
  873. BufferWriter_Init(&con->udp_send_writer, options.udp_mtu, BReactor_PendingGroup(&ss));
  874. // init UDP buffer
  875. 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))) {
  876. client_log(client, BLOG_ERROR, "PacketBuffer_Init failed");
  877. goto fail4;
  878. }
  879. // init UDP recv interface
  880. PacketPassInterface_Init(&con->udp_recv_if, options.udp_mtu, (PacketPassInterface_handler_send)connection_udp_recv_if_handler_send, con, BReactor_PendingGroup(&ss));
  881. // init UDP recv buffer
  882. if (!SinglePacketBuffer_Init(&con->udp_recv_buffer, BDatagram_RecvAsync_GetIf(&con->udp_dgram), &con->udp_recv_if, BReactor_PendingGroup(&ss))) {
  883. client_log(client, BLOG_ERROR, "SinglePacketBuffer_Init failed");
  884. goto fail5;
  885. }
  886. // insert to client's connections tree
  887. ASSERT_EXECUTE(BAVL_Insert(&client->connections_tree, &con->connections_tree_node, NULL))
  888. // insert to client's connections list
  889. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  890. // increment number of connections
  891. client->num_connections++;
  892. connection_log(con, BLOG_DEBUG, "initialized");
  893. return;
  894. fail5:
  895. PacketPassInterface_Free(&con->udp_recv_if);
  896. PacketBuffer_Free(&con->udp_send_buffer);
  897. fail4:
  898. BufferWriter_Free(&con->udp_send_writer);
  899. BDatagram_RecvAsync_Free(&con->udp_dgram);
  900. BDatagram_SendAsync_Free(&con->udp_dgram);
  901. BDatagram_Free(&con->udp_dgram);
  902. fail2:
  903. PacketProtoFlow_Free(&con->send_ppflow);
  904. fail1:
  905. PacketPassFairQueueFlow_Free(&con->send_qflow);
  906. BPending_Free(&con->first_job);
  907. free(con);
  908. fail0:
  909. return;
  910. }
  911. void connection_free (struct connection *con)
  912. {
  913. struct client *client = con->client;
  914. PacketPassFairQueueFlow_AssertFree(&con->send_qflow);
  915. if (con->closing) {
  916. // remove from client's closing connections list
  917. LinkedList1_Remove(&client->closing_connections_list, &con->closing_connections_list_node);
  918. } else {
  919. // decrement number of connections
  920. client->num_connections--;
  921. // remove from client's connections list
  922. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  923. // remove from client's connections tree
  924. BAVL_Remove(&client->connections_tree, &con->connections_tree_node);
  925. // free UDP
  926. connection_free_udp(con);
  927. }
  928. // free send PacketProtoFlow
  929. PacketProtoFlow_Free(&con->send_ppflow);
  930. // free send queue flow
  931. PacketPassFairQueueFlow_Free(&con->send_qflow);
  932. // free first job
  933. BPending_Free(&con->first_job);
  934. // free structure
  935. free(con);
  936. }
  937. void connection_logfunc (struct connection *con)
  938. {
  939. client_logfunc(con->client);
  940. if (con->closing) {
  941. BLog_Append("old connection %"PRIu16": ", con->conid);
  942. } else {
  943. BLog_Append("connection %"PRIu16": ", con->conid);
  944. }
  945. }
  946. void connection_log (struct connection *con, int level, const char *fmt, ...)
  947. {
  948. va_list vl;
  949. va_start(vl, fmt);
  950. BLog_LogViaFuncVarArg((BLog_logfunc)connection_logfunc, con, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  951. va_end(vl);
  952. }
  953. void connection_free_udp (struct connection *con)
  954. {
  955. // free UDP receive buffer
  956. SinglePacketBuffer_Free(&con->udp_recv_buffer);
  957. // free UDP receive interface
  958. PacketPassInterface_Free(&con->udp_recv_if);
  959. // free UDP buffer
  960. PacketBuffer_Free(&con->udp_send_buffer);
  961. // free UDP writer
  962. BufferWriter_Free(&con->udp_send_writer);
  963. // free UDP dgram interfaces
  964. BDatagram_RecvAsync_Free(&con->udp_dgram);
  965. BDatagram_SendAsync_Free(&con->udp_dgram);
  966. // free UDP dgram
  967. BDatagram_Free(&con->udp_dgram);
  968. }
  969. void connection_first_job_handler (struct connection *con)
  970. {
  971. ASSERT(!con->closing)
  972. connection_send_to_udp(con, con->first_data, con->first_data_len);
  973. }
  974. int connection_send_to_client (struct connection *con, uint8_t flags, const uint8_t *data, int data_len)
  975. {
  976. ASSERT(data_len >= 0)
  977. ASSERT(data_len <= options.udp_mtu)
  978. // get buffer location
  979. uint8_t *out;
  980. if (!BufferWriter_StartPacket(con->send_if, &out)) {
  981. connection_log(con, BLOG_ERROR, "out of client buffer");
  982. return 0;
  983. }
  984. // write header
  985. struct udpgw_header *header = (struct udpgw_header *)out;
  986. header->flags = htol8(flags);
  987. header->conid = htol16(con->conid);
  988. header->addr_ip = con->addr.ipv4.ip;
  989. header->addr_port = con->addr.ipv4.port;
  990. // write message
  991. memcpy(out + sizeof(*header), data, data_len);
  992. // submit written message
  993. BufferWriter_EndPacket(con->send_if, sizeof(*header) + data_len);
  994. return 1;
  995. }
  996. int connection_send_to_udp (struct connection *con, const uint8_t *data, int data_len)
  997. {
  998. struct client *client = con->client;
  999. ASSERT(!con->closing)
  1000. ASSERT(data_len >= 0)
  1001. ASSERT(data_len <= options.udp_mtu)
  1002. connection_log(con, BLOG_DEBUG, "from client %d bytes", data_len);
  1003. // set last use time
  1004. con->last_use_time = btime_gettime();
  1005. // move connection to front
  1006. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1007. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  1008. // get buffer location
  1009. uint8_t *out;
  1010. if (!BufferWriter_StartPacket(&con->udp_send_writer, &out)) {
  1011. connection_log(con, BLOG_ERROR, "out of UDP buffer");
  1012. return 0;
  1013. }
  1014. // write message
  1015. memcpy(out, data, data_len);
  1016. // submit written message
  1017. BufferWriter_EndPacket(&con->udp_send_writer, data_len);
  1018. return 1;
  1019. }
  1020. void connection_close (struct connection *con)
  1021. {
  1022. struct client *client = con->client;
  1023. ASSERT(!con->closing)
  1024. // if possible, free connection immediately
  1025. if (!PacketPassFairQueueFlow_IsBusy(&con->send_qflow)) {
  1026. connection_free(con);
  1027. return;
  1028. }
  1029. connection_log(con, BLOG_DEBUG, "closing later");
  1030. // decrement number of connections
  1031. client->num_connections--;
  1032. // remove from client's connections list
  1033. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1034. // remove from client's connections tree
  1035. BAVL_Remove(&client->connections_tree, &con->connections_tree_node);
  1036. // free UDP
  1037. connection_free_udp(con);
  1038. // insert to client's closing connections list
  1039. LinkedList1_Append(&client->closing_connections_list, &con->closing_connections_list_node);
  1040. // set busy handler
  1041. PacketPassFairQueueFlow_SetBusyHandler(&con->send_qflow, (PacketPassFairQueue_handler_busy)connection_send_qflow_busy_handler, con);
  1042. // unset first job
  1043. BPending_Unset(&con->first_job);
  1044. // set closing
  1045. con->closing = 1;
  1046. }
  1047. void connection_send_qflow_busy_handler (struct connection *con)
  1048. {
  1049. ASSERT(con->closing)
  1050. PacketPassFairQueueFlow_AssertFree(&con->send_qflow);
  1051. connection_log(con, BLOG_DEBUG, "closing finally");
  1052. // free connection
  1053. connection_free(con);
  1054. }
  1055. void connection_dgram_handler_event (struct connection *con, int event)
  1056. {
  1057. ASSERT(!con->closing)
  1058. connection_log(con, BLOG_INFO, "UDP error");
  1059. // close connection
  1060. connection_close(con);
  1061. }
  1062. void connection_udp_recv_if_handler_send (struct connection *con, uint8_t *data, int data_len)
  1063. {
  1064. struct client *client = con->client;
  1065. ASSERT(!con->closing)
  1066. ASSERT(data_len >= 0)
  1067. ASSERT(data_len <= options.udp_mtu)
  1068. connection_log(con, BLOG_DEBUG, "from UDP %d bytes", data_len);
  1069. // set last use time
  1070. con->last_use_time = btime_gettime();
  1071. // move connection to front
  1072. LinkedList1_Remove(&client->connections_list, &con->connections_list_node);
  1073. LinkedList1_Append(&client->connections_list, &con->connections_list_node);
  1074. // accept packet
  1075. PacketPassInterface_Done(&con->udp_recv_if);
  1076. // send packet to client
  1077. connection_send_to_client(con, 0, data, data_len);
  1078. }
  1079. struct connection * find_connection (struct client *client, uint16_t conid)
  1080. {
  1081. BAVLNode *tree_node = BAVL_LookupExact(&client->connections_tree, &conid);
  1082. if (!tree_node) {
  1083. return NULL;
  1084. }
  1085. struct connection *con = UPPER_OBJECT(tree_node, struct connection, connections_tree_node);
  1086. ASSERT(con->conid == conid)
  1087. ASSERT(!con->closing)
  1088. return con;
  1089. }
  1090. int uint16_comparator (void *unused, uint16_t *v1, uint16_t *v2)
  1091. {
  1092. return B_COMPARE(*v1, *v2);
  1093. }