server.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  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. 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. 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. LinkedList2_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. LinkedList2Node *node;
  407. while (node = LinkedList2_GetFirst(&clients)) {
  408. struct client_data *client = UPPER_OBJECT(node, struct client_data, list_node);
  409. // remove outgoing knows
  410. LinkedList2Node *node2;
  411. while (node2 = LinkedList2_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. LinkedList2Node *node3;
  417. while (node3 = LinkedList2_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. LinkedList2Node *flow_node;
  423. while (flow_node = LinkedList2_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. LinkedList2_Append(&clients, &client->list_node);
  770. ASSERT_EXECUTE(BAVL_Insert(&clients_tree, &client->tree_node, NULL))
  771. // init knowledge lists
  772. LinkedList2_Init(&client->know_out_list);
  773. LinkedList2_Init(&client->know_in_list);
  774. // initialize peer flows from us list and tree (flows for sending messages to other clients)
  775. LinkedList2_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(LinkedList2_IsEmpty(&client->know_out_list))
  800. ASSERT(LinkedList2_IsEmpty(&client->know_in_list))
  801. ASSERT(LinkedList2_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. LinkedList2_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. LinkedList2_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. LinkedList2Node *node;
  895. while (node = LinkedList2_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. LinkedList2Node *node;
  927. while (node = LinkedList2_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 = LinkedList2_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. LinkedList2Iterator it;
  949. LinkedList2Iterator_InitForward(&it, &client->know_in_list);
  950. while (node = LinkedList2Iterator_Next(&it)) {
  951. struct peer_know *k = UPPER_OBJECT(node, struct peer_know, to_node);
  952. uninform_know(k);
  953. }
  954. }
  955. void client_dying_job (struct client_data *client)
  956. {
  957. ASSERT(client->dying)
  958. ASSERT(LinkedList2_IsEmpty(&client->know_in_list))
  959. client_dealloc(client);
  960. return;
  961. }
  962. void client_logfunc (struct client_data *client)
  963. {
  964. char addr[BADDR_MAX_PRINT_LEN];
  965. BAddr_Print(&client->addr, addr);
  966. BLog_Append("client %d (%s)", (int)client->id, addr);
  967. if (client->common_name) {
  968. BLog_Append(" (%s)", client->common_name);
  969. }
  970. BLog_Append(": ");
  971. }
  972. void client_log (struct client_data *client, int level, const char *fmt, ...)
  973. {
  974. va_list vl;
  975. va_start(vl, fmt);
  976. BLog_LogViaFuncVarArg((BLog_logfunc)client_logfunc, client, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  977. va_end(vl);
  978. }
  979. void client_disconnect_timer_handler (struct client_data *client)
  980. {
  981. ASSERT(!client->dying)
  982. client_log(client, BLOG_INFO, "timed out");
  983. client_remove(client);
  984. return;
  985. }
  986. void client_connection_handler (struct client_data *client, int event)
  987. {
  988. ASSERT(!client->dying)
  989. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  990. client_log(client, BLOG_INFO, "connection closed");
  991. } else {
  992. client_log(client, BLOG_INFO, "connection error");
  993. }
  994. client_remove(client);
  995. return;
  996. }
  997. void client_sslcon_handler (struct client_data *client, int event)
  998. {
  999. ASSERT(options.ssl)
  1000. ASSERT(!client->dying)
  1001. ASSERT(event == BSSLCONNECTION_EVENT_UP || event == BSSLCONNECTION_EVENT_ERROR)
  1002. ASSERT(!(event == BSSLCONNECTION_EVENT_UP) || client->initstatus == INITSTATUS_HANDSHAKE)
  1003. if (event == BSSLCONNECTION_EVENT_ERROR) {
  1004. client_log(client, BLOG_ERROR, "SSL error");
  1005. client_remove(client);
  1006. return;
  1007. }
  1008. // get client certificate
  1009. CERTCertificate *cert = SSL_PeerCertificate(client->ssl_prfd);
  1010. if (!cert) {
  1011. client_log(client, BLOG_ERROR, "SSL_PeerCertificate failed");
  1012. goto fail0;
  1013. }
  1014. // remember common name
  1015. if (!(client->common_name = CERT_GetCommonName(&cert->subject))) {
  1016. client_log(client, BLOG_NOTICE, "CERT_GetCommonName failed");
  1017. goto fail1;
  1018. }
  1019. // store certificate
  1020. SECItem der = cert->derCert;
  1021. if (der.len > sizeof(client->cert)) {
  1022. client_log(client, BLOG_NOTICE, "client certificate too big");
  1023. goto fail1;
  1024. }
  1025. memcpy(client->cert, der.data, der.len);
  1026. client->cert_len = der.len;
  1027. PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1028. if (!arena) {
  1029. client_log(client, BLOG_ERROR, "PORT_NewArena failed");
  1030. goto fail1;
  1031. }
  1032. // encode certificate
  1033. memset(&der, 0, sizeof(der));
  1034. if (!SEC_ASN1EncodeItem(arena, &der, cert, SEC_ASN1_GET(CERT_CertificateTemplate))) {
  1035. client_log(client, BLOG_ERROR, "SEC_ASN1EncodeItem failed");
  1036. goto fail2;
  1037. }
  1038. // store re-encoded certificate (for compatibility with old clients)
  1039. if (der.len > sizeof(client->cert_old)) {
  1040. client_log(client, BLOG_NOTICE, "client certificate too big");
  1041. goto fail2;
  1042. }
  1043. memcpy(client->cert_old, der.data, der.len);
  1044. client->cert_old_len = der.len;
  1045. // init I/O chains
  1046. if (!client_init_io(client)) {
  1047. goto fail2;
  1048. }
  1049. PORT_FreeArena(arena, PR_FALSE);
  1050. CERT_DestroyCertificate(cert);
  1051. // set client state
  1052. client->initstatus = INITSTATUS_WAITHELLO;
  1053. client_log(client, BLOG_INFO, "handshake complete");
  1054. return;
  1055. // handle errors
  1056. fail2:
  1057. PORT_FreeArena(arena, PR_FALSE);
  1058. fail1:
  1059. CERT_DestroyCertificate(cert);
  1060. fail0:
  1061. client_remove(client);
  1062. }
  1063. void client_decoder_handler_error (struct client_data *client)
  1064. {
  1065. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1066. ASSERT(!client->dying)
  1067. client_log(client, BLOG_ERROR, "decoder error");
  1068. client_remove(client);
  1069. return;
  1070. }
  1071. int client_start_control_packet (struct client_data *client, void **data, int len)
  1072. {
  1073. ASSERT(len >= 0)
  1074. ASSERT(len <= SC_MAX_PAYLOAD)
  1075. ASSERT(!(len > 0) || data)
  1076. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1077. ASSERT(!client->dying)
  1078. ASSERT(client->output_control_packet_len == -1)
  1079. #ifdef SIMULATE_OUT_OF_CONTROL_BUFFER
  1080. uint8_t x;
  1081. BRandom_randomize(&x, sizeof(x));
  1082. if (x < SIMULATE_OUT_OF_CONTROL_BUFFER) {
  1083. client_log(client, BLOG_INFO, "out of control buffer, removing");
  1084. client_remove(client);
  1085. return -1;
  1086. }
  1087. #endif
  1088. // obtain location for writing the packet
  1089. if (!BufferWriter_StartPacket(client->output_control_input, &client->output_control_packet)) {
  1090. // out of buffer, kill client
  1091. client_log(client, BLOG_INFO, "out of control buffer, removing");
  1092. client_remove(client);
  1093. return -1;
  1094. }
  1095. client->output_control_packet_len = len;
  1096. if (data) {
  1097. *data = client->output_control_packet + sizeof(struct sc_header);
  1098. }
  1099. return 0;
  1100. }
  1101. void client_end_control_packet (struct client_data *client, uint8_t type)
  1102. {
  1103. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1104. ASSERT(!client->dying)
  1105. ASSERT(client->output_control_packet_len >= 0)
  1106. ASSERT(client->output_control_packet_len <= SC_MAX_PAYLOAD)
  1107. // write header
  1108. struct sc_header *header = (struct sc_header *)client->output_control_packet;
  1109. header->type = htol8(type);
  1110. // finish writing packet
  1111. BufferWriter_EndPacket(client->output_control_input, sizeof(struct sc_header) + client->output_control_packet_len);
  1112. client->output_control_packet_len = -1;
  1113. }
  1114. int client_send_newclient (struct client_data *client, struct client_data *nc, int relay_server, int relay_client)
  1115. {
  1116. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1117. ASSERT(!client->dying)
  1118. ASSERT(nc->initstatus == INITSTATUS_COMPLETE)
  1119. ASSERT(!nc->dying)
  1120. int flags = 0;
  1121. if (relay_server) {
  1122. flags |= SCID_NEWCLIENT_FLAG_RELAY_SERVER;
  1123. }
  1124. if (relay_client) {
  1125. flags |= SCID_NEWCLIENT_FLAG_RELAY_CLIENT;
  1126. }
  1127. if (options.ssl && client->version > SC_OLDVERSION_NOSSL && nc->version > SC_OLDVERSION_NOSSL) {
  1128. flags |= SCID_NEWCLIENT_FLAG_SSL;
  1129. }
  1130. uint8_t *cert_data = NULL;
  1131. int cert_len = 0;
  1132. if (options.ssl) {
  1133. cert_data = (client->version == SC_OLDVERSION_BROKENCERT ? nc->cert_old : nc->cert);
  1134. cert_len = (client->version == SC_OLDVERSION_BROKENCERT ? nc->cert_old_len : nc->cert_len);
  1135. }
  1136. struct sc_server_newclient *pack;
  1137. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_newclient) + cert_len) < 0) {
  1138. return -1;
  1139. }
  1140. pack->id = htol16(nc->id);
  1141. pack->flags = htol16(flags);
  1142. if (cert_len > 0) {
  1143. memcpy(pack + 1, cert_data, cert_len);
  1144. }
  1145. client_end_control_packet(client, SCID_NEWCLIENT);
  1146. return 0;
  1147. }
  1148. int client_send_endclient (struct client_data *client, peerid_t end_id)
  1149. {
  1150. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1151. ASSERT(!client->dying)
  1152. struct sc_server_endclient *pack;
  1153. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_endclient)) < 0) {
  1154. return -1;
  1155. }
  1156. pack->id = htol16(end_id);
  1157. client_end_control_packet(client, SCID_ENDCLIENT);
  1158. return 0;
  1159. }
  1160. void client_input_handler_send (struct client_data *client, uint8_t *data, int data_len)
  1161. {
  1162. ASSERT(data_len >= 0)
  1163. ASSERT(data_len <= SC_MAX_ENC)
  1164. ASSERT(INITSTATUS_HASLINK(client->initstatus))
  1165. ASSERT(!client->dying)
  1166. // accept packet
  1167. PacketPassInterface_Done(&client->input_interface);
  1168. // restart disconnect timer
  1169. BReactor_SetTimer(&ss, &client->disconnect_timer);
  1170. // parse header
  1171. if (data_len < sizeof(struct sc_header)) {
  1172. client_log(client, BLOG_NOTICE, "packet too short");
  1173. client_remove(client);
  1174. return;
  1175. }
  1176. struct sc_header *header = (struct sc_header *)data;
  1177. data += sizeof(*header);
  1178. data_len -= sizeof(*header);
  1179. uint8_t type = ltoh8(header->type);
  1180. ASSERT(data_len >= 0)
  1181. ASSERT(data_len <= SC_MAX_PAYLOAD)
  1182. // perform action based on packet type
  1183. switch (type) {
  1184. case SCID_KEEPALIVE:
  1185. client_log(client, BLOG_DEBUG, "received keep-alive");
  1186. return;
  1187. case SCID_CLIENTHELLO:
  1188. process_packet_hello(client, data, data_len);
  1189. return;
  1190. case SCID_OUTMSG:
  1191. process_packet_outmsg(client, data, data_len);
  1192. return;
  1193. case SCID_RESETPEER:
  1194. process_packet_resetpeer(client, data, data_len);
  1195. return;
  1196. case SCID_ACCEPTPEER:
  1197. process_packet_acceptpeer(client, data, data_len);
  1198. return;
  1199. default:
  1200. client_log(client, BLOG_NOTICE, "unknown packet type %d, removing", (int)type);
  1201. client_remove(client);
  1202. return;
  1203. }
  1204. }
  1205. void process_packet_hello (struct client_data *client, uint8_t *data, int data_len)
  1206. {
  1207. if (client->initstatus != INITSTATUS_WAITHELLO) {
  1208. client_log(client, BLOG_NOTICE, "hello: not expected");
  1209. client_remove(client);
  1210. return;
  1211. }
  1212. if (data_len != sizeof(struct sc_client_hello)) {
  1213. client_log(client, BLOG_NOTICE, "hello: invalid length");
  1214. client_remove(client);
  1215. return;
  1216. }
  1217. struct sc_client_hello *msg = (struct sc_client_hello *)data;
  1218. client->version = ltoh16(msg->version);
  1219. switch (client->version) {
  1220. case SC_VERSION:
  1221. case SC_OLDVERSION_NOSSL:
  1222. case SC_OLDVERSION_BROKENCERT:
  1223. break;
  1224. default:
  1225. client_log(client, BLOG_ERROR, "hello: unknown version (%d)", client->version);
  1226. client_remove(client);
  1227. return;
  1228. }
  1229. client_log(client, BLOG_INFO, "received hello");
  1230. // set client state to complete
  1231. client->initstatus = INITSTATUS_COMPLETE;
  1232. // publish client
  1233. for (LinkedList2Node *list_node = LinkedList2_GetFirst(&clients); list_node; list_node = LinkedList2Node_Next(list_node)) {
  1234. struct client_data *client2 = UPPER_OBJECT(list_node, struct client_data, list_node);
  1235. if (client2 == client || client2->initstatus != INITSTATUS_COMPLETE || client2->dying || !clients_allowed(client, client2)) {
  1236. continue;
  1237. }
  1238. // create flow from client to client2
  1239. struct peer_flow *flow_to = peer_flow_create(client, client2);
  1240. if (!flow_to) {
  1241. client_log(client, BLOG_ERROR, "failed to allocate flow to %d", (int)client2->id);
  1242. goto fail;
  1243. }
  1244. // create flow from client2 to client
  1245. struct peer_flow *flow_from = peer_flow_create(client2, client);
  1246. if (!flow_from) {
  1247. client_log(client, BLOG_ERROR, "failed to allocate flow from %d", (int)client2->id);
  1248. goto fail;
  1249. }
  1250. // set opposite flow pointers
  1251. flow_to->opposite = flow_from;
  1252. flow_from->opposite = flow_to;
  1253. // launch pair
  1254. if (!launch_pair(flow_to)) {
  1255. return;
  1256. }
  1257. }
  1258. // send hello
  1259. struct sc_server_hello *pack;
  1260. if (client_start_control_packet(client, (void **)&pack, sizeof(struct sc_server_hello)) < 0) {
  1261. return;
  1262. }
  1263. pack->flags = htol16(0);
  1264. pack->id = htol16(client->id);
  1265. pack->clientAddr = (client->addr.type == BADDR_TYPE_IPV4 ? client->addr.ipv4.ip : hton32(0));
  1266. client_end_control_packet(client, SCID_SERVERHELLO);
  1267. return;
  1268. fail:
  1269. client_remove(client);
  1270. }
  1271. void process_packet_outmsg (struct client_data *client, uint8_t *data, int data_len)
  1272. {
  1273. if (client->initstatus != INITSTATUS_COMPLETE) {
  1274. client_log(client, BLOG_NOTICE, "outmsg: not expected");
  1275. client_remove(client);
  1276. return;
  1277. }
  1278. if (data_len < sizeof(struct sc_client_outmsg)) {
  1279. client_log(client, BLOG_NOTICE, "outmsg: wrong size");
  1280. client_remove(client);
  1281. return;
  1282. }
  1283. struct sc_client_outmsg *msg = (struct sc_client_outmsg *)data;
  1284. peerid_t id = ltoh16(msg->clientid);
  1285. int payload_size = data_len - sizeof(struct sc_client_outmsg);
  1286. if (payload_size > SC_MAX_MSGLEN) {
  1287. client_log(client, BLOG_NOTICE, "outmsg: too large payload");
  1288. client_remove(client);
  1289. return;
  1290. }
  1291. uint8_t *payload = data + sizeof(struct sc_client_outmsg);
  1292. // lookup flow to destination client
  1293. struct peer_flow *flow = find_flow(client, id);
  1294. if (!flow) {
  1295. client_log(client, BLOG_INFO, "no flow for message to %d", (int)id);
  1296. return;
  1297. }
  1298. // if pair is resetting, ignore message
  1299. if (flow->resetting || flow->opposite->resetting) {
  1300. client_log(client, BLOG_INFO, "pair is resetting; not forwarding message to %d", (int)id);
  1301. return;
  1302. }
  1303. // if sending client hasn't accepted yet, ignore message
  1304. if (!flow->accepted) {
  1305. client_log(client, BLOG_INFO, "client hasn't accepted; not forwarding message to %d", (int)id);
  1306. return;
  1307. }
  1308. #ifdef SIMULATE_OUT_OF_FLOW_BUFFER
  1309. uint8_t x;
  1310. BRandom_randomize(&x, sizeof(x));
  1311. if (x < SIMULATE_OUT_OF_FLOW_BUFFER) {
  1312. client_log(client, BLOG_WARNING, "simulating error; resetting to %d", (int)flow->dest_client->id);
  1313. peer_flow_start_reset(flow);
  1314. return;
  1315. }
  1316. #endif
  1317. // send packet
  1318. struct sc_server_inmsg *pack;
  1319. if (!peer_flow_start_packet(flow, (void **)&pack, sizeof(struct sc_server_inmsg) + payload_size)) {
  1320. // out of buffer, reset these two clients
  1321. client_log(client, BLOG_WARNING, "out of buffer; resetting to %d", (int)flow->dest_client->id);
  1322. peer_flow_start_reset(flow);
  1323. return;
  1324. }
  1325. pack->clientid = htol16(client->id);
  1326. memcpy((uint8_t *)(pack + 1), payload, payload_size);
  1327. peer_flow_end_packet(flow, SCID_INMSG);
  1328. }
  1329. void process_packet_resetpeer (struct client_data *client, uint8_t *data, int data_len)
  1330. {
  1331. if (client->initstatus != INITSTATUS_COMPLETE) {
  1332. client_log(client, BLOG_NOTICE, "resetpeer: not expected");
  1333. client_remove(client);
  1334. return;
  1335. }
  1336. if (data_len != sizeof(struct sc_client_resetpeer)) {
  1337. client_log(client, BLOG_NOTICE, "resetpeer: wrong size");
  1338. client_remove(client);
  1339. return;
  1340. }
  1341. struct sc_client_resetpeer *msg = (struct sc_client_resetpeer *)data;
  1342. peerid_t id = ltoh16(msg->clientid);
  1343. // lookup flow to destination client
  1344. struct peer_flow *flow = find_flow(client, id);
  1345. if (!flow) {
  1346. client_log(client, BLOG_INFO, "no flow for reset to %d", (int)id);
  1347. return;
  1348. }
  1349. // if pair is resetting, ignore message
  1350. if (flow->resetting || flow->opposite->resetting) {
  1351. client_log(client, BLOG_INFO, "pair is resetting; not resetting to %d", (int)id);
  1352. return;
  1353. }
  1354. // if sending client hasn't accepted yet, ignore message
  1355. if (!flow->accepted) {
  1356. client_log(client, BLOG_INFO, "client hasn't accepted; not resetting to %d", (int)id);
  1357. return;
  1358. }
  1359. client_log(client, BLOG_WARNING, "resetting to %d", (int)flow->dest_client->id);
  1360. // reset clients
  1361. peer_flow_start_reset(flow);
  1362. }
  1363. void process_packet_acceptpeer (struct client_data *client, uint8_t *data, int data_len)
  1364. {
  1365. if (client->initstatus != INITSTATUS_COMPLETE) {
  1366. client_log(client, BLOG_NOTICE, "acceptpeer: not expected");
  1367. client_remove(client);
  1368. return;
  1369. }
  1370. if (data_len != sizeof(struct sc_client_acceptpeer)) {
  1371. client_log(client, BLOG_NOTICE, "acceptpeer: wrong size");
  1372. client_remove(client);
  1373. return;
  1374. }
  1375. struct sc_client_acceptpeer *msg = (struct sc_client_acceptpeer *)data;
  1376. peerid_t id = ltoh16(msg->clientid);
  1377. // lookup flow to destination client
  1378. struct peer_flow *flow = find_flow(client, id);
  1379. if (!flow) {
  1380. // the specified client has probably gone away but the sending client didn't know
  1381. // that yet; this is expected
  1382. client_log(client, BLOG_INFO, "acceptpeer: no flow to %d", (int)id);
  1383. return;
  1384. }
  1385. // client can only accept once
  1386. if (flow->accepted) {
  1387. // the previous accept is probably from an old client with the same ID as this one;
  1388. // this is bad, disconnect client
  1389. client_log(client, BLOG_ERROR, "acceptpeer: already accepted to %d", (int)id);
  1390. client_remove(client);
  1391. return;
  1392. }
  1393. client_log(client, BLOG_INFO, "accepted %d", (int)id);
  1394. // set accepted
  1395. flow->accepted = 1;
  1396. // if pair is resetting, continue
  1397. if (flow->resetting) {
  1398. peer_flow_drive_reset(flow);
  1399. } else if (flow->opposite->resetting) {
  1400. peer_flow_drive_reset(flow->opposite);
  1401. }
  1402. }
  1403. struct peer_flow * peer_flow_create (struct client_data *src_client, struct client_data *dest_client)
  1404. {
  1405. ASSERT(src_client->initstatus == INITSTATUS_COMPLETE)
  1406. ASSERT(!src_client->dying)
  1407. ASSERT(dest_client->initstatus == INITSTATUS_COMPLETE)
  1408. ASSERT(!dest_client->dying)
  1409. ASSERT(!find_flow(src_client, dest_client->id))
  1410. // allocate flow structure
  1411. struct peer_flow *flow = (struct peer_flow *)malloc(sizeof(*flow));
  1412. if (!flow) {
  1413. BLog(BLOG_ERROR, "malloc failed");
  1414. goto fail0;
  1415. }
  1416. // set source and destination
  1417. flow->src_client = src_client;
  1418. flow->dest_client = dest_client;
  1419. flow->dest_client_id = dest_client->id;
  1420. // add to source list and tree
  1421. LinkedList2_Append(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1422. ASSERT_EXECUTE(BAVL_Insert(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node, NULL))
  1423. // add to destination client list
  1424. LinkedList2_Append(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1425. // have no I/O
  1426. flow->have_io = 0;
  1427. // init reset timer
  1428. BTimer_Init(&flow->reset_timer, CLIENT_RESET_TIME, (BTimer_handler)peer_flow_reset_timer_handler, flow);
  1429. return flow;
  1430. fail0:
  1431. return NULL;
  1432. }
  1433. void peer_flow_dealloc (struct peer_flow *flow)
  1434. {
  1435. if (flow->have_io) { PacketPassFairQueueFlow_AssertFree(&flow->qflow); }
  1436. // free reset timer
  1437. BReactor_RemoveTimer(&ss, &flow->reset_timer);
  1438. // free I/O
  1439. if (flow->have_io) {
  1440. peer_flow_free_io(flow);
  1441. }
  1442. // remove from destination client list
  1443. LinkedList2_Remove(&flow->dest_client->output_peers_flows, &flow->dest_list_node);
  1444. // remove from source list and hash table
  1445. if (flow->src_client) {
  1446. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1447. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1448. }
  1449. // free memory
  1450. free(flow);
  1451. }
  1452. int peer_flow_init_io (struct peer_flow *flow)
  1453. {
  1454. ASSERT(!flow->have_io)
  1455. // init queue flow
  1456. PacketPassFairQueueFlow_Init(&flow->qflow, &flow->dest_client->output_peers_fairqueue);
  1457. // init PacketProtoFlow
  1458. if (!PacketProtoFlow_Init(
  1459. &flow->oflow, SC_MAX_ENC, CLIENT_PEER_FLOW_BUFFER_MIN_PACKETS,
  1460. PacketPassFairQueueFlow_GetInput(&flow->qflow), BReactor_PendingGroup(&ss)
  1461. )) {
  1462. BLog(BLOG_ERROR, "PacketProtoFlow_Init failed");
  1463. goto fail1;
  1464. }
  1465. flow->input = PacketProtoFlow_GetInput(&flow->oflow);
  1466. // set no packet
  1467. flow->packet_len = -1;
  1468. // set have I/O
  1469. flow->have_io = 1;
  1470. return 1;
  1471. fail1:
  1472. PacketPassFairQueueFlow_Free(&flow->qflow);
  1473. return 0;
  1474. }
  1475. void peer_flow_free_io (struct peer_flow *flow)
  1476. {
  1477. ASSERT(flow->have_io)
  1478. PacketPassFairQueueFlow_AssertFree(&flow->qflow);
  1479. // free PacketProtoFlow
  1480. PacketProtoFlow_Free(&flow->oflow);
  1481. // free queue flow
  1482. PacketPassFairQueueFlow_Free(&flow->qflow);
  1483. // set have no I/O
  1484. flow->have_io = 0;
  1485. }
  1486. void peer_flow_disconnect (struct peer_flow *flow)
  1487. {
  1488. ASSERT(flow->src_client)
  1489. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1490. ASSERT(!flow->dest_client->dying)
  1491. ASSERT(flow->have_io)
  1492. ASSERT(PacketPassFairQueueFlow_IsBusy(&flow->qflow))
  1493. // stop reset timer
  1494. BReactor_RemoveTimer(&ss, &flow->reset_timer);
  1495. // remove from source list and hash table
  1496. BAVL_Remove(&flow->src_client->peer_out_flows_tree, &flow->src_tree_node);
  1497. LinkedList2_Remove(&flow->src_client->peer_out_flows_list, &flow->src_list_node);
  1498. // set no source
  1499. flow->src_client = NULL;
  1500. // set busy handler
  1501. PacketPassFairQueueFlow_SetBusyHandler(&flow->qflow, (PacketPassFairQueue_handler_busy)peer_flow_handler_canremove, flow);
  1502. }
  1503. int peer_flow_start_packet (struct peer_flow *flow, void **data, int len)
  1504. {
  1505. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1506. ASSERT(!flow->dest_client->dying)
  1507. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1508. ASSERT(!flow->src_client->dying)
  1509. ASSERT(!flow->resetting)
  1510. ASSERT(!flow->opposite->resetting)
  1511. ASSERT(flow->have_io)
  1512. ASSERT(flow->packet_len == -1)
  1513. ASSERT(len >= 0)
  1514. ASSERT(len <= SC_MAX_PAYLOAD)
  1515. ASSERT(!(len > 0) || data)
  1516. // obtain location for writing the packet
  1517. if (!BufferWriter_StartPacket(flow->input, &flow->packet)) {
  1518. return 0;
  1519. }
  1520. // remember packet length
  1521. flow->packet_len = len;
  1522. if (data) {
  1523. *data = flow->packet + sizeof(struct sc_header);
  1524. }
  1525. return 1;
  1526. }
  1527. void peer_flow_end_packet (struct peer_flow *flow, uint8_t type)
  1528. {
  1529. ASSERT(flow->have_io)
  1530. ASSERT(flow->packet_len >= 0)
  1531. ASSERT(flow->packet_len <= SC_MAX_PAYLOAD)
  1532. // write header
  1533. struct sc_header *header = (struct sc_header *)flow->packet;
  1534. header->type = type;
  1535. // finish writing packet
  1536. BufferWriter_EndPacket(flow->input, sizeof(struct sc_header) + flow->packet_len);
  1537. // set have no packet
  1538. flow->packet_len = -1;
  1539. }
  1540. void peer_flow_handler_canremove (struct peer_flow *flow)
  1541. {
  1542. ASSERT(!flow->src_client)
  1543. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1544. ASSERT(!flow->dest_client->dying)
  1545. ASSERT(flow->have_io)
  1546. PacketPassFairQueueFlow_AssertFree(&flow->qflow);
  1547. client_log(flow->dest_client, BLOG_DEBUG, "removing old flow");
  1548. peer_flow_dealloc(flow);
  1549. return;
  1550. }
  1551. void peer_flow_start_reset (struct peer_flow *flow)
  1552. {
  1553. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1554. ASSERT(!flow->src_client->dying)
  1555. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1556. ASSERT(!flow->dest_client->dying)
  1557. ASSERT(!flow->resetting)
  1558. ASSERT(!flow->opposite->resetting)
  1559. ASSERT(flow->have_io)
  1560. ASSERT(flow->opposite->have_io)
  1561. client_log(flow->src_client, BLOG_INFO, "starting reset to %d", (int)flow->dest_client->id);
  1562. // set resetting
  1563. flow->resetting = 1;
  1564. peer_flow_drive_reset(flow);
  1565. }
  1566. void peer_flow_drive_reset (struct peer_flow *flow)
  1567. {
  1568. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1569. ASSERT(!flow->src_client->dying)
  1570. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1571. ASSERT(!flow->dest_client->dying)
  1572. ASSERT(flow->resetting)
  1573. ASSERT(!flow->opposite->resetting)
  1574. ASSERT(!BTimer_IsRunning(&flow->reset_timer))
  1575. // try to free I/O
  1576. if (flow->have_io) {
  1577. if (PacketPassFairQueueFlow_IsBusy(&flow->qflow)) {
  1578. PacketPassFairQueueFlow_SetBusyHandler(&flow->qflow, (PacketPassFairQueue_handler_busy)peer_flow_reset_qflow_handler_busy, flow);
  1579. } else {
  1580. peer_flow_free_io(flow);
  1581. }
  1582. }
  1583. // try to free opposite I/O
  1584. if (flow->opposite->have_io) {
  1585. if (PacketPassFairQueueFlow_IsBusy(&flow->opposite->qflow)) {
  1586. PacketPassFairQueueFlow_SetBusyHandler(&flow->opposite->qflow, (PacketPassFairQueue_handler_busy)peer_flow_reset_qflow_handler_busy, flow->opposite);
  1587. } else {
  1588. peer_flow_free_io(flow->opposite);
  1589. }
  1590. }
  1591. // if we still got some I/O, or some client hasn't accepted yet, wait
  1592. if (flow->have_io || flow->opposite->have_io || !flow->accepted || !flow->opposite->accepted) {
  1593. return;
  1594. }
  1595. // set reset timer
  1596. BReactor_SetTimer(&ss, &flow->reset_timer);
  1597. }
  1598. void peer_flow_reset_qflow_handler_busy (struct peer_flow *flow)
  1599. {
  1600. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1601. ASSERT(!flow->src_client->dying)
  1602. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1603. ASSERT(!flow->dest_client->dying)
  1604. ASSERT(flow->resetting || flow->opposite->resetting)
  1605. ASSERT(flow->have_io)
  1606. ASSERT(!PacketPassFairQueueFlow_IsBusy(&flow->qflow))
  1607. if (flow->resetting) {
  1608. peer_flow_drive_reset(flow);
  1609. } else {
  1610. peer_flow_drive_reset(flow->opposite);
  1611. }
  1612. }
  1613. void peer_flow_reset_timer_handler (struct peer_flow *flow)
  1614. {
  1615. ASSERT(flow->src_client->initstatus == INITSTATUS_COMPLETE)
  1616. ASSERT(!flow->src_client->dying)
  1617. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1618. ASSERT(!flow->dest_client->dying)
  1619. ASSERT(flow->resetting)
  1620. ASSERT(!flow->opposite->resetting)
  1621. ASSERT(!flow->have_io)
  1622. ASSERT(!flow->opposite->have_io)
  1623. ASSERT(flow->accepted)
  1624. ASSERT(flow->opposite->accepted)
  1625. client_log(flow->src_client, BLOG_INFO, "finally resetting to %d", (int)flow->dest_client->id);
  1626. struct peer_know *know = flow->know;
  1627. struct peer_know *know_opposite = flow->opposite->know;
  1628. // launch pair
  1629. if (!launch_pair(flow)) {
  1630. return;
  1631. }
  1632. // remove old knows
  1633. uninform_know(know);
  1634. uninform_know(know_opposite);
  1635. }
  1636. peerid_t new_client_id (void)
  1637. {
  1638. ASSERT(clients_num < MAX_CLIENTS)
  1639. for (int i = 0; i < MAX_CLIENTS; i++) {
  1640. peerid_t id = clients_nextid++;
  1641. if (!find_client_by_id(id)) {
  1642. return id;
  1643. }
  1644. }
  1645. ASSERT(0)
  1646. return 42;
  1647. }
  1648. struct client_data * find_client_by_id (peerid_t id)
  1649. {
  1650. BAVLNode *node;
  1651. if (!(node = BAVL_LookupExact(&clients_tree, &id))) {
  1652. return NULL;
  1653. }
  1654. return UPPER_OBJECT(node, struct client_data, tree_node);
  1655. }
  1656. int clients_allowed (struct client_data *client1, struct client_data *client2)
  1657. {
  1658. ASSERT(client1->initstatus == INITSTATUS_COMPLETE)
  1659. ASSERT(!client1->dying)
  1660. ASSERT(client2->initstatus == INITSTATUS_COMPLETE)
  1661. ASSERT(!client2->dying)
  1662. if (!options.comm_predicate) {
  1663. return 1;
  1664. }
  1665. // set values to compare against
  1666. comm_predicate_p1name = (client1->common_name ? client1->common_name : "");
  1667. comm_predicate_p2name = (client2->common_name ? client2->common_name : "");
  1668. BAddr_GetIPAddr(&client1->addr, &comm_predicate_p1addr);
  1669. BAddr_GetIPAddr(&client2->addr, &comm_predicate_p2addr);
  1670. // evaluate predicate
  1671. int res = BPredicate_Eval(&comm_predicate);
  1672. if (res < 0) {
  1673. return 0;
  1674. }
  1675. return res;
  1676. }
  1677. int comm_predicate_func_p1name_cb (void *user, void **args)
  1678. {
  1679. char *arg = (char *)args[0];
  1680. return (!strcmp(arg, comm_predicate_p1name));
  1681. }
  1682. int comm_predicate_func_p2name_cb (void *user, void **args)
  1683. {
  1684. char *arg = (char *)args[0];
  1685. return (!strcmp(arg, comm_predicate_p2name));
  1686. }
  1687. int comm_predicate_func_p1addr_cb (void *user, void **args)
  1688. {
  1689. char *arg = (char *)args[0];
  1690. BIPAddr addr;
  1691. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1692. BLog(BLOG_WARNING, "failed to parse address");
  1693. return -1;
  1694. }
  1695. return BIPAddr_Compare(&addr, &comm_predicate_p1addr);
  1696. }
  1697. int comm_predicate_func_p2addr_cb (void *user, void **args)
  1698. {
  1699. char *arg = (char *)args[0];
  1700. BIPAddr addr;
  1701. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1702. BLog(BLOG_WARNING, "failed to parse address");
  1703. return -1;
  1704. }
  1705. return BIPAddr_Compare(&addr, &comm_predicate_p2addr);
  1706. }
  1707. int relay_allowed (struct client_data *client, struct client_data *relay)
  1708. {
  1709. if (!options.relay_predicate) {
  1710. return 0;
  1711. }
  1712. // set values to compare against
  1713. relay_predicate_pname = (client->common_name ? client->common_name : "");
  1714. relay_predicate_rname = (relay->common_name ? relay->common_name : "");
  1715. BAddr_GetIPAddr(&client->addr, &relay_predicate_paddr);
  1716. BAddr_GetIPAddr(&relay->addr, &relay_predicate_raddr);
  1717. // evaluate predicate
  1718. int res = BPredicate_Eval(&relay_predicate);
  1719. if (res < 0) {
  1720. return 0;
  1721. }
  1722. return res;
  1723. }
  1724. int relay_predicate_func_pname_cb (void *user, void **args)
  1725. {
  1726. char *arg = (char *)args[0];
  1727. return (!strcmp(arg, relay_predicate_pname));
  1728. }
  1729. int relay_predicate_func_rname_cb (void *user, void **args)
  1730. {
  1731. char *arg = (char *)args[0];
  1732. return (!strcmp(arg, relay_predicate_rname));
  1733. }
  1734. int relay_predicate_func_paddr_cb (void *user, void **args)
  1735. {
  1736. char *arg = (char *)args[0];
  1737. BIPAddr addr;
  1738. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1739. BLog(BLOG_ERROR, "paddr: failed to parse address");
  1740. return -1;
  1741. }
  1742. return BIPAddr_Compare(&addr, &relay_predicate_paddr);
  1743. }
  1744. int relay_predicate_func_raddr_cb (void *user, void **args)
  1745. {
  1746. char *arg = (char *)args[0];
  1747. BIPAddr addr;
  1748. if (!BIPAddr_Resolve(&addr, arg, 1)) {
  1749. BLog(BLOG_ERROR, "raddr: failed to parse address");
  1750. return -1;
  1751. }
  1752. return BIPAddr_Compare(&addr, &relay_predicate_raddr);
  1753. }
  1754. int peerid_comparator (void *unused, peerid_t *p1, peerid_t *p2)
  1755. {
  1756. return B_COMPARE(*p1, *p2);
  1757. }
  1758. struct peer_know * create_know (struct client_data *from, struct client_data *to, int relay_server, int relay_client)
  1759. {
  1760. ASSERT(from->initstatus == INITSTATUS_COMPLETE)
  1761. ASSERT(!from->dying)
  1762. ASSERT(to->initstatus == INITSTATUS_COMPLETE)
  1763. ASSERT(!to->dying)
  1764. // allocate structure
  1765. struct peer_know *k = (struct peer_know *)malloc(sizeof(*k));
  1766. if (!k) {
  1767. return NULL;
  1768. }
  1769. // init arguments
  1770. k->from = from;
  1771. k->to = to;
  1772. k->relay_server = relay_server;
  1773. k->relay_client = relay_client;
  1774. // append to lists
  1775. LinkedList2_Append(&from->know_out_list, &k->from_node);
  1776. LinkedList2_Append(&to->know_in_list, &k->to_node);
  1777. // init and set inform job to inform client 'from' about client 'to'
  1778. BPending_Init(&k->inform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_inform_job_handler, k);
  1779. BPending_Set(&k->inform_job);
  1780. // init uninform job
  1781. BPending_Init(&k->uninform_job, BReactor_PendingGroup(&ss), (BPending_handler)know_uninform_job_handler, k);
  1782. return k;
  1783. }
  1784. void remove_know (struct peer_know *k)
  1785. {
  1786. // free uninform job
  1787. BPending_Free(&k->uninform_job);
  1788. // free inform job
  1789. BPending_Free(&k->inform_job);
  1790. // remove from lists
  1791. LinkedList2_Remove(&k->to->know_in_list, &k->to_node);
  1792. LinkedList2_Remove(&k->from->know_out_list, &k->from_node);
  1793. // free structure
  1794. free(k);
  1795. }
  1796. void know_inform_job_handler (struct peer_know *k)
  1797. {
  1798. ASSERT(!k->from->dying)
  1799. ASSERT(!k->to->dying)
  1800. client_send_newclient(k->from, k->to, k->relay_server, k->relay_client);
  1801. return;
  1802. }
  1803. void uninform_know (struct peer_know *k)
  1804. {
  1805. ASSERT(!k->from->dying)
  1806. // if 'from' has not been informed about 'to' yet, remove know, otherwise
  1807. // schedule informing 'from' that 'to' is no more
  1808. if (BPending_IsSet(&k->inform_job)) {
  1809. remove_know(k);
  1810. } else {
  1811. BPending_Set(&k->uninform_job);
  1812. }
  1813. }
  1814. void know_uninform_job_handler (struct peer_know *k)
  1815. {
  1816. ASSERT(!k->from->dying)
  1817. ASSERT(!BPending_IsSet(&k->inform_job))
  1818. struct client_data *from = k->from;
  1819. struct client_data *to = k->to;
  1820. // remove know
  1821. remove_know(k);
  1822. // uninform
  1823. client_send_endclient(from, to->id);
  1824. }
  1825. int launch_pair (struct peer_flow *flow_to)
  1826. {
  1827. struct client_data *client = flow_to->src_client;
  1828. struct client_data *client2 = flow_to->dest_client;
  1829. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1830. ASSERT(!client->dying)
  1831. ASSERT(client2->initstatus == INITSTATUS_COMPLETE)
  1832. ASSERT(!client2->dying)
  1833. ASSERT(!flow_to->have_io)
  1834. ASSERT(!flow_to->opposite->have_io)
  1835. ASSERT(!BTimer_IsRunning(&flow_to->reset_timer))
  1836. ASSERT(!BTimer_IsRunning(&flow_to->opposite->reset_timer))
  1837. // init I/O
  1838. if (!peer_flow_init_io(flow_to)) {
  1839. goto fail;
  1840. }
  1841. // init opposite I/O
  1842. if (!peer_flow_init_io(flow_to->opposite)) {
  1843. goto fail;
  1844. }
  1845. // determine relay relations
  1846. int relay_to = relay_allowed(client, client2);
  1847. int relay_from = relay_allowed(client2, client);
  1848. // create know to
  1849. struct peer_know *know_to = create_know(client, client2, relay_to, relay_from);
  1850. if (!know_to) {
  1851. client_log(client, BLOG_ERROR, "failed to allocate know to %d", (int)client2->id);
  1852. goto fail;
  1853. }
  1854. // create know from
  1855. struct peer_know *know_from = create_know(client2, client, relay_from, relay_to);
  1856. if (!know_from) {
  1857. client_log(client, BLOG_ERROR, "failed to allocate know from %d", (int)client2->id);
  1858. goto fail;
  1859. }
  1860. // set know pointers in flows
  1861. flow_to->know = know_to;
  1862. flow_to->opposite->know = know_from;
  1863. // set not accepted, or assume accepted for old version
  1864. flow_to->accepted = (flow_to->src_client->version <= SC_OLDVERSION_NOSSL);
  1865. flow_to->opposite->accepted = (flow_to->opposite->src_client->version <= SC_OLDVERSION_NOSSL);
  1866. // set not resetting
  1867. flow_to->resetting = 0;
  1868. flow_to->opposite->resetting = 0;
  1869. return 1;
  1870. fail:
  1871. client_remove(client);
  1872. return 0;
  1873. }
  1874. struct peer_flow * find_flow (struct client_data *client, peerid_t dest_id)
  1875. {
  1876. ASSERT(client->initstatus == INITSTATUS_COMPLETE)
  1877. ASSERT(!client->dying)
  1878. BAVLNode *node = BAVL_LookupExact(&client->peer_out_flows_tree, &dest_id);
  1879. if (!node) {
  1880. return NULL;
  1881. }
  1882. struct peer_flow *flow = UPPER_OBJECT(node, struct peer_flow, src_tree_node);
  1883. ASSERT(flow->dest_client->id == dest_id)
  1884. ASSERT(flow->dest_client->initstatus == INITSTATUS_COMPLETE)
  1885. ASSERT(!flow->dest_client->dying)
  1886. return flow;
  1887. }