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