The patches for 3.0.9.
[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 based-on: 40afd365cc8ca968fd16e161d24df5b8a8a520cc
39 diff --git a/Makefile.in b/Makefile.in
40 --- a/Makefile.in
41 +++ b/Makefile.in
42 @@ -40,7 +40,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 lib/sysxattrs.o @BUILD_POPT@
50  
51 diff --git a/cleanup.c b/cleanup.c
52 --- a/cleanup.c
53 +++ b/cleanup.c
54 @@ -26,6 +26,9 @@ extern int am_server;
55  extern int am_daemon;
56  extern int am_receiver;
57  extern int io_error;
58 +#ifdef HAVE_OPENSSL
59 +extern int use_ssl;
60 +#endif
61  extern int keep_partial;
62  extern int got_xfer_error;
63  extern char *partial_dir;
64 @@ -129,6 +132,14 @@ NORETURN void _exit_cleanup(int code, const char *file, int line)
65                                 who_am_i(), code, file, line);
66                 }
67  
68 +#ifdef HAVE_OPENSSL
69 +               /* FALLTHROUGH */
70 +#include "case_N.h"
71 +
72 +               if (use_ssl)
73 +                       end_tls();
74 +#endif
75 +
76                 /* FALLTHROUGH */
77  #include "case_N.h"
78                 switch_step++;
79 diff --git a/clientserver.c b/clientserver.c
80 --- a/clientserver.c
81 +++ b/clientserver.c
82 @@ -31,6 +31,9 @@ extern int am_sender;
83  extern int am_server;
84  extern int am_daemon;
85  extern int am_root;
86 +#ifdef HAVE_OPENSSL
87 +extern int use_ssl;
88 +#endif
89  extern int rsync_port;
90  extern int protect_args;
91  extern int ignore_errors;
92 @@ -126,8 +129,18 @@ int start_socket_client(char *host, int remote_argc, char *remote_argv[],
93  #endif
94  
95         ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
96 +       if (ret)
97 +               return ret;
98 +
99 +#ifdef HAVE_OPENSSL
100 +       if (use_ssl) {
101 +               int f_in = get_tls_rfd();
102 +               int f_out = get_tls_wfd();
103 +               return client_run(f_in, f_out, -1, argc, argv);
104 +       }
105 +#endif
106  
107 -       return ret ? ret : client_run(fd, fd, -1, argc, argv);
108 +       return client_run(fd, fd, -1, argc, argv);
109  }
110  
111  static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
112 @@ -273,6 +286,32 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
113         if (verbose > 1)
114                 print_child_argv("sending daemon args:", sargs);
115  
116 +#ifdef HAVE_OPENSSL
117 +       if (use_ssl) {
118 +               io_printf(f_out, "#starttls\n");
119 +               while (1) {
120 +                       if (!read_line_old(f_in, line, sizeof line)) {
121 +                               rprintf(FERROR, "rsync: did not receive reply to #starttls\n");
122 +                               return -1;
123 +                       }
124 +                       if (strncmp(line, "@ERROR", 6) == 0) {
125 +                               rprintf(FERROR, "%s\n", line);
126 +                               return -1;
127 +                       }
128 +                       if (strcmp(line, "@RSYNCD: starttls") == 0)
129 +                               break;
130 +                       rprintf(FINFO, "%s\n", line);
131 +               }
132 +               if (start_tls(f_in, f_out)) {
133 +                       rprintf(FERROR, "rsync: error during SSL handshake: %s\n",
134 +                               get_ssl_error());
135 +                       return -1;
136 +               }
137 +               f_in = get_tls_rfd();
138 +               f_out = get_tls_wfd();
139 +       }
140 +#endif
141 +
142         io_printf(f_out, "%.*s\n", modlen, modname);
143  
144         /* Old servers may just drop the connection here,
145 @@ -298,6 +337,10 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
146                          * server to terminate the listing of modules.
147                          * We don't want to go on and transfer
148                          * anything; just exit. */
149 +#ifdef HAVE_OPENSSL
150 +                       if (use_ssl)
151 +                               end_tls();
152 +#endif
153                         exit(0);
154                 }
155  
156 @@ -305,6 +348,10 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
157                         rprintf(FERROR, "%s\n", line);
158                         /* This is always fatal; the server will now
159                          * close the socket. */
160 +#ifdef HAVE_OPENSSL
161 +                       if (use_ssl)
162 +                               end_tls();
163 +#endif
164                         return -1;
165                 }
166  
167 @@ -598,10 +645,17 @@ static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
168                                 return -1;
169                         }
170                         if (pid) {
171 +                               close(f_in);
172 +                               if (f_out != f_in)
173 +                                       close(f_out);
174                                 if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
175                                         putenv(p);
176                                 if (wait_process(pid, &status, 0) < 0)
177                                         status = -1;
178 +#ifdef HAVE_OPENSSL
179 +                               if (use_ssl)
180 +                                       end_tls();
181 +#endif
182                                 if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
183                                         putenv(p);
184                                 if (WIFEXITED(status))
185 @@ -944,6 +998,9 @@ int start_daemon(int f_in, int f_out)
186         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
187                 return -1;
188  
189 +#ifdef HAVE_OPENSSL
190 +  retry:
191 +#endif
192         line[0] = 0;
193         if (!read_line_old(f_in, line, sizeof line))
194                 return -1;
195 @@ -955,6 +1012,20 @@ int start_daemon(int f_in, int f_out)
196                 return -1;
197         }
198  
199 +#ifdef HAVE_OPENSSL
200 +       if (use_ssl && strcmp(line, "#starttls") == 0) {
201 +               io_printf(f_out, "@RSYNCD: starttls\n");
202 +               if (start_tls(f_in, f_out)) {
203 +                       rprintf(FLOG, "SSL connection failed: %s\n",
204 +                               get_ssl_error());
205 +                       return -1;
206 +               }
207 +               f_in = get_tls_rfd();
208 +               f_out = get_tls_wfd();
209 +               goto retry;
210 +       }
211 +#endif
212 +
213         if (*line == '#') {
214                 /* it's some sort of command that I don't understand */
215                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
216 diff --git a/configure.ac b/configure.ac
217 --- a/configure.ac
218 +++ b/configure.ac
219 @@ -312,6 +312,25 @@ if test x"$enable_locale" != x"no"; then
220         AC_DEFINE(CONFIG_LOCALE)
221  fi
222  
223 +AC_ARG_ENABLE(openssl,
224 +              AC_HELP_STRING([--enable-openssl], [compile SSL support with OpenSSL.]))
225 +
226 +if test "x$enable_openssl" != xno
227 +then
228 +       save_LIBS=$LIBS
229 +       LIBS="$LIBS -lcrypto"
230 +       have_ssl=yes
231 +       AC_CHECK_LIB(ssl, SSL_library_init, , [have_ssl=no])
232 +       if test "x$have_ssl" = xyes
233 +       then
234 +               AC_DEFINE(HAVE_OPENSSL, 1, [true if you want to use SSL.])
235 +               SSL_OBJS=ssl.o
236 +               AC_SUBST(SSL_OBJS)
237 +       else
238 +               LIBS=$save_LIBS
239 +       fi
240 +fi
241 +
242  AC_MSG_CHECKING([whether to call shutdown on all sockets])
243  case $host_os in
244         *cygwin* ) AC_MSG_RESULT(yes)
245 diff --git a/main.c b/main.c
246 --- a/main.c
247 +++ b/main.c
248 @@ -79,6 +79,9 @@ extern char *password_file;
249  extern char curr_dir[MAXPATHLEN];
250  extern struct file_list *first_flist;
251  extern struct filter_list_struct daemon_filter_list;
252 +#ifdef HAVE_OPENSSL
253 +extern int use_ssl;
254 +#endif
255  
256  uid_t our_uid;
257  int am_receiver = 0;  /* Only set to 1 after the receiver/generator fork. */
258 @@ -137,6 +140,52 @@ pid_t wait_process(pid_t pid, int *status_ptr, int flags)
259         return waited_pid;
260  }
261  
262 +/* Sends signal "signo", waits for the process to die, and if it doesn't, sends
263 + * a SIGKILL.  If "graceful" is set, the initial "signo" signal is delayed by a
264 + * second to try to let the process exit on its own first. */
265 +pid_t terminate_process(pid_t pid, int *status_ptr, int signo, int graceful)
266 +{
267 +       pid_t waited_pid;
268 +       int timeout = graceful ? 1000 : 3000;
269 +       if (!graceful)
270 +               kill(pid, signo);
271 +       while (1) {
272 +               waited_pid = wait_process(pid, status_ptr, timeout >= 0 ? WNOHANG : 0);
273 +               if (waited_pid)
274 +                       break;
275 +               if (timeout == 0) {
276 +                       if (graceful) {
277 +                               graceful = 0;
278 +                               timeout = 3000;
279 +                       } else {
280 +                               signo = SIGKILL;
281 +                               timeout = -1;
282 +                       }
283 +                       rprintf(FINFO, "%s:%s shutdown didn't work - sending signal %d\n",
284 +                               __FUNCTION__, graceful ? " graceful" : "", signo);
285 +                       kill(pid, signo);
286 +               }
287 +
288 +               if (timeout > 0) {
289 +                       /* interruptible wait and calculate the time left for waiting */
290 +                       struct timeval tval, t1, t2;
291 +
292 +                       gettimeofday(&t1, NULL);
293 +
294 +                       tval.tv_sec = timeout/1000;
295 +                       tval.tv_usec = (timeout%1000)*1000;
296 +                       select(0, NULL, NULL, NULL, &tval);
297 +                       gettimeofday(&t2, NULL);
298 +
299 +                       timeout -= (t2.tv_sec-t1.tv_sec)*1000 + (t2.tv_usec-t1.tv_usec)/1000;
300 +                       if (timeout < 0)
301 +                               timeout = 0;
302 +               }
303 +       }
304 +
305 +       return waited_pid;
306 +}
307 +
308  /* Wait for a process to exit, calling io_flush while waiting. */
309  static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
310  {
311 @@ -727,6 +776,11 @@ static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
312                 argv[0] = ".";
313         }
314  
315 +#ifdef HAVE_OPENSSL
316 +       if (use_ssl)
317 +               start_tls_buffering();
318 +#endif
319 +
320         flist = send_file_list(f_out,argc,argv);
321         if (!flist || flist->used == 0)
322                 exit_cleanup(0);
323 @@ -828,6 +882,10 @@ static int do_recv(int f_in, int f_out, char *local_name)
324                 close(f_in);
325  
326         io_start_buffering_out(f_out);
327 +#ifdef HAVE_OPENSSL
328 +       if (use_ssl)
329 +               start_tls_buffering();
330 +#endif
331  
332         set_msg_fd_in(error_pipe[0]);
333         io_start_buffering_in(error_pipe[0]);
334 @@ -1022,6 +1080,10 @@ int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
335                         io_start_buffering_out(f_out);
336                 if (!filesfrom_host)
337                         set_msg_fd_in(f_in);
338 +#ifdef HAVE_OPENSSL
339 +               if (use_ssl)
340 +                       start_tls_buffering();
341 +#endif
342                 send_filter_list(f_out);
343                 if (filesfrom_host)
344                         filesfrom_fd = f_in;
345 diff --git a/options.c b/options.c
346 --- a/options.c
347 +++ b/options.c
348 @@ -183,6 +183,14 @@ int logfile_format_has_o_or_i = 0;
349  int always_checksum = 0;
350  int list_only = 0;
351  
352 +#ifdef HAVE_OPENSSL
353 +int use_ssl = 0;
354 +char *ssl_cert_path = NULL;
355 +char *ssl_key_path = NULL;
356 +char *ssl_key_passwd = NULL;
357 +char *ssl_ca_path = NULL;
358 +#endif
359 +
360  #define MAX_BATCH_NAME_LEN 256 /* Must be less than MAXPATHLEN-13 */
361  char *batch_name = NULL;
362  
363 @@ -223,6 +231,7 @@ static void print_rsync_version(enum logcode f)
364         char const *links = "no ";
365         char const *iconv = "no ";
366         char const *ipv6 = "no ";
367 +       char const *ssl = "no ";
368         STRUCT_STAT *dumstat;
369  
370  #if SUBPROTOCOL_VERSION != 0
371 @@ -256,6 +265,9 @@ static void print_rsync_version(enum logcode f)
372  #ifdef CAN_SET_SYMLINK_TIMES
373         symtimes = "";
374  #endif
375 +#ifdef HAVE_OPENSSL
376 +       ssl = "";
377 +#endif
378  
379         rprintf(f, "%s  version %s  protocol version %d%s\n",
380                 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION, subprotocol);
381 @@ -269,8 +281,8 @@ static void print_rsync_version(enum logcode f)
382                 (int)(sizeof (int64) * 8));
383         rprintf(f, "    %ssocketpairs, %shardlinks, %ssymlinks, %sIPv6, batchfiles, %sinplace,\n",
384                 got_socketpair, hardlinks, links, ipv6, have_inplace);
385 -       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes\n",
386 -               have_inplace, acls, xattrs, iconv, symtimes);
387 +       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes, %sSSL\n",
388 +               have_inplace, acls, xattrs, iconv, symtimes, ssl);
389  
390  #ifdef MAINTAINER_MODE
391         rprintf(f, "Panic Action: \"%s\"\n", get_panic_action());
392 @@ -432,6 +444,13 @@ void usage(enum logcode F)
393  #endif
394    rprintf(F," -4, --ipv4                  prefer IPv4\n");
395    rprintf(F," -6, --ipv6                  prefer IPv6\n");
396 +#ifdef HAVE_OPENSSL
397 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
398 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
399 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
400 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
401 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
402 +#endif
403    rprintf(F,"     --version               print version number\n");
404    rprintf(F,"(-h) --help                  show this help (-h is --help only if used alone)\n");
405  
406 @@ -445,7 +464,7 @@ enum {OPT_VERSION = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
407        OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
408        OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
409        OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
410 -      OPT_NO_D, OPT_APPEND, OPT_NO_ICONV,
411 +      OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_USE_SSL,
412        OPT_SERVER, OPT_REFUSED_BASE = 9000};
413  
414  static struct poptOption long_options[] = {
415 @@ -648,6 +667,13 @@ static struct poptOption long_options[] = {
416    {"checksum-seed",    0,  POPT_ARG_INT,    &checksum_seed, 0, 0, 0 },
417    {"server",           0,  POPT_ARG_NONE,   0, OPT_SERVER, 0, 0 },
418    {"sender",           0,  POPT_ARG_NONE,   0, OPT_SENDER, 0, 0 },
419 +#ifdef HAVE_OPENSSL
420 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
421 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
422 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
423 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
424 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
425 +#endif
426    /* All the following options switch us into daemon-mode option-parsing. */
427    {"config",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
428    {"daemon",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
429 @@ -673,6 +699,13 @@ static void daemon_usage(enum logcode F)
430    rprintf(F," -v, --verbose               increase verbosity\n");
431    rprintf(F," -4, --ipv4                  prefer IPv4\n");
432    rprintf(F," -6, --ipv6                  prefer IPv6\n");
433 +#ifdef HAVE_OPENSSL
434 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
435 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
436 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
437 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
438 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
439 +#endif
440    rprintf(F,"     --help                  show this help screen\n");
441  
442    rprintf(F,"\n");
443 @@ -697,6 +730,13 @@ static struct poptOption long_daemon_options[] = {
444    {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
445    {"server",           0,  POPT_ARG_NONE,   &am_server, 0, 0, 0 },
446    {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
447 +#ifdef HAVE_OPENSSL
448 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
449 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
450 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
451 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
452 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
453 +#endif
454    {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
455    {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
456    {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
457 @@ -978,6 +1018,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
458                                         verbose++;
459                                         break;
460  
461 +#ifdef HAVE_OPENSSL
462 +                               case OPT_USE_SSL:
463 +                                       use_ssl = 1;
464 +                                       break;
465 +#endif
466 +
467                                 default:
468                                         rprintf(FERROR,
469                                             "rsync: %s: %s (in daemon mode)\n",
470 @@ -1001,6 +1047,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
471                                 exit_cleanup(RERR_SYNTAX);
472                         }
473  
474 +#ifdef HAVE_OPENSSL
475 +                       if (use_ssl) {
476 +                               if (init_tls()) {
477 +                                       snprintf(err_buf, sizeof(err_buf),
478 +                                                "Openssl error: %s\n",
479 +                                                get_ssl_error());
480 +                                       return 0;
481 +                               }
482 +                       }
483 +#endif
484 +
485                         *argv_p = argv = poptGetArgs(pc);
486                         *argc_p = argc = count_args(argv);
487                         am_starting_up = 0;
488 @@ -1259,6 +1316,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
489                         return 0;
490  #endif
491  
492 +#ifdef HAVE_OPENSSL
493 +               case OPT_USE_SSL:
494 +                       use_ssl = 1;
495 +                       break;
496 +#endif
497 +
498                 default:
499                         /* A large opt value means that set_refuse_options()
500                          * turned this option off. */
501 @@ -1604,6 +1667,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
502         if (delay_updates && !partial_dir)
503                 partial_dir = tmp_partialdir;
504  
505 +#ifdef HAVE_OPENSSL
506 +       if (use_ssl) {
507 +               if (init_tls()) {
508 +                       snprintf(err_buf, sizeof(err_buf),
509 +                                "Openssl error: %s\n",
510 +                                get_ssl_error());
511 +                       return 0;
512 +               }
513 +       }
514 +#endif
515 +
516         if (inplace) {
517  #ifdef HAVE_FTRUNCATE
518                 if (partial_dir) {
519 @@ -2152,9 +2226,26 @@ static char *parse_hostspec(char *str, char **path_start_ptr, int *port_ptr)
520  char *check_for_hostspec(char *s, char **host_ptr, int *port_ptr)
521  {
522         char *path;
523 -
524 -       if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
525 -               *host_ptr = parse_hostspec(s + strlen(URL_PREFIX), &path, port_ptr);
526 +       int url_prefix_len = sizeof URL_PREFIX - 1;
527 +
528 +       if (!port_ptr)
529 +               url_prefix_len = 0;
530 +       else if (strncasecmp(URL_PREFIX, s, url_prefix_len) != 0) {
531 +#ifdef HAVE_OPENSSL
532 +               url_prefix_len = sizeof SSL_URL_PREFIX - 1;
533 +               if (strncasecmp(SSL_URL_PREFIX, s, url_prefix_len) != 0)
534 +                       url_prefix_len = 0;
535 +               else {
536 +                       if (!use_ssl)
537 +                               init_tls();
538 +                       use_ssl = 1;
539 +               }
540 +#else
541 +               url_prefix_len = 0;
542 +#endif
543 +       }
544 +       if (url_prefix_len) {
545 +               *host_ptr = parse_hostspec(s + url_prefix_len, &path, port_ptr);
546                 if (*host_ptr) {
547                         if (!*port_ptr)
548                                 *port_ptr = RSYNC_PORT;
549 diff --git a/rsync.h b/rsync.h
550 --- a/rsync.h
551 +++ b/rsync.h
552 @@ -31,6 +31,7 @@
553  
554  #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
555  #define URL_PREFIX "rsync://"
556 +#define SSL_URL_PREFIX "rsyncs://"
557  
558  #define SYMLINK_PREFIX "/rsyncd-munged/"  /* This MUST have a trailing slash! */
559  #define SYMLINK_PREFIX_LEN ((int)sizeof SYMLINK_PREFIX - 1)
560 @@ -569,6 +570,11 @@ typedef unsigned int size_t;
561  # define SIZEOF_INT64 SIZEOF_OFF_T
562  #endif
563  
564 +#ifdef HAVE_OPENSSL
565 +#include <openssl/ssl.h>
566 +#include <openssl/err.h>
567 +#endif
568 +
569  struct hashtable {
570         void *nodes;
571         int32 size, entries;
572 diff --git a/ssl.c b/ssl.c
573 new file mode 100644
574 --- /dev/null
575 +++ b/ssl.c
576 @@ -0,0 +1,604 @@
577 +/* -*- c-file-style: "linux" -*-
578 + * ssl.c: operations for negotiating SSL rsync connections.
579 + *
580 + * Copyright (C) 2003  Casey Marshall <rsdio@metastatic.org>
581 + *
582 + * This program is free software; you can redistribute it and/or modify
583 + * it under the terms of the GNU General Public License as published by
584 + * the Free Software Foundation; either version 2 of the License, or
585 + * (at your option) any later version.
586 + *
587 + * This program is distributed in the hope that it will be useful,
588 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
589 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
590 + * GNU General Public License for more details.
591 + *
592 + * You should have received a copy of the GNU General Public License
593 + * along with this program; if not, write to the Free Software
594 + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
595 + */
596 +
597 +#include "rsync.h"
598 +
599 +#ifdef HAVE_SYS_SELECT_H
600 +#include <sys/select.h>
601 +#else
602 +#include <sys/time.h>
603 +#include <sys/types.h>
604 +#include <unistd.h>
605 +#endif
606 +#include <string.h>
607 +
608 +#define SSL_MAX_RECORD_SIZE (1024*16) /* TLS record size */
609 +#define MAX_BUFFERING_TIME_MS  100
610 +
611 +extern int verbose;
612 +extern int am_daemon;
613 +extern int am_server;
614 +
615 +extern char *ssl_cert_path;
616 +extern char *ssl_key_path;
617 +extern char *ssl_key_passwd;
618 +extern char *ssl_ca_path;
619 +
620 +static SSL_CTX *ssl_ctx;
621 +static SSL *ssl;
622 +static int tls_read[2] = { -1, -1 };
623 +static int tls_write[2] = { -1, -1 };
624 +static int ssl_running;
625 +static int ssl_min_send_size;
626 +static int ssl_pid = -1;
627 +
628 +#ifdef HAVE_SIGACTION
629 +static struct sigaction sigact;
630 +#endif
631 +
632 +/* copied from progress.c */
633 +static unsigned long msdiff(struct timeval *t1, struct timeval *t2)
634 +{
635 +       return (t2->tv_sec - t1->tv_sec) * 1000L
636 +               + (t2->tv_usec - t1->tv_usec) / 1000;
637 +}
638 +
639 +/**
640 + * A non-interactive callback to be passed to SSL_CTX_set_default_password_cb,
641 + * which merely copies the value of ssl_key_passwd into buf. This is
642 + * used for when the private key password is supplied via an option.
643 + */
644 +static int default_password_cb(char *buf, int n, UNUSED(int f), UNUSED(void *u))
645 +{
646 +       if (ssl_key_passwd == NULL || n < (int)strlen(ssl_key_passwd))
647 +               return 0;
648 +       strncpy(buf, ssl_key_passwd, n-1);
649 +       return strlen(ssl_key_passwd);
650 +}
651 +
652 +/**
653 + * If verbose, this method traces the status of the SSL handshake.
654 + */
655 +static void info_callback(const SSL *ssl, int cb, int val)
656 +{
657 +       char buf[128];
658 +       char *cbs;
659 +
660 +       switch (cb) {
661 +       case SSL_CB_LOOP:
662 +               cbs = "SSL_CB_LOOP";
663 +               break;
664 +       case SSL_CB_EXIT:
665 +               cbs = "SSL_CB_EXIT";
666 +               break;
667 +       case SSL_CB_READ:
668 +               cbs = "SSL_CB_READ";
669 +               break;
670 +       case SSL_CB_WRITE:
671 +               cbs = "SSL_CB_WRITE";
672 +               break;
673 +       case SSL_CB_ALERT:
674 +               cbs = "SSL_CB_ALERT";
675 +               break;
676 +       case SSL_CB_READ_ALERT:
677 +               cbs = "SSL_CB_READ_ALERT";
678 +               break;
679 +       case SSL_CB_WRITE_ALERT:
680 +               cbs = "SSL_CB_WRITE_ALERT";
681 +               break;
682 +       case SSL_CB_ACCEPT_LOOP:
683 +               cbs = "SSL_CB_ACCEPT_LOOP";
684 +               break;
685 +       case SSL_CB_ACCEPT_EXIT:
686 +               cbs = "SSL_CB_ACCEPT_EXIT";
687 +               break;
688 +       case SSL_CB_CONNECT_LOOP:
689 +               cbs = "SSL_CB_CONNECT_LOOP";
690 +               break;
691 +       case SSL_CB_CONNECT_EXIT:
692 +               cbs = "SSL_CB_CONNECT_EXIT";
693 +               break;
694 +       case SSL_CB_HANDSHAKE_START:
695 +               cbs = "SSL_CB_HANDSHAKE_START";
696 +               break;
697 +       case SSL_CB_HANDSHAKE_DONE:
698 +               cbs = "SSL_CB_HANDSHAKE_DONE";
699 +               break;
700 +       default:
701 +               snprintf(buf, sizeof buf, "??? (%d)", cb);
702 +               cbs = buf;
703 +               break;
704 +       }
705 +       if (verbose > 2) {
706 +               rprintf(FLOG, "SSL: info_callback(%p,%s,%d)\n", ssl, cbs, val);
707 +               if (cb == SSL_CB_HANDSHAKE_DONE) {
708 +                       SSL_CIPHER_description(SSL_get_current_cipher((SSL*)ssl),
709 +                                              buf, sizeof buf);
710 +                       rprintf(FLOG, "SSL: cipher: %s", buf);
711 +               }
712 +       }
713 +}
714 +
715 +/**
716 + * Initializes the SSL context for TLSv1 connections; returns zero on
717 + * success.
718 + */
719 +int init_tls(void)
720 +{
721 +       if (ssl_ctx)
722 +               return 0;
723 +       SSL_library_init();
724 +       SSL_load_error_strings();
725 +       ssl_ctx = SSL_CTX_new(TLSv1_method());
726 +       if (!ssl_ctx)
727 +               return 1;
728 +       SSL_CTX_set_info_callback(ssl_ctx, info_callback);
729 +
730 +       SSL_CTX_set_options(ssl_ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
731 +
732 +       /* Sets the certificate sent to the other party. */
733 +       if (ssl_cert_path != NULL
734 +           && SSL_CTX_use_certificate_file(ssl_ctx, ssl_cert_path,
735 +                                           SSL_FILETYPE_PEM) != 1)
736 +               return 1;
737 +       /* Set up the simple non-interactive callback if the password
738 +        * was supplied on the command line. */
739 +       if (ssl_key_passwd != NULL)
740 +               SSL_CTX_set_default_passwd_cb(ssl_ctx, default_password_cb);
741 +       /* Sets the private key that matches the public certificate. */
742 +       if (ssl_key_path != NULL) {
743 +               if (SSL_CTX_use_PrivateKey_file(ssl_ctx, ssl_key_path,
744 +                                               SSL_FILETYPE_PEM) != 1)
745 +                       return 1;
746 +               if (SSL_CTX_check_private_key(ssl_ctx) != 1)
747 +                       return 1;
748 +       }
749 +       if (ssl_ca_path != NULL
750 +           && !SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_path, NULL))
751 +               return 1;
752 +
753 +       return 0;
754 +}
755 +
756 +/**
757 + * Returns the error string for the current SSL error, if any.
758 + */
759 +char *get_ssl_error(void)
760 +{
761 +       return ERR_error_string(ERR_get_error(), NULL);
762 +}
763 +
764 +/**
765 + * Returns the input file descriptor for the SSL connection.
766 + */
767 +int get_tls_rfd(void)
768 +{
769 +       return tls_read[0];
770 +}
771 +
772 +/**
773 + * Returns the output file descriptor for the SSL connection.
774 + */
775 +int get_tls_wfd(void)
776 +{
777 +       return tls_write[1];
778 +}
779 +
780 +/**
781 + * Signal handler that ends the SSL connection.
782 + */
783 +static RETSIGTYPE tls_sigusr1(int UNUSED(val))
784 +{
785 +       ssl_running = 0;
786 +}
787 +
788 +/* Signal handler that starts record-size buffering. */
789 +static RETSIGTYPE tls_sigusr2(int UNUSED(val))
790 +{
791 +       ssl_min_send_size = SSL_MAX_RECORD_SIZE;
792 +}
793 +
794 +/**
795 + * Negotiates the TLS connection, creates a socket pair for communicating
796 + * with the rsync process, then forks into a new process that will handle
797 + * the communication.
798 + *
799 + * 0 is returned on success.
800 + * rsync to network algorithm:
801 + * A buffer ring of two buffers is maintained. Data is read from the local
802 + * socket into the current buffer. The buffer is eligible for sending if
803 + * enough data has been buffered, or enough time has passed. Once the buffer
804 + * becomes eligible for sending it is marked "ready" and buffering continues
805 + * on the other buffer (assuming it's "unready"). This algorithm tries to
806 + * maximize SSL record size.
807 + *
808 + * network to rsync algorithm:
809 + * One receive buffer twice the size of the SSL max record size. Reading
810 + * from the network is attempted only if there's enough space for a whole
811 + * record (this is done to optimize OpenSSL per-call overhead).
812 + * As bytes enter the buffer sending to rsync begins, when the buffer becomes
813 + * full we wait for sending to rsync to finish.
814 + *
815 + * A graceful stop is attempted on both directions. So if the pipe from rsync
816 + * is gracefully shut down, we try to send all data to the network before closing
817 + * the connection and if the SSL connection is gracefully shut down we try to
818 + * send everything to rsync before closing the rsync pipe.
819 + */
820 +int start_tls(int f_in, int f_out)
821 +{
822 +       int n = 0, r;
823 +       unsigned char buf_tonetwork[2][SSL_MAX_RECORD_SIZE], buf_fromnetwork[2*SSL_MAX_RECORD_SIZE];
824 +       int tonet_ready[2] = {0}, tonet_size[2] = {0}, write_tonet = 0, tonet_fill_idx = 0, tonet_send_idx = 0;
825 +       struct timeval buffering_start, now, timeout, *tp;
826 +       int avail_fromnet = 0, write_fromnet = 0;
827 +       int want_read_fromnet = 1, want_write_tonet = 0;
828 +       int want_read_fromrsync = 1, want_write_torsync = 0;
829 +       int write_tonet_blocks = 0, read_fromnet_blocks = 0;
830 +       int write_torsync_blocks = 0, read_fromrsync_blocks = 0;
831 +       int ssl_readfd_blocks = 0, ssl_writefd_blocks = 0;
832 +       int ssl_write_count = 0;
833 +       int want_more_io;
834 +       int net_closed = 0, rsync_closed = 0;
835 +       int loopcount;
836 +       fd_set rd, wd;
837 +       const char *ssl_ciphers;
838 +
839 +       if (fd_pair(tls_read))
840 +               return 1;
841 +       if (fd_pair(tls_write))
842 +               return 1;
843 +
844 +       set_blocking(tls_read[0]);
845 +       set_nonblocking(tls_read[1]);
846 +       set_nonblocking(tls_write[0]);
847 +       set_blocking(tls_write[1]);
848 +       set_nonblocking(f_in);
849 +       set_nonblocking(f_out);
850 +
851 +       ssl_pid = do_fork();
852 +       if (ssl_pid < 0)
853 +               return -1;
854 +       if (ssl_pid != 0) {
855 +               close(tls_write[0]);
856 +               close(tls_read[1]);
857 +               close(f_in);
858 +               close(f_out);
859 +               return 0;
860 +       }
861 +
862 +       close(tls_write[1]);
863 +       close(tls_read[0]);
864 +
865 +       SIGACTION(SIGUSR1, tls_sigusr1);
866 +       SIGACTION(SIGUSR2, tls_sigusr2);
867 +       ssl = SSL_new(ssl_ctx);
868 +       if (!ssl)
869 +               goto out;
870 +       if (am_daemon || am_server)
871 +               SSL_set_accept_state(ssl);
872 +       else {
873 +               SSL_set_connect_state(ssl);
874 +               ssl_ciphers = getenv("RSYNC_SSL_CIPHERS");
875 +               if (ssl_ciphers)
876 +                       SSL_set_cipher_list(ssl, ssl_ciphers);
877 +       }
878 +
879 +       SSL_set_rfd(ssl, f_in);
880 +       SSL_set_wfd(ssl, f_out);
881 +
882 +       n = tls_write[0];
883 +       n = MAX(tls_read[1], n);
884 +       n = MAX(f_in, n);
885 +       n = MAX(f_out, n) + 1;
886 +
887 +       ssl_running = 1;
888 +       loopcount = 0;
889 +       while (ssl_running) {
890 +               ++loopcount; /* the loopcount prevents starvation of one transfer direction by the other */
891 +               want_more_io = 0;
892 +
893 +               if (want_read_fromrsync && !read_fromrsync_blocks) {
894 +                       int cur_buf_size = tonet_size[tonet_fill_idx];
895 +                       r = read(tls_write[0], buf_tonetwork[tonet_fill_idx]+cur_buf_size, sizeof(buf_tonetwork[0])-cur_buf_size);
896 +                       if (r > 0) {
897 +                               want_more_io = 1;
898 +                               if (!net_closed) {
899 +                                       if (cur_buf_size == 0)
900 +                                               gettimeofday(&buffering_start, NULL);
901 +                                       cur_buf_size += r;
902 +                                       tonet_size[tonet_fill_idx] = cur_buf_size;
903 +                                       if (cur_buf_size >= ssl_min_send_size) {
904 +                                               want_write_tonet = 1;
905 +                                               tonet_ready[tonet_fill_idx] = 1;
906 +                                               tonet_fill_idx = !tonet_fill_idx;
907 +                                               if (tonet_ready[tonet_fill_idx])
908 +                                                       want_read_fromrsync = 0;
909 +                                       }
910 +                               }
911 +                       } else if (r < 0 && errno == EWOULDBLOCK)
912 +                               read_fromrsync_blocks = 1;
913 +                       else if (r < 0) {
914 +                               rprintf(FERROR, "pipe read error: %s\n",
915 +                                       strerror(errno));
916 +                               break;
917 +                       } else {
918 +                               rsync_closed = 1;
919 +                               if (cur_buf_size) {
920 +                                       want_write_tonet = 1;
921 +                                       tonet_ready[tonet_fill_idx] = 1; /* close current buffer */
922 +                               }
923 +                               want_read_fromrsync = 0; /* don't read */
924 +                               want_write_torsync = 0; /* don't write */
925 +                               read_fromrsync_blocks = 0; /* don't select */
926 +                               write_torsync_blocks = 0;
927 +                               want_read_fromnet = 1; /* purge incoming data from network */
928 +                               avail_fromnet = 0;
929 +                               if (net_closed || !want_write_tonet)
930 +                                       break;
931 +                       }
932 +               }
933 +
934 +               if (want_read_fromnet && !read_fromnet_blocks) {
935 +                       r = SSL_read(ssl, buf_fromnetwork+avail_fromnet, SSL_MAX_RECORD_SIZE);
936 +                       if (r > 0) {
937 +                               want_more_io = 1;
938 +                               if (!rsync_closed) {
939 +                                       avail_fromnet += r;
940 +                                       want_write_torsync = 1;
941 +                                       if (avail_fromnet >= (int)(sizeof(buf_fromnetwork)-SSL_MAX_RECORD_SIZE))
942 +                                               want_read_fromnet = 0;
943 +                               }
944 +                       } else {
945 +                               switch (SSL_get_error(ssl, r)) {
946 +                               case SSL_ERROR_ZERO_RETURN:
947 +                                       net_closed = 1;
948 +                                       want_read_fromnet = 0; /* don't read */
949 +                                       want_write_tonet = 0; /* don't write */
950 +                                       ssl_readfd_blocks = 0; /* and for heaven's sake - don't select() */
951 +                                       ssl_writefd_blocks = 0;
952 +                                       want_read_fromrsync = 1; /* and purge stuff from rsync side */
953 +                                       tonet_size[tonet_fill_idx] = 0;
954 +                                       tonet_ready[tonet_fill_idx] = 0;
955 +                                       if (rsync_closed || !want_write_torsync)
956 +                                               goto graceful_stop;
957 +                                       break;
958 +                               case SSL_ERROR_WANT_READ:
959 +                                       ssl_readfd_blocks = 1;
960 +                                       read_fromnet_blocks = 1;
961 +                                       break;
962 +                               case SSL_ERROR_WANT_WRITE:
963 +                                       ssl_writefd_blocks = 1;
964 +                                       read_fromnet_blocks = 1;
965 +                                       break;
966 +                               case SSL_ERROR_SYSCALL:
967 +                                       if (r == 0)
968 +                                               rprintf(FERROR, "SSL spurious EOF\n");
969 +                                       else
970 +                                               rprintf(FERROR, "SSL I/O error: %s\n",
971 +                                                       strerror(errno));
972 +                                       goto closed;
973 +                               case SSL_ERROR_SSL:
974 +                                       rprintf(FERROR, "SSL %s\n",
975 +                                               ERR_error_string(ERR_get_error(), NULL));
976 +                                       goto closed;
977 +                               default:
978 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
979 +                                       goto closed;
980 +                               }
981 +                       }
982 +               }
983 +
984 +               if (want_write_torsync && !write_torsync_blocks) {
985 +                       r = write(tls_read[1], buf_fromnetwork+write_fromnet, avail_fromnet-write_fromnet);
986 +                       if (r > 0) {
987 +                               want_more_io = 1;
988 +                               write_fromnet += r;
989 +                               if (write_fromnet >= avail_fromnet) {
990 +                                       write_fromnet = 0;
991 +                                       avail_fromnet = 0;
992 +                                       if (net_closed)
993 +                                               break;
994 +                                       want_read_fromnet = 1;
995 +                                       want_write_torsync = 0;
996 +                               }
997 +                       }
998 +                       else if (errno == EWOULDBLOCK)
999 +                               write_torsync_blocks = 1;
1000 +                       else {
1001 +                               if (errno != EPIPE)
1002 +                                       rprintf(FERROR, "pipe write error: %s\n", strerror(errno));
1003 +                               break;
1004 +                       }
1005 +               }
1006 +
1007 +               if (want_write_tonet && !write_tonet_blocks) {
1008 +                       /* lock the write count, 'cause if SSL_write fails on non-blocking IO, it
1009 +                        * must be repeated with same parameters. */
1010 +                       if (ssl_write_count == 0)
1011 +                               ssl_write_count = tonet_size[tonet_send_idx] - write_tonet;
1012 +                       r = SSL_write(ssl, buf_tonetwork[tonet_send_idx]+write_tonet, ssl_write_count);
1013 +                       if (r > 0) {
1014 +                               want_more_io = 1;
1015 +                               write_tonet += r;
1016 +                               ssl_write_count = 0;
1017 +                               if (write_tonet >= tonet_size[tonet_send_idx]) {
1018 +                                       write_tonet = 0;
1019 +                                       tonet_size[tonet_send_idx] = 0;
1020 +                                       tonet_ready[tonet_send_idx] = 0;
1021 +                                       if (!rsync_closed)
1022 +                                               want_read_fromrsync = 1;
1023 +                                       tonet_send_idx = !tonet_send_idx;
1024 +                                       if (!tonet_ready[tonet_send_idx]) {
1025 +                                               want_write_tonet = 0;
1026 +                                               if (rsync_closed)
1027 +                                                       break;
1028 +                                       }
1029 +                               }
1030 +                       } else {
1031 +                               switch (SSL_get_error(ssl, r)) {
1032 +                               case SSL_ERROR_ZERO_RETURN:
1033 +                                       goto graceful_stop;
1034 +                               case SSL_ERROR_WANT_READ:
1035 +                                       ssl_readfd_blocks = 1;
1036 +                                       write_tonet_blocks = 1;
1037 +                                       break;
1038 +                               case SSL_ERROR_WANT_WRITE:
1039 +                                       ssl_writefd_blocks = 1;
1040 +                                       write_tonet_blocks = 1;
1041 +                                       break;
1042 +                               case SSL_ERROR_SYSCALL:
1043 +                                       if (r == 0)
1044 +                                               rprintf(FERROR, "SSL: spurious EOF\n");
1045 +                                       else
1046 +                                               rprintf(FERROR, "SSL: I/O error: %s\n", strerror(errno));
1047 +                                       goto closed;
1048 +                               case SSL_ERROR_SSL:
1049 +                                       rprintf(FERROR, "SSL: %s\n",
1050 +                                               ERR_error_string(ERR_get_error(), NULL));
1051 +                                       goto closed;
1052 +                               default:
1053 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
1054 +                                       goto closed;
1055 +                               }
1056 +                       }
1057 +               }
1058 +
1059 +               if (!want_more_io || (loopcount&31) == 0) {
1060 +                       int has_buffered = 0;
1061 +                       if (!net_closed && !tonet_ready[tonet_fill_idx] && tonet_size[tonet_fill_idx]) {
1062 +                               has_buffered = 1;
1063 +                               unsigned long buffering_time;
1064 +                               gettimeofday(&now,NULL);
1065 +                               buffering_time = msdiff(&buffering_start,&now);
1066 +                               if (buffering_time >= MAX_BUFFERING_TIME_MS) {
1067 +                                       want_write_tonet = 1;
1068 +                                       want_more_io = 1;
1069 +                                       tonet_ready[tonet_fill_idx] = 1;
1070 +                                       tonet_fill_idx = !tonet_fill_idx;
1071 +                                       if (tonet_ready[tonet_fill_idx])
1072 +                                               want_read_fromrsync = 0;
1073 +                               }
1074 +                       }
1075 +
1076 +                       int waiting_on_something = 0;
1077 +                       FD_ZERO(&rd);
1078 +                       FD_ZERO(&wd);
1079 +                       if (read_fromrsync_blocks) {
1080 +                               waiting_on_something = 1;
1081 +                               FD_SET(tls_write[0], &rd);
1082 +                       }
1083 +                       if (write_torsync_blocks) {
1084 +                               waiting_on_something = 1;
1085 +                               FD_SET(tls_read[1], &wd);
1086 +                       }
1087 +                       if (ssl_readfd_blocks) {
1088 +                               waiting_on_something = 1;
1089 +                               FD_SET(f_in, &rd);
1090 +                       }
1091 +                       if (ssl_writefd_blocks) {
1092 +                               waiting_on_something = 1;
1093 +                               FD_SET(f_out, &wd);
1094 +                       }
1095 +
1096 +                       if (want_more_io) {
1097 +                               /* just poll to see if some sockets became non-blocking*/
1098 +                               timeout.tv_sec = 0;
1099 +                               timeout.tv_usec = 0;
1100 +                               tp = &timeout;
1101 +                       } else if (waiting_on_something && !has_buffered)
1102 +                               tp = NULL; /*infinite wait until a socket becomes available*/
1103 +                       else {
1104 +                               timeout.tv_sec = MAX_BUFFERING_TIME_MS/1000;
1105 +                               timeout.tv_usec = (MAX_BUFFERING_TIME_MS%1000)*1000;
1106 +                               tp = &timeout;
1107 +                       }
1108 +
1109 +                       if (waiting_on_something || !want_more_io) {
1110 +                               r = select(n, &rd, &wd, NULL, tp);
1111 +
1112 +                               if (r == -1) {
1113 +                                       if (errno != EINTR) {
1114 +                                               rprintf(FERROR, "select error: %s\n",
1115 +                                                       strerror(errno));
1116 +                                               break;
1117 +                                       }
1118 +                               }
1119 +
1120 +                               if (r > 0) {
1121 +                                       if (FD_ISSET(tls_write[0], &rd))
1122 +                                               read_fromrsync_blocks = 0;
1123 +                                       if (FD_ISSET(f_in,&rd)) {
1124 +                                               read_fromnet_blocks = 0;
1125 +                                               write_tonet_blocks = 0;
1126 +                                               ssl_readfd_blocks = 0;
1127 +                                       }
1128 +                                       if (FD_ISSET(tls_read[1],&wd))
1129 +                                               write_torsync_blocks = 0;
1130 +                                       if (FD_ISSET(f_out,&wd)) {
1131 +                                               read_fromnet_blocks = 0;
1132 +                                               write_tonet_blocks = 0;
1133 +                                               ssl_writefd_blocks = 0;
1134 +                                       }
1135 +                               }
1136 +                       }
1137 +               }
1138 +       }
1139 +
1140 +  graceful_stop:
1141 +       /* The SSL shutdown API looks pretty broken with respect to corner cases
1142 +        * where the underlying socket is blocking. This is a "best effort". */
1143 +       if (SSL_shutdown(ssl) != 1)
1144 +               SSL_shutdown(ssl);
1145 +  closed:
1146 +       SSL_free(ssl);
1147 +
1148 +       /* We're finished. */
1149 +  out:
1150 +       close(tls_read[1]);
1151 +       close(tls_write[0]);
1152 +       close(f_in);
1153 +       if (f_out != f_in)
1154 +               close(f_out);
1155 +       _exit(0);
1156 +}
1157 +
1158 +void start_tls_buffering(void)
1159 +{
1160 +       if (ssl_pid > 0)
1161 +               kill(ssl_pid, SIGUSR2);
1162 +}
1163 +
1164 +/**
1165 + * Ends the TLS connection.
1166 + */
1167 +void end_tls(void)
1168 +{
1169 +       if (ssl_pid > 0) {
1170 +               int status;
1171 +               /* try a graceful stop - this makes sure all data is sent, and
1172 +                * also causes our side to send a close_notify alert, as required
1173 +                * by TLS specs. */
1174 +               close(get_tls_rfd());
1175 +               if (get_tls_wfd() != get_tls_rfd())
1176 +                       close(get_tls_wfd());
1177 +               terminate_process(ssl_pid, &status, SIGUSR1, 1);
1178 +               ssl_pid = -1;
1179 +       }
1180 +}