server.c 62 KB

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