Forward a MSG_ERROR_EXIT value to generator too.
[rsync.git] / io.c
1 /*
2  * Socket and pipe I/O utilities used in rsync.
3  *
4  * Copyright (C) 1996-2001 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2003-2013 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 /* Rsync provides its own multiplexing system, which is used to send
24  * stderr and stdout over a single socket.
25  *
26  * For historical reasons this is off during the start of the
27  * connection, but it's switched on quite early using
28  * io_start_multiplex_out() and io_start_multiplex_in(). */
29
30 #include "rsync.h"
31 #include "ifuncs.h"
32 #include "inums.h"
33
34 /** If no timeout is specified then use a 60 second select timeout */
35 #define SELECT_TIMEOUT 60
36
37 extern int bwlimit;
38 extern size_t bwlimit_writemax;
39 extern int io_timeout;
40 extern int am_server;
41 extern int am_sender;
42 extern int am_receiver;
43 extern int am_generator;
44 extern int msgs2stderr;
45 extern int inc_recurse;
46 extern int io_error;
47 extern int eol_nulls;
48 extern int flist_eof;
49 extern int file_total;
50 extern int file_old_total;
51 extern int list_only;
52 extern int read_batch;
53 extern int compat_flags;
54 extern int protect_args;
55 extern int checksum_seed;
56 extern int protocol_version;
57 extern int remove_source_files;
58 extern int preserve_hard_links;
59 extern BOOL extra_flist_sending_enabled;
60 extern BOOL flush_ok_after_signal;
61 extern struct stats stats;
62 extern struct file_list *cur_flist;
63 #ifdef ICONV_OPTION
64 extern int filesfrom_convert;
65 extern iconv_t ic_send, ic_recv;
66 #endif
67
68 int csum_length = SHORT_SUM_LENGTH; /* initial value */
69 int allowed_lull = 0;
70 int batch_fd = -1;
71 int msgdone_cnt = 0;
72 int forward_flist_data = 0;
73 BOOL flist_receiving_enabled = False;
74
75 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
76 int kluge_around_eof = 0;
77 int got_kill_signal = -1; /* is set to 0 only after multiplexed I/O starts */
78
79 int sock_f_in = -1;
80 int sock_f_out = -1;
81
82 int64 total_data_read = 0;
83 int64 total_data_written = 0;
84
85 static struct {
86         xbuf in, out, msg;
87         int in_fd;
88         int out_fd; /* Both "out" and "msg" go to this fd. */
89         int in_multiplexed;
90         unsigned out_empty_len;
91         size_t raw_data_header_pos;      /* in the out xbuf */
92         size_t raw_flushing_ends_before; /* in the out xbuf */
93         size_t raw_input_ends_before;    /* in the in xbuf */
94 } iobuf = { .in_fd = -1, .out_fd = -1 };
95
96 static time_t last_io_in;
97 static time_t last_io_out;
98
99 static int write_batch_monitor_in = -1;
100 static int write_batch_monitor_out = -1;
101
102 static int ff_forward_fd = -1;
103 static int ff_reenable_multiplex = -1;
104 static char ff_lastchar = '\0';
105 static xbuf ff_xb = EMPTY_XBUF;
106 #ifdef ICONV_OPTION
107 static xbuf iconv_buf = EMPTY_XBUF;
108 #endif
109 static int select_timeout = SELECT_TIMEOUT;
110 static int active_filecnt = 0;
111 static OFF_T active_bytecnt = 0;
112 static int first_message = 1;
113
114 static char int_byte_extra[64] = {
115         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
116         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
117         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
118         2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
119 };
120
121 /* Our I/O buffers are sized with no bits on in the lowest byte of the "size"
122  * (indeed, our rounding of sizes in 1024-byte units assures more than this).
123  * This allows the code that is storing bytes near the physical end of a
124  * circular buffer to temporarily reduce the buffer's size (in order to make
125  * some storing idioms easier), while also making it simple to restore the
126  * buffer's actual size when the buffer's "pos" wraps around to the start (we
127  * just round the buffer's size up again). */
128
129 #define IOBUF_WAS_REDUCED(siz) ((siz) & 0xFF)
130 #define IOBUF_RESTORE_SIZE(siz) (((siz) | 0xFF) + 1)
131
132 #define IN_MULTIPLEXED (iobuf.in_multiplexed != 0)
133 #define IN_MULTIPLEXED_AND_READY (iobuf.in_multiplexed > 0)
134 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
135
136 #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
137 #define PIO_NEED_OUTROOM (1<<1)
138 #define PIO_NEED_MSGROOM (1<<2)
139
140 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
141
142 #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
143 #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
144
145 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
146 #define REMOTE_OPTION_ERROR2 ": unknown option"
147
148 #define FILESFROM_BUFLEN 2048
149
150 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
151
152 static flist_ndx_list redo_list, hlink_list;
153
154 static void read_a_msg(void);
155 static void drain_multiplex_messages(void);
156 static void sleep_for_bwlimit(int bytes_written);
157
158 static void check_timeout(BOOL allow_keepalive)
159 {
160         time_t t, chk;
161
162         /* On the receiving side, the generator is now the one that decides
163          * when a timeout has occurred.  When it is sifting through a lot of
164          * files looking for work, it will be sending keep-alive messages to
165          * the sender, and even though the receiver won't be sending/receiving
166          * anything (not even keep-alive messages), the successful writes to
167          * the sender will keep things going.  If the receiver is actively
168          * receiving data, it will ensure that the generator knows that it is
169          * not idle by sending the generator keep-alive messages (since the
170          * generator might be blocked trying to send checksums, it needs to
171          * know that the receiver is active).  Thus, as long as one or the
172          * other is successfully doing work, the generator will not timeout. */
173         if (!io_timeout)
174                 return;
175
176         t = time(NULL);
177
178         if (allow_keepalive) {
179                 /* This may put data into iobuf.msg w/o flushing. */
180                 maybe_send_keepalive(t, 0);
181         }
182
183         if (!last_io_in)
184                 last_io_in = t;
185
186         if (am_receiver)
187                 return;
188
189         chk = MAX(last_io_out, last_io_in);
190         if (t - chk >= io_timeout) {
191                 if (am_server)
192                         msgs2stderr = 1;
193                 rprintf(FERROR, "[%s] io timeout after %d seconds -- exiting\n",
194                         who_am_i(), (int)(t-chk));
195                 exit_cleanup(RERR_TIMEOUT);
196         }
197 }
198
199 /* It's almost always an error to get an EOF when we're trying to read from the
200  * network, because the protocol is (for the most part) self-terminating.
201  *
202  * There is one case for the receiver when it is at the end of the transfer
203  * (hanging around reading any keep-alive packets that might come its way): if
204  * the sender dies before the generator's kill-signal comes through, we can end
205  * up here needing to loop until the kill-signal arrives.  In this situation,
206  * kluge_around_eof will be < 0.
207  *
208  * There is another case for older protocol versions (< 24) where the module
209  * listing was not terminated, so we must ignore an EOF error in that case and
210  * exit.  In this situation, kluge_around_eof will be > 0. */
211 static NORETURN void whine_about_eof(BOOL allow_kluge)
212 {
213         if (kluge_around_eof && allow_kluge) {
214                 int i;
215                 if (kluge_around_eof > 0)
216                         exit_cleanup(0);
217                 /* If we're still here after 10 seconds, exit with an error. */
218                 for (i = 10*1000/20; i--; )
219                         msleep(20);
220         }
221
222         rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
223                 "(%s bytes received so far) [%s]\n",
224                 big_num(stats.total_read), who_am_i());
225
226         exit_cleanup(RERR_STREAMIO);
227 }
228
229 /* Do a safe read, handling any needed looping and error handling.
230  * Returns the count of the bytes read, which will only be different
231  * from "len" if we encountered an EOF.  This routine is not used on
232  * the socket except very early in the transfer. */
233 static size_t safe_read(int fd, char *buf, size_t len)
234 {
235         size_t got;
236         int n;
237
238         assert(fd != iobuf.in_fd);
239
240         n = read(fd, buf, len);
241         if ((size_t)n == len || n == 0) {
242                 if (DEBUG_GTE(IO, 2))
243                         rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
244                 return n;
245         }
246         if (n < 0) {
247                 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
248                   read_failed:
249                         rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
250                                 (long)len, who_am_i());
251                         exit_cleanup(RERR_STREAMIO);
252                 }
253                 got = 0;
254         } else
255                 got = n;
256
257         while (1) {
258                 struct timeval tv;
259                 fd_set r_fds, e_fds;
260                 int cnt;
261
262                 FD_ZERO(&r_fds);
263                 FD_SET(fd, &r_fds);
264                 FD_ZERO(&e_fds);
265                 FD_SET(fd, &e_fds);
266                 tv.tv_sec = select_timeout;
267                 tv.tv_usec = 0;
268
269                 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
270                 if (cnt <= 0) {
271                         if (cnt < 0 && errno == EBADF) {
272                                 rsyserr(FERROR, errno, "safe_read select failed [%s]",
273                                         who_am_i());
274                                 exit_cleanup(RERR_FILEIO);
275                         }
276                         if (io_timeout)
277                                 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
278                         continue;
279                 }
280
281                 /*if (FD_ISSET(fd, &e_fds))
282                         rprintf(FINFO, "select exception on fd %d\n", fd); */
283
284                 if (FD_ISSET(fd, &r_fds)) {
285                         n = read(fd, buf + got, len - got);
286                         if (DEBUG_GTE(IO, 2))
287                                 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
288                         if (n == 0)
289                                 break;
290                         if (n < 0) {
291                                 if (errno == EINTR)
292                                         continue;
293                                 goto read_failed;
294                         }
295                         if ((got += (size_t)n) == len)
296                                 break;
297                 }
298         }
299
300         return got;
301 }
302
303 static const char *what_fd_is(int fd)
304 {
305         static char buf[20];
306
307         if (fd == sock_f_out)
308                 return "socket";
309         else if (fd == iobuf.out_fd)
310                 return "message fd";
311         else if (fd == batch_fd)
312                 return "batch file";
313         else {
314                 snprintf(buf, sizeof buf, "fd %d", fd);
315                 return buf;
316         }
317 }
318
319 /* Do a safe write, handling any needed looping and error handling.
320  * Returns only if everything was successfully written.  This routine
321  * is not used on the socket except very early in the transfer. */
322 static void safe_write(int fd, const char *buf, size_t len)
323 {
324         int n;
325
326         assert(fd != iobuf.out_fd);
327
328         n = write(fd, buf, len);
329         if ((size_t)n == len)
330                 return;
331         if (n < 0) {
332                 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
333                   write_failed:
334                         rsyserr(FERROR, errno,
335                                 "safe_write failed to write %ld bytes to %s [%s]",
336                                 (long)len, what_fd_is(fd), who_am_i());
337                         exit_cleanup(RERR_STREAMIO);
338                 }
339         } else {
340                 buf += n;
341                 len -= n;
342         }
343
344         while (len) {
345                 struct timeval tv;
346                 fd_set w_fds;
347                 int cnt;
348
349                 FD_ZERO(&w_fds);
350                 FD_SET(fd, &w_fds);
351                 tv.tv_sec = select_timeout;
352                 tv.tv_usec = 0;
353
354                 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
355                 if (cnt <= 0) {
356                         if (cnt < 0 && errno == EBADF) {
357                                 rsyserr(FERROR, errno, "safe_write select failed on %s [%s]",
358                                         what_fd_is(fd), who_am_i());
359                                 exit_cleanup(RERR_FILEIO);
360                         }
361                         if (io_timeout)
362                                 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
363                         continue;
364                 }
365
366                 if (FD_ISSET(fd, &w_fds)) {
367                         n = write(fd, buf, len);
368                         if (n < 0) {
369                                 if (errno == EINTR)
370                                         continue;
371                                 goto write_failed;
372                         }
373                         buf += n;
374                         len -= n;
375                 }
376         }
377 }
378
379 /* This is only called when files-from data is known to be available.  We read
380  * a chunk of data and put it into the output buffer. */
381 static void forward_filesfrom_data(void)
382 {
383         int len;
384
385         len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
386         if (len <= 0) {
387                 if (len == 0 || errno != EINTR) {
388                         /* Send end-of-file marker */
389                         ff_forward_fd = -1;
390                         write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
391                         free_xbuf(&ff_xb);
392                         if (ff_reenable_multiplex >= 0)
393                                 io_start_multiplex_out(ff_reenable_multiplex);
394                 }
395                 return;
396         }
397
398         if (DEBUG_GTE(IO, 2))
399                 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
400
401 #ifdef ICONV_OPTION
402         len += ff_xb.len;
403 #endif
404
405         if (!eol_nulls) {
406                 char *s = ff_xb.buf + len;
407                 /* Transform CR and/or LF into '\0' */
408                 while (s-- > ff_xb.buf) {
409                         if (*s == '\n' || *s == '\r')
410                                 *s = '\0';
411                 }
412         }
413
414         if (ff_lastchar)
415                 ff_xb.pos = 0;
416         else {
417                 char *s = ff_xb.buf;
418                 /* Last buf ended with a '\0', so don't let this buf start with one. */
419                 while (len && *s == '\0')
420                         s++, len--;
421                 ff_xb.pos = s - ff_xb.buf;
422         }
423
424 #ifdef ICONV_OPTION
425         if (filesfrom_convert && len) {
426                 char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
427                 char *eob = sob + len;
428                 int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
429                 if (ff_lastchar == '\0')
430                         flags |= ICB_INIT;
431                 /* Convert/send each null-terminated string separately, skipping empties. */
432                 while (s != eob) {
433                         if (*s++ == '\0') {
434                                 ff_xb.len = s - sob - 1;
435                                 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
436                                         exit_cleanup(RERR_PROTOCOL); /* impossible? */
437                                 write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
438                                 while (s != eob && *s == '\0')
439                                         s++;
440                                 sob = s;
441                                 ff_xb.pos = sob - ff_xb.buf;
442                                 flags |= ICB_INIT;
443                         }
444                 }
445
446                 if ((ff_xb.len = s - sob) == 0)
447                         ff_lastchar = '\0';
448                 else {
449                         /* Handle a partial string specially, saving any incomplete chars. */
450                         flags &= ~ICB_INCLUDE_INCOMPLETE;
451                         if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
452                                 if (errno == E2BIG)
453                                         exit_cleanup(RERR_PROTOCOL); /* impossible? */
454                                 if (ff_xb.pos)
455                                         memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
456                         }
457                         ff_lastchar = 'x'; /* Anything non-zero. */
458                 }
459         } else
460 #endif
461
462         if (len) {
463                 char *f = ff_xb.buf + ff_xb.pos;
464                 char *t = ff_xb.buf;
465                 char *eob = f + len;
466                 /* Eliminate any multi-'\0' runs. */
467                 while (f != eob) {
468                         if (!(*t++ = *f++)) {
469                                 while (f != eob && *f == '\0')
470                                         f++;
471                         }
472                 }
473                 ff_lastchar = f[-1];
474                 if ((len = t - ff_xb.buf) != 0) {
475                         /* This will not circle back to perform_io() because we only get
476                          * called when there is plenty of room in the output buffer. */
477                         write_buf(iobuf.out_fd, ff_xb.buf, len);
478                 }
479         }
480 }
481
482 void reduce_iobuf_size(xbuf *out, size_t new_size)
483 {
484         if (new_size < out->size) {
485                 /* Avoid weird buffer interactions by only outputting this to stderr. */
486                 if (msgs2stderr && DEBUG_GTE(IO, 4)) {
487                         const char *name = out == &iobuf.out ? "iobuf.out"
488                                          : out == &iobuf.msg ? "iobuf.msg"
489                                          : NULL;
490                         if (name) {
491                                 rprintf(FINFO, "[%s] reduced size of %s (-%d)\n",
492                                         who_am_i(), name, (int)(out->size - new_size));
493                         }
494                 }
495                 out->size = new_size;
496         }
497 }
498
499 void restore_iobuf_size(xbuf *out)
500 {
501         if (IOBUF_WAS_REDUCED(out->size)) {
502                 size_t new_size = IOBUF_RESTORE_SIZE(out->size);
503                 /* Avoid weird buffer interactions by only outputting this to stderr. */
504                 if (msgs2stderr && DEBUG_GTE(IO, 4)) {
505                         const char *name = out == &iobuf.out ? "iobuf.out"
506                                          : out == &iobuf.msg ? "iobuf.msg"
507                                          : NULL;
508                         if (name) {
509                                 rprintf(FINFO, "[%s] restored size of %s (+%d)\n",
510                                         who_am_i(), name, (int)(new_size - out->size));
511                         }
512                 }
513                 out->size = new_size;
514         }
515 }
516
517 /* Perform buffered input and/or output until specified conditions are met.
518  * When given a "needed" read or write request, this returns without doing any
519  * I/O if the needed input bytes or write space is already available.  Once I/O
520  * is needed, this will try to do whatever reading and/or writing is currently
521  * possible, up to the maximum buffer allowances, no matter if this is a read
522  * or write request.  However, the I/O stops as soon as the required input
523  * bytes or output space is available.  If this is not a read request, the
524  * routine may also do some advantageous reading of messages from a multiplexed
525  * input source (which ensures that we don't jam up with everyone in their
526  * "need to write" code and nobody reading the accumulated data that would make
527  * writing possible).
528  *
529  * The iobuf.in, .out and .msg buffers are all circular.  Callers need to be
530  * aware that some data copies will need to be split when the bytes wrap around
531  * from the end to the start.  In order to help make writing into the output
532  * buffers easier for some operations (such as the use of SIVAL() into the
533  * buffer) a buffer may be temporarily shortened by a small amount, but the
534  * original size will be automatically restored when the .pos wraps to the
535  * start.  See also the 3 raw_* iobuf vars that are used in the handling of
536  * MSG_DATA bytes as they are read-from/written-into the buffers.
537  *
538  * When writing, we flush data in the following priority order:
539  *
540  * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
541  *
542  * 2. Write out all the messages from the message buf (if iobuf.msg is active).
543  *    Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
544  *    messages before getting to the iobuf.out flushing (except for rule 1).
545  *
546  * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
547  *    MSG_DATA header that was pre-allocated (when output is multiplexed).
548  *
549  * TODO:  items for possible future work:
550  *
551  *    - Make this routine able to read the generator-to-receiver batch flow?
552  *
553  * Unlike the old routines that this replaces, it is OK to read ahead as far as
554  * we can because the read_a_msg() routine now reads its bytes out of the input
555  * buffer.  In the old days, only raw data was in the input buffer, and any
556  * unused raw data in the buf would prevent the reading of socket data. */
557 static char *perform_io(size_t needed, int flags)
558 {
559         fd_set r_fds, e_fds, w_fds;
560         struct timeval tv;
561         int cnt, max_fd;
562         size_t empty_buf_len = 0;
563         xbuf *out;
564         char *data;
565
566         if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
567                 if (iobuf.raw_input_ends_before)
568                         iobuf.raw_input_ends_before -= iobuf.in.pos;
569                 iobuf.in.pos = 0;
570         }
571
572         switch (flags & PIO_NEED_FLAGS) {
573         case PIO_NEED_INPUT:
574                 /* We never resize the circular input buffer. */
575                 if (iobuf.in.size < needed) {
576                         rprintf(FERROR, "need to read %ld bytes, iobuf.in.buf is only %ld bytes.\n",
577                                 (long)needed, (long)iobuf.in.size);
578                         exit_cleanup(RERR_PROTOCOL);
579                 }
580
581                 if (msgs2stderr && DEBUG_GTE(IO, 3)) {
582                         rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
583                                 who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
584                 }
585                 break;
586
587         case PIO_NEED_OUTROOM:
588                 /* We never resize the circular output buffer. */
589                 if (iobuf.out.size - iobuf.out_empty_len < needed) {
590                         fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
591                                 (long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
592                         exit_cleanup(RERR_PROTOCOL);
593                 }
594
595                 if (msgs2stderr && DEBUG_GTE(IO, 3)) {
596                         rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
597                                 who_am_i(), (long)needed,
598                                 iobuf.out.len + needed > iobuf.out.size
599                                 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
600                 }
601                 break;
602
603         case PIO_NEED_MSGROOM:
604                 /* We never resize the circular message buffer. */
605                 if (iobuf.msg.size < needed) {
606                         fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
607                                 (long)needed, (long)iobuf.msg.size);
608                         exit_cleanup(RERR_PROTOCOL);
609                 }
610
611                 if (msgs2stderr && DEBUG_GTE(IO, 3)) {
612                         rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
613                                 who_am_i(), (long)needed,
614                                 iobuf.msg.len + needed > iobuf.msg.size
615                                 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
616                 }
617                 break;
618
619         case 0:
620                 if (msgs2stderr && DEBUG_GTE(IO, 3))
621                         rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
622                 break;
623
624         default:
625                 exit_cleanup(RERR_UNSUPPORTED);
626         }
627
628         while (1) {
629                 switch (flags & PIO_NEED_FLAGS) {
630                 case PIO_NEED_INPUT:
631                         if (iobuf.in.len >= needed)
632                                 goto double_break;
633                         break;
634                 case PIO_NEED_OUTROOM:
635                         /* Note that iobuf.out_empty_len doesn't factor into this check
636                          * because iobuf.out.len already holds any needed header len. */
637                         if (iobuf.out.len + needed <= iobuf.out.size)
638                                 goto double_break;
639                         break;
640                 case PIO_NEED_MSGROOM:
641                         if (iobuf.msg.len + needed <= iobuf.msg.size)
642                                 goto double_break;
643                         break;
644                 }
645
646                 max_fd = -1;
647
648                 FD_ZERO(&r_fds);
649                 FD_ZERO(&e_fds);
650                 if (iobuf.in_fd >= 0 && iobuf.in.size - iobuf.in.len) {
651                         if (!read_batch || batch_fd >= 0) {
652                                 FD_SET(iobuf.in_fd, &r_fds);
653                                 FD_SET(iobuf.in_fd, &e_fds);
654                         }
655                         if (iobuf.in_fd > max_fd)
656                                 max_fd = iobuf.in_fd;
657                 }
658
659                 /* Only do more filesfrom processing if there is enough room in the out buffer. */
660                 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
661                         FD_SET(ff_forward_fd, &r_fds);
662                         if (ff_forward_fd > max_fd)
663                                 max_fd = ff_forward_fd;
664                 }
665
666                 FD_ZERO(&w_fds);
667                 if (iobuf.out_fd >= 0) {
668                         if (iobuf.raw_flushing_ends_before
669                          || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
670                                 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
671                                         /* The iobuf.raw_flushing_ends_before value can point off the end
672                                          * of the iobuf.out buffer for a while, for easier subtracting. */
673                                         iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
674
675                                         SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
676                                               ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
677
678                                         if (msgs2stderr && DEBUG_GTE(IO, 1)) {
679                                                 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
680                                                         who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
681                                         }
682
683                                         /* reserve room for the next MSG_DATA header */
684                                         iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
685                                         if (iobuf.raw_data_header_pos >= iobuf.out.size)
686                                                 iobuf.raw_data_header_pos -= iobuf.out.size;
687                                         else if (iobuf.raw_data_header_pos + 4 > iobuf.out.size) {
688                                                 /* The 4-byte header won't fit at the end of the buffer,
689                                                  * so we'll temporarily reduce the output buffer's size
690                                                  * and put the header at the start of the buffer. */
691                                                 reduce_iobuf_size(&iobuf.out, iobuf.raw_data_header_pos);
692                                                 iobuf.raw_data_header_pos = 0;
693                                         }
694                                         /* Yes, it is possible for this to make len > size for a while. */
695                                         iobuf.out.len += 4;
696                                 }
697
698                                 empty_buf_len = iobuf.out_empty_len;
699                                 out = &iobuf.out;
700                         } else if (iobuf.msg.len) {
701                                 empty_buf_len = 0;
702                                 out = &iobuf.msg;
703                         } else
704                                 out = NULL;
705                         if (out) {
706                                 FD_SET(iobuf.out_fd, &w_fds);
707                                 if (iobuf.out_fd > max_fd)
708                                         max_fd = iobuf.out_fd;
709                         }
710                 } else
711                         out = NULL;
712
713                 if (max_fd < 0) {
714                         switch (flags & PIO_NEED_FLAGS) {
715                         case PIO_NEED_INPUT:
716                                 iobuf.in.len = 0;
717                                 if (kluge_around_eof == 2)
718                                         exit_cleanup(0);
719                                 if (iobuf.in_fd == -2)
720                                         whine_about_eof(True);
721                                 rprintf(FERROR, "error in perform_io: no fd for input.\n");
722                                 exit_cleanup(RERR_PROTOCOL);
723                         case PIO_NEED_OUTROOM:
724                         case PIO_NEED_MSGROOM:
725                                 msgs2stderr = 1;
726                                 drain_multiplex_messages();
727                                 if (iobuf.out_fd == -2)
728                                         whine_about_eof(True);
729                                 rprintf(FERROR, "error in perform_io: no fd for output.\n");
730                                 exit_cleanup(RERR_PROTOCOL);
731                         default:
732                                 /* No stated needs, so I guess this is OK. */
733                                 break;
734                         }
735                         break;
736                 }
737
738                 if (extra_flist_sending_enabled) {
739                         if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD && IN_MULTIPLEXED_AND_READY)
740                                 tv.tv_sec = 0;
741                         else {
742                                 extra_flist_sending_enabled = False;
743                                 tv.tv_sec = select_timeout;
744                         }
745                 } else
746                         tv.tv_sec = select_timeout;
747                 tv.tv_usec = 0;
748
749                 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
750
751                 if (cnt <= 0) {
752                         if (cnt < 0 && errno == EBADF) {
753                                 msgs2stderr = 1;
754                                 exit_cleanup(RERR_SOCKETIO);
755                         }
756                         if (extra_flist_sending_enabled) {
757                                 extra_flist_sending_enabled = False;
758                                 send_extra_file_list(sock_f_out, -1);
759                                 extra_flist_sending_enabled = !flist_eof;
760                         } else
761                                 check_timeout((flags & PIO_NEED_INPUT) != 0);
762                         FD_ZERO(&r_fds); /* Just in case... */
763                         FD_ZERO(&w_fds);
764                 }
765
766                 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
767                         size_t len, pos = iobuf.in.pos + iobuf.in.len;
768                         int n;
769                         if (pos >= iobuf.in.size) {
770                                 pos -= iobuf.in.size;
771                                 len = iobuf.in.size - iobuf.in.len;
772                         } else
773                                 len = iobuf.in.size - pos;
774                         if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
775                                 if (n == 0) {
776                                         /* Signal that input has become invalid. */
777                                         if (!read_batch || batch_fd < 0 || am_generator)
778                                                 iobuf.in_fd = -2;
779                                         batch_fd = -1;
780                                         continue;
781                                 }
782                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
783                                         n = 0;
784                                 else {
785                                         /* Don't write errors on a dead socket. */
786                                         if (iobuf.in_fd == sock_f_in) {
787                                                 if (am_sender)
788                                                         msgs2stderr = 1;
789                                                 rsyserr(FERROR_SOCKET, errno, "read error");
790                                         } else
791                                                 rsyserr(FERROR, errno, "read error");
792                                         exit_cleanup(RERR_SOCKETIO);
793                                 }
794                         }
795                         if (msgs2stderr && DEBUG_GTE(IO, 2))
796                                 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
797
798                         if (io_timeout) {
799                                 last_io_in = time(NULL);
800                                 if (flags & PIO_NEED_INPUT)
801                                         maybe_send_keepalive(last_io_in, 0);
802                         }
803                         stats.total_read += n;
804
805                         iobuf.in.len += n;
806                 }
807
808                 if (out && FD_ISSET(iobuf.out_fd, &w_fds)) {
809                         size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
810                         int n;
811
812                         if (bwlimit_writemax && len > bwlimit_writemax)
813                                 len = bwlimit_writemax;
814
815                         if (out->pos + len > out->size)
816                                 len = out->size - out->pos;
817                         if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
818                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
819                                         n = 0;
820                                 else {
821                                         /* Don't write errors on a dead socket. */
822                                         msgs2stderr = 1;
823                                         iobuf.out_fd = -2;
824                                         iobuf.out.len = iobuf.msg.len = iobuf.raw_flushing_ends_before = 0;
825                                         rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
826                                         drain_multiplex_messages();
827                                         exit_cleanup(RERR_SOCKETIO);
828                                 }
829                         }
830                         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
831                                 rprintf(FINFO, "[%s] %s sent=%ld\n",
832                                         who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
833                         }
834
835                         if (io_timeout)
836                                 last_io_out = time(NULL);
837                         stats.total_written += n;
838
839                         if (bwlimit_writemax)
840                                 sleep_for_bwlimit(n);
841
842                         if ((out->pos += n) == out->size) {
843                                 if (iobuf.raw_flushing_ends_before)
844                                         iobuf.raw_flushing_ends_before -= out->size;
845                                 out->pos = 0;
846                                 restore_iobuf_size(out);
847                         } else if (out->pos == iobuf.raw_flushing_ends_before)
848                                 iobuf.raw_flushing_ends_before = 0;
849                         if ((out->len -= n) == empty_buf_len) {
850                                 out->pos = 0;
851                                 restore_iobuf_size(out);
852                                 if (empty_buf_len)
853                                         iobuf.raw_data_header_pos = 0;
854                         }
855                 }
856
857                 if (got_kill_signal > 0) {
858                         got_kill_signal = -1;
859                         flush_ok_after_signal = True;
860                         exit_cleanup(RERR_SIGNAL);
861                 }
862
863                 /* We need to help prevent deadlock by doing what reading
864                  * we can whenever we are here trying to write. */
865                 if (IN_MULTIPLEXED_AND_READY && !(flags & PIO_NEED_INPUT)) {
866                         while (!iobuf.raw_input_ends_before && iobuf.in.len > 512)
867                                 read_a_msg();
868                         if (flist_receiving_enabled && iobuf.in.len > 512)
869                                 wait_for_receiver(); /* generator only */
870                 }
871
872                 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
873                         /* This can potentially flush all output and enable
874                          * multiplexed output, so keep this last in the loop
875                          * and be sure to not cache anything that would break
876                          * such a change. */
877                         forward_filesfrom_data();
878                 }
879         }
880   double_break:
881
882         data = iobuf.in.buf + iobuf.in.pos;
883
884         if (flags & PIO_CONSUME_INPUT) {
885                 iobuf.in.len -= needed;
886                 iobuf.in.pos += needed;
887                 if (iobuf.in.pos == iobuf.raw_input_ends_before)
888                         iobuf.raw_input_ends_before = 0;
889                 if (iobuf.in.pos >= iobuf.in.size) {
890                         iobuf.in.pos -= iobuf.in.size;
891                         if (iobuf.raw_input_ends_before)
892                                 iobuf.raw_input_ends_before -= iobuf.in.size;
893                 }
894         }
895
896         return data;
897 }
898
899 static void raw_read_buf(char *buf, size_t len)
900 {
901         size_t pos = iobuf.in.pos;
902         char *data = perform_io(len, PIO_INPUT_AND_CONSUME);
903         if (iobuf.in.pos <= pos && len) {
904                 size_t siz = len - iobuf.in.pos;
905                 memcpy(buf, data, siz);
906                 memcpy(buf + siz, iobuf.in.buf, iobuf.in.pos);
907         } else
908                 memcpy(buf, data, len);
909 }
910
911 static int32 raw_read_int(void)
912 {
913         char *data, buf[4];
914         if (iobuf.in.size - iobuf.in.pos >= 4)
915                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
916         else
917                 raw_read_buf(data = buf, 4);
918         return IVAL(data, 0);
919 }
920
921 void noop_io_until_death(void)
922 {
923         char buf[1024];
924
925         if (!iobuf.in.buf || !iobuf.out.buf || iobuf.in_fd < 0 || iobuf.out_fd < 0 || kluge_around_eof)
926                 return;
927
928         kluge_around_eof = 2;
929         /* Setting an I/O timeout ensures that if something inexplicably weird
930          * happens, we won't hang around forever. */
931         if (!io_timeout)
932                 set_io_timeout(60);
933
934         while (1)
935                 read_buf(iobuf.in_fd, buf, sizeof buf);
936 }
937
938 /* Buffer a message for the multiplexed output stream.  Is not used for (normal) MSG_DATA. */
939 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
940 {
941         char *hdr;
942         size_t needed, pos;
943         BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
944
945         if (!OUT_MULTIPLEXED)
946                 return 0;
947
948         if (want_debug)
949                 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
950
951         /* When checking for enough free space for this message, we need to
952          * make sure that there is space for the 4-byte header, plus we'll
953          * assume that we may waste up to 3 bytes (if the header doesn't fit
954          * at the physical end of the buffer). */
955 #ifdef ICONV_OPTION
956         if (convert > 0 && ic_send == (iconv_t)-1)
957                 convert = 0;
958         if (convert > 0) {
959                 /* Ensuring double-size room leaves space for maximal conversion expansion. */
960                 needed = len*2 + 4 + 3;
961         } else
962 #endif
963                 needed = len + 4 + 3;
964         if (iobuf.msg.len + needed > iobuf.msg.size)
965                 perform_io(needed, PIO_NEED_MSGROOM);
966
967         pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
968         if (pos >= iobuf.msg.size)
969                 pos -= iobuf.msg.size;
970         else if (pos + 4 > iobuf.msg.size) {
971                 /* The 4-byte header won't fit at the end of the buffer,
972                  * so we'll temporarily reduce the message buffer's size
973                  * and put the header at the start of the buffer. */
974                 reduce_iobuf_size(&iobuf.msg, pos);
975                 pos = 0;
976         }
977         hdr = iobuf.msg.buf + pos;
978
979         iobuf.msg.len += 4; /* Allocate room for the coming header bytes. */
980
981 #ifdef ICONV_OPTION
982         if (convert > 0) {
983                 xbuf inbuf;
984
985                 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
986
987                 len = iobuf.msg.len;
988                 iconvbufs(ic_send, &inbuf, &iobuf.msg,
989                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
990                 if (inbuf.len > 0) {
991                         rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
992                         exit_cleanup(RERR_UNSUPPORTED);
993                 }
994                 len = iobuf.msg.len - len;
995         } else
996 #endif
997         {
998                 size_t siz;
999
1000                 if ((pos += 4) == iobuf.msg.size)
1001                         pos = 0;
1002
1003                 /* Handle a split copy if we wrap around the end of the circular buffer. */
1004                 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
1005                         memcpy(iobuf.msg.buf + pos, buf, siz);
1006                         memcpy(iobuf.msg.buf, buf + siz, len - siz);
1007                 } else
1008                         memcpy(iobuf.msg.buf + pos, buf, len);
1009
1010                 iobuf.msg.len += len;
1011         }
1012
1013         SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1014
1015         if (want_debug && convert > 0)
1016                 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
1017
1018         return 1;
1019 }
1020
1021 void send_msg_int(enum msgcode code, int num)
1022 {
1023         char numbuf[4];
1024
1025         if (DEBUG_GTE(IO, 1))
1026                 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
1027
1028         SIVAL(numbuf, 0, num);
1029         send_msg(code, numbuf, 4, -1);
1030 }
1031
1032 static void got_flist_entry_status(enum festatus status, int ndx)
1033 {
1034         struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
1035
1036         if (remove_source_files) {
1037                 active_filecnt--;
1038                 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
1039         }
1040
1041         if (inc_recurse)
1042                 flist->in_progress--;
1043
1044         switch (status) {
1045         case FES_SUCCESS:
1046                 if (remove_source_files)
1047                         send_msg_int(MSG_SUCCESS, ndx);
1048                 /* FALL THROUGH */
1049         case FES_NO_SEND:
1050 #ifdef SUPPORT_HARD_LINKS
1051                 if (preserve_hard_links) {
1052                         struct file_struct *file = flist->files[ndx - flist->ndx_start];
1053                         if (F_IS_HLINKED(file)) {
1054                                 if (status == FES_NO_SEND)
1055                                         flist_ndx_push(&hlink_list, -2); /* indicates a failure follows */
1056                                 flist_ndx_push(&hlink_list, ndx);
1057                                 if (inc_recurse)
1058                                         flist->in_progress++;
1059                         }
1060                 }
1061 #endif
1062                 break;
1063         case FES_REDO:
1064                 if (read_batch) {
1065                         if (inc_recurse)
1066                                 flist->in_progress++;
1067                         break;
1068                 }
1069                 if (inc_recurse)
1070                         flist->to_redo++;
1071                 flist_ndx_push(&redo_list, ndx);
1072                 break;
1073         }
1074 }
1075
1076 /* Note the fds used for the main socket (which might really be a pipe
1077  * for a local transfer, but we can ignore that). */
1078 void io_set_sock_fds(int f_in, int f_out)
1079 {
1080         sock_f_in = f_in;
1081         sock_f_out = f_out;
1082 }
1083
1084 void set_io_timeout(int secs)
1085 {
1086         io_timeout = secs;
1087         allowed_lull = (io_timeout + 1) / 2;
1088
1089         if (!io_timeout || allowed_lull > SELECT_TIMEOUT)
1090                 select_timeout = SELECT_TIMEOUT;
1091         else
1092                 select_timeout = allowed_lull;
1093
1094         if (read_batch)
1095                 allowed_lull = 0;
1096 }
1097
1098 static void check_for_d_option_error(const char *msg)
1099 {
1100         static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
1101         char *colon;
1102         int saw_d = 0;
1103
1104         if (*msg != 'r'
1105          || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
1106                 return;
1107
1108         msg += sizeof REMOTE_OPTION_ERROR - 1;
1109         if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
1110          || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
1111                 return;
1112
1113         for ( ; *msg != ':'; msg++) {
1114                 if (*msg == 'd')
1115                         saw_d = 1;
1116                 else if (*msg == 'e')
1117                         break;
1118                 else if (strchr(rsync263_opts, *msg) == NULL)
1119                         return;
1120         }
1121
1122         if (saw_d) {
1123                 rprintf(FWARNING,
1124                     "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
1125         }
1126 }
1127
1128 /* This is used by the generator to limit how many file transfers can
1129  * be active at once when --remove-source-files is specified.  Without
1130  * this, sender-side deletions were mostly happening at the end. */
1131 void increment_active_files(int ndx, int itemizing, enum logcode code)
1132 {
1133         while (1) {
1134                 /* TODO: tune these limits? */
1135                 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1136                 if (active_filecnt < limit)
1137                         break;
1138                 check_for_finished_files(itemizing, code, 0);
1139                 if (active_filecnt < limit)
1140                         break;
1141                 wait_for_receiver();
1142         }
1143
1144         active_filecnt++;
1145         active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1146 }
1147
1148 int get_redo_num(void)
1149 {
1150         return flist_ndx_pop(&redo_list);
1151 }
1152
1153 int get_hlink_num(void)
1154 {
1155         return flist_ndx_pop(&hlink_list);
1156 }
1157
1158 /* When we're the receiver and we have a local --files-from list of names
1159  * that needs to be sent over the socket to the sender, we have to do two
1160  * things at the same time: send the sender a list of what files we're
1161  * processing and read the incoming file+info list from the sender.  We do
1162  * this by making recv_file_list() call forward_filesfrom_data(), which
1163  * will ensure that we forward data to the sender until we get some data
1164  * for recv_file_list() to use. */
1165 void start_filesfrom_forwarding(int fd)
1166 {
1167         if (protocol_version < 31 && OUT_MULTIPLEXED) {
1168                 /* Older protocols send the files-from data w/o packaging
1169                  * it in multiplexed I/O packets, so temporarily switch
1170                  * to buffered I/O to match this behavior. */
1171                 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1172                 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1173         }
1174         ff_forward_fd = fd;
1175
1176         alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1177 }
1178
1179 /* Read a line into the "buf" buffer. */
1180 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1181 {
1182         char ch, *s, *eob;
1183
1184 #ifdef ICONV_OPTION
1185         if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1186                 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1187 #endif
1188
1189   start:
1190 #ifdef ICONV_OPTION
1191         s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1192 #else
1193         s = buf;
1194 #endif
1195         eob = s + bufsiz - 1;
1196         while (1) {
1197                 /* We avoid read_byte() for files because files can return an EOF. */
1198                 if (fd == iobuf.in_fd)
1199                         ch = read_byte(fd);
1200                 else if (safe_read(fd, &ch, 1) == 0)
1201                         break;
1202                 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1203                         /* Skip empty lines if dumping comments. */
1204                         if (flags & RL_DUMP_COMMENTS && s == buf)
1205                                 continue;
1206                         break;
1207                 }
1208                 if (s < eob)
1209                         *s++ = ch;
1210         }
1211         *s = '\0';
1212
1213         if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1214                 goto start;
1215
1216 #ifdef ICONV_OPTION
1217         if (flags & RL_CONVERT) {
1218                 xbuf outbuf;
1219                 INIT_XBUF(outbuf, buf, 0, bufsiz);
1220                 iconv_buf.pos = 0;
1221                 iconv_buf.len = s - iconv_buf.buf;
1222                 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1223                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1224                 outbuf.buf[outbuf.len] = '\0';
1225                 return outbuf.len;
1226         }
1227 #endif
1228
1229         return s - buf;
1230 }
1231
1232 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1233                char ***argv_p, int *argc_p, char **request_p)
1234 {
1235         int maxargs = MAX_ARGS;
1236         int dot_pos = 0, argc = 0, request_len = 0;
1237         char **argv, *p;
1238         int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1239
1240 #ifdef ICONV_OPTION
1241         rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1242 #endif
1243
1244         if (!(argv = new_array(char *, maxargs)))
1245                 out_of_memory("read_args");
1246         if (mod_name && !protect_args)
1247                 argv[argc++] = "rsyncd";
1248
1249         if (request_p)
1250                 *request_p = NULL;
1251
1252         while (1) {
1253                 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1254                         break;
1255
1256                 if (argc == maxargs-1) {
1257                         maxargs += MAX_ARGS;
1258                         if (!(argv = realloc_array(argv, char *, maxargs)))
1259                                 out_of_memory("read_args");
1260                 }
1261
1262                 if (dot_pos) {
1263                         if (request_p && request_len < 1024) {
1264                                 int len = strlen(buf);
1265                                 if (request_len)
1266                                         request_p[0][request_len++] = ' ';
1267                                 if (!(*request_p = realloc_array(*request_p, char, request_len + len + 1)))
1268                                         out_of_memory("read_args");
1269                                 memcpy(*request_p + request_len, buf, len + 1);
1270                                 request_len += len;
1271                         }
1272                         if (mod_name)
1273                                 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1274                         else
1275                                 glob_expand(buf, &argv, &argc, &maxargs);
1276                 } else {
1277                         if (!(p = strdup(buf)))
1278                                 out_of_memory("read_args");
1279                         argv[argc++] = p;
1280                         if (*p == '.' && p[1] == '\0')
1281                                 dot_pos = argc;
1282                 }
1283         }
1284         argv[argc] = NULL;
1285
1286         glob_expand(NULL, NULL, NULL, NULL);
1287
1288         *argc_p = argc;
1289         *argv_p = argv;
1290 }
1291
1292 BOOL io_start_buffering_out(int f_out)
1293 {
1294         if (msgs2stderr && DEBUG_GTE(IO, 2))
1295                 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1296
1297         if (iobuf.out.buf) {
1298                 if (iobuf.out_fd == -1)
1299                         iobuf.out_fd = f_out;
1300                 else
1301                         assert(f_out == iobuf.out_fd);
1302                 return False;
1303         }
1304
1305         alloc_xbuf(&iobuf.out, ROUND_UP_1024(IO_BUFFER_SIZE * 2));
1306         iobuf.out_fd = f_out;
1307
1308         return True;
1309 }
1310
1311 BOOL io_start_buffering_in(int f_in)
1312 {
1313         if (msgs2stderr && DEBUG_GTE(IO, 2))
1314                 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1315
1316         if (iobuf.in.buf) {
1317                 if (iobuf.in_fd == -1)
1318                         iobuf.in_fd = f_in;
1319                 else
1320                         assert(f_in == iobuf.in_fd);
1321                 return False;
1322         }
1323
1324         alloc_xbuf(&iobuf.in, ROUND_UP_1024(IO_BUFFER_SIZE));
1325         iobuf.in_fd = f_in;
1326
1327         return True;
1328 }
1329
1330 void io_end_buffering_in(BOOL free_buffers)
1331 {
1332         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1333                 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1334                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1335         }
1336
1337         if (free_buffers)
1338                 free_xbuf(&iobuf.in);
1339         else
1340                 iobuf.in.pos = iobuf.in.len = 0;
1341
1342         iobuf.in_fd = -1;
1343 }
1344
1345 void io_end_buffering_out(BOOL free_buffers)
1346 {
1347         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1348                 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1349                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1350         }
1351
1352         io_flush(FULL_FLUSH);
1353
1354         if (free_buffers) {
1355                 free_xbuf(&iobuf.out);
1356                 free_xbuf(&iobuf.msg);
1357         }
1358
1359         iobuf.out_fd = -1;
1360 }
1361
1362 void maybe_flush_socket(int important)
1363 {
1364         if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1365          && (important || time(NULL) - last_io_out >= 5))
1366                 io_flush(NORMAL_FLUSH);
1367 }
1368
1369 /* Older rsync versions used to send either a MSG_NOOP (protocol 30) or a
1370  * raw-data-based keep-alive (protocol 29), both of which implied forwarding of
1371  * the message through the sender.  Since the new timeout method does not need
1372  * any forwarding, we just send an empty MSG_DATA message, which works with all
1373  * rsync versions.  This avoids any message forwarding, and leaves the raw-data
1374  * stream alone (since we can never be quite sure if that stream is in the
1375  * right state for a keep-alive message). */
1376 void maybe_send_keepalive(time_t now, int flags)
1377 {
1378         if (flags & MSK_ACTIVE_RECEIVER)
1379                 last_io_in = now; /* Fudge things when we're working hard on the files. */
1380
1381         if (now - last_io_out >= allowed_lull) {
1382                 /* The receiver is special:  it only sends keep-alive messages if it is
1383                  * actively receiving data.  Otherwise, it lets the generator timeout. */
1384                 if (am_receiver && now - last_io_in >= io_timeout)
1385                         return;
1386
1387                 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len)
1388                         send_msg(MSG_DATA, "", 0, 0);
1389                 if (!(flags & MSK_ALLOW_FLUSH)) {
1390                         /* Let the caller worry about writing out the data. */
1391                 } else if (iobuf.msg.len)
1392                         perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1393                 else if (iobuf.out.len > iobuf.out_empty_len)
1394                         io_flush(NORMAL_FLUSH);
1395         }
1396 }
1397
1398 void start_flist_forward(int ndx)
1399 {
1400         write_int(iobuf.out_fd, ndx);
1401         forward_flist_data = 1;
1402 }
1403
1404 void stop_flist_forward(void)
1405 {
1406         forward_flist_data = 0;
1407 }
1408
1409 /* Read a message from a multiplexed source. */
1410 static void read_a_msg(void)
1411 {
1412         char data[BIGPATHBUFLEN];
1413         int tag, val;
1414         size_t msg_bytes;
1415
1416         /* This ensures that perform_io() does not try to do any message reading
1417          * until we've read all of the data for this message.  We should also
1418          * try to avoid calling things that will cause data to be written via
1419          * perform_io() prior to this being reset to 1. */
1420         iobuf.in_multiplexed = -1;
1421
1422         tag = raw_read_int();
1423
1424         msg_bytes = tag & 0xFFFFFF;
1425         tag = (tag >> 24) - MPLEX_BASE;
1426
1427         if (DEBUG_GTE(IO, 1) && msgs2stderr)
1428                 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1429
1430         switch (tag) {
1431         case MSG_DATA:
1432                 assert(iobuf.raw_input_ends_before == 0);
1433                 /* Though this does not yet read the data, we do mark where in
1434                  * the buffer the msg data will end once it is read.  It is
1435                  * possible that this points off the end of the buffer, in
1436                  * which case the gradual reading of the input stream will
1437                  * cause this value to wrap around and eventually become real. */
1438                 if (msg_bytes)
1439                         iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1440                 iobuf.in_multiplexed = 1;
1441                 break;
1442         case MSG_STATS:
1443                 if (msg_bytes != sizeof stats.total_read || !am_generator)
1444                         goto invalid_msg;
1445                 raw_read_buf((char*)&stats.total_read, sizeof stats.total_read);
1446                 iobuf.in_multiplexed = 1;
1447                 break;
1448         case MSG_REDO:
1449                 if (msg_bytes != 4 || !am_generator)
1450                         goto invalid_msg;
1451                 val = raw_read_int();
1452                 iobuf.in_multiplexed = 1;
1453                 got_flist_entry_status(FES_REDO, val);
1454                 break;
1455         case MSG_IO_ERROR:
1456                 if (msg_bytes != 4)
1457                         goto invalid_msg;
1458                 val = raw_read_int();
1459                 iobuf.in_multiplexed = 1;
1460                 io_error |= val;
1461                 if (am_receiver)
1462                         send_msg_int(MSG_IO_ERROR, val);
1463                 break;
1464         case MSG_IO_TIMEOUT:
1465                 if (msg_bytes != 4 || am_server || am_generator)
1466                         goto invalid_msg;
1467                 val = raw_read_int();
1468                 iobuf.in_multiplexed = 1;
1469                 if (!io_timeout || io_timeout > val) {
1470                         if (INFO_GTE(MISC, 2))
1471                                 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1472                         set_io_timeout(val);
1473                 }
1474                 break;
1475         case MSG_NOOP:
1476                 /* Support protocol-30 keep-alive method. */
1477                 if (msg_bytes != 0)
1478                         goto invalid_msg;
1479                 iobuf.in_multiplexed = 1;
1480                 if (am_sender)
1481                         maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
1482                 break;
1483         case MSG_DELETED:
1484                 if (msg_bytes >= sizeof data)
1485                         goto overflow;
1486                 if (am_generator) {
1487                         raw_read_buf(data, msg_bytes);
1488                         iobuf.in_multiplexed = 1;
1489                         send_msg(MSG_DELETED, data, msg_bytes, 1);
1490                         break;
1491                 }
1492 #ifdef ICONV_OPTION
1493                 if (ic_recv != (iconv_t)-1) {
1494                         xbuf outbuf, inbuf;
1495                         char ibuf[512];
1496                         int add_null = 0;
1497                         int flags = ICB_INCLUDE_BAD | ICB_INIT;
1498
1499                         INIT_CONST_XBUF(outbuf, data);
1500                         INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1501
1502                         while (msg_bytes) {
1503                                 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1504                                 raw_read_buf(ibuf + inbuf.len, len);
1505                                 inbuf.pos = 0;
1506                                 inbuf.len += len;
1507                                 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1508                                         inbuf.len--, add_null = 1;
1509                                 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1510                                         if (errno == E2BIG)
1511                                                 goto overflow;
1512                                         /* Buffer ended with an incomplete char, so move the
1513                                          * bytes to the start of the buffer and continue. */
1514                                         memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1515                                 }
1516                                 flags &= ~ICB_INIT;
1517                         }
1518                         if (add_null) {
1519                                 if (outbuf.len == outbuf.size)
1520                                         goto overflow;
1521                                 outbuf.buf[outbuf.len++] = '\0';
1522                         }
1523                         msg_bytes = outbuf.len;
1524                 } else
1525 #endif
1526                         raw_read_buf(data, msg_bytes);
1527                 iobuf.in_multiplexed = 1;
1528                 /* A directory name was sent with the trailing null */
1529                 if (msg_bytes > 0 && !data[msg_bytes-1])
1530                         log_delete(data, S_IFDIR);
1531                 else {
1532                         data[msg_bytes] = '\0';
1533                         log_delete(data, S_IFREG);
1534                 }
1535                 break;
1536         case MSG_SUCCESS:
1537                 if (msg_bytes != 4) {
1538                   invalid_msg:
1539                         rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1540                                 tag, (unsigned long)msg_bytes, who_am_i(),
1541                                 inc_recurse ? "/inc" : "");
1542                         exit_cleanup(RERR_STREAMIO);
1543                 }
1544                 val = raw_read_int();
1545                 iobuf.in_multiplexed = 1;
1546                 if (am_generator)
1547                         got_flist_entry_status(FES_SUCCESS, val);
1548                 else
1549                         successful_send(val);
1550                 break;
1551         case MSG_NO_SEND:
1552                 if (msg_bytes != 4)
1553                         goto invalid_msg;
1554                 val = raw_read_int();
1555                 iobuf.in_multiplexed = 1;
1556                 if (am_generator)
1557                         got_flist_entry_status(FES_NO_SEND, val);
1558                 else
1559                         send_msg_int(MSG_NO_SEND, val);
1560                 break;
1561         case MSG_ERROR_SOCKET:
1562         case MSG_ERROR_UTF8:
1563         case MSG_CLIENT:
1564         case MSG_LOG:
1565                 if (!am_generator)
1566                         goto invalid_msg;
1567                 if (tag == MSG_ERROR_SOCKET)
1568                         msgs2stderr = 1;
1569                 /* FALL THROUGH */
1570         case MSG_INFO:
1571         case MSG_ERROR:
1572         case MSG_ERROR_XFER:
1573         case MSG_WARNING:
1574                 if (msg_bytes >= sizeof data) {
1575                     overflow:
1576                         rprintf(FERROR,
1577                                 "multiplexing overflow %d:%lu [%s%s]\n",
1578                                 tag, (unsigned long)msg_bytes, who_am_i(),
1579                                 inc_recurse ? "/inc" : "");
1580                         exit_cleanup(RERR_STREAMIO);
1581                 }
1582                 raw_read_buf(data, msg_bytes);
1583                 /* We don't set in_multiplexed value back to 1 before writing this message
1584                  * because the write might loop back and read yet another message, over and
1585                  * over again, while waiting for room to put the message in the msg buffer. */
1586                 rwrite((enum logcode)tag, data, msg_bytes, !am_generator);
1587                 iobuf.in_multiplexed = 1;
1588                 if (first_message) {
1589                         if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof data) {
1590                                 data[msg_bytes] = '\0';
1591                                 check_for_d_option_error(data);
1592                         }
1593                         first_message = 0;
1594                 }
1595                 break;
1596         case MSG_ERROR_EXIT:
1597                 if (msg_bytes == 4)
1598                         val = raw_read_int();
1599                 else if (msg_bytes == 0)
1600                         val = 0;
1601                 else
1602                         goto invalid_msg;
1603                 iobuf.in_multiplexed = 1;
1604                 if (DEBUG_GTE(EXIT, 3))
1605                         rprintf(FINFO, "[%s] got MSG_ERROR_EXIT with %ld bytes\n", who_am_i(), (long)msg_bytes);
1606                 if (msg_bytes == 0) {
1607                         if (!am_sender && !am_generator) {
1608                                 if (DEBUG_GTE(EXIT, 3)) {
1609                                         rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1610                                                 who_am_i());
1611                                 }
1612                                 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1613                                 io_flush(FULL_FLUSH);
1614                         }
1615                 } else if (protocol_version >= 31) {
1616                         if (am_generator || am_receiver) {
1617                                 if (DEBUG_GTE(EXIT, 3)) {
1618                                         rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT with exit_code %d\n",
1619                                                 who_am_i(), val);
1620                                 }
1621                                 send_msg_int(MSG_ERROR_EXIT, val);
1622                         } else {
1623                                 if (DEBUG_GTE(EXIT, 3)) {
1624                                         rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1625                                                 who_am_i());
1626                                 }
1627                                 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1628                         }
1629                 }
1630                 /* Send a negative linenum so that we don't end up
1631                  * with a duplicate exit message. */
1632                 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1633         default:
1634                 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1635                         tag, who_am_i(), inc_recurse ? "/inc" : "");
1636                 exit_cleanup(RERR_STREAMIO);
1637         }
1638
1639         assert(iobuf.in_multiplexed > 0);
1640 }
1641
1642 static void drain_multiplex_messages(void)
1643 {
1644         while (IN_MULTIPLEXED_AND_READY && iobuf.in.len) {
1645                 if (iobuf.raw_input_ends_before) {
1646                         size_t raw_len = iobuf.raw_input_ends_before - iobuf.in.pos;
1647                         iobuf.raw_input_ends_before = 0;
1648                         if (raw_len >= iobuf.in.len) {
1649                                 iobuf.in.len = 0;
1650                                 break;
1651                         }
1652                         iobuf.in.len -= raw_len;
1653                         if ((iobuf.in.pos += raw_len) >= iobuf.in.size)
1654                                 iobuf.in.pos -= iobuf.in.size;
1655                 }
1656                 read_a_msg();
1657         }
1658 }
1659
1660 void wait_for_receiver(void)
1661 {
1662         if (!iobuf.raw_input_ends_before)
1663                 read_a_msg();
1664
1665         if (iobuf.raw_input_ends_before) {
1666                 int ndx = read_int(iobuf.in_fd);
1667                 if (ndx < 0) {
1668                         switch (ndx) {
1669                         case NDX_FLIST_EOF:
1670                                 flist_eof = 1;
1671                                 if (DEBUG_GTE(FLIST, 3))
1672                                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1673                                 break;
1674                         case NDX_DONE:
1675                                 msgdone_cnt++;
1676                                 break;
1677                         default:
1678                                 exit_cleanup(RERR_STREAMIO);
1679                         }
1680                 } else {
1681                         struct file_list *flist;
1682                         flist_receiving_enabled = False;
1683                         if (DEBUG_GTE(FLIST, 2)) {
1684                                 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1685                                         who_am_i(), ndx);
1686                         }
1687                         flist = recv_file_list(iobuf.in_fd);
1688                         flist->parent_ndx = ndx;
1689 #ifdef SUPPORT_HARD_LINKS
1690                         if (preserve_hard_links)
1691                                 match_hard_links(flist);
1692 #endif
1693                         flist_receiving_enabled = True;
1694                 }
1695         }
1696 }
1697
1698 unsigned short read_shortint(int f)
1699 {
1700         char b[2];
1701         read_buf(f, b, 2);
1702         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1703 }
1704
1705 int32 read_int(int f)
1706 {
1707         char b[4];
1708         int32 num;
1709
1710         read_buf(f, b, 4);
1711         num = IVAL(b, 0);
1712 #if SIZEOF_INT32 > 4
1713         if (num & (int32)0x80000000)
1714                 num |= ~(int32)0xffffffff;
1715 #endif
1716         return num;
1717 }
1718
1719 int32 read_varint(int f)
1720 {
1721         union {
1722                 char b[5];
1723                 int32 x;
1724         } u;
1725         uchar ch;
1726         int extra;
1727
1728         u.x = 0;
1729         ch = read_byte(f);
1730         extra = int_byte_extra[ch / 4];
1731         if (extra) {
1732                 uchar bit = ((uchar)1<<(8-extra));
1733                 if (extra >= (int)sizeof u.b) {
1734                         rprintf(FERROR, "Overflow in read_varint()\n");
1735                         exit_cleanup(RERR_STREAMIO);
1736                 }
1737                 read_buf(f, u.b, extra);
1738                 u.b[extra] = ch & (bit-1);
1739         } else
1740                 u.b[0] = ch;
1741 #if CAREFUL_ALIGNMENT
1742         u.x = IVAL(u.b,0);
1743 #endif
1744 #if SIZEOF_INT32 > 4
1745         if (u.x & (int32)0x80000000)
1746                 u.x |= ~(int32)0xffffffff;
1747 #endif
1748         return u.x;
1749 }
1750
1751 int64 read_varlong(int f, uchar min_bytes)
1752 {
1753         union {
1754                 char b[9];
1755                 int64 x;
1756         } u;
1757         char b2[8];
1758         int extra;
1759
1760 #if SIZEOF_INT64 < 8
1761         memset(u.b, 0, 8);
1762 #else
1763         u.x = 0;
1764 #endif
1765         read_buf(f, b2, min_bytes);
1766         memcpy(u.b, b2+1, min_bytes-1);
1767         extra = int_byte_extra[CVAL(b2, 0) / 4];
1768         if (extra) {
1769                 uchar bit = ((uchar)1<<(8-extra));
1770                 if (min_bytes + extra > (int)sizeof u.b) {
1771                         rprintf(FERROR, "Overflow in read_varlong()\n");
1772                         exit_cleanup(RERR_STREAMIO);
1773                 }
1774                 read_buf(f, u.b + min_bytes - 1, extra);
1775                 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1776 #if SIZEOF_INT64 < 8
1777                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1778                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1779                         exit_cleanup(RERR_UNSUPPORTED);
1780                 }
1781 #endif
1782         } else
1783                 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1784 #if SIZEOF_INT64 < 8
1785         u.x = IVAL(u.b,0);
1786 #elif CAREFUL_ALIGNMENT
1787         u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1788 #endif
1789         return u.x;
1790 }
1791
1792 int64 read_longint(int f)
1793 {
1794 #if SIZEOF_INT64 >= 8
1795         char b[9];
1796 #endif
1797         int32 num = read_int(f);
1798
1799         if (num != (int32)0xffffffff)
1800                 return num;
1801
1802 #if SIZEOF_INT64 < 8
1803         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1804         exit_cleanup(RERR_UNSUPPORTED);
1805 #else
1806         read_buf(f, b, 8);
1807         return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1808 #endif
1809 }
1810
1811 void read_buf(int f, char *buf, size_t len)
1812 {
1813         if (f != iobuf.in_fd) {
1814                 if (safe_read(f, buf, len) != len)
1815                         whine_about_eof(False); /* Doesn't return. */
1816                 goto batch_copy;
1817         }
1818
1819         if (!IN_MULTIPLEXED) {
1820                 raw_read_buf(buf, len);
1821                 total_data_read += len;
1822                 if (forward_flist_data)
1823                         write_buf(iobuf.out_fd, buf, len);
1824           batch_copy:
1825                 if (f == write_batch_monitor_in)
1826                         safe_write(batch_fd, buf, len);
1827                 return;
1828         }
1829
1830         while (1) {
1831                 size_t siz;
1832
1833                 while (!iobuf.raw_input_ends_before)
1834                         read_a_msg();
1835
1836                 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1837                 if (siz >= iobuf.in.size)
1838                         siz = iobuf.in.size;
1839                 raw_read_buf(buf, siz);
1840                 total_data_read += siz;
1841
1842                 if (forward_flist_data)
1843                         write_buf(iobuf.out_fd, buf, siz);
1844
1845                 if (f == write_batch_monitor_in)
1846                         safe_write(batch_fd, buf, siz);
1847
1848                 if ((len -= siz) == 0)
1849                         break;
1850                 buf += siz;
1851         }
1852 }
1853
1854 void read_sbuf(int f, char *buf, size_t len)
1855 {
1856         read_buf(f, buf, len);
1857         buf[len] = '\0';
1858 }
1859
1860 uchar read_byte(int f)
1861 {
1862         uchar c;
1863         read_buf(f, (char*)&c, 1);
1864         return c;
1865 }
1866
1867 int read_vstring(int f, char *buf, int bufsize)
1868 {
1869         int len = read_byte(f);
1870
1871         if (len & 0x80)
1872                 len = (len & ~0x80) * 0x100 + read_byte(f);
1873
1874         if (len >= bufsize) {
1875                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1876                         len, bufsize - 1);
1877                 return -1;
1878         }
1879
1880         if (len)
1881                 read_buf(f, buf, len);
1882         buf[len] = '\0';
1883         return len;
1884 }
1885
1886 /* Populate a sum_struct with values from the socket.  This is
1887  * called by both the sender and the receiver. */
1888 void read_sum_head(int f, struct sum_struct *sum)
1889 {
1890         int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1891         sum->count = read_int(f);
1892         if (sum->count < 0) {
1893                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1894                         (long)sum->count, who_am_i());
1895                 exit_cleanup(RERR_PROTOCOL);
1896         }
1897         sum->blength = read_int(f);
1898         if (sum->blength < 0 || sum->blength > max_blength) {
1899                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1900                         (long)sum->blength, who_am_i());
1901                 exit_cleanup(RERR_PROTOCOL);
1902         }
1903         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1904         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1905                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1906                         sum->s2length, who_am_i());
1907                 exit_cleanup(RERR_PROTOCOL);
1908         }
1909         sum->remainder = read_int(f);
1910         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1911                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1912                         (long)sum->remainder, who_am_i());
1913                 exit_cleanup(RERR_PROTOCOL);
1914         }
1915 }
1916
1917 /* Send the values from a sum_struct over the socket.  Set sum to
1918  * NULL if there are no checksums to send.  This is called by both
1919  * the generator and the sender. */
1920 void write_sum_head(int f, struct sum_struct *sum)
1921 {
1922         static struct sum_struct null_sum;
1923
1924         if (sum == NULL)
1925                 sum = &null_sum;
1926
1927         write_int(f, sum->count);
1928         write_int(f, sum->blength);
1929         if (protocol_version >= 27)
1930                 write_int(f, sum->s2length);
1931         write_int(f, sum->remainder);
1932 }
1933
1934 /* Sleep after writing to limit I/O bandwidth usage.
1935  *
1936  * @todo Rather than sleeping after each write, it might be better to
1937  * use some kind of averaging.  The current algorithm seems to always
1938  * use a bit less bandwidth than specified, because it doesn't make up
1939  * for slow periods.  But arguably this is a feature.  In addition, we
1940  * ought to take the time used to write the data into account.
1941  *
1942  * During some phases of big transfers (file FOO is uptodate) this is
1943  * called with a small bytes_written every time.  As the kernel has to
1944  * round small waits up to guarantee that we actually wait at least the
1945  * requested number of microseconds, this can become grossly inaccurate.
1946  * We therefore keep track of the bytes we've written over time and only
1947  * sleep when the accumulated delay is at least 1 tenth of a second. */
1948 static void sleep_for_bwlimit(int bytes_written)
1949 {
1950         static struct timeval prior_tv;
1951         static long total_written = 0;
1952         struct timeval tv, start_tv;
1953         long elapsed_usec, sleep_usec;
1954
1955 #define ONE_SEC 1000000L /* # of microseconds in a second */
1956
1957         total_written += bytes_written;
1958
1959         gettimeofday(&start_tv, NULL);
1960         if (prior_tv.tv_sec) {
1961                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1962                              + (start_tv.tv_usec - prior_tv.tv_usec);
1963                 total_written -= (int64)elapsed_usec * bwlimit / (ONE_SEC/1024);
1964                 if (total_written < 0)
1965                         total_written = 0;
1966         }
1967
1968         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1969         if (sleep_usec < ONE_SEC / 10) {
1970                 prior_tv = start_tv;
1971                 return;
1972         }
1973
1974         tv.tv_sec  = sleep_usec / ONE_SEC;
1975         tv.tv_usec = sleep_usec % ONE_SEC;
1976         select(0, NULL, NULL, NULL, &tv);
1977
1978         gettimeofday(&prior_tv, NULL);
1979         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1980                      + (prior_tv.tv_usec - start_tv.tv_usec);
1981         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1982 }
1983
1984 void io_flush(int flush_it_all)
1985 {
1986         if (iobuf.out.len > iobuf.out_empty_len) {
1987                 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1988                         perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1989                 else /* NORMAL_FLUSH: flush at least 1 byte */
1990                         perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1991         }
1992         if (iobuf.msg.len)
1993                 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1994 }
1995
1996 void write_shortint(int f, unsigned short x)
1997 {
1998         char b[2];
1999         b[0] = (char)x;
2000         b[1] = (char)(x >> 8);
2001         write_buf(f, b, 2);
2002 }
2003
2004 void write_int(int f, int32 x)
2005 {
2006         char b[4];
2007         SIVAL(b, 0, x);
2008         write_buf(f, b, 4);
2009 }
2010
2011 void write_varint(int f, int32 x)
2012 {
2013         char b[5];
2014         uchar bit;
2015         int cnt = 4;
2016
2017         SIVAL(b, 1, x);
2018
2019         while (cnt > 1 && b[cnt] == 0)
2020                 cnt--;
2021         bit = ((uchar)1<<(7-cnt+1));
2022         if (CVAL(b, cnt) >= bit) {
2023                 cnt++;
2024                 *b = ~(bit-1);
2025         } else if (cnt > 1)
2026                 *b = b[cnt] | ~(bit*2-1);
2027         else
2028                 *b = b[cnt];
2029
2030         write_buf(f, b, cnt);
2031 }
2032
2033 void write_varlong(int f, int64 x, uchar min_bytes)
2034 {
2035         char b[9];
2036         uchar bit;
2037         int cnt = 8;
2038
2039         SIVAL(b, 1, x);
2040 #if SIZEOF_INT64 >= 8
2041         SIVAL(b, 5, x >> 32);
2042 #else
2043         if (x <= 0x7FFFFFFF && x >= 0)
2044                 memset(b + 5, 0, 4);
2045         else {
2046                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
2047                 exit_cleanup(RERR_UNSUPPORTED);
2048         }
2049 #endif
2050
2051         while (cnt > min_bytes && b[cnt] == 0)
2052                 cnt--;
2053         bit = ((uchar)1<<(7-cnt+min_bytes));
2054         if (CVAL(b, cnt) >= bit) {
2055                 cnt++;
2056                 *b = ~(bit-1);
2057         } else if (cnt > min_bytes)
2058                 *b = b[cnt] | ~(bit*2-1);
2059         else
2060                 *b = b[cnt];
2061
2062         write_buf(f, b, cnt);
2063 }
2064
2065 /*
2066  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
2067  * 64-bit types on this platform.
2068  */
2069 void write_longint(int f, int64 x)
2070 {
2071         char b[12], * const s = b+4;
2072
2073         SIVAL(s, 0, x);
2074         if (x <= 0x7FFFFFFF && x >= 0) {
2075                 write_buf(f, s, 4);
2076                 return;
2077         }
2078
2079 #if SIZEOF_INT64 < 8
2080         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
2081         exit_cleanup(RERR_UNSUPPORTED);
2082 #else
2083         memset(b, 0xFF, 4);
2084         SIVAL(s, 4, x >> 32);
2085         write_buf(f, b, 12);
2086 #endif
2087 }
2088
2089 void write_buf(int f, const char *buf, size_t len)
2090 {
2091         size_t pos, siz;
2092
2093         if (f != iobuf.out_fd) {
2094                 safe_write(f, buf, len);
2095                 goto batch_copy;
2096         }
2097
2098         if (iobuf.out.len + len > iobuf.out.size)
2099                 perform_io(len, PIO_NEED_OUTROOM);
2100
2101         pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
2102         if (pos >= iobuf.out.size)
2103                 pos -= iobuf.out.size;
2104
2105         /* Handle a split copy if we wrap around the end of the circular buffer. */
2106         if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
2107                 memcpy(iobuf.out.buf + pos, buf, siz);
2108                 memcpy(iobuf.out.buf, buf + siz, len - siz);
2109         } else
2110                 memcpy(iobuf.out.buf + pos, buf, len);
2111
2112         iobuf.out.len += len;
2113         total_data_written += len;
2114
2115   batch_copy:
2116         if (f == write_batch_monitor_out)
2117                 safe_write(batch_fd, buf, len);
2118 }
2119
2120 /* Write a string to the connection */
2121 void write_sbuf(int f, const char *buf)
2122 {
2123         write_buf(f, buf, strlen(buf));
2124 }
2125
2126 void write_byte(int f, uchar c)
2127 {
2128         write_buf(f, (char *)&c, 1);
2129 }
2130
2131 void write_vstring(int f, const char *str, int len)
2132 {
2133         uchar lenbuf[3], *lb = lenbuf;
2134
2135         if (len > 0x7F) {
2136                 if (len > 0x7FFF) {
2137                         rprintf(FERROR,
2138                                 "attempting to send over-long vstring (%d > %d)\n",
2139                                 len, 0x7FFF);
2140                         exit_cleanup(RERR_PROTOCOL);
2141                 }
2142                 *lb++ = len / 0x100 + 0x80;
2143         }
2144         *lb = len;
2145
2146         write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
2147         if (len)
2148                 write_buf(f, str, len);
2149 }
2150
2151 /* Send a file-list index using a byte-reduction method. */
2152 void write_ndx(int f, int32 ndx)
2153 {
2154         static int32 prev_positive = -1, prev_negative = 1;
2155         int32 diff, cnt = 0;
2156         char b[6];
2157
2158         if (protocol_version < 30 || read_batch) {
2159                 write_int(f, ndx);
2160                 return;
2161         }
2162
2163         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
2164          * negative nums as a positive after sending a leading 0xFF. */
2165         if (ndx >= 0) {
2166                 diff = ndx - prev_positive;
2167                 prev_positive = ndx;
2168         } else if (ndx == NDX_DONE) {
2169                 *b = 0;
2170                 write_buf(f, b, 1);
2171                 return;
2172         } else {
2173                 b[cnt++] = (char)0xFF;
2174                 ndx = -ndx;
2175                 diff = ndx - prev_negative;
2176                 prev_negative = ndx;
2177         }
2178
2179         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
2180          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
2181          * & all 4 bytes of the (non-negative) num with the high-bit set. */
2182         if (diff < 0xFE && diff > 0)
2183                 b[cnt++] = (char)diff;
2184         else if (diff < 0 || diff > 0x7FFF) {
2185                 b[cnt++] = (char)0xFE;
2186                 b[cnt++] = (char)((ndx >> 24) | 0x80);
2187                 b[cnt++] = (char)ndx;
2188                 b[cnt++] = (char)(ndx >> 8);
2189                 b[cnt++] = (char)(ndx >> 16);
2190         } else {
2191                 b[cnt++] = (char)0xFE;
2192                 b[cnt++] = (char)(diff >> 8);
2193                 b[cnt++] = (char)diff;
2194         }
2195         write_buf(f, b, cnt);
2196 }
2197
2198 /* Receive a file-list index using a byte-reduction method. */
2199 int32 read_ndx(int f)
2200 {
2201         static int32 prev_positive = -1, prev_negative = 1;
2202         int32 *prev_ptr, num;
2203         char b[4];
2204
2205         if (protocol_version < 30)
2206                 return read_int(f);
2207
2208         read_buf(f, b, 1);
2209         if (CVAL(b, 0) == 0xFF) {
2210                 read_buf(f, b, 1);
2211                 prev_ptr = &prev_negative;
2212         } else if (CVAL(b, 0) == 0)
2213                 return NDX_DONE;
2214         else
2215                 prev_ptr = &prev_positive;
2216         if (CVAL(b, 0) == 0xFE) {
2217                 read_buf(f, b, 2);
2218                 if (CVAL(b, 0) & 0x80) {
2219                         b[3] = CVAL(b, 0) & ~0x80;
2220                         b[0] = b[1];
2221                         read_buf(f, b+1, 2);
2222                         num = IVAL(b, 0);
2223                 } else
2224                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2225         } else
2226                 num = UVAL(b, 0) + *prev_ptr;
2227         *prev_ptr = num;
2228         if (prev_ptr == &prev_negative)
2229                 num = -num;
2230         return num;
2231 }
2232
2233 /* Read a line of up to bufsiz-1 characters into buf.  Strips
2234  * the (required) trailing newline and all carriage returns.
2235  * Returns 1 for success; 0 for I/O error or truncation. */
2236 int read_line_old(int fd, char *buf, size_t bufsiz, int eof_ok)
2237 {
2238         assert(fd != iobuf.in_fd);
2239         bufsiz--; /* leave room for the null */
2240         while (bufsiz > 0) {
2241                 if (safe_read(fd, buf, 1) == 0) {
2242                         if (eof_ok)
2243                                 break;
2244                         return 0;
2245                 }
2246                 if (*buf == '\0')
2247                         return 0;
2248                 if (*buf == '\n')
2249                         break;
2250                 if (*buf != '\r') {
2251                         buf++;
2252                         bufsiz--;
2253                 }
2254         }
2255         *buf = '\0';
2256         return bufsiz > 0;
2257 }
2258
2259 void io_printf(int fd, const char *format, ...)
2260 {
2261         va_list ap;
2262         char buf[BIGPATHBUFLEN];
2263         int len;
2264
2265         va_start(ap, format);
2266         len = vsnprintf(buf, sizeof buf, format, ap);
2267         va_end(ap);
2268
2269         if (len < 0)
2270                 exit_cleanup(RERR_PROTOCOL);
2271
2272         if (len > (int)sizeof buf) {
2273                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2274                 exit_cleanup(RERR_PROTOCOL);
2275         }
2276
2277         write_sbuf(fd, buf);
2278 }
2279
2280 /* Setup for multiplexing a MSG_* stream with the data stream. */
2281 void io_start_multiplex_out(int fd)
2282 {
2283         io_flush(FULL_FLUSH);
2284
2285         if (msgs2stderr && DEBUG_GTE(IO, 2))
2286                 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2287
2288         if (!iobuf.msg.buf)
2289                 alloc_xbuf(&iobuf.msg, ROUND_UP_1024(IO_BUFFER_SIZE));
2290
2291         iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2292         io_start_buffering_out(fd);
2293         got_kill_signal = 0;
2294
2295         iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2296         iobuf.out.len += 4;
2297 }
2298
2299 /* Setup for multiplexing a MSG_* stream with the data stream. */
2300 void io_start_multiplex_in(int fd)
2301 {
2302         if (msgs2stderr && DEBUG_GTE(IO, 2))
2303                 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2304
2305         iobuf.in_multiplexed = 1; /* See also IN_MULTIPLEXED */
2306         io_start_buffering_in(fd);
2307 }
2308
2309 int io_end_multiplex_in(int mode)
2310 {
2311         int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2312
2313         if (msgs2stderr && DEBUG_GTE(IO, 2))
2314                 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2315
2316         iobuf.in_multiplexed = 0;
2317         if (mode == MPLX_SWITCHING)
2318                 iobuf.raw_input_ends_before = 0;
2319         else
2320                 assert(iobuf.raw_input_ends_before == 0);
2321         if (mode != MPLX_TO_BUFFERED)
2322                 io_end_buffering_in(mode);
2323
2324         return ret;
2325 }
2326
2327 int io_end_multiplex_out(int mode)
2328 {
2329         int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2330
2331         if (msgs2stderr && DEBUG_GTE(IO, 2))
2332                 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2333
2334         if (mode != MPLX_TO_BUFFERED)
2335                 io_end_buffering_out(mode);
2336         else
2337                 io_flush(FULL_FLUSH);
2338
2339         iobuf.out.len = 0;
2340         iobuf.out_empty_len = 0;
2341         if (got_kill_signal > 0) /* Just in case... */
2342                 exit_cleanup(RERR_SIGNAL);
2343         got_kill_signal = -1;
2344
2345         return ret;
2346 }
2347
2348 void start_write_batch(int fd)
2349 {
2350         /* Some communication has already taken place, but we don't
2351          * enable batch writing until here so that we can write a
2352          * canonical record of the communication even though the
2353          * actual communication so far depends on whether a daemon
2354          * is involved. */
2355         write_int(batch_fd, protocol_version);
2356         if (protocol_version >= 30)
2357                 write_byte(batch_fd, compat_flags);
2358         write_int(batch_fd, checksum_seed);
2359
2360         if (am_sender)
2361                 write_batch_monitor_out = fd;
2362         else
2363                 write_batch_monitor_in = fd;
2364 }
2365
2366 void stop_write_batch(void)
2367 {
2368         write_batch_monitor_out = -1;
2369         write_batch_monitor_in = -1;
2370 }