oops, remove comments that are no longer true.
[openssl.git] / demos / tunala / tunala.c
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*"
3 #endif
4
5 /* Include our bits'n'pieces */
6 #include "tunala.h"
7
8
9 /********************************************/
10 /* Our local types that specify our "world" */
11 /********************************************/
12
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". */
20         state_machine_t sm;
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
23          * identical. */
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;
29 } tunala_item_t;
30
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() */
39 } select_sets_t;
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 */
43 } tunala_selector_t;
44
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 */
50         int listen_fd;
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. */
59         SSL_CTX *ssl_ctx;
60         /* Simple flag with complex logic :-) Indicates whether we're an SSL
61          * server or an SSL client. */
62         int server_mode;
63 } tunala_world_t;
64
65 /*****************************/
66 /* Internal static functions */
67 /*****************************/
68
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 static void selector_init(tunala_selector_t *selector);
72 static void selector_add_listener(tunala_selector_t *selector, int fd);
73 static void selector_add_tunala(tunala_selector_t *selector, tunala_item_t *t);
74 static int selector_select(tunala_selector_t *selector);
75 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
76  * which case *newfd is populated. */
77 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd);
78 static int tunala_world_new_item(tunala_world_t *world, int fd,
79                 const unsigned char *ip, unsigned short port);
80 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx);
81 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item);
82
83 /*********************************************/
84 /* MAIN FUNCTION (and its utility functions) */
85 /*********************************************/
86
87 static const char *def_proxyhost = "127.0.0.1:443";
88 static const char *def_listenhost = "127.0.0.1:8080";
89 static int def_max_tunnels = 50;
90 static const char *def_cacert = NULL;
91 static const char *def_cert = NULL;
92 static const char *def_key = NULL;
93 static const char *def_engine_id = NULL;
94 static int def_server_mode = 0;
95
96 static const char *helpstring =
97         "\n'Tunala' (A tunneler with a New Zealand accent)\n"
98         "Usage: tunala [options], where options are from;\n"
99         "    -listen [host:]<port>  (default = 127.0.0.1:8080)\n"
100         "    -proxy <host>:<port>   (default = 127.0.0.1:443)\n"
101         "    -maxtunnels <num>      (default = 50)\n"
102         "    -cacert <path|NULL>    (default = NULL)\n"
103         "    -cert <path|NULL>      (default = NULL)\n"
104         "    -key <path|NULL>       (default = whatever '-cert' is)\n"
105         "    -engine <id|NULL>      (default = NULL)\n"
106         "    -server <0|1>          (default = 0, ie. an SSL client)\n"
107         "    -<h|help|?>            (displays this help screen)\n"
108         "NB: It is recommended to specify a cert+key when operating as an\n"
109         "SSL server. If you only specify '-cert', the same file must\n"
110         "contain a matching private key.\n";
111
112 static int usage(const char *errstr, int isunknownarg)
113 {
114         if(isunknownarg)
115                 fprintf(stderr, "Error: unknown argument '%s'\n", errstr);
116         else
117                 fprintf(stderr, "Error: %s\n", errstr);
118         fprintf(stderr, "%s\n", helpstring);
119         return 1;
120 }
121
122 static int err_str0(const char *str0)
123 {
124         fprintf(stderr, str0);
125         fprintf(stderr, "\n");
126         return 1;
127 }
128
129 static int err_str1(const char *str0, const char *str1)
130 {
131         fprintf(stderr, str0, str1);
132         fprintf(stderr, "\n");
133         return 1;
134 }
135
136 static int parse_max_tunnels(const char *s, unsigned int *maxtunnels)
137 {
138         unsigned long l;
139         char *temp;
140         l = strtoul(s, &temp, 10);
141         if((temp == s) || (*temp != '\0') || (l < 1) || (l > 1024)) {
142                 fprintf(stderr, "Error, '%s' is an invalid value for "
143                                 "maxtunnels\n", s);
144                 return 0;
145         }
146         *maxtunnels = (unsigned int)l;
147         return 1;
148 }
149
150 static int parse_server_mode(const char *s, int *servermode)
151 {
152         unsigned long l;
153         char *temp;
154         l = strtoul(s, &temp, 10);
155         if((temp == s) || (*temp != '\0') || (l > 1)) {
156                 fprintf(stderr, "Error, '%s' is an invalid value for the "
157                                 "server mode\n", s);
158                 return 0;
159         }
160         *servermode = (int)l;
161         return 1;
162 }
163
164 int main(int argc, char *argv[])
165 {
166         unsigned int loop;
167         int newfd;
168         tunala_world_t world;
169         tunala_item_t *t_item;
170         unsigned char *proxy_ip;
171         unsigned short proxy_port;
172         /* Overridables */
173         const char *proxyhost = def_proxyhost;
174         const char *listenhost = def_listenhost;
175         unsigned int max_tunnels = def_max_tunnels;
176         const char *cacert = def_cacert;
177         const char *cert = def_cert;
178         const char *key = def_key;
179         const char *engine_id = def_engine_id;
180         int server_mode = def_server_mode;
181
182 /* Parse command-line arguments */
183 next_arg:
184         argc--; argv++;
185         if(argc > 0) {
186                 if(strcmp(*argv, "-listen") == 0) {
187                         if(argc < 2)
188                                 return usage("-listen requires an argument", 0);
189                         argc--; argv++;
190                         listenhost = *argv;
191                         goto next_arg;
192                 } else if(strcmp(*argv, "-proxy") == 0) {
193                         if(argc < 2)
194                                 return usage("-proxy requires an argument", 0);
195                         argc--; argv++;
196                         proxyhost = *argv;
197                         goto next_arg;
198                 } else if(strcmp(*argv, "-maxtunnels") == 0) {
199                         if(argc < 2)
200                                 return usage("-maxtunnels requires an argument", 0);
201                         argc--; argv++;
202                         if(!parse_max_tunnels(*argv, &max_tunnels))
203                                 return 1;
204                         goto next_arg;
205                 } else if(strcmp(*argv, "-cacert") == 0) {
206                         if(argc < 2)
207                                 return usage("-cacert requires an argument", 0);
208                         argc--; argv++;
209                         if(strcmp(*argv, "NULL") == 0)
210                                 cacert = NULL;
211                         else
212                                 cacert = *argv;
213                         goto next_arg;
214                 } else if(strcmp(*argv, "-cert") == 0) {
215                         if(argc < 2)
216                                 return usage("-cert requires an argument", 0);
217                         argc--; argv++;
218                         if(strcmp(*argv, "NULL") == 0)
219                                 cert = NULL;
220                         else
221                                 cert = *argv;
222                         goto next_arg;
223                 } else if(strcmp(*argv, "-key") == 0) {
224                         if(argc < 2)
225                                 return usage("-key requires an argument", 0);
226                         argc--; argv++;
227                         if(strcmp(*argv, "NULL") == 0)
228                                 key = NULL;
229                         else
230                                 key = *argv;
231                         goto next_arg;
232                 } else if(strcmp(*argv, "-engine") == 0) {
233                         if(argc < 2)
234                                 return usage("-engine requires an argument", 0);
235                         argc--; argv++;
236                         engine_id = *argv;
237                         goto next_arg;
238                 } else if(strcmp(*argv, "-server") == 0) {
239                         if(argc < 2)
240                                 return usage("-server requires an argument", 0);
241                         argc--; argv++;
242                         if(!parse_server_mode(*argv, &server_mode))
243                                 return 1;
244                         goto next_arg;
245                 } else if((strcmp(*argv, "-h") == 0) ||
246                                 (strcmp(*argv, "-help") == 0) ||
247                                 (strcmp(*argv, "-?") == 0)) {
248                         fprintf(stderr, "%s\n", helpstring);
249                         return 0;
250                 } else
251                         return usage(*argv, 1);
252         }
253
254         /* Initialise network stuff */
255         if(!ip_initialise())
256                 return err_str0("ip_initialise failed");
257         err_str0("ip_initialise succeeded");
258         /* Create the SSL_CTX */
259         if((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id,
260                         cacert, cert, key)) == NULL)
261                 return err_str1("initialise_ssl_ctx(engine_id=%s) failed",
262                         (engine_id == NULL) ? "NULL" : engine_id);
263         err_str1("initialise_ssl_ctx(engine_id=%s) succeeded",
264                         (engine_id == NULL) ? "NULL" : engine_id);
265         /* Create the listener */
266         if((world.listen_fd = ip_create_listener(listenhost)) == -1)
267                 return err_str1("ip_create_listener(%s) failed", listenhost);
268         err_str1("ip_create_listener(%s) succeeded", listenhost);
269         if(!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0))
270                 return err_str1("ip_parse_address(%s) failed", proxyhost);
271         err_str1("ip_parse_address(%s) succeeded", proxyhost);
272         fprintf(stderr, "Info - proxying to %d.%d.%d.%d:%d\n",
273                         (int)proxy_ip[0], (int)proxy_ip[1],
274                         (int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port);
275         fprintf(stderr, "Info - set maxtunnels to %d\n", (int)max_tunnels);
276         fprintf(stderr, "Info - set to operate as an SSL %s\n",
277                         (server_mode ? "server" : "client"));
278         /* Initialise the rest of the stuff */
279         world.tunnels_used = world.tunnels_size = 0;
280         world.tunnels = NULL;
281         world.server_mode = server_mode;
282         selector_init(&world.selector);
283
284 /* We're ready to loop */
285 main_loop:
286         /* Should we listen for *new* tunnels? */
287         if(world.tunnels_used < max_tunnels)
288                 selector_add_listener(&world.selector, world.listen_fd);
289         /* We should add in our existing tunnels */
290         for(loop = 0; loop < world.tunnels_used; loop++)
291                 selector_add_tunala(&world.selector, world.tunnels + loop);
292         /* Now do the select */
293         switch(selector_select(&world.selector)) {
294         case -1:
295                 fprintf(stderr, "selector_select returned a badness error.\n");
296                 abort();
297         case 0:
298                 fprintf(stderr, "Warn, selector_select return 0 - signal??\n");
299                 goto main_loop;
300         default:
301                 break;
302         }
303         /* Accept new connection if we should and can */
304         if((world.tunnels_used < max_tunnels) && (selector_get_listener(
305                                         &world.selector, world.listen_fd,
306                                         &newfd) == 1)) {
307                 /* We have a new connection */
308                 if(!tunala_world_new_item(&world, newfd,
309                                         proxy_ip, proxy_port)) {
310                         fprintf(stderr, "tunala_world_new_item failed\n");
311                         abort();
312                 }
313                 fprintf(stderr, "Info, new tunnel opened, now up to %d\n",
314                                 world.tunnels_used);
315         }
316         /* Give each tunnel its moment, note the while loop is because it makes
317          * the logic easier than with "for" to deal with an array that may shift
318          * because of deletes. */
319         loop = 0;
320         t_item = world.tunnels;
321         while(loop < world.tunnels_used) {
322                 if(!tunala_item_io(&world.selector, t_item)) {
323                         /* We're closing whether for reasons of an error or a
324                          * natural close. Don't increment loop or t_item because
325                          * the next item is moving to us! */
326                         tunala_world_del_item(&world, loop);
327                         fprintf(stderr, "Info, tunnel closed, down to %d\n",
328                                         world.tunnels_used);
329                 }
330                 else {
331                         /* Move to the next item */
332                         loop++;
333                         t_item++;
334                 }
335         }
336         goto main_loop;
337         /* Should never get here */
338         abort();
339         return 1;
340 }
341
342 /****************/
343 /* OpenSSL bits */
344 /****************/
345
346 static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
347                 const char *CAfile, const char *cert, const char *key)
348 {
349         SSL_CTX *ctx, *ret = NULL;
350         SSL_METHOD *meth;
351         ENGINE *e = NULL;
352         FILE *fp = NULL;
353         X509 *x509 = NULL;
354         EVP_PKEY *pkey = NULL;
355
356         OpenSSL_add_ssl_algorithms();
357         SSL_load_error_strings();
358
359         meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method());
360         if(meth == NULL)
361                 goto err;
362         if(engine_id) {
363                 if((e = ENGINE_by_id(engine_id)) == NULL) {
364                         fprintf(stderr, "Error obtaining '%s' engine, openssl "
365                                         "errors follow\n", engine_id);
366                         goto err;
367                 }
368                 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
369                         fprintf(stderr, "Error assigning '%s' engine, openssl "
370                                         "errors follow\n", engine_id);
371                         goto err;
372                 }
373                 ENGINE_free(e);
374         }
375         if((ctx = SSL_CTX_new(meth)) == NULL)
376                 goto err;
377         /* cacert */
378         if(CAfile) {
379                 if(!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx),
380                                         CAfile, NULL)) {
381                         fprintf(stderr, "Error loading CA cert(s) in '%s'\n",
382                                         CAfile);
383                         goto err;
384                 }
385                 fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n",
386                                 CAfile);
387         } else
388                 fprintf(stderr, "Info, operating without a CA cert(-list)\n");
389         if(!SSL_CTX_set_default_verify_paths(ctx)) {
390                 fprintf(stderr, "Error setting default verify paths\n");
391                 goto err;
392         }
393         /* cert */
394         if(cert) {
395                 if((fp = fopen(cert, "r")) == NULL) {
396                         fprintf(stderr, "Error opening cert file '%s'\n", cert);
397                         goto err;
398                 }
399                 if(!PEM_read_X509(fp, &x509, NULL, NULL)) {
400                         fprintf(stderr, "Error reading PEM cert from '%s'\n",
401                                         cert);
402                         goto err;
403                 }
404                 if(!SSL_CTX_use_certificate(ctx, x509)) {
405                         fprintf(stderr, "Error, cert in '%s' can not be used\n",
406                                         cert);
407                         goto err;
408                 }
409                 fprintf(stderr, "Info, operating with cert in '%s'\n", cert);
410                 fclose(fp);
411                 fp = NULL;
412                 /* If a cert was given without matching key, we assume the same
413                  * file contains the required key. */
414                 if(!key)
415                         key = cert;
416         } else
417                 if(key) {
418                         fprintf(stderr, "Error, can't specify a key without a "
419                                         "corresponding certificate\n");
420                         goto err;
421                 }
422         /* key */
423         if(key) {
424                 if((fp = fopen(key, "r")) == NULL) {
425                         fprintf(stderr, "Error opening key file '%s'\n", key);
426                         goto err;
427                 }
428                 if(!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) {
429                         fprintf(stderr, "Error reading PEM key from '%s'\n",
430                                         key);
431                         goto err;
432                 }
433                 if(!SSL_CTX_use_PrivateKey(ctx, pkey)) {
434                         fprintf(stderr, "Error, key in '%s' can not be used\n",
435                                         key);
436                         goto err;
437                 }
438                 fprintf(stderr, "Info, operating with key in '%s'\n", key);
439         } else
440                 fprintf(stderr, "Info, operating without a cert or key\n");
441
442         /* Success! */
443         ret = ctx;
444 err:
445         if(!ret) {
446                 ERR_print_errors_fp(stderr);
447                 if(ctx)
448                         SSL_CTX_free(ctx);
449         }
450         if(fp)
451                 fclose(fp);
452         if(x509)
453                 X509_free(x509);
454         if(pkey)
455                 EVP_PKEY_free(pkey);
456         return ret;
457 }
458
459 /*****************/
460 /* Selector bits */
461 /*****************/
462
463 static void selector_sets_init(select_sets_t *s)
464 {
465         s->max = 0;
466         FD_ZERO(&s->reads);
467         FD_ZERO(&s->sends);
468         FD_ZERO(&s->excepts);
469 }
470 static void selector_init(tunala_selector_t *selector)
471 {
472         selector_sets_init(&selector->last_selected);
473         selector_sets_init(&selector->next_select);
474 }
475
476 #define SEL_EXCEPTS 0x00
477 #define SEL_READS   0x01
478 #define SEL_SENDS   0x02
479 static void selector_add_raw_fd(tunala_selector_t *s, int fd, int flags)
480 {
481         FD_SET(fd, &s->next_select.excepts);
482         if(flags & SEL_READS)
483                 FD_SET(fd, &s->next_select.reads);
484         if(flags & SEL_SENDS)
485                 FD_SET(fd, &s->next_select.sends);
486         /* Adjust "max" */
487         if(s->next_select.max < (fd + 1))
488                 s->next_select.max = fd + 1;
489 }
490
491 static void selector_add_listener(tunala_selector_t *selector, int fd)
492 {
493         selector_add_raw_fd(selector, fd, SEL_READS);
494 }
495
496 static void selector_add_tunala(tunala_selector_t *s, tunala_item_t *t)
497 {
498         /* Set clean read if sm.clean_in is not full */
499         if(t->clean_read != -1) {
500                 selector_add_raw_fd(s, t->clean_read,
501                         (buffer_full(state_machine_get_buffer(&t->sm,
502                                 SM_CLEAN_IN)) ? SEL_EXCEPTS : SEL_READS));
503         }
504         /* Set clean send if sm.clean_out is not empty */
505         if(t->clean_send != -1) {
506                 selector_add_raw_fd(s, t->clean_send,
507                         (buffer_empty(state_machine_get_buffer(&t->sm,
508                                 SM_CLEAN_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
509         }
510         /* Set dirty read if sm.dirty_in is not full */
511         if(t->dirty_read != -1) {
512                 selector_add_raw_fd(s, t->dirty_read,
513                         (buffer_full(state_machine_get_buffer(&t->sm,
514                                 SM_DIRTY_IN)) ? SEL_EXCEPTS : SEL_READS));
515         }
516         /* Set dirty send if sm.dirty_out is not empty */
517         if(t->dirty_send != -1) {
518                 selector_add_raw_fd(s, t->dirty_send,
519                         (buffer_empty(state_machine_get_buffer(&t->sm,
520                                 SM_DIRTY_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
521         }
522 }
523
524 static int selector_select(tunala_selector_t *selector)
525 {
526         memcpy(&selector->last_selected, &selector->next_select,
527                         sizeof(select_sets_t));
528         selector_sets_init(&selector->next_select);
529         return select(selector->last_selected.max,
530                         &selector->last_selected.reads,
531                         &selector->last_selected.sends,
532                         &selector->last_selected.excepts, NULL);
533 }
534
535 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
536  * which case *newfd is populated. */
537 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd)
538 {
539         if(FD_ISSET(fd, &selector->last_selected.excepts))
540                 return -1;
541         if(!FD_ISSET(fd, &selector->last_selected.reads))
542                 return 0;
543         if((*newfd = ip_accept_connection(fd)) == -1)
544                 return -1;
545         return 1;
546 }
547
548 /************************/
549 /* "Tunala" world stuff */
550 /************************/
551
552 static int tunala_world_make_room(tunala_world_t *world)
553 {
554         unsigned int newsize;
555         tunala_item_t *newarray;
556
557         if(world->tunnels_used < world->tunnels_size)
558                 return 1;
559         newsize = (world->tunnels_size == 0 ? 16 :
560                         ((world->tunnels_size * 3) / 2));
561         if((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL)
562                 return 0;
563         memset(newarray, 0, newsize * sizeof(tunala_item_t));
564         if(world->tunnels_used > 0)
565                 memcpy(newarray, world->tunnels,
566                         world->tunnels_used * sizeof(tunala_item_t));
567         if(world->tunnels_size > 0)
568                 free(world->tunnels);
569         /* migrate */
570         world->tunnels = newarray;
571         world->tunnels_size = newsize;
572         return 1;
573 }
574
575 static int tunala_world_new_item(tunala_world_t *world, int fd,
576                 const unsigned char *ip, unsigned short port)
577 {
578         tunala_item_t *item;
579         int newfd;
580
581         if(!tunala_world_make_room(world))
582                 return 0;
583         item = world->tunnels + (world->tunnels_used++);
584         state_machine_init(&item->sm);
585         item->clean_read = item->clean_send =
586                 item->dirty_read = item->dirty_send = -1;
587         if((newfd = ip_create_connection_split(ip, port)) == -1)
588                 goto err;
589         /* Which way round? If we're a server, "fd" is the dirty side and the
590          * connection we open is the clean one. For a client, it's the other way
591          * around. */
592         if(world->server_mode) {
593                 item->dirty_read = item->dirty_send = fd;
594                 item->clean_read = item->clean_send = newfd;
595         } else {
596                 item->clean_read = item->clean_send = fd;
597                 item->dirty_read = item->dirty_send = newfd;
598         }
599         state_machine_set_SSL(&item->sm, SSL_new(world->ssl_ctx),
600                         world->server_mode);
601         return 1;
602 err:
603         state_machine_close(&item->sm);
604         return 0;
605
606 }
607
608 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx)
609 {
610         tunala_item_t *item = world->tunnels + idx;
611         if(item->clean_read != -1)
612                 close(item->clean_read);
613         if(item->clean_send != item->clean_read)
614                 close(item->clean_send);
615         item->clean_read = item->clean_send = -1;
616         if(item->dirty_read != -1)
617                 close(item->dirty_read);
618         if(item->dirty_send != item->dirty_read)
619                 close(item->dirty_send);
620         item->dirty_read = item->dirty_send = -1;
621         state_machine_close(&item->sm);
622         /* OK, now we fix the item array */
623         if(idx + 1 < world->tunnels_used)
624                 /* We need to scroll entries to the left */
625                 memmove(world->tunnels + idx,
626                                 world->tunnels + (idx + 1),
627                                 (world->tunnels_used - (idx + 1)) *
628                                         sizeof(tunala_item_t));
629         world->tunnels_used--;
630 }
631
632 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item)
633 {
634         int c_r, c_s, d_r, d_s; /* Four boolean flags */
635
636         /* Take ourselves out of the gene-pool if there was an except */
637         if((item->clean_read != -1) && FD_ISSET(item->clean_read,
638                                 &selector->last_selected.excepts))
639                 return 0;
640         if((item->clean_send != -1) && FD_ISSET(item->clean_send,
641                                 &selector->last_selected.excepts))
642                 return 0;
643         if((item->dirty_read != -1) && FD_ISSET(item->dirty_read,
644                                 &selector->last_selected.excepts))
645                 return 0;
646         if((item->dirty_send != -1) && FD_ISSET(item->dirty_send,
647                                 &selector->last_selected.excepts))
648                 return 0;
649         /* Grab our 4 IO flags */
650         c_r = c_s = d_r = d_s = 0;
651         if(item->clean_read != -1)
652                 c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads);
653         if(item->clean_send != -1)
654                 c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends);
655         if(item->dirty_read != -1)
656                 d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads);
657         if(item->dirty_send != -1)
658                 d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends);
659         /* If no IO has happened for us, skip needless data looping */
660         if(!c_r && !c_s && !d_r && !d_s)
661                 return 1;
662         if(c_r)
663                 c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
664                                 SM_CLEAN_IN), item->clean_read) <= 0);
665         if(c_s)
666                 c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
667                                 SM_CLEAN_OUT), item->clean_send) <= 0);
668         if(d_r)
669                 d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
670                                 SM_DIRTY_IN), item->dirty_read) <= 0);
671         if(d_s)
672                 d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
673                                 SM_DIRTY_OUT), item->dirty_send) <= 0);
674         /* If any of the flags is non-zero, that means they need closing */
675         if(c_r) {
676                 close(item->clean_read);
677                 if(item->clean_send == item->clean_read)
678                         item->clean_send = -1;
679                 item->clean_read = -1;
680         }
681         if(c_s) {
682                 close(item->clean_send);
683                 if(item->clean_send == item->clean_read)
684                         item->clean_read = -1;
685                 item->clean_send = -1;
686         }
687         if(d_r) {
688                 close(item->dirty_read);
689                 if(item->dirty_send == item->dirty_read)
690                         item->dirty_send = -1;
691                 item->dirty_read = -1;
692         }
693         if(d_s) {
694                 close(item->dirty_send);
695                 if(item->dirty_send == item->dirty_read)
696                         item->dirty_read = -1;
697                 item->dirty_send = -1;
698         }
699         /* This function name is attributed to the term donated by David
700          * Schwartz on openssl-dev, message-ID:
701          * <NCBBLIEPOCNJOAEKBEAKEEDGLIAA.davids@webmaster.com>. :-) */
702         if(!state_machine_churn(&item->sm))
703                 /* If the SSL closes, it will also zero-out the _in buffers
704                  * and will in future process just outgoing data. As and
705                  * when the outgoing data has gone, it will return zero
706                  * here to tell us to bail out. */
707                 return 0;
708         /* Otherwise, we return zero if both sides are dead. */
709         if(((item->clean_read == -1) || (item->clean_send == -1)) &&
710                         ((item->dirty_read == -1) || (item->dirty_send == -1)))
711                 return 0;
712         /* If only one side closed, notify the SSL of this so it can take
713          * appropriate action. */
714         if((item->clean_read == -1) || (item->clean_send == -1)) {
715                 if(!state_machine_close_clean(&item->sm))
716                         return 0;
717         }
718         if((item->dirty_read == -1) || (item->dirty_send == -1)) {
719                 if(state_machine_close_dirty(&item->sm))
720                         return 0;
721         }
722         return 1;
723 }
724