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