server.c 60 KB

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