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