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