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