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