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