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