dostest-server.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /**
  2. * @file dostest-server.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. #ifdef BADVPN_LINUX
  34. #include <sys/types.h>
  35. #include <sys/socket.h>
  36. #endif
  37. #include <misc/debug.h>
  38. #include <misc/version.h>
  39. #include <misc/offset.h>
  40. #include <misc/open_standard_streams.h>
  41. #include <misc/balloc.h>
  42. #include <misc/loglevel.h>
  43. #include <structure/LinkedList1.h>
  44. #include <base/BLog.h>
  45. #include <system/BAddr.h>
  46. #include <system/BReactor.h>
  47. #include <system/BNetwork.h>
  48. #include <system/BConnection.h>
  49. #include <system/BSignal.h>
  50. #include "StreamBuffer.h"
  51. #include <generated/blog_channel_dostest_server.h>
  52. #define PROGRAM_NAME "dostest-server"
  53. #ifdef BADVPN_LINUX
  54. #ifndef SO_DOSDEF_PREPARE
  55. #define SO_DOSDEF_PREPARE 48
  56. #endif
  57. #ifndef SO_DOSDEF_ACTIVATE
  58. #define SO_DOSDEF_ACTIVATE 49
  59. #endif
  60. #endif
  61. #define BUF_SIZE 1024
  62. // client structure
  63. struct client {
  64. BConnection con;
  65. BAddr addr;
  66. StreamBuffer buf;
  67. BTimer disconnect_timer;
  68. LinkedList1Node clients_list_node;
  69. };
  70. // command-line options
  71. static struct {
  72. int help;
  73. int version;
  74. char *listen_addr;
  75. int max_clients;
  76. int disconnect_time;
  77. int defense_prepare_clients;
  78. int defense_activate_clients;
  79. int loglevel;
  80. int loglevels[BLOG_NUM_CHANNELS];
  81. } options;
  82. // listen address
  83. static BAddr listen_addr;
  84. // reactor
  85. static BReactor ss;
  86. // listener
  87. static BListener listener;
  88. // clients
  89. static LinkedList1 clients_list;
  90. static int num_clients;
  91. // defense status
  92. static int defense_prepare;
  93. static int defense_activate;
  94. static void print_help (const char *name);
  95. static void print_version (void);
  96. static int parse_arguments (int argc, char *argv[]);
  97. static int process_arguments (void);
  98. static void signal_handler (void *unused);
  99. static void listener_handler (void *unused);
  100. static void client_free (struct client *client);
  101. static void client_logfunc (struct client *client);
  102. static void client_log (struct client *client, int level, const char *fmt, ...);
  103. static void client_disconnect_timer_handler (struct client *client);
  104. static void client_connection_handler (struct client *client, int event);
  105. static void update_defense (void);
  106. int main (int argc, char **argv)
  107. {
  108. if (argc <= 0) {
  109. return 1;
  110. }
  111. // open standard streams
  112. open_standard_streams();
  113. // parse command-line arguments
  114. if (!parse_arguments(argc, argv)) {
  115. fprintf(stderr, "Failed to parse arguments\n");
  116. print_help(argv[0]);
  117. goto fail0;
  118. }
  119. // handle --help and --version
  120. if (options.help) {
  121. print_version();
  122. print_help(argv[0]);
  123. return 0;
  124. }
  125. if (options.version) {
  126. print_version();
  127. return 0;
  128. }
  129. // init loger
  130. BLog_InitStderr();
  131. // configure logger channels
  132. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  133. if (options.loglevels[i] >= 0) {
  134. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  135. }
  136. else if (options.loglevel >= 0) {
  137. BLog_SetChannelLoglevel(i, options.loglevel);
  138. }
  139. }
  140. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  141. // initialize network
  142. if (!BNetwork_GlobalInit()) {
  143. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  144. goto fail1;
  145. }
  146. // process arguments
  147. if (!process_arguments()) {
  148. BLog(BLOG_ERROR, "Failed to process arguments");
  149. goto fail1;
  150. }
  151. // init time
  152. BTime_Init();
  153. // init reactor
  154. if (!BReactor_Init(&ss)) {
  155. BLog(BLOG_ERROR, "BReactor_Init failed");
  156. goto fail1;
  157. }
  158. // setup signal handler
  159. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  160. BLog(BLOG_ERROR, "BSignal_Init failed");
  161. goto fail2;
  162. }
  163. // initialize listener
  164. if (!BListener_Init(&listener, listen_addr, &ss, NULL, listener_handler)) {
  165. BLog(BLOG_ERROR, "Listener_Init failed");
  166. goto fail3;
  167. }
  168. // init clients list
  169. LinkedList1_Init(&clients_list);
  170. num_clients = 0;
  171. // clear defense state
  172. defense_prepare = 0;
  173. defense_activate = 0;
  174. // update defense
  175. update_defense();
  176. // enter event loop
  177. BLog(BLOG_NOTICE, "entering event loop");
  178. BReactor_Exec(&ss);
  179. // free clients
  180. while (!LinkedList1_IsEmpty(&clients_list)) {
  181. struct client *client = UPPER_OBJECT(LinkedList1_GetFirst(&clients_list), struct client, clients_list_node);
  182. client_free(client);
  183. }
  184. // free listener
  185. BListener_Free(&listener);
  186. fail3:
  187. // free signal
  188. BSignal_Finish();
  189. fail2:
  190. // free reactor
  191. BReactor_Free(&ss);
  192. fail1:
  193. // free logger
  194. BLog(BLOG_NOTICE, "exiting");
  195. BLog_Free();
  196. fail0:
  197. // finish debug objects
  198. DebugObjectGlobal_Finish();
  199. return 1;
  200. }
  201. void print_help (const char *name)
  202. {
  203. printf(
  204. "Usage:\n"
  205. " %s\n"
  206. " [--help]\n"
  207. " [--version]\n"
  208. " --listen-addr <addr>\n"
  209. " --max-clients <number>\n"
  210. " --disconnect-time <milliseconds>\n"
  211. " [--defense-prepare-clients <number>]\n"
  212. " [--defense-activate-clients <number>]\n"
  213. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  214. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  215. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  216. name
  217. );
  218. }
  219. void print_version (void)
  220. {
  221. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  222. }
  223. int parse_arguments (int argc, char *argv[])
  224. {
  225. options.help = 0;
  226. options.version = 0;
  227. options.listen_addr = NULL;
  228. options.max_clients = -1;
  229. options.disconnect_time = -1;
  230. options.defense_prepare_clients = -1;
  231. options.defense_activate_clients = -1;
  232. options.loglevel = -1;
  233. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  234. options.loglevels[i] = -1;
  235. }
  236. int i;
  237. for (i = 1; i < argc; i++) {
  238. char *arg = argv[i];
  239. if (!strcmp(arg, "--help")) {
  240. options.help = 1;
  241. }
  242. else if (!strcmp(arg, "--version")) {
  243. options.version = 1;
  244. }
  245. else if (!strcmp(arg, "--listen-addr")) {
  246. if (1 >= argc - i) {
  247. fprintf(stderr, "%s: requires an argument\n", arg);
  248. return 0;
  249. }
  250. options.listen_addr = argv[i + 1];
  251. i++;
  252. }
  253. else if (!strcmp(arg, "--max-clients")) {
  254. if (1 >= argc - i) {
  255. fprintf(stderr, "%s: requires an argument\n", arg);
  256. return 0;
  257. }
  258. if ((options.max_clients = atoi(argv[i + 1])) <= 0) {
  259. fprintf(stderr, "%s: wrong argument\n", arg);
  260. return 0;
  261. }
  262. i++;
  263. }
  264. else if (!strcmp(arg, "--disconnect-time")) {
  265. if (1 >= argc - i) {
  266. fprintf(stderr, "%s: requires an argument\n", arg);
  267. return 0;
  268. }
  269. if ((options.disconnect_time = atoi(argv[i + 1])) <= 0) {
  270. fprintf(stderr, "%s: wrong argument\n", arg);
  271. return 0;
  272. }
  273. i++;
  274. }
  275. else if (!strcmp(arg, "--defense-prepare-clients")) {
  276. if (1 >= argc - i) {
  277. fprintf(stderr, "%s: requires an argument\n", arg);
  278. return 0;
  279. }
  280. if ((options.defense_prepare_clients = atoi(argv[i + 1])) <= 0) {
  281. fprintf(stderr, "%s: wrong argument\n", arg);
  282. return 0;
  283. }
  284. i++;
  285. }
  286. else if (!strcmp(arg, "--defense-activate-clients")) {
  287. if (1 >= argc - i) {
  288. fprintf(stderr, "%s: requires an argument\n", arg);
  289. return 0;
  290. }
  291. if ((options.defense_activate_clients = atoi(argv[i + 1])) <= 0) {
  292. fprintf(stderr, "%s: wrong argument\n", arg);
  293. return 0;
  294. }
  295. i++;
  296. }
  297. else if (!strcmp(arg, "--loglevel")) {
  298. if (1 >= argc - i) {
  299. fprintf(stderr, "%s: requires an argument\n", arg);
  300. return 0;
  301. }
  302. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  303. fprintf(stderr, "%s: wrong argument\n", arg);
  304. return 0;
  305. }
  306. i++;
  307. }
  308. else if (!strcmp(arg, "--channel-loglevel")) {
  309. if (2 >= argc - i) {
  310. fprintf(stderr, "%s: requires two arguments\n", arg);
  311. return 0;
  312. }
  313. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  314. if (channel < 0) {
  315. fprintf(stderr, "%s: wrong channel argument\n", arg);
  316. return 0;
  317. }
  318. int loglevel = parse_loglevel(argv[i + 2]);
  319. if (loglevel < 0) {
  320. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  321. return 0;
  322. }
  323. options.loglevels[channel] = loglevel;
  324. i += 2;
  325. }
  326. else {
  327. fprintf(stderr, "unknown option: %s\n", arg);
  328. return 0;
  329. }
  330. }
  331. if (options.help || options.version) {
  332. return 1;
  333. }
  334. if (!options.listen_addr) {
  335. fprintf(stderr, "--listen-addr missing\n");
  336. return 0;
  337. }
  338. if (options.max_clients == -1) {
  339. fprintf(stderr, "--max-clients missing\n");
  340. return 0;
  341. }
  342. if (options.disconnect_time == -1) {
  343. fprintf(stderr, "--disconnect-time missing\n");
  344. return 0;
  345. }
  346. return 1;
  347. }
  348. int process_arguments (void)
  349. {
  350. // resolve listen address
  351. if (!BAddr_Parse(&listen_addr, options.listen_addr, NULL, 0)) {
  352. BLog(BLOG_ERROR, "listen addr: BAddr_Parse failed");
  353. return 0;
  354. }
  355. return 1;
  356. }
  357. void signal_handler (void *unused)
  358. {
  359. BLog(BLOG_NOTICE, "termination requested");
  360. // exit event loop
  361. BReactor_Quit(&ss, 1);
  362. }
  363. void listener_handler (void *unused)
  364. {
  365. if (num_clients == options.max_clients) {
  366. BLog(BLOG_ERROR, "maximum number of clients reached");
  367. goto fail0;
  368. }
  369. // allocate structure
  370. struct client *client = (struct client *)malloc(sizeof(*client));
  371. if (!client) {
  372. BLog(BLOG_ERROR, "malloc failed");
  373. goto fail0;
  374. }
  375. // accept client
  376. if (!BConnection_Init(&client->con, BConnection_source_listener(&listener, &client->addr), &ss, client, (BConnection_handler)client_connection_handler)) {
  377. BLog(BLOG_ERROR, "BConnection_Init failed");
  378. goto fail1;
  379. }
  380. // init connection interfaces
  381. BConnection_RecvAsync_Init(&client->con);
  382. BConnection_SendAsync_Init(&client->con);
  383. StreamRecvInterface *recv_if = BConnection_RecvAsync_GetIf(&client->con);
  384. StreamPassInterface *send_if = BConnection_SendAsync_GetIf(&client->con);
  385. // init stream buffer (to loop received data back to the client)
  386. if (!StreamBuffer_Init(&client->buf, BUF_SIZE, recv_if, send_if)) {
  387. BLog(BLOG_ERROR, "StreamBuffer_Init failed");
  388. goto fail2;
  389. }
  390. // init disconnect timer
  391. BTimer_Init(&client->disconnect_timer, options.disconnect_time, (BTimer_handler)client_disconnect_timer_handler, client);
  392. BReactor_SetTimer(&ss, &client->disconnect_timer);
  393. // insert to clients list
  394. LinkedList1_Append(&clients_list, &client->clients_list_node);
  395. num_clients++;
  396. client_log(client, BLOG_INFO, "connected");
  397. BLog(BLOG_NOTICE, "%d clients", num_clients);
  398. // update defense
  399. update_defense();
  400. return;
  401. fail2:
  402. BConnection_SendAsync_Free(&client->con);
  403. BConnection_RecvAsync_Free(&client->con);
  404. BConnection_Free(&client->con);
  405. fail1:
  406. free(client);
  407. fail0:
  408. return;
  409. }
  410. void client_free (struct client *client)
  411. {
  412. // remove from clients list
  413. LinkedList1_Remove(&clients_list, &client->clients_list_node);
  414. num_clients--;
  415. // free disconnect timer
  416. BReactor_RemoveTimer(&ss, &client->disconnect_timer);
  417. // free stream buffer
  418. StreamBuffer_Free(&client->buf);
  419. // free connection interfaces
  420. BConnection_SendAsync_Free(&client->con);
  421. BConnection_RecvAsync_Free(&client->con);
  422. // free connection
  423. BConnection_Free(&client->con);
  424. // free structure
  425. free(client);
  426. BLog(BLOG_NOTICE, "%d clients", num_clients);
  427. // update defense
  428. update_defense();
  429. }
  430. void client_logfunc (struct client *client)
  431. {
  432. char addr[BADDR_MAX_PRINT_LEN];
  433. BAddr_Print(&client->addr, addr);
  434. BLog_Append("client (%s): ", addr);
  435. }
  436. void client_log (struct client *client, int level, const char *fmt, ...)
  437. {
  438. va_list vl;
  439. va_start(vl, fmt);
  440. BLog_LogViaFuncVarArg((BLog_logfunc)client_logfunc, client, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  441. va_end(vl);
  442. }
  443. void client_disconnect_timer_handler (struct client *client)
  444. {
  445. client_log(client, BLOG_INFO, "timed out, disconnecting");
  446. // free client
  447. client_free(client);
  448. }
  449. void client_connection_handler (struct client *client, int event)
  450. {
  451. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  452. client_log(client, BLOG_INFO, "client closed");
  453. } else {
  454. client_log(client, BLOG_INFO, "client error");
  455. }
  456. // free client
  457. client_free(client);
  458. }
  459. void update_defense (void)
  460. {
  461. #ifdef BADVPN_LINUX
  462. if (options.defense_prepare_clients != -1) {
  463. int val = num_clients >= options.defense_prepare_clients;
  464. int res = setsockopt(listener.fd, SOL_SOCKET, SO_DOSDEF_PREPARE, &val, sizeof(val));
  465. if (res < 0) {
  466. BLog(BLOG_ERROR, "failed to %s defense preparation", (val ? "enable" : "disable"));
  467. } else {
  468. if (!defense_prepare && val) {
  469. BLog(BLOG_NOTICE, "defense preparation enabled");
  470. }
  471. else if (defense_prepare && !val) {
  472. BLog(BLOG_NOTICE, "defense preparation disabled");
  473. }
  474. }
  475. defense_prepare = val;
  476. }
  477. if (options.defense_activate_clients != -1) {
  478. int val = num_clients >= options.defense_activate_clients;
  479. int res = setsockopt(listener.fd, SOL_SOCKET, SO_DOSDEF_ACTIVATE, &val, sizeof(val));
  480. if (res < 0) {
  481. BLog(BLOG_ERROR, "failed to %s defense activation", (val ? "enable" : "disable"));
  482. } else {
  483. if (!defense_activate && val) {
  484. BLog(BLOG_NOTICE, "defense activation enabled");
  485. }
  486. else if (defense_activate && !val) {
  487. BLog(BLOG_NOTICE, "defense activation disabled");
  488. }
  489. }
  490. defense_activate = val;
  491. }
  492. #endif
  493. }