Some improvements from marineam@osuosl.org.
[rsync/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 @@ -39,7 +39,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 @@ -26,6 +26,9 @@
52  extern int am_server;
53  extern int am_daemon;
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 @@ -106,6 +109,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 @@ -29,6 +29,9 @@ extern int am_sender;
76  extern int am_server;
77  extern int am_daemon;
78  extern int am_root;
79 +#if HAVE_OPENSSL
80 +extern int use_ssl;
81 +#endif
82  extern int rsync_port;
83  extern int kluge_around_eof;
84  extern int daemon_over_rsh;
85 @@ -105,8 +108,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 @@ -167,6 +180,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 @@ -195,6 +235,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 @@ -202,6 +246,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 @@ -718,6 +766,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 @@ -776,6 +825,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 @@ -787,6 +839,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 @@ -290,6 +290,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 @@ -172,6 +172,14 @@ int logfile_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 @@ -200,6 +208,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 @@ -222,6 +231,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 @@ -234,9 +247,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 @@ -383,6 +396,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,"(-h) --help                  show this help (-h works with no other options)\n");
285  
286 @@ -396,7 +416,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 @@ -541,6 +561,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 @@ -568,6 +595,13 @@ static void daemon_usage(enum logcode F)
310    rprintf(F," -4, --ipv4                  prefer IPv4\n");
311    rprintf(F," -6, --ipv6                  prefer IPv6\n");
312  #endif
313 +#if HAVE_OPENSSL
314 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
315 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
316 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
317 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
318 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
319 +#endif
320    rprintf(F,"     --help                  show this help screen\n");
321  
322    rprintf(F,"\n");
323 @@ -594,6 +628,13 @@ static struct poptOption long_daemon_opt
324    {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
325    {"server",           0,  POPT_ARG_NONE,   &am_server, 0, 0, 0 },
326    {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
327 +#if HAVE_OPENSSL
328 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
329 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
330 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
331 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
332 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
333 +#endif
334    {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
335    {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
336    {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
337 @@ -848,6 +889,12 @@ int parse_arguments(int *argc, const cha
338                                         verbose++;
339                                         break;
340  
341 +#ifdef HAVE_OPENSSL
342 +                               case OPT_USE_SSL:
343 +                                       use_ssl = 1;
344 +                                       break;
345 +#endif
346 +
347                                 default:
348                                         rprintf(FERROR,
349                                             "rsync: %s: %s (in daemon mode)\n",
350 @@ -871,6 +918,17 @@ int parse_arguments(int *argc, const cha
351                                 exit_cleanup(RERR_SYNTAX);
352                         }
353  
354 +#ifdef HAVE_OPENSSL
355 +                       if (use_ssl) {
356 +                               if (init_tls()) {
357 +                                       snprintf(err_buf, sizeof(err_buf),
358 +                                                "Openssl error: %s\n",
359 +                                                get_ssl_error());
360 +                                       return 0;
361 +                               }
362 +                       }
363 +#endif
364 +
365                         *argv = poptGetArgs(pc);
366                         *argc = count_args(*argv);
367                         am_starting_up = 0;
368 @@ -1084,6 +1142,12 @@ int parse_arguments(int *argc, const cha
369                         usage(FINFO);
370                         exit_cleanup(0);
371  
372 +#if HAVE_OPENSSL
373 +               case OPT_USE_SSL:
374 +                       use_ssl = 1;
375 +                       break;
376 +#endif
377 +
378                 default:
379                         /* A large opt value means that set_refuse_options()
380                          * turned this option off. */
381 @@ -1364,6 +1428,17 @@ int parse_arguments(int *argc, const cha
382         if (delay_updates && !partial_dir)
383                 partial_dir = tmp_partialdir;
384  
385 +#if HAVE_OPENSSL
386 +       if (use_ssl) {
387 +               if (init_tls()) {
388 +                       snprintf(err_buf, sizeof(err_buf),
389 +                                "Openssl error: %s\n",
390 +                                get_ssl_error());
391 +                       return 0;
392 +               }
393 +       }
394 +#endif
395 +
396         if (inplace) {
397  #ifdef HAVE_FTRUNCATE
398                 if (partial_dir) {
399 @@ -1781,10 +1856,27 @@ char *check_for_hostspec(char *s, char *
400         char *p;
401         int not_host;
402         int hostlen;
403 +       int url_prefix_len = sizeof URL_PREFIX - 1;
404  
405 -       if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
406 +       if (!port_ptr)
407 +               url_prefix_len = 0;
408 +       else if (strncasecmp(URL_PREFIX, s, url_prefix_len) != 0) {
409 +#if HAVE_OPENSSL
410 +               url_prefix_len = sizeof SSL_URL_PREFIX - 1;
411 +               if (strncasecmp(SSL_URL_PREFIX, s, url_prefix_len) != 0)
412 +                       url_prefix_len = 0;
413 +               else {
414 +                       if (!use_ssl)
415 +                               init_tls();
416 +                       use_ssl = 1;
417 +               }
418 +#else
419 +               url_prefix_len = 0;
420 +#endif
421 +       }
422 +       if (url_prefix_len) {
423                 char *path;
424 -               s += strlen(URL_PREFIX);
425 +               s += url_prefix_len;
426                 if ((p = strchr(s, '/')) != NULL) {
427                         hostlen = p - s;
428                         path = p + 1;
429 --- old/rsync.h
430 +++ new/rsync.h
431 @@ -32,6 +32,7 @@
432  
433  #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
434  #define URL_PREFIX "rsync://"
435 +#define SSL_URL_PREFIX "rsyncs://"
436  
437  #define BACKUP_SUFFIX "~"
438  
439 @@ -419,6 +420,11 @@ enum msgcode {
440  # define SIZEOF_INT64 SIZEOF_OFF_T
441  #endif
442  
443 +#if HAVE_OPENSSL
444 +#include <openssl/ssl.h>
445 +#include <openssl/err.h>
446 +#endif
447 +
448  /* Starting from protocol version 26, we always use 64-bit
449   * ino_t and dev_t internally, even if this platform does not
450   * allow files to have 64-bit inums.  That's because the
451 --- old/ssl.c
452 +++ new/ssl.c
453 @@ -0,0 +1,370 @@
454 +/* -*- c-file-style: "linux" -*-
455 + * ssl.c: operations for negotiating SSL rsync connections. 
456 + *
457 + * Copyright (C) 2003  Casey Marshall <rsdio@metastatic.org>
458 + *
459 + * This program is free software; you can redistribute it and/or modify
460 + * it under the terms of the GNU General Public License as published by
461 + * the Free Software Foundation; either version 2 of the License, or
462 + * (at your option) any later version.
463 + * 
464 + * This program is distributed in the hope that it will be useful,
465 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
466 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
467 + * GNU General Public License for more details.
468 + * 
469 + * You should have received a copy of the GNU General Public License
470 + * along with this program; if not, write to the Free Software
471 + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
472 + */
473 +
474 +#include "rsync.h"
475 +
476 +#if HAVE_SYS_SELECT_H
477 +#include <sys/select.h>
478 +#else
479 +#include <sys/time.h>
480 +#include <sys/types.h>
481 +#include <unistd.h>
482 +#endif
483 +#include <string.h>
484 +
485 +#define BUF_SIZE 1024
486 +
487 +extern int verbose;
488 +extern int am_daemon;
489 +extern int am_server;
490 +
491 +extern char *ssl_cert_path;
492 +extern char *ssl_key_path;
493 +extern char *ssl_key_passwd;
494 +extern char *ssl_ca_path;
495 +
496 +static SSL_CTX *ssl_ctx;
497 +static SSL *ssl;
498 +static int tls_read[2] = { -1, -1 };
499 +static int tls_write[2] = { -1, -1 };
500 +static int ssl_running;
501 +static int ssl_pid = -1;
502 +
503 +#ifdef HAVE_SIGACTION
504 +static struct sigaction sigact;
505 +#endif
506 +
507 +/**
508 + * A non-interactive callback to be passed to SSL_CTX_set_default_password_cb,
509 + * which merely copies the value of ssl_key_passwd into buf. This is
510 + * used for when the private key password is supplied via an option.
511 + */
512 +static int default_password_cb(char *buf, int n, UNUSED(int f), UNUSED(void *u))
513 +{
514 +       if (ssl_key_passwd == NULL || n < (int)strlen(ssl_key_passwd))
515 +               return 0;
516 +       strncpy(buf, ssl_key_passwd, n-1);
517 +       return strlen(ssl_key_passwd);
518 +}
519 +
520 +/**
521 + * If verbose, this method traces the status of the SSL handshake.
522 + */
523 +static void info_callback(const SSL *ssl, int cb, int val)
524 +{
525 +       char buf[128];
526 +       char *cbs;
527 +
528 +       switch (cb) {
529 +       case SSL_CB_LOOP:
530 +               cbs = "SSL_CB_LOOP";
531 +               break;
532 +       case SSL_CB_EXIT:
533 +               cbs = "SSL_CB_EXIT";
534 +               break;
535 +       case SSL_CB_READ:
536 +               cbs = "SSL_CB_READ";
537 +               break;
538 +       case SSL_CB_WRITE:
539 +               cbs = "SSL_CB_WRITE";
540 +               break;
541 +       case SSL_CB_ALERT:
542 +               cbs = "SSL_CB_ALERT";
543 +               break;
544 +       case SSL_CB_READ_ALERT:
545 +               cbs = "SSL_CB_READ_ALERT";
546 +               break;
547 +       case SSL_CB_WRITE_ALERT:
548 +               cbs = "SSL_CB_WRITE_ALERT";
549 +               break;
550 +       case SSL_CB_ACCEPT_LOOP:
551 +               cbs = "SSL_CB_ACCEPT_LOOP";
552 +               break;
553 +       case SSL_CB_ACCEPT_EXIT:
554 +               cbs = "SSL_CB_ACCEPT_EXIT";
555 +               break;
556 +       case SSL_CB_CONNECT_LOOP:
557 +               cbs = "SSL_CB_CONNECT_LOOP";
558 +               break;
559 +       case SSL_CB_CONNECT_EXIT:
560 +               cbs = "SSL_CB_CONNECT_EXIT";
561 +               break;
562 +       case SSL_CB_HANDSHAKE_START:
563 +               cbs = "SSL_CB_HANDSHAKE_START";
564 +               break;
565 +       case SSL_CB_HANDSHAKE_DONE:
566 +               cbs = "SSL_CB_HANDSHAKE_DONE";
567 +               break;
568 +       default:
569 +               snprintf(buf, sizeof buf, "??? (%d)", cb);
570 +               cbs = buf;
571 +               break;
572 +       }
573 +       if (verbose > 2) {
574 +               rprintf(FLOG, "SSL: info_callback(%p,%s,%d)\n", ssl, cbs, val);
575 +               if (cb == SSL_CB_HANDSHAKE_DONE) {
576 +                       SSL_CIPHER_description(SSL_get_current_cipher((SSL*)ssl),
577 +                                              buf, sizeof buf);
578 +                       rprintf(FLOG, "SSL: cipher: %s", buf);
579 +               }
580 +       }
581 +}
582 +
583 +/**
584 + * Initializes the SSL context for TLSv1 connections; returns zero on
585 + * success.
586 + */
587 +int init_tls(void)
588 +{
589 +       if (ssl_ctx)
590 +               return 0;
591 +       SSL_library_init();
592 +       SSL_load_error_strings();
593 +       ssl_ctx = SSL_CTX_new(TLSv1_method());
594 +       if (!ssl_ctx)
595 +               return 1;
596 +       SSL_CTX_set_info_callback(ssl_ctx, info_callback);
597 +
598 +       /* Sets the certificate sent to the other party. */
599 +       if (ssl_cert_path != NULL
600 +           && SSL_CTX_use_certificate_file(ssl_ctx, ssl_cert_path,
601 +                                           SSL_FILETYPE_PEM) != 1)
602 +               return 1;
603 +       /* Set up the simple non-interactive callback if the password
604 +        * was supplied on the command line. */
605 +       if (ssl_key_passwd != NULL)
606 +               SSL_CTX_set_default_passwd_cb(ssl_ctx, default_password_cb);
607 +       /* Sets the private key that matches the public certificate. */
608 +       if (ssl_key_path != NULL) {
609 +               if (SSL_CTX_use_PrivateKey_file(ssl_ctx, ssl_key_path,
610 +                                               SSL_FILETYPE_PEM) != 1)
611 +                       return 1;
612 +               if (SSL_CTX_check_private_key(ssl_ctx) != 1)
613 +                       return 1;
614 +       }
615 +       if (ssl_ca_path != NULL
616 +           && !SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_path, NULL))
617 +               return 1;
618 +
619 +       return 0;
620 +}
621 +
622 +/**
623 + * Returns the error string for the current SSL error, if any.
624 + */
625 +char *get_ssl_error(void)
626 +{
627 +       return ERR_error_string(ERR_get_error(), NULL);
628 +}
629 +
630 +/**
631 + * Returns the input file descriptor for the SSL connection.
632 + */
633 +int get_tls_rfd(void)
634 +{
635 +       return tls_read[0];
636 +}
637 +
638 +/**
639 + * Returns the output file descriptor for the SSL connection.
640 + */
641 +int get_tls_wfd(void)
642 +{
643 +       return tls_write[1];
644 +}
645 +
646 +/**
647 + * Signal handler that ends the SSL connection.
648 + */
649 +static RETSIGTYPE tls_sigusr1(int UNUSED(val))
650 +{
651 +       if (ssl) {
652 +               SSL_shutdown(ssl);
653 +               SSL_free(ssl);
654 +               ssl = NULL;
655 +       }
656 +       ssl_running = 0;
657 +}
658 +
659 +/**
660 + * Negotiates the TLS connection, creates a socket pair for communicating
661 + * with the rsync process, then forks into a new process that will handle
662 + * the communication.
663 + *
664 + * 0 is returned on success.
665 + */
666 +int start_tls(int f_in, int f_out)
667 +{
668 +       int tls_fd;
669 +       int n = 0, r;
670 +       unsigned char buf1[BUF_SIZE], buf2[BUF_SIZE];
671 +       int avail1 = 0, avail2 = 0, write1 = 0, write2 = 0;
672 +       fd_set rd, wd;
673 +
674 +       if (fd_pair(tls_read))
675 +               return 1;
676 +       if (fd_pair(tls_write))
677 +               return 1;
678 +
679 +       set_blocking(tls_read[0]);
680 +       set_blocking(tls_read[1]);
681 +       set_blocking(tls_write[0]);
682 +       set_blocking(tls_write[1]);
683 +       set_blocking(f_in);
684 +       set_blocking(f_out);
685 +
686 +       ssl_pid = do_fork();
687 +       if (ssl_pid < 0)
688 +               return -1;
689 +       if (ssl_pid != 0) {
690 +               close(tls_write[0]);
691 +               close(tls_read[1]);
692 +               return 0;
693 +       }
694 +
695 +       SIGACTION(SIGUSR1, tls_sigusr1);
696 +       ssl = SSL_new(ssl_ctx);
697 +       if (!ssl)
698 +               goto closed;
699 +       if (am_daemon || am_server)
700 +               SSL_set_accept_state(ssl);
701 +       else
702 +               SSL_set_connect_state(ssl);
703 +       SSL_set_rfd(ssl, f_in);
704 +       SSL_set_wfd(ssl, f_out);
705 +
706 +       tls_fd = SSL_get_fd(ssl);
707 +       n = tls_write[0];
708 +       n = MAX(tls_read[1], n);
709 +       n = MAX(tls_fd, n) + 1;
710 +
711 +       ssl_running = 1;
712 +       while (ssl_running) {
713 +               FD_ZERO(&rd);
714 +               FD_ZERO(&wd);
715 +               FD_SET(tls_write[0], &rd);
716 +               FD_SET(tls_read[1], &wd);
717 +               FD_SET(tls_fd, &rd);
718 +               FD_SET(tls_fd, &wd);
719 +
720 +               r = select(n, &rd, &wd, NULL, NULL);
721 +
722 +               if (r == -1 && errno == EINTR)
723 +                       continue;
724 +               if (FD_ISSET(tls_write[0], &rd)) {
725 +                       r = read(tls_write[0], buf1+avail1, BUF_SIZE-avail1);
726 +                       if (r >= 0)
727 +                               avail1 += r;
728 +                       else {
729 +                               rprintf(FERROR, "pipe read error: %s\n",
730 +                                       strerror(errno));
731 +                               break;
732 +                       }
733 +               }
734 +               if (FD_ISSET(tls_fd, &rd)) {
735 +                       r = SSL_read(ssl, buf2+avail2, BUF_SIZE-avail2);
736 +                       if (r > 0)
737 +                               avail2 += r;
738 +                       else {
739 +                               switch (SSL_get_error(ssl, r)) {
740 +                               case SSL_ERROR_ZERO_RETURN:
741 +                                       goto closed;
742 +                               case SSL_ERROR_WANT_READ:
743 +                               case SSL_ERROR_WANT_WRITE:
744 +                                       break;
745 +                               case SSL_ERROR_SYSCALL:
746 +                                       if (r == 0)
747 +                                               rprintf(FERROR, "SSL spurious EOF\n");
748 +                                       else
749 +                                               rprintf(FERROR, "SSL I/O error: %s\n",
750 +                                                       strerror(errno));
751 +                                       goto closed;
752 +                               case SSL_ERROR_SSL:
753 +                                       rprintf(FERROR, "SSL: %s\n",
754 +                                               ERR_error_string(ERR_get_error(), NULL));
755 +                                       goto closed;
756 +                               default:
757 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
758 +                                       goto closed;
759 +                               }
760 +                       }
761 +               }
762 +               if (FD_ISSET(tls_read[1], &wd) && write2 < avail2) {
763 +                       r = write(tls_read[1], buf2+write2, avail2-write2);
764 +                       if (r >= 0)
765 +                               write2 += r;
766 +                       else {
767 +                               rprintf(FERROR, "pipe write error: %s\n",
768 +                                       strerror(errno));
769 +                               break;
770 +                       }
771 +               }
772 +               if (FD_ISSET(tls_fd, &wd) && write1 < avail1) {
773 +                       r = SSL_write(ssl, buf1+write1, avail1-write1);
774 +                       if (r > 0)
775 +                               write1 += r;
776 +                       else {
777 +                               switch (SSL_get_error(ssl, r)) {
778 +                               case SSL_ERROR_ZERO_RETURN:
779 +                                       goto closed;
780 +                               case SSL_ERROR_WANT_READ:
781 +                               case SSL_ERROR_WANT_WRITE:
782 +                                       break;
783 +                               case SSL_ERROR_SYSCALL:
784 +                                       if (r == 0)
785 +                                               rprintf(FERROR, "SSL: spurious EOF\n");
786 +                                       else
787 +                                               rprintf(FERROR, "SSL: I/O error: %s\n",
788 +                                                       strerror(errno));
789 +                                       goto closed;
790 +                               case SSL_ERROR_SSL:
791 +                                       rprintf(FERROR, "SSL: %s\n",
792 +                                               ERR_error_string(ERR_get_error(), NULL));
793 +                                       goto closed;
794 +                               default:
795 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
796 +                                       goto closed;
797 +                               }
798 +                       }
799 +               }
800 +               if (avail1 == write1)
801 +                       avail1 = write1 = 0;
802 +               if (avail2 == write2)
803 +                       avail2 = write2 = 0;
804 +       }
805 +
806 +       /* XXX I'm pretty sure that there is a lot that I am not considering
807 +          here. Bugs? Yes, probably. */
808 +
809 +       /* We're finished. */
810 +    closed:
811 +       close(tls_read[1]);
812 +       close(tls_write[0]);
813 +       exit(0);
814 +}
815 +
816 +/**
817 + * Ends the TLS connection.
818 + */
819 +void end_tls(void)
820 +{
821 +       if (ssl_pid > 0)
822 +               kill(ssl_pid, SIGUSR1);
823 +}