server.c 58 KB

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