udpgw.c 34 KB

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