server.c 74 KB

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