server.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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 <system/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 (struct client_data *client, int component, int code);
  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. FlowErrorDomain_Init(&client->input_decoder_domain, (FlowErrorDomain_handler)client_decoder_handler, client);
  795. if (!PacketProtoDecoder_Init(&client->input_decoder, FlowErrorReporter_Create(&client->input_decoder_domain, 0),
  796. recv_if, &client->input_interface, BReactor_PendingGroup(&ss)
  797. )) {
  798. client_log(client, BLOG_ERROR, "PacketProtoDecoder_Init failed");
  799. goto fail1;
  800. }
  801. // init output common
  802. // init sender
  803. PacketStreamSender_Init(&client->output_sender, send_if, PACKETPROTO_ENCLEN(SC_MAX_ENC), BReactor_PendingGroup(&ss));
  804. // init queue
  805. PacketPassPriorityQueue_Init(&client->output_priorityqueue, PacketStreamSender_GetInput(&client->output_sender), BReactor_PendingGroup(&ss), 0);
  806. // init output control flow
  807. // init queue flow
  808. PacketPassPriorityQueueFlow_Init(&client->output_control_qflow, &client->output_priorityqueue, -1);
  809. // init PacketProtoFlow
  810. if (!PacketProtoFlow_Init(
  811. &client->output_control_oflow, SC_MAX_ENC, CLIENT_CONTROL_BUFFER_MIN_PACKETS,
  812. PacketPassPriorityQueueFlow_GetInput(&client->output_control_qflow), BReactor_PendingGroup(&ss)
  813. )) {
  814. client_log(client, BLOG_ERROR, "PacketProtoFlow_Init failed");
  815. goto fail2;
  816. }
  817. client->output_control_input = PacketProtoFlow_GetInput(&client->output_control_oflow);
  818. client->output_control_packet_len = -1;
  819. // init output peers flow
  820. // init queue flow
  821. // use lower priority than control flow (higher number)
  822. PacketPassPriorityQueueFlow_Init(&client->output_peers_qflow, &client->output_priorityqueue, 0);
  823. // init fair queue (for different peers)
  824. PacketPassFairQueue_Init(&client->output_peers_fairqueue, PacketPassPriorityQueueFlow_GetInput(&client->output_peers_qflow), BReactor_PendingGroup(&ss), 0, 1);
  825. // init list of flows
  826. LinkedList2_Init(&client->output_peers_flows);
  827. return 1;
  828. fail2:
  829. PacketPassPriorityQueueFlow_Free(&client->output_control_qflow);
  830. // free output common
  831. PacketPassPriorityQueue_Free(&client->output_priorityqueue);
  832. PacketStreamSender_Free(&client->output_sender);
  833. // free input
  834. PacketProtoDecoder_Free(&client->input_decoder);
  835. fail1:
  836. PacketPassInterface_Free(&client->input_interface);
  837. return 0;
  838. }
  839. void client_dealloc_io (struct client_data *client)
  840. {
  841. // allow freeing fair queue flows
  842. PacketPassFairQueue_PrepareFree(&client->output_peers_fairqueue);
  843. // remove flows to us
  844. LinkedList2Node *node;
  845. while (node = LinkedList2_GetFirst(&client->output_peers_flows)) {
  846. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, dest_list_node);
  847. ASSERT(flow->dest_client == client)
  848. peer_flow_dealloc(flow);
  849. }
  850. // allow freeing priority queue flows
  851. PacketPassPriorityQueue_PrepareFree(&client->output_priorityqueue);
  852. // free output peers flow
  853. PacketPassFairQueue_Free(&client->output_peers_fairqueue);
  854. PacketPassPriorityQueueFlow_Free(&client->output_peers_qflow);
  855. // free output control flow
  856. PacketProtoFlow_Free(&client->output_control_oflow);
  857. PacketPassPriorityQueueFlow_Free(&client->output_control_qflow);
  858. // free output common
  859. PacketPassPriorityQueue_Free(&client->output_priorityqueue);
  860. PacketStreamSender_Free(&client->output_sender);
  861. // free input
  862. PacketProtoDecoder_Free(&client->input_decoder);
  863. PacketPassInterface_Free(&client->input_interface);
  864. }
  865. void client_remove (struct client_data *client)
  866. {
  867. ASSERT(!client->dying)
  868. client_log(client, BLOG_INFO, "removing");
  869. // set dying to prevent sending this client anything
  870. client->dying = 1;
  871. // free I/O now, removing incoming flows
  872. if (client->initstatus >= INITSTATUS_WAITHELLO) {
  873. client_dealloc_io(client);
  874. }
  875. // remove outgoing knows
  876. LinkedList2Node *node;
  877. while (node = LinkedList2_GetFirst(&client->know_out_list)) {
  878. struct peer_know *k = UPPER_OBJECT(node, struct peer_know, from_node);
  879. remove_know(k);
  880. }
  881. // remove outgoing flows
  882. while (node = LinkedList2_GetFirst(&client->peer_out_flows_list)) {
  883. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, src_list_node);
  884. ASSERT(flow->src_client == client)
  885. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  886. ASSERT(!flow->dest_client->dying)
  887. if (PacketPassFairQueueFlow_IsBusy(&flow->qflow)) {
  888. client_log(client, BLOG_DEBUG, "removing flow to %d later", (int)flow->dest_client->id);
  889. peer_flow_disconnect(flow);
  890. PacketPassFairQueueFlow_SetBusyHandler(&flow->qflow, (PacketPassFairQueue_handler_busy)peer_flow_handler_canremove, flow);
  891. } else {
  892. client_log(client, BLOG_DEBUG, "removing flow to %d now", (int)flow->dest_client->id);
  893. peer_flow_dealloc(flow);
  894. }
  895. }
  896. // schedule job to finish removal after clients are informed
  897. BPending_Set(&client->dying_job);
  898. // inform other clients that 'client' is no more
  899. LinkedList2Iterator it;
  900. LinkedList2Iterator_InitForward(&it, &client->know_in_list);
  901. while (node = LinkedList2Iterator_Next(&it)) {
  902. struct peer_know *k = UPPER_OBJECT(node, struct peer_know, to_node);
  903. uninform_know(k);
  904. }
  905. }
  906. void client_dying_job (struct client_data *client)
  907. {
  908. ASSERT(client->dying)
  909. ASSERT(LinkedList2_IsEmpty(&client->know_in_list))
  910. client_dealloc(client);
  911. return;
  912. }
  913. void client_log (struct client_data *client, int level, const char *fmt, ...)
  914. {
  915. va_list vl;
  916. va_start(vl, fmt);
  917. char addr[BADDR_MAX_PRINT_LEN];
  918. BAddr_Print(&client->addr, addr);
  919. BLog_Append("client %d (%s)", (int)client->id, addr);
  920. if (client->common_name) {
  921. BLog_Append(" (%s)", client->common_name);
  922. }
  923. BLog_Append(": ");
  924. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  925. va_end(vl);
  926. }
  927. void client_disconnect_timer_handler (struct client_data *client)
  928. {
  929. ASSERT(!client->dying)
  930. client_log(client, BLOG_INFO, "timed out");
  931. client_remove(client);
  932. return;
  933. }
  934. void client_connection_handler (struct client_data *client, int event)
  935. {
  936. ASSERT(!client->dying)
  937. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  938. client_log(client, BLOG_INFO, "connection closed");
  939. } else {
  940. client_log(client, BLOG_INFO, "connection error");
  941. }
  942. client_remove(client);
  943. return;
  944. }
  945. void client_sslcon_handler (struct client_data *client, int event)
  946. {
  947. ASSERT(options.ssl)
  948. ASSERT(!client->dying)
  949. ASSERT(event == BSSLCONNECTION_EVENT_UP || event == BSSLCONNECTION_EVENT_ERROR)
  950. ASSERT(!(event == BSSLCONNECTION_EVENT_UP) || client->initstatus == INITSTATUS_HANDSHAKE)
  951. if (event == BSSLCONNECTION_EVENT_ERROR) {
  952. client_log(client, BLOG_ERROR, "SSL error");
  953. client_remove(client);
  954. return;
  955. }
  956. client_log(client, BLOG_INFO, "handshake complete");
  957. // get client certificate
  958. CERTCertificate *cert = SSL_PeerCertificate(client->ssl_prfd);
  959. if (!cert) {
  960. client_log(client, BLOG_ERROR, "SSL_PeerCertificate failed");
  961. goto fail0;
  962. }
  963. // remember common name
  964. if (!(client->common_name = CERT_GetCommonName(&cert->subject))) {
  965. client_log(client, BLOG_NOTICE, "CERT_GetCommonName failed");
  966. goto fail1;
  967. }
  968. // store certificate
  969. SECItem der = cert->derCert;
  970. if (der.len > sizeof(client->cert)) {
  971. client_log(client, BLOG_NOTICE, "client certificate too big");
  972. goto fail1;
  973. }
  974. memcpy(client->cert, der.data, der.len);
  975. client->cert_len = der.len;
  976. PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  977. if (!arena) {
  978. client_log(client, BLOG_ERROR, "PORT_NewArena failed");
  979. goto fail1;
  980. }
  981. // encode certificate
  982. memset(&der, 0, sizeof(der));
  983. if (!SEC_ASN1EncodeItem(arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate))) {
  984. client_log(client, BLOG_ERROR, "SEC_ASN1EncodeItem failed");
  985. goto fail2;
  986. }
  987. // store re-encoded certificate (for compatibility with old clients)
  988. if (der.len > sizeof(client->cert_old)) {
  989. client_log(client, BLOG_NOTICE, "client certificate too big");
  990. goto fail2;
  991. }
  992. memcpy(client->cert_old, der.data, der.len);
  993. client->cert_old_len = der.len;
  994. // init I/O chains
  995. if (!client_init_io(client)) {
  996. goto fail2;
  997. }
  998. PORT_FreeArena(arena, PR_FALSE);
  999. CERT_DestroyCertificate(cert);
  1000. // set client state
  1001. client->initstatus = INITSTATUS_WAITHELLO;
  1002. client_log(client, BLOG_INFO, "handshake complete");
  1003. return;
  1004. // handle errors
  1005. fail2:
  1006. PORT_FreeArena(arena, PR_FALSE);
  1007. fail1:
  1008. CERT_DestroyCertificate(cert);
  1009. fail0:
  1010. client_remove(client);
  1011. }
  1012. void client_decoder_handler (struct client_data *client, int component, int code)
  1013. {
  1014. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1015. ASSERT(!client->dying)
  1016. client_log(client, BLOG_ERROR, "decoder error");
  1017. client_remove(client);
  1018. return;
  1019. }
  1020. int client_start_control_packet (struct client_data *client, void **data, int len)
  1021. {
  1022. ASSERT(len >= 0)
  1023. ASSERT(len <= SC_MAX_PAYLOAD)
  1024. ASSERT(!(len > 0) || data)
  1025. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1026. ASSERT(!client->dying)
  1027. ASSERT(client->output_control_packet_len == -1)
  1028. // obtain location for writing the packet
  1029. if (!BufferWriter_StartPacket(client->output_control_input, &client->output_control_packet)) {
  1030. // out of buffer, kill client
  1031. client_log(client, BLOG_INFO, "out of control buffer, removing");
  1032. client_remove(client);
  1033. return -1;
  1034. }
  1035. client->output_control_packet_len = len;
  1036. if (data) {
  1037. *data = client->output_control_packet + sizeof(struct sc_header);
  1038. }
  1039. return 0;
  1040. }
  1041. void client_end_control_packet (struct client_data *client, uint8_t type)
  1042. {
  1043. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1044. ASSERT(!client->dying)
  1045. ASSERT(client->output_control_packet_len >= 0)
  1046. ASSERT(client->output_control_packet_len <= SC_MAX_PAYLOAD)
  1047. // write header
  1048. struct sc_header *header = (struct sc_header *)client->output_control_packet;
  1049. header->type = htol8(type);
  1050. // finish writing packet
  1051. BufferWriter_EndPacket(client->output_control_input, sizeof(struct sc_header) + client->output_control_packet_len);
  1052. client->output_control_packet_len = -1;
  1053. }
  1054. int client_send_newclient (struct client_data *client, struct client_data *nc, int relay_server, int relay_client)
  1055. {
  1056. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1057. ASSERT(!client->dying)
  1058. ASSERT(nc->initstatus == INITSTATUS_COMPLETE)
  1059. ASSERT(!nc->dying)
  1060. int flags = 0;
  1061. if (relay_server) {
  1062. flags |= SCID_NEWCLIENT_FLAG_RELAY_SERVER;
  1063. }
  1064. if (relay_client) {
  1065. flags |= SCID_NEWCLIENT_FLAG_RELAY_CLIENT;
  1066. }
  1067. uint8_t *cert_data = NULL;
  1068. int cert_len = 0;
  1069. if (options.ssl) {
  1070. cert_data = (client->version == SC_OLDVERSION ? nc->cert_old : nc->cert);
  1071. cert_len = (client->version == SC_OLDVERSION ? nc->cert_old_len : nc->cert_len);
  1072. }
  1073. struct sc_server_newclient *pack;
  1074. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_newclient) + cert_len) < 0) {
  1075. return -1;
  1076. }
  1077. pack->id = htol16(nc->id);
  1078. pack->flags = htol16(flags);
  1079. memcpy(pack + 1, cert_data, cert_len);
  1080. client_end_control_packet(client, SCID_NEWCLIENT);
  1081. return 0;
  1082. }
  1083. int client_send_endclient (struct client_data *client, peerid_t end_id)
  1084. {
  1085. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1086. ASSERT(!client->dying)
  1087. struct sc_server_endclient *pack;
  1088. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_endclient)) < 0) {
  1089. return -1;
  1090. }
  1091. pack->id = htol16(end_id);
  1092. client_end_control_packet(client, SCID_ENDCLIENT);
  1093. return 0;
  1094. }
  1095. void client_input_handler_send (struct client_data *client, uint8_t *data, int data_len)
  1096. {
  1097. ASSERT(data_len >= 0)
  1098. ASSERT(data_len <= SC_MAX_ENC)
  1099. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1100. ASSERT(!client->dying)
  1101. // accept packet
  1102. PacketPassInterface_Done(&client->input_interface);
  1103. // restart disconnect timer
  1104. BReactor_SetTimer(&ss, &client->disconnect_timer);
  1105. // parse header
  1106. if (data_len < sizeof(struct sc_header)) {
  1107. client_log(client, BLOG_NOTICE, "packet too short");
  1108. client_remove(client);
  1109. return;
  1110. }
  1111. struct sc_header *header = (struct sc_header *)data;
  1112. data += sizeof(*header);
  1113. data_len -= sizeof(*header);
  1114. uint8_t type = ltoh8(header->type);
  1115. ASSERT(data_len >= 0)
  1116. ASSERT(data_len <= SC_MAX_PAYLOAD)
  1117. // perform action based on packet type
  1118. switch (type) {
  1119. case SCID_KEEPALIVE:
  1120. client_log(client, BLOG_DEBUG, "received keep-alive");
  1121. return;
  1122. case SCID_CLIENTHELLO:
  1123. process_packet_hello(client, data, data_len);
  1124. return;
  1125. case SCID_OUTMSG:
  1126. process_packet_outmsg(client, data, data_len);
  1127. return;
  1128. default:
  1129. client_log(client, BLOG_NOTICE, "unknown packet type %d, removing", (int)type);
  1130. client_remove(client);
  1131. return;
  1132. }
  1133. }
  1134. void process_packet_hello (struct client_data *client, uint8_t *data, int data_len)
  1135. {
  1136. if (client->initstatus != INITSTATUS_WAITHELLO) {
  1137. client_log(client, BLOG_NOTICE, "hello: not expected");
  1138. client_remove(client);
  1139. return;
  1140. }
  1141. if (data_len != sizeof(struct sc_client_hello)) {
  1142. client_log(client, BLOG_NOTICE, "hello: invalid length");
  1143. client_remove(client);
  1144. return;
  1145. }
  1146. struct sc_client_hello *msg = (struct sc_client_hello *)data;
  1147. client->version = ltoh16(msg->version);
  1148. if (client->version != SC_VERSION && client->version != SC_OLDVERSION) {
  1149. client_log(client, BLOG_NOTICE, "hello: unknown version");
  1150. client_remove(client);
  1151. return;
  1152. }
  1153. client_log(client, BLOG_INFO, "received hello");
  1154. // set client state to complete
  1155. client->initstatus = INITSTATUS_COMPLETE;
  1156. // publish client
  1157. for (LinkedList2Node *list_node = LinkedList2_GetFirst(&clients); list_node; list_node = LinkedList2Node_Next(list_node)) {
  1158. struct client_data *client2 = UPPER_OBJECT(list_node, struct client_data, list_node);
  1159. if (client2 == client || client2->initstatus != INITSTATUS_COMPLETE || client2->dying || !clients_allowed(client, client2)) {
  1160. continue;
  1161. }
  1162. // determine relay relations
  1163. int relay_to = relay_allowed(client, client2);
  1164. int relay_from = relay_allowed(client2, client);
  1165. if (!create_know(client, client2, relay_to, relay_from)) {
  1166. client_log(client, BLOG_ERROR, "failed to allocate know to %d", (int)client2->id);
  1167. goto fail;
  1168. }
  1169. if (!create_know(client2, client, relay_from, relay_to)) {
  1170. client_log(client, BLOG_ERROR, "failed to allocate know from %d", (int)client2->id);
  1171. goto fail;
  1172. }
  1173. // create flow from client to client2
  1174. if (!peer_flow_create(client, client2)) {
  1175. client_log(client, BLOG_ERROR, "failed to allocate flow to %d", (int)client2->id);
  1176. goto fail;
  1177. }
  1178. // create flow from client2 to client
  1179. if (!peer_flow_create(client2, client)) {
  1180. client_log(client, BLOG_ERROR, "failed to allocate flow from %d", (int)client2->id);
  1181. goto fail;
  1182. }
  1183. }
  1184. // send hello
  1185. struct sc_server_hello *pack;
  1186. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_hello)) < 0) {
  1187. return;
  1188. }
  1189. pack->flags = htol16(0);
  1190. pack->id = htol16(client->id);
  1191. pack->clientAddr = (client->addr.type == BADDR_TYPE_IPV4 ? client->addr.ipv4.ip : hton32(0));
  1192. client_end_control_packet(client, SCID_SERVERHELLO);
  1193. return;
  1194. fail:
  1195. client_remove(client);
  1196. }
  1197. void process_packet_outmsg (struct client_data *client, uint8_t *data, int data_len)
  1198. {
  1199. if (client->initstatus != INITSTATUS_COMPLETE) {
  1200. client_log(client, BLOG_NOTICE, "outmsg: not expected");
  1201. client_remove(client);
  1202. return;
  1203. }
  1204. if (data_len < sizeof(struct sc_client_outmsg)) {
  1205. client_log(client, BLOG_NOTICE, "outmsg: wrong size");
  1206. client_remove(client);
  1207. return;
  1208. }
  1209. struct sc_client_outmsg *msg = (struct sc_client_outmsg *)data;
  1210. peerid_t id = ltoh16(msg->clientid);
  1211. int payload_size = data_len - sizeof(struct sc_client_outmsg);
  1212. if (payload_size > SC_MAX_MSGLEN) {
  1213. client_log(client, BLOG_NOTICE, "outmsg: too large payload");
  1214. client_remove(client);
  1215. return;
  1216. }
  1217. uint8_t *payload = data + sizeof(struct sc_client_outmsg);
  1218. // lookup flow to destination client
  1219. BAVLNode *node = BAVL_LookupExact(&client->peer_out_flows_tree, &id);
  1220. if (!node) {
  1221. client_log(client, BLOG_INFO, "no flow for message to %d", (int)id);
  1222. return;
  1223. }
  1224. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, src_tree_node);
  1225. // send packet
  1226. struct sc_server_inmsg *pack;
  1227. if (!peer_flow_start_packet(flow, (void **)&pack, sizeof(struct sc_server_inmsg) + payload_size)) {
  1228. return;
  1229. }
  1230. pack->clientid = htol16(client->id);
  1231. memcpy((uint8_t *)(pack + 1), payload, payload_size);
  1232. peer_flow_end_packet(flow, SCID_INMSG);
  1233. }
  1234. struct peer_flow * peer_flow_create (struct client_data *src_client, struct client_data *dest_client)
  1235. {
  1236. ASSERT(src_client->initstatus == INITSTATUS_COMPLETE)
  1237. ASSERT(!src_client->dying)
  1238. ASSERT(dest_client->initstatus == INITSTATUS_COMPLETE)
  1239. ASSERT(!dest_client->dying)
  1240. ASSERT(!BAVL_LookupExact(&src_client->peer_out_flows_tree, &dest_client->id))
  1241. // allocate flow structure
  1242. struct peer_flow *flow = malloc(sizeof(*flow));
  1243. if (!flow) {
  1244. goto fail0;
  1245. }
  1246. // set source and destination
  1247. flow->src_client = src_client;
  1248. flow->dest_client = dest_client;
  1249. flow->dest_client_id = dest_client->id;
  1250. // add to source list and tree
  1251. LinkedList2_Append(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1252. ASSERT_EXECUTE(BAVL_Insert(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node, NULL))
  1253. // add to destination client list
  1254. LinkedList2_Append(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1255. // initialize I/O
  1256. PacketPassFairQueueFlow_Init(&flow->qflow, &flow->dest_client->output_peers_fairqueue);
  1257. if (!PacketProtoFlow_Init(
  1258. &flow->oflow, SC_MAX_ENC, CLIENT_PEER_FLOW_BUFFER_MIN_PACKETS,
  1259. PacketPassFairQueueFlow_GetInput(&flow->qflow), BReactor_PendingGroup(&ss)
  1260. )) {
  1261. BLog(BLOG_ERROR, "PacketProtoFlow_Init failed");
  1262. goto fail1;
  1263. }
  1264. flow->input = PacketProtoFlow_GetInput(&flow->oflow);
  1265. flow->packet_len = -1;
  1266. return flow;
  1267. fail1:
  1268. PacketPassFairQueueFlow_Free(&flow->qflow);
  1269. LinkedList2_Remove(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1270. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1271. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1272. free(flow);
  1273. fail0:
  1274. return NULL;
  1275. }
  1276. void peer_flow_dealloc (struct peer_flow *flow)
  1277. {
  1278. PacketPassFairQueueFlow_AssertFree(&flow->qflow);
  1279. // free I/O
  1280. PacketProtoFlow_Free(&flow->oflow);
  1281. PacketPassFairQueueFlow_Free(&flow->qflow);
  1282. // remove from destination client list
  1283. LinkedList2_Remove(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1284. // remove from source list and hash table
  1285. if (flow->src_client) {
  1286. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1287. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1288. }
  1289. // free memory
  1290. free(flow);
  1291. }
  1292. void peer_flow_disconnect (struct peer_flow *flow)
  1293. {
  1294. ASSERT(flow->src_client)
  1295. // remove from source list and hash table
  1296. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1297. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1298. // set no source
  1299. flow->src_client = NULL;
  1300. }
  1301. int peer_flow_start_packet (struct peer_flow *flow, void **data, int len)
  1302. {
  1303. ASSERT(len >= 0)
  1304. ASSERT(len <= SC_MAX_PAYLOAD)
  1305. ASSERT(!(len > 0) || data)
  1306. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1307. ASSERT(!flow->dest_client->dying)
  1308. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1309. ASSERT(!flow->src_client->dying)
  1310. ASSERT(flow->packet_len == -1)
  1311. // obtain location for writing the packet
  1312. if (!BufferWriter_StartPacket(flow->input, &flow->packet)) {
  1313. client_log(flow->src_client, BLOG_INFO, "out of flow buffer for message to %d", (int)flow->dest_client->id);
  1314. return 0;
  1315. }
  1316. flow->packet_len = len;
  1317. if (data) {
  1318. *data = flow->packet + sizeof(struct sc_header);
  1319. }
  1320. return 1;
  1321. }
  1322. void peer_flow_end_packet (struct peer_flow *flow, uint8_t type)
  1323. {
  1324. ASSERT(flow->packet_len >= 0)
  1325. ASSERT(flow->packet_len <= SC_MAX_PAYLOAD)
  1326. // write header
  1327. struct sc_header *header = (struct sc_header *)flow->packet;
  1328. header->type = type;
  1329. // finish writing packet
  1330. BufferWriter_EndPacket(flow->input, sizeof(struct sc_header) + flow->packet_len);
  1331. flow->packet_len = -1;
  1332. }
  1333. void peer_flow_handler_canremove (struct peer_flow *flow)
  1334. {
  1335. ASSERT(!flow->src_client)
  1336. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1337. ASSERT(!flow->dest_client->dying)
  1338. client_log(flow->dest_client, BLOG_DEBUG, "removing old flow");
  1339. peer_flow_dealloc(flow);
  1340. return;
  1341. }
  1342. peerid_t new_client_id (void)
  1343. {
  1344. ASSERT(clients_num < MAX_CLIENTS)
  1345. for (int i = 0; i < MAX_CLIENTS; i++) {
  1346. peerid_t id = clients_nextid++;
  1347. if (!find_client_by_id(id)) {
  1348. return id;
  1349. }
  1350. }
  1351. ASSERT(0)
  1352. return 42;
  1353. }
  1354. struct client_data * find_client_by_id (peerid_t id)
  1355. {
  1356. BAVLNode *node;
  1357. if (!(node = BAVL_LookupExact(&clients_tree, &id))) {
  1358. return NULL;
  1359. }
  1360. return UPPER_OBJECT(node, struct client_data, tree_node);
  1361. }
  1362. int clients_allowed (struct client_data *client1, struct client_data *client2)
  1363. {
  1364. ASSERT(client1->initstatus == INITSTATUS_COMPLETE)
  1365. ASSERT(!client1->dying)
  1366. ASSERT(client2->initstatus == INITSTATUS_COMPLETE)
  1367. ASSERT(!client2->dying)
  1368. if (!options.comm_predicate) {
  1369. return 1;
  1370. }
  1371. // set values to compare against
  1372. comm_predicate_p1name = (client1->common_name ? client1->common_name : "");
  1373. comm_predicate_p2name = (client2->common_name ? client2->common_name : "");
  1374. BAddr_GetIPAddr(&client1->addr, &comm_predicate_p1addr);
  1375. BAddr_GetIPAddr(&client2->addr, &comm_predicate_p2addr);
  1376. // evaluate predicate
  1377. int res = BPredicate_Eval(&comm_predicate);
  1378. if (res < 0) {
  1379. return 0;
  1380. }
  1381. return res;
  1382. }
  1383. int comm_predicate_func_p1name_cb (void *user, void **args)
  1384. {
  1385. char *arg = args[0];
  1386. return (!strcmp(arg, comm_predicate_p1name));
  1387. }
  1388. int comm_predicate_func_p2name_cb (void *user, void **args)
  1389. {
  1390. char *arg = args[0];
  1391. return (!strcmp(arg, comm_predicate_p2name));
  1392. }
  1393. int comm_predicate_func_p1addr_cb (void *user, void **args)
  1394. {
  1395. char *arg = args[0];
  1396. BIPAddr addr;
  1397. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1398. BLog(BLOG_WARNING, "failed to parse address");
  1399. return -1;
  1400. }
  1401. return BIPAddr_Compare(&addr, &comm_predicate_p1addr);
  1402. }
  1403. int comm_predicate_func_p2addr_cb (void *user, void **args)
  1404. {
  1405. char *arg = args[0];
  1406. BIPAddr addr;
  1407. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1408. BLog(BLOG_WARNING, "failed to parse address");
  1409. return -1;
  1410. }
  1411. return BIPAddr_Compare(&addr, &comm_predicate_p2addr);
  1412. }
  1413. int relay_allowed (struct client_data *client, struct client_data *relay)
  1414. {
  1415. if (!options.relay_predicate) {
  1416. return 0;
  1417. }
  1418. // set values to compare against
  1419. relay_predicate_pname = (client->common_name ? client->common_name : "");
  1420. relay_predicate_rname = (relay->common_name ? relay->common_name : "");
  1421. BAddr_GetIPAddr(&client->addr, &relay_predicate_paddr);
  1422. BAddr_GetIPAddr(&relay->addr, &relay_predicate_raddr);
  1423. // evaluate predicate
  1424. int res = BPredicate_Eval(&relay_predicate);
  1425. if (res < 0) {
  1426. return 0;
  1427. }
  1428. return res;
  1429. }
  1430. int relay_predicate_func_pname_cb (void *user, void **args)
  1431. {
  1432. char *arg = args[0];
  1433. return (!strcmp(arg, relay_predicate_pname));
  1434. }
  1435. int relay_predicate_func_rname_cb (void *user, void **args)
  1436. {
  1437. char *arg = args[0];
  1438. return (!strcmp(arg, relay_predicate_rname));
  1439. }
  1440. int relay_predicate_func_paddr_cb (void *user, void **args)
  1441. {
  1442. char *arg = args[0];
  1443. BIPAddr addr;
  1444. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1445. BLog(BLOG_ERROR, "paddr: failed to parse address");
  1446. return -1;
  1447. }
  1448. return BIPAddr_Compare(&addr, &relay_predicate_paddr);
  1449. }
  1450. int relay_predicate_func_raddr_cb (void *user, void **args)
  1451. {
  1452. char *arg = args[0];
  1453. BIPAddr addr;
  1454. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1455. BLog(BLOG_ERROR, "raddr: failed to parse address");
  1456. return -1;
  1457. }
  1458. return BIPAddr_Compare(&addr, &relay_predicate_raddr);
  1459. }
  1460. int peerid_comparator (void *unused, peerid_t *p1, peerid_t *p2)
  1461. {
  1462. if (*p1 < *p2) {
  1463. return -1;
  1464. }
  1465. if (*p1 > *p2) {
  1466. return 1;
  1467. }
  1468. return 0;
  1469. }
  1470. int create_know (struct client_data *from, struct client_data *to, int relay_server, int relay_client)
  1471. {
  1472. ASSERT(from->initstatus == INITSTATUS_COMPLETE)
  1473. ASSERT(!from->dying)
  1474. ASSERT(to->initstatus == INITSTATUS_COMPLETE)
  1475. ASSERT(!to->dying)
  1476. // allocate structure
  1477. struct peer_know *k = malloc(sizeof(*k));
  1478. if (!k) {
  1479. return 0;
  1480. }
  1481. // init arguments
  1482. k->from = from;
  1483. k->to = to;
  1484. k->relay_server = relay_server;
  1485. k->relay_client = relay_client;
  1486. // append to lists
  1487. LinkedList2_Append(&from->know_out_list, &k->from_node);
  1488. LinkedList2_Append(&to->know_in_list, &k->to_node);
  1489. // init and set inform job to inform client 'from' about client 'to'
  1490. BPending_Init(&k->inform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_inform_job_handler, k);
  1491. BPending_Set(&k->inform_job);
  1492. // init uninform job
  1493. BPending_Init(&k->uninform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_uninform_job_handler, k);
  1494. return 1;
  1495. }
  1496. void remove_know (struct peer_know *k)
  1497. {
  1498. // free uninform job
  1499. BPending_Free(&k->uninform_job);
  1500. // free inform job
  1501. BPending_Free(&k->inform_job);
  1502. // remove from lists
  1503. LinkedList2_Remove(&k->to->know_in_list, &k->to_node);
  1504. LinkedList2_Remove(&k->from->know_out_list, &k->from_node);
  1505. // free structure
  1506. free(k);
  1507. }
  1508. void know_inform_job_handler (struct peer_know *k)
  1509. {
  1510. ASSERT(!k->from->dying)
  1511. ASSERT(!k->to->dying)
  1512. client_send_newclient(k->from, k->to, k->relay_server, k->relay_client);
  1513. return;
  1514. }
  1515. void uninform_know (struct peer_know *k)
  1516. {
  1517. ASSERT(!k->from->dying)
  1518. ASSERT(k->to->dying)
  1519. ASSERT(!BPending_IsSet(&k->uninform_job))
  1520. // if 'from' has not been informed about 'to' yet, remove know, otherwise
  1521. // schedule informing 'from' that 'to' is no more
  1522. if (BPending_IsSet(&k->inform_job)) {
  1523. remove_know(k);
  1524. } else {
  1525. BPending_Set(&k->uninform_job);
  1526. }
  1527. }
  1528. void know_uninform_job_handler (struct peer_know *k)
  1529. {
  1530. ASSERT(!k->from->dying)
  1531. ASSERT(k->to->dying)
  1532. ASSERT(!BPending_IsSet(&k->inform_job))
  1533. struct client_data *from = k->from;
  1534. struct client_data *to = k->to;
  1535. // remove know
  1536. remove_know(k);
  1537. // uninform
  1538. client_send_endclient(from, to->id);
  1539. }