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