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