server.c 61 KB

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