server.c 60 KB

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