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