server.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887
  1. /**
  2. * @file server.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 <stdlib.h>
  24. #include <string.h>
  25. #include <stddef.h>
  26. #include <stdarg.h>
  27. // NSPR and NSS
  28. #include <prinit.h>
  29. #include <prio.h>
  30. #include <prerror.h>
  31. #include <prtypes.h>
  32. #include <nss.h>
  33. #include <ssl.h>
  34. #include <cert.h>
  35. #include <keyhi.h>
  36. #include <secasn1.h>
  37. // BadVPN
  38. #include <misc/version.h>
  39. #include <misc/debug.h>
  40. #include <misc/offset.h>
  41. #include <misc/nsskey.h>
  42. #include <misc/byteorder.h>
  43. #include <misc/loglevel.h>
  44. #include <misc/loggers_string.h>
  45. #include <predicate/BPredicate.h>
  46. #include <base/DebugObject.h>
  47. #include <base/BLog.h>
  48. #include <system/BSignal.h>
  49. #include <system/BTime.h>
  50. #include <system/BNetwork.h>
  51. #include <security/BRandom.h>
  52. #include <nspr_support/DummyPRFileDesc.h>
  53. #ifndef BADVPN_USE_WINAPI
  54. #include <base/BLog_syslog.h>
  55. #endif
  56. #include <server/server.h>
  57. #include <generated/blog_channel_server.h>
  58. #define LOGGER_STDOUT 1
  59. #define LOGGER_SYSLOG 2
  60. // parsed command-line options
  61. struct {
  62. int help;
  63. int version;
  64. int logger;
  65. #ifndef BADVPN_USE_WINAPI
  66. char *logger_syslog_facility;
  67. char *logger_syslog_ident;
  68. #endif
  69. int loglevel;
  70. int loglevels[BLOG_NUM_CHANNELS];
  71. int ssl;
  72. char *nssdb;
  73. char *server_cert_name;
  74. char *listen_addrs[MAX_LISTEN_ADDRS];
  75. int num_listen_addrs;
  76. char *comm_predicate;
  77. char *relay_predicate;
  78. int client_socket_sndbuf;
  79. } options;
  80. // listen addresses
  81. BAddr listen_addrs[MAX_LISTEN_ADDRS];
  82. int num_listen_addrs;
  83. // communication predicate
  84. BPredicate comm_predicate;
  85. // communication predicate functions
  86. BPredicateFunction comm_predicate_func_p1name;
  87. BPredicateFunction comm_predicate_func_p2name;
  88. BPredicateFunction comm_predicate_func_p1addr;
  89. BPredicateFunction comm_predicate_func_p2addr;
  90. // variables when evaluating the predicate, adjusted before every evaluation
  91. const char *comm_predicate_p1name;
  92. const char *comm_predicate_p2name;
  93. BIPAddr comm_predicate_p1addr;
  94. BIPAddr comm_predicate_p2addr;
  95. // relay predicate
  96. BPredicate relay_predicate;
  97. // gateway predicate functions
  98. BPredicateFunction relay_predicate_func_pname;
  99. BPredicateFunction relay_predicate_func_rname;
  100. BPredicateFunction relay_predicate_func_paddr;
  101. BPredicateFunction relay_predicate_func_raddr;
  102. // variables when evaluating the comm_predicate, adjusted before every evaluation
  103. const char *relay_predicate_pname;
  104. const char *relay_predicate_rname;
  105. BIPAddr relay_predicate_paddr;
  106. BIPAddr relay_predicate_raddr;
  107. // i/o system
  108. BReactor ss;
  109. // server certificate if using SSL
  110. CERTCertificate *server_cert;
  111. // server private key if using SSL
  112. SECKEYPrivateKey *server_key;
  113. // model NSPR file descriptor to speed up client initialization
  114. PRFileDesc model_dprfd;
  115. PRFileDesc *model_prfd;
  116. // listeners
  117. BListener listeners[MAX_LISTEN_ADDRS];
  118. int num_listeners;
  119. // number of connected clients
  120. int clients_num;
  121. // ID assigned to last connected client
  122. peerid_t clients_nextid;
  123. // clients list
  124. LinkedList2 clients;
  125. // clients tree (by ID)
  126. BAVL clients_tree;
  127. // prints help text to standard output
  128. static void print_help (const char *name);
  129. // prints program name and version to standard output
  130. static void print_version (void);
  131. // parses the command line
  132. static int parse_arguments (int argc, char *argv[]);
  133. // processes certain command line options
  134. static int process_arguments (void);
  135. // handler for program termination request
  136. static void signal_handler (void *unused);
  137. // listener handler, accepts new clients
  138. static void listener_handler (BListener *listener);
  139. // frees resources used by a client
  140. static void client_dealloc (struct client_data *client);
  141. // initializes the I/O porition of the client
  142. static int client_init_io (struct client_data *client);
  143. // deallocates the I/O portion of the client. Must have no outgoing flows.
  144. static void client_dealloc_io (struct client_data *client);
  145. // removes a client
  146. static void client_remove (struct client_data *client);
  147. // job to finish removal after clients are informed
  148. static void client_dying_job (struct client_data *client);
  149. // passes a message to the logger, prepending about the client
  150. static void client_log (struct client_data *client, int level, const char *fmt, ...);
  151. // client activity timer handler. Removes the client.
  152. static void client_disconnect_timer_handler (struct client_data *client);
  153. // BConnection handler
  154. static void client_connection_handler (struct client_data *client, int event);
  155. // BSSLConnection handler
  156. static void client_sslcon_handler (struct client_data *client, int event);
  157. // decoder handler
  158. static void client_decoder_handler_error (struct client_data *client);
  159. // provides a buffer for sending a control packet to the client
  160. static int client_start_control_packet (struct client_data *client, void **data, int len);
  161. // submits a packet written after client_start_control_packet
  162. static void client_end_control_packet (struct client_data *client, uint8_t id);
  163. // sends a newclient message to a client
  164. static int client_send_newclient (struct client_data *client, struct client_data *nc, int relay_server, int relay_client);
  165. // sends an endclient message to a client
  166. static int client_send_endclient (struct client_data *client, peerid_t end_id);
  167. // handler for packets received from the client
  168. static void client_input_handler_send (struct client_data *client, uint8_t *data, int data_len);
  169. // processes hello packets from clients
  170. static void process_packet_hello (struct client_data *client, uint8_t *data, int data_len);
  171. // processes outmsg packets from clients
  172. static void process_packet_outmsg (struct client_data *client, uint8_t *data, int data_len);
  173. // creates a peer flow
  174. static struct peer_flow * peer_flow_create (struct client_data *src_client, struct client_data *dest_client);
  175. // deallocates a peer flow
  176. static void peer_flow_dealloc (struct peer_flow *flow);
  177. // disconnects the source client from a peer flow
  178. static void peer_flow_disconnect (struct peer_flow *flow);
  179. // provides a buffer for sending a peer-to-peer packet
  180. static int peer_flow_start_packet (struct peer_flow *flow, void **data, int len);
  181. // submits a peer-to-peer packet written after peer_flow_start_packet
  182. static void peer_flow_end_packet (struct peer_flow *flow, uint8_t type);
  183. // handler called by the queue when a peer flow can be freed after its source has gone away
  184. static void peer_flow_handler_canremove (struct peer_flow *flow);
  185. // generates a client ID to be used for a newly connected client
  186. static peerid_t new_client_id (void);
  187. // finds a client by its ID
  188. static struct client_data * find_client_by_id (peerid_t id);
  189. // checks if two clients are allowed to communicate. May depend on the order
  190. // of the clients.
  191. static int clients_allowed (struct client_data *client1, struct client_data *client2);
  192. // communication predicate function p1name
  193. static int comm_predicate_func_p1name_cb (void *user, void **args);
  194. // communication predicate function p2name
  195. static int comm_predicate_func_p2name_cb (void *user, void **args);
  196. // communication predicate function p1addr
  197. static int comm_predicate_func_p1addr_cb (void *user, void **args);
  198. // communication predicate function p2addr
  199. static int comm_predicate_func_p2addr_cb (void *user, void **args);
  200. // checks if relay is allowed for a client through another client
  201. static int relay_allowed (struct client_data *client, struct client_data *relay);
  202. // relay predicate function pname
  203. static int relay_predicate_func_pname_cb (void *user, void **args);
  204. // relay predicate function rname
  205. static int relay_predicate_func_rname_cb (void *user, void **args);
  206. // relay predicate function paddr
  207. static int relay_predicate_func_paddr_cb (void *user, void **args);
  208. // relay predicate function raddr
  209. static int relay_predicate_func_raddr_cb (void *user, void **args);
  210. // comparator for peerid_t used in AVL tree
  211. static int peerid_comparator (void *unused, peerid_t *p1, peerid_t *p2);
  212. static int create_know (struct client_data *from, struct client_data *to, int relay_server, int relay_client);
  213. static void remove_know (struct peer_know *k);
  214. static void know_inform_job_handler (struct peer_know *k);
  215. static void uninform_know (struct peer_know *k);
  216. static void know_uninform_job_handler (struct peer_know *k);
  217. int main (int argc, char *argv[])
  218. {
  219. if (argc <= 0) {
  220. return 1;
  221. }
  222. // parse command-line arguments
  223. if (!parse_arguments(argc, argv)) {
  224. fprintf(stderr, "Failed to parse arguments\n");
  225. print_help(argv[0]);
  226. goto fail0;
  227. }
  228. // handle --help and --version
  229. if (options.help) {
  230. print_version();
  231. print_help(argv[0]);
  232. return 0;
  233. }
  234. if (options.version) {
  235. print_version();
  236. return 0;
  237. }
  238. // initialize logger
  239. switch (options.logger) {
  240. case LOGGER_STDOUT:
  241. BLog_InitStdout();
  242. break;
  243. #ifndef BADVPN_USE_WINAPI
  244. case LOGGER_SYSLOG:
  245. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  246. fprintf(stderr, "Failed to initialize syslog logger\n");
  247. goto fail0;
  248. }
  249. break;
  250. #endif
  251. default:
  252. ASSERT(0);
  253. }
  254. // configure logger channels
  255. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  256. if (options.loglevels[i] >= 0) {
  257. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  258. }
  259. else if (options.loglevel >= 0) {
  260. BLog_SetChannelLoglevel(i, options.loglevel);
  261. }
  262. }
  263. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  264. // initialize network
  265. if (!BNetwork_GlobalInit()) {
  266. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  267. goto fail1;
  268. }
  269. // process arguments
  270. if (!process_arguments()) {
  271. BLog(BLOG_ERROR, "Failed to process arguments");
  272. goto fail1;
  273. }
  274. // init communication predicate
  275. if (options.comm_predicate) {
  276. // init predicate
  277. if (!BPredicate_Init(&comm_predicate, options.comm_predicate)) {
  278. BLog(BLOG_ERROR, "BPredicate_Init failed");
  279. goto fail1;
  280. }
  281. // init functions
  282. BPredicateFunction_Init(&comm_predicate_func_p1name, &comm_predicate, "p1name", (int []){PREDICATE_TYPE_STRING}, 1, comm_predicate_func_p1name_cb, NULL);
  283. BPredicateFunction_Init(&comm_predicate_func_p2name, &comm_predicate, "p2name", (int []){PREDICATE_TYPE_STRING}, 1, comm_predicate_func_p2name_cb, NULL);
  284. BPredicateFunction_Init(&comm_predicate_func_p1addr, &comm_predicate, "p1addr", (int []){PREDICATE_TYPE_STRING}, 1, comm_predicate_func_p1addr_cb, NULL);
  285. BPredicateFunction_Init(&comm_predicate_func_p2addr, &comm_predicate, "p2addr", (int []){PREDICATE_TYPE_STRING}, 1, comm_predicate_func_p2addr_cb, NULL);
  286. }
  287. // init relay predicate
  288. if (options.relay_predicate) {
  289. // init predicate
  290. if (!BPredicate_Init(&relay_predicate, options.relay_predicate)) {
  291. BLog(BLOG_ERROR, "BPredicate_Init failed");
  292. goto fail1_1;
  293. }
  294. // init functions
  295. BPredicateFunction_Init(&relay_predicate_func_pname, &relay_predicate, "pname", (int []){PREDICATE_TYPE_STRING}, 1, relay_predicate_func_pname_cb, NULL);
  296. BPredicateFunction_Init(&relay_predicate_func_rname, &relay_predicate, "rname", (int []){PREDICATE_TYPE_STRING}, 1, relay_predicate_func_rname_cb, NULL);
  297. BPredicateFunction_Init(&relay_predicate_func_paddr, &relay_predicate, "paddr", (int []){PREDICATE_TYPE_STRING}, 1, relay_predicate_func_paddr_cb, NULL);
  298. BPredicateFunction_Init(&relay_predicate_func_raddr, &relay_predicate, "raddr", (int []){PREDICATE_TYPE_STRING}, 1, relay_predicate_func_raddr_cb, NULL);
  299. }
  300. // init time
  301. BTime_Init();
  302. // initialize reactor
  303. if (!BReactor_Init(&ss)) {
  304. BLog(BLOG_ERROR, "BReactor_Init failed");
  305. goto fail2;
  306. }
  307. // setup signal handler
  308. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  309. BLog(BLOG_ERROR, "BSignal_Init failed");
  310. goto fail2a;
  311. }
  312. if (options.ssl) {
  313. // initialize NSPR
  314. PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
  315. // initialize i/o layer types
  316. if (!DummyPRFileDesc_GlobalInit()) {
  317. BLog(BLOG_ERROR, "DummyPRFileDesc_GlobalInit failed");
  318. goto fail3;
  319. }
  320. if (!BSSLConnection_GlobalInit()) {
  321. BLog(BLOG_ERROR, "BSSLConnection_GlobalInit failed");
  322. goto fail3;
  323. }
  324. // initialize NSS
  325. if (NSS_Init(options.nssdb) != SECSuccess) {
  326. BLog(BLOG_ERROR, "NSS_Init failed (%d)", (int)PR_GetError());
  327. goto fail3;
  328. }
  329. if (NSS_SetDomesticPolicy() != SECSuccess) {
  330. BLog(BLOG_ERROR, "NSS_SetDomesticPolicy failed (%d)", (int)PR_GetError());
  331. goto fail4;
  332. }
  333. // initialize server cache
  334. if (SSL_ConfigServerSessionIDCache(0, 0, 0, NULL) != SECSuccess) {
  335. BLog(BLOG_ERROR, "SSL_ConfigServerSessionIDCache failed (%d)", (int)PR_GetError());
  336. goto fail4;
  337. }
  338. // open server certificate and private key
  339. if (!open_nss_cert_and_key(options.server_cert_name, &server_cert, &server_key)) {
  340. BLog(BLOG_ERROR, "Cannot open certificate and key");
  341. goto fail4a;
  342. }
  343. // initialize model SSL fd
  344. DummyPRFileDesc_Create(&model_dprfd);
  345. if (!(model_prfd = SSL_ImportFD(NULL, &model_dprfd))) {
  346. BLog(BLOG_ERROR, "SSL_ImportFD failed");
  347. ASSERT_FORCE(PR_Close(&model_dprfd) == PR_SUCCESS)
  348. goto fail5;
  349. }
  350. // set server certificate
  351. if (SSL_ConfigSecureServer(model_prfd, server_cert, server_key, NSS_FindCertKEAType(server_cert)) != SECSuccess) {
  352. BLog(BLOG_ERROR, "SSL_ConfigSecureServer failed");
  353. goto fail6;
  354. }
  355. }
  356. // initialize number of clients
  357. clients_num = 0;
  358. // first client ID will be zero
  359. clients_nextid = 0;
  360. // initialize clients linked list
  361. LinkedList2_Init(&clients);
  362. // initialize clients tree
  363. BAVL_Init(&clients_tree, OFFSET_DIFF(struct client_data, id, tree_node), (BAVL_comparator)peerid_comparator, NULL);
  364. // initialize listeners
  365. num_listeners = 0;
  366. while (num_listeners < num_listen_addrs) {
  367. if (!BListener_Init(&listeners[num_listeners], listen_addrs[num_listeners], &ss, &listeners[num_listeners], (BListener_handler)listener_handler)) {
  368. BLog(BLOG_ERROR, "BListener_Init failed");
  369. goto fail7;
  370. }
  371. num_listeners++;
  372. }
  373. // enter event loop
  374. BLog(BLOG_NOTICE, "entering event loop");
  375. BReactor_Exec(&ss);
  376. // free clients
  377. LinkedList2Node *node;
  378. while (node = LinkedList2_GetFirst(&clients)) {
  379. struct client_data *client = UPPER_OBJECT(node, struct client_data, list_node);
  380. // remove outgoing knows
  381. LinkedList2Node *node2;
  382. while (node2 = LinkedList2_GetFirst(&client->know_out_list)) {
  383. struct peer_know *k = UPPER_OBJECT(node2, struct peer_know, from_node);
  384. remove_know(k);
  385. }
  386. // remove incoming knows
  387. LinkedList2Node *node3;
  388. while (node3 = LinkedList2_GetFirst(&client->know_in_list)) {
  389. struct peer_know *k = UPPER_OBJECT(node3, struct peer_know, to_node);
  390. remove_know(k);
  391. }
  392. // remove outgoing flows
  393. LinkedList2Node *flow_node;
  394. while (flow_node = LinkedList2_GetFirst(&client->peer_out_flows_list)) {
  395. struct peer_flow *flow = UPPER_OBJECT(flow_node, struct peer_flow, src_list_node);
  396. ASSERT(flow->src_client == client)
  397. // allow freeing queue flows at dest
  398. PacketPassFairQueue_PrepareFree(&flow->dest_client->output_peers_fairqueue);
  399. // deallocate flow
  400. peer_flow_dealloc(flow);
  401. }
  402. // deallocate client
  403. client_dealloc(client);
  404. }
  405. fail7:
  406. while (num_listeners > 0) {
  407. num_listeners--;
  408. BListener_Free(&listeners[num_listeners]);
  409. }
  410. if (options.ssl) {
  411. fail6:
  412. ASSERT_FORCE(PR_Close(model_prfd) == PR_SUCCESS)
  413. fail5:
  414. CERT_DestroyCertificate(server_cert);
  415. SECKEY_DestroyPrivateKey(server_key);
  416. fail4a:
  417. ASSERT_FORCE(SSL_ShutdownServerSessionIDCache() == SECSuccess)
  418. fail4:
  419. ASSERT_FORCE(NSS_Shutdown() == SECSuccess)
  420. fail3:
  421. ASSERT_FORCE(PR_Cleanup() == PR_SUCCESS)
  422. PL_ArenaFinish();
  423. }
  424. BSignal_Finish();
  425. fail2a:
  426. BReactor_Free(&ss);
  427. fail2:
  428. if (options.relay_predicate) {
  429. BPredicateFunction_Free(&relay_predicate_func_raddr);
  430. BPredicateFunction_Free(&relay_predicate_func_paddr);
  431. BPredicateFunction_Free(&relay_predicate_func_rname);
  432. BPredicateFunction_Free(&relay_predicate_func_pname);
  433. BPredicate_Free(&relay_predicate);
  434. }
  435. fail1_1:
  436. if (options.comm_predicate) {
  437. BPredicateFunction_Free(&comm_predicate_func_p2addr);
  438. BPredicateFunction_Free(&comm_predicate_func_p1addr);
  439. BPredicateFunction_Free(&comm_predicate_func_p2name);
  440. BPredicateFunction_Free(&comm_predicate_func_p1name);
  441. BPredicate_Free(&comm_predicate);
  442. }
  443. fail1:
  444. BLog(BLOG_NOTICE, "exiting");
  445. BLog_Free();
  446. fail0:
  447. DebugObjectGlobal_Finish();
  448. return 1;
  449. }
  450. void print_help (const char *name)
  451. {
  452. printf(
  453. "Usage:\n"
  454. " %s\n"
  455. " [--help]\n"
  456. " [--version]\n"
  457. " [--logger <"LOGGERS_STRING">]\n"
  458. #ifndef BADVPN_USE_WINAPI
  459. " (logger=syslog?\n"
  460. " [--syslog-facility <string>]\n"
  461. " [--syslog-ident <string>]\n"
  462. " )\n"
  463. #endif
  464. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  465. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  466. " [--listen-addr <addr>] ...\n"
  467. " [--ssl --nssdb <string> --server-cert-name <string>]\n"
  468. " [--comm-predicate <string>]\n"
  469. " [--relay-predicate <string>]\n"
  470. " [--client-socket-sndbuf <bytes / 0>]\n"
  471. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  472. name
  473. );
  474. }
  475. void print_version (void)
  476. {
  477. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  478. }
  479. int parse_arguments (int argc, char *argv[])
  480. {
  481. options.help = 0;
  482. options.version = 0;
  483. options.logger = LOGGER_STDOUT;
  484. #ifndef BADVPN_USE_WINAPI
  485. options.logger_syslog_facility = "daemon";
  486. options.logger_syslog_ident = argv[0];
  487. #endif
  488. options.loglevel = -1;
  489. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  490. options.loglevels[i] = -1;
  491. }
  492. options.ssl = 0;
  493. options.nssdb = NULL;
  494. options.server_cert_name = NULL;
  495. options.num_listen_addrs = 0;
  496. options.comm_predicate = NULL;
  497. options.relay_predicate = NULL;
  498. options.client_socket_sndbuf = CLIENT_DEFAULT_SOCKET_SNDBUF;
  499. for (int i = 1; i < argc; i++) {
  500. char *arg = argv[i];
  501. if (!strcmp(arg, "--help")) {
  502. options.help = 1;
  503. }
  504. else if (!strcmp(arg, "--version")) {
  505. options.version = 1;
  506. }
  507. else if (!strcmp(arg, "--logger")) {
  508. if (i + 1 >= argc) {
  509. fprintf(stderr, "%s: requires an argument\n", arg);
  510. return 0;
  511. }
  512. char *arg2 = argv[i + 1];
  513. if (!strcmp(arg2, "stdout")) {
  514. options.logger = LOGGER_STDOUT;
  515. }
  516. #ifndef BADVPN_USE_WINAPI
  517. else if (!strcmp(arg2, "syslog")) {
  518. options.logger = LOGGER_SYSLOG;
  519. }
  520. #endif
  521. else {
  522. fprintf(stderr, "%s: wrong argument\n", arg);
  523. return 0;
  524. }
  525. i++;
  526. }
  527. #ifndef BADVPN_USE_WINAPI
  528. else if (!strcmp(arg, "--syslog-facility")) {
  529. if (i + 1 >= argc) {
  530. fprintf(stderr, "%s: requires an argument\n", arg);
  531. return 0;
  532. }
  533. options.logger_syslog_facility = argv[i + 1];
  534. i++;
  535. }
  536. else if (!strcmp(arg, "--syslog-ident")) {
  537. if (i + 1 >= argc) {
  538. fprintf(stderr, "%s: requires an argument\n", arg);
  539. return 0;
  540. }
  541. options.logger_syslog_ident = argv[i + 1];
  542. i++;
  543. }
  544. #endif
  545. else if (!strcmp(arg, "--loglevel")) {
  546. if (1 >= argc - i) {
  547. fprintf(stderr, "%s: requires an argument\n", arg);
  548. return 0;
  549. }
  550. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  551. fprintf(stderr, "%s: wrong argument\n", arg);
  552. return 0;
  553. }
  554. i++;
  555. }
  556. else if (!strcmp(arg, "--channel-loglevel")) {
  557. if (2 >= argc - i) {
  558. fprintf(stderr, "%s: requires two arguments\n", arg);
  559. return 0;
  560. }
  561. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  562. if (channel < 0) {
  563. fprintf(stderr, "%s: wrong channel argument\n", arg);
  564. return 0;
  565. }
  566. int loglevel = parse_loglevel(argv[i + 2]);
  567. if (loglevel < 0) {
  568. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  569. return 0;
  570. }
  571. options.loglevels[channel] = loglevel;
  572. i += 2;
  573. }
  574. else if (!strcmp(arg, "--ssl")) {
  575. options.ssl = 1;
  576. }
  577. else if (!strcmp(arg, "--nssdb")) {
  578. if (1 >= argc - i) {
  579. fprintf(stderr, "%s: requires an argument\n", arg);
  580. return 0;
  581. }
  582. options.nssdb = argv[i + 1];
  583. i++;
  584. }
  585. else if (!strcmp(arg, "--server-cert-name")) {
  586. if (1 >= argc - i) {
  587. fprintf(stderr, "%s: requires an argument\n", arg);
  588. return 0;
  589. }
  590. options.server_cert_name = argv[i + 1];
  591. i++;
  592. }
  593. else if (!strcmp(arg, "--listen-addr")) {
  594. if (1 >= argc - i) {
  595. fprintf(stderr, "%s: requires an argument\n", arg);
  596. return 0;
  597. }
  598. if (options.num_listen_addrs == MAX_LISTEN_ADDRS) {
  599. fprintf(stderr, "%s: too many\n", arg);
  600. return 0;
  601. }
  602. options.listen_addrs[options.num_listen_addrs] = argv[i + 1];
  603. options.num_listen_addrs++;
  604. i++;
  605. }
  606. else if (!strcmp(arg, "--comm-predicate")) {
  607. if (1 >= argc - i) {
  608. fprintf(stderr, "%s: requires an argument\n", arg);
  609. return 0;
  610. }
  611. options.comm_predicate = argv[i + 1];
  612. i++;
  613. }
  614. else if (!strcmp(arg, "--relay-predicate")) {
  615. if (1 >= argc - i) {
  616. fprintf(stderr, "%s: requires an argument\n", arg);
  617. return 0;
  618. }
  619. options.relay_predicate = argv[i + 1];
  620. i++;
  621. }
  622. else if (!strcmp(arg, "--client-socket-sndbuf")) {
  623. if (1 >= argc - i) {
  624. fprintf(stderr, "%s: requires an argument\n", arg);
  625. return 0;
  626. }
  627. if ((options.client_socket_sndbuf = atoi(argv[i + 1])) < 0) {
  628. fprintf(stderr, "%s: wrong argument\n", arg);
  629. return 0;
  630. }
  631. i++;
  632. }
  633. else {
  634. fprintf(stderr, "%s: unknown option\n", arg);
  635. return 0;
  636. }
  637. }
  638. if (options.help || options.version) {
  639. return 1;
  640. }
  641. if (!!options.nssdb != options.ssl) {
  642. fprintf(stderr, "--ssl and --nssdb must be used together\n");
  643. return 0;
  644. }
  645. if (!!options.server_cert_name != options.ssl) {
  646. fprintf(stderr, "--ssl and --server-cert-name must be used together\n");
  647. return 0;
  648. }
  649. return 1;
  650. }
  651. int process_arguments (void)
  652. {
  653. // resolve listen addresses
  654. num_listen_addrs = 0;
  655. while (num_listen_addrs < options.num_listen_addrs) {
  656. if (!BAddr_Parse(&listen_addrs[num_listen_addrs], options.listen_addrs[num_listen_addrs], NULL, 0)) {
  657. BLog(BLOG_ERROR, "listen addr: BAddr_Parse failed");
  658. return 0;
  659. }
  660. num_listen_addrs++;
  661. }
  662. return 1;
  663. }
  664. void signal_handler (void *unused)
  665. {
  666. BLog(BLOG_NOTICE, "termination requested");
  667. // exit event loop
  668. BReactor_Quit(&ss, 0);
  669. }
  670. void listener_handler (BListener *listener)
  671. {
  672. if (clients_num == MAX_CLIENTS) {
  673. BLog(BLOG_WARNING, "too many clients for new client");
  674. goto fail0;
  675. }
  676. // allocate the client structure
  677. struct client_data *client = malloc(sizeof(*client));
  678. if (!client) {
  679. BLog(BLOG_ERROR, "failed to allocate client");
  680. goto fail0;
  681. }
  682. // accept connection
  683. if (!BConnection_Init(&client->con, BCONNECTION_SOURCE_LISTENER(listener, &client->addr), &ss, client, (BConnection_handler)client_connection_handler)) {
  684. BLog(BLOG_ERROR, "BConnection_Init failed");
  685. goto fail1;
  686. }
  687. // limit socket send buffer, else our scheduling is pointless
  688. if (options.client_socket_sndbuf > 0) {
  689. if (!BConnection_SetSendBuffer(&client->con, options.client_socket_sndbuf) < 0) {
  690. BLog(BLOG_WARNING, "BConnection_SetSendBuffer failed");
  691. }
  692. }
  693. // assign ID
  694. client->id = new_client_id();
  695. // set no common name
  696. client->common_name = NULL;
  697. // now client_log() works
  698. // init connection interfaces
  699. BConnection_SendAsync_Init(&client->con);
  700. BConnection_RecvAsync_Init(&client->con);
  701. if (options.ssl) {
  702. // create bottom NSPR file descriptor
  703. if (!BSSLConnection_MakeBackend(&client->bottom_prfd, BConnection_SendAsync_GetIf(&client->con), BConnection_RecvAsync_GetIf(&client->con))) {
  704. client_log(client, BLOG_ERROR, "BSSLConnection_MakeBackend failed");
  705. goto fail2;
  706. }
  707. // create SSL file descriptor from the bottom NSPR file descriptor
  708. if (!(client->ssl_prfd = SSL_ImportFD(model_prfd, &client->bottom_prfd))) {
  709. client_log(client, BLOG_ERROR, "SSL_ImportFD failed");
  710. ASSERT_FORCE(PR_Close(&client->bottom_prfd) == PR_SUCCESS)
  711. goto fail2;
  712. }
  713. // set server mode
  714. if (SSL_ResetHandshake(client->ssl_prfd, PR_TRUE) != SECSuccess) {
  715. client_log(client, BLOG_ERROR, "SSL_ResetHandshake failed");
  716. goto fail3;
  717. }
  718. // set require client certificate
  719. if (SSL_OptionSet(client->ssl_prfd, SSL_REQUEST_CERTIFICATE, PR_TRUE) != SECSuccess) {
  720. client_log(client, BLOG_ERROR, "SSL_OptionSet(SSL_REQUEST_CERTIFICATE) failed");
  721. goto fail3;
  722. }
  723. if (SSL_OptionSet(client->ssl_prfd, SSL_REQUIRE_CERTIFICATE, PR_TRUE) != SECSuccess) {
  724. client_log(client, BLOG_ERROR, "SSL_OptionSet(SSL_REQUIRE_CERTIFICATE) failed");
  725. goto fail3;
  726. }
  727. // init SSL connection
  728. BSSLConnection_Init(&client->sslcon, client->ssl_prfd, 1, &ss, client, (BSSLConnection_handler)client_sslcon_handler);
  729. } else {
  730. // initialize I/O
  731. if (!client_init_io(client)) {
  732. goto fail2;
  733. }
  734. }
  735. // start disconnect timer
  736. BTimer_Init(&client->disconnect_timer, CLIENT_NO_DATA_TIME_LIMIT, (BTimer_handler)client_disconnect_timer_handler, client);
  737. BReactor_SetTimer(&ss, &client->disconnect_timer);
  738. // link in
  739. clients_num++;
  740. LinkedList2_Append(&clients, &client->list_node);
  741. ASSERT_EXECUTE(BAVL_Insert(&clients_tree, &client->tree_node, NULL))
  742. // init knowledge lists
  743. LinkedList2_Init(&client->know_out_list);
  744. LinkedList2_Init(&client->know_in_list);
  745. // initialize peer flows from us list and tree (flows for sending messages to other clients)
  746. LinkedList2_Init(&client->peer_out_flows_list);
  747. BAVL_Init(&client->peer_out_flows_tree, OFFSET_DIFF(struct peer_flow, dest_client_id, src_tree_node), (BAVL_comparator)peerid_comparator, NULL);
  748. // init dying
  749. client->dying = 0;
  750. BPending_Init(&client->dying_job, BReactor_PendingGroup(&ss), (BPending_handler)client_dying_job, client);
  751. // set state
  752. client->initstatus = (options.ssl ? INITSTATUS_HANDSHAKE : INITSTATUS_WAITHELLO);
  753. client_log(client, BLOG_INFO, "initialized");
  754. return;
  755. if (options.ssl) {
  756. fail3:
  757. ASSERT_FORCE(PR_Close(client->ssl_prfd) == PR_SUCCESS)
  758. }
  759. fail2:
  760. BConnection_RecvAsync_Free(&client->con);
  761. BConnection_SendAsync_Free(&client->con);
  762. BConnection_Free(&client->con);
  763. fail1:
  764. free(client);
  765. fail0:
  766. return;
  767. }
  768. void client_dealloc (struct client_data *client)
  769. {
  770. ASSERT(LinkedList2_IsEmpty(&client->know_out_list))
  771. ASSERT(LinkedList2_IsEmpty(&client->know_in_list))
  772. ASSERT(LinkedList2_IsEmpty(&client->peer_out_flows_list))
  773. // free I/O
  774. if (client->initstatus >= INITSTATUS_WAITHELLO && !client->dying) {
  775. client_dealloc_io(client);
  776. }
  777. // free dying
  778. BPending_Free(&client->dying_job);
  779. // link out
  780. BAVL_Remove(&clients_tree, &client->tree_node);
  781. LinkedList2_Remove(&clients, &client->list_node);
  782. clients_num--;
  783. // stop disconnect timer
  784. BReactor_RemoveTimer(&ss, &client->disconnect_timer);
  785. // free SSL
  786. if (options.ssl) {
  787. BSSLConnection_Free(&client->sslcon);
  788. ASSERT_FORCE(PR_Close(client->ssl_prfd) == PR_SUCCESS)
  789. }
  790. // free common name
  791. if (client->common_name) {
  792. PORT_Free(client->common_name);
  793. }
  794. // free connection interfaces
  795. BConnection_RecvAsync_Free(&client->con);
  796. BConnection_SendAsync_Free(&client->con);
  797. // free connection
  798. BConnection_Free(&client->con);
  799. // free memory
  800. free(client);
  801. }
  802. int client_init_io (struct client_data *client)
  803. {
  804. StreamPassInterface *send_if = (options.ssl ? BSSLConnection_GetSendIf(&client->sslcon) : BConnection_SendAsync_GetIf(&client->con));
  805. StreamRecvInterface *recv_if = (options.ssl ? BSSLConnection_GetRecvIf(&client->sslcon) : BConnection_RecvAsync_GetIf(&client->con));
  806. // init input
  807. // init interface
  808. PacketPassInterface_Init(&client->input_interface, SC_MAX_ENC, (PacketPassInterface_handler_send)client_input_handler_send, client, BReactor_PendingGroup(&ss));
  809. // init decoder
  810. if (!PacketProtoDecoder_Init(&client->input_decoder, recv_if, &client->input_interface, BReactor_PendingGroup(&ss), client,
  811. (PacketProtoDecoder_handler_error)client_decoder_handler_error
  812. )) {
  813. client_log(client, BLOG_ERROR, "PacketProtoDecoder_Init failed");
  814. goto fail1;
  815. }
  816. // init output common
  817. // init sender
  818. PacketStreamSender_Init(&client->output_sender, send_if, PACKETPROTO_ENCLEN(SC_MAX_ENC), BReactor_PendingGroup(&ss));
  819. // init queue
  820. PacketPassPriorityQueue_Init(&client->output_priorityqueue, PacketStreamSender_GetInput(&client->output_sender), BReactor_PendingGroup(&ss), 0);
  821. // init output control flow
  822. // init queue flow
  823. PacketPassPriorityQueueFlow_Init(&client->output_control_qflow, &client->output_priorityqueue, -1);
  824. // init PacketProtoFlow
  825. if (!PacketProtoFlow_Init(
  826. &client->output_control_oflow, SC_MAX_ENC, CLIENT_CONTROL_BUFFER_MIN_PACKETS,
  827. PacketPassPriorityQueueFlow_GetInput(&client->output_control_qflow), BReactor_PendingGroup(&ss)
  828. )) {
  829. client_log(client, BLOG_ERROR, "PacketProtoFlow_Init failed");
  830. goto fail2;
  831. }
  832. client->output_control_input = PacketProtoFlow_GetInput(&client->output_control_oflow);
  833. client->output_control_packet_len = -1;
  834. // init output peers flow
  835. // init queue flow
  836. // use lower priority than control flow (higher number)
  837. PacketPassPriorityQueueFlow_Init(&client->output_peers_qflow, &client->output_priorityqueue, 0);
  838. // init fair queue (for different peers)
  839. PacketPassFairQueue_Init(&client->output_peers_fairqueue, PacketPassPriorityQueueFlow_GetInput(&client->output_peers_qflow), BReactor_PendingGroup(&ss), 0, 1);
  840. // init list of flows
  841. LinkedList2_Init(&client->output_peers_flows);
  842. return 1;
  843. fail2:
  844. PacketPassPriorityQueueFlow_Free(&client->output_control_qflow);
  845. // free output common
  846. PacketPassPriorityQueue_Free(&client->output_priorityqueue);
  847. PacketStreamSender_Free(&client->output_sender);
  848. // free input
  849. PacketProtoDecoder_Free(&client->input_decoder);
  850. fail1:
  851. PacketPassInterface_Free(&client->input_interface);
  852. return 0;
  853. }
  854. void client_dealloc_io (struct client_data *client)
  855. {
  856. // allow freeing fair queue flows
  857. PacketPassFairQueue_PrepareFree(&client->output_peers_fairqueue);
  858. // remove flows to us
  859. LinkedList2Node *node;
  860. while (node = LinkedList2_GetFirst(&client->output_peers_flows)) {
  861. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, dest_list_node);
  862. ASSERT(flow->dest_client == client)
  863. peer_flow_dealloc(flow);
  864. }
  865. // allow freeing priority queue flows
  866. PacketPassPriorityQueue_PrepareFree(&client->output_priorityqueue);
  867. // free output peers flow
  868. PacketPassFairQueue_Free(&client->output_peers_fairqueue);
  869. PacketPassPriorityQueueFlow_Free(&client->output_peers_qflow);
  870. // free output control flow
  871. PacketProtoFlow_Free(&client->output_control_oflow);
  872. PacketPassPriorityQueueFlow_Free(&client->output_control_qflow);
  873. // free output common
  874. PacketPassPriorityQueue_Free(&client->output_priorityqueue);
  875. PacketStreamSender_Free(&client->output_sender);
  876. // free input
  877. PacketProtoDecoder_Free(&client->input_decoder);
  878. PacketPassInterface_Free(&client->input_interface);
  879. }
  880. void client_remove (struct client_data *client)
  881. {
  882. ASSERT(!client->dying)
  883. client_log(client, BLOG_INFO, "removing");
  884. // set dying to prevent sending this client anything
  885. client->dying = 1;
  886. // free I/O now, removing incoming flows
  887. if (client->initstatus >= INITSTATUS_WAITHELLO) {
  888. client_dealloc_io(client);
  889. }
  890. // remove outgoing knows
  891. LinkedList2Node *node;
  892. while (node = LinkedList2_GetFirst(&client->know_out_list)) {
  893. struct peer_know *k = UPPER_OBJECT(node, struct peer_know, from_node);
  894. remove_know(k);
  895. }
  896. // remove outgoing flows
  897. while (node = LinkedList2_GetFirst(&client->peer_out_flows_list)) {
  898. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, src_list_node);
  899. ASSERT(flow->src_client == client)
  900. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  901. ASSERT(!flow->dest_client->dying)
  902. if (PacketPassFairQueueFlow_IsBusy(&flow->qflow)) {
  903. client_log(client, BLOG_DEBUG, "removing flow to %d later", (int)flow->dest_client->id);
  904. peer_flow_disconnect(flow);
  905. PacketPassFairQueueFlow_SetBusyHandler(&flow->qflow, (PacketPassFairQueue_handler_busy)peer_flow_handler_canremove, flow);
  906. } else {
  907. client_log(client, BLOG_DEBUG, "removing flow to %d now", (int)flow->dest_client->id);
  908. peer_flow_dealloc(flow);
  909. }
  910. }
  911. // schedule job to finish removal after clients are informed
  912. BPending_Set(&client->dying_job);
  913. // inform other clients that 'client' is no more
  914. LinkedList2Iterator it;
  915. LinkedList2Iterator_InitForward(&it, &client->know_in_list);
  916. while (node = LinkedList2Iterator_Next(&it)) {
  917. struct peer_know *k = UPPER_OBJECT(node, struct peer_know, to_node);
  918. uninform_know(k);
  919. }
  920. }
  921. void client_dying_job (struct client_data *client)
  922. {
  923. ASSERT(client->dying)
  924. ASSERT(LinkedList2_IsEmpty(&client->know_in_list))
  925. client_dealloc(client);
  926. return;
  927. }
  928. void client_log (struct client_data *client, int level, const char *fmt, ...)
  929. {
  930. va_list vl;
  931. va_start(vl, fmt);
  932. char addr[BADDR_MAX_PRINT_LEN];
  933. BAddr_Print(&client->addr, addr);
  934. BLog_Append("client %d (%s)", (int)client->id, addr);
  935. if (client->common_name) {
  936. BLog_Append(" (%s)", client->common_name);
  937. }
  938. BLog_Append(": ");
  939. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  940. va_end(vl);
  941. }
  942. void client_disconnect_timer_handler (struct client_data *client)
  943. {
  944. ASSERT(!client->dying)
  945. client_log(client, BLOG_INFO, "timed out");
  946. client_remove(client);
  947. return;
  948. }
  949. void client_connection_handler (struct client_data *client, int event)
  950. {
  951. ASSERT(!client->dying)
  952. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  953. client_log(client, BLOG_INFO, "connection closed");
  954. } else {
  955. client_log(client, BLOG_INFO, "connection error");
  956. }
  957. client_remove(client);
  958. return;
  959. }
  960. void client_sslcon_handler (struct client_data *client, int event)
  961. {
  962. ASSERT(options.ssl)
  963. ASSERT(!client->dying)
  964. ASSERT(event == BSSLCONNECTION_EVENT_UP || event == BSSLCONNECTION_EVENT_ERROR)
  965. ASSERT(!(event == BSSLCONNECTION_EVENT_UP) || client->initstatus == INITSTATUS_HANDSHAKE)
  966. if (event == BSSLCONNECTION_EVENT_ERROR) {
  967. client_log(client, BLOG_ERROR, "SSL error");
  968. client_remove(client);
  969. return;
  970. }
  971. // get client certificate
  972. CERTCertificate *cert = SSL_PeerCertificate(client->ssl_prfd);
  973. if (!cert) {
  974. client_log(client, BLOG_ERROR, "SSL_PeerCertificate failed");
  975. goto fail0;
  976. }
  977. // remember common name
  978. if (!(client->common_name = CERT_GetCommonName(&cert->subject))) {
  979. client_log(client, BLOG_NOTICE, "CERT_GetCommonName failed");
  980. goto fail1;
  981. }
  982. // store certificate
  983. SECItem der = cert->derCert;
  984. if (der.len > sizeof(client->cert)) {
  985. client_log(client, BLOG_NOTICE, "client certificate too big");
  986. goto fail1;
  987. }
  988. memcpy(client->cert, der.data, der.len);
  989. client->cert_len = der.len;
  990. PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  991. if (!arena) {
  992. client_log(client, BLOG_ERROR, "PORT_NewArena failed");
  993. goto fail1;
  994. }
  995. // encode certificate
  996. memset(&der, 0, sizeof(der));
  997. if (!SEC_ASN1EncodeItem(arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate))) {
  998. client_log(client, BLOG_ERROR, "SEC_ASN1EncodeItem failed");
  999. goto fail2;
  1000. }
  1001. // store re-encoded certificate (for compatibility with old clients)
  1002. if (der.len > sizeof(client->cert_old)) {
  1003. client_log(client, BLOG_NOTICE, "client certificate too big");
  1004. goto fail2;
  1005. }
  1006. memcpy(client->cert_old, der.data, der.len);
  1007. client->cert_old_len = der.len;
  1008. // init I/O chains
  1009. if (!client_init_io(client)) {
  1010. goto fail2;
  1011. }
  1012. PORT_FreeArena(arena, PR_FALSE);
  1013. CERT_DestroyCertificate(cert);
  1014. // set client state
  1015. client->initstatus = INITSTATUS_WAITHELLO;
  1016. client_log(client, BLOG_INFO, "handshake complete");
  1017. return;
  1018. // handle errors
  1019. fail2:
  1020. PORT_FreeArena(arena, PR_FALSE);
  1021. fail1:
  1022. CERT_DestroyCertificate(cert);
  1023. fail0:
  1024. client_remove(client);
  1025. }
  1026. void client_decoder_handler_error (struct client_data *client)
  1027. {
  1028. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1029. ASSERT(!client->dying)
  1030. client_log(client, BLOG_ERROR, "decoder error");
  1031. client_remove(client);
  1032. return;
  1033. }
  1034. int client_start_control_packet (struct client_data *client, void **data, int len)
  1035. {
  1036. ASSERT(len >= 0)
  1037. ASSERT(len <= SC_MAX_PAYLOAD)
  1038. ASSERT(!(len > 0) || data)
  1039. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1040. ASSERT(!client->dying)
  1041. ASSERT(client->output_control_packet_len == -1)
  1042. // obtain location for writing the packet
  1043. if (!BufferWriter_StartPacket(client->output_control_input, &client->output_control_packet)) {
  1044. // out of buffer, kill client
  1045. client_log(client, BLOG_INFO, "out of control buffer, removing");
  1046. client_remove(client);
  1047. return -1;
  1048. }
  1049. client->output_control_packet_len = len;
  1050. if (data) {
  1051. *data = client->output_control_packet + sizeof(struct sc_header);
  1052. }
  1053. return 0;
  1054. }
  1055. void client_end_control_packet (struct client_data *client, uint8_t type)
  1056. {
  1057. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1058. ASSERT(!client->dying)
  1059. ASSERT(client->output_control_packet_len >= 0)
  1060. ASSERT(client->output_control_packet_len <= SC_MAX_PAYLOAD)
  1061. // write header
  1062. struct sc_header *header = (struct sc_header *)client->output_control_packet;
  1063. header->type = htol8(type);
  1064. // finish writing packet
  1065. BufferWriter_EndPacket(client->output_control_input, sizeof(struct sc_header) + client->output_control_packet_len);
  1066. client->output_control_packet_len = -1;
  1067. }
  1068. int client_send_newclient (struct client_data *client, struct client_data *nc, int relay_server, int relay_client)
  1069. {
  1070. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1071. ASSERT(!client->dying)
  1072. ASSERT(nc->initstatus == INITSTATUS_COMPLETE)
  1073. ASSERT(!nc->dying)
  1074. int flags = 0;
  1075. if (relay_server) {
  1076. flags |= SCID_NEWCLIENT_FLAG_RELAY_SERVER;
  1077. }
  1078. if (relay_client) {
  1079. flags |= SCID_NEWCLIENT_FLAG_RELAY_CLIENT;
  1080. }
  1081. uint8_t *cert_data = NULL;
  1082. int cert_len = 0;
  1083. if (options.ssl) {
  1084. cert_data = (client->version == SC_OLDVERSION ? nc->cert_old : nc->cert);
  1085. cert_len = (client->version == SC_OLDVERSION ? nc->cert_old_len : nc->cert_len);
  1086. }
  1087. struct sc_server_newclient *pack;
  1088. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_newclient) + cert_len) < 0) {
  1089. return -1;
  1090. }
  1091. pack->id = htol16(nc->id);
  1092. pack->flags = htol16(flags);
  1093. memcpy(pack + 1, cert_data, cert_len);
  1094. client_end_control_packet(client, SCID_NEWCLIENT);
  1095. return 0;
  1096. }
  1097. int client_send_endclient (struct client_data *client, peerid_t end_id)
  1098. {
  1099. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1100. ASSERT(!client->dying)
  1101. struct sc_server_endclient *pack;
  1102. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_endclient)) < 0) {
  1103. return -1;
  1104. }
  1105. pack->id = htol16(end_id);
  1106. client_end_control_packet(client, SCID_ENDCLIENT);
  1107. return 0;
  1108. }
  1109. void client_input_handler_send (struct client_data *client, uint8_t *data, int data_len)
  1110. {
  1111. ASSERT(data_len >= 0)
  1112. ASSERT(data_len <= SC_MAX_ENC)
  1113. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1114. ASSERT(!client->dying)
  1115. // accept packet
  1116. PacketPassInterface_Done(&client->input_interface);
  1117. // restart disconnect timer
  1118. BReactor_SetTimer(&ss, &client->disconnect_timer);
  1119. // parse header
  1120. if (data_len < sizeof(struct sc_header)) {
  1121. client_log(client, BLOG_NOTICE, "packet too short");
  1122. client_remove(client);
  1123. return;
  1124. }
  1125. struct sc_header *header = (struct sc_header *)data;
  1126. data += sizeof(*header);
  1127. data_len -= sizeof(*header);
  1128. uint8_t type = ltoh8(header->type);
  1129. ASSERT(data_len >= 0)
  1130. ASSERT(data_len <= SC_MAX_PAYLOAD)
  1131. // perform action based on packet type
  1132. switch (type) {
  1133. case SCID_KEEPALIVE:
  1134. client_log(client, BLOG_DEBUG, "received keep-alive");
  1135. return;
  1136. case SCID_CLIENTHELLO:
  1137. process_packet_hello(client, data, data_len);
  1138. return;
  1139. case SCID_OUTMSG:
  1140. process_packet_outmsg(client, data, data_len);
  1141. return;
  1142. default:
  1143. client_log(client, BLOG_NOTICE, "unknown packet type %d, removing", (int)type);
  1144. client_remove(client);
  1145. return;
  1146. }
  1147. }
  1148. void process_packet_hello (struct client_data *client, uint8_t *data, int data_len)
  1149. {
  1150. if (client->initstatus != INITSTATUS_WAITHELLO) {
  1151. client_log(client, BLOG_NOTICE, "hello: not expected");
  1152. client_remove(client);
  1153. return;
  1154. }
  1155. if (data_len != sizeof(struct sc_client_hello)) {
  1156. client_log(client, BLOG_NOTICE, "hello: invalid length");
  1157. client_remove(client);
  1158. return;
  1159. }
  1160. struct sc_client_hello *msg = (struct sc_client_hello *)data;
  1161. client->version = ltoh16(msg->version);
  1162. if (client->version != SC_VERSION && client->version != SC_OLDVERSION) {
  1163. client_log(client, BLOG_NOTICE, "hello: unknown version");
  1164. client_remove(client);
  1165. return;
  1166. }
  1167. client_log(client, BLOG_INFO, "received hello");
  1168. // set client state to complete
  1169. client->initstatus = INITSTATUS_COMPLETE;
  1170. // publish client
  1171. for (LinkedList2Node *list_node = LinkedList2_GetFirst(&clients); list_node; list_node = LinkedList2Node_Next(list_node)) {
  1172. struct client_data *client2 = UPPER_OBJECT(list_node, struct client_data, list_node);
  1173. if (client2 == client || client2->initstatus != INITSTATUS_COMPLETE || client2->dying || !clients_allowed(client, client2)) {
  1174. continue;
  1175. }
  1176. // determine relay relations
  1177. int relay_to = relay_allowed(client, client2);
  1178. int relay_from = relay_allowed(client2, client);
  1179. if (!create_know(client, client2, relay_to, relay_from)) {
  1180. client_log(client, BLOG_ERROR, "failed to allocate know to %d", (int)client2->id);
  1181. goto fail;
  1182. }
  1183. if (!create_know(client2, client, relay_from, relay_to)) {
  1184. client_log(client, BLOG_ERROR, "failed to allocate know from %d", (int)client2->id);
  1185. goto fail;
  1186. }
  1187. // create flow from client to client2
  1188. if (!peer_flow_create(client, client2)) {
  1189. client_log(client, BLOG_ERROR, "failed to allocate flow to %d", (int)client2->id);
  1190. goto fail;
  1191. }
  1192. // create flow from client2 to client
  1193. if (!peer_flow_create(client2, client)) {
  1194. client_log(client, BLOG_ERROR, "failed to allocate flow from %d", (int)client2->id);
  1195. goto fail;
  1196. }
  1197. }
  1198. // send hello
  1199. struct sc_server_hello *pack;
  1200. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_hello)) < 0) {
  1201. return;
  1202. }
  1203. pack->flags = htol16(0);
  1204. pack->id = htol16(client->id);
  1205. pack->clientAddr = (client->addr.type == BADDR_TYPE_IPV4 ? client->addr.ipv4.ip : hton32(0));
  1206. client_end_control_packet(client, SCID_SERVERHELLO);
  1207. return;
  1208. fail:
  1209. client_remove(client);
  1210. }
  1211. void process_packet_outmsg (struct client_data *client, uint8_t *data, int data_len)
  1212. {
  1213. if (client->initstatus != INITSTATUS_COMPLETE) {
  1214. client_log(client, BLOG_NOTICE, "outmsg: not expected");
  1215. client_remove(client);
  1216. return;
  1217. }
  1218. if (data_len < sizeof(struct sc_client_outmsg)) {
  1219. client_log(client, BLOG_NOTICE, "outmsg: wrong size");
  1220. client_remove(client);
  1221. return;
  1222. }
  1223. struct sc_client_outmsg *msg = (struct sc_client_outmsg *)data;
  1224. peerid_t id = ltoh16(msg->clientid);
  1225. int payload_size = data_len - sizeof(struct sc_client_outmsg);
  1226. if (payload_size > SC_MAX_MSGLEN) {
  1227. client_log(client, BLOG_NOTICE, "outmsg: too large payload");
  1228. client_remove(client);
  1229. return;
  1230. }
  1231. uint8_t *payload = data + sizeof(struct sc_client_outmsg);
  1232. // lookup flow to destination client
  1233. BAVLNode *node = BAVL_LookupExact(&client->peer_out_flows_tree, &id);
  1234. if (!node) {
  1235. client_log(client, BLOG_INFO, "no flow for message to %d", (int)id);
  1236. return;
  1237. }
  1238. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, src_tree_node);
  1239. // send packet
  1240. struct sc_server_inmsg *pack;
  1241. if (!peer_flow_start_packet(flow, (void **)&pack, sizeof(struct sc_server_inmsg) + payload_size)) {
  1242. return;
  1243. }
  1244. pack->clientid = htol16(client->id);
  1245. memcpy((uint8_t *)(pack + 1), payload, payload_size);
  1246. peer_flow_end_packet(flow, SCID_INMSG);
  1247. }
  1248. struct peer_flow * peer_flow_create (struct client_data *src_client, struct client_data *dest_client)
  1249. {
  1250. ASSERT(src_client->initstatus == INITSTATUS_COMPLETE)
  1251. ASSERT(!src_client->dying)
  1252. ASSERT(dest_client->initstatus == INITSTATUS_COMPLETE)
  1253. ASSERT(!dest_client->dying)
  1254. ASSERT(!BAVL_LookupExact(&src_client->peer_out_flows_tree, &dest_client->id))
  1255. // allocate flow structure
  1256. struct peer_flow *flow = malloc(sizeof(*flow));
  1257. if (!flow) {
  1258. goto fail0;
  1259. }
  1260. // set source and destination
  1261. flow->src_client = src_client;
  1262. flow->dest_client = dest_client;
  1263. flow->dest_client_id = dest_client->id;
  1264. // add to source list and tree
  1265. LinkedList2_Append(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1266. ASSERT_EXECUTE(BAVL_Insert(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node, NULL))
  1267. // add to destination client list
  1268. LinkedList2_Append(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1269. // initialize I/O
  1270. PacketPassFairQueueFlow_Init(&flow->qflow, &flow->dest_client->output_peers_fairqueue);
  1271. if (!PacketProtoFlow_Init(
  1272. &flow->oflow, SC_MAX_ENC, CLIENT_PEER_FLOW_BUFFER_MIN_PACKETS,
  1273. PacketPassFairQueueFlow_GetInput(&flow->qflow), BReactor_PendingGroup(&ss)
  1274. )) {
  1275. BLog(BLOG_ERROR, "PacketProtoFlow_Init failed");
  1276. goto fail1;
  1277. }
  1278. flow->input = PacketProtoFlow_GetInput(&flow->oflow);
  1279. flow->packet_len = -1;
  1280. return flow;
  1281. fail1:
  1282. PacketPassFairQueueFlow_Free(&flow->qflow);
  1283. LinkedList2_Remove(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1284. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1285. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1286. free(flow);
  1287. fail0:
  1288. return NULL;
  1289. }
  1290. void peer_flow_dealloc (struct peer_flow *flow)
  1291. {
  1292. PacketPassFairQueueFlow_AssertFree(&flow->qflow);
  1293. // free I/O
  1294. PacketProtoFlow_Free(&flow->oflow);
  1295. PacketPassFairQueueFlow_Free(&flow->qflow);
  1296. // remove from destination client list
  1297. LinkedList2_Remove(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1298. // remove from source list and hash table
  1299. if (flow->src_client) {
  1300. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1301. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1302. }
  1303. // free memory
  1304. free(flow);
  1305. }
  1306. void peer_flow_disconnect (struct peer_flow *flow)
  1307. {
  1308. ASSERT(flow->src_client)
  1309. // remove from source list and hash table
  1310. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1311. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1312. // set no source
  1313. flow->src_client = NULL;
  1314. }
  1315. int peer_flow_start_packet (struct peer_flow *flow, void **data, int len)
  1316. {
  1317. ASSERT(len >= 0)
  1318. ASSERT(len <= SC_MAX_PAYLOAD)
  1319. ASSERT(!(len > 0) || data)
  1320. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1321. ASSERT(!flow->dest_client->dying)
  1322. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1323. ASSERT(!flow->src_client->dying)
  1324. ASSERT(flow->packet_len == -1)
  1325. // obtain location for writing the packet
  1326. if (!BufferWriter_StartPacket(flow->input, &flow->packet)) {
  1327. client_log(flow->src_client, BLOG_INFO, "out of flow buffer for message to %d", (int)flow->dest_client->id);
  1328. return 0;
  1329. }
  1330. flow->packet_len = len;
  1331. if (data) {
  1332. *data = flow->packet + sizeof(struct sc_header);
  1333. }
  1334. return 1;
  1335. }
  1336. void peer_flow_end_packet (struct peer_flow *flow, uint8_t type)
  1337. {
  1338. ASSERT(flow->packet_len >= 0)
  1339. ASSERT(flow->packet_len <= SC_MAX_PAYLOAD)
  1340. // write header
  1341. struct sc_header *header = (struct sc_header *)flow->packet;
  1342. header->type = type;
  1343. // finish writing packet
  1344. BufferWriter_EndPacket(flow->input, sizeof(struct sc_header) + flow->packet_len);
  1345. flow->packet_len = -1;
  1346. }
  1347. void peer_flow_handler_canremove (struct peer_flow *flow)
  1348. {
  1349. ASSERT(!flow->src_client)
  1350. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1351. ASSERT(!flow->dest_client->dying)
  1352. client_log(flow->dest_client, BLOG_DEBUG, "removing old flow");
  1353. peer_flow_dealloc(flow);
  1354. return;
  1355. }
  1356. peerid_t new_client_id (void)
  1357. {
  1358. ASSERT(clients_num < MAX_CLIENTS)
  1359. for (int i = 0; i < MAX_CLIENTS; i++) {
  1360. peerid_t id = clients_nextid++;
  1361. if (!find_client_by_id(id)) {
  1362. return id;
  1363. }
  1364. }
  1365. ASSERT(0)
  1366. return 42;
  1367. }
  1368. struct client_data * find_client_by_id (peerid_t id)
  1369. {
  1370. BAVLNode *node;
  1371. if (!(node = BAVL_LookupExact(&clients_tree, &id))) {
  1372. return NULL;
  1373. }
  1374. return UPPER_OBJECT(node, struct client_data, tree_node);
  1375. }
  1376. int clients_allowed (struct client_data *client1, struct client_data *client2)
  1377. {
  1378. ASSERT(client1->initstatus == INITSTATUS_COMPLETE)
  1379. ASSERT(!client1->dying)
  1380. ASSERT(client2->initstatus == INITSTATUS_COMPLETE)
  1381. ASSERT(!client2->dying)
  1382. if (!options.comm_predicate) {
  1383. return 1;
  1384. }
  1385. // set values to compare against
  1386. comm_predicate_p1name = (client1->common_name ? client1->common_name : "");
  1387. comm_predicate_p2name = (client2->common_name ? client2->common_name : "");
  1388. BAddr_GetIPAddr(&client1->addr, &comm_predicate_p1addr);
  1389. BAddr_GetIPAddr(&client2->addr, &comm_predicate_p2addr);
  1390. // evaluate predicate
  1391. int res = BPredicate_Eval(&comm_predicate);
  1392. if (res < 0) {
  1393. return 0;
  1394. }
  1395. return res;
  1396. }
  1397. int comm_predicate_func_p1name_cb (void *user, void **args)
  1398. {
  1399. char *arg = args[0];
  1400. return (!strcmp(arg, comm_predicate_p1name));
  1401. }
  1402. int comm_predicate_func_p2name_cb (void *user, void **args)
  1403. {
  1404. char *arg = args[0];
  1405. return (!strcmp(arg, comm_predicate_p2name));
  1406. }
  1407. int comm_predicate_func_p1addr_cb (void *user, void **args)
  1408. {
  1409. char *arg = args[0];
  1410. BIPAddr addr;
  1411. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1412. BLog(BLOG_WARNING, "failed to parse address");
  1413. return -1;
  1414. }
  1415. return BIPAddr_Compare(&addr, &comm_predicate_p1addr);
  1416. }
  1417. int comm_predicate_func_p2addr_cb (void *user, void **args)
  1418. {
  1419. char *arg = args[0];
  1420. BIPAddr addr;
  1421. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1422. BLog(BLOG_WARNING, "failed to parse address");
  1423. return -1;
  1424. }
  1425. return BIPAddr_Compare(&addr, &comm_predicate_p2addr);
  1426. }
  1427. int relay_allowed (struct client_data *client, struct client_data *relay)
  1428. {
  1429. if (!options.relay_predicate) {
  1430. return 0;
  1431. }
  1432. // set values to compare against
  1433. relay_predicate_pname = (client->common_name ? client->common_name : "");
  1434. relay_predicate_rname = (relay->common_name ? relay->common_name : "");
  1435. BAddr_GetIPAddr(&client->addr, &relay_predicate_paddr);
  1436. BAddr_GetIPAddr(&relay->addr, &relay_predicate_raddr);
  1437. // evaluate predicate
  1438. int res = BPredicate_Eval(&relay_predicate);
  1439. if (res < 0) {
  1440. return 0;
  1441. }
  1442. return res;
  1443. }
  1444. int relay_predicate_func_pname_cb (void *user, void **args)
  1445. {
  1446. char *arg = args[0];
  1447. return (!strcmp(arg, relay_predicate_pname));
  1448. }
  1449. int relay_predicate_func_rname_cb (void *user, void **args)
  1450. {
  1451. char *arg = args[0];
  1452. return (!strcmp(arg, relay_predicate_rname));
  1453. }
  1454. int relay_predicate_func_paddr_cb (void *user, void **args)
  1455. {
  1456. char *arg = args[0];
  1457. BIPAddr addr;
  1458. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1459. BLog(BLOG_ERROR, "paddr: failed to parse address");
  1460. return -1;
  1461. }
  1462. return BIPAddr_Compare(&addr, &relay_predicate_paddr);
  1463. }
  1464. int relay_predicate_func_raddr_cb (void *user, void **args)
  1465. {
  1466. char *arg = args[0];
  1467. BIPAddr addr;
  1468. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1469. BLog(BLOG_ERROR, "raddr: failed to parse address");
  1470. return -1;
  1471. }
  1472. return BIPAddr_Compare(&addr, &relay_predicate_raddr);
  1473. }
  1474. int peerid_comparator (void *unused, peerid_t *p1, peerid_t *p2)
  1475. {
  1476. if (*p1 < *p2) {
  1477. return -1;
  1478. }
  1479. if (*p1 > *p2) {
  1480. return 1;
  1481. }
  1482. return 0;
  1483. }
  1484. int create_know (struct client_data *from, struct client_data *to, int relay_server, int relay_client)
  1485. {
  1486. ASSERT(from->initstatus == INITSTATUS_COMPLETE)
  1487. ASSERT(!from->dying)
  1488. ASSERT(to->initstatus == INITSTATUS_COMPLETE)
  1489. ASSERT(!to->dying)
  1490. // allocate structure
  1491. struct peer_know *k = malloc(sizeof(*k));
  1492. if (!k) {
  1493. return 0;
  1494. }
  1495. // init arguments
  1496. k->from = from;
  1497. k->to = to;
  1498. k->relay_server = relay_server;
  1499. k->relay_client = relay_client;
  1500. // append to lists
  1501. LinkedList2_Append(&from->know_out_list, &k->from_node);
  1502. LinkedList2_Append(&to->know_in_list, &k->to_node);
  1503. // init and set inform job to inform client 'from' about client 'to'
  1504. BPending_Init(&k->inform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_inform_job_handler, k);
  1505. BPending_Set(&k->inform_job);
  1506. // init uninform job
  1507. BPending_Init(&k->uninform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_uninform_job_handler, k);
  1508. return 1;
  1509. }
  1510. void remove_know (struct peer_know *k)
  1511. {
  1512. // free uninform job
  1513. BPending_Free(&k->uninform_job);
  1514. // free inform job
  1515. BPending_Free(&k->inform_job);
  1516. // remove from lists
  1517. LinkedList2_Remove(&k->to->know_in_list, &k->to_node);
  1518. LinkedList2_Remove(&k->from->know_out_list, &k->from_node);
  1519. // free structure
  1520. free(k);
  1521. }
  1522. void know_inform_job_handler (struct peer_know *k)
  1523. {
  1524. ASSERT(!k->from->dying)
  1525. ASSERT(!k->to->dying)
  1526. client_send_newclient(k->from, k->to, k->relay_server, k->relay_client);
  1527. return;
  1528. }
  1529. void uninform_know (struct peer_know *k)
  1530. {
  1531. ASSERT(!k->from->dying)
  1532. ASSERT(k->to->dying)
  1533. ASSERT(!BPending_IsSet(&k->uninform_job))
  1534. // if 'from' has not been informed about 'to' yet, remove know, otherwise
  1535. // schedule informing 'from' that 'to' is no more
  1536. if (BPending_IsSet(&k->inform_job)) {
  1537. remove_know(k);
  1538. } else {
  1539. BPending_Set(&k->uninform_job);
  1540. }
  1541. }
  1542. void know_uninform_job_handler (struct peer_know *k)
  1543. {
  1544. ASSERT(!k->from->dying)
  1545. ASSERT(k->to->dying)
  1546. ASSERT(!BPending_IsSet(&k->inform_job))
  1547. struct client_data *from = k->from;
  1548. struct client_data *to = k->to;
  1549. // remove know
  1550. remove_know(k);
  1551. // uninform
  1552. client_send_endclient(from, to->id);
  1553. }