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