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