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