server.c 63 KB

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