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