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;
42 extern int am_generator;
43 extern int msgs2stderr;
44 extern int inc_recurse;
48 extern int file_total;
49 extern int file_old_total;
51 extern int read_batch;
52 extern int protect_args;
53 extern int checksum_seed;
54 extern int protocol_version;
55 extern int remove_source_files;
56 extern int preserve_hard_links;
57 extern BOOL extra_flist_sending_enabled;
58 extern struct stats stats;
59 extern struct file_list *cur_flist;
61 extern int filesfrom_convert;
62 extern iconv_t ic_send, ic_recv;
65 int csum_length = SHORT_SUM_LENGTH; /* initial value */
67 int ignore_timeout = 0;
70 int forward_flist_data = 0;
71 BOOL flist_receiving_enabled = False;
73 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
74 int kluge_around_eof = 0;
79 int64 total_data_read = 0;
80 int64 total_data_written = 0;
85 int out_fd; /* Both "out" and "msg" go to this fd. */
87 unsigned out_empty_len;
88 size_t raw_data_header_pos; /* in the out xbuf */
89 size_t raw_flushing_ends_before; /* in the out xbuf */
90 size_t raw_input_ends_before; /* in the in xbuf */
91 } iobuf = { .in_fd = -1, .out_fd = -1 };
93 static time_t last_io_in;
94 static time_t last_io_out;
96 static int write_batch_monitor_in = -1;
97 static int write_batch_monitor_out = -1;
99 static int ff_forward_fd = -1;
100 static int ff_reenable_multiplex = -1;
101 static char ff_lastchar = '\0';
102 static xbuf ff_xb = EMPTY_XBUF;
104 static xbuf iconv_buf = EMPTY_XBUF;
106 static int select_timeout = SELECT_TIMEOUT;
107 static int active_filecnt = 0;
108 static OFF_T active_bytecnt = 0;
109 static int first_message = 1;
111 static char int_byte_extra[64] = {
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
114 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
115 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
118 /* Our I/O buffers are sized with no bits on in the lowest byte of the "size"
119 * (indeed, our rounding of sizes in 1024-byte units assures more than this).
120 * This allows the code that is storing bytes near the physical end of a
121 * circular buffer to temporarily reduce the buffer's size (in order to make
122 * some storing idioms easier), while also making it simple to restore the
123 * buffer's actual size when the buffer's "pos" wraps around to the start (we
124 * just round the buffer's size up again). */
126 #define IOBUF_WAS_REDUCED(siz) ((siz) & 0xFF)
127 #define IOBUF_RESTORE_SIZE(siz) (((siz) | 0xFF) + 1)
129 #define IN_MULTIPLEXED (iobuf.in_multiplexed != 0)
130 #define IN_MULTIPLEXED_AND_READY (iobuf.in_multiplexed > 0)
131 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
133 #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
134 #define PIO_NEED_OUTROOM (1<<1)
135 #define PIO_NEED_MSGROOM (1<<2)
137 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
139 #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
140 #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
142 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
143 #define REMOTE_OPTION_ERROR2 ": unknown option"
145 #define FILESFROM_BUFLEN 2048
147 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
149 static flist_ndx_list redo_list, hlink_list;
151 static void read_a_msg(void);
152 static void drain_multiplex_messages(void);
153 static void sleep_for_bwlimit(int bytes_written);
155 static void check_timeout(void)
159 if (!io_timeout || ignore_timeout)
163 last_io_in = time(NULL);
169 if (t - last_io_in >= io_timeout) {
172 rprintf(FERROR, "[%s] io timeout after %d seconds -- exiting\n",
173 who_am_i(), (int)(t-last_io_in));
174 exit_cleanup(RERR_TIMEOUT);
178 /* It's almost always an error to get an EOF when we're trying to read from the
179 * network, because the protocol is (for the most part) self-terminating.
181 * There is one case for the receiver when it is at the end of the transfer
182 * (hanging around reading any keep-alive packets that might come its way): if
183 * the sender dies before the generator's kill-signal comes through, we can end
184 * up here needing to loop until the kill-signal arrives. In this situation,
185 * kluge_around_eof will be < 0.
187 * There is another case for older protocol versions (< 24) where the module
188 * listing was not terminated, so we must ignore an EOF error in that case and
189 * exit. In this situation, kluge_around_eof will be > 0. */
190 static NORETURN void whine_about_eof(BOOL allow_kluge)
192 if (kluge_around_eof && allow_kluge) {
194 if (kluge_around_eof > 0)
196 /* If we're still here after 10 seconds, exit with an error. */
197 for (i = 10*1000/20; i--; )
201 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
202 "(%s bytes received so far) [%s]\n",
203 big_num(stats.total_read), who_am_i());
205 exit_cleanup(RERR_STREAMIO);
208 /* Do a safe read, handling any needed looping and error handling.
209 * Returns the count of the bytes read, which will only be different
210 * from "len" if we encountered an EOF. This routine is not used on
211 * the socket except very early in the transfer. */
212 static size_t safe_read(int fd, char *buf, size_t len)
217 assert(fd != iobuf.in_fd);
219 n = read(fd, buf, len);
220 if ((size_t)n == len || n == 0) {
221 if (DEBUG_GTE(IO, 2))
222 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
226 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
228 rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
229 (long)len, who_am_i());
230 exit_cleanup(RERR_STREAMIO);
245 tv.tv_sec = select_timeout;
248 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
250 if (cnt < 0 && errno == EBADF) {
251 rsyserr(FERROR, errno, "safe_read select failed [%s]",
253 exit_cleanup(RERR_FILEIO);
259 /*if (FD_ISSET(fd, &e_fds))
260 rprintf(FINFO, "select exception on fd %d\n", fd); */
262 if (FD_ISSET(fd, &r_fds)) {
263 n = read(fd, buf + got, len - got);
264 if (DEBUG_GTE(IO, 2))
265 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
273 if ((got += (size_t)n) == len)
281 static const char *what_fd_is(int fd)
285 if (fd == sock_f_out)
287 else if (fd == iobuf.out_fd)
289 else if (fd == batch_fd)
292 snprintf(buf, sizeof buf, "fd %d", fd);
297 /* Do a safe write, handling any needed looping and error handling.
298 * Returns only if everything was successfully written. This routine
299 * is not used on the socket except very early in the transfer. */
300 static void safe_write(int fd, const char *buf, size_t len)
304 assert(fd != iobuf.out_fd);
306 n = write(fd, buf, len);
307 if ((size_t)n == len)
310 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
312 rsyserr(FERROR, errno,
313 "safe_write failed to write %ld bytes to %s [%s]",
314 (long)len, what_fd_is(fd), who_am_i());
315 exit_cleanup(RERR_STREAMIO);
329 tv.tv_sec = select_timeout;
332 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
334 if (cnt < 0 && errno == EBADF) {
335 rsyserr(FERROR, errno, "safe_write select failed on %s [%s]",
336 what_fd_is(fd), who_am_i());
337 exit_cleanup(RERR_FILEIO);
343 if (FD_ISSET(fd, &w_fds)) {
344 n = write(fd, buf, len);
356 /* This is only called when files-from data is known to be available. We read
357 * a chunk of data and put it into the output buffer. */
358 static void forward_filesfrom_data(void)
362 len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
364 if (len == 0 || errno != EINTR) {
365 /* Send end-of-file marker */
367 write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
369 if (ff_reenable_multiplex >= 0)
370 io_start_multiplex_out(ff_reenable_multiplex);
375 if (DEBUG_GTE(IO, 2))
376 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
383 char *s = ff_xb.buf + len;
384 /* Transform CR and/or LF into '\0' */
385 while (s-- > ff_xb.buf) {
386 if (*s == '\n' || *s == '\r')
395 /* Last buf ended with a '\0', so don't let this buf start with one. */
396 while (len && *s == '\0')
398 ff_xb.pos = s - ff_xb.buf;
402 if (filesfrom_convert && len) {
403 char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
404 char *eob = sob + len;
405 int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
406 if (ff_lastchar == '\0')
408 /* Convert/send each null-terminated string separately, skipping empties. */
411 ff_xb.len = s - sob - 1;
412 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
413 exit_cleanup(RERR_PROTOCOL); /* impossible? */
414 write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
415 while (s != eob && *s == '\0')
418 ff_xb.pos = sob - ff_xb.buf;
423 if ((ff_xb.len = s - sob) == 0)
426 /* Handle a partial string specially, saving any incomplete chars. */
427 flags &= ~ICB_INCLUDE_INCOMPLETE;
428 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
430 exit_cleanup(RERR_PROTOCOL); /* impossible? */
432 memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
434 ff_lastchar = 'x'; /* Anything non-zero. */
440 char *f = ff_xb.buf + ff_xb.pos;
443 /* Eliminate any multi-'\0' runs. */
445 if (!(*t++ = *f++)) {
446 while (f != eob && *f == '\0')
451 if ((len = t - ff_xb.buf) != 0) {
452 /* This will not circle back to perform_io() because we only get
453 * called when there is plenty of room in the output buffer. */
454 write_buf(iobuf.out_fd, ff_xb.buf, len);
459 void reduce_iobuf_size(xbuf *out, size_t new_size)
461 if (new_size < out->size) {
462 if (DEBUG_GTE(IO, 4)) {
463 const char *name = out == &iobuf.out ? "iobuf.out"
464 : out == &iobuf.msg ? "iobuf.msg"
467 rprintf(FINFO, "[%s] reduced size of %s (-%d)\n",
468 who_am_i(), name, (int)(out->size - new_size));
471 out->size = new_size;
475 void restore_iobuf_size(xbuf *out)
477 if (IOBUF_WAS_REDUCED(out->size)) {
478 size_t new_size = IOBUF_RESTORE_SIZE(out->size);
479 if (DEBUG_GTE(IO, 4)) {
480 const char *name = out == &iobuf.out ? "iobuf.out"
481 : out == &iobuf.msg ? "iobuf.msg"
484 rprintf(FINFO, "[%s] restored size of %s (+%d)\n",
485 who_am_i(), name, (int)(new_size - out->size));
488 out->size = new_size;
492 /* Perform buffered input and output until specified conditions are met. When
493 * given a "needed" read requirement, we'll return without doing any I/O if the
494 * iobuf.in bytes are already available. When reading, we'll read as many
495 * bytes as we can into the buffer, and return as soon as we meet the minimum
496 * read requirement. When given a "needed" write requirement, we'll return
497 * without doing any I/O if that many bytes will fit in the output buffer (we
498 * check either iobuf.out or iobuf.msg, depending on the flags). When writing,
499 * we write out as much as we can, and return as soon as the given free-space
500 * requirement is available.
502 * The iobuf.out and iobuf.msg buffers are circular, so some writes into them
503 * will need to be split when the data needs to wrap around to the start. In
504 * order to help make this easier for some operations (such as the use of
505 * SIVAL() into the buffer) a buffer may be temporarily shortened, but the
506 * original size will be automatically restored. The iobuf.in buffer is also
507 * circular, so callers may need to split their reading of the data if it spans
508 * the end. See also the 3 raw_* iobuf vars that are used in the handling of
509 * MSG_DATA bytes as they are read-from/written-into the buffers.
511 * When writing, we flush data in the following priority order:
513 * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
515 * 2. Write out all the messages from the message buf (if iobuf.msg is active).
516 * Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
517 * messages before getting to the iobuf.out flushing (except for rule 1).
519 * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
520 * MSG_DATA header that was pre-allocated (when output is multiplexed).
522 * TODO: items for possible future work:
524 * - Make this routine able to read the generator-to-receiver batch flow?
526 * Unlike the old routines that this replaces, it is OK to read ahead as far as
527 * we can because the read_a_msg() routine now reads its bytes out of the input
528 * buffer. In the old days, only raw data was in the input buffer, and any
529 * unused raw data in the buf would prevent the reading of socket data. */
530 static char *perform_io(size_t needed, int flags)
532 fd_set r_fds, e_fds, w_fds;
535 size_t empty_buf_len = 0;
539 if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
540 if (iobuf.raw_input_ends_before)
541 iobuf.raw_input_ends_before -= iobuf.in.pos;
545 switch (flags & PIO_NEED_FLAGS) {
547 /* We never resize the circular input buffer. */
548 if (iobuf.in.size < needed) {
549 rprintf(FERROR, "need to read %ld bytes, iobuf.in.buf is only %ld bytes.\n",
550 (long)needed, (long)iobuf.in.size);
551 exit_cleanup(RERR_PROTOCOL);
554 if (DEBUG_GTE(IO, 3)) {
555 rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
556 who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
560 case PIO_NEED_OUTROOM:
561 /* We never resize the circular output buffer. */
562 if (iobuf.out.size - iobuf.out_empty_len < needed) {
563 fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
564 (long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
565 exit_cleanup(RERR_PROTOCOL);
568 if (DEBUG_GTE(IO, 3)) {
569 rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
570 who_am_i(), (long)needed,
571 iobuf.out.len + needed > iobuf.out.size
572 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
576 case PIO_NEED_MSGROOM:
577 /* We never resize the circular message buffer. */
578 if (iobuf.msg.size < needed) {
579 fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
580 (long)needed, (long)iobuf.msg.size);
581 exit_cleanup(RERR_PROTOCOL);
584 if (DEBUG_GTE(IO, 3)) {
585 rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
586 who_am_i(), (long)needed,
587 iobuf.msg.len + needed > iobuf.msg.size
588 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
593 if (DEBUG_GTE(IO, 3))
594 rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
598 exit_cleanup(RERR_UNSUPPORTED);
602 switch (flags & PIO_NEED_FLAGS) {
604 if (iobuf.in.len >= needed)
607 case PIO_NEED_OUTROOM:
608 /* Note that iobuf.out_empty_len doesn't factor into this check
609 * because iobuf.out.len already holds any needed header len. */
610 if (iobuf.out.len + needed <= iobuf.out.size)
613 case PIO_NEED_MSGROOM:
614 if (iobuf.msg.len + needed <= iobuf.msg.size)
623 if (iobuf.in_fd >= 0 && iobuf.in.size - iobuf.in.len) {
624 if (!read_batch || batch_fd >= 0) {
625 FD_SET(iobuf.in_fd, &r_fds);
626 FD_SET(iobuf.in_fd, &e_fds);
628 if (iobuf.in_fd > max_fd)
629 max_fd = iobuf.in_fd;
632 /* Only do more filesfrom processing if there is enough room in the out buffer. */
633 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
634 FD_SET(ff_forward_fd, &r_fds);
635 if (ff_forward_fd > max_fd)
636 max_fd = ff_forward_fd;
640 if (iobuf.out_fd >= 0) {
641 if (iobuf.raw_flushing_ends_before
642 || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
643 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
644 /* The iobuf.raw_flushing_ends_before value can point off the end
645 * of the iobuf.out buffer for a while, for easier subtracting. */
646 iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
648 SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
649 ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
651 if (DEBUG_GTE(IO, 1)) {
652 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
653 who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
656 /* reserve room for the next MSG_DATA header */
657 iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
658 if (iobuf.raw_data_header_pos >= iobuf.out.size)
659 iobuf.raw_data_header_pos -= iobuf.out.size;
660 else if (iobuf.raw_data_header_pos + 4 > iobuf.out.size) {
661 /* The 4-byte header won't fit at the end of the buffer,
662 * so we'll temporarily reduce the output buffer's size
663 * and put the header at the start of the buffer. */
664 reduce_iobuf_size(&iobuf.out, iobuf.raw_data_header_pos);
665 iobuf.raw_data_header_pos = 0;
667 /* Yes, it is possible for this to make len > size for a while. */
671 empty_buf_len = iobuf.out_empty_len;
673 } else if (iobuf.msg.len) {
679 FD_SET(iobuf.out_fd, &w_fds);
680 if (iobuf.out_fd > max_fd)
681 max_fd = iobuf.out_fd;
687 switch (flags & PIO_NEED_FLAGS) {
690 if (kluge_around_eof == 2)
692 if (iobuf.in_fd == -2)
693 whine_about_eof(True);
694 rprintf(FERROR, "error in perform_io: no fd for input.\n");
695 exit_cleanup(RERR_PROTOCOL);
696 case PIO_NEED_OUTROOM:
697 case PIO_NEED_MSGROOM:
699 drain_multiplex_messages();
700 if (iobuf.out_fd == -2)
701 whine_about_eof(True);
702 rprintf(FERROR, "error in perform_io: no fd for output.\n");
703 exit_cleanup(RERR_PROTOCOL);
705 /* No stated needs, so I guess this is OK. */
711 if (extra_flist_sending_enabled) {
712 if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD)
715 extra_flist_sending_enabled = False;
716 tv.tv_sec = select_timeout;
719 tv.tv_sec = select_timeout;
722 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
725 if (cnt < 0 && errno == EBADF) {
727 exit_cleanup(RERR_SOCKETIO);
729 if (extra_flist_sending_enabled) {
730 extra_flist_sending_enabled = False;
731 send_extra_file_list(sock_f_out, -1);
732 extra_flist_sending_enabled = !flist_eof;
735 FD_ZERO(&r_fds); /* Just in case... */
739 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
740 size_t len, pos = iobuf.in.pos + iobuf.in.len;
742 if (pos >= iobuf.in.size) {
743 pos -= iobuf.in.size;
744 len = iobuf.in.size - iobuf.in.len;
746 len = iobuf.in.size - pos;
747 if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
749 /* Signal that input has become invalid. */
750 if (!read_batch || batch_fd < 0 || am_generator)
755 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
758 /* Don't write errors on a dead socket. */
759 if (iobuf.in_fd == sock_f_in) {
762 rsyserr(FERROR_SOCKET, errno, "read error");
764 rsyserr(FERROR, errno, "read error");
765 exit_cleanup(RERR_SOCKETIO);
768 if (msgs2stderr && DEBUG_GTE(IO, 2))
769 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
772 last_io_in = time(NULL);
773 stats.total_read += n;
778 if (out && FD_ISSET(iobuf.out_fd, &w_fds)) {
779 size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
782 if (bwlimit_writemax && len > bwlimit_writemax)
783 len = bwlimit_writemax;
785 if (out->pos + len > out->size)
786 len = out->size - out->pos;
787 if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
788 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
791 /* Don't write errors on a dead socket. */
794 iobuf.out.len = iobuf.msg.len = iobuf.raw_flushing_ends_before = 0;
795 rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
796 drain_multiplex_messages();
797 exit_cleanup(RERR_SOCKETIO);
800 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
801 rprintf(FINFO, "[%s] %s sent=%ld\n",
802 who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
806 last_io_out = time(NULL);
807 stats.total_written += n;
809 if (bwlimit_writemax)
810 sleep_for_bwlimit(n);
812 if ((out->pos += n) == out->size) {
813 if (iobuf.raw_flushing_ends_before)
814 iobuf.raw_flushing_ends_before -= out->size;
816 restore_iobuf_size(out);
817 } else if (out->pos == iobuf.raw_flushing_ends_before)
818 iobuf.raw_flushing_ends_before = 0;
819 if ((out->len -= n) == empty_buf_len) {
821 restore_iobuf_size(out);
823 iobuf.raw_data_header_pos = 0;
827 /* We need to help prevent deadlock by doing what reading
828 * we can whenever we are here trying to write. */
829 if (IN_MULTIPLEXED_AND_READY && !(flags & PIO_NEED_INPUT)) {
830 while (!iobuf.raw_input_ends_before && iobuf.in.len > 512)
832 if (flist_receiving_enabled && iobuf.in.len > 512)
833 wait_for_receiver(); /* generator only */
836 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
837 /* This can potentially flush all output and enable
838 * multiplexed output, so keep this last in the loop
839 * and be sure to not cache anything that would break
841 forward_filesfrom_data();
846 data = iobuf.in.buf + iobuf.in.pos;
848 if (flags & PIO_CONSUME_INPUT) {
849 iobuf.in.len -= needed;
850 iobuf.in.pos += needed;
851 if (iobuf.in.pos == iobuf.raw_input_ends_before)
852 iobuf.raw_input_ends_before = 0;
853 if (iobuf.in.pos >= iobuf.in.size) {
854 iobuf.in.pos -= iobuf.in.size;
855 if (iobuf.raw_input_ends_before)
856 iobuf.raw_input_ends_before -= iobuf.in.size;
863 static void raw_read_buf(char *buf, size_t len)
865 size_t pos = iobuf.in.pos;
866 char *data = perform_io(len, PIO_INPUT_AND_CONSUME);
867 if (iobuf.in.pos <= pos && len) {
868 size_t siz = len - iobuf.in.pos;
869 memcpy(buf, data, siz);
870 memcpy(buf + siz, iobuf.in.buf, iobuf.in.pos);
872 memcpy(buf, data, len);
875 static int32 raw_read_int(void)
878 if (iobuf.in.size - iobuf.in.pos >= 4)
879 data = perform_io(4, PIO_INPUT_AND_CONSUME);
881 raw_read_buf(data = buf, 4);
882 return IVAL(data, 0);
885 void noop_io_until_death(void)
889 kluge_around_eof = 2;
890 /* Setting an I/O timeout ensures that if something inexplicably weird
891 * happens, we won't hang around forever. */
896 read_buf(iobuf.in_fd, buf, sizeof buf);
899 /* Buffer a message for the multiplexed output stream. Is never used for MSG_DATA. */
900 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
904 BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
906 if (!OUT_MULTIPLEXED)
910 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
912 /* When checking for enough free space for this message, we need to
913 * make sure that there is space for the 4-byte header, plus we'll
914 * assume that we may waste up to 3 bytes (if the header doesn't fit
915 * at the physical end of the buffer). */
917 if (convert > 0 && ic_send == (iconv_t)-1)
920 /* Ensuring double-size room leaves space for maximal conversion expansion. */
921 needed = len*2 + 4 + 3;
924 needed = len + 4 + 3;
925 if (iobuf.msg.len + needed > iobuf.msg.size)
926 perform_io(needed, PIO_NEED_MSGROOM);
928 pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
929 if (pos >= iobuf.msg.size)
930 pos -= iobuf.msg.size;
931 else if (pos + 4 > iobuf.msg.size) {
932 /* The 4-byte header won't fit at the end of the buffer,
933 * so we'll temporarily reduce the message buffer's size
934 * and put the header at the start of the buffer. */
935 reduce_iobuf_size(&iobuf.msg, pos);
938 hdr = iobuf.msg.buf + pos;
940 iobuf.msg.len += 4; /* Allocate room for the coming header bytes. */
946 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
949 iconvbufs(ic_send, &inbuf, &iobuf.msg,
950 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
952 rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
953 exit_cleanup(RERR_UNSUPPORTED);
955 len = iobuf.msg.len - len;
961 if ((pos += 4) >= iobuf.msg.size)
962 pos -= iobuf.msg.size;
964 /* Handle a split copy if we wrap around the end of the circular buffer. */
965 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
966 memcpy(iobuf.msg.buf + pos, buf, siz);
967 memcpy(iobuf.msg.buf, buf + siz, len - siz);
969 memcpy(iobuf.msg.buf + pos, buf, len);
971 iobuf.msg.len += len;
974 SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
976 if (want_debug && convert > 0)
977 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
982 void send_msg_int(enum msgcode code, int num)
986 if (DEBUG_GTE(IO, 1))
987 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
989 SIVAL(numbuf, 0, num);
990 send_msg(code, numbuf, 4, -1);
993 static void got_flist_entry_status(enum festatus status, int ndx)
995 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
997 if (remove_source_files) {
999 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
1003 flist->in_progress--;
1007 if (remove_source_files)
1008 send_msg_int(MSG_SUCCESS, ndx);
1009 if (preserve_hard_links) {
1010 struct file_struct *file = flist->files[ndx - flist->ndx_start];
1011 if (F_IS_HLINKED(file)) {
1012 flist_ndx_push(&hlink_list, ndx);
1013 flist->in_progress++;
1020 flist->in_progress++;
1025 flist_ndx_push(&redo_list, ndx);
1032 /* Note the fds used for the main socket (which might really be a pipe
1033 * for a local transfer, but we can ignore that). */
1034 void io_set_sock_fds(int f_in, int f_out)
1040 void set_io_timeout(int secs)
1044 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
1045 select_timeout = SELECT_TIMEOUT;
1047 select_timeout = io_timeout;
1049 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
1052 static void check_for_d_option_error(const char *msg)
1054 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
1059 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
1062 msg += sizeof REMOTE_OPTION_ERROR - 1;
1063 if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
1064 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
1067 for ( ; *msg != ':'; msg++) {
1070 else if (*msg == 'e')
1072 else if (strchr(rsync263_opts, *msg) == NULL)
1078 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
1082 /* This is used by the generator to limit how many file transfers can
1083 * be active at once when --remove-source-files is specified. Without
1084 * this, sender-side deletions were mostly happening at the end. */
1085 void increment_active_files(int ndx, int itemizing, enum logcode code)
1088 /* TODO: tune these limits? */
1089 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1090 if (active_filecnt < limit)
1092 check_for_finished_files(itemizing, code, 0);
1093 if (active_filecnt < limit)
1095 wait_for_receiver();
1099 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1102 int get_redo_num(void)
1104 return flist_ndx_pop(&redo_list);
1107 int get_hlink_num(void)
1109 return flist_ndx_pop(&hlink_list);
1112 /* When we're the receiver and we have a local --files-from list of names
1113 * that needs to be sent over the socket to the sender, we have to do two
1114 * things at the same time: send the sender a list of what files we're
1115 * processing and read the incoming file+info list from the sender. We do
1116 * this by making recv_file_list() call forward_filesfrom_data(), which
1117 * will ensure that we forward data to the sender until we get some data
1118 * for recv_file_list() to use. */
1119 void start_filesfrom_forwarding(int fd)
1121 if (protocol_version < 31 && OUT_MULTIPLEXED) {
1122 /* Older protocols send the files-from data w/o packaging
1123 * it in multiplexed I/O packets, so temporarily switch
1124 * to buffered I/O to match this behavior. */
1125 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1126 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1130 alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1133 /* Read a line into the "buf" buffer. */
1134 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1139 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1140 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1145 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1149 eob = s + bufsiz - 1;
1151 /* We avoid read_byte() for files because files can return an EOF. */
1152 if (fd == iobuf.in_fd)
1154 else if (safe_read(fd, &ch, 1) == 0)
1156 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1157 /* Skip empty lines if dumping comments. */
1158 if (flags & RL_DUMP_COMMENTS && s == buf)
1167 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1171 if (flags & RL_CONVERT) {
1173 INIT_XBUF(outbuf, buf, 0, bufsiz);
1175 iconv_buf.len = s - iconv_buf.buf;
1176 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1177 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1178 outbuf.buf[outbuf.len] = '\0';
1186 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1187 char ***argv_p, int *argc_p, char **request_p)
1189 int maxargs = MAX_ARGS;
1193 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1196 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1199 if (!(argv = new_array(char *, maxargs)))
1200 out_of_memory("read_args");
1201 if (mod_name && !protect_args)
1202 argv[argc++] = "rsyncd";
1205 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1208 if (argc == maxargs-1) {
1209 maxargs += MAX_ARGS;
1210 if (!(argv = realloc_array(argv, char *, maxargs)))
1211 out_of_memory("read_args");
1216 *request_p = strdup(buf);
1220 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1222 glob_expand(buf, &argv, &argc, &maxargs);
1224 if (!(p = strdup(buf)))
1225 out_of_memory("read_args");
1227 if (*p == '.' && p[1] == '\0')
1233 glob_expand(NULL, NULL, NULL, NULL);
1239 BOOL io_start_buffering_out(int f_out)
1241 if (msgs2stderr && DEBUG_GTE(IO, 2))
1242 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1244 if (iobuf.out.buf) {
1245 if (iobuf.out_fd == -1)
1246 iobuf.out_fd = f_out;
1248 assert(f_out == iobuf.out_fd);
1252 alloc_xbuf(&iobuf.out, ROUND_UP_1024(IO_BUFFER_SIZE * 2));
1253 iobuf.out_fd = f_out;
1258 BOOL io_start_buffering_in(int f_in)
1260 if (msgs2stderr && DEBUG_GTE(IO, 2))
1261 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1264 if (iobuf.in_fd == -1)
1267 assert(f_in == iobuf.in_fd);
1271 alloc_xbuf(&iobuf.in, ROUND_UP_1024(IO_BUFFER_SIZE));
1277 void io_end_buffering_in(BOOL free_buffers)
1279 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1280 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1281 who_am_i(), free_buffers ? "FREE" : "KEEP");
1285 free_xbuf(&iobuf.in);
1287 iobuf.in.pos = iobuf.in.len = 0;
1292 void io_end_buffering_out(BOOL free_buffers)
1294 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1295 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1296 who_am_i(), free_buffers ? "FREE" : "KEEP");
1299 io_flush(FULL_FLUSH);
1302 free_xbuf(&iobuf.out);
1303 free_xbuf(&iobuf.msg);
1309 void maybe_flush_socket(int important)
1311 if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1312 && (important || time(NULL) - last_io_out >= 5))
1313 io_flush(NORMAL_FLUSH);
1316 void maybe_send_keepalive(void)
1318 if (time(NULL) - last_io_out >= allowed_lull) {
1319 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1320 if (protocol_version < 29)
1321 return; /* there's nothing we can do */
1322 if (protocol_version >= 30)
1323 send_msg(MSG_NOOP, "", 0, 0);
1325 write_int(iobuf.out_fd, cur_flist->used);
1326 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1330 perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1331 else if (iobuf.out.len > iobuf.out_empty_len)
1332 io_flush(NORMAL_FLUSH);
1336 void start_flist_forward(int ndx)
1338 write_int(iobuf.out_fd, ndx);
1339 forward_flist_data = 1;
1342 void stop_flist_forward(void)
1344 forward_flist_data = 0;
1347 /* Read a message from a multiplexed source. */
1348 static void read_a_msg(void)
1350 char data[BIGPATHBUFLEN];
1354 /* This ensures that perform_io() does not try to do any message reading
1355 * until we've read all of the data for this message. We should also
1356 * try to avoid calling things that will cause data to be written via
1357 * perform_io() prior to this being reset to 1. */
1358 iobuf.in_multiplexed = -1;
1360 tag = raw_read_int();
1362 msg_bytes = tag & 0xFFFFFF;
1363 tag = (tag >> 24) - MPLEX_BASE;
1365 if (DEBUG_GTE(IO, 1) && msgs2stderr)
1366 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1370 assert(iobuf.raw_input_ends_before == 0);
1371 /* Though this does not yet read the data, we do mark where in
1372 * the buffer the msg data will end once it is read. It is
1373 * possible that this points off the end of the buffer, in
1374 * which case the gradual reading of the input stream will
1375 * cause this value to decrease and eventually become real. */
1376 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1377 iobuf.in_multiplexed = 1;
1380 if (msg_bytes != sizeof stats.total_read || !am_generator)
1382 raw_read_buf((char*)&stats.total_read, sizeof stats.total_read);
1383 iobuf.in_multiplexed = 1;
1386 if (msg_bytes != 4 || !am_generator)
1388 val = raw_read_int();
1389 iobuf.in_multiplexed = 1;
1390 got_flist_entry_status(FES_REDO, val);
1393 if (msg_bytes != 4 || am_sender)
1395 val = raw_read_int();
1396 iobuf.in_multiplexed = 1;
1399 send_msg_int(MSG_IO_ERROR, val);
1401 case MSG_IO_TIMEOUT:
1402 if (msg_bytes != 4 || am_server || am_generator)
1404 val = raw_read_int();
1405 iobuf.in_multiplexed = 1;
1406 if (!io_timeout || io_timeout > val) {
1407 if (INFO_GTE(MISC, 2))
1408 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1409 set_io_timeout(val);
1414 maybe_send_keepalive();
1415 iobuf.in_multiplexed = 1;
1418 if (msg_bytes >= sizeof data)
1421 raw_read_buf(data, msg_bytes);
1422 iobuf.in_multiplexed = 1;
1423 send_msg(MSG_DELETED, data, msg_bytes, 1);
1427 if (ic_recv != (iconv_t)-1) {
1431 int flags = ICB_INCLUDE_BAD | ICB_INIT;
1433 INIT_CONST_XBUF(outbuf, data);
1434 INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1437 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1438 raw_read_buf(ibuf + inbuf.len, len);
1441 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1442 inbuf.len--, add_null = 1;
1443 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1446 /* Buffer ended with an incomplete char, so move the
1447 * bytes to the start of the buffer and continue. */
1448 memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1453 if (outbuf.len == outbuf.size)
1455 outbuf.buf[outbuf.len++] = '\0';
1457 msg_bytes = outbuf.len;
1460 raw_read_buf(data, msg_bytes);
1461 iobuf.in_multiplexed = 1;
1462 /* A directory name was sent with the trailing null */
1463 if (msg_bytes > 0 && !data[msg_bytes-1])
1464 log_delete(data, S_IFDIR);
1466 data[msg_bytes] = '\0';
1467 log_delete(data, S_IFREG);
1471 if (msg_bytes != 4) {
1473 rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1474 tag, (unsigned long)msg_bytes, who_am_i(),
1475 inc_recurse ? "/inc" : "");
1476 exit_cleanup(RERR_STREAMIO);
1478 val = raw_read_int();
1479 iobuf.in_multiplexed = 1;
1481 got_flist_entry_status(FES_SUCCESS, val);
1483 successful_send(val);
1488 val = raw_read_int();
1489 iobuf.in_multiplexed = 1;
1491 got_flist_entry_status(FES_NO_SEND, val);
1493 send_msg_int(MSG_NO_SEND, val);
1495 case MSG_ERROR_SOCKET:
1496 case MSG_ERROR_UTF8:
1501 if (tag == MSG_ERROR_SOCKET)
1506 case MSG_ERROR_XFER:
1508 if (msg_bytes >= sizeof data) {
1511 "multiplexing overflow %d:%lu [%s%s]\n",
1512 tag, (unsigned long)msg_bytes, who_am_i(),
1513 inc_recurse ? "/inc" : "");
1514 exit_cleanup(RERR_STREAMIO);
1516 raw_read_buf(data, msg_bytes);
1517 iobuf.in_multiplexed = 1;
1518 rwrite((enum logcode)tag, data, msg_bytes, !am_generator);
1519 if (first_message) {
1520 if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof data) {
1521 data[msg_bytes] = '\0';
1522 check_for_d_option_error(data);
1527 case MSG_ERROR_EXIT:
1529 val = raw_read_int();
1530 else if (msg_bytes == 0)
1534 iobuf.in_multiplexed = 1;
1535 if (DEBUG_GTE(EXIT, 3))
1536 rprintf(FINFO, "[%s] got MSG_ERROR_EXIT with %ld bytes\n", who_am_i(), (long)msg_bytes);
1537 if (msg_bytes == 0) {
1538 if (!am_sender && !am_generator) {
1539 if (DEBUG_GTE(EXIT, 3)) {
1540 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1543 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1544 io_flush(FULL_FLUSH);
1548 val = raw_read_int();
1549 if (protocol_version >= 31) {
1551 if (DEBUG_GTE(EXIT, 3)) {
1552 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT with exit_code %d\n",
1555 send_msg_int(MSG_ERROR_EXIT, val);
1557 if (DEBUG_GTE(EXIT, 3)) {
1558 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1561 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1565 /* Send a negative linenum so that we don't end up
1566 * with a duplicate exit message. */
1567 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1569 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1570 tag, who_am_i(), inc_recurse ? "/inc" : "");
1571 exit_cleanup(RERR_STREAMIO);
1574 assert(iobuf.in_multiplexed > 0);
1577 static void drain_multiplex_messages(void)
1579 while (IN_MULTIPLEXED_AND_READY && iobuf.in.len) {
1580 if (iobuf.raw_input_ends_before) {
1581 size_t raw_len = iobuf.raw_input_ends_before - iobuf.in.pos;
1582 iobuf.raw_input_ends_before = 0;
1583 if (raw_len >= iobuf.in.len) {
1587 iobuf.in.len -= raw_len;
1588 if ((iobuf.in.pos += raw_len) >= iobuf.in.size)
1589 iobuf.in.pos -= iobuf.in.size;
1595 void wait_for_receiver(void)
1597 if (!iobuf.raw_input_ends_before)
1600 if (iobuf.raw_input_ends_before) {
1601 int ndx = read_int(iobuf.in_fd);
1606 if (DEBUG_GTE(FLIST, 3))
1607 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1613 exit_cleanup(RERR_STREAMIO);
1616 struct file_list *flist;
1617 flist_receiving_enabled = False;
1618 if (DEBUG_GTE(FLIST, 2)) {
1619 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1622 flist = recv_file_list(iobuf.in_fd);
1623 flist->parent_ndx = ndx;
1624 #ifdef SUPPORT_HARD_LINKS
1625 if (preserve_hard_links)
1626 match_hard_links(flist);
1628 flist_receiving_enabled = True;
1633 unsigned short read_shortint(int f)
1637 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1640 int32 read_int(int f)
1647 #if SIZEOF_INT32 > 4
1648 if (num & (int32)0x80000000)
1649 num |= ~(int32)0xffffffff;
1654 int32 read_varint(int f)
1665 extra = int_byte_extra[ch / 4];
1667 uchar bit = ((uchar)1<<(8-extra));
1668 if (extra >= (int)sizeof u.b) {
1669 rprintf(FERROR, "Overflow in read_varint()\n");
1670 exit_cleanup(RERR_STREAMIO);
1672 read_buf(f, u.b, extra);
1673 u.b[extra] = ch & (bit-1);
1676 #if CAREFUL_ALIGNMENT
1679 #if SIZEOF_INT32 > 4
1680 if (u.x & (int32)0x80000000)
1681 u.x |= ~(int32)0xffffffff;
1686 int64 read_varlong(int f, uchar min_bytes)
1695 #if SIZEOF_INT64 < 8
1700 read_buf(f, b2, min_bytes);
1701 memcpy(u.b, b2+1, min_bytes-1);
1702 extra = int_byte_extra[CVAL(b2, 0) / 4];
1704 uchar bit = ((uchar)1<<(8-extra));
1705 if (min_bytes + extra > (int)sizeof u.b) {
1706 rprintf(FERROR, "Overflow in read_varlong()\n");
1707 exit_cleanup(RERR_STREAMIO);
1709 read_buf(f, u.b + min_bytes - 1, extra);
1710 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1711 #if SIZEOF_INT64 < 8
1712 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1713 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1714 exit_cleanup(RERR_UNSUPPORTED);
1718 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1719 #if SIZEOF_INT64 < 8
1721 #elif CAREFUL_ALIGNMENT
1722 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1727 int64 read_longint(int f)
1729 #if SIZEOF_INT64 >= 8
1732 int32 num = read_int(f);
1734 if (num != (int32)0xffffffff)
1737 #if SIZEOF_INT64 < 8
1738 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1739 exit_cleanup(RERR_UNSUPPORTED);
1742 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1746 void read_buf(int f, char *buf, size_t len)
1748 if (f != iobuf.in_fd) {
1749 if (safe_read(f, buf, len) != len)
1750 whine_about_eof(False); /* Doesn't return. */
1754 if (!IN_MULTIPLEXED) {
1755 raw_read_buf(buf, len);
1756 total_data_read += len;
1757 if (forward_flist_data)
1758 write_buf(iobuf.out_fd, buf, len);
1760 if (f == write_batch_monitor_in)
1761 safe_write(batch_fd, buf, len);
1768 while (!iobuf.raw_input_ends_before)
1771 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1772 if (siz >= iobuf.in.size)
1773 siz = iobuf.in.size;
1774 raw_read_buf(buf, siz);
1775 total_data_read += siz;
1777 if (forward_flist_data)
1778 write_buf(iobuf.out_fd, buf, siz);
1780 if (f == write_batch_monitor_in)
1781 safe_write(batch_fd, buf, siz);
1783 if ((len -= siz) == 0)
1789 void read_sbuf(int f, char *buf, size_t len)
1791 read_buf(f, buf, len);
1795 uchar read_byte(int f)
1798 read_buf(f, (char*)&c, 1);
1802 int read_vstring(int f, char *buf, int bufsize)
1804 int len = read_byte(f);
1807 len = (len & ~0x80) * 0x100 + read_byte(f);
1809 if (len >= bufsize) {
1810 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1816 read_buf(f, buf, len);
1821 /* Populate a sum_struct with values from the socket. This is
1822 * called by both the sender and the receiver. */
1823 void read_sum_head(int f, struct sum_struct *sum)
1825 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1826 sum->count = read_int(f);
1827 if (sum->count < 0) {
1828 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1829 (long)sum->count, who_am_i());
1830 exit_cleanup(RERR_PROTOCOL);
1832 sum->blength = read_int(f);
1833 if (sum->blength < 0 || sum->blength > max_blength) {
1834 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1835 (long)sum->blength, who_am_i());
1836 exit_cleanup(RERR_PROTOCOL);
1838 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1839 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1840 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1841 sum->s2length, who_am_i());
1842 exit_cleanup(RERR_PROTOCOL);
1844 sum->remainder = read_int(f);
1845 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1846 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1847 (long)sum->remainder, who_am_i());
1848 exit_cleanup(RERR_PROTOCOL);
1852 /* Send the values from a sum_struct over the socket. Set sum to
1853 * NULL if there are no checksums to send. This is called by both
1854 * the generator and the sender. */
1855 void write_sum_head(int f, struct sum_struct *sum)
1857 static struct sum_struct null_sum;
1862 write_int(f, sum->count);
1863 write_int(f, sum->blength);
1864 if (protocol_version >= 27)
1865 write_int(f, sum->s2length);
1866 write_int(f, sum->remainder);
1869 /* Sleep after writing to limit I/O bandwidth usage.
1871 * @todo Rather than sleeping after each write, it might be better to
1872 * use some kind of averaging. The current algorithm seems to always
1873 * use a bit less bandwidth than specified, because it doesn't make up
1874 * for slow periods. But arguably this is a feature. In addition, we
1875 * ought to take the time used to write the data into account.
1877 * During some phases of big transfers (file FOO is uptodate) this is
1878 * called with a small bytes_written every time. As the kernel has to
1879 * round small waits up to guarantee that we actually wait at least the
1880 * requested number of microseconds, this can become grossly inaccurate.
1881 * We therefore keep track of the bytes we've written over time and only
1882 * sleep when the accumulated delay is at least 1 tenth of a second. */
1883 static void sleep_for_bwlimit(int bytes_written)
1885 static struct timeval prior_tv;
1886 static long total_written = 0;
1887 struct timeval tv, start_tv;
1888 long elapsed_usec, sleep_usec;
1890 #define ONE_SEC 1000000L /* # of microseconds in a second */
1892 total_written += bytes_written;
1894 gettimeofday(&start_tv, NULL);
1895 if (prior_tv.tv_sec) {
1896 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1897 + (start_tv.tv_usec - prior_tv.tv_usec);
1898 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1899 if (total_written < 0)
1903 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1904 if (sleep_usec < ONE_SEC / 10) {
1905 prior_tv = start_tv;
1909 tv.tv_sec = sleep_usec / ONE_SEC;
1910 tv.tv_usec = sleep_usec % ONE_SEC;
1911 select(0, NULL, NULL, NULL, &tv);
1913 gettimeofday(&prior_tv, NULL);
1914 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1915 + (prior_tv.tv_usec - start_tv.tv_usec);
1916 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1919 void io_flush(int flush_it_all)
1921 if (iobuf.out.len > iobuf.out_empty_len) {
1922 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1923 perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1924 else /* NORMAL_FLUSH: flush at least 1 byte */
1925 perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1928 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1931 void write_shortint(int f, unsigned short x)
1935 b[1] = (char)(x >> 8);
1939 void write_int(int f, int32 x)
1946 void write_varint(int f, int32 x)
1954 while (cnt > 1 && b[cnt] == 0)
1956 bit = ((uchar)1<<(7-cnt+1));
1957 if (CVAL(b, cnt) >= bit) {
1961 *b = b[cnt] | ~(bit*2-1);
1965 write_buf(f, b, cnt);
1968 void write_varlong(int f, int64 x, uchar min_bytes)
1975 #if SIZEOF_INT64 >= 8
1976 SIVAL(b, 5, x >> 32);
1978 if (x <= 0x7FFFFFFF && x >= 0)
1979 memset(b + 5, 0, 4);
1981 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1982 exit_cleanup(RERR_UNSUPPORTED);
1986 while (cnt > min_bytes && b[cnt] == 0)
1988 bit = ((uchar)1<<(7-cnt+min_bytes));
1989 if (CVAL(b, cnt) >= bit) {
1992 } else if (cnt > min_bytes)
1993 *b = b[cnt] | ~(bit*2-1);
1997 write_buf(f, b, cnt);
2001 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
2002 * 64-bit types on this platform.
2004 void write_longint(int f, int64 x)
2006 char b[12], * const s = b+4;
2009 if (x <= 0x7FFFFFFF && x >= 0) {
2014 #if SIZEOF_INT64 < 8
2015 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
2016 exit_cleanup(RERR_UNSUPPORTED);
2019 SIVAL(s, 4, x >> 32);
2020 write_buf(f, b, 12);
2024 void write_buf(int f, const char *buf, size_t len)
2028 if (f != iobuf.out_fd) {
2029 safe_write(f, buf, len);
2033 if (iobuf.out.len + len > iobuf.out.size)
2034 perform_io(len, PIO_NEED_OUTROOM);
2036 pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
2037 if (pos >= iobuf.out.size)
2038 pos -= iobuf.out.size;
2040 /* Handle a split copy if we wrap around the end of the circular buffer. */
2041 if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
2042 memcpy(iobuf.out.buf + pos, buf, siz);
2043 memcpy(iobuf.out.buf, buf + siz, len - siz);
2045 memcpy(iobuf.out.buf + pos, buf, len);
2047 iobuf.out.len += len;
2048 total_data_written += len;
2051 if (f == write_batch_monitor_out)
2052 safe_write(batch_fd, buf, len);
2055 /* Write a string to the connection */
2056 void write_sbuf(int f, const char *buf)
2058 write_buf(f, buf, strlen(buf));
2061 void write_byte(int f, uchar c)
2063 write_buf(f, (char *)&c, 1);
2066 void write_vstring(int f, const char *str, int len)
2068 uchar lenbuf[3], *lb = lenbuf;
2073 "attempting to send over-long vstring (%d > %d)\n",
2075 exit_cleanup(RERR_PROTOCOL);
2077 *lb++ = len / 0x100 + 0x80;
2081 write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
2083 write_buf(f, str, len);
2086 /* Send a file-list index using a byte-reduction method. */
2087 void write_ndx(int f, int32 ndx)
2089 static int32 prev_positive = -1, prev_negative = 1;
2090 int32 diff, cnt = 0;
2093 if (protocol_version < 30 || read_batch) {
2098 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
2099 * negative nums as a positive after sending a leading 0xFF. */
2101 diff = ndx - prev_positive;
2102 prev_positive = ndx;
2103 } else if (ndx == NDX_DONE) {
2108 b[cnt++] = (char)0xFF;
2110 diff = ndx - prev_negative;
2111 prev_negative = ndx;
2114 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
2115 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
2116 * & all 4 bytes of the (non-negative) num with the high-bit set. */
2117 if (diff < 0xFE && diff > 0)
2118 b[cnt++] = (char)diff;
2119 else if (diff < 0 || diff > 0x7FFF) {
2120 b[cnt++] = (char)0xFE;
2121 b[cnt++] = (char)((ndx >> 24) | 0x80);
2122 b[cnt++] = (char)ndx;
2123 b[cnt++] = (char)(ndx >> 8);
2124 b[cnt++] = (char)(ndx >> 16);
2126 b[cnt++] = (char)0xFE;
2127 b[cnt++] = (char)(diff >> 8);
2128 b[cnt++] = (char)diff;
2130 write_buf(f, b, cnt);
2133 /* Receive a file-list index using a byte-reduction method. */
2134 int32 read_ndx(int f)
2136 static int32 prev_positive = -1, prev_negative = 1;
2137 int32 *prev_ptr, num;
2140 if (protocol_version < 30)
2144 if (CVAL(b, 0) == 0xFF) {
2146 prev_ptr = &prev_negative;
2147 } else if (CVAL(b, 0) == 0)
2150 prev_ptr = &prev_positive;
2151 if (CVAL(b, 0) == 0xFE) {
2153 if (CVAL(b, 0) & 0x80) {
2154 b[3] = CVAL(b, 0) & ~0x80;
2156 read_buf(f, b+1, 2);
2159 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2161 num = UVAL(b, 0) + *prev_ptr;
2163 if (prev_ptr == &prev_negative)
2168 /* Read a line of up to bufsiz-1 characters into buf. Strips
2169 * the (required) trailing newline and all carriage returns.
2170 * Returns 1 for success; 0 for I/O error or truncation. */
2171 int read_line_old(int fd, char *buf, size_t bufsiz)
2173 bufsiz--; /* leave room for the null */
2174 while (bufsiz > 0) {
2175 assert(fd != iobuf.in_fd);
2176 if (safe_read(fd, buf, 1) == 0)
2191 void io_printf(int fd, const char *format, ...)
2194 char buf[BIGPATHBUFLEN];
2197 va_start(ap, format);
2198 len = vsnprintf(buf, sizeof buf, format, ap);
2202 exit_cleanup(RERR_PROTOCOL);
2204 if (len > (int)sizeof buf) {
2205 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2206 exit_cleanup(RERR_PROTOCOL);
2209 write_sbuf(fd, buf);
2212 /* Setup for multiplexing a MSG_* stream with the data stream. */
2213 void io_start_multiplex_out(int fd)
2215 io_flush(FULL_FLUSH);
2217 if (msgs2stderr && DEBUG_GTE(IO, 2))
2218 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2221 alloc_xbuf(&iobuf.msg, ROUND_UP_1024(IO_BUFFER_SIZE));
2223 iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2224 io_start_buffering_out(fd);
2226 iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2230 /* Setup for multiplexing a MSG_* stream with the data stream. */
2231 void io_start_multiplex_in(int fd)
2233 if (msgs2stderr && DEBUG_GTE(IO, 2))
2234 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2236 iobuf.in_multiplexed = 1; /* See also IN_MULTIPLEXED */
2237 io_start_buffering_in(fd);
2240 int io_end_multiplex_in(int mode)
2242 int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2244 if (msgs2stderr && DEBUG_GTE(IO, 2))
2245 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2247 iobuf.in_multiplexed = 0;
2248 if (mode == MPLX_SWITCHING)
2249 iobuf.raw_input_ends_before = 0;
2251 assert(iobuf.raw_input_ends_before == 0);
2252 if (mode != MPLX_TO_BUFFERED)
2253 io_end_buffering_in(mode);
2258 int io_end_multiplex_out(int mode)
2260 int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2262 if (msgs2stderr && DEBUG_GTE(IO, 2))
2263 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2265 if (mode != MPLX_TO_BUFFERED)
2266 io_end_buffering_out(mode);
2268 io_flush(FULL_FLUSH);
2271 iobuf.out_empty_len = 0;
2276 void start_write_batch(int fd)
2278 /* Some communication has already taken place, but we don't
2279 * enable batch writing until here so that we can write a
2280 * canonical record of the communication even though the
2281 * actual communication so far depends on whether a daemon
2283 write_int(batch_fd, protocol_version);
2284 if (protocol_version >= 30)
2285 write_byte(batch_fd, inc_recurse);
2286 write_int(batch_fd, checksum_seed);
2289 write_batch_monitor_out = fd;
2291 write_batch_monitor_in = fd;
2294 void stop_write_batch(void)
2296 write_batch_monitor_out = -1;
2297 write_batch_monitor_in = -1;