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