server.c 73 KB

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