server.c 72 KB

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