server.c 64 KB

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