server.c 72 KB

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