BadVPN – Blame information for rev 1

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