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