server.c 59 KB

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