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