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