server.c 63 KB

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