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