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