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