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