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