2 * Socket and pipe I/O utilities used in rsync.
4 * Copyright (C) 1996-2001 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7 * Copyright (C) 2003-2009 Wayne Davison
9 * This program is free software; you can redistribute it and/or modify
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.
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.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
23 /* Rsync provides its own multiplexing system, which is used to send
24 * stderr and stdout over a single socket.
26 * For historical reasons this is off during the start of the
27 * connection, but it's switched on quite early using
28 * io_start_multiplex_out() and io_start_multiplex_in(). */
34 /** If no timeout is specified then use a 60 second select timeout */
35 #define SELECT_TIMEOUT 60
38 extern size_t bwlimit_writemax;
39 extern int io_timeout;
43 extern int am_generator;
44 extern int msgs2stderr;
45 extern int inc_recurse;
49 extern int file_total;
50 extern int file_old_total;
52 extern int read_batch;
53 extern int protect_args;
54 extern int checksum_seed;
55 extern int protocol_version;
56 extern int remove_source_files;
57 extern int preserve_hard_links;
58 extern BOOL extra_flist_sending_enabled;
59 extern struct stats stats;
60 extern struct file_list *cur_flist;
62 extern int filesfrom_convert;
63 extern iconv_t ic_send, ic_recv;
66 int csum_length = SHORT_SUM_LENGTH; /* initial value */
68 int ignore_timeout = 0;
71 int forward_flist_data = 0;
73 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
74 int kluge_around_eof = 0;
82 int out_fd; /* Both "out" and "msg" go to this fd. */
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 };
90 static time_t last_io_in;
91 static time_t last_io_out;
93 static int write_batch_monitor_in = -1;
94 static int write_batch_monitor_out = -1;
96 static int ff_forward_fd = -1;
97 static char ff_lastchar;
99 static xbuf iconv_buf = EMPTY_XBUF;
101 static int select_timeout = SELECT_TIMEOUT;
102 static int active_filecnt = 0;
103 static OFF_T active_bytecnt = 0;
104 static int first_message = 1;
106 static 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 */
113 #define IN_MULTIPLEXED (iobuf.in_multiplexed)
114 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
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)
120 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
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)
125 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
126 #define REMOTE_OPTION_ERROR2 ": unknown option"
128 #define FILESFROM_BUFLEN 2048
130 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
132 static flist_ndx_list redo_list, hlink_list;
134 static void sleep_for_bwlimit(int bytes_written);
136 static void check_timeout(void)
140 if (!io_timeout || ignore_timeout)
144 last_io_in = time(NULL);
150 if (t - last_io_in >= io_timeout) {
151 if (!am_server && !am_daemon) {
152 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
153 (int)(t-last_io_in));
155 exit_cleanup(RERR_TIMEOUT);
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.
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.
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. */
171 static NORETURN void whine_about_eof(int fd)
173 if (kluge_around_eof && fd == sock_f_in) {
175 if (kluge_around_eof > 0)
177 /* If we're still here after 10 seconds, exit with an error. */
178 for (i = 10*1000/20; i--; )
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());
186 exit_cleanup(RERR_STREAMIO);
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. */
193 static size_t safe_read(int fd, char *buf, size_t len)
198 assert(fd != iobuf.in_fd);
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);
207 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
209 rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
210 (long)len, who_am_i());
211 exit_cleanup(RERR_STREAMIO);
226 tv.tv_sec = select_timeout;
229 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
231 if (cnt < 0 && errno == EBADF) {
232 rsyserr(FERROR, errno, "safe_read select failed [%s]",
234 exit_cleanup(RERR_FILEIO);
240 /*if (FD_ISSET(fd, &e_fds))
241 rprintf(FINFO, "select exception on fd %d\n", fd); */
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);
254 if ((got += (size_t)n) == len)
262 static const char *what_fd_is(int fd)
266 if (fd == sock_f_out)
268 else if (fd == iobuf.out_fd)
270 else if (fd == batch_fd)
273 snprintf(buf, sizeof buf, "fd %d", fd);
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. */
281 static void safe_write(int fd, const char *buf, size_t len)
285 assert(fd != iobuf.out_fd);
287 n = write(fd, buf, len);
288 if ((size_t)n == len)
291 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
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);
310 tv.tv_sec = select_timeout;
313 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
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);
324 if (FD_ISSET(fd, &w_fds)) {
325 n = write(fd, buf, len);
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. */
339 static void forward_filesfrom_data(void)
341 char buf[FILESFROM_BUFLEN];
345 INIT_CONST_XBUF(x, buf);
347 len = read(ff_forward_fd, x.buf, x.size);
349 if (len == 0 || errno != EINTR) {
350 /* Send end-of-file marker */
351 write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
353 if (protocol_version < 31)
354 io_start_multiplex_out(iobuf.out_fd);
359 if (DEBUG_GTE(IO, 2))
360 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
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')
374 /* Last buf ended with a '\0', so don't let this buf start with one. */
375 while (len && *s == '\0')
380 char *f = x.buf + x.pos;
381 char *t = f; /* Keep any non-zero offset to avoid iconv reset. */
383 /* Eliminate any multi-'\0' runs. */
385 if (!(*t++ = *f++)) {
386 while (f != eob && !*f)
393 if (filesfrom_convert) {
394 /* TODO would it help to translate each string between nulls separately? */
396 iconvbufs(ic_send, &x, &iobuf.out, ICB_INCLUDE_BAD|ICB_INCLUDE_INCOMPLETE|ICB_CIRCULAR_OUT);
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);
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.
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.
424 * When writing, we flush data in the following priority order:
426 * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
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).
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).
435 * TODO: items for possible future work:
437 * - Make this routine able to read the generator-to-receiver batch flow?
439 * - Make the input buffer circular?
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. */
445 static char *perform_io(size_t needed, int flags)
447 fd_set r_fds, e_fds, w_fds;
450 size_t empty_buf_len = 0;
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;
460 switch (flags & PIO_NEED_FLAGS) {
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&" : "");
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)) {
474 rprintf(FINFO, "[%s] resized input buffer from %d to %d bytes.\n",
475 who_am_i(), iobuf.in.size, needed);
477 iobuf.in.size = needed;
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)) {
485 "[%s] moved %d bytes from %d to 0 in the input buffer (size=%d, needed=%d).\n",
486 who_am_i(), iobuf.in.len, iobuf.in.pos, iobuf.in.size, needed);
488 if (iobuf.raw_input_ends_before)
489 iobuf.raw_input_ends_before -= iobuf.in.pos;
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);
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);
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);
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);
527 if (DEBUG_GTE(IO, 3))
528 rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
532 exit_cleanup(RERR_UNSUPPORTED);
536 switch (flags & PIO_NEED_FLAGS) {
538 if (iobuf.in.len >= needed)
541 case PIO_NEED_OUTROOM:
542 if (iobuf.out.len <= iobuf.out.size - needed)
545 case PIO_NEED_MSGROOM:
546 if (iobuf.msg.len <= iobuf.msg.size - needed)
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);
560 if (iobuf.in_fd > max_fd)
561 max_fd = iobuf.in_fd;
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;
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) {
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;
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);
590 memcpy(iobuf.out.buf, iobuf.out.buf + iobuf.out.size, 4 - val);
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);
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;
605 empty_buf_len = iobuf.out_empty_len;
607 } else if (iobuf.msg.len) {
613 FD_SET(iobuf.out_fd, &w_fds);
614 if (iobuf.out_fd > max_fd)
615 max_fd = iobuf.out_fd;
621 switch (flags & PIO_NEED_FLAGS) {
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:
628 rprintf(FERROR, "error in perform_io: no fd for output.\n");
629 exit_cleanup(RERR_PROTOCOL);
631 /* No stated needs, so I guess this is OK. */
637 if (extra_flist_sending_enabled) {
638 if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD
639 && file_total - file_old_total >= MIN_FILECNT_LOOKAHEAD)
642 extra_flist_sending_enabled = False;
643 tv.tv_sec = select_timeout;
646 tv.tv_sec = select_timeout;
649 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
652 if (cnt < 0 && errno == EBADF) {
654 exit_cleanup(RERR_SOCKETIO);
656 if (extra_flist_sending_enabled) {
657 extra_flist_sending_enabled = False;
658 send_extra_file_list(sock_f_out, -1);
659 extra_flist_sending_enabled = !flist_eof;
662 FD_ZERO(&r_fds); /* Just in case... */
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;
670 if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
672 if (!read_batch || batch_fd < 0 || am_generator)
673 whine_about_eof(iobuf.in_fd); /* Doesn't return. */
677 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
680 /* Don't write errors on a dead socket. */
681 if (iobuf.in_fd == sock_f_in) {
684 rsyserr(FERROR_SOCKET, errno, "read error");
686 rsyserr(FERROR, errno, "read error");
687 exit_cleanup(RERR_STREAMIO);
690 if (msgs2stderr && DEBUG_GTE(IO, 2))
691 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
694 last_io_in = time(NULL);
695 stats.total_read += n;
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;
704 if (bwlimit_writemax && len > bwlimit_writemax)
705 len = bwlimit_writemax;
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)
713 /* Don't write errors on a dead socket. */
715 out->len = iobuf.raw_flushing_ends_before = out->pos = 0;
716 rsyserr(FERROR_SOCKET, errno, "write error");
717 exit_cleanup(RERR_STREAMIO);
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);
726 last_io_out = time(NULL);
727 stats.total_written += n;
729 if (bwlimit_writemax)
730 sleep_for_bwlimit(n);
732 if ((out->pos += n) == out->size) {
733 if (iobuf.raw_flushing_ends_before)
734 iobuf.raw_flushing_ends_before -= out->size;
737 if (out->pos == iobuf.raw_flushing_ends_before)
738 iobuf.raw_flushing_ends_before = 0;
739 if ((out->len -= n) == empty_buf_len) {
742 iobuf.raw_data_header_pos = 0;
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
751 forward_filesfrom_data();
756 data = iobuf.in.buf + iobuf.in.pos;
758 if (flags & PIO_CONSUME_INPUT) {
759 iobuf.in.len -= needed;
760 iobuf.in.pos += needed;
766 /* Buffer a message for the multiplexed output stream. Is never used for MSG_DATA. */
767 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
771 BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
773 if (!OUT_MULTIPLEXED)
777 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
780 if (convert > 0 && ic_send == (iconv_t)-1)
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);
788 if (iobuf.msg.len + len + 4 > iobuf.msg.size)
789 perform_io(len + 4, PIO_NEED_MSGROOM);
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;
796 iobuf.msg.len += 4; /* Leave room for the coming header bytes. */
802 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
805 iconvbufs(ic_send, &inbuf, &iobuf.msg,
806 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT);
808 rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
809 exit_cleanup(RERR_UNSUPPORTED);
811 len = iobuf.msg.len - len;
817 if ((pos += 4) >= iobuf.msg.size)
818 pos -= iobuf.msg.size;
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);
825 memcpy(iobuf.msg.buf + pos, buf, len);
827 iobuf.msg.len += len;
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);
839 if (want_debug && convert > 0)
840 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
845 void send_msg_int(enum msgcode code, int num)
849 if (DEBUG_GTE(IO, 1))
850 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
852 SIVAL(numbuf, 0, num);
853 send_msg(code, numbuf, 4, -1);
856 static void got_flist_entry_status(enum festatus status, int ndx)
858 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
860 if (remove_source_files) {
862 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
866 flist->in_progress--;
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++;
883 flist->in_progress++;
888 flist_ndx_push(&redo_list, ndx);
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). */
897 void io_set_sock_fds(int f_in, int f_out)
903 void set_io_timeout(int secs)
907 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
908 select_timeout = SELECT_TIMEOUT;
910 select_timeout = io_timeout;
912 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
915 static void check_for_d_option_error(const char *msg)
917 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
922 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
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)
930 for ( ; *msg != ':'; msg++) {
933 else if (*msg == 'e')
935 else if (strchr(rsync263_opts, *msg) == NULL)
941 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
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. */
948 void increment_active_files(int ndx, int itemizing, enum logcode code)
951 /* TODO: tune these limits? */
952 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
953 if (active_filecnt < limit)
955 check_for_finished_files(itemizing, code, 0);
956 if (active_filecnt < limit)
962 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
965 int get_redo_num(void)
967 return flist_ndx_pop(&redo_list);
970 int get_hlink_num(void)
972 return flist_ndx_pop(&hlink_list);
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. */
982 void start_filesfrom_forwarding(int 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;
998 /* Read a line into the "buf" buffer. */
999 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1004 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1005 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1010 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1014 eob = s + bufsiz - 1;
1016 /* We avoid read_byte() for files because files can return an EOF. */
1017 if (fd == iobuf.in_fd)
1019 else if (safe_read(fd, &ch, 1) == 0)
1021 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1022 /* Skip empty lines if dumping comments. */
1023 if (flags & RL_DUMP_COMMENTS && s == buf)
1032 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1036 if (flags & RL_CONVERT) {
1038 INIT_XBUF(outbuf, buf, 0, bufsiz);
1040 iconv_buf.len = s - iconv_buf.buf;
1041 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1042 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE);
1043 outbuf.buf[outbuf.len] = '\0';
1051 void 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)
1054 int maxargs = MAX_ARGS;
1058 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1061 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1064 if (!(argv = new_array(char *, maxargs)))
1065 out_of_memory("read_args");
1066 if (mod_name && !protect_args)
1067 argv[argc++] = "rsyncd";
1070 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1073 if (argc == maxargs-1) {
1074 maxargs += MAX_ARGS;
1075 if (!(argv = realloc_array(argv, char *, maxargs)))
1076 out_of_memory("read_args");
1081 *request_p = strdup(buf);
1085 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1087 glob_expand(buf, &argv, &argc, &maxargs);
1089 if (!(p = strdup(buf)))
1090 out_of_memory("read_args");
1092 if (*p == '.' && p[1] == '\0')
1098 glob_expand(NULL, NULL, NULL, NULL);
1104 int io_start_buffering_out(int f_out)
1106 if (msgs2stderr && DEBUG_GTE(IO, 2))
1107 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
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;
1116 if (iobuf.out.buf) {
1117 if (iobuf.out_fd == -1)
1118 iobuf.out_fd = f_out;
1119 assert(f_out == iobuf.out_fd);
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)))
1126 out_of_memory("io_start_buffering_out");
1127 iobuf.out.pos = iobuf.out.len = 0;
1128 iobuf.out_fd = f_out;
1133 int io_start_buffering_in(int f_in)
1135 if (msgs2stderr && DEBUG_GTE(IO, 2))
1136 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1139 if (iobuf.in_fd == -1)
1141 assert(f_in == iobuf.in_fd);
1145 iobuf.in.size = IO_BUFFER_SIZE;
1146 if (!(iobuf.in.buf = new_array(char, iobuf.in.size)))
1147 out_of_memory("io_start_buffering_in");
1149 iobuf.in.pos = iobuf.in.len = 0;
1156 static void free_xbuf(xbuf *x)
1160 memset(x, 0, sizeof (xbuf));
1163 void io_end_buffering_in(BOOL free_buffers)
1165 if (DEBUG_GTE(IO, 2)) {
1166 rprintf(FINFO, "[%s] io_end_buffering_in(%s)\n",
1167 who_am_i(), free_buffers ? "True" : "False");
1171 free_xbuf(&iobuf.in);
1173 iobuf.in.pos = iobuf.in.len = 0;
1178 void io_end_buffering_out(BOOL free_buffers)
1180 if (DEBUG_GTE(IO, 2)) {
1181 rprintf(FINFO, "[%s] io_end_buffering_out(%s)\n",
1182 who_am_i(), free_buffers ? "True" : "False");
1185 io_flush(FULL_FLUSH);
1188 free_xbuf(&iobuf.out);
1189 free_xbuf(&iobuf.msg);
1191 iobuf.out.pos = iobuf.out.len = 0;
1192 iobuf.msg.pos = iobuf.msg.len = 0;
1198 void maybe_flush_socket(int important)
1200 if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1201 && (important || time(NULL) - last_io_out >= 5))
1202 io_flush(NORMAL_FLUSH);
1205 void maybe_send_keepalive(void)
1207 if (time(NULL) - last_io_out >= allowed_lull) {
1208 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1209 if (protocol_version < 29)
1210 return; /* there's nothing we can do */
1211 if (protocol_version >= 30)
1212 send_msg(MSG_NOOP, "", 0, 0);
1214 write_int(iobuf.out_fd, cur_flist->used);
1215 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1219 perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1220 else if (iobuf.out.len > iobuf.out_empty_len)
1221 io_flush(NORMAL_FLUSH);
1225 void start_flist_forward(int ndx)
1227 write_int(iobuf.out_fd, ndx);
1228 forward_flist_data = 1;
1231 void stop_flist_forward(void)
1233 forward_flist_data = 0;
1236 /* Read a message from a multiplexed source. */
1237 static void read_a_msg(void)
1239 char *data, line[BIGPATHBUFLEN];
1243 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1244 tag = IVAL(data, 0);
1246 msg_bytes = tag & 0xFFFFFF;
1247 tag = (tag >> 24) - MPLEX_BASE;
1249 if (DEBUG_GTE(IO, 1) && (msgs2stderr || tag != MSG_INFO))
1250 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1254 assert(iobuf.raw_input_ends_before == 0);
1255 /* Though this does not yet read the data, we do mark where in
1256 * the buffer the msg data will end once it is read. It is
1257 * possible that this points off the end of the buffer, in
1258 * which case the gradual reading of the input stream will
1259 * cause this value to decrease and eventually become real. */
1260 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1263 if (msg_bytes != sizeof stats.total_read || !am_generator)
1265 data = perform_io(sizeof stats.total_read, PIO_INPUT_AND_CONSUME);
1266 memcpy((char*)&stats.total_read, data, sizeof stats.total_read);
1269 if (msg_bytes != 4 || !am_generator)
1271 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1272 got_flist_entry_status(FES_REDO, IVAL(data, 0));
1275 if (msg_bytes != 4 || am_sender)
1277 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1278 io_error |= IVAL(data, 0);
1280 send_msg(MSG_IO_ERROR, data, 4, 0);
1284 maybe_send_keepalive();
1287 if (msg_bytes >= sizeof line)
1290 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1291 send_msg(MSG_DELETED, line, msg_bytes, 1);
1295 if (ic_recv != (iconv_t)-1) {
1300 INIT_CONST_XBUF(outbuf, line);
1301 INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1304 inbuf.len = msg_bytes > sizeof ibuf ? sizeof ibuf : msg_bytes;
1305 memcpy(inbuf.buf, perform_io(inbuf.len, PIO_INPUT_AND_CONSUME), inbuf.len);
1306 if (!(msg_bytes -= inbuf.len)
1307 && !ibuf[inbuf.len-1])
1308 inbuf.len--, add_null = 1;
1309 if (iconvbufs(ic_send, &inbuf, &outbuf,
1310 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE) < 0)
1314 if (outbuf.len == outbuf.size)
1316 outbuf.buf[outbuf.len++] = '\0';
1318 msg_bytes = outbuf.len;
1321 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1322 /* A directory name was sent with the trailing null */
1323 if (msg_bytes > 0 && !line[msg_bytes-1])
1324 log_delete(line, S_IFDIR);
1326 line[msg_bytes] = '\0';
1327 log_delete(line, S_IFREG);
1331 if (msg_bytes != 4) {
1333 rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1334 tag, (unsigned long)msg_bytes, who_am_i(),
1335 inc_recurse ? "/inc" : "");
1336 exit_cleanup(RERR_STREAMIO);
1338 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1340 got_flist_entry_status(FES_SUCCESS, IVAL(data, 0));
1342 successful_send(IVAL(data, 0));
1347 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1349 got_flist_entry_status(FES_NO_SEND, IVAL(data, 0));
1351 send_msg(MSG_NO_SEND, data, 4, 0);
1353 case MSG_ERROR_SOCKET:
1354 case MSG_ERROR_UTF8:
1359 if (tag == MSG_ERROR_SOCKET)
1364 case MSG_ERROR_XFER:
1366 if (msg_bytes >= sizeof line) {
1369 "multiplexing overflow %d:%lu [%s%s]\n",
1370 tag, (unsigned long)msg_bytes, who_am_i(),
1371 inc_recurse ? "/inc" : "");
1372 exit_cleanup(RERR_STREAMIO);
1374 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1375 rwrite((enum logcode)tag, line, msg_bytes, !am_generator);
1376 if (first_message) {
1377 if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof line) {
1378 line[msg_bytes] = '\0';
1379 check_for_d_option_error(line);
1385 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1386 tag, who_am_i(), inc_recurse ? "/inc" : "");
1387 exit_cleanup(RERR_STREAMIO);
1391 void wait_for_receiver(void)
1393 if (!iobuf.raw_input_ends_before)
1396 if (iobuf.raw_input_ends_before) {
1397 int ndx = read_int(iobuf.in_fd);
1402 if (DEBUG_GTE(FLIST, 3))
1403 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1409 exit_cleanup(RERR_STREAMIO);
1412 struct file_list *flist;
1413 if (DEBUG_GTE(FLIST, 2)) {
1414 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1417 flist = recv_file_list(iobuf.in_fd);
1418 flist->parent_ndx = ndx;
1419 #ifdef SUPPORT_HARD_LINKS
1420 if (preserve_hard_links)
1421 match_hard_links(flist);
1427 unsigned short read_shortint(int f)
1431 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1434 int32 read_int(int f)
1441 #if SIZEOF_INT32 > 4
1442 if (num & (int32)0x80000000)
1443 num |= ~(int32)0xffffffff;
1448 int32 read_varint(int f)
1459 extra = int_byte_extra[ch / 4];
1461 uchar bit = ((uchar)1<<(8-extra));
1462 if (extra >= (int)sizeof u.b) {
1463 rprintf(FERROR, "Overflow in read_varint()\n");
1464 exit_cleanup(RERR_STREAMIO);
1466 read_buf(f, u.b, extra);
1467 u.b[extra] = ch & (bit-1);
1470 #if CAREFUL_ALIGNMENT
1473 #if SIZEOF_INT32 > 4
1474 if (u.x & (int32)0x80000000)
1475 u.x |= ~(int32)0xffffffff;
1480 int64 read_varlong(int f, uchar min_bytes)
1489 #if SIZEOF_INT64 < 8
1494 read_buf(f, b2, min_bytes);
1495 memcpy(u.b, b2+1, min_bytes-1);
1496 extra = int_byte_extra[CVAL(b2, 0) / 4];
1498 uchar bit = ((uchar)1<<(8-extra));
1499 if (min_bytes + extra > (int)sizeof u.b) {
1500 rprintf(FERROR, "Overflow in read_varlong()\n");
1501 exit_cleanup(RERR_STREAMIO);
1503 read_buf(f, u.b + min_bytes - 1, extra);
1504 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1505 #if SIZEOF_INT64 < 8
1506 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1507 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1508 exit_cleanup(RERR_UNSUPPORTED);
1512 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1513 #if SIZEOF_INT64 < 8
1515 #elif CAREFUL_ALIGNMENT
1516 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1521 int64 read_longint(int f)
1523 #if SIZEOF_INT64 >= 8
1526 int32 num = read_int(f);
1528 if (num != (int32)0xffffffff)
1531 #if SIZEOF_INT64 < 8
1532 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1533 exit_cleanup(RERR_UNSUPPORTED);
1536 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1540 void read_buf(int f, char *buf, size_t len)
1542 if (f != iobuf.in_fd) {
1543 if (safe_read(f, buf, len) != len)
1544 whine_about_eof(f); /* Doesn't return. */
1548 if (!IN_MULTIPLEXED) {
1549 memcpy(buf, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1550 if (forward_flist_data)
1551 write_buf(iobuf.out_fd, buf, len);
1553 if (f == write_batch_monitor_in)
1554 safe_write(batch_fd, buf, len);
1562 while (!iobuf.raw_input_ends_before)
1565 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1566 data = perform_io(siz, PIO_INPUT_AND_CONSUME);
1567 if (iobuf.in.pos == iobuf.raw_input_ends_before)
1568 iobuf.raw_input_ends_before = 0;
1570 /* The bytes at the "data" pointer will survive long
1571 * enough to make a copy, but not past future I/O. */
1572 memcpy(buf, data, siz);
1574 if (forward_flist_data)
1575 write_buf(iobuf.out_fd, buf, siz);
1577 if (f == write_batch_monitor_in)
1578 safe_write(batch_fd, buf, siz);
1580 if ((len -= siz) == 0)
1586 void read_sbuf(int f, char *buf, size_t len)
1588 read_buf(f, buf, len);
1592 uchar read_byte(int f)
1595 read_buf(f, (char*)&c, 1);
1599 int read_vstring(int f, char *buf, int bufsize)
1601 int len = read_byte(f);
1604 len = (len & ~0x80) * 0x100 + read_byte(f);
1606 if (len >= bufsize) {
1607 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1613 read_buf(f, buf, len);
1618 /* Populate a sum_struct with values from the socket. This is
1619 * called by both the sender and the receiver. */
1620 void read_sum_head(int f, struct sum_struct *sum)
1622 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1623 sum->count = read_int(f);
1624 if (sum->count < 0) {
1625 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1626 (long)sum->count, who_am_i());
1627 exit_cleanup(RERR_PROTOCOL);
1629 sum->blength = read_int(f);
1630 if (sum->blength < 0 || sum->blength > max_blength) {
1631 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1632 (long)sum->blength, who_am_i());
1633 exit_cleanup(RERR_PROTOCOL);
1635 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1636 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1637 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1638 sum->s2length, who_am_i());
1639 exit_cleanup(RERR_PROTOCOL);
1641 sum->remainder = read_int(f);
1642 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1643 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1644 (long)sum->remainder, who_am_i());
1645 exit_cleanup(RERR_PROTOCOL);
1649 /* Send the values from a sum_struct over the socket. Set sum to
1650 * NULL if there are no checksums to send. This is called by both
1651 * the generator and the sender. */
1652 void write_sum_head(int f, struct sum_struct *sum)
1654 static struct sum_struct null_sum;
1659 write_int(f, sum->count);
1660 write_int(f, sum->blength);
1661 if (protocol_version >= 27)
1662 write_int(f, sum->s2length);
1663 write_int(f, sum->remainder);
1666 /* Sleep after writing to limit I/O bandwidth usage.
1668 * @todo Rather than sleeping after each write, it might be better to
1669 * use some kind of averaging. The current algorithm seems to always
1670 * use a bit less bandwidth than specified, because it doesn't make up
1671 * for slow periods. But arguably this is a feature. In addition, we
1672 * ought to take the time used to write the data into account.
1674 * During some phases of big transfers (file FOO is uptodate) this is
1675 * called with a small bytes_written every time. As the kernel has to
1676 * round small waits up to guarantee that we actually wait at least the
1677 * requested number of microseconds, this can become grossly inaccurate.
1678 * We therefore keep track of the bytes we've written over time and only
1679 * sleep when the accumulated delay is at least 1 tenth of a second. */
1680 static void sleep_for_bwlimit(int bytes_written)
1682 static struct timeval prior_tv;
1683 static long total_written = 0;
1684 struct timeval tv, start_tv;
1685 long elapsed_usec, sleep_usec;
1687 #define ONE_SEC 1000000L /* # of microseconds in a second */
1689 total_written += bytes_written;
1691 gettimeofday(&start_tv, NULL);
1692 if (prior_tv.tv_sec) {
1693 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1694 + (start_tv.tv_usec - prior_tv.tv_usec);
1695 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1696 if (total_written < 0)
1700 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1701 if (sleep_usec < ONE_SEC / 10) {
1702 prior_tv = start_tv;
1706 tv.tv_sec = sleep_usec / ONE_SEC;
1707 tv.tv_usec = sleep_usec % ONE_SEC;
1708 select(0, NULL, NULL, NULL, &tv);
1710 gettimeofday(&prior_tv, NULL);
1711 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1712 + (prior_tv.tv_usec - start_tv.tv_usec);
1713 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1716 void io_flush(int flush_it_all)
1718 if (iobuf.out.len > iobuf.out_empty_len) {
1719 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1720 perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1721 else /* NORMAL_FLUSH: flush at least 1 byte */
1722 perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1725 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1728 void write_shortint(int f, unsigned short x)
1732 b[1] = (char)(x >> 8);
1736 void write_int(int f, int32 x)
1743 void write_varint(int f, int32 x)
1751 while (cnt > 1 && b[cnt] == 0)
1753 bit = ((uchar)1<<(7-cnt+1));
1754 if (CVAL(b, cnt) >= bit) {
1758 *b = b[cnt] | ~(bit*2-1);
1762 write_buf(f, b, cnt);
1765 void write_varlong(int f, int64 x, uchar min_bytes)
1772 #if SIZEOF_INT64 >= 8
1773 SIVAL(b, 5, x >> 32);
1775 if (x <= 0x7FFFFFFF && x >= 0)
1776 memset(b + 5, 0, 4);
1778 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1779 exit_cleanup(RERR_UNSUPPORTED);
1783 while (cnt > min_bytes && b[cnt] == 0)
1785 bit = ((uchar)1<<(7-cnt+min_bytes));
1786 if (CVAL(b, cnt) >= bit) {
1789 } else if (cnt > min_bytes)
1790 *b = b[cnt] | ~(bit*2-1);
1794 write_buf(f, b, cnt);
1798 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1799 * 64-bit types on this platform.
1801 void write_longint(int f, int64 x)
1803 char b[12], * const s = b+4;
1806 if (x <= 0x7FFFFFFF && x >= 0) {
1811 #if SIZEOF_INT64 < 8
1812 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1813 exit_cleanup(RERR_UNSUPPORTED);
1816 SIVAL(s, 4, x >> 32);
1817 write_buf(f, b, 12);
1821 void write_buf(int f, const char *buf, size_t len)
1825 if (f != iobuf.out_fd) {
1826 safe_write(f, buf, len);
1830 if (iobuf.out.size - iobuf.out.len < len)
1831 perform_io(len, PIO_NEED_OUTROOM);
1833 pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
1834 if (pos >= iobuf.out.size)
1835 pos -= iobuf.out.size;
1837 /* Handle a split copy if we wrap around the end of the circular buffer. */
1838 if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
1839 memcpy(iobuf.out.buf + pos, buf, siz);
1840 memcpy(iobuf.out.buf, buf + siz, len - siz);
1842 memcpy(iobuf.out.buf + pos, buf, len);
1844 iobuf.out.len += len;
1847 if (f == write_batch_monitor_out)
1848 safe_write(batch_fd, buf, len);
1851 /* Write a string to the connection */
1852 void write_sbuf(int f, const char *buf)
1854 write_buf(f, buf, strlen(buf));
1857 void write_byte(int f, uchar c)
1859 write_buf(f, (char *)&c, 1);
1862 void write_vstring(int f, const char *str, int len)
1864 uchar lenbuf[3], *lb = lenbuf;
1869 "attempting to send over-long vstring (%d > %d)\n",
1871 exit_cleanup(RERR_PROTOCOL);
1873 *lb++ = len / 0x100 + 0x80;
1877 write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
1879 write_buf(f, str, len);
1882 /* Send a file-list index using a byte-reduction method. */
1883 void write_ndx(int f, int32 ndx)
1885 static int32 prev_positive = -1, prev_negative = 1;
1886 int32 diff, cnt = 0;
1889 if (protocol_version < 30 || read_batch) {
1894 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1895 * negative nums as a positive after sending a leading 0xFF. */
1897 diff = ndx - prev_positive;
1898 prev_positive = ndx;
1899 } else if (ndx == NDX_DONE) {
1904 b[cnt++] = (char)0xFF;
1906 diff = ndx - prev_negative;
1907 prev_negative = ndx;
1910 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1911 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1912 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1913 if (diff < 0xFE && diff > 0)
1914 b[cnt++] = (char)diff;
1915 else if (diff < 0 || diff > 0x7FFF) {
1916 b[cnt++] = (char)0xFE;
1917 b[cnt++] = (char)((ndx >> 24) | 0x80);
1918 b[cnt++] = (char)ndx;
1919 b[cnt++] = (char)(ndx >> 8);
1920 b[cnt++] = (char)(ndx >> 16);
1922 b[cnt++] = (char)0xFE;
1923 b[cnt++] = (char)(diff >> 8);
1924 b[cnt++] = (char)diff;
1926 write_buf(f, b, cnt);
1929 /* Receive a file-list index using a byte-reduction method. */
1930 int32 read_ndx(int f)
1932 static int32 prev_positive = -1, prev_negative = 1;
1933 int32 *prev_ptr, num;
1936 if (protocol_version < 30)
1940 if (CVAL(b, 0) == 0xFF) {
1942 prev_ptr = &prev_negative;
1943 } else if (CVAL(b, 0) == 0)
1946 prev_ptr = &prev_positive;
1947 if (CVAL(b, 0) == 0xFE) {
1949 if (CVAL(b, 0) & 0x80) {
1950 b[3] = CVAL(b, 0) & ~0x80;
1952 read_buf(f, b+1, 2);
1955 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1957 num = UVAL(b, 0) + *prev_ptr;
1959 if (prev_ptr == &prev_negative)
1964 /* Read a line of up to bufsiz-1 characters into buf. Strips
1965 * the (required) trailing newline and all carriage returns.
1966 * Returns 1 for success; 0 for I/O error or truncation. */
1967 int read_line_old(int fd, char *buf, size_t bufsiz)
1969 bufsiz--; /* leave room for the null */
1970 while (bufsiz > 0) {
1971 assert(fd != iobuf.in_fd);
1972 if (safe_read(fd, buf, 1) == 0)
1987 void io_printf(int fd, const char *format, ...)
1990 char buf[BIGPATHBUFLEN];
1993 va_start(ap, format);
1994 len = vsnprintf(buf, sizeof buf, format, ap);
1998 exit_cleanup(RERR_STREAMIO);
2000 if (len > (int)sizeof buf) {
2001 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2002 exit_cleanup(RERR_STREAMIO);
2005 write_sbuf(fd, buf);
2008 /* Setup for multiplexing a MSG_* stream with the data stream. */
2009 void io_start_multiplex_out(int fd)
2011 if (msgs2stderr && DEBUG_GTE(IO, 2))
2012 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2014 io_flush(FULL_FLUSH);
2016 iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2017 io_start_buffering_out(fd);
2019 iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2023 /* Setup for multiplexing a MSG_* stream with the data stream. */
2024 void io_start_multiplex_in(int fd)
2026 if (msgs2stderr && DEBUG_GTE(IO, 2))
2027 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2029 iobuf.in_multiplexed = True; /* See also IN_MULTIPLEXED */
2030 io_start_buffering_in(fd);
2033 void io_end_multiplex_in(BOOL free_buffers)
2035 if (DEBUG_GTE(IO, 2)) {
2036 rprintf(FINFO, "[%s] io_end_multiplex_in(%s)\n",
2037 who_am_i(), free_buffers ? "True" : "False");
2040 iobuf.in_multiplexed = False;
2041 iobuf.raw_input_ends_before = 0;
2042 io_end_buffering_in(free_buffers);
2045 /* Stop output multiplexing. */
2046 void io_end_multiplex_out(BOOL free_buffers)
2048 if (DEBUG_GTE(IO, 2)) {
2049 rprintf(FINFO, "[%s] io_end_multiplex_out(%s)\n",
2050 who_am_i(), free_buffers ? "True" : "False");
2053 io_end_buffering_out(free_buffers);
2054 iobuf.out_empty_len = 0;
2057 void start_write_batch(int fd)
2059 /* Some communication has already taken place, but we don't
2060 * enable batch writing until here so that we can write a
2061 * canonical record of the communication even though the
2062 * actual communication so far depends on whether a daemon
2064 write_int(batch_fd, protocol_version);
2065 if (protocol_version >= 30)
2066 write_byte(batch_fd, inc_recurse);
2067 write_int(batch_fd, checksum_seed);
2070 write_batch_monitor_out = fd;
2072 write_batch_monitor_in = fd;
2075 void stop_write_batch(void)
2077 write_batch_monitor_out = -1;
2078 write_batch_monitor_in = -1;