server.c 60 KB

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