Tweaked sizing checks in perform_io().
[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 + needed > iobuf.out.size
545                                 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 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.msg.len + needed > iobuf.msg.size
561                                 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 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                         /* Note that iobuf.out_empty_len doesn't factor into this check
582                          * because iobuf.out.len already holds any needed header len. */
583                         if (iobuf.out.len + needed <= iobuf.out.size)
584                                 goto double_break;
585                         break;
586                 case PIO_NEED_MSGROOM:
587                         if (iobuf.msg.len + needed <= iobuf.msg.size)
588                                 goto double_break;
589                         break;
590                 }
591
592                 max_fd = -1;
593
594                 FD_ZERO(&r_fds);
595                 FD_ZERO(&e_fds);
596                 if (iobuf.in_fd >= 0 && iobuf.in.size - (iobuf.in.pos + iobuf.in.len)) {
597                         if (!read_batch || batch_fd >= 0) {
598                                 FD_SET(iobuf.in_fd, &r_fds);
599                                 FD_SET(iobuf.in_fd, &e_fds);
600                         }
601                         if (iobuf.in_fd > max_fd)
602                                 max_fd = iobuf.in_fd;
603                 }
604
605                 /* Only do more filesfrom processing if there is enough room in the out buffer. */
606                 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
607                         FD_SET(ff_forward_fd, &r_fds);
608                         if (ff_forward_fd > max_fd)
609                                 max_fd = ff_forward_fd;
610                 }
611
612                 FD_ZERO(&w_fds);
613                 if (iobuf.out_fd >= 0) {
614                         if (iobuf.raw_flushing_ends_before
615                          || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
616                                 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
617                                         size_t val;
618
619                                         /* The iobuf.raw_flushing_ends_before value can point off the end
620                                          * of the iobuf.out buffer for a while, for easier subtracting. */
621                                         iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
622
623                                         SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
624                                               ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
625                                         if ((val = iobuf.out.size - iobuf.raw_data_header_pos) < 4) {
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(), (int)val);
630                                                 }
631                                                 memcpy(iobuf.out.buf, iobuf.out.buf + iobuf.out.size, 4 - val);
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                                 rprintf(FERROR, "error in perform_io: no fd for input.\n");
666                                 exit_cleanup(RERR_PROTOCOL);
667                         case PIO_NEED_OUTROOM:
668                         case PIO_NEED_MSGROOM:
669                                 msgs2stderr = 1;
670                                 rprintf(FERROR, "error in perform_io: no fd for output.\n");
671                                 exit_cleanup(RERR_PROTOCOL);
672                         default:
673                                 /* No stated needs, so I guess this is OK. */
674                                 break;
675                         }
676                         break;
677                 }
678
679                 if (extra_flist_sending_enabled) {
680                         if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD
681                          && file_total - file_old_total >= MIN_FILECNT_LOOKAHEAD)
682                                 tv.tv_sec = 0;
683                         else {
684                                 extra_flist_sending_enabled = False;
685                                 tv.tv_sec = select_timeout;
686                         }
687                 } else
688                         tv.tv_sec = select_timeout;
689                 tv.tv_usec = 0;
690
691                 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
692
693                 if (cnt <= 0) {
694                         if (cnt < 0 && errno == EBADF) {
695                                 msgs2stderr = 1;
696                                 exit_cleanup(RERR_SOCKETIO);
697                         }
698                         if (extra_flist_sending_enabled) {
699                                 extra_flist_sending_enabled = False;
700                                 send_extra_file_list(sock_f_out, -1);
701                                 extra_flist_sending_enabled = !flist_eof;
702                         } else
703                                 check_timeout();
704                         FD_ZERO(&r_fds); /* Just in case... */
705                         FD_ZERO(&w_fds);
706                 }
707
708                 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
709                         size_t pos = iobuf.in.pos + iobuf.in.len;
710                         size_t len = iobuf.in.size - pos;
711                         int n;
712                         if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
713                                 if (n == 0) {
714                                         if (!read_batch || batch_fd < 0 || am_generator)
715                                                 whine_about_eof(iobuf.in_fd); /* Doesn't return. */
716                                         batch_fd = -1;
717                                         continue;
718                                 }
719                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
720                                         n = 0;
721                                 else {
722                                         /* Don't write errors on a dead socket. */
723                                         if (iobuf.in_fd == sock_f_in) {
724                                                 if (am_sender)
725                                                         msgs2stderr = 1;
726                                                 rsyserr(FERROR_SOCKET, errno, "read error");
727                                         } else
728                                                 rsyserr(FERROR, errno, "read error");
729                                         exit_cleanup(RERR_STREAMIO);
730                                 }
731                         }
732                         if (msgs2stderr && DEBUG_GTE(IO, 2))
733                                 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
734
735                         if (io_timeout)
736                                 last_io_in = time(NULL);
737                         stats.total_read += n;
738
739                         iobuf.in.len += n;
740                 }
741
742                 if (iobuf.out_fd >= 0 && FD_ISSET(iobuf.out_fd, &w_fds)) {
743                         size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
744                         int n;
745
746                         if (bwlimit_writemax && len > bwlimit_writemax)
747                                 len = bwlimit_writemax;
748
749                         if (out->pos + len > out->size)
750                                 len = out->size - out->pos;
751                         if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
752                                 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
753                                         n = 0;
754                                 else {
755                                         /* Don't write errors on a dead socket. */
756                                         msgs2stderr = 1;
757                                         out->len = iobuf.raw_flushing_ends_before = out->pos = 0;
758                                         rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
759                                         exit_cleanup(RERR_STREAMIO);
760                                 }
761                         }
762                         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
763                                 rprintf(FINFO, "[%s] %s sent=%ld\n",
764                                         who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
765                         }
766
767                         if (io_timeout)
768                                 last_io_out = time(NULL);
769                         stats.total_written += n;
770
771                         if (bwlimit_writemax)
772                                 sleep_for_bwlimit(n);
773
774                         if ((out->pos += n) == out->size) {
775                                 if (iobuf.raw_flushing_ends_before)
776                                         iobuf.raw_flushing_ends_before -= out->size;
777                                 out->pos = 0;
778                         }
779                         if (out->pos == iobuf.raw_flushing_ends_before)
780                                 iobuf.raw_flushing_ends_before = 0;
781                         if ((out->len -= n) == empty_buf_len) {
782                                 out->pos = 0;
783                                 if (empty_buf_len)
784                                         iobuf.raw_data_header_pos = 0;
785                         }
786                 }
787
788                 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
789                         /* This can potentially flush all output and enable
790                          * multiplexed output, so keep this last in the loop
791                          * and be sure to not cache anything that would break
792                          * such a change. */
793                         forward_filesfrom_data();
794                 }
795         }
796   double_break:
797
798         data = iobuf.in.buf + iobuf.in.pos;
799
800         if (flags & PIO_CONSUME_INPUT) {
801                 iobuf.in.len -= needed;
802                 iobuf.in.pos += needed;
803         }
804
805         return data;
806 }
807
808 void noop_io_until_death(void)
809 {
810         char buf[1024];
811
812         kluge_around_eof = 1;
813         set_io_timeout(protocol_version >= 31 ? 10 : 1);
814
815         while (1)
816                 read_buf(iobuf.in_fd, buf, sizeof buf);
817 }
818
819 /* Buffer a message for the multiplexed output stream.  Is never used for MSG_DATA. */
820 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
821 {
822         char *hdr;
823         size_t pos;
824         BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
825
826         if (!OUT_MULTIPLEXED)
827                 return 0;
828
829         if (want_debug)
830                 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
831
832 #ifdef ICONV_OPTION
833         if (convert > 0 && ic_send == (iconv_t)-1)
834                 convert = 0;
835         if (convert > 0) {
836                 /* Ensuring double-size room leaves space for a potential conversion. */
837                 if (iobuf.msg.len + len*2 + 4 > iobuf.msg.size)
838                         perform_io(len*2 + 4, PIO_NEED_MSGROOM);
839         } else
840 #endif
841         if (iobuf.msg.len + len + 4 > iobuf.msg.size)
842                 perform_io(len + 4, PIO_NEED_MSGROOM);
843
844         pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
845         if (pos >= iobuf.msg.size)
846                 pos -= iobuf.msg.size;
847         hdr = iobuf.msg.buf + pos;
848
849         iobuf.msg.len += 4; /* Leave room for the coming header bytes. */
850
851 #ifdef ICONV_OPTION
852         if (convert > 0) {
853                 xbuf inbuf;
854
855                 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
856
857                 len = iobuf.msg.len;
858                 iconvbufs(ic_send, &inbuf, &iobuf.msg,
859                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
860                 if (inbuf.len > 0) {
861                         rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
862                         exit_cleanup(RERR_UNSUPPORTED);
863                 }
864                 len = iobuf.msg.len - len;
865         } else
866 #endif
867         {
868                 size_t siz;
869
870                 if ((pos += 4) >= iobuf.msg.size)
871                         pos -= iobuf.msg.size;
872
873                 /* Handle a split copy if we wrap around the end of the circular buffer. */
874                 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
875                         memcpy(iobuf.msg.buf + pos, buf, siz);
876                         memcpy(iobuf.msg.buf, buf + siz, len - siz);
877                 } else
878                         memcpy(iobuf.msg.buf + pos, buf, len);
879
880                 iobuf.msg.len += len;
881         }
882
883         SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
884         /* If the header used any overflow bytes, move them to the start. */
885         if ((pos = hdr+4 - iobuf.msg.buf) > iobuf.msg.size) {
886                 size_t siz = pos - iobuf.msg.size;
887                 if (DEBUG_GTE(IO, 4))
888                         rprintf(FINFO, "[%s] wrap-bytes moved: %d (send_msg)\n", who_am_i(), (int)siz);
889                 memcpy(iobuf.msg.buf, hdr+4 - siz, siz);
890         }
891
892         if (want_debug && convert > 0)
893                 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
894
895         return 1;
896 }
897
898 void send_msg_int(enum msgcode code, int num)
899 {
900         char numbuf[4];
901
902         if (DEBUG_GTE(IO, 1))
903                 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
904
905         SIVAL(numbuf, 0, num);
906         send_msg(code, numbuf, 4, -1);
907 }
908
909 static void got_flist_entry_status(enum festatus status, int ndx)
910 {
911         struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
912
913         if (remove_source_files) {
914                 active_filecnt--;
915                 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
916         }
917
918         if (inc_recurse)
919                 flist->in_progress--;
920
921         switch (status) {
922         case FES_SUCCESS:
923                 if (remove_source_files)
924                         send_msg_int(MSG_SUCCESS, ndx);
925                 if (preserve_hard_links) {
926                         struct file_struct *file = flist->files[ndx - flist->ndx_start];
927                         if (F_IS_HLINKED(file)) {
928                                 flist_ndx_push(&hlink_list, ndx);
929                                 flist->in_progress++;
930                         }
931                 }
932                 break;
933         case FES_REDO:
934                 if (read_batch) {
935                         if (inc_recurse)
936                                 flist->in_progress++;
937                         break;
938                 }
939                 if (inc_recurse)
940                         flist->to_redo++;
941                 flist_ndx_push(&redo_list, ndx);
942                 break;
943         case FES_NO_SEND:
944                 break;
945         }
946 }
947
948 /* Note the fds used for the main socket (which might really be a pipe
949  * for a local transfer, but we can ignore that). */
950 void io_set_sock_fds(int f_in, int f_out)
951 {
952         sock_f_in = f_in;
953         sock_f_out = f_out;
954 }
955
956 void set_io_timeout(int secs)
957 {
958         io_timeout = secs;
959
960         if (!io_timeout || io_timeout > SELECT_TIMEOUT)
961                 select_timeout = SELECT_TIMEOUT;
962         else
963                 select_timeout = io_timeout;
964
965         allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
966 }
967
968 static void check_for_d_option_error(const char *msg)
969 {
970         static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
971         char *colon;
972         int saw_d = 0;
973
974         if (*msg != 'r'
975          || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
976                 return;
977
978         msg += sizeof REMOTE_OPTION_ERROR - 1;
979         if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
980          || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
981                 return;
982
983         for ( ; *msg != ':'; msg++) {
984                 if (*msg == 'd')
985                         saw_d = 1;
986                 else if (*msg == 'e')
987                         break;
988                 else if (strchr(rsync263_opts, *msg) == NULL)
989                         return;
990         }
991
992         if (saw_d) {
993                 rprintf(FWARNING,
994                     "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
995         }
996 }
997
998 /* This is used by the generator to limit how many file transfers can
999  * be active at once when --remove-source-files is specified.  Without
1000  * this, sender-side deletions were mostly happening at the end. */
1001 void increment_active_files(int ndx, int itemizing, enum logcode code)
1002 {
1003         while (1) {
1004                 /* TODO: tune these limits? */
1005                 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1006                 if (active_filecnt < limit)
1007                         break;
1008                 check_for_finished_files(itemizing, code, 0);
1009                 if (active_filecnt < limit)
1010                         break;
1011                 wait_for_receiver();
1012         }
1013
1014         active_filecnt++;
1015         active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1016 }
1017
1018 int get_redo_num(void)
1019 {
1020         return flist_ndx_pop(&redo_list);
1021 }
1022
1023 int get_hlink_num(void)
1024 {
1025         return flist_ndx_pop(&hlink_list);
1026 }
1027
1028 /* When we're the receiver and we have a local --files-from list of names
1029  * that needs to be sent over the socket to the sender, we have to do two
1030  * things at the same time: send the sender a list of what files we're
1031  * processing and read the incoming file+info list from the sender.  We do
1032  * this by making recv_file_list() call forward_filesfrom_data(), which
1033  * will ensure that we forward data to the sender until we get some data
1034  * for recv_file_list() to use. */
1035 void start_filesfrom_forwarding(int fd)
1036 {
1037         if (protocol_version < 31 && OUT_MULTIPLEXED) {
1038                 /* Older protocols send the files-from data w/o packaging
1039                  * it in multiplexed I/O packets, so temporarily switch
1040                  * to buffered I/O to match this behavior. */
1041                 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1042                 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1043         }
1044         ff_forward_fd = fd;
1045
1046         alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1047 }
1048
1049 /* Read a line into the "buf" buffer. */
1050 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1051 {
1052         char ch, *s, *eob;
1053
1054 #ifdef ICONV_OPTION
1055         if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1056                 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1057 #endif
1058
1059   start:
1060 #ifdef ICONV_OPTION
1061         s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1062 #else
1063         s = buf;
1064 #endif
1065         eob = s + bufsiz - 1;
1066         while (1) {
1067                 /* We avoid read_byte() for files because files can return an EOF. */
1068                 if (fd == iobuf.in_fd)
1069                         ch = read_byte(fd);
1070                 else if (safe_read(fd, &ch, 1) == 0)
1071                         break;
1072                 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1073                         /* Skip empty lines if dumping comments. */
1074                         if (flags & RL_DUMP_COMMENTS && s == buf)
1075                                 continue;
1076                         break;
1077                 }
1078                 if (s < eob)
1079                         *s++ = ch;
1080         }
1081         *s = '\0';
1082
1083         if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1084                 goto start;
1085
1086 #ifdef ICONV_OPTION
1087         if (flags & RL_CONVERT) {
1088                 xbuf outbuf;
1089                 INIT_XBUF(outbuf, buf, 0, bufsiz);
1090                 iconv_buf.pos = 0;
1091                 iconv_buf.len = s - iconv_buf.buf;
1092                 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1093                           ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1094                 outbuf.buf[outbuf.len] = '\0';
1095                 return outbuf.len;
1096         }
1097 #endif
1098
1099         return s - buf;
1100 }
1101
1102 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1103                char ***argv_p, int *argc_p, char **request_p)
1104 {
1105         int maxargs = MAX_ARGS;
1106         int dot_pos = 0;
1107         int argc = 0;
1108         char **argv, *p;
1109         int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1110
1111 #ifdef ICONV_OPTION
1112         rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1113 #endif
1114
1115         if (!(argv = new_array(char *, maxargs)))
1116                 out_of_memory("read_args");
1117         if (mod_name && !protect_args)
1118                 argv[argc++] = "rsyncd";
1119
1120         while (1) {
1121                 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1122                         break;
1123
1124                 if (argc == maxargs-1) {
1125                         maxargs += MAX_ARGS;
1126                         if (!(argv = realloc_array(argv, char *, maxargs)))
1127                                 out_of_memory("read_args");
1128                 }
1129
1130                 if (dot_pos) {
1131                         if (request_p) {
1132                                 *request_p = strdup(buf);
1133                                 request_p = NULL;
1134                         }
1135                         if (mod_name)
1136                                 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1137                         else
1138                                 glob_expand(buf, &argv, &argc, &maxargs);
1139                 } else {
1140                         if (!(p = strdup(buf)))
1141                                 out_of_memory("read_args");
1142                         argv[argc++] = p;
1143                         if (*p == '.' && p[1] == '\0')
1144                                 dot_pos = argc;
1145                 }
1146         }
1147         argv[argc] = NULL;
1148
1149         glob_expand(NULL, NULL, NULL, NULL);
1150
1151         *argc_p = argc;
1152         *argv_p = argv;
1153 }
1154
1155 BOOL io_start_buffering_out(int f_out)
1156 {
1157         if (msgs2stderr && DEBUG_GTE(IO, 2))
1158                 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1159
1160         if (OUT_MULTIPLEXED && !iobuf.msg.buf) {
1161                 iobuf.msg.size = IO_BUFFER_SIZE - 4;
1162                 if (!(iobuf.msg.buf = new_array(char, iobuf.msg.size + 4)))
1163                         out_of_memory("io_start_buffering_out");
1164                 iobuf.msg.pos = iobuf.msg.len = 0;
1165         }
1166
1167         if (iobuf.out.buf) {
1168                 if (iobuf.out_fd == -1)
1169                         iobuf.out_fd = f_out;
1170                 assert(f_out == iobuf.out_fd);
1171                 return False;
1172         }
1173
1174         iobuf.out.size = IO_BUFFER_SIZE * 2 - 4;
1175         /* The 4 overflow bytes makes some circular-buffer wrapping operations easier. */
1176         if (!(iobuf.out.buf = new_array(char, iobuf.out.size + 4)))
1177                 out_of_memory("io_start_buffering_out");
1178         iobuf.out.pos = iobuf.out.len = 0;
1179         iobuf.out_fd = f_out;
1180
1181         return True;
1182 }
1183
1184 BOOL io_start_buffering_in(int f_in)
1185 {
1186         if (msgs2stderr && DEBUG_GTE(IO, 2))
1187                 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1188
1189         if (iobuf.in.buf) {
1190                 if (iobuf.in_fd == -1)
1191                         iobuf.in_fd = f_in;
1192                 assert(f_in == iobuf.in_fd);
1193                 return False;
1194         }
1195
1196         iobuf.in.size = IO_BUFFER_SIZE;
1197         if (!(iobuf.in.buf = new_array(char, iobuf.in.size)))
1198                 out_of_memory("io_start_buffering_in");
1199
1200         iobuf.in.pos = iobuf.in.len = 0;
1201
1202         iobuf.in_fd = f_in;
1203
1204         return True;
1205 }
1206
1207 void io_end_buffering_in(BOOL free_buffers)
1208 {
1209         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1210                 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1211                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1212         }
1213
1214         if (free_buffers)
1215                 free_xbuf(&iobuf.in);
1216         else
1217                 iobuf.in.pos = iobuf.in.len = 0;
1218
1219         iobuf.in_fd = -1;
1220 }
1221
1222 void io_end_buffering_out(BOOL free_buffers)
1223 {
1224         if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1225                 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1226                         who_am_i(), free_buffers ? "FREE" : "KEEP");
1227         }
1228
1229         io_flush(FULL_FLUSH);
1230
1231         if (free_buffers) {
1232                 free_xbuf(&iobuf.out);
1233                 free_xbuf(&iobuf.msg);
1234         }
1235
1236         iobuf.out_fd = -1;
1237 }
1238
1239 void maybe_flush_socket(int important)
1240 {
1241         if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1242          && (important || time(NULL) - last_io_out >= 5))
1243                 io_flush(NORMAL_FLUSH);
1244 }
1245
1246 void maybe_send_keepalive(void)
1247 {
1248         if (time(NULL) - last_io_out >= allowed_lull) {
1249                 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1250                         if (protocol_version < 29)
1251                                 return; /* there's nothing we can do */
1252                         if (protocol_version >= 30)
1253                                 send_msg(MSG_NOOP, "", 0, 0);
1254                         else {
1255                                 write_int(iobuf.out_fd, cur_flist->used);
1256                                 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1257                         }
1258                 }
1259                 if (iobuf.msg.len)
1260                         perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1261                 else if (iobuf.out.len > iobuf.out_empty_len)
1262                         io_flush(NORMAL_FLUSH);
1263         }
1264 }
1265
1266 void start_flist_forward(int ndx)
1267 {
1268         write_int(iobuf.out_fd, ndx);
1269         forward_flist_data = 1;
1270 }
1271
1272 void stop_flist_forward(void)
1273 {
1274         forward_flist_data = 0;
1275 }
1276
1277 /* Read a message from a multiplexed source. */
1278 static void read_a_msg(void)
1279 {
1280         char *data, line[BIGPATHBUFLEN];
1281         int tag, val;
1282         size_t msg_bytes;
1283
1284         data = perform_io(4, PIO_INPUT_AND_CONSUME);
1285         tag = IVAL(data, 0);
1286
1287         msg_bytes = tag & 0xFFFFFF;
1288         tag = (tag >> 24) - MPLEX_BASE;
1289
1290         if (DEBUG_GTE(IO, 1) && (msgs2stderr || tag != MSG_INFO))
1291                 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1292
1293         switch (tag) {
1294         case MSG_DATA:
1295                 assert(iobuf.raw_input_ends_before == 0);
1296                 /* Though this does not yet read the data, we do mark where in
1297                  * the buffer the msg data will end once it is read.  It is
1298                  * possible that this points off the end of the buffer, in
1299                  * which case the gradual reading of the input stream will
1300                  * cause this value to decrease and eventually become real. */
1301                 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1302                 break;
1303         case MSG_STATS:
1304                 if (msg_bytes != sizeof stats.total_read || !am_generator)
1305                         goto invalid_msg;
1306                 data = perform_io(sizeof stats.total_read, PIO_INPUT_AND_CONSUME);
1307                 memcpy((char*)&stats.total_read, data, sizeof stats.total_read);
1308                 break;
1309         case MSG_REDO:
1310                 if (msg_bytes != 4 || !am_generator)
1311                         goto invalid_msg;
1312                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1313                 got_flist_entry_status(FES_REDO, IVAL(data, 0));
1314                 break;
1315         case MSG_IO_ERROR:
1316                 if (msg_bytes != 4 || am_sender)
1317                         goto invalid_msg;
1318                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1319                 io_error |= IVAL(data, 0);
1320                 if (!am_generator)
1321                         send_msg(MSG_IO_ERROR, data, 4, 0);
1322                 break;
1323         case MSG_IO_TIMEOUT:
1324                 if (msg_bytes != 4 || am_server || am_generator)
1325                         goto invalid_msg;
1326                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1327                 val = IVAL(data, 0);
1328                 if (!io_timeout || io_timeout > val) {
1329                         if (INFO_GTE(MISC, 2))
1330                                 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1331                         set_io_timeout(val);
1332                 }
1333                 break;
1334         case MSG_NOOP:
1335                 if (am_sender)
1336                         maybe_send_keepalive();
1337                 break;
1338         case MSG_DELETED:
1339                 if (msg_bytes >= sizeof line)
1340                         goto overflow;
1341                 if (am_generator) {
1342                         memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1343                         send_msg(MSG_DELETED, line, msg_bytes, 1);
1344                         break;
1345                 }
1346 #ifdef ICONV_OPTION
1347                 if (ic_recv != (iconv_t)-1) {
1348                         xbuf outbuf, inbuf;
1349                         char ibuf[512];
1350                         int add_null = 0;
1351                         int flags = ICB_INCLUDE_BAD | ICB_INIT;
1352
1353                         INIT_CONST_XBUF(outbuf, line);
1354                         INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1355
1356                         while (msg_bytes) {
1357                                 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1358                                 memcpy(ibuf + inbuf.len, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1359                                 inbuf.pos = 0;
1360                                 inbuf.len += len;
1361                                 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1362                                         inbuf.len--, add_null = 1;
1363                                 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1364                                         if (errno == E2BIG)
1365                                                 goto overflow;
1366                                         /* Buffer ended with an incomplete char, so move the
1367                                          * bytes to the start of the buffer and continue. */
1368                                         memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1369                                 }
1370                                 flags &= ~ICB_INIT;
1371                         }
1372                         if (add_null) {
1373                                 if (outbuf.len == outbuf.size)
1374                                         goto overflow;
1375                                 outbuf.buf[outbuf.len++] = '\0';
1376                         }
1377                         msg_bytes = outbuf.len;
1378                 } else
1379 #endif
1380                         memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1381                 /* A directory name was sent with the trailing null */
1382                 if (msg_bytes > 0 && !line[msg_bytes-1])
1383                         log_delete(line, S_IFDIR);
1384                 else {
1385                         line[msg_bytes] = '\0';
1386                         log_delete(line, S_IFREG);
1387                 }
1388                 break;
1389         case MSG_SUCCESS:
1390                 if (msg_bytes != 4) {
1391                   invalid_msg:
1392                         rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1393                                 tag, (unsigned long)msg_bytes, who_am_i(),
1394                                 inc_recurse ? "/inc" : "");
1395                         exit_cleanup(RERR_STREAMIO);
1396                 }
1397                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1398                 if (am_generator)
1399                         got_flist_entry_status(FES_SUCCESS, IVAL(data, 0));
1400                 else
1401                         successful_send(IVAL(data, 0));
1402                 break;
1403         case MSG_NO_SEND:
1404                 if (msg_bytes != 4)
1405                         goto invalid_msg;
1406                 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1407                 if (am_generator)
1408                         got_flist_entry_status(FES_NO_SEND, IVAL(data, 0));
1409                 else
1410                         send_msg(MSG_NO_SEND, data, 4, 0);
1411                 break;
1412         case MSG_ERROR_SOCKET:
1413         case MSG_ERROR_UTF8:
1414         case MSG_CLIENT:
1415         case MSG_LOG:
1416                 if (!am_generator)
1417                         goto invalid_msg;
1418                 if (tag == MSG_ERROR_SOCKET)
1419                         msgs2stderr = 1;
1420                 /* FALL THROUGH */
1421         case MSG_INFO:
1422         case MSG_ERROR:
1423         case MSG_ERROR_XFER:
1424         case MSG_WARNING:
1425                 if (msg_bytes >= sizeof line) {
1426                     overflow:
1427                         rprintf(FERROR,
1428                                 "multiplexing overflow %d:%lu [%s%s]\n",
1429                                 tag, (unsigned long)msg_bytes, who_am_i(),
1430                                 inc_recurse ? "/inc" : "");
1431                         exit_cleanup(RERR_STREAMIO);
1432                 }
1433                 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1434                 rwrite((enum logcode)tag, line, msg_bytes, !am_generator);
1435                 if (first_message) {
1436                         if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof line) {
1437                                 line[msg_bytes] = '\0';
1438                                 check_for_d_option_error(line);
1439                         }
1440                         first_message = 0;
1441                 }
1442                 break;
1443         case MSG_ERROR_EXIT:
1444                 if (msg_bytes == 0) {
1445                         if (!am_sender && !am_generator) {
1446                                 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1447                                 io_flush(FULL_FLUSH);
1448                         }
1449                         val = 0;
1450                 } else if (msg_bytes == 4) {
1451                         data = perform_io(4, PIO_INPUT_AND_CONSUME);
1452                         val = IVAL(data, 0);
1453                         if (protocol_version >= 31) {
1454                                 if (am_generator)
1455                                         send_msg_int(MSG_ERROR_EXIT, val);
1456                                 else
1457                                         send_msg(MSG_ERROR_EXIT, "", 0, 0);
1458                         }
1459                 } else
1460                         goto invalid_msg;
1461                 /* Send a negative linenum so that we don't end up
1462                  * with a duplicate exit message. */
1463                 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1464         default:
1465                 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1466                         tag, who_am_i(), inc_recurse ? "/inc" : "");
1467                 exit_cleanup(RERR_STREAMIO);
1468         }
1469 }
1470
1471 void wait_for_receiver(void)
1472 {
1473         if (!iobuf.raw_input_ends_before)
1474                 read_a_msg();
1475
1476         if (iobuf.raw_input_ends_before) {
1477                 int ndx = read_int(iobuf.in_fd);
1478                 if (ndx < 0) {
1479                         switch (ndx) {
1480                         case NDX_FLIST_EOF:
1481                                 flist_eof = 1;
1482                                 if (DEBUG_GTE(FLIST, 3))
1483                                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1484                                 break;
1485                         case NDX_DONE:
1486                                 msgdone_cnt++;
1487                                 break;
1488                         default:
1489                                 exit_cleanup(RERR_STREAMIO);
1490                         }
1491                 } else {
1492                         struct file_list *flist;
1493                         if (DEBUG_GTE(FLIST, 2)) {
1494                                 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1495                                         who_am_i(), ndx);
1496                         }
1497                         flist = recv_file_list(iobuf.in_fd);
1498                         flist->parent_ndx = ndx;
1499 #ifdef SUPPORT_HARD_LINKS
1500                         if (preserve_hard_links)
1501                                 match_hard_links(flist);
1502 #endif
1503                 }
1504         }
1505 }
1506
1507 unsigned short read_shortint(int f)
1508 {
1509         char b[2];
1510         read_buf(f, b, 2);
1511         return (UVAL(b, 1) << 8) + UVAL(b, 0);
1512 }
1513
1514 int32 read_int(int f)
1515 {
1516         char b[4];
1517         int32 num;
1518
1519         read_buf(f, b, 4);
1520         num = IVAL(b, 0);
1521 #if SIZEOF_INT32 > 4
1522         if (num & (int32)0x80000000)
1523                 num |= ~(int32)0xffffffff;
1524 #endif
1525         return num;
1526 }
1527
1528 int32 read_varint(int f)
1529 {
1530         union {
1531                 char b[5];
1532                 int32 x;
1533         } u;
1534         uchar ch;
1535         int extra;
1536
1537         u.x = 0;
1538         ch = read_byte(f);
1539         extra = int_byte_extra[ch / 4];
1540         if (extra) {
1541                 uchar bit = ((uchar)1<<(8-extra));
1542                 if (extra >= (int)sizeof u.b) {
1543                         rprintf(FERROR, "Overflow in read_varint()\n");
1544                         exit_cleanup(RERR_STREAMIO);
1545                 }
1546                 read_buf(f, u.b, extra);
1547                 u.b[extra] = ch & (bit-1);
1548         } else
1549                 u.b[0] = ch;
1550 #if CAREFUL_ALIGNMENT
1551         u.x = IVAL(u.b,0);
1552 #endif
1553 #if SIZEOF_INT32 > 4
1554         if (u.x & (int32)0x80000000)
1555                 u.x |= ~(int32)0xffffffff;
1556 #endif
1557         return u.x;
1558 }
1559
1560 int64 read_varlong(int f, uchar min_bytes)
1561 {
1562         union {
1563                 char b[9];
1564                 int64 x;
1565         } u;
1566         char b2[8];
1567         int extra;
1568
1569 #if SIZEOF_INT64 < 8
1570         memset(u.b, 0, 8);
1571 #else
1572         u.x = 0;
1573 #endif
1574         read_buf(f, b2, min_bytes);
1575         memcpy(u.b, b2+1, min_bytes-1);
1576         extra = int_byte_extra[CVAL(b2, 0) / 4];
1577         if (extra) {
1578                 uchar bit = ((uchar)1<<(8-extra));
1579                 if (min_bytes + extra > (int)sizeof u.b) {
1580                         rprintf(FERROR, "Overflow in read_varlong()\n");
1581                         exit_cleanup(RERR_STREAMIO);
1582                 }
1583                 read_buf(f, u.b + min_bytes - 1, extra);
1584                 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1585 #if SIZEOF_INT64 < 8
1586                 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1587                         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1588                         exit_cleanup(RERR_UNSUPPORTED);
1589                 }
1590 #endif
1591         } else
1592                 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1593 #if SIZEOF_INT64 < 8
1594         u.x = IVAL(u.b,0);
1595 #elif CAREFUL_ALIGNMENT
1596         u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1597 #endif
1598         return u.x;
1599 }
1600
1601 int64 read_longint(int f)
1602 {
1603 #if SIZEOF_INT64 >= 8
1604         char b[9];
1605 #endif
1606         int32 num = read_int(f);
1607
1608         if (num != (int32)0xffffffff)
1609                 return num;
1610
1611 #if SIZEOF_INT64 < 8
1612         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1613         exit_cleanup(RERR_UNSUPPORTED);
1614 #else
1615         read_buf(f, b, 8);
1616         return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1617 #endif
1618 }
1619
1620 void read_buf(int f, char *buf, size_t len)
1621 {
1622         if (f != iobuf.in_fd) {
1623                 if (safe_read(f, buf, len) != len)
1624                         whine_about_eof(f); /* Doesn't return. */
1625                 goto batch_copy;
1626         }
1627
1628         if (!IN_MULTIPLEXED) {
1629                 memcpy(buf, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1630                 total_data_read += len;
1631                 if (forward_flist_data)
1632                         write_buf(iobuf.out_fd, buf, len);
1633           batch_copy:
1634                 if (f == write_batch_monitor_in)
1635                         safe_write(batch_fd, buf, len);
1636                 return;
1637         }
1638
1639         while (1) {
1640                 char *data;
1641                 size_t siz;
1642
1643                 while (!iobuf.raw_input_ends_before)
1644                         read_a_msg();
1645
1646                 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1647                 data = perform_io(siz, PIO_INPUT_AND_CONSUME);
1648                 if (iobuf.in.pos == iobuf.raw_input_ends_before)
1649                         iobuf.raw_input_ends_before = 0;
1650
1651                 /* The bytes at the "data" pointer will survive long
1652                  * enough to make a copy, but not past future I/O. */
1653                 memcpy(buf, data, siz);
1654                 total_data_read += siz;
1655
1656                 if (forward_flist_data)
1657                         write_buf(iobuf.out_fd, buf, siz);
1658
1659                 if (f == write_batch_monitor_in)
1660                         safe_write(batch_fd, buf, siz);
1661
1662                 if ((len -= siz) == 0)
1663                         break;
1664                 buf += siz;
1665         }
1666 }
1667
1668 void read_sbuf(int f, char *buf, size_t len)
1669 {
1670         read_buf(f, buf, len);
1671         buf[len] = '\0';
1672 }
1673
1674 uchar read_byte(int f)
1675 {
1676         uchar c;
1677         read_buf(f, (char*)&c, 1);
1678         return c;
1679 }
1680
1681 int read_vstring(int f, char *buf, int bufsize)
1682 {
1683         int len = read_byte(f);
1684
1685         if (len & 0x80)
1686                 len = (len & ~0x80) * 0x100 + read_byte(f);
1687
1688         if (len >= bufsize) {
1689                 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1690                         len, bufsize - 1);
1691                 return -1;
1692         }
1693
1694         if (len)
1695                 read_buf(f, buf, len);
1696         buf[len] = '\0';
1697         return len;
1698 }
1699
1700 /* Populate a sum_struct with values from the socket.  This is
1701  * called by both the sender and the receiver. */
1702 void read_sum_head(int f, struct sum_struct *sum)
1703 {
1704         int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1705         sum->count = read_int(f);
1706         if (sum->count < 0) {
1707                 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1708                         (long)sum->count, who_am_i());
1709                 exit_cleanup(RERR_PROTOCOL);
1710         }
1711         sum->blength = read_int(f);
1712         if (sum->blength < 0 || sum->blength > max_blength) {
1713                 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1714                         (long)sum->blength, who_am_i());
1715                 exit_cleanup(RERR_PROTOCOL);
1716         }
1717         sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1718         if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1719                 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1720                         sum->s2length, who_am_i());
1721                 exit_cleanup(RERR_PROTOCOL);
1722         }
1723         sum->remainder = read_int(f);
1724         if (sum->remainder < 0 || sum->remainder > sum->blength) {
1725                 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1726                         (long)sum->remainder, who_am_i());
1727                 exit_cleanup(RERR_PROTOCOL);
1728         }
1729 }
1730
1731 /* Send the values from a sum_struct over the socket.  Set sum to
1732  * NULL if there are no checksums to send.  This is called by both
1733  * the generator and the sender. */
1734 void write_sum_head(int f, struct sum_struct *sum)
1735 {
1736         static struct sum_struct null_sum;
1737
1738         if (sum == NULL)
1739                 sum = &null_sum;
1740
1741         write_int(f, sum->count);
1742         write_int(f, sum->blength);
1743         if (protocol_version >= 27)
1744                 write_int(f, sum->s2length);
1745         write_int(f, sum->remainder);
1746 }
1747
1748 /* Sleep after writing to limit I/O bandwidth usage.
1749  *
1750  * @todo Rather than sleeping after each write, it might be better to
1751  * use some kind of averaging.  The current algorithm seems to always
1752  * use a bit less bandwidth than specified, because it doesn't make up
1753  * for slow periods.  But arguably this is a feature.  In addition, we
1754  * ought to take the time used to write the data into account.
1755  *
1756  * During some phases of big transfers (file FOO is uptodate) this is
1757  * called with a small bytes_written every time.  As the kernel has to
1758  * round small waits up to guarantee that we actually wait at least the
1759  * requested number of microseconds, this can become grossly inaccurate.
1760  * We therefore keep track of the bytes we've written over time and only
1761  * sleep when the accumulated delay is at least 1 tenth of a second. */
1762 static void sleep_for_bwlimit(int bytes_written)
1763 {
1764         static struct timeval prior_tv;
1765         static long total_written = 0;
1766         struct timeval tv, start_tv;
1767         long elapsed_usec, sleep_usec;
1768
1769 #define ONE_SEC 1000000L /* # of microseconds in a second */
1770
1771         total_written += bytes_written;
1772
1773         gettimeofday(&start_tv, NULL);
1774         if (prior_tv.tv_sec) {
1775                 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1776                              + (start_tv.tv_usec - prior_tv.tv_usec);
1777                 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1778                 if (total_written < 0)
1779                         total_written = 0;
1780         }
1781
1782         sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1783         if (sleep_usec < ONE_SEC / 10) {
1784                 prior_tv = start_tv;
1785                 return;
1786         }
1787
1788         tv.tv_sec  = sleep_usec / ONE_SEC;
1789         tv.tv_usec = sleep_usec % ONE_SEC;
1790         select(0, NULL, NULL, NULL, &tv);
1791
1792         gettimeofday(&prior_tv, NULL);
1793         elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1794                      + (prior_tv.tv_usec - start_tv.tv_usec);
1795         total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1796 }
1797
1798 void io_flush(int flush_it_all)
1799 {
1800         if (iobuf.out.len > iobuf.out_empty_len) {
1801                 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1802                         perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1803                 else /* NORMAL_FLUSH: flush at least 1 byte */
1804                         perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1805         }
1806         if (iobuf.msg.len)
1807                 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1808 }
1809
1810 void write_shortint(int f, unsigned short x)
1811 {
1812         char b[2];
1813         b[0] = (char)x;
1814         b[1] = (char)(x >> 8);
1815         write_buf(f, b, 2);
1816 }
1817
1818 void write_int(int f, int32 x)
1819 {
1820         char b[4];
1821         SIVAL(b, 0, x);
1822         write_buf(f, b, 4);
1823 }
1824
1825 void write_varint(int f, int32 x)
1826 {
1827         char b[5];
1828         uchar bit;
1829         int cnt = 4;
1830
1831         SIVAL(b, 1, x);
1832
1833         while (cnt > 1 && b[cnt] == 0)
1834                 cnt--;
1835         bit = ((uchar)1<<(7-cnt+1));
1836         if (CVAL(b, cnt) >= bit) {
1837                 cnt++;
1838                 *b = ~(bit-1);
1839         } else if (cnt > 1)
1840                 *b = b[cnt] | ~(bit*2-1);
1841         else
1842                 *b = b[cnt];
1843
1844         write_buf(f, b, cnt);
1845 }
1846
1847 void write_varlong(int f, int64 x, uchar min_bytes)
1848 {
1849         char b[9];
1850         uchar bit;
1851         int cnt = 8;
1852
1853         SIVAL(b, 1, x);
1854 #if SIZEOF_INT64 >= 8
1855         SIVAL(b, 5, x >> 32);
1856 #else
1857         if (x <= 0x7FFFFFFF && x >= 0)
1858                 memset(b + 5, 0, 4);
1859         else {
1860                 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1861                 exit_cleanup(RERR_UNSUPPORTED);
1862         }
1863 #endif
1864
1865         while (cnt > min_bytes && b[cnt] == 0)
1866                 cnt--;
1867         bit = ((uchar)1<<(7-cnt+min_bytes));
1868         if (CVAL(b, cnt) >= bit) {
1869                 cnt++;
1870                 *b = ~(bit-1);
1871         } else if (cnt > min_bytes)
1872                 *b = b[cnt] | ~(bit*2-1);
1873         else
1874                 *b = b[cnt];
1875
1876         write_buf(f, b, cnt);
1877 }
1878
1879 /*
1880  * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1881  * 64-bit types on this platform.
1882  */
1883 void write_longint(int f, int64 x)
1884 {
1885         char b[12], * const s = b+4;
1886
1887         SIVAL(s, 0, x);
1888         if (x <= 0x7FFFFFFF && x >= 0) {
1889                 write_buf(f, s, 4);
1890                 return;
1891         }
1892
1893 #if SIZEOF_INT64 < 8
1894         rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1895         exit_cleanup(RERR_UNSUPPORTED);
1896 #else
1897         memset(b, 0xFF, 4);
1898         SIVAL(s, 4, x >> 32);
1899         write_buf(f, b, 12);
1900 #endif
1901 }
1902
1903 void write_buf(int f, const char *buf, size_t len)
1904 {
1905         size_t pos, siz;
1906
1907         if (f != iobuf.out_fd) {
1908                 safe_write(f, buf, len);
1909                 goto batch_copy;
1910         }
1911
1912         if (iobuf.out.len + len > iobuf.out.size)
1913                 perform_io(len, PIO_NEED_OUTROOM);
1914
1915         pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
1916         if (pos >= iobuf.out.size)
1917                 pos -= iobuf.out.size;
1918
1919         /* Handle a split copy if we wrap around the end of the circular buffer. */
1920         if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
1921                 memcpy(iobuf.out.buf + pos, buf, siz);
1922                 memcpy(iobuf.out.buf, buf + siz, len - siz);
1923         } else
1924                 memcpy(iobuf.out.buf + pos, buf, len);
1925
1926         iobuf.out.len += len;
1927         total_data_written += len;
1928
1929   batch_copy:
1930         if (f == write_batch_monitor_out)
1931                 safe_write(batch_fd, buf, len);
1932 }
1933
1934 /* Write a string to the connection */
1935 void write_sbuf(int f, const char *buf)
1936 {
1937         write_buf(f, buf, strlen(buf));
1938 }
1939
1940 void write_byte(int f, uchar c)
1941 {
1942         write_buf(f, (char *)&c, 1);
1943 }
1944
1945 void write_vstring(int f, const char *str, int len)
1946 {
1947         uchar lenbuf[3], *lb = lenbuf;
1948
1949         if (len > 0x7F) {
1950                 if (len > 0x7FFF) {
1951                         rprintf(FERROR,
1952                                 "attempting to send over-long vstring (%d > %d)\n",
1953                                 len, 0x7FFF);
1954                         exit_cleanup(RERR_PROTOCOL);
1955                 }
1956                 *lb++ = len / 0x100 + 0x80;
1957         }
1958         *lb = len;
1959
1960         write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
1961         if (len)
1962                 write_buf(f, str, len);
1963 }
1964
1965 /* Send a file-list index using a byte-reduction method. */
1966 void write_ndx(int f, int32 ndx)
1967 {
1968         static int32 prev_positive = -1, prev_negative = 1;
1969         int32 diff, cnt = 0;
1970         char b[6];
1971
1972         if (protocol_version < 30 || read_batch) {
1973                 write_int(f, ndx);
1974                 return;
1975         }
1976
1977         /* Send NDX_DONE as a single-byte 0 with no side effects.  Send
1978          * negative nums as a positive after sending a leading 0xFF. */
1979         if (ndx >= 0) {
1980                 diff = ndx - prev_positive;
1981                 prev_positive = ndx;
1982         } else if (ndx == NDX_DONE) {
1983                 *b = 0;
1984                 write_buf(f, b, 1);
1985                 return;
1986         } else {
1987                 b[cnt++] = (char)0xFF;
1988                 ndx = -ndx;
1989                 diff = ndx - prev_negative;
1990                 prev_negative = ndx;
1991         }
1992
1993         /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1994          * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1995          * & all 4 bytes of the (non-negative) num with the high-bit set. */
1996         if (diff < 0xFE && diff > 0)
1997                 b[cnt++] = (char)diff;
1998         else if (diff < 0 || diff > 0x7FFF) {
1999                 b[cnt++] = (char)0xFE;
2000                 b[cnt++] = (char)((ndx >> 24) | 0x80);
2001                 b[cnt++] = (char)ndx;
2002                 b[cnt++] = (char)(ndx >> 8);
2003                 b[cnt++] = (char)(ndx >> 16);
2004         } else {
2005                 b[cnt++] = (char)0xFE;
2006                 b[cnt++] = (char)(diff >> 8);
2007                 b[cnt++] = (char)diff;
2008         }
2009         write_buf(f, b, cnt);
2010 }
2011
2012 /* Receive a file-list index using a byte-reduction method. */
2013 int32 read_ndx(int f)
2014 {
2015         static int32 prev_positive = -1, prev_negative = 1;
2016         int32 *prev_ptr, num;
2017         char b[4];
2018
2019         if (protocol_version < 30)
2020                 return read_int(f);
2021
2022         read_buf(f, b, 1);
2023         if (CVAL(b, 0) == 0xFF) {
2024                 read_buf(f, b, 1);
2025                 prev_ptr = &prev_negative;
2026         } else if (CVAL(b, 0) == 0)
2027                 return NDX_DONE;
2028         else
2029                 prev_ptr = &prev_positive;
2030         if (CVAL(b, 0) == 0xFE) {
2031                 read_buf(f, b, 2);
2032                 if (CVAL(b, 0) & 0x80) {
2033                         b[3] = CVAL(b, 0) & ~0x80;
2034                         b[0] = b[1];
2035                         read_buf(f, b+1, 2);
2036                         num = IVAL(b, 0);
2037                 } else
2038                         num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2039         } else
2040                 num = UVAL(b, 0) + *prev_ptr;
2041         *prev_ptr = num;
2042         if (prev_ptr == &prev_negative)
2043                 num = -num;
2044         return num;
2045 }
2046
2047 /* Read a line of up to bufsiz-1 characters into buf.  Strips
2048  * the (required) trailing newline and all carriage returns.
2049  * Returns 1 for success; 0 for I/O error or truncation. */
2050 int read_line_old(int fd, char *buf, size_t bufsiz)
2051 {
2052         bufsiz--; /* leave room for the null */
2053         while (bufsiz > 0) {
2054                 assert(fd != iobuf.in_fd);
2055                 if (safe_read(fd, buf, 1) == 0)
2056                         return 0;
2057                 if (*buf == '\0')
2058                         return 0;
2059                 if (*buf == '\n')
2060                         break;
2061                 if (*buf != '\r') {
2062                         buf++;
2063                         bufsiz--;
2064                 }
2065         }
2066         *buf = '\0';
2067         return bufsiz > 0;
2068 }
2069
2070 void io_printf(int fd, const char *format, ...)
2071 {
2072         va_list ap;
2073         char buf[BIGPATHBUFLEN];
2074         int len;
2075
2076         va_start(ap, format);
2077         len = vsnprintf(buf, sizeof buf, format, ap);
2078         va_end(ap);
2079
2080         if (len < 0)
2081                 exit_cleanup(RERR_STREAMIO);
2082
2083         if (len > (int)sizeof buf) {
2084                 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2085                 exit_cleanup(RERR_STREAMIO);
2086         }
2087
2088         write_sbuf(fd, buf);
2089 }
2090
2091 /* Setup for multiplexing a MSG_* stream with the data stream. */
2092 void io_start_multiplex_out(int fd)
2093 {
2094         io_flush(FULL_FLUSH);
2095
2096         if (msgs2stderr && DEBUG_GTE(IO, 2))
2097                 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2098
2099         iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2100         io_start_buffering_out(fd);
2101
2102         iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2103         iobuf.out.len += 4;
2104 }
2105
2106 /* Setup for multiplexing a MSG_* stream with the data stream. */
2107 void io_start_multiplex_in(int fd)
2108 {
2109         if (msgs2stderr && DEBUG_GTE(IO, 2))
2110                 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2111
2112         iobuf.in_multiplexed = True; /* See also IN_MULTIPLEXED */
2113         io_start_buffering_in(fd);
2114 }
2115
2116 int io_end_multiplex_in(int mode)
2117 {
2118         int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2119
2120         if (msgs2stderr && DEBUG_GTE(IO, 2))
2121                 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2122
2123         iobuf.in_multiplexed = False;
2124         if (mode == MPLX_SWITCHING)
2125                 iobuf.raw_input_ends_before = 0;
2126         else
2127                 assert(iobuf.raw_input_ends_before == 0);
2128         if (mode != MPLX_TO_BUFFERED)
2129                 io_end_buffering_in(mode);
2130
2131         return ret;
2132 }
2133
2134 int io_end_multiplex_out(int mode)
2135 {
2136         int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2137
2138         if (msgs2stderr && DEBUG_GTE(IO, 2))
2139                 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2140
2141         if (mode != MPLX_TO_BUFFERED)
2142                 io_end_buffering_out(mode);
2143         else
2144                 io_flush(FULL_FLUSH);
2145
2146         iobuf.out.len = 0;
2147         iobuf.out_empty_len = 0;
2148
2149         return ret;
2150 }
2151
2152 void start_write_batch(int fd)
2153 {
2154         /* Some communication has already taken place, but we don't
2155          * enable batch writing until here so that we can write a
2156          * canonical record of the communication even though the
2157          * actual communication so far depends on whether a daemon
2158          * is involved. */
2159         write_int(batch_fd, protocol_version);
2160         if (protocol_version >= 30)
2161                 write_byte(batch_fd, inc_recurse);
2162         write_int(batch_fd, checksum_seed);
2163
2164         if (am_sender)
2165                 write_batch_monitor_out = fd;
2166         else
2167                 write_batch_monitor_in = fd;
2168 }
2169
2170 void stop_write_batch(void)
2171 {
2172         write_batch_monitor_out = -1;
2173         write_batch_monitor_in = -1;
2174 }