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