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