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