server.c 64 KB

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