1 #if defined(NO_BUFFER) || defined(NO_IP) || defined(NO_OPENSSL)
2 #error "Badness, NO_BUFFER, NO_IP or NO_OPENSSL is defined, turn them *off*"
5 /* Include our bits'n'pieces */
9 /********************************************/
10 /* Our local types that specify our "world" */
11 /********************************************/
13 /* These represent running "tunnels". Eg. if you wanted to do SSL in a
14 * "message-passing" scanario, the "int" file-descriptors might be replaced by
15 * thread or process IDs, and the "select" code might be replaced by message
16 * handling code. Whatever. */
17 typedef struct _tunala_item_t {
18 /* The underlying SSL state machine. This is a data-only processing unit
19 * and we communicate with it by talking to its four "buffers". */
21 /* The file-descriptors for the "dirty" (encrypted) side of the SSL
22 * setup. In actuality, this is typically a socket and both values are
24 int dirty_read, dirty_send;
25 /* The file-descriptors for the "clean" (unencrypted) side of the SSL
26 * setup. These could be stdin/stdout, a socket (both values the same),
27 * or whatever you like. */
28 int clean_read, clean_send;
31 /* This structure is used as the data for running the main loop. Namely, in a
32 * network format such as this, it is stuff for select() - but as pointed out,
33 * when moving the real-world to somewhere else, this might be replaced by
34 * something entirely different. It's basically the stuff that controls when
35 * it's time to do some "work". */
36 typedef struct _select_sets_t {
37 int max; /* As required as the first argument to select() */
38 fd_set reads, sends, excepts; /* As passed to select() */
40 typedef struct _tunala_selector_t {
41 select_sets_t last_selected; /* Results of the last select() */
42 select_sets_t next_select; /* What we'll next select on */
45 /* This structure is *everything*. We do it to avoid the use of globals so that,
46 * for example, it would be easier to shift things around between async-IO,
47 * thread-based, or multi-fork()ed (or combinations thereof). */
48 typedef struct _tunala_world_t {
49 /* The file-descriptor we "listen" on for new connections */
51 /* The array of tunnels */
52 tunala_item_t *tunnels;
53 /* the number of tunnels in use and allocated, respectively */
54 unsigned int tunnels_used, tunnels_size;
55 /* Our outside "loop" context stuff */
56 tunala_selector_t selector;
57 /* Our SSL_CTX, which is configured as the SSL client or server and has
58 * the various cert-settings and callbacks configured. */
60 /* Simple flag with complex logic :-) Indicates whether we're an SSL
61 * server or an SSL client. */
65 /*****************************/
66 /* Internal static functions */
67 /*****************************/
69 static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
70 const char *CAfile, const char *cert, const char *key,
71 const char *dcert, const char *dkey, const char *cipher_list,
72 int out_state, int out_verify, int verify_mode,
73 unsigned int verify_depth);
74 static void selector_init(tunala_selector_t *selector);
75 static void selector_add_listener(tunala_selector_t *selector, int fd);
76 static void selector_add_tunala(tunala_selector_t *selector, tunala_item_t *t);
77 static int selector_select(tunala_selector_t *selector);
78 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
79 * which case *newfd is populated. */
80 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd);
81 static int tunala_world_new_item(tunala_world_t *world, int fd,
82 const unsigned char *ip, unsigned short port);
83 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx);
84 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item);
86 /*********************************************/
87 /* MAIN FUNCTION (and its utility functions) */
88 /*********************************************/
90 static const char *def_proxyhost = "127.0.0.1:443";
91 static const char *def_listenhost = "127.0.0.1:8080";
92 static int def_max_tunnels = 50;
93 static const char *def_cacert = NULL;
94 static const char *def_cert = NULL;
95 static const char *def_key = NULL;
96 static const char *def_dcert = NULL;
97 static const char *def_dkey = NULL;
98 static const char *def_engine_id = NULL;
99 static int def_server_mode = 0;
100 static const char *def_cipher_list = NULL;
101 static int def_out_state = 0;
102 static unsigned int def_out_verify = 0;
103 static int def_out_totals = 0;
104 static int def_verify_mode = 0;
105 static unsigned int def_verify_depth = 10;
107 static const char *helpstring =
108 "\n'Tunala' (A tunneler with a New Zealand accent)\n"
109 "Usage: tunala [options], where options are from;\n"
110 " -listen [host:]<port> (default = 127.0.0.1:8080)\n"
111 " -proxy <host>:<port> (default = 127.0.0.1:443)\n"
112 " -maxtunnels <num> (default = 50)\n"
113 " -cacert <path|NULL> (default = NULL)\n"
114 " -cert <path|NULL> (default = NULL)\n"
115 " -key <path|NULL> (default = whatever '-cert' is)\n"
116 " -dcert <path|NULL> (usually for DSA, default = NULL)\n"
117 " -dkey <path|NULL> (usually for DSA, default = whatever '-dcert' is)\n"
118 " -engine <id|NULL> (default = NULL)\n"
119 " -server <0|1> (default = 0, ie. an SSL client)\n"
120 " -cipher <list> (specifies cipher list to use)\n"
121 " -out_state (prints SSL handshake states)\n"
122 " -out_verify <0|1|2|3> (prints certificate verification states: def=1)\n"
123 " -out_totals (prints out byte-totals when a tunnel closes)\n"
124 " -v_peer (verify the peer certificate)\n"
125 " -v_strict (do not continue if peer doesn't authenticate)\n"
126 " -v_once (no verification in renegotiates)\n"
127 " -v_depth <num> (limit certificate chain depth, default = 10)\n"
128 " -<h|help|?> (displays this help screen)\n"
129 "NB: It is recommended to specify a cert+key when operating as an\n"
130 "SSL server. If you only specify '-cert', the same file must\n"
131 "contain a matching private key.\n";
133 static int usage(const char *errstr, int isunknownarg)
136 fprintf(stderr, "Error: unknown argument '%s'\n", errstr);
138 fprintf(stderr, "Error: %s\n", errstr);
139 fprintf(stderr, "%s\n", helpstring);
143 static int err_str0(const char *str0)
145 fprintf(stderr, str0);
146 fprintf(stderr, "\n");
150 static int err_str1(const char *str0, const char *str1)
152 fprintf(stderr, str0, str1);
153 fprintf(stderr, "\n");
157 static int parse_max_tunnels(const char *s, unsigned int *maxtunnels)
161 l = strtoul(s, &temp, 10);
162 if((temp == s) || (*temp != '\0') || (l < 1) || (l > 1024)) {
163 fprintf(stderr, "Error, '%s' is an invalid value for "
167 *maxtunnels = (unsigned int)l;
171 static int parse_server_mode(const char *s, int *servermode)
175 l = strtoul(s, &temp, 10);
176 if((temp == s) || (*temp != '\0') || (l > 1)) {
177 fprintf(stderr, "Error, '%s' is an invalid value for the "
181 *servermode = (int)l;
185 static int parse_verify_level(const char *s, unsigned int *verify_level)
189 l = strtoul(s, &temp, 10);
190 if((temp == s) || (*temp != '\0') || (l > 3)) {
191 fprintf(stderr, "Error, '%s' is an invalid value for "
195 *verify_level = (unsigned int)l;
199 static int parse_verify_depth(const char *s, unsigned int *verify_depth)
203 l = strtoul(s, &temp, 10);
204 if((temp == s) || (*temp != '\0') || (l < 1) || (l > 50)) {
205 fprintf(stderr, "Error, '%s' is an invalid value for "
206 "verify_depth\n", s);
209 *verify_depth = (unsigned int)l;
213 /* Some fprintf format strings used when tunnels close */
214 static const char *io_stats_client_dirty =
215 " SSL (network) traffic to/from server; %8lu bytes in, %8lu bytes out\n";
216 static const char *io_stats_client_clean =
217 " tunnelled data to/from server; %8lu bytes in, %8lu bytes out\n";
218 static const char *io_stats_server_dirty =
219 " SSL (network) traffic to/from client; %8lu bytes in, %8lu bytes out\n";
220 static const char *io_stats_server_clean =
221 " tunnelled data to/from client; %8lu bytes in, %8lu bytes out\n";
223 int main(int argc, char *argv[])
227 tunala_world_t world;
228 tunala_item_t *t_item;
229 unsigned char *proxy_ip;
230 unsigned short proxy_port;
232 const char *proxyhost = def_proxyhost;
233 const char *listenhost = def_listenhost;
234 unsigned int max_tunnels = def_max_tunnels;
235 const char *cacert = def_cacert;
236 const char *cert = def_cert;
237 const char *key = def_key;
238 const char *dcert = def_dcert;
239 const char *dkey = def_dkey;
240 const char *engine_id = def_engine_id;
241 int server_mode = def_server_mode;
242 const char *cipher_list = def_cipher_list;
243 int out_state = def_out_state;
244 unsigned int out_verify = def_out_verify;
245 int out_totals = def_out_totals;
246 int verify_mode = def_verify_mode;
247 unsigned int verify_depth = def_verify_depth;
249 /* Parse command-line arguments */
253 if(strcmp(*argv, "-listen") == 0) {
255 return usage("-listen requires an argument", 0);
259 } else if(strcmp(*argv, "-proxy") == 0) {
261 return usage("-proxy requires an argument", 0);
265 } else if(strcmp(*argv, "-maxtunnels") == 0) {
267 return usage("-maxtunnels requires an argument", 0);
269 if(!parse_max_tunnels(*argv, &max_tunnels))
272 } else if(strcmp(*argv, "-cacert") == 0) {
274 return usage("-cacert requires an argument", 0);
276 if(strcmp(*argv, "NULL") == 0)
281 } else if(strcmp(*argv, "-cert") == 0) {
283 return usage("-cert requires an argument", 0);
285 if(strcmp(*argv, "NULL") == 0)
290 } else if(strcmp(*argv, "-key") == 0) {
292 return usage("-key requires an argument", 0);
294 if(strcmp(*argv, "NULL") == 0)
299 } else if(strcmp(*argv, "-dcert") == 0) {
301 return usage("-dcert requires an argument", 0);
303 if(strcmp(*argv, "NULL") == 0)
308 } else if(strcmp(*argv, "-dkey") == 0) {
310 return usage("-dkey requires an argument", 0);
312 if(strcmp(*argv, "NULL") == 0)
317 } else if(strcmp(*argv, "-engine") == 0) {
319 return usage("-engine requires an argument", 0);
323 } else if(strcmp(*argv, "-server") == 0) {
325 return usage("-server requires an argument", 0);
327 if(!parse_server_mode(*argv, &server_mode))
330 } else if(strcmp(*argv, "-cipher") == 0) {
332 return usage("-cipher requires an argument", 0);
336 } else if(strcmp(*argv, "-out_state") == 0) {
339 } else if(strcmp(*argv, "-out_verify") == 0) {
341 return usage("-out_verify requires an argument", 0);
343 if(!parse_verify_level(*argv, &out_verify))
346 } else if(strcmp(*argv, "-out_totals") == 0) {
349 } else if(strcmp(*argv, "-v_peer") == 0) {
350 verify_mode |= SSL_VERIFY_PEER;
352 } else if(strcmp(*argv, "-v_strict") == 0) {
353 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
355 } else if(strcmp(*argv, "-v_once") == 0) {
356 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
358 } else if(strcmp(*argv, "-v_depth") == 0) {
360 return usage("-v_depth requires an argument", 0);
362 if(!parse_verify_depth(*argv, &verify_depth))
365 } else if((strcmp(*argv, "-h") == 0) ||
366 (strcmp(*argv, "-help") == 0) ||
367 (strcmp(*argv, "-?") == 0)) {
368 fprintf(stderr, "%s\n", helpstring);
371 return usage(*argv, 1);
374 /* Initialise network stuff */
376 return err_str0("ip_initialise failed");
377 err_str0("ip_initialise succeeded");
378 /* Create the SSL_CTX */
379 if((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id,
380 cacert, cert, key, dcert, dkey, cipher_list, out_state,
381 out_verify, verify_mode, verify_depth)) == NULL)
382 return err_str1("initialise_ssl_ctx(engine_id=%s) failed",
383 (engine_id == NULL) ? "NULL" : engine_id);
384 err_str1("initialise_ssl_ctx(engine_id=%s) succeeded",
385 (engine_id == NULL) ? "NULL" : engine_id);
386 /* Create the listener */
387 if((world.listen_fd = ip_create_listener(listenhost)) == -1)
388 return err_str1("ip_create_listener(%s) failed", listenhost);
389 err_str1("ip_create_listener(%s) succeeded", listenhost);
390 if(!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0))
391 return err_str1("ip_parse_address(%s) failed", proxyhost);
392 err_str1("ip_parse_address(%s) succeeded", proxyhost);
393 fprintf(stderr, "Info - proxying to %d.%d.%d.%d:%d\n",
394 (int)proxy_ip[0], (int)proxy_ip[1],
395 (int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port);
396 fprintf(stderr, "Info - set maxtunnels to %d\n", (int)max_tunnels);
397 fprintf(stderr, "Info - set to operate as an SSL %s\n",
398 (server_mode ? "server" : "client"));
399 /* Initialise the rest of the stuff */
400 world.tunnels_used = world.tunnels_size = 0;
401 world.tunnels = NULL;
402 world.server_mode = server_mode;
403 selector_init(&world.selector);
405 /* We're ready to loop */
407 /* Should we listen for *new* tunnels? */
408 if(world.tunnels_used < max_tunnels)
409 selector_add_listener(&world.selector, world.listen_fd);
410 /* We should add in our existing tunnels */
411 for(loop = 0; loop < world.tunnels_used; loop++)
412 selector_add_tunala(&world.selector, world.tunnels + loop);
413 /* Now do the select */
414 switch(selector_select(&world.selector)) {
416 fprintf(stderr, "selector_select returned a badness error.\n");
419 fprintf(stderr, "Warn, selector_select returned 0 - signal??\n");
424 /* Accept new connection if we should and can */
425 if((world.tunnels_used < max_tunnels) && (selector_get_listener(
426 &world.selector, world.listen_fd,
428 /* We have a new connection */
429 if(!tunala_world_new_item(&world, newfd,
430 proxy_ip, proxy_port))
431 fprintf(stderr, "tunala_world_new_item failed\n");
433 fprintf(stderr, "Info, new tunnel opened, now up to "
434 "%d\n", world.tunnels_used);
436 /* Give each tunnel its moment, note the while loop is because it makes
437 * the logic easier than with "for" to deal with an array that may shift
438 * because of deletes. */
440 t_item = world.tunnels;
441 while(loop < world.tunnels_used) {
442 if(!tunala_item_io(&world.selector, t_item)) {
443 /* We're closing whether for reasons of an error or a
444 * natural close. Don't increment loop or t_item because
445 * the next item is moving to us! */
448 fprintf(stderr, "Tunnel closing, traffic stats follow\n");
449 /* Display the encrypted (over the network) stats */
450 fprintf(stderr, (server_mode ? io_stats_server_dirty :
451 io_stats_client_dirty),
452 buffer_total_in(state_machine_get_buffer(
453 &t_item->sm,SM_DIRTY_IN)),
454 buffer_total_out(state_machine_get_buffer(
455 &t_item->sm,SM_DIRTY_OUT)));
456 /* Display the local (tunnelled) stats. NB: Data we
457 * *receive* is data sent *out* of the state_machine on
458 * its 'clean' side. Hence the apparent back-to-front
459 * OUT/IN mixup here :-) */
460 fprintf(stderr, (server_mode ? io_stats_server_clean :
461 io_stats_client_clean),
462 buffer_total_out(state_machine_get_buffer(
463 &t_item->sm,SM_CLEAN_OUT)),
464 buffer_total_in(state_machine_get_buffer(
465 &t_item->sm,SM_CLEAN_IN)));
467 tunala_world_del_item(&world, loop);
468 fprintf(stderr, "Info, tunnel closed, down to %d\n",
472 /* Move to the next item */
478 /* Should never get here */
487 static int ctx_set_cert(SSL_CTX *ctx, const char *cert, const char *key)
491 EVP_PKEY *pkey = NULL;
492 int toret = 0; /* Assume an error */
496 if((fp = fopen(cert, "r")) == NULL) {
497 fprintf(stderr, "Error opening cert file '%s'\n", cert);
500 if(!PEM_read_X509(fp, &x509, NULL, NULL)) {
501 fprintf(stderr, "Error reading PEM cert from '%s'\n",
505 if(!SSL_CTX_use_certificate(ctx, x509)) {
506 fprintf(stderr, "Error, cert in '%s' can not be used\n",
510 /* Clear the FILE* for reuse in the "key" code */
513 fprintf(stderr, "Info, operating with cert in '%s'\n", cert);
514 /* If a cert was given without matching key, we assume the same
515 * file contains the required key. */
520 fprintf(stderr, "Error, can't specify a key without a "
521 "corresponding certificate\n");
523 fprintf(stderr, "Error, ctx_set_cert called with "
529 if((fp = fopen(key, "r")) == NULL) {
530 fprintf(stderr, "Error opening key file '%s'\n", key);
533 if(!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) {
534 fprintf(stderr, "Error reading PEM key from '%s'\n",
538 if(!SSL_CTX_use_PrivateKey(ctx, pkey)) {
539 fprintf(stderr, "Error, key in '%s' can not be used\n",
543 fprintf(stderr, "Info, operating with key in '%s'\n", key);
545 fprintf(stderr, "Info, operating without a cert or key\n");
557 static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
558 const char *CAfile, const char *cert, const char *key,
559 const char *dcert, const char *dkey, const char *cipher_list,
560 int out_state, int out_verify, int verify_mode,
561 unsigned int verify_depth)
563 SSL_CTX *ctx, *ret = NULL;
567 OpenSSL_add_ssl_algorithms();
568 SSL_load_error_strings();
570 meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method());
574 if((e = ENGINE_by_id(engine_id)) == NULL) {
575 fprintf(stderr, "Error obtaining '%s' engine, openssl "
576 "errors follow\n", engine_id);
579 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
580 fprintf(stderr, "Error assigning '%s' engine, openssl "
581 "errors follow\n", engine_id);
586 if((ctx = SSL_CTX_new(meth)) == NULL)
590 if(!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx),
592 fprintf(stderr, "Error loading CA cert(s) in '%s'\n",
596 fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n",
599 fprintf(stderr, "Info, operating without a CA cert(-list)\n");
600 if(!SSL_CTX_set_default_verify_paths(ctx)) {
601 fprintf(stderr, "Error setting default verify paths\n");
606 if((cert || key) && !ctx_set_cert(ctx, cert, key))
609 if((dcert || dkey) && !ctx_set_cert(ctx, dcert, dkey))
614 if(!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
615 fprintf(stderr, "Error setting cipher list '%s'\n",
619 fprintf(stderr, "Info, set cipher list '%s'\n", cipher_list);
621 fprintf(stderr, "Info, operating with default cipher list\n");
623 /* out_state (output of SSL handshake states to screen). */
625 cb_ssl_info_set_output(stderr);
629 cb_ssl_verify_set_output(stderr);
630 cb_ssl_verify_set_level(out_verify);
634 cb_ssl_verify_set_depth(verify_depth);
636 /* Success! (includes setting verify_mode) */
637 SSL_CTX_set_info_callback(ctx, cb_ssl_info);
638 SSL_CTX_set_verify(ctx, verify_mode, cb_ssl_verify);
642 ERR_print_errors_fp(stderr);
653 static void selector_sets_init(select_sets_t *s)
658 FD_ZERO(&s->excepts);
660 static void selector_init(tunala_selector_t *selector)
662 selector_sets_init(&selector->last_selected);
663 selector_sets_init(&selector->next_select);
666 #define SEL_EXCEPTS 0x00
667 #define SEL_READS 0x01
668 #define SEL_SENDS 0x02
669 static void selector_add_raw_fd(tunala_selector_t *s, int fd, int flags)
671 FD_SET(fd, &s->next_select.excepts);
672 if(flags & SEL_READS)
673 FD_SET(fd, &s->next_select.reads);
674 if(flags & SEL_SENDS)
675 FD_SET(fd, &s->next_select.sends);
677 if(s->next_select.max < (fd + 1))
678 s->next_select.max = fd + 1;
681 static void selector_add_listener(tunala_selector_t *selector, int fd)
683 selector_add_raw_fd(selector, fd, SEL_READS);
686 static void selector_add_tunala(tunala_selector_t *s, tunala_item_t *t)
688 /* Set clean read if sm.clean_in is not full */
689 if(t->clean_read != -1) {
690 selector_add_raw_fd(s, t->clean_read,
691 (buffer_full(state_machine_get_buffer(&t->sm,
692 SM_CLEAN_IN)) ? SEL_EXCEPTS : SEL_READS));
694 /* Set clean send if sm.clean_out is not empty */
695 if(t->clean_send != -1) {
696 selector_add_raw_fd(s, t->clean_send,
697 (buffer_empty(state_machine_get_buffer(&t->sm,
698 SM_CLEAN_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
700 /* Set dirty read if sm.dirty_in is not full */
701 if(t->dirty_read != -1) {
702 selector_add_raw_fd(s, t->dirty_read,
703 (buffer_full(state_machine_get_buffer(&t->sm,
704 SM_DIRTY_IN)) ? SEL_EXCEPTS : SEL_READS));
706 /* Set dirty send if sm.dirty_out is not empty */
707 if(t->dirty_send != -1) {
708 selector_add_raw_fd(s, t->dirty_send,
709 (buffer_empty(state_machine_get_buffer(&t->sm,
710 SM_DIRTY_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
714 static int selector_select(tunala_selector_t *selector)
716 memcpy(&selector->last_selected, &selector->next_select,
717 sizeof(select_sets_t));
718 selector_sets_init(&selector->next_select);
719 return select(selector->last_selected.max,
720 &selector->last_selected.reads,
721 &selector->last_selected.sends,
722 &selector->last_selected.excepts, NULL);
725 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
726 * which case *newfd is populated. */
727 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd)
729 if(FD_ISSET(fd, &selector->last_selected.excepts))
731 if(!FD_ISSET(fd, &selector->last_selected.reads))
733 if((*newfd = ip_accept_connection(fd)) == -1)
738 /************************/
739 /* "Tunala" world stuff */
740 /************************/
742 static int tunala_world_make_room(tunala_world_t *world)
744 unsigned int newsize;
745 tunala_item_t *newarray;
747 if(world->tunnels_used < world->tunnels_size)
749 newsize = (world->tunnels_size == 0 ? 16 :
750 ((world->tunnels_size * 3) / 2));
751 if((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL)
753 memset(newarray, 0, newsize * sizeof(tunala_item_t));
754 if(world->tunnels_used > 0)
755 memcpy(newarray, world->tunnels,
756 world->tunnels_used * sizeof(tunala_item_t));
757 if(world->tunnels_size > 0)
758 free(world->tunnels);
760 world->tunnels = newarray;
761 world->tunnels_size = newsize;
765 static int tunala_world_new_item(tunala_world_t *world, int fd,
766 const unsigned char *ip, unsigned short port)
772 if(!tunala_world_make_room(world))
774 if((new_ssl = SSL_new(world->ssl_ctx)) == NULL) {
775 fprintf(stderr, "Error creating new SSL\n");
776 ERR_print_errors_fp(stderr);
779 item = world->tunnels + (world->tunnels_used++);
780 state_machine_init(&item->sm);
781 item->clean_read = item->clean_send =
782 item->dirty_read = item->dirty_send = -1;
783 if((newfd = ip_create_connection_split(ip, port)) == -1)
785 /* Which way round? If we're a server, "fd" is the dirty side and the
786 * connection we open is the clean one. For a client, it's the other way
788 if(world->server_mode) {
789 item->dirty_read = item->dirty_send = fd;
790 item->clean_read = item->clean_send = newfd;
792 item->clean_read = item->clean_send = fd;
793 item->dirty_read = item->dirty_send = newfd;
795 /* We use the SSL's "app_data" to indicate a call-back induced "kill" */
796 SSL_set_app_data(new_ssl, NULL);
797 if(!state_machine_set_SSL(&item->sm, new_ssl, world->server_mode))
801 tunala_world_del_item(world, world->tunnels_used - 1);
806 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx)
808 tunala_item_t *item = world->tunnels + idx;
809 if(item->clean_read != -1)
810 close(item->clean_read);
811 if(item->clean_send != item->clean_read)
812 close(item->clean_send);
813 item->clean_read = item->clean_send = -1;
814 if(item->dirty_read != -1)
815 close(item->dirty_read);
816 if(item->dirty_send != item->dirty_read)
817 close(item->dirty_send);
818 item->dirty_read = item->dirty_send = -1;
819 state_machine_close(&item->sm);
820 /* OK, now we fix the item array */
821 if(idx + 1 < world->tunnels_used)
822 /* We need to scroll entries to the left */
823 memmove(world->tunnels + idx,
824 world->tunnels + (idx + 1),
825 (world->tunnels_used - (idx + 1)) *
826 sizeof(tunala_item_t));
827 world->tunnels_used--;
830 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item)
832 int c_r, c_s, d_r, d_s; /* Four boolean flags */
834 /* Take ourselves out of the gene-pool if there was an except */
835 if((item->clean_read != -1) && FD_ISSET(item->clean_read,
836 &selector->last_selected.excepts))
838 if((item->clean_send != -1) && FD_ISSET(item->clean_send,
839 &selector->last_selected.excepts))
841 if((item->dirty_read != -1) && FD_ISSET(item->dirty_read,
842 &selector->last_selected.excepts))
844 if((item->dirty_send != -1) && FD_ISSET(item->dirty_send,
845 &selector->last_selected.excepts))
847 /* Grab our 4 IO flags */
848 c_r = c_s = d_r = d_s = 0;
849 if(item->clean_read != -1)
850 c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads);
851 if(item->clean_send != -1)
852 c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends);
853 if(item->dirty_read != -1)
854 d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads);
855 if(item->dirty_send != -1)
856 d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends);
857 /* If no IO has happened for us, skip needless data looping */
858 if(!c_r && !c_s && !d_r && !d_s)
861 c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
862 SM_CLEAN_IN), item->clean_read) <= 0);
864 c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
865 SM_CLEAN_OUT), item->clean_send) <= 0);
867 d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
868 SM_DIRTY_IN), item->dirty_read) <= 0);
870 d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
871 SM_DIRTY_OUT), item->dirty_send) <= 0);
872 /* If any of the flags is non-zero, that means they need closing */
874 close(item->clean_read);
875 if(item->clean_send == item->clean_read)
876 item->clean_send = -1;
877 item->clean_read = -1;
879 if(c_s && (item->clean_send != -1)) {
880 close(item->clean_send);
881 if(item->clean_send == item->clean_read)
882 item->clean_read = -1;
883 item->clean_send = -1;
886 close(item->dirty_read);
887 if(item->dirty_send == item->dirty_read)
888 item->dirty_send = -1;
889 item->dirty_read = -1;
891 if(d_s && (item->dirty_send != -1)) {
892 close(item->dirty_send);
893 if(item->dirty_send == item->dirty_read)
894 item->dirty_read = -1;
895 item->dirty_send = -1;
897 /* This function name is attributed to the term donated by David
898 * Schwartz on openssl-dev, message-ID:
899 * <NCBBLIEPOCNJOAEKBEAKEEDGLIAA.davids@webmaster.com>. :-) */
900 if(!state_machine_churn(&item->sm))
901 /* If the SSL closes, it will also zero-out the _in buffers
902 * and will in future process just outgoing data. As and
903 * when the outgoing data has gone, it will return zero
904 * here to tell us to bail out. */
906 /* Otherwise, we return zero if both sides are dead. */
907 if(((item->clean_read == -1) || (item->clean_send == -1)) &&
908 ((item->dirty_read == -1) || (item->dirty_send == -1)))
910 /* If only one side closed, notify the SSL of this so it can take
911 * appropriate action. */
912 if((item->clean_read == -1) || (item->clean_send == -1)) {
913 if(!state_machine_close_clean(&item->sm))
916 if((item->dirty_read == -1) || (item->dirty_send == -1)) {
917 if(!state_machine_close_dirty(&item->sm))