udpgw.c 34 KB

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