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