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