server.c 62 KB

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