server.c 71 KB

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