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