server.c 72 KB

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