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