1e78fcdc22b67904762e75e8cde895d17c46b768
[rsync-patches.git] / openssl-support.diff
1 After applying this patch, run these commands for a successful build:
2
3     ./prepare-source
4     ./configure
5     make
6
7 Casey Marshall writes:
8
9 I've been hacking together a way to use rsync with OpenSSL, and have
10 attached my current patch against a recent CVS tree. The details of
11 this implementation are:
12
13   1. The SSL code is added as a "layer" that is forked into its own
14      process.
15
16   2. An SSL connection is established by the client issuing the
17      command:
18
19        #starttls
20
21      And, if the daemon allows SSL, it replies with
22
23        @RSYNCD: starttls
24
25      At which point both sides begin negotiating the SSL connection.
26      Servers that can't or don't want to use SSL just treat it as a
27      normal unknown command.
28
29   3. The SSL code is meant to be unobtrusive, and when this patch is
30      applied the program may still be built with no SSL code.
31
32   4. There are a number of details not implemented.
33
34 All warnings apply; I don't do C programming all that often, so I
35 can't say if I've left any cleanup/compatibility errors in the code.
36
37
38 --- old/Makefile.in
39 +++ new/Makefile.in
40 @@ -38,7 +38,7 @@ OBJS3=progress.o pipe.o
41  DAEMON_OBJ = params.o loadparm.o clientserver.o access.o connection.o authenticate.o
42  popt_OBJS=popt/findme.o  popt/popt.o  popt/poptconfig.o \
43         popt/popthelp.o popt/poptparse.o
44 -OBJS=$(OBJS1) $(OBJS2) $(OBJS3) $(DAEMON_OBJ) $(LIBOBJ) $(ZLIBOBJ) @BUILD_POPT@
45 +OBJS=$(OBJS1) $(OBJS2) $(OBJS3) $(DAEMON_OBJ) $(LIBOBJ) $(ZLIBOBJ) @BUILD_POPT@ @SSL_OBJS@
46  
47  TLS_OBJ = tls.o syscall.o lib/compat.o lib/snprintf.o lib/permstring.o
48  
49 --- old/cleanup.c
50 +++ new/cleanup.c
51 @@ -22,6 +22,9 @@
52  #include "rsync.h"
53  
54  extern int io_error;
55 +#if HAVE_OPENSSL
56 +extern int use_ssl;
57 +#endif
58  extern int keep_partial;
59  extern int log_got_error;
60  extern char *partial_dir;
61 @@ -101,6 +104,11 @@ void _exit_cleanup(int code, const char 
62         SIGACTION(SIGUSR1, SIG_IGN);
63         SIGACTION(SIGUSR2, SIG_IGN);
64  
65 +#if HAVE_OPENSSL
66 +       if (use_ssl)
67 +               end_tls();
68 +#endif
69 +
70         if (verbose > 3) {
71                 rprintf(FINFO,"_exit_cleanup(code=%d, file=%s, line=%d): entered\n",
72                         code, file, line);
73 --- old/clientserver.c
74 +++ new/clientserver.c
75 @@ -45,6 +45,9 @@ extern int io_timeout;
76  extern int orig_umask;
77  extern int no_detach;
78  extern int default_af_hint;
79 +#if HAVE_OPENSSL
80 +extern int use_ssl;
81 +#endif
82  extern char *bind_address;
83  extern char *sockopts;
84  extern char *config_file;
85 @@ -104,8 +107,18 @@ int start_socket_client(char *host, char
86         set_socket_options(fd, sockopts);
87  
88         ret = start_inband_exchange(user, path, fd, fd, argc);
89 +       if (ret)
90 +               return ret;
91 +
92 +#if HAVE_OPENSSL
93 +       if (use_ssl) {
94 +               int f_in = get_tls_rfd();
95 +               int f_out = get_tls_wfd();
96 +               return client_run(f_in, f_out, -1, argc, argv);
97 +       }
98 +#endif
99  
100 -       return ret ? ret : client_run(fd, fd, -1, argc, argv);
101 +       return client_run(fd, fd, -1, argc, argv);
102  }
103  
104  int start_inband_exchange(char *user, char *path, int f_in, int f_out, 
105 @@ -166,6 +179,33 @@ int start_inband_exchange(char *user, ch
106         if (verbose > 1)
107                 print_child_argv(sargs);
108  
109 +#if HAVE_OPENSSL
110 +       if (use_ssl) {
111 +               io_printf(f_out, "#starttls\n");
112 +               while (1) {
113 +                       if (!read_line(f_in, line, sizeof(line)-1)) {
114 +                               rprintf(FERROR, "rsync: did not receive reply to #starttls\n");
115 +                               return -1;
116 +                       }
117 +                       if (strncmp(line, "@ERROR", 6) == 0) {
118 +                               rprintf(FERROR, "%s\n", line);
119 +                               return -1;
120 +                       }
121 +                       if (strcmp(line, "@RSYNCD: starttls") == 0) {
122 +                               break;
123 +                       }
124 +                       rprintf(FINFO, "%s\n", line);
125 +               }
126 +               if (start_tls(f_in, f_out)) {
127 +                       rprintf(FERROR, "rsync: error during SSL handshake: %s\n",
128 +                               get_ssl_error());
129 +                       return -1;
130 +               }
131 +               f_in = get_tls_rfd();
132 +               f_out = get_tls_wfd();
133 +       }
134 +#endif
135 +
136         p = strchr(path,'/');
137         if (p) *p = 0;
138         io_printf(f_out, "%s\n", path);
139 @@ -194,6 +234,10 @@ int start_inband_exchange(char *user, ch
140                          * server to terminate the listing of modules.
141                          * We don't want to go on and transfer
142                          * anything; just exit. */
143 +#if HAVE_OPENSSL
144 +                       if (use_ssl)
145 +                               end_tls();
146 +#endif
147                         exit(0);
148                 }
149  
150 @@ -201,6 +245,10 @@ int start_inband_exchange(char *user, ch
151                         rprintf(FERROR, "%s\n", line);
152                         /* This is always fatal; the server will now
153                          * close the socket. */
154 +#if HAVE_OPENSSL
155 +                       if (use_ssl)
156 +                               end_tls();
157 +#endif
158                         return -1;
159                 }
160  
161 @@ -716,6 +764,7 @@ static void send_listing(int fd)
162                 io_printf(fd,"@RSYNCD: EXIT\n");
163  }
164  
165 +
166  /* this is called when a connection is established to a client
167     and we want to start talking. The setup of the system is done from
168     here */
169 @@ -768,6 +817,9 @@ int start_daemon(int f_in, int f_out)
170         if (protocol_version > remote_protocol)
171                 protocol_version = remote_protocol;
172  
173 +#if HAVE_OPENSSL
174 +retry:
175 +#endif
176         line[0] = 0;
177         if (!read_line(f_in, line, sizeof line - 1))
178                 return -1;
179 @@ -781,6 +833,20 @@ int start_daemon(int f_in, int f_out)
180                 return -1;
181         }
182  
183 +#if HAVE_OPENSSL
184 +       if (use_ssl && strcmp(line, "#starttls") == 0) {
185 +               io_printf(f_out, "@RSYNCD: starttls\n");
186 +               if (start_tls(f_in, f_out)) {
187 +                       rprintf(FLOG, "SSL connection failed: %s\n",
188 +                               get_ssl_error());
189 +                       return -1;
190 +               }
191 +               f_in = get_tls_rfd();
192 +               f_out = get_tls_wfd();
193 +               goto retry;
194 +       }
195 +#endif
196 +
197         if (*line == '#') {
198                 /* it's some sort of command that I don't understand */
199                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
200 --- old/configure.in
201 +++ new/configure.in
202 @@ -282,6 +282,21 @@ if test x"$enable_locale" != x"no"; then
203         AC_DEFINE(CONFIG_LOCALE)
204  fi
205  
206 +AC_ARG_ENABLE(openssl,
207 +              AC_HELP_STRING([--enable-openssl], [compile SSL support with OpenSSL.]))
208 +
209 +if test "x$enable_openssl" != xno
210 +then
211 +       have_ssl=yes
212 +       AC_CHECK_LIB(ssl, SSL_library_init, , [have_ssl=no])
213 +       if test "x$have_ssl" = xyes
214 +       then
215 +               AC_DEFINE(HAVE_OPENSSL, 1, [true if you want to use SSL.])
216 +               SSL_OBJS=ssl.o
217 +               AC_SUBST(SSL_OBJS)
218 +       fi
219 +fi
220 +
221  AC_MSG_CHECKING([whether to call shutdown on all sockets])
222  case $host_os in
223         *cygwin* ) AC_MSG_RESULT(yes)
224 --- old/options.c
225 +++ new/options.c
226 @@ -168,6 +168,14 @@ int log_format_has_o_or_i = 0;
227  int always_checksum = 0;
228  int list_only = 0;
229  
230 +#if HAVE_OPENSSL
231 +int use_ssl = 0;
232 +char *ssl_cert_path = NULL;
233 +char *ssl_key_path = NULL;
234 +char *ssl_key_passwd = NULL;
235 +char *ssl_ca_path = NULL;
236 +#endif
237 +
238  #define MAX_BATCH_NAME_LEN 256 /* Must be less than MAXPATHLEN-13 */
239  char *batch_name = NULL;
240  
241 @@ -196,6 +204,7 @@ static void print_rsync_version(enum log
242         char const *hardlinks = "no ";
243         char const *links = "no ";
244         char const *ipv6 = "no ";
245 +       char const *ssl = "no ";
246         STRUCT_STAT *dumstat;
247  
248  #ifdef HAVE_SOCKETPAIR
249 @@ -218,6 +227,10 @@ static void print_rsync_version(enum log
250         ipv6 = "";
251  #endif
252  
253 +#if HAVE_OPENSSL
254 +       ssl = "";
255 +#endif
256 +
257         rprintf(f, "%s  version %s  protocol version %d\n",
258                 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION);
259         rprintf(f, "Copyright (C) 1996-2006 by Andrew Tridgell, Wayne Davison, and others.\n");
260 @@ -230,9 +243,9 @@ static void print_rsync_version(enum log
261         /* Note that this field may not have type ino_t.  It depends
262          * on the complicated interaction between largefile feature
263          * macros. */
264 -       rprintf(f, "              %sinplace, %sIPv6, "
265 +       rprintf(f, "              %sinplace, %sIPv6, %sSSL, "
266                 "%d-bit system inums, %d-bit internal inums\n",
267 -               have_inplace, ipv6,
268 +               have_inplace, ipv6, ssl,
269                 (int) (sizeof dumstat->st_ino * 8),
270                 (int) (sizeof (int64) * 8));
271  #ifdef MAINTAINER_MODE
272 @@ -373,6 +386,13 @@ void usage(enum logcode F)
273    rprintf(F," -4, --ipv4                  prefer IPv4\n");
274    rprintf(F," -6, --ipv6                  prefer IPv6\n");
275  #endif
276 +#if HAVE_OPENSSL
277 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
278 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
279 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
280 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
281 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
282 +#endif
283    rprintf(F,"     --version               print version number\n");
284    rprintf(F,"     --help                  show this help screen\n");
285  
286 @@ -385,7 +405,7 @@ enum {OPT_VERSION = 1000, OPT_DAEMON, OP
287        OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
288        OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
289        OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
290 -      OPT_NO_D,
291 +      OPT_NO_D, OPT_USE_SSL,
292        OPT_SERVER, OPT_REFUSED_BASE = 9000};
293  
294  static struct poptOption long_options[] = {
295 @@ -523,6 +543,13 @@ static struct poptOption long_options[] 
296    {"checksum-seed",    0,  POPT_ARG_INT,    &checksum_seed, 0, 0, 0 },
297    {"server",           0,  POPT_ARG_NONE,   0, OPT_SERVER, 0, 0 },
298    {"sender",           0,  POPT_ARG_NONE,   0, OPT_SENDER, 0, 0 },
299 +#if HAVE_OPENSSL
300 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
301 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
302 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
303 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
304 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
305 +#endif
306    /* All the following options switch us into daemon-mode option-parsing. */
307    {"config",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
308    {"daemon",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
309 @@ -1060,6 +1087,12 @@ int parse_arguments(int *argc, const cha
310                         usage(FINFO);
311                         exit_cleanup(0);
312  
313 +               case OPT_USE_SSL:
314 +#if HAVE_OPENSSL
315 +                       use_ssl = 1;
316 +#endif
317 +                       break;
318 +
319                 default:
320                         /* A large opt value means that set_refuse_options()
321                          * turned this option off. */
322 @@ -1337,6 +1370,17 @@ int parse_arguments(int *argc, const cha
323         if (delay_updates && !partial_dir)
324                 partial_dir = tmp_partialdir;
325  
326 +#if HAVE_OPENSSL
327 +       if (use_ssl) {
328 +               if (init_tls()) {
329 +                       snprintf(err_buf, sizeof(err_buf),
330 +                                "Openssl error: %s\n",
331 +                                get_ssl_error());
332 +                       return 0;
333 +               }
334 +       }
335 +#endif
336 +
337         if (inplace) {
338  #ifdef HAVE_FTRUNCATE
339                 if (partial_dir) {
340 @@ -1748,11 +1792,28 @@ char *check_for_hostspec(char *s, char *
341  {
342         char *p;
343         int not_host;
344 +       int url_prefix_len = sizeof URL_PREFIX - 1;
345  
346 -       if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
347 +       if (!port_ptr)
348 +               url_prefix_len = 0;
349 +       else if (strncasecmp(URL_PREFIX, s, url_prefix_len) != 0) {
350 +#if HAVE_OPENSSL
351 +               url_prefix_len = sizeof SSL_URL_PREFIX - 1;
352 +               if (strncasecmp(SSL_URL_PREFIX, s, url_prefix_len) != 0)
353 +                       url_prefix_len = 0;
354 +               else {
355 +                       if (!use_ssl)
356 +                               init_tls();
357 +                       use_ssl = 1;
358 +               }
359 +#else
360 +               url_prefix_len = 0;
361 +#endif
362 +       }
363 +       if (url_prefix_len) {
364                 char *path;
365                 int hostlen;
366 -               s += strlen(URL_PREFIX);
367 +               s += url_prefix_len;
368                 if ((p = strchr(s, '/')) != NULL) {
369                         hostlen = p - s;
370                         path = p + 1;
371 --- old/rsync.h
372 +++ new/rsync.h
373 @@ -32,6 +32,7 @@
374  
375  #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
376  #define URL_PREFIX "rsync://"
377 +#define SSL_URL_PREFIX "rsyncs://"
378  
379  #define BACKUP_SUFFIX "~"
380  
381 @@ -410,6 +411,11 @@ enum msgcode {
382  # define SIZEOF_INT64 SIZEOF_OFF_T
383  #endif
384  
385 +#if HAVE_OPENSSL
386 +#include <openssl/ssl.h>
387 +#include <openssl/err.h>
388 +#endif
389 +
390  /* Starting from protocol version 26, we always use 64-bit
391   * ino_t and dev_t internally, even if this platform does not
392   * allow files to have 64-bit inums.  That's because the
393 --- old/ssl.c
394 +++ new/ssl.c
395 @@ -0,0 +1,366 @@
396 +/* -*- c-file-style: "linux" -*-
397 + * ssl.c: operations for negotiating SSL rsync connections. 
398 + *
399 + * Copyright (C) 2003  Casey Marshall <rsdio@metastatic.org>
400 + *
401 + * This program is free software; you can redistribute it and/or modify
402 + * it under the terms of the GNU General Public License as published by
403 + * the Free Software Foundation; either version 2 of the License, or
404 + * (at your option) any later version.
405 + * 
406 + * This program is distributed in the hope that it will be useful,
407 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
408 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
409 + * GNU General Public License for more details.
410 + * 
411 + * You should have received a copy of the GNU General Public License
412 + * along with this program; if not, write to the Free Software
413 + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
414 + */
415 +
416 +#include "rsync.h"
417 +
418 +#if HAVE_SYS_SELECT_H
419 +#include <sys/select.h>
420 +#else
421 +#include <sys/time.h>
422 +#include <sys/types.h>
423 +#include <unistd.h>
424 +#endif
425 +#include <string.h>
426 +
427 +#define BUF_SIZE 1024
428 +
429 +extern int verbose;
430 +extern int am_daemon;
431 +extern int am_server;
432 +
433 +extern char *ssl_cert_path;
434 +extern char *ssl_key_path;
435 +extern char *ssl_key_passwd;
436 +extern char *ssl_ca_path;
437 +
438 +static SSL_CTX *ssl_ctx;
439 +static SSL *ssl;
440 +static int tls_read[2] = { -1, -1 };
441 +static int tls_write[2] = { -1, -1 };
442 +static int ssl_running;
443 +static int ssl_pid = -1;
444 +
445 +/**
446 + * A non-interactive callback to be passed to SSL_CTX_set_default_password_cb,
447 + * which merely copies the value of ssl_key_passwd into buf. This is
448 + * used for when the private key password is supplied via an option.
449 + */
450 +static int default_password_cb(char *buf, int n, UNUSED(int f), UNUSED(void *u))
451 +{
452 +       if (ssl_key_passwd == NULL || n < (int)strlen(ssl_key_passwd))
453 +               return 0;
454 +       strncpy(buf, ssl_key_passwd, n-1);
455 +       return strlen(ssl_key_passwd);
456 +}
457 +
458 +/**
459 + * If verbose, this method traces the status of the SSL handshake.
460 + */
461 +static void info_callback(const SSL *ssl, int cb, int val)
462 +{
463 +       char buf[128];
464 +       char *cbs;
465 +
466 +       switch (cb) {
467 +       case SSL_CB_LOOP:
468 +               cbs = "SSL_CB_LOOP";
469 +               break;
470 +       case SSL_CB_EXIT:
471 +               cbs = "SSL_CB_EXIT";
472 +               break;
473 +       case SSL_CB_READ:
474 +               cbs = "SSL_CB_READ";
475 +               break;
476 +       case SSL_CB_WRITE:
477 +               cbs = "SSL_CB_WRITE";
478 +               break;
479 +       case SSL_CB_ALERT:
480 +               cbs = "SSL_CB_ALERT";
481 +               break;
482 +       case SSL_CB_READ_ALERT:
483 +               cbs = "SSL_CB_READ_ALERT";
484 +               break;
485 +       case SSL_CB_WRITE_ALERT:
486 +               cbs = "SSL_CB_WRITE_ALERT";
487 +               break;
488 +       case SSL_CB_ACCEPT_LOOP:
489 +               cbs = "SSL_CB_ACCEPT_LOOP";
490 +               break;
491 +       case SSL_CB_ACCEPT_EXIT:
492 +               cbs = "SSL_CB_ACCEPT_EXIT";
493 +               break;
494 +       case SSL_CB_CONNECT_LOOP:
495 +               cbs = "SSL_CB_CONNECT_LOOP";
496 +               break;
497 +       case SSL_CB_CONNECT_EXIT:
498 +               cbs = "SSL_CB_CONNECT_EXIT";
499 +               break;
500 +       case SSL_CB_HANDSHAKE_START:
501 +               cbs = "SSL_CB_HANDSHAKE_START";
502 +               break;
503 +       case SSL_CB_HANDSHAKE_DONE:
504 +               cbs = "SSL_CB_HANDSHAKE_DONE";
505 +               break;
506 +       default:
507 +               snprintf(buf, sizeof buf, "??? (%d)", cb);
508 +               cbs = buf;
509 +               break;
510 +       }
511 +       if (verbose > 2) {
512 +               rprintf(FLOG, "SSL: info_callback(%p,%s,%d)\n", ssl, cbs, val);
513 +               if (cb == SSL_CB_HANDSHAKE_DONE) {
514 +                       SSL_CIPHER_description(SSL_get_current_cipher((SSL*)ssl),
515 +                                              buf, sizeof buf);
516 +                       rprintf(FLOG, "SSL: cipher: %s", buf);
517 +               }
518 +       }
519 +}
520 +
521 +/**
522 + * Initializes the SSL context for TLSv1 connections; returns zero on
523 + * success.
524 + */
525 +int init_tls(void)
526 +{
527 +       if (ssl_ctx)
528 +               return 0;
529 +       SSL_library_init();
530 +       SSL_load_error_strings();
531 +       ssl_ctx = SSL_CTX_new(TLSv1_method());
532 +       if (!ssl_ctx)
533 +               return 1;
534 +       SSL_CTX_set_info_callback(ssl_ctx, info_callback);
535 +
536 +       /* Sets the certificate sent to the other party. */
537 +       if (ssl_cert_path != NULL
538 +           && SSL_CTX_use_certificate_file(ssl_ctx, ssl_cert_path,
539 +                                           SSL_FILETYPE_PEM) != 1)
540 +               return 1;
541 +       /* Set up the simple non-interactive callback if the password
542 +        * was supplied on the command line. */
543 +       if (ssl_key_passwd != NULL)
544 +               SSL_CTX_set_default_passwd_cb(ssl_ctx, default_password_cb);
545 +       /* Sets the private key that matches the public certificate. */
546 +       if (ssl_key_path != NULL) {
547 +               if (SSL_CTX_use_PrivateKey_file(ssl_ctx, ssl_key_path,
548 +                                               SSL_FILETYPE_PEM) != 1)
549 +                       return 1;
550 +               if (SSL_CTX_check_private_key(ssl_ctx) != 1)
551 +                       return 1;
552 +       }
553 +       if (ssl_ca_path != NULL
554 +           && !SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_path, NULL))
555 +               return 1;
556 +
557 +       return 0;
558 +}
559 +
560 +/**
561 + * Returns the error string for the current SSL error, if any.
562 + */
563 +char *get_ssl_error(void)
564 +{
565 +       return ERR_error_string(ERR_get_error(), NULL);
566 +}
567 +
568 +/**
569 + * Returns the input file descriptor for the SSL connection.
570 + */
571 +int get_tls_rfd(void)
572 +{
573 +       return tls_read[0];
574 +}
575 +
576 +/**
577 + * Returns the output file descriptor for the SSL connection.
578 + */
579 +int get_tls_wfd(void)
580 +{
581 +       return tls_write[1];
582 +}
583 +
584 +/**
585 + * Signal handler that ends the SSL connection.
586 + */
587 +static RETSIGTYPE tls_sigusr1(int UNUSED(val))
588 +{
589 +       if (ssl) {
590 +               SSL_shutdown(ssl);
591 +               SSL_free(ssl);
592 +               ssl = NULL;
593 +       }
594 +       ssl_running = 0;
595 +}
596 +
597 +/**
598 + * Negotiates the TLS connection, creates a socket pair for communicating
599 + * with the rsync process, then forks into a new process that will handle
600 + * the communication.
601 + *
602 + * 0 is returned on success.
603 + */
604 +int start_tls(int f_in, int f_out)
605 +{
606 +       int tls_fd;
607 +       int n = 0, r;
608 +       unsigned char buf1[BUF_SIZE], buf2[BUF_SIZE];
609 +       int avail1 = 0, avail2 = 0, write1 = 0, write2 = 0;
610 +       fd_set rd, wd;
611 +
612 +       if (fd_pair(tls_read))
613 +               return 1;
614 +       if (fd_pair(tls_write))
615 +               return 1;
616 +
617 +       set_blocking(tls_read[0]);
618 +       set_blocking(tls_read[1]);
619 +       set_blocking(tls_write[0]);
620 +       set_blocking(tls_write[1]);
621 +       set_blocking(f_in);
622 +       set_blocking(f_out);
623 +
624 +       ssl_pid = do_fork();
625 +       if (ssl_pid < 0)
626 +               return -1;
627 +       if (ssl_pid != 0) {
628 +               close(tls_write[0]);
629 +               close(tls_read[1]);
630 +               return 0;
631 +       }
632 +
633 +       signal(SIGUSR1, tls_sigusr1);
634 +       ssl = SSL_new(ssl_ctx);
635 +       if (!ssl)
636 +               goto closed;
637 +       if (am_daemon || am_server)
638 +               SSL_set_accept_state(ssl);
639 +       else
640 +               SSL_set_connect_state(ssl);
641 +       SSL_set_rfd(ssl, f_in);
642 +       SSL_set_wfd(ssl, f_out);
643 +
644 +       tls_fd = SSL_get_fd(ssl);
645 +       n = tls_write[0];
646 +       n = MAX(tls_read[1], n);
647 +       n = MAX(tls_fd, n) + 1;
648 +
649 +       ssl_running = 1;
650 +       while (ssl_running) {
651 +               FD_ZERO(&rd);
652 +               FD_ZERO(&wd);
653 +               FD_SET(tls_write[0], &rd);
654 +               FD_SET(tls_read[1], &wd);
655 +               FD_SET(tls_fd, &rd);
656 +               FD_SET(tls_fd, &wd);
657 +
658 +               r = select(n, &rd, &wd, NULL, NULL);
659 +
660 +               if (r == -1 && errno == EINTR)
661 +                       continue;
662 +               if (FD_ISSET(tls_write[0], &rd)) {
663 +                       r = read(tls_write[0], buf1+avail1, BUF_SIZE-avail1);
664 +                       if (r >= 0)
665 +                               avail1 += r;
666 +                       else {
667 +                               rprintf(FERROR, "pipe read error: %s\n",
668 +                                       strerror(errno));
669 +                               break;
670 +                       }
671 +               }
672 +               if (FD_ISSET(tls_fd, &rd)) {
673 +                       r = SSL_read(ssl, buf2+avail2, BUF_SIZE-avail2);
674 +                       if (r > 0)
675 +                               avail2 += r;
676 +                       else {
677 +                               switch (SSL_get_error(ssl, r)) {
678 +                               case SSL_ERROR_ZERO_RETURN:
679 +                                       goto closed;
680 +                               case SSL_ERROR_WANT_READ:
681 +                               case SSL_ERROR_WANT_WRITE:
682 +                                       break;
683 +                               case SSL_ERROR_SYSCALL:
684 +                                       if (r == 0)
685 +                                               rprintf(FERROR, "SSL spurious EOF\n");
686 +                                       else
687 +                                               rprintf(FERROR, "SSL I/O error: %s\n",
688 +                                                       strerror(errno));
689 +                                       goto closed;
690 +                               case SSL_ERROR_SSL:
691 +                                       rprintf(FERROR, "SSL: %s\n",
692 +                                               ERR_error_string(ERR_get_error(), NULL));
693 +                                       goto closed;
694 +                               default:
695 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
696 +                                       goto closed;
697 +                               }
698 +                       }
699 +               }
700 +               if (FD_ISSET(tls_read[1], &wd) && write2 < avail2) {
701 +                       r = write(tls_read[1], buf2+write2, avail2-write2);
702 +                       if (r >= 0)
703 +                               write2 += r;
704 +                       else {
705 +                               rprintf(FERROR, "pipe write error: %s\n",
706 +                                       strerror(errno));
707 +                               break;
708 +                       }
709 +               }
710 +               if (FD_ISSET(tls_fd, &wd) && write1 < avail1) {
711 +                       r = SSL_write(ssl, buf1+write1, avail1-write1);
712 +                       if (r > 0)
713 +                               write1 += r;
714 +                       else {
715 +                               switch (SSL_get_error(ssl, r)) {
716 +                               case SSL_ERROR_ZERO_RETURN:
717 +                                       goto closed;
718 +                               case SSL_ERROR_WANT_READ:
719 +                               case SSL_ERROR_WANT_WRITE:
720 +                                       break;
721 +                               case SSL_ERROR_SYSCALL:
722 +                                       if (r == 0)
723 +                                               rprintf(FERROR, "SSL: spurious EOF\n");
724 +                                       else
725 +                                               rprintf(FERROR, "SSL: I/O error: %s\n",
726 +                                                       strerror(errno));
727 +                                       goto closed;
728 +                               case SSL_ERROR_SSL:
729 +                                       rprintf(FERROR, "SSL: %s\n",
730 +                                               ERR_error_string(ERR_get_error(), NULL));
731 +                                       goto closed;
732 +                               default:
733 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
734 +                                       goto closed;
735 +                               }
736 +                       }
737 +               }
738 +               if (avail1 == write1)
739 +                       avail1 = write1 = 0;
740 +               if (avail2 == write2)
741 +                       avail2 = write2 = 0;
742 +       }
743 +
744 +       /* XXX I'm pretty sure that there is a lot that I am not considering
745 +          here. Bugs? Yes, probably. */
746 +
747 +       /* We're finished. */
748 +    closed:
749 +       close(tls_read[1]);
750 +       close(tls_write[0]);
751 +       exit(0);
752 +}
753 +
754 +/**
755 + * Ends the TLS connection.
756 + */
757 +void end_tls(void)
758 +{
759 +       if (ssl_pid > 0)
760 +               kill(ssl_pid, SIGUSR1);
761 +}