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