server.c 71 KB

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