server.c 70 KB

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