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