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;
72 BOOL flist_receiving_enabled = False;
74 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
75 int kluge_around_eof = 0;
80 int64 total_data_read = 0;
81 int64 total_data_written = 0;
86 int out_fd; /* Both "out" and "msg" go to this fd. */
88 unsigned out_empty_len;
89 size_t raw_data_header_pos; /* in the out xbuf */
90 size_t raw_flushing_ends_before; /* in the out xbuf */
91 size_t raw_input_ends_before; /* in the in xbuf */
92 } iobuf = { .in_fd = -1, .out_fd = -1 };
94 static time_t last_io_in;
95 static time_t last_io_out;
97 static int write_batch_monitor_in = -1;
98 static int write_batch_monitor_out = -1;
100 static int ff_forward_fd = -1;
101 static int ff_reenable_multiplex = -1;
102 static char ff_lastchar = '\0';
103 static xbuf ff_xb = EMPTY_XBUF;
105 static xbuf iconv_buf = EMPTY_XBUF;
107 static int select_timeout = SELECT_TIMEOUT;
108 static int active_filecnt = 0;
109 static OFF_T active_bytecnt = 0;
110 static int first_message = 1;
112 static char int_byte_extra[64] = {
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
116 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
119 /* Our I/O buffers are sized with no bits on in the lowest byte of the "size"
120 * (indeed, our rounding of sizes in 1024-byte units assures more than this).
121 * This allows the code that is storing bytes near the physical end of a
122 * circular buffer to temporarily reduce the buffer's size (in order to make
123 * some storing idioms easier), while also making it simple to restore the
124 * buffer's actual size when the buffer's "pos" wraps around to the start (we
125 * just round the buffer's size up again). */
127 #define IOBUF_WAS_REDUCED(siz) ((siz) & 0xFF)
128 #define IOBUF_RESTORE_SIZE(siz) (((siz) | 0xFF) + 1)
130 #define IN_MULTIPLEXED (iobuf.in_multiplexed != 0)
131 #define IN_MULTIPLEXED_AND_READY (iobuf.in_multiplexed > 0)
132 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
134 #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
135 #define PIO_NEED_OUTROOM (1<<1)
136 #define PIO_NEED_MSGROOM (1<<2)
138 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
140 #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
141 #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
143 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
144 #define REMOTE_OPTION_ERROR2 ": unknown option"
146 #define FILESFROM_BUFLEN 2048
148 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
150 static flist_ndx_list redo_list, hlink_list;
152 static void read_a_msg(void);
153 static void drain_multiplex_messages(void);
154 static void sleep_for_bwlimit(int bytes_written);
156 static void check_timeout(void)
160 if (!io_timeout || ignore_timeout)
164 last_io_in = time(NULL);
170 if (t - last_io_in >= io_timeout) {
171 if (!am_server && !am_daemon) {
172 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
173 (int)(t-last_io_in));
175 exit_cleanup(RERR_TIMEOUT);
179 /* It's almost always an error to get an EOF when we're trying to read from the
180 * network, because the protocol is (for the most part) self-terminating.
182 * There is one case for the receiver when it is at the end of the transfer
183 * (hanging around reading any keep-alive packets that might come its way): if
184 * the sender dies before the generator's kill-signal comes through, we can end
185 * up here needing to loop until the kill-signal arrives. In this situation,
186 * kluge_around_eof will be < 0.
188 * There is another case for older protocol versions (< 24) where the module
189 * listing was not terminated, so we must ignore an EOF error in that case and
190 * exit. In this situation, kluge_around_eof will be > 0. */
191 static NORETURN void whine_about_eof(BOOL allow_kluge)
193 if (kluge_around_eof && allow_kluge) {
195 if (kluge_around_eof > 0)
197 /* If we're still here after 10 seconds, exit with an error. */
198 for (i = 10*1000/20; i--; )
202 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
203 "(%s bytes received so far) [%s]\n",
204 big_num(stats.total_read), who_am_i());
206 exit_cleanup(RERR_STREAMIO);
209 /* Do a safe read, handling any needed looping and error handling.
210 * Returns the count of the bytes read, which will only be different
211 * from "len" if we encountered an EOF. This routine is not used on
212 * the socket except very early in the transfer. */
213 static size_t safe_read(int fd, char *buf, size_t len)
218 assert(fd != iobuf.in_fd);
220 n = read(fd, buf, len);
221 if ((size_t)n == len || n == 0) {
222 if (DEBUG_GTE(IO, 2))
223 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
227 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
229 rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
230 (long)len, who_am_i());
231 exit_cleanup(RERR_STREAMIO);
246 tv.tv_sec = select_timeout;
249 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
251 if (cnt < 0 && errno == EBADF) {
252 rsyserr(FERROR, errno, "safe_read select failed [%s]",
254 exit_cleanup(RERR_FILEIO);
260 /*if (FD_ISSET(fd, &e_fds))
261 rprintf(FINFO, "select exception on fd %d\n", fd); */
263 if (FD_ISSET(fd, &r_fds)) {
264 n = read(fd, buf + got, len - got);
265 if (DEBUG_GTE(IO, 2))
266 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
274 if ((got += (size_t)n) == len)
282 static const char *what_fd_is(int fd)
286 if (fd == sock_f_out)
288 else if (fd == iobuf.out_fd)
290 else if (fd == batch_fd)
293 snprintf(buf, sizeof buf, "fd %d", fd);
298 /* Do a safe write, handling any needed looping and error handling.
299 * Returns only if everything was successfully written. This routine
300 * is not used on the socket except very early in the transfer. */
301 static void safe_write(int fd, const char *buf, size_t len)
305 assert(fd != iobuf.out_fd);
307 n = write(fd, buf, len);
308 if ((size_t)n == len)
311 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
313 rsyserr(FERROR, errno,
314 "safe_write failed to write %ld bytes to %s [%s]",
315 (long)len, what_fd_is(fd), who_am_i());
316 exit_cleanup(RERR_STREAMIO);
330 tv.tv_sec = select_timeout;
333 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
335 if (cnt < 0 && errno == EBADF) {
336 rsyserr(FERROR, errno, "safe_write select failed on %s [%s]",
337 what_fd_is(fd), who_am_i());
338 exit_cleanup(RERR_FILEIO);
344 if (FD_ISSET(fd, &w_fds)) {
345 n = write(fd, buf, len);
357 /* This is only called when files-from data is known to be available. We read
358 * a chunk of data and put it into the output buffer. */
359 static void forward_filesfrom_data(void)
363 len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
365 if (len == 0 || errno != EINTR) {
366 /* Send end-of-file marker */
368 write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
370 if (ff_reenable_multiplex >= 0)
371 io_start_multiplex_out(ff_reenable_multiplex);
376 if (DEBUG_GTE(IO, 2))
377 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
384 char *s = ff_xb.buf + len;
385 /* Transform CR and/or LF into '\0' */
386 while (s-- > ff_xb.buf) {
387 if (*s == '\n' || *s == '\r')
396 /* Last buf ended with a '\0', so don't let this buf start with one. */
397 while (len && *s == '\0')
399 ff_xb.pos = s - ff_xb.buf;
403 if (filesfrom_convert && len) {
404 char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
405 char *eob = sob + len;
406 int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
407 if (ff_lastchar == '\0')
409 /* Convert/send each null-terminated string separately, skipping empties. */
412 ff_xb.len = s - sob - 1;
413 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
414 exit_cleanup(RERR_PROTOCOL); /* impossible? */
415 write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
416 while (s != eob && *s == '\0')
419 ff_xb.pos = sob - ff_xb.buf;
424 if ((ff_xb.len = s - sob) == 0)
427 /* Handle a partial string specially, saving any incomplete chars. */
428 flags &= ~ICB_INCLUDE_INCOMPLETE;
429 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
431 exit_cleanup(RERR_PROTOCOL); /* impossible? */
433 memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
435 ff_lastchar = 'x'; /* Anything non-zero. */
441 char *f = ff_xb.buf + ff_xb.pos;
444 /* Eliminate any multi-'\0' runs. */
446 if (!(*t++ = *f++)) {
447 while (f != eob && *f == '\0')
452 if ((len = t - ff_xb.buf) != 0) {
453 /* This will not circle back to perform_io() because we only get
454 * called when there is plenty of room in the output buffer. */
455 write_buf(iobuf.out_fd, ff_xb.buf, len);
460 void reduce_iobuf_size(xbuf *out, size_t new_size)
462 if (new_size < out->size) {
463 if (DEBUG_GTE(IO, 4)) {
464 const char *name = out == &iobuf.out ? "iobuf.out"
465 : out == &iobuf.msg ? "iobuf.msg"
468 rprintf(FINFO, "[%s] reduced size of %s (-%d)\n",
469 who_am_i(), name, (int)(out->size - new_size));
472 out->size = new_size;
476 void restore_iobuf_size(xbuf *out)
478 if (IOBUF_WAS_REDUCED(out->size)) {
479 size_t new_size = IOBUF_RESTORE_SIZE(out->size);
480 if (DEBUG_GTE(IO, 4)) {
481 const char *name = out == &iobuf.out ? "iobuf.out"
482 : out == &iobuf.msg ? "iobuf.msg"
485 rprintf(FINFO, "[%s] restored size of %s (+%d)\n",
486 who_am_i(), name, (int)(new_size - out->size));
489 out->size = new_size;
493 /* Perform buffered input and output until specified conditions are met. When
494 * given a "needed" read requirement, we'll return without doing any I/O if the
495 * iobuf.in bytes are already available. When reading, we'll read as many
496 * bytes as we can into the buffer, and return as soon as we meet the minimum
497 * read requirement. When given a "needed" write requirement, we'll return
498 * without doing any I/O if that many bytes will fit in the output buffer (we
499 * check either iobuf.out or iobuf.msg, depending on the flags). When writing,
500 * we write out as much as we can, and return as soon as the given free-space
501 * requirement is available.
503 * The iobuf.out and iobuf.msg buffers are circular, so some writes into them
504 * will need to be split when the data needs to wrap around to the start. In
505 * order to help make this easier for some operations (such as the use of
506 * SIVAL() into the buffer) a buffer may be temporarily shortened, but the
507 * original size will be automatically restored. The iobuf.in buffer is also
508 * circular, so callers may need to split their reading of the data if it spans
509 * the end. See also the 3 raw_* iobuf vars that are used in the handling of
510 * MSG_DATA bytes as they are read-from/written-into the buffers.
512 * When writing, we flush data in the following priority order:
514 * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
516 * 2. Write out all the messages from the message buf (if iobuf.msg is active).
517 * Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
518 * messages before getting to the iobuf.out flushing (except for rule 1).
520 * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
521 * MSG_DATA header that was pre-allocated (when output is multiplexed).
523 * TODO: items for possible future work:
525 * - Make this routine able to read the generator-to-receiver batch flow?
527 * Unlike the old routines that this replaces, it is OK to read ahead as far as
528 * we can because the read_a_msg() routine now reads its bytes out of the input
529 * buffer. In the old days, only raw data was in the input buffer, and any
530 * unused raw data in the buf would prevent the reading of socket data. */
531 static char *perform_io(size_t needed, int flags)
533 fd_set r_fds, e_fds, w_fds;
536 size_t empty_buf_len = 0;
540 if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
541 if (iobuf.raw_input_ends_before)
542 iobuf.raw_input_ends_before -= iobuf.in.pos;
546 switch (flags & PIO_NEED_FLAGS) {
548 /* We never resize the circular input buffer. */
549 if (iobuf.in.size < needed) {
550 rprintf(FERROR, "need to read %ld bytes, iobuf.in.buf is only %ld bytes.\n",
551 (long)needed, (long)iobuf.in.size);
552 exit_cleanup(RERR_PROTOCOL);
555 if (DEBUG_GTE(IO, 3)) {
556 rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
557 who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
561 case PIO_NEED_OUTROOM:
562 /* We never resize the circular output buffer. */
563 if (iobuf.out.size - iobuf.out_empty_len < needed) {
564 fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
565 (long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
566 exit_cleanup(RERR_PROTOCOL);
569 if (DEBUG_GTE(IO, 3)) {
570 rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
571 who_am_i(), (long)needed,
572 iobuf.out.len + needed > iobuf.out.size
573 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
577 case PIO_NEED_MSGROOM:
578 /* We never resize the circular message buffer. */
579 if (iobuf.msg.size < needed) {
580 fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
581 (long)needed, (long)iobuf.msg.size);
582 exit_cleanup(RERR_PROTOCOL);
585 if (DEBUG_GTE(IO, 3)) {
586 rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
587 who_am_i(), (long)needed,
588 iobuf.msg.len + needed > iobuf.msg.size
589 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
594 if (DEBUG_GTE(IO, 3))
595 rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
599 exit_cleanup(RERR_UNSUPPORTED);
603 switch (flags & PIO_NEED_FLAGS) {
605 if (iobuf.in.len >= needed)
608 case PIO_NEED_OUTROOM:
609 /* Note that iobuf.out_empty_len doesn't factor into this check
610 * because iobuf.out.len already holds any needed header len. */
611 if (iobuf.out.len + needed <= iobuf.out.size)
614 case PIO_NEED_MSGROOM:
615 if (iobuf.msg.len + needed <= iobuf.msg.size)
624 if (iobuf.in_fd >= 0 && iobuf.in.size - iobuf.in.len) {
625 if (!read_batch || batch_fd >= 0) {
626 FD_SET(iobuf.in_fd, &r_fds);
627 FD_SET(iobuf.in_fd, &e_fds);
629 if (iobuf.in_fd > max_fd)
630 max_fd = iobuf.in_fd;
633 /* Only do more filesfrom processing if there is enough room in the out buffer. */
634 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
635 FD_SET(ff_forward_fd, &r_fds);
636 if (ff_forward_fd > max_fd)
637 max_fd = ff_forward_fd;
641 if (iobuf.out_fd >= 0) {
642 if (iobuf.raw_flushing_ends_before
643 || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
644 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
645 /* The iobuf.raw_flushing_ends_before value can point off the end
646 * of the iobuf.out buffer for a while, for easier subtracting. */
647 iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
649 SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
650 ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
652 if (DEBUG_GTE(IO, 1)) {
653 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
654 who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
657 /* reserve room for the next MSG_DATA header */
658 iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
659 if (iobuf.raw_data_header_pos >= iobuf.out.size)
660 iobuf.raw_data_header_pos -= iobuf.out.size;
661 else if (iobuf.raw_data_header_pos + 4 > iobuf.out.size) {
662 /* The 4-byte header won't fit at the end of the buffer,
663 * so we'll temporarily reduce the output buffer's size
664 * and put the header at the start of the buffer. */
665 reduce_iobuf_size(&iobuf.out, iobuf.raw_data_header_pos);
666 iobuf.raw_data_header_pos = 0;
668 /* Yes, it is possible for this to make len > size for a while. */
672 empty_buf_len = iobuf.out_empty_len;
674 } else if (iobuf.msg.len) {
680 FD_SET(iobuf.out_fd, &w_fds);
681 if (iobuf.out_fd > max_fd)
682 max_fd = iobuf.out_fd;
688 switch (flags & PIO_NEED_FLAGS) {
691 if (kluge_around_eof == 2)
693 if (iobuf.in_fd == -2)
694 whine_about_eof(True);
695 rprintf(FERROR, "error in perform_io: no fd for input.\n");
696 exit_cleanup(RERR_PROTOCOL);
697 case PIO_NEED_OUTROOM:
698 case PIO_NEED_MSGROOM:
700 drain_multiplex_messages();
701 if (iobuf.out_fd == -2)
702 whine_about_eof(True);
703 rprintf(FERROR, "error in perform_io: no fd for output.\n");
704 exit_cleanup(RERR_PROTOCOL);
706 /* No stated needs, so I guess this is OK. */
712 if (extra_flist_sending_enabled) {
713 if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD)
716 extra_flist_sending_enabled = False;
717 tv.tv_sec = select_timeout;
720 tv.tv_sec = select_timeout;
723 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
726 if (cnt < 0 && errno == EBADF) {
728 exit_cleanup(RERR_SOCKETIO);
730 if (extra_flist_sending_enabled) {
731 extra_flist_sending_enabled = False;
732 send_extra_file_list(sock_f_out, -1);
733 extra_flist_sending_enabled = !flist_eof;
736 FD_ZERO(&r_fds); /* Just in case... */
740 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
741 size_t len, pos = iobuf.in.pos + iobuf.in.len;
743 if (pos >= iobuf.in.size) {
744 pos -= iobuf.in.size;
745 len = iobuf.in.size - iobuf.in.len;
747 len = iobuf.in.size - pos;
748 if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
750 /* Signal that input has become invalid. */
751 if (!read_batch || batch_fd < 0 || am_generator)
756 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
759 /* Don't write errors on a dead socket. */
760 if (iobuf.in_fd == sock_f_in) {
763 rsyserr(FERROR_SOCKET, errno, "read error");
765 rsyserr(FERROR, errno, "read error");
766 exit_cleanup(RERR_SOCKETIO);
769 if (msgs2stderr && DEBUG_GTE(IO, 2))
770 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
773 last_io_in = time(NULL);
774 stats.total_read += n;
779 if (out && FD_ISSET(iobuf.out_fd, &w_fds)) {
780 size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
783 if (bwlimit_writemax && len > bwlimit_writemax)
784 len = bwlimit_writemax;
786 if (out->pos + len > out->size)
787 len = out->size - out->pos;
788 if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
789 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
792 /* Don't write errors on a dead socket. */
795 iobuf.out.len = iobuf.msg.len = iobuf.raw_flushing_ends_before = 0;
796 rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
797 drain_multiplex_messages();
798 exit_cleanup(RERR_SOCKETIO);
801 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
802 rprintf(FINFO, "[%s] %s sent=%ld\n",
803 who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
807 last_io_out = time(NULL);
808 stats.total_written += n;
810 if (bwlimit_writemax)
811 sleep_for_bwlimit(n);
813 if ((out->pos += n) == out->size) {
814 if (iobuf.raw_flushing_ends_before)
815 iobuf.raw_flushing_ends_before -= out->size;
817 restore_iobuf_size(out);
818 } else if (out->pos == iobuf.raw_flushing_ends_before)
819 iobuf.raw_flushing_ends_before = 0;
820 if ((out->len -= n) == empty_buf_len) {
822 restore_iobuf_size(out);
824 iobuf.raw_data_header_pos = 0;
828 /* We need to help prevent deadlock by doing what reading
829 * we can whenever we are here trying to write. */
830 if (IN_MULTIPLEXED_AND_READY && !(flags & PIO_NEED_INPUT)) {
831 while (!iobuf.raw_input_ends_before && iobuf.in.len > 512)
833 if (flist_receiving_enabled && iobuf.in.len > 512)
834 wait_for_receiver(); /* generator only */
837 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
838 /* This can potentially flush all output and enable
839 * multiplexed output, so keep this last in the loop
840 * and be sure to not cache anything that would break
842 forward_filesfrom_data();
847 data = iobuf.in.buf + iobuf.in.pos;
849 if (flags & PIO_CONSUME_INPUT) {
850 iobuf.in.len -= needed;
851 iobuf.in.pos += needed;
852 if (iobuf.in.pos == iobuf.raw_input_ends_before)
853 iobuf.raw_input_ends_before = 0;
854 if (iobuf.in.pos >= iobuf.in.size) {
855 iobuf.in.pos -= iobuf.in.size;
856 if (iobuf.raw_input_ends_before)
857 iobuf.raw_input_ends_before -= iobuf.in.size;
864 static void raw_read_buf(char *buf, size_t len)
866 size_t pos = iobuf.in.pos;
867 char *data = perform_io(len, PIO_INPUT_AND_CONSUME);
868 if (iobuf.in.pos <= pos && len) {
869 size_t siz = len - iobuf.in.pos;
870 memcpy(buf, data, siz);
871 memcpy(buf + siz, iobuf.in.buf, iobuf.in.pos);
873 memcpy(buf, data, len);
876 static int32 raw_read_int(void)
879 if (iobuf.in.size - iobuf.in.pos >= 4)
880 data = perform_io(4, PIO_INPUT_AND_CONSUME);
882 raw_read_buf(data = buf, 4);
883 return IVAL(data, 0);
886 void noop_io_until_death(void)
890 kluge_around_eof = 2;
891 /* Setting an I/O timeout ensures that if something inexplicably weird
892 * happens, we won't hang around forever. */
897 read_buf(iobuf.in_fd, buf, sizeof buf);
900 /* Buffer a message for the multiplexed output stream. Is never used for MSG_DATA. */
901 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
905 BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
907 if (!OUT_MULTIPLEXED)
911 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
913 /* When checking for enough free space for this message, we need to
914 * make sure that there is space for the 4-byte header, plus we'll
915 * assume that we may waste up to 3 bytes (if the header doesn't fit
916 * at the physical end of the buffer). */
918 if (convert > 0 && ic_send == (iconv_t)-1)
921 /* Ensuring double-size room leaves space for maximal conversion expansion. */
922 needed = len*2 + 4 + 3;
925 needed = len + 4 + 3;
926 if (iobuf.msg.len + needed > iobuf.msg.size)
927 perform_io(needed, PIO_NEED_MSGROOM);
929 pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
930 if (pos >= iobuf.msg.size)
931 pos -= iobuf.msg.size;
932 else if (pos + 4 > iobuf.msg.size) {
933 /* The 4-byte header won't fit at the end of the buffer,
934 * so we'll temporarily reduce the message buffer's size
935 * and put the header at the start of the buffer. */
936 reduce_iobuf_size(&iobuf.msg, pos);
939 hdr = iobuf.msg.buf + pos;
941 iobuf.msg.len += 4; /* Allocate room for the coming header bytes. */
947 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
950 iconvbufs(ic_send, &inbuf, &iobuf.msg,
951 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
953 rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
954 exit_cleanup(RERR_UNSUPPORTED);
956 len = iobuf.msg.len - len;
962 if ((pos += 4) >= iobuf.msg.size)
963 pos -= iobuf.msg.size;
965 /* Handle a split copy if we wrap around the end of the circular buffer. */
966 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
967 memcpy(iobuf.msg.buf + pos, buf, siz);
968 memcpy(iobuf.msg.buf, buf + siz, len - siz);
970 memcpy(iobuf.msg.buf + pos, buf, len);
972 iobuf.msg.len += len;
975 SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
977 if (want_debug && convert > 0)
978 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
983 void send_msg_int(enum msgcode code, int num)
987 if (DEBUG_GTE(IO, 1))
988 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
990 SIVAL(numbuf, 0, num);
991 send_msg(code, numbuf, 4, -1);
994 static void got_flist_entry_status(enum festatus status, int ndx)
996 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
998 if (remove_source_files) {
1000 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
1004 flist->in_progress--;
1008 if (remove_source_files)
1009 send_msg_int(MSG_SUCCESS, ndx);
1010 if (preserve_hard_links) {
1011 struct file_struct *file = flist->files[ndx - flist->ndx_start];
1012 if (F_IS_HLINKED(file)) {
1013 flist_ndx_push(&hlink_list, ndx);
1014 flist->in_progress++;
1021 flist->in_progress++;
1026 flist_ndx_push(&redo_list, ndx);
1033 /* Note the fds used for the main socket (which might really be a pipe
1034 * for a local transfer, but we can ignore that). */
1035 void io_set_sock_fds(int f_in, int f_out)
1041 void set_io_timeout(int secs)
1045 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
1046 select_timeout = SELECT_TIMEOUT;
1048 select_timeout = io_timeout;
1050 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
1053 static void check_for_d_option_error(const char *msg)
1055 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
1060 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
1063 msg += sizeof REMOTE_OPTION_ERROR - 1;
1064 if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
1065 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
1068 for ( ; *msg != ':'; msg++) {
1071 else if (*msg == 'e')
1073 else if (strchr(rsync263_opts, *msg) == NULL)
1079 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
1083 /* This is used by the generator to limit how many file transfers can
1084 * be active at once when --remove-source-files is specified. Without
1085 * this, sender-side deletions were mostly happening at the end. */
1086 void increment_active_files(int ndx, int itemizing, enum logcode code)
1089 /* TODO: tune these limits? */
1090 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1091 if (active_filecnt < limit)
1093 check_for_finished_files(itemizing, code, 0);
1094 if (active_filecnt < limit)
1096 wait_for_receiver();
1100 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1103 int get_redo_num(void)
1105 return flist_ndx_pop(&redo_list);
1108 int get_hlink_num(void)
1110 return flist_ndx_pop(&hlink_list);
1113 /* When we're the receiver and we have a local --files-from list of names
1114 * that needs to be sent over the socket to the sender, we have to do two
1115 * things at the same time: send the sender a list of what files we're
1116 * processing and read the incoming file+info list from the sender. We do
1117 * this by making recv_file_list() call forward_filesfrom_data(), which
1118 * will ensure that we forward data to the sender until we get some data
1119 * for recv_file_list() to use. */
1120 void start_filesfrom_forwarding(int fd)
1122 if (protocol_version < 31 && OUT_MULTIPLEXED) {
1123 /* Older protocols send the files-from data w/o packaging
1124 * it in multiplexed I/O packets, so temporarily switch
1125 * to buffered I/O to match this behavior. */
1126 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1127 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1131 alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1134 /* Read a line into the "buf" buffer. */
1135 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1140 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1141 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1146 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1150 eob = s + bufsiz - 1;
1152 /* We avoid read_byte() for files because files can return an EOF. */
1153 if (fd == iobuf.in_fd)
1155 else if (safe_read(fd, &ch, 1) == 0)
1157 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1158 /* Skip empty lines if dumping comments. */
1159 if (flags & RL_DUMP_COMMENTS && s == buf)
1168 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1172 if (flags & RL_CONVERT) {
1174 INIT_XBUF(outbuf, buf, 0, bufsiz);
1176 iconv_buf.len = s - iconv_buf.buf;
1177 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1178 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1179 outbuf.buf[outbuf.len] = '\0';
1187 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1188 char ***argv_p, int *argc_p, char **request_p)
1190 int maxargs = MAX_ARGS;
1194 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1197 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1200 if (!(argv = new_array(char *, maxargs)))
1201 out_of_memory("read_args");
1202 if (mod_name && !protect_args)
1203 argv[argc++] = "rsyncd";
1206 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1209 if (argc == maxargs-1) {
1210 maxargs += MAX_ARGS;
1211 if (!(argv = realloc_array(argv, char *, maxargs)))
1212 out_of_memory("read_args");
1217 *request_p = strdup(buf);
1221 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1223 glob_expand(buf, &argv, &argc, &maxargs);
1225 if (!(p = strdup(buf)))
1226 out_of_memory("read_args");
1228 if (*p == '.' && p[1] == '\0')
1234 glob_expand(NULL, NULL, NULL, NULL);
1240 BOOL io_start_buffering_out(int f_out)
1242 if (msgs2stderr && DEBUG_GTE(IO, 2))
1243 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1245 if (iobuf.out.buf) {
1246 if (iobuf.out_fd == -1)
1247 iobuf.out_fd = f_out;
1249 assert(f_out == iobuf.out_fd);
1253 alloc_xbuf(&iobuf.out, ROUND_UP_1024(IO_BUFFER_SIZE * 2));
1254 iobuf.out_fd = f_out;
1259 BOOL io_start_buffering_in(int f_in)
1261 if (msgs2stderr && DEBUG_GTE(IO, 2))
1262 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1265 if (iobuf.in_fd == -1)
1268 assert(f_in == iobuf.in_fd);
1272 alloc_xbuf(&iobuf.in, ROUND_UP_1024(IO_BUFFER_SIZE));
1278 void io_end_buffering_in(BOOL free_buffers)
1280 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1281 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1282 who_am_i(), free_buffers ? "FREE" : "KEEP");
1286 free_xbuf(&iobuf.in);
1288 iobuf.in.pos = iobuf.in.len = 0;
1293 void io_end_buffering_out(BOOL free_buffers)
1295 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1296 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1297 who_am_i(), free_buffers ? "FREE" : "KEEP");
1300 io_flush(FULL_FLUSH);
1303 free_xbuf(&iobuf.out);
1304 free_xbuf(&iobuf.msg);
1310 void maybe_flush_socket(int important)
1312 if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1313 && (important || time(NULL) - last_io_out >= 5))
1314 io_flush(NORMAL_FLUSH);
1317 void maybe_send_keepalive(void)
1319 if (time(NULL) - last_io_out >= allowed_lull) {
1320 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1321 if (protocol_version < 29)
1322 return; /* there's nothing we can do */
1323 if (protocol_version >= 30)
1324 send_msg(MSG_NOOP, "", 0, 0);
1326 write_int(iobuf.out_fd, cur_flist->used);
1327 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1331 perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1332 else if (iobuf.out.len > iobuf.out_empty_len)
1333 io_flush(NORMAL_FLUSH);
1337 void start_flist_forward(int ndx)
1339 write_int(iobuf.out_fd, ndx);
1340 forward_flist_data = 1;
1343 void stop_flist_forward(void)
1345 forward_flist_data = 0;
1348 /* Read a message from a multiplexed source. */
1349 static void read_a_msg(void)
1351 char data[BIGPATHBUFLEN];
1355 /* This ensures that perform_io() does not try to do any message reading
1356 * until we've read all of the data for this message. We should also
1357 * try to avoid calling things that will cause data to be written via
1358 * perform_io() prior to this being reset to 1. */
1359 iobuf.in_multiplexed = -1;
1361 tag = raw_read_int();
1363 msg_bytes = tag & 0xFFFFFF;
1364 tag = (tag >> 24) - MPLEX_BASE;
1366 if (DEBUG_GTE(IO, 1) && msgs2stderr)
1367 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1371 assert(iobuf.raw_input_ends_before == 0);
1372 /* Though this does not yet read the data, we do mark where in
1373 * the buffer the msg data will end once it is read. It is
1374 * possible that this points off the end of the buffer, in
1375 * which case the gradual reading of the input stream will
1376 * cause this value to decrease and eventually become real. */
1377 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1378 iobuf.in_multiplexed = 1;
1381 if (msg_bytes != sizeof stats.total_read || !am_generator)
1383 raw_read_buf((char*)&stats.total_read, sizeof stats.total_read);
1384 iobuf.in_multiplexed = 1;
1387 if (msg_bytes != 4 || !am_generator)
1389 val = raw_read_int();
1390 iobuf.in_multiplexed = 1;
1391 got_flist_entry_status(FES_REDO, val);
1394 if (msg_bytes != 4 || am_sender)
1396 val = raw_read_int();
1397 iobuf.in_multiplexed = 1;
1400 send_msg_int(MSG_IO_ERROR, val);
1402 case MSG_IO_TIMEOUT:
1403 if (msg_bytes != 4 || am_server || am_generator)
1405 val = raw_read_int();
1406 iobuf.in_multiplexed = 1;
1407 if (!io_timeout || io_timeout > val) {
1408 if (INFO_GTE(MISC, 2))
1409 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1410 set_io_timeout(val);
1415 maybe_send_keepalive();
1416 iobuf.in_multiplexed = 1;
1419 if (msg_bytes >= sizeof data)
1422 raw_read_buf(data, msg_bytes);
1423 iobuf.in_multiplexed = 1;
1424 send_msg(MSG_DELETED, data, msg_bytes, 1);
1428 if (ic_recv != (iconv_t)-1) {
1432 int flags = ICB_INCLUDE_BAD | ICB_INIT;
1434 INIT_CONST_XBUF(outbuf, data);
1435 INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1438 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1439 raw_read_buf(ibuf + inbuf.len, len);
1442 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1443 inbuf.len--, add_null = 1;
1444 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1447 /* Buffer ended with an incomplete char, so move the
1448 * bytes to the start of the buffer and continue. */
1449 memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1454 if (outbuf.len == outbuf.size)
1456 outbuf.buf[outbuf.len++] = '\0';
1458 msg_bytes = outbuf.len;
1461 raw_read_buf(data, msg_bytes);
1462 iobuf.in_multiplexed = 1;
1463 /* A directory name was sent with the trailing null */
1464 if (msg_bytes > 0 && !data[msg_bytes-1])
1465 log_delete(data, S_IFDIR);
1467 data[msg_bytes] = '\0';
1468 log_delete(data, S_IFREG);
1472 if (msg_bytes != 4) {
1474 rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1475 tag, (unsigned long)msg_bytes, who_am_i(),
1476 inc_recurse ? "/inc" : "");
1477 exit_cleanup(RERR_STREAMIO);
1479 val = raw_read_int();
1480 iobuf.in_multiplexed = 1;
1482 got_flist_entry_status(FES_SUCCESS, val);
1484 successful_send(val);
1489 val = raw_read_int();
1490 iobuf.in_multiplexed = 1;
1492 got_flist_entry_status(FES_NO_SEND, val);
1494 send_msg_int(MSG_NO_SEND, val);
1496 case MSG_ERROR_SOCKET:
1497 case MSG_ERROR_UTF8:
1502 if (tag == MSG_ERROR_SOCKET)
1507 case MSG_ERROR_XFER:
1509 if (msg_bytes >= sizeof data) {
1512 "multiplexing overflow %d:%lu [%s%s]\n",
1513 tag, (unsigned long)msg_bytes, who_am_i(),
1514 inc_recurse ? "/inc" : "");
1515 exit_cleanup(RERR_STREAMIO);
1517 raw_read_buf(data, msg_bytes);
1518 iobuf.in_multiplexed = 1;
1519 rwrite((enum logcode)tag, data, msg_bytes, !am_generator);
1520 if (first_message) {
1521 if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof data) {
1522 data[msg_bytes] = '\0';
1523 check_for_d_option_error(data);
1528 case MSG_ERROR_EXIT:
1530 val = raw_read_int();
1531 else if (msg_bytes == 0)
1535 iobuf.in_multiplexed = 1;
1536 if (DEBUG_GTE(EXIT, 3))
1537 rprintf(FINFO, "[%s] got MSG_ERROR_EXIT with %d bytes\n", who_am_i(), msg_bytes);
1538 if (msg_bytes == 0) {
1539 if (!am_sender && !am_generator) {
1540 if (DEBUG_GTE(EXIT, 3)) {
1541 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1544 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1545 io_flush(FULL_FLUSH);
1549 val = raw_read_int();
1550 if (protocol_version >= 31) {
1552 if (DEBUG_GTE(EXIT, 3)) {
1553 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT with exit_code %d\n",
1556 send_msg_int(MSG_ERROR_EXIT, val);
1558 if (DEBUG_GTE(EXIT, 3)) {
1559 rprintf(FINFO, "[%s] sending MSG_ERROR_EXIT (len 0)\n",
1562 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1566 /* Send a negative linenum so that we don't end up
1567 * with a duplicate exit message. */
1568 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1570 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1571 tag, who_am_i(), inc_recurse ? "/inc" : "");
1572 exit_cleanup(RERR_STREAMIO);
1575 assert(iobuf.in_multiplexed > 0);
1578 static void drain_multiplex_messages(void)
1580 while (IN_MULTIPLEXED_AND_READY && iobuf.in.len) {
1581 if (iobuf.raw_input_ends_before) {
1582 size_t raw_len = iobuf.raw_input_ends_before - iobuf.in.pos;
1583 iobuf.raw_input_ends_before = 0;
1584 if (raw_len >= iobuf.in.len) {
1588 iobuf.in.len -= raw_len;
1589 if ((iobuf.in.pos += raw_len) >= iobuf.in.size)
1590 iobuf.in.pos -= iobuf.in.size;
1596 void wait_for_receiver(void)
1598 if (!iobuf.raw_input_ends_before)
1601 if (iobuf.raw_input_ends_before) {
1602 int ndx = read_int(iobuf.in_fd);
1607 if (DEBUG_GTE(FLIST, 3))
1608 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1614 exit_cleanup(RERR_STREAMIO);
1617 struct file_list *flist;
1618 flist_receiving_enabled = False;
1619 if (DEBUG_GTE(FLIST, 2)) {
1620 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1623 flist = recv_file_list(iobuf.in_fd);
1624 flist->parent_ndx = ndx;
1625 #ifdef SUPPORT_HARD_LINKS
1626 if (preserve_hard_links)
1627 match_hard_links(flist);
1629 flist_receiving_enabled = True;
1634 unsigned short read_shortint(int f)
1638 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1641 int32 read_int(int f)
1648 #if SIZEOF_INT32 > 4
1649 if (num & (int32)0x80000000)
1650 num |= ~(int32)0xffffffff;
1655 int32 read_varint(int f)
1666 extra = int_byte_extra[ch / 4];
1668 uchar bit = ((uchar)1<<(8-extra));
1669 if (extra >= (int)sizeof u.b) {
1670 rprintf(FERROR, "Overflow in read_varint()\n");
1671 exit_cleanup(RERR_STREAMIO);
1673 read_buf(f, u.b, extra);
1674 u.b[extra] = ch & (bit-1);
1677 #if CAREFUL_ALIGNMENT
1680 #if SIZEOF_INT32 > 4
1681 if (u.x & (int32)0x80000000)
1682 u.x |= ~(int32)0xffffffff;
1687 int64 read_varlong(int f, uchar min_bytes)
1696 #if SIZEOF_INT64 < 8
1701 read_buf(f, b2, min_bytes);
1702 memcpy(u.b, b2+1, min_bytes-1);
1703 extra = int_byte_extra[CVAL(b2, 0) / 4];
1705 uchar bit = ((uchar)1<<(8-extra));
1706 if (min_bytes + extra > (int)sizeof u.b) {
1707 rprintf(FERROR, "Overflow in read_varlong()\n");
1708 exit_cleanup(RERR_STREAMIO);
1710 read_buf(f, u.b + min_bytes - 1, extra);
1711 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1712 #if SIZEOF_INT64 < 8
1713 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1714 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1715 exit_cleanup(RERR_UNSUPPORTED);
1719 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1720 #if SIZEOF_INT64 < 8
1722 #elif CAREFUL_ALIGNMENT
1723 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1728 int64 read_longint(int f)
1730 #if SIZEOF_INT64 >= 8
1733 int32 num = read_int(f);
1735 if (num != (int32)0xffffffff)
1738 #if SIZEOF_INT64 < 8
1739 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1740 exit_cleanup(RERR_UNSUPPORTED);
1743 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1747 void read_buf(int f, char *buf, size_t len)
1749 if (f != iobuf.in_fd) {
1750 if (safe_read(f, buf, len) != len)
1751 whine_about_eof(False); /* Doesn't return. */
1755 if (!IN_MULTIPLEXED) {
1756 raw_read_buf(buf, len);
1757 total_data_read += len;
1758 if (forward_flist_data)
1759 write_buf(iobuf.out_fd, buf, len);
1761 if (f == write_batch_monitor_in)
1762 safe_write(batch_fd, buf, len);
1769 while (!iobuf.raw_input_ends_before)
1772 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1773 if (siz >= iobuf.in.size)
1774 siz = iobuf.in.size;
1775 raw_read_buf(buf, siz);
1776 total_data_read += siz;
1778 if (forward_flist_data)
1779 write_buf(iobuf.out_fd, buf, siz);
1781 if (f == write_batch_monitor_in)
1782 safe_write(batch_fd, buf, siz);
1784 if ((len -= siz) == 0)
1790 void read_sbuf(int f, char *buf, size_t len)
1792 read_buf(f, buf, len);
1796 uchar read_byte(int f)
1799 read_buf(f, (char*)&c, 1);
1803 int read_vstring(int f, char *buf, int bufsize)
1805 int len = read_byte(f);
1808 len = (len & ~0x80) * 0x100 + read_byte(f);
1810 if (len >= bufsize) {
1811 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1817 read_buf(f, buf, len);
1822 /* Populate a sum_struct with values from the socket. This is
1823 * called by both the sender and the receiver. */
1824 void read_sum_head(int f, struct sum_struct *sum)
1826 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1827 sum->count = read_int(f);
1828 if (sum->count < 0) {
1829 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1830 (long)sum->count, who_am_i());
1831 exit_cleanup(RERR_PROTOCOL);
1833 sum->blength = read_int(f);
1834 if (sum->blength < 0 || sum->blength > max_blength) {
1835 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1836 (long)sum->blength, who_am_i());
1837 exit_cleanup(RERR_PROTOCOL);
1839 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1840 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1841 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1842 sum->s2length, who_am_i());
1843 exit_cleanup(RERR_PROTOCOL);
1845 sum->remainder = read_int(f);
1846 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1847 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1848 (long)sum->remainder, who_am_i());
1849 exit_cleanup(RERR_PROTOCOL);
1853 /* Send the values from a sum_struct over the socket. Set sum to
1854 * NULL if there are no checksums to send. This is called by both
1855 * the generator and the sender. */
1856 void write_sum_head(int f, struct sum_struct *sum)
1858 static struct sum_struct null_sum;
1863 write_int(f, sum->count);
1864 write_int(f, sum->blength);
1865 if (protocol_version >= 27)
1866 write_int(f, sum->s2length);
1867 write_int(f, sum->remainder);
1870 /* Sleep after writing to limit I/O bandwidth usage.
1872 * @todo Rather than sleeping after each write, it might be better to
1873 * use some kind of averaging. The current algorithm seems to always
1874 * use a bit less bandwidth than specified, because it doesn't make up
1875 * for slow periods. But arguably this is a feature. In addition, we
1876 * ought to take the time used to write the data into account.
1878 * During some phases of big transfers (file FOO is uptodate) this is
1879 * called with a small bytes_written every time. As the kernel has to
1880 * round small waits up to guarantee that we actually wait at least the
1881 * requested number of microseconds, this can become grossly inaccurate.
1882 * We therefore keep track of the bytes we've written over time and only
1883 * sleep when the accumulated delay is at least 1 tenth of a second. */
1884 static void sleep_for_bwlimit(int bytes_written)
1886 static struct timeval prior_tv;
1887 static long total_written = 0;
1888 struct timeval tv, start_tv;
1889 long elapsed_usec, sleep_usec;
1891 #define ONE_SEC 1000000L /* # of microseconds in a second */
1893 total_written += bytes_written;
1895 gettimeofday(&start_tv, NULL);
1896 if (prior_tv.tv_sec) {
1897 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1898 + (start_tv.tv_usec - prior_tv.tv_usec);
1899 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1900 if (total_written < 0)
1904 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1905 if (sleep_usec < ONE_SEC / 10) {
1906 prior_tv = start_tv;
1910 tv.tv_sec = sleep_usec / ONE_SEC;
1911 tv.tv_usec = sleep_usec % ONE_SEC;
1912 select(0, NULL, NULL, NULL, &tv);
1914 gettimeofday(&prior_tv, NULL);
1915 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1916 + (prior_tv.tv_usec - start_tv.tv_usec);
1917 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1920 void io_flush(int flush_it_all)
1922 if (iobuf.out.len > iobuf.out_empty_len) {
1923 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1924 perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1925 else /* NORMAL_FLUSH: flush at least 1 byte */
1926 perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1929 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1932 void write_shortint(int f, unsigned short x)
1936 b[1] = (char)(x >> 8);
1940 void write_int(int f, int32 x)
1947 void write_varint(int f, int32 x)
1955 while (cnt > 1 && b[cnt] == 0)
1957 bit = ((uchar)1<<(7-cnt+1));
1958 if (CVAL(b, cnt) >= bit) {
1962 *b = b[cnt] | ~(bit*2-1);
1966 write_buf(f, b, cnt);
1969 void write_varlong(int f, int64 x, uchar min_bytes)
1976 #if SIZEOF_INT64 >= 8
1977 SIVAL(b, 5, x >> 32);
1979 if (x <= 0x7FFFFFFF && x >= 0)
1980 memset(b + 5, 0, 4);
1982 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1983 exit_cleanup(RERR_UNSUPPORTED);
1987 while (cnt > min_bytes && b[cnt] == 0)
1989 bit = ((uchar)1<<(7-cnt+min_bytes));
1990 if (CVAL(b, cnt) >= bit) {
1993 } else if (cnt > min_bytes)
1994 *b = b[cnt] | ~(bit*2-1);
1998 write_buf(f, b, cnt);
2002 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
2003 * 64-bit types on this platform.
2005 void write_longint(int f, int64 x)
2007 char b[12], * const s = b+4;
2010 if (x <= 0x7FFFFFFF && x >= 0) {
2015 #if SIZEOF_INT64 < 8
2016 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
2017 exit_cleanup(RERR_UNSUPPORTED);
2020 SIVAL(s, 4, x >> 32);
2021 write_buf(f, b, 12);
2025 void write_buf(int f, const char *buf, size_t len)
2029 if (f != iobuf.out_fd) {
2030 safe_write(f, buf, len);
2034 if (iobuf.out.len + len > iobuf.out.size)
2035 perform_io(len, PIO_NEED_OUTROOM);
2037 pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
2038 if (pos >= iobuf.out.size)
2039 pos -= iobuf.out.size;
2041 /* Handle a split copy if we wrap around the end of the circular buffer. */
2042 if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
2043 memcpy(iobuf.out.buf + pos, buf, siz);
2044 memcpy(iobuf.out.buf, buf + siz, len - siz);
2046 memcpy(iobuf.out.buf + pos, buf, len);
2048 iobuf.out.len += len;
2049 total_data_written += len;
2052 if (f == write_batch_monitor_out)
2053 safe_write(batch_fd, buf, len);
2056 /* Write a string to the connection */
2057 void write_sbuf(int f, const char *buf)
2059 write_buf(f, buf, strlen(buf));
2062 void write_byte(int f, uchar c)
2064 write_buf(f, (char *)&c, 1);
2067 void write_vstring(int f, const char *str, int len)
2069 uchar lenbuf[3], *lb = lenbuf;
2074 "attempting to send over-long vstring (%d > %d)\n",
2076 exit_cleanup(RERR_PROTOCOL);
2078 *lb++ = len / 0x100 + 0x80;
2082 write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
2084 write_buf(f, str, len);
2087 /* Send a file-list index using a byte-reduction method. */
2088 void write_ndx(int f, int32 ndx)
2090 static int32 prev_positive = -1, prev_negative = 1;
2091 int32 diff, cnt = 0;
2094 if (protocol_version < 30 || read_batch) {
2099 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
2100 * negative nums as a positive after sending a leading 0xFF. */
2102 diff = ndx - prev_positive;
2103 prev_positive = ndx;
2104 } else if (ndx == NDX_DONE) {
2109 b[cnt++] = (char)0xFF;
2111 diff = ndx - prev_negative;
2112 prev_negative = ndx;
2115 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
2116 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
2117 * & all 4 bytes of the (non-negative) num with the high-bit set. */
2118 if (diff < 0xFE && diff > 0)
2119 b[cnt++] = (char)diff;
2120 else if (diff < 0 || diff > 0x7FFF) {
2121 b[cnt++] = (char)0xFE;
2122 b[cnt++] = (char)((ndx >> 24) | 0x80);
2123 b[cnt++] = (char)ndx;
2124 b[cnt++] = (char)(ndx >> 8);
2125 b[cnt++] = (char)(ndx >> 16);
2127 b[cnt++] = (char)0xFE;
2128 b[cnt++] = (char)(diff >> 8);
2129 b[cnt++] = (char)diff;
2131 write_buf(f, b, cnt);
2134 /* Receive a file-list index using a byte-reduction method. */
2135 int32 read_ndx(int f)
2137 static int32 prev_positive = -1, prev_negative = 1;
2138 int32 *prev_ptr, num;
2141 if (protocol_version < 30)
2145 if (CVAL(b, 0) == 0xFF) {
2147 prev_ptr = &prev_negative;
2148 } else if (CVAL(b, 0) == 0)
2151 prev_ptr = &prev_positive;
2152 if (CVAL(b, 0) == 0xFE) {
2154 if (CVAL(b, 0) & 0x80) {
2155 b[3] = CVAL(b, 0) & ~0x80;
2157 read_buf(f, b+1, 2);
2160 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2162 num = UVAL(b, 0) + *prev_ptr;
2164 if (prev_ptr == &prev_negative)
2169 /* Read a line of up to bufsiz-1 characters into buf. Strips
2170 * the (required) trailing newline and all carriage returns.
2171 * Returns 1 for success; 0 for I/O error or truncation. */
2172 int read_line_old(int fd, char *buf, size_t bufsiz)
2174 bufsiz--; /* leave room for the null */
2175 while (bufsiz > 0) {
2176 assert(fd != iobuf.in_fd);
2177 if (safe_read(fd, buf, 1) == 0)
2192 void io_printf(int fd, const char *format, ...)
2195 char buf[BIGPATHBUFLEN];
2198 va_start(ap, format);
2199 len = vsnprintf(buf, sizeof buf, format, ap);
2203 exit_cleanup(RERR_PROTOCOL);
2205 if (len > (int)sizeof buf) {
2206 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2207 exit_cleanup(RERR_PROTOCOL);
2210 write_sbuf(fd, buf);
2213 /* Setup for multiplexing a MSG_* stream with the data stream. */
2214 void io_start_multiplex_out(int fd)
2216 io_flush(FULL_FLUSH);
2218 if (msgs2stderr && DEBUG_GTE(IO, 2))
2219 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2222 alloc_xbuf(&iobuf.msg, ROUND_UP_1024(IO_BUFFER_SIZE));
2224 iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2225 io_start_buffering_out(fd);
2227 iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2231 /* Setup for multiplexing a MSG_* stream with the data stream. */
2232 void io_start_multiplex_in(int fd)
2234 if (msgs2stderr && DEBUG_GTE(IO, 2))
2235 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2237 iobuf.in_multiplexed = 1; /* See also IN_MULTIPLEXED */
2238 io_start_buffering_in(fd);
2241 int io_end_multiplex_in(int mode)
2243 int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2245 if (msgs2stderr && DEBUG_GTE(IO, 2))
2246 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2248 iobuf.in_multiplexed = 0;
2249 if (mode == MPLX_SWITCHING)
2250 iobuf.raw_input_ends_before = 0;
2252 assert(iobuf.raw_input_ends_before == 0);
2253 if (mode != MPLX_TO_BUFFERED)
2254 io_end_buffering_in(mode);
2259 int io_end_multiplex_out(int mode)
2261 int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2263 if (msgs2stderr && DEBUG_GTE(IO, 2))
2264 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2266 if (mode != MPLX_TO_BUFFERED)
2267 io_end_buffering_out(mode);
2269 io_flush(FULL_FLUSH);
2272 iobuf.out_empty_len = 0;
2277 void start_write_batch(int fd)
2279 /* Some communication has already taken place, but we don't
2280 * enable batch writing until here so that we can write a
2281 * canonical record of the communication even though the
2282 * actual communication so far depends on whether a daemon
2284 write_int(batch_fd, protocol_version);
2285 if (protocol_version >= 30)
2286 write_byte(batch_fd, inc_recurse);
2287 write_int(batch_fd, checksum_seed);
2290 write_batch_monitor_out = fd;
2292 write_batch_monitor_in = fd;
2295 void stop_write_batch(void)
2297 write_batch_monitor_out = -1;
2298 write_batch_monitor_in = -1;