2 * Socket and pipe I/O utilities used in rsync.
4 * Copyright (C) 1996-2001 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7 * Copyright (C) 2003-2009 Wayne Davison
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
23 /* Rsync provides its own multiplexing system, which is used to send
24 * stderr and stdout over a single socket.
26 * For historical reasons this is off during the start of the
27 * connection, but it's switched on quite early using
28 * io_start_multiplex_out() and io_start_multiplex_in(). */
34 /** If no timeout is specified then use a 60 second select timeout */
35 #define SELECT_TIMEOUT 60
38 extern size_t bwlimit_writemax;
39 extern int io_timeout;
43 extern int am_generator;
44 extern int msgs2stderr;
45 extern int inc_recurse;
49 extern int file_total;
50 extern int file_old_total;
52 extern int read_batch;
53 extern int protect_args;
54 extern int checksum_seed;
55 extern int protocol_version;
56 extern int remove_source_files;
57 extern int preserve_hard_links;
58 extern BOOL extra_flist_sending_enabled;
59 extern struct stats stats;
60 extern struct file_list *cur_flist;
62 extern int filesfrom_convert;
63 extern iconv_t ic_send, ic_recv;
66 int csum_length = SHORT_SUM_LENGTH; /* initial value */
68 int ignore_timeout = 0;
71 int forward_flist_data = 0;
73 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
74 int kluge_around_eof = 0;
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 #define IN_MULTIPLEXED (iobuf.in_multiplexed)
119 #define OUT_MULTIPLEXED (iobuf.out_empty_len != 0)
121 #define PIO_NEED_INPUT (1<<0) /* The *_NEED_* flags are mutually exclusive. */
122 #define PIO_NEED_OUTROOM (1<<1)
123 #define PIO_NEED_MSGROOM (1<<2)
125 #define PIO_CONSUME_INPUT (1<<4) /* Must becombined with PIO_NEED_INPUT. */
127 #define PIO_INPUT_AND_CONSUME (PIO_NEED_INPUT | PIO_CONSUME_INPUT)
128 #define PIO_NEED_FLAGS (PIO_NEED_INPUT | PIO_NEED_OUTROOM | PIO_NEED_MSGROOM)
130 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
131 #define REMOTE_OPTION_ERROR2 ": unknown option"
133 #define FILESFROM_BUFLEN 2048
135 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
137 static flist_ndx_list redo_list, hlink_list;
139 static void drain_multiplex_messages(void);
140 static void sleep_for_bwlimit(int bytes_written);
142 static void check_timeout(void)
146 if (!io_timeout || ignore_timeout)
150 last_io_in = time(NULL);
156 if (t - last_io_in >= io_timeout) {
157 if (!am_server && !am_daemon) {
158 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
159 (int)(t-last_io_in));
161 exit_cleanup(RERR_TIMEOUT);
165 /* It's almost always an error to get an EOF when we're trying to read from the
166 * network, because the protocol is (for the most part) self-terminating.
168 * There is one case for the receiver when it is at the end of the transfer
169 * (hanging around reading any keep-alive packets that might come its way): if
170 * the sender dies before the generator's kill-signal comes through, we can end
171 * up here needing to loop until the kill-signal arrives. In this situation,
172 * kluge_around_eof will be < 0.
174 * There is another case for older protocol versions (< 24) where the module
175 * listing was not terminated, so we must ignore an EOF error in that case and
176 * exit. In this situation, kluge_around_eof will be > 0. */
177 static NORETURN void whine_about_eof(BOOL allow_kluge)
179 if (kluge_around_eof && allow_kluge) {
181 if (kluge_around_eof > 0)
183 /* If we're still here after 10 seconds, exit with an error. */
184 for (i = 10*1000/20; i--; )
188 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
189 "(%s bytes received so far) [%s]\n",
190 big_num(stats.total_read), who_am_i());
192 exit_cleanup(RERR_STREAMIO);
195 /* Do a safe read, handling any needed looping and error handling.
196 * Returns the count of the bytes read, which will only be different
197 * from "len" if we encountered an EOF. This routine is not used on
198 * the socket except very early in the transfer. */
199 static size_t safe_read(int fd, char *buf, size_t len)
204 assert(fd != iobuf.in_fd);
206 n = read(fd, buf, len);
207 if ((size_t)n == len || n == 0) {
208 if (DEBUG_GTE(IO, 2))
209 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
213 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
215 rsyserr(FERROR, errno, "safe_read failed to read %ld bytes [%s]",
216 (long)len, who_am_i());
217 exit_cleanup(RERR_STREAMIO);
232 tv.tv_sec = select_timeout;
235 cnt = select(fd+1, &r_fds, NULL, &e_fds, &tv);
237 if (cnt < 0 && errno == EBADF) {
238 rsyserr(FERROR, errno, "safe_read select failed [%s]",
240 exit_cleanup(RERR_FILEIO);
246 /*if (FD_ISSET(fd, &e_fds))
247 rprintf(FINFO, "select exception on fd %d\n", fd); */
249 if (FD_ISSET(fd, &r_fds)) {
250 n = read(fd, buf + got, len - got);
251 if (DEBUG_GTE(IO, 2))
252 rprintf(FINFO, "[%s] safe_read(%d)=%ld\n", who_am_i(), fd, (long)n);
260 if ((got += (size_t)n) == len)
268 static const char *what_fd_is(int fd)
272 if (fd == sock_f_out)
274 else if (fd == iobuf.out_fd)
276 else if (fd == batch_fd)
279 snprintf(buf, sizeof buf, "fd %d", fd);
284 /* Do a safe write, handling any needed looping and error handling.
285 * Returns only if everything was successfully written. This routine
286 * is not used on the socket except very early in the transfer. */
287 static void safe_write(int fd, const char *buf, size_t len)
291 assert(fd != iobuf.out_fd);
293 n = write(fd, buf, len);
294 if ((size_t)n == len)
297 if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) {
299 rsyserr(FERROR, errno,
300 "safe_write failed to write %ld bytes to %s [%s]",
301 (long)len, what_fd_is(fd), who_am_i());
302 exit_cleanup(RERR_STREAMIO);
316 tv.tv_sec = select_timeout;
319 cnt = select(fd + 1, NULL, &w_fds, NULL, &tv);
321 if (cnt < 0 && errno == EBADF) {
322 rsyserr(FERROR, errno, "safe_write select failed on %s [%s]",
323 what_fd_is(fd), who_am_i());
324 exit_cleanup(RERR_FILEIO);
330 if (FD_ISSET(fd, &w_fds)) {
331 n = write(fd, buf, len);
343 /* This is only called when files-from data is known to be available. We read
344 * a chunk of data and put it into the output buffer. */
345 static void forward_filesfrom_data(void)
349 len = read(ff_forward_fd, ff_xb.buf + ff_xb.len, ff_xb.size - ff_xb.len);
351 if (len == 0 || errno != EINTR) {
352 /* Send end-of-file marker */
354 write_buf(iobuf.out_fd, "\0\0", ff_lastchar ? 2 : 1);
356 if (ff_reenable_multiplex >= 0)
357 io_start_multiplex_out(ff_reenable_multiplex);
362 if (DEBUG_GTE(IO, 2))
363 rprintf(FINFO, "[%s] files-from read=%ld\n", who_am_i(), (long)len);
370 char *s = ff_xb.buf + len;
371 /* Transform CR and/or LF into '\0' */
372 while (s-- > ff_xb.buf) {
373 if (*s == '\n' || *s == '\r')
382 /* Last buf ended with a '\0', so don't let this buf start with one. */
383 while (len && *s == '\0')
385 ff_xb.pos = s - ff_xb.buf;
389 if (filesfrom_convert && len) {
390 char *sob = ff_xb.buf + ff_xb.pos, *s = sob;
391 char *eob = sob + len;
392 int flags = ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT;
393 if (ff_lastchar == '\0')
395 /* Convert/send each null-terminated string separately, skipping empties. */
398 ff_xb.len = s - sob - 1;
399 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0)
400 exit_cleanup(RERR_PROTOCOL); /* impossible? */
401 write_buf(iobuf.out_fd, s-1, 1); /* Send the '\0'. */
402 while (s != eob && *s == '\0')
405 ff_xb.pos = sob - ff_xb.buf;
410 if ((ff_xb.len = s - sob) == 0)
413 /* Handle a partial string specially, saving any incomplete chars. */
414 flags &= ~ICB_INCLUDE_INCOMPLETE;
415 if (iconvbufs(ic_send, &ff_xb, &iobuf.out, flags) < 0) {
417 exit_cleanup(RERR_PROTOCOL); /* impossible? */
419 memmove(ff_xb.buf, ff_xb.buf + ff_xb.pos, ff_xb.len);
421 ff_lastchar = 'x'; /* Anything non-zero. */
427 char *f = ff_xb.buf + ff_xb.pos;
430 /* Eliminate any multi-'\0' runs. */
432 if (!(*t++ = *f++)) {
433 while (f != eob && *f == '\0')
438 if ((len = t - ff_xb.buf) != 0) {
439 /* This will not circle back to perform_io() because we only get
440 * called when there is plenty of room in the output buffer. */
441 write_buf(iobuf.out_fd, ff_xb.buf, len);
446 /* Perform buffered input and output until specified conditions are met. When
447 * given a "needed" read requirement, we'll return without doing any I/O if the
448 * iobuf.in bytes are already available. When reading, we'll read as many
449 * bytes as we can into the buffer, and return as soon as we meet the minimum
450 * read requirement. When given a "needed" write requirement, we'll return
451 * without doing any I/O if that many bytes will fit in the output buffer (we
452 * check either iobuf.out or iobuf.msg, depending on the flags). When writing,
453 * we write out as much as we can, and return as soon as the given free-space
454 * requirement is available.
456 * The iobuf.out and iobuf.msg buffers are circular, so some writes into them
457 * will need to be split when the data needs to wrap around to the start. In
458 * order to help make this easier for some operations (such as the use of
459 * SIVAL() into the buffer) the buffers MUST have 4 bytes of overflow space at
460 * the end that is not not counted in the "size". The iobuf.in buffer is not
461 * (currently) circular. To facilitate the handling of MSG_DATA bytes as they
462 * are read-from/written-into the buffers, see the three raw_* iobuf vars.
464 * When writing, we flush data in the following priority order:
466 * 1. Finish writing any in-progress MSG_DATA sequence from iobuf.out.
468 * 2. Write out all the messages from the message buf (if iobuf.msg is active).
469 * Yes, this means that a PIO_NEED_OUTROOM call will completely flush any
470 * messages before getting to the iobuf.out flushing (except for rule 1).
472 * 3. Write out the raw data from iobuf.out, possibly filling in the multiplexed
473 * MSG_DATA header that was pre-allocated (when output is multiplexed).
475 * TODO: items for possible future work:
477 * - Make this routine able to read the generator-to-receiver batch flow?
479 * - Make the input buffer circular?
481 * Unlike the old routines that this replaces, it is OK to read ahead as far as
482 * we can because the read_a_msg() routine now reads its bytes out of the input
483 * buffer. In the old days, only raw data was in the input buffer, and any
484 * unused raw data in the buf would prevent the reading of socket data. */
485 static char *perform_io(size_t needed, int flags)
487 fd_set r_fds, e_fds, w_fds;
490 size_t empty_buf_len = 0;
494 if (iobuf.in.len == 0 && iobuf.in.pos != 0) {
495 if (iobuf.raw_input_ends_before)
496 iobuf.raw_input_ends_before -= iobuf.in.pos;
500 switch (flags & PIO_NEED_FLAGS) {
502 if (DEBUG_GTE(IO, 3)) {
503 rprintf(FINFO, "[%s] perform_io(%ld, %sinput)\n",
504 who_am_i(), (long)needed, flags & PIO_CONSUME_INPUT ? "consume&" : "");
507 /* Make sure the input buffer is big enough to hold "needed" bytes.
508 * Also make sure it will fit in the free space at the end, or
509 * else we need to shift some bytes. */
510 if (needed && iobuf.in.size < needed) {
511 if (!(iobuf.in.buf = realloc_array(iobuf.in.buf, char, needed)))
512 out_of_memory("perform_io");
513 if (DEBUG_GTE(IO, 4)) {
514 rprintf(FINFO, "[%s] resized input buffer from %ld to %ld bytes.\n",
515 who_am_i(), (long)iobuf.in.size, (long)needed);
517 iobuf.in.size = needed;
519 if (iobuf.in.size - iobuf.in.pos < needed
520 || (iobuf.in.len < needed && iobuf.in.len < 1024
521 && iobuf.in.size - (iobuf.in.pos + iobuf.in.len) < 1024)) {
522 memmove(iobuf.in.buf, iobuf.in.buf + iobuf.in.pos, iobuf.in.len);
523 if (DEBUG_GTE(IO, 4)) {
525 "[%s] moved %ld bytes from %ld to 0 in the input buffer (size=%ld, needed=%ld).\n",
526 who_am_i(), (long)iobuf.in.len, (long)iobuf.in.pos, (long)iobuf.in.size, (long)needed);
528 if (iobuf.raw_input_ends_before)
529 iobuf.raw_input_ends_before -= iobuf.in.pos;
534 case PIO_NEED_OUTROOM:
535 /* We never resize the circular output buffer. */
536 if (iobuf.out.size - iobuf.out_empty_len < needed) {
537 fprintf(stderr, "need to write %ld bytes, iobuf.out.buf is only %ld bytes.\n",
538 (long)needed, (long)(iobuf.out.size - iobuf.out_empty_len));
539 exit_cleanup(RERR_PROTOCOL);
542 if (DEBUG_GTE(IO, 3)) {
543 rprintf(FINFO, "[%s] perform_io(%ld, outroom) needs to flush %ld\n",
544 who_am_i(), (long)needed,
545 iobuf.out.len + needed > iobuf.out.size
546 ? (long)(iobuf.out.len + needed - iobuf.out.size) : 0L);
550 case PIO_NEED_MSGROOM:
551 /* We never resize the circular message buffer. */
552 if (iobuf.msg.size < needed) {
553 fprintf(stderr, "need to write %ld bytes, iobuf.msg.buf is only %ld bytes.\n",
554 (long)needed, (long)iobuf.msg.size);
555 exit_cleanup(RERR_PROTOCOL);
558 if (DEBUG_GTE(IO, 3)) {
559 rprintf(FINFO, "[%s] perform_io(%ld, msgroom) needs to flush %ld\n",
560 who_am_i(), (long)needed,
561 iobuf.msg.len + needed > iobuf.msg.size
562 ? (long)(iobuf.msg.len + needed - iobuf.msg.size) : 0L);
567 if (DEBUG_GTE(IO, 3))
568 rprintf(FINFO, "[%s] perform_io(%ld, %d)\n", who_am_i(), (long)needed, flags);
572 exit_cleanup(RERR_UNSUPPORTED);
576 switch (flags & PIO_NEED_FLAGS) {
578 if (iobuf.in.len >= needed)
581 case PIO_NEED_OUTROOM:
582 /* Note that iobuf.out_empty_len doesn't factor into this check
583 * because iobuf.out.len already holds any needed header len. */
584 if (iobuf.out.len + needed <= iobuf.out.size)
587 case PIO_NEED_MSGROOM:
588 if (iobuf.msg.len + needed <= iobuf.msg.size)
597 if (iobuf.in_fd >= 0 && iobuf.in.size - (iobuf.in.pos + iobuf.in.len)) {
598 if (!read_batch || batch_fd >= 0) {
599 FD_SET(iobuf.in_fd, &r_fds);
600 FD_SET(iobuf.in_fd, &e_fds);
602 if (iobuf.in_fd > max_fd)
603 max_fd = iobuf.in_fd;
606 /* Only do more filesfrom processing if there is enough room in the out buffer. */
607 if (ff_forward_fd >= 0 && iobuf.out.size - iobuf.out.len > FILESFROM_BUFLEN*2) {
608 FD_SET(ff_forward_fd, &r_fds);
609 if (ff_forward_fd > max_fd)
610 max_fd = ff_forward_fd;
614 if (iobuf.out_fd >= 0) {
615 if (iobuf.raw_flushing_ends_before
616 || (!iobuf.msg.len && iobuf.out.len > iobuf.out_empty_len && !(flags & PIO_NEED_MSGROOM))) {
617 if (OUT_MULTIPLEXED && !iobuf.raw_flushing_ends_before) {
618 /* The iobuf.raw_flushing_ends_before value can point off the end
619 * of the iobuf.out buffer for a while, for easier subtracting. */
620 iobuf.raw_flushing_ends_before = iobuf.out.pos + iobuf.out.len;
622 SIVAL(iobuf.out.buf + iobuf.raw_data_header_pos, 0,
623 ((MPLEX_BASE + (int)MSG_DATA)<<24) + iobuf.out.len - 4);
624 if (iobuf.raw_data_header_pos + 4 > iobuf.out.size) {
625 int siz = (int)(iobuf.raw_data_header_pos + 4 - iobuf.out.size);
626 /* We used some of the overflow bytes, so move them. */
627 if (DEBUG_GTE(IO, 4)) {
628 rprintf(FINFO, "[%s] wrap-bytes moved: %d (perform_io)\n",
631 memcpy(iobuf.out.buf, iobuf.out.buf + iobuf.out.size, siz);
634 if (DEBUG_GTE(IO, 1)) {
635 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n",
636 who_am_i(), (int)MSG_DATA, (long)iobuf.out.len - 4);
639 /* reserve room for the next MSG_DATA header */
640 iobuf.raw_data_header_pos = iobuf.raw_flushing_ends_before;
641 if (iobuf.raw_data_header_pos >= iobuf.out.size)
642 iobuf.raw_data_header_pos -= iobuf.out.size;
643 /* Yes, it is possible for this to make len > size for a while. */
647 empty_buf_len = iobuf.out_empty_len;
649 } else if (iobuf.msg.len) {
655 FD_SET(iobuf.out_fd, &w_fds);
656 if (iobuf.out_fd > max_fd)
657 max_fd = iobuf.out_fd;
663 switch (flags & PIO_NEED_FLAGS) {
666 if (kluge_around_eof == 2)
668 if (iobuf.in_fd == -2)
669 whine_about_eof(True);
670 rprintf(FERROR, "error in perform_io: no fd for input.\n");
671 exit_cleanup(RERR_PROTOCOL);
672 case PIO_NEED_OUTROOM:
673 case PIO_NEED_MSGROOM:
675 drain_multiplex_messages();
676 if (iobuf.out_fd == -2)
677 whine_about_eof(True);
678 rprintf(FERROR, "error in perform_io: no fd for output.\n");
679 exit_cleanup(RERR_PROTOCOL);
681 /* No stated needs, so I guess this is OK. */
687 if (extra_flist_sending_enabled) {
688 if (file_total - file_old_total < MAX_FILECNT_LOOKAHEAD)
691 extra_flist_sending_enabled = False;
692 tv.tv_sec = select_timeout;
695 tv.tv_sec = select_timeout;
698 cnt = select(max_fd + 1, &r_fds, &w_fds, &e_fds, &tv);
701 if (cnt < 0 && errno == EBADF) {
703 exit_cleanup(RERR_SOCKETIO);
705 if (extra_flist_sending_enabled) {
706 extra_flist_sending_enabled = False;
707 send_extra_file_list(sock_f_out, -1);
708 extra_flist_sending_enabled = !flist_eof;
711 FD_ZERO(&r_fds); /* Just in case... */
715 if (iobuf.in_fd >= 0 && FD_ISSET(iobuf.in_fd, &r_fds)) {
716 size_t pos = iobuf.in.pos + iobuf.in.len;
717 size_t len = iobuf.in.size - pos;
719 if ((n = read(iobuf.in_fd, iobuf.in.buf + pos, len)) <= 0) {
721 /* Signal that input has become invalid. */
722 if (!read_batch || batch_fd < 0 || am_generator)
727 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
730 /* Don't write errors on a dead socket. */
731 if (iobuf.in_fd == sock_f_in) {
734 rsyserr(FERROR_SOCKET, errno, "read error");
736 rsyserr(FERROR, errno, "read error");
737 exit_cleanup(RERR_STREAMIO);
740 if (msgs2stderr && DEBUG_GTE(IO, 2))
741 rprintf(FINFO, "[%s] recv=%ld\n", who_am_i(), (long)n);
744 last_io_in = time(NULL);
745 stats.total_read += n;
750 if (iobuf.out_fd >= 0 && FD_ISSET(iobuf.out_fd, &w_fds)) {
751 size_t len = iobuf.raw_flushing_ends_before ? iobuf.raw_flushing_ends_before - out->pos : out->len;
754 if (bwlimit_writemax && len > bwlimit_writemax)
755 len = bwlimit_writemax;
757 if (out->pos + len > out->size)
758 len = out->size - out->pos;
759 if ((n = write(iobuf.out_fd, out->buf + out->pos, len)) <= 0) {
760 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
763 /* Don't write errors on a dead socket. */
766 iobuf.out.len = iobuf.msg.len = iobuf.raw_flushing_ends_before = 0;
767 rsyserr(FERROR_SOCKET, errno, "[%s] write error", who_am_i());
768 drain_multiplex_messages();
769 exit_cleanup(RERR_STREAMIO);
772 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
773 rprintf(FINFO, "[%s] %s sent=%ld\n",
774 who_am_i(), out == &iobuf.out ? "out" : "msg", (long)n);
778 last_io_out = time(NULL);
779 stats.total_written += n;
781 if (bwlimit_writemax)
782 sleep_for_bwlimit(n);
784 if ((out->pos += n) == out->size) {
785 if (iobuf.raw_flushing_ends_before)
786 iobuf.raw_flushing_ends_before -= out->size;
788 } else if (out->pos == iobuf.raw_flushing_ends_before)
789 iobuf.raw_flushing_ends_before = 0;
790 if ((out->len -= n) == empty_buf_len) {
793 iobuf.raw_data_header_pos = 0;
797 if (ff_forward_fd >= 0 && FD_ISSET(ff_forward_fd, &r_fds)) {
798 /* This can potentially flush all output and enable
799 * multiplexed output, so keep this last in the loop
800 * and be sure to not cache anything that would break
802 forward_filesfrom_data();
807 data = iobuf.in.buf + iobuf.in.pos;
809 if (flags & PIO_CONSUME_INPUT) {
810 iobuf.in.len -= needed;
811 iobuf.in.pos += needed;
817 void noop_io_until_death(void)
821 kluge_around_eof = 2;
822 /* For protocol 31: setting an I/O timeout ensures that if something
823 * inexplicably weird happens, we won't hang around forever. For older
824 * protocols: we can't tell the other side to die, so we linger a brief
825 * time (to try to give our error messages time to arrive) and then let
826 * the "unexpectedly" closed socket tell them to die. */
827 set_io_timeout(protocol_version >= 31 ? 30 : 1);
830 read_buf(iobuf.in_fd, buf, sizeof buf);
833 /* Buffer a message for the multiplexed output stream. Is never used for MSG_DATA. */
834 int send_msg(enum msgcode code, const char *buf, size_t len, int convert)
838 BOOL want_debug = DEBUG_GTE(IO, 1) && convert >= 0 && (msgs2stderr || code != MSG_INFO);
840 if (!OUT_MULTIPLEXED)
844 rprintf(FINFO, "[%s] send_msg(%d, %ld)\n", who_am_i(), (int)code, (long)len);
847 if (convert > 0 && ic_send == (iconv_t)-1)
850 /* Ensuring double-size room leaves space for maximal conversion expansion. */
851 if (iobuf.msg.len + len*2 + 4 > iobuf.msg.size)
852 perform_io(len*2 + 4, PIO_NEED_MSGROOM);
855 if (iobuf.msg.len + len + 4 > iobuf.msg.size)
856 perform_io(len + 4, PIO_NEED_MSGROOM);
858 pos = iobuf.msg.pos + iobuf.msg.len; /* Must be set after any flushing. */
859 if (pos >= iobuf.msg.size)
860 pos -= iobuf.msg.size;
861 hdr = iobuf.msg.buf + pos;
863 iobuf.msg.len += 4; /* Allocate room for the coming header bytes. */
869 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
872 iconvbufs(ic_send, &inbuf, &iobuf.msg,
873 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_CIRCULAR_OUT | ICB_INIT);
875 rprintf(FERROR, "overflowed iobuf.msg buffer in send_msg");
876 exit_cleanup(RERR_UNSUPPORTED);
878 len = iobuf.msg.len - len;
884 if ((pos += 4) >= iobuf.msg.size)
885 pos -= iobuf.msg.size;
887 /* Handle a split copy if we wrap around the end of the circular buffer. */
888 if (pos >= iobuf.msg.pos && (siz = iobuf.msg.size - pos) < len) {
889 memcpy(iobuf.msg.buf + pos, buf, siz);
890 memcpy(iobuf.msg.buf, buf + siz, len - siz);
892 memcpy(iobuf.msg.buf + pos, buf, len);
894 iobuf.msg.len += len;
897 SIVAL(hdr, 0, ((MPLEX_BASE + (int)code)<<24) + len);
898 /* If the header used any overflow bytes, move them to the start. */
899 if ((pos = hdr+4 - iobuf.msg.buf) > iobuf.msg.size) {
900 int siz = (int)(pos - iobuf.msg.size);
901 if (DEBUG_GTE(IO, 4))
902 rprintf(FINFO, "[%s] wrap-bytes moved: %d (send_msg)\n", who_am_i(), siz);
903 memcpy(iobuf.msg.buf, iobuf.msg.buf + iobuf.msg.size, siz);
906 if (want_debug && convert > 0)
907 rprintf(FINFO, "[%s] converted msg len=%ld\n", who_am_i(), (long)len);
912 void send_msg_int(enum msgcode code, int num)
916 if (DEBUG_GTE(IO, 1))
917 rprintf(FINFO, "[%s] send_msg_int(%d, %d)\n", who_am_i(), (int)code, num);
919 SIVAL(numbuf, 0, num);
920 send_msg(code, numbuf, 4, -1);
923 static void got_flist_entry_status(enum festatus status, int ndx)
925 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
927 if (remove_source_files) {
929 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
933 flist->in_progress--;
937 if (remove_source_files)
938 send_msg_int(MSG_SUCCESS, ndx);
939 if (preserve_hard_links) {
940 struct file_struct *file = flist->files[ndx - flist->ndx_start];
941 if (F_IS_HLINKED(file)) {
942 flist_ndx_push(&hlink_list, ndx);
943 flist->in_progress++;
950 flist->in_progress++;
955 flist_ndx_push(&redo_list, ndx);
962 /* Note the fds used for the main socket (which might really be a pipe
963 * for a local transfer, but we can ignore that). */
964 void io_set_sock_fds(int f_in, int f_out)
970 void set_io_timeout(int secs)
974 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
975 select_timeout = SELECT_TIMEOUT;
977 select_timeout = io_timeout;
979 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
982 static void check_for_d_option_error(const char *msg)
984 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
989 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
992 msg += sizeof REMOTE_OPTION_ERROR - 1;
993 if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
994 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
997 for ( ; *msg != ':'; msg++) {
1000 else if (*msg == 'e')
1002 else if (strchr(rsync263_opts, *msg) == NULL)
1008 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
1012 /* This is used by the generator to limit how many file transfers can
1013 * be active at once when --remove-source-files is specified. Without
1014 * this, sender-side deletions were mostly happening at the end. */
1015 void increment_active_files(int ndx, int itemizing, enum logcode code)
1018 /* TODO: tune these limits? */
1019 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
1020 if (active_filecnt < limit)
1022 check_for_finished_files(itemizing, code, 0);
1023 if (active_filecnt < limit)
1025 wait_for_receiver();
1029 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
1032 int get_redo_num(void)
1034 return flist_ndx_pop(&redo_list);
1037 int get_hlink_num(void)
1039 return flist_ndx_pop(&hlink_list);
1042 /* When we're the receiver and we have a local --files-from list of names
1043 * that needs to be sent over the socket to the sender, we have to do two
1044 * things at the same time: send the sender a list of what files we're
1045 * processing and read the incoming file+info list from the sender. We do
1046 * this by making recv_file_list() call forward_filesfrom_data(), which
1047 * will ensure that we forward data to the sender until we get some data
1048 * for recv_file_list() to use. */
1049 void start_filesfrom_forwarding(int fd)
1051 if (protocol_version < 31 && OUT_MULTIPLEXED) {
1052 /* Older protocols send the files-from data w/o packaging
1053 * it in multiplexed I/O packets, so temporarily switch
1054 * to buffered I/O to match this behavior. */
1055 iobuf.msg.pos = iobuf.msg.len = 0; /* Be extra sure no messages go out. */
1056 ff_reenable_multiplex = io_end_multiplex_out(MPLX_TO_BUFFERED);
1060 alloc_xbuf(&ff_xb, FILESFROM_BUFLEN);
1063 /* Read a line into the "buf" buffer. */
1064 int read_line(int fd, char *buf, size_t bufsiz, int flags)
1069 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
1070 realloc_xbuf(&iconv_buf, bufsiz + 1024);
1075 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
1079 eob = s + bufsiz - 1;
1081 /* We avoid read_byte() for files because files can return an EOF. */
1082 if (fd == iobuf.in_fd)
1084 else if (safe_read(fd, &ch, 1) == 0)
1086 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
1087 /* Skip empty lines if dumping comments. */
1088 if (flags & RL_DUMP_COMMENTS && s == buf)
1097 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
1101 if (flags & RL_CONVERT) {
1103 INIT_XBUF(outbuf, buf, 0, bufsiz);
1105 iconv_buf.len = s - iconv_buf.buf;
1106 iconvbufs(ic_recv, &iconv_buf, &outbuf,
1107 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE | ICB_INIT);
1108 outbuf.buf[outbuf.len] = '\0';
1116 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
1117 char ***argv_p, int *argc_p, char **request_p)
1119 int maxargs = MAX_ARGS;
1123 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
1126 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
1129 if (!(argv = new_array(char *, maxargs)))
1130 out_of_memory("read_args");
1131 if (mod_name && !protect_args)
1132 argv[argc++] = "rsyncd";
1135 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
1138 if (argc == maxargs-1) {
1139 maxargs += MAX_ARGS;
1140 if (!(argv = realloc_array(argv, char *, maxargs)))
1141 out_of_memory("read_args");
1146 *request_p = strdup(buf);
1150 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
1152 glob_expand(buf, &argv, &argc, &maxargs);
1154 if (!(p = strdup(buf)))
1155 out_of_memory("read_args");
1157 if (*p == '.' && p[1] == '\0')
1163 glob_expand(NULL, NULL, NULL, NULL);
1169 BOOL io_start_buffering_out(int f_out)
1171 if (msgs2stderr && DEBUG_GTE(IO, 2))
1172 rprintf(FINFO, "[%s] io_start_buffering_out(%d)\n", who_am_i(), f_out);
1174 if (OUT_MULTIPLEXED && !iobuf.msg.buf) {
1175 iobuf.msg.size = IO_BUFFER_SIZE - 4;
1176 if (!(iobuf.msg.buf = new_array(char, iobuf.msg.size + 4)))
1177 out_of_memory("io_start_buffering_out");
1178 iobuf.msg.pos = iobuf.msg.len = 0;
1181 if (iobuf.out.buf) {
1182 if (iobuf.out_fd == -1)
1183 iobuf.out_fd = f_out;
1185 assert(f_out == iobuf.out_fd);
1189 iobuf.out.size = IO_BUFFER_SIZE * 2 - 4;
1190 /* The 4 overflow bytes makes some circular-buffer wrapping operations easier. */
1191 if (!(iobuf.out.buf = new_array(char, iobuf.out.size + 4)))
1192 out_of_memory("io_start_buffering_out");
1193 iobuf.out.pos = iobuf.out.len = 0;
1194 iobuf.out_fd = f_out;
1199 BOOL io_start_buffering_in(int f_in)
1201 if (msgs2stderr && DEBUG_GTE(IO, 2))
1202 rprintf(FINFO, "[%s] io_start_buffering_in(%d)\n", who_am_i(), f_in);
1205 if (iobuf.in_fd == -1)
1208 assert(f_in == iobuf.in_fd);
1212 iobuf.in.size = IO_BUFFER_SIZE;
1213 if (!(iobuf.in.buf = new_array(char, iobuf.in.size)))
1214 out_of_memory("io_start_buffering_in");
1216 iobuf.in.pos = iobuf.in.len = 0;
1223 void io_end_buffering_in(BOOL free_buffers)
1225 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1226 rprintf(FINFO, "[%s] io_end_buffering_in(IOBUF_%s_BUFS)\n",
1227 who_am_i(), free_buffers ? "FREE" : "KEEP");
1231 free_xbuf(&iobuf.in);
1233 iobuf.in.pos = iobuf.in.len = 0;
1238 void io_end_buffering_out(BOOL free_buffers)
1240 if (msgs2stderr && DEBUG_GTE(IO, 2)) {
1241 rprintf(FINFO, "[%s] io_end_buffering_out(IOBUF_%s_BUFS)\n",
1242 who_am_i(), free_buffers ? "FREE" : "KEEP");
1245 io_flush(FULL_FLUSH);
1248 free_xbuf(&iobuf.out);
1249 free_xbuf(&iobuf.msg);
1255 void maybe_flush_socket(int important)
1257 if (flist_eof && iobuf.out.buf && iobuf.out.len > iobuf.out_empty_len
1258 && (important || time(NULL) - last_io_out >= 5))
1259 io_flush(NORMAL_FLUSH);
1262 void maybe_send_keepalive(void)
1264 if (time(NULL) - last_io_out >= allowed_lull) {
1265 if (!iobuf.msg.len && iobuf.out.len == iobuf.out_empty_len) {
1266 if (protocol_version < 29)
1267 return; /* there's nothing we can do */
1268 if (protocol_version >= 30)
1269 send_msg(MSG_NOOP, "", 0, 0);
1271 write_int(iobuf.out_fd, cur_flist->used);
1272 write_shortint(iobuf.out_fd, ITEM_IS_NEW);
1276 perform_io(iobuf.msg.size - iobuf.msg.len + 1, PIO_NEED_MSGROOM);
1277 else if (iobuf.out.len > iobuf.out_empty_len)
1278 io_flush(NORMAL_FLUSH);
1282 void start_flist_forward(int ndx)
1284 write_int(iobuf.out_fd, ndx);
1285 forward_flist_data = 1;
1288 void stop_flist_forward(void)
1290 forward_flist_data = 0;
1293 /* Read a message from a multiplexed source. */
1294 static void read_a_msg(void)
1296 char *data, line[BIGPATHBUFLEN];
1300 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1301 tag = IVAL(data, 0);
1303 msg_bytes = tag & 0xFFFFFF;
1304 tag = (tag >> 24) - MPLEX_BASE;
1306 if (DEBUG_GTE(IO, 1) && (msgs2stderr || tag != MSG_INFO))
1307 rprintf(FINFO, "[%s] got msg=%d, len=%ld\n", who_am_i(), (int)tag, (long)msg_bytes);
1311 assert(iobuf.raw_input_ends_before == 0);
1312 /* Though this does not yet read the data, we do mark where in
1313 * the buffer the msg data will end once it is read. It is
1314 * possible that this points off the end of the buffer, in
1315 * which case the gradual reading of the input stream will
1316 * cause this value to decrease and eventually become real. */
1317 iobuf.raw_input_ends_before = iobuf.in.pos + msg_bytes;
1320 if (msg_bytes != sizeof stats.total_read || !am_generator)
1322 data = perform_io(sizeof stats.total_read, PIO_INPUT_AND_CONSUME);
1323 memcpy((char*)&stats.total_read, data, sizeof stats.total_read);
1326 if (msg_bytes != 4 || !am_generator)
1328 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1329 got_flist_entry_status(FES_REDO, IVAL(data, 0));
1332 if (msg_bytes != 4 || am_sender)
1334 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1335 val = IVAL(data, 0);
1338 send_msg_int(MSG_IO_ERROR, val);
1340 case MSG_IO_TIMEOUT:
1341 if (msg_bytes != 4 || am_server || am_generator)
1343 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1344 val = IVAL(data, 0);
1345 if (!io_timeout || io_timeout > val) {
1346 if (INFO_GTE(MISC, 2))
1347 rprintf(FINFO, "Setting --timeout=%d to match server\n", val);
1348 set_io_timeout(val);
1353 maybe_send_keepalive();
1356 if (msg_bytes >= sizeof line)
1359 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1360 send_msg(MSG_DELETED, line, msg_bytes, 1);
1364 if (ic_recv != (iconv_t)-1) {
1368 int flags = ICB_INCLUDE_BAD | ICB_INIT;
1370 INIT_CONST_XBUF(outbuf, line);
1371 INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
1374 size_t len = msg_bytes > sizeof ibuf - inbuf.len ? sizeof ibuf - inbuf.len : msg_bytes;
1375 memcpy(ibuf + inbuf.len, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1378 if (!(msg_bytes -= len) && !ibuf[inbuf.len-1])
1379 inbuf.len--, add_null = 1;
1380 if (iconvbufs(ic_send, &inbuf, &outbuf, flags) < 0) {
1383 /* Buffer ended with an incomplete char, so move the
1384 * bytes to the start of the buffer and continue. */
1385 memmove(ibuf, ibuf + inbuf.pos, inbuf.len);
1390 if (outbuf.len == outbuf.size)
1392 outbuf.buf[outbuf.len++] = '\0';
1394 msg_bytes = outbuf.len;
1397 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1398 /* A directory name was sent with the trailing null */
1399 if (msg_bytes > 0 && !line[msg_bytes-1])
1400 log_delete(line, S_IFDIR);
1402 line[msg_bytes] = '\0';
1403 log_delete(line, S_IFREG);
1407 if (msg_bytes != 4) {
1409 rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1410 tag, (unsigned long)msg_bytes, who_am_i(),
1411 inc_recurse ? "/inc" : "");
1412 exit_cleanup(RERR_STREAMIO);
1414 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1415 val = IVAL(data, 0);
1417 got_flist_entry_status(FES_SUCCESS, val);
1419 successful_send(val);
1424 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1425 val = IVAL(data, 0);
1427 got_flist_entry_status(FES_NO_SEND, val);
1429 send_msg_int(MSG_NO_SEND, val);
1431 case MSG_ERROR_SOCKET:
1432 case MSG_ERROR_UTF8:
1437 if (tag == MSG_ERROR_SOCKET)
1442 case MSG_ERROR_XFER:
1444 if (msg_bytes >= sizeof line) {
1447 "multiplexing overflow %d:%lu [%s%s]\n",
1448 tag, (unsigned long)msg_bytes, who_am_i(),
1449 inc_recurse ? "/inc" : "");
1450 exit_cleanup(RERR_STREAMIO);
1452 memcpy(line, perform_io(msg_bytes, PIO_INPUT_AND_CONSUME), msg_bytes);
1453 rwrite((enum logcode)tag, line, msg_bytes, !am_generator);
1454 if (first_message) {
1455 if (list_only && !am_sender && tag == 1 && msg_bytes < sizeof line) {
1456 line[msg_bytes] = '\0';
1457 check_for_d_option_error(line);
1462 case MSG_ERROR_EXIT:
1463 if (msg_bytes == 0) {
1464 if (!am_sender && !am_generator) {
1465 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1466 io_flush(FULL_FLUSH);
1469 } else if (msg_bytes == 4) {
1470 data = perform_io(4, PIO_INPUT_AND_CONSUME);
1471 val = IVAL(data, 0);
1472 if (protocol_version >= 31) {
1474 send_msg_int(MSG_ERROR_EXIT, val);
1476 send_msg(MSG_ERROR_EXIT, "", 0, 0);
1480 /* Send a negative linenum so that we don't end up
1481 * with a duplicate exit message. */
1482 _exit_cleanup(val, __FILE__, 0 - __LINE__);
1484 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1485 tag, who_am_i(), inc_recurse ? "/inc" : "");
1486 exit_cleanup(RERR_STREAMIO);
1490 static void drain_multiplex_messages(void)
1492 while (IN_MULTIPLEXED && iobuf.in.len) {
1493 if (iobuf.raw_input_ends_before) {
1494 size_t raw_len = iobuf.raw_input_ends_before - iobuf.in.pos;
1495 iobuf.raw_input_ends_before = 0;
1496 if (raw_len >= iobuf.in.len) {
1500 iobuf.in.pos += raw_len;
1501 iobuf.in.len -= raw_len;
1507 void wait_for_receiver(void)
1509 if (!iobuf.raw_input_ends_before)
1512 if (iobuf.raw_input_ends_before) {
1513 int ndx = read_int(iobuf.in_fd);
1518 if (DEBUG_GTE(FLIST, 3))
1519 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
1525 exit_cleanup(RERR_STREAMIO);
1528 struct file_list *flist;
1529 if (DEBUG_GTE(FLIST, 2)) {
1530 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
1533 flist = recv_file_list(iobuf.in_fd);
1534 flist->parent_ndx = ndx;
1535 #ifdef SUPPORT_HARD_LINKS
1536 if (preserve_hard_links)
1537 match_hard_links(flist);
1543 unsigned short read_shortint(int f)
1547 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1550 int32 read_int(int f)
1557 #if SIZEOF_INT32 > 4
1558 if (num & (int32)0x80000000)
1559 num |= ~(int32)0xffffffff;
1564 int32 read_varint(int f)
1575 extra = int_byte_extra[ch / 4];
1577 uchar bit = ((uchar)1<<(8-extra));
1578 if (extra >= (int)sizeof u.b) {
1579 rprintf(FERROR, "Overflow in read_varint()\n");
1580 exit_cleanup(RERR_STREAMIO);
1582 read_buf(f, u.b, extra);
1583 u.b[extra] = ch & (bit-1);
1586 #if CAREFUL_ALIGNMENT
1589 #if SIZEOF_INT32 > 4
1590 if (u.x & (int32)0x80000000)
1591 u.x |= ~(int32)0xffffffff;
1596 int64 read_varlong(int f, uchar min_bytes)
1605 #if SIZEOF_INT64 < 8
1610 read_buf(f, b2, min_bytes);
1611 memcpy(u.b, b2+1, min_bytes-1);
1612 extra = int_byte_extra[CVAL(b2, 0) / 4];
1614 uchar bit = ((uchar)1<<(8-extra));
1615 if (min_bytes + extra > (int)sizeof u.b) {
1616 rprintf(FERROR, "Overflow in read_varlong()\n");
1617 exit_cleanup(RERR_STREAMIO);
1619 read_buf(f, u.b + min_bytes - 1, extra);
1620 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1621 #if SIZEOF_INT64 < 8
1622 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1623 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1624 exit_cleanup(RERR_UNSUPPORTED);
1628 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1629 #if SIZEOF_INT64 < 8
1631 #elif CAREFUL_ALIGNMENT
1632 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1637 int64 read_longint(int f)
1639 #if SIZEOF_INT64 >= 8
1642 int32 num = read_int(f);
1644 if (num != (int32)0xffffffff)
1647 #if SIZEOF_INT64 < 8
1648 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1649 exit_cleanup(RERR_UNSUPPORTED);
1652 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1656 void read_buf(int f, char *buf, size_t len)
1658 if (f != iobuf.in_fd) {
1659 if (safe_read(f, buf, len) != len)
1660 whine_about_eof(False); /* Doesn't return. */
1664 if (!IN_MULTIPLEXED) {
1665 memcpy(buf, perform_io(len, PIO_INPUT_AND_CONSUME), len);
1666 total_data_read += len;
1667 if (forward_flist_data)
1668 write_buf(iobuf.out_fd, buf, len);
1670 if (f == write_batch_monitor_in)
1671 safe_write(batch_fd, buf, len);
1679 while (!iobuf.raw_input_ends_before)
1682 siz = MIN(len, iobuf.raw_input_ends_before - iobuf.in.pos);
1683 data = perform_io(siz, PIO_INPUT_AND_CONSUME);
1684 if (iobuf.in.pos == iobuf.raw_input_ends_before)
1685 iobuf.raw_input_ends_before = 0;
1687 /* The bytes at the "data" pointer will survive long
1688 * enough to make a copy, but not past future I/O. */
1689 memcpy(buf, data, siz);
1690 total_data_read += siz;
1692 if (forward_flist_data)
1693 write_buf(iobuf.out_fd, buf, siz);
1695 if (f == write_batch_monitor_in)
1696 safe_write(batch_fd, buf, siz);
1698 if ((len -= siz) == 0)
1704 void read_sbuf(int f, char *buf, size_t len)
1706 read_buf(f, buf, len);
1710 uchar read_byte(int f)
1713 read_buf(f, (char*)&c, 1);
1717 int read_vstring(int f, char *buf, int bufsize)
1719 int len = read_byte(f);
1722 len = (len & ~0x80) * 0x100 + read_byte(f);
1724 if (len >= bufsize) {
1725 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1731 read_buf(f, buf, len);
1736 /* Populate a sum_struct with values from the socket. This is
1737 * called by both the sender and the receiver. */
1738 void read_sum_head(int f, struct sum_struct *sum)
1740 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1741 sum->count = read_int(f);
1742 if (sum->count < 0) {
1743 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1744 (long)sum->count, who_am_i());
1745 exit_cleanup(RERR_PROTOCOL);
1747 sum->blength = read_int(f);
1748 if (sum->blength < 0 || sum->blength > max_blength) {
1749 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1750 (long)sum->blength, who_am_i());
1751 exit_cleanup(RERR_PROTOCOL);
1753 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1754 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1755 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1756 sum->s2length, who_am_i());
1757 exit_cleanup(RERR_PROTOCOL);
1759 sum->remainder = read_int(f);
1760 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1761 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1762 (long)sum->remainder, who_am_i());
1763 exit_cleanup(RERR_PROTOCOL);
1767 /* Send the values from a sum_struct over the socket. Set sum to
1768 * NULL if there are no checksums to send. This is called by both
1769 * the generator and the sender. */
1770 void write_sum_head(int f, struct sum_struct *sum)
1772 static struct sum_struct null_sum;
1777 write_int(f, sum->count);
1778 write_int(f, sum->blength);
1779 if (protocol_version >= 27)
1780 write_int(f, sum->s2length);
1781 write_int(f, sum->remainder);
1784 /* Sleep after writing to limit I/O bandwidth usage.
1786 * @todo Rather than sleeping after each write, it might be better to
1787 * use some kind of averaging. The current algorithm seems to always
1788 * use a bit less bandwidth than specified, because it doesn't make up
1789 * for slow periods. But arguably this is a feature. In addition, we
1790 * ought to take the time used to write the data into account.
1792 * During some phases of big transfers (file FOO is uptodate) this is
1793 * called with a small bytes_written every time. As the kernel has to
1794 * round small waits up to guarantee that we actually wait at least the
1795 * requested number of microseconds, this can become grossly inaccurate.
1796 * We therefore keep track of the bytes we've written over time and only
1797 * sleep when the accumulated delay is at least 1 tenth of a second. */
1798 static void sleep_for_bwlimit(int bytes_written)
1800 static struct timeval prior_tv;
1801 static long total_written = 0;
1802 struct timeval tv, start_tv;
1803 long elapsed_usec, sleep_usec;
1805 #define ONE_SEC 1000000L /* # of microseconds in a second */
1807 total_written += bytes_written;
1809 gettimeofday(&start_tv, NULL);
1810 if (prior_tv.tv_sec) {
1811 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1812 + (start_tv.tv_usec - prior_tv.tv_usec);
1813 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1814 if (total_written < 0)
1818 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1819 if (sleep_usec < ONE_SEC / 10) {
1820 prior_tv = start_tv;
1824 tv.tv_sec = sleep_usec / ONE_SEC;
1825 tv.tv_usec = sleep_usec % ONE_SEC;
1826 select(0, NULL, NULL, NULL, &tv);
1828 gettimeofday(&prior_tv, NULL);
1829 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1830 + (prior_tv.tv_usec - start_tv.tv_usec);
1831 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1834 void io_flush(int flush_it_all)
1836 if (iobuf.out.len > iobuf.out_empty_len) {
1837 if (flush_it_all) /* FULL_FLUSH: flush everything in the output buffers */
1838 perform_io(iobuf.out.size - iobuf.out_empty_len, PIO_NEED_OUTROOM);
1839 else /* NORMAL_FLUSH: flush at least 1 byte */
1840 perform_io(iobuf.out.size - iobuf.out.len + 1, PIO_NEED_OUTROOM);
1843 perform_io(iobuf.msg.size, PIO_NEED_MSGROOM);
1846 void write_shortint(int f, unsigned short x)
1850 b[1] = (char)(x >> 8);
1854 void write_int(int f, int32 x)
1861 void write_varint(int f, int32 x)
1869 while (cnt > 1 && b[cnt] == 0)
1871 bit = ((uchar)1<<(7-cnt+1));
1872 if (CVAL(b, cnt) >= bit) {
1876 *b = b[cnt] | ~(bit*2-1);
1880 write_buf(f, b, cnt);
1883 void write_varlong(int f, int64 x, uchar min_bytes)
1890 #if SIZEOF_INT64 >= 8
1891 SIVAL(b, 5, x >> 32);
1893 if (x <= 0x7FFFFFFF && x >= 0)
1894 memset(b + 5, 0, 4);
1896 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1897 exit_cleanup(RERR_UNSUPPORTED);
1901 while (cnt > min_bytes && b[cnt] == 0)
1903 bit = ((uchar)1<<(7-cnt+min_bytes));
1904 if (CVAL(b, cnt) >= bit) {
1907 } else if (cnt > min_bytes)
1908 *b = b[cnt] | ~(bit*2-1);
1912 write_buf(f, b, cnt);
1916 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1917 * 64-bit types on this platform.
1919 void write_longint(int f, int64 x)
1921 char b[12], * const s = b+4;
1924 if (x <= 0x7FFFFFFF && x >= 0) {
1929 #if SIZEOF_INT64 < 8
1930 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1931 exit_cleanup(RERR_UNSUPPORTED);
1934 SIVAL(s, 4, x >> 32);
1935 write_buf(f, b, 12);
1939 void write_buf(int f, const char *buf, size_t len)
1943 if (f != iobuf.out_fd) {
1944 safe_write(f, buf, len);
1948 if (iobuf.out.len + len > iobuf.out.size)
1949 perform_io(len, PIO_NEED_OUTROOM);
1951 pos = iobuf.out.pos + iobuf.out.len; /* Must be set after any flushing. */
1952 if (pos >= iobuf.out.size)
1953 pos -= iobuf.out.size;
1955 /* Handle a split copy if we wrap around the end of the circular buffer. */
1956 if (pos >= iobuf.out.pos && (siz = iobuf.out.size - pos) < len) {
1957 memcpy(iobuf.out.buf + pos, buf, siz);
1958 memcpy(iobuf.out.buf, buf + siz, len - siz);
1960 memcpy(iobuf.out.buf + pos, buf, len);
1962 iobuf.out.len += len;
1963 total_data_written += len;
1966 if (f == write_batch_monitor_out)
1967 safe_write(batch_fd, buf, len);
1970 /* Write a string to the connection */
1971 void write_sbuf(int f, const char *buf)
1973 write_buf(f, buf, strlen(buf));
1976 void write_byte(int f, uchar c)
1978 write_buf(f, (char *)&c, 1);
1981 void write_vstring(int f, const char *str, int len)
1983 uchar lenbuf[3], *lb = lenbuf;
1988 "attempting to send over-long vstring (%d > %d)\n",
1990 exit_cleanup(RERR_PROTOCOL);
1992 *lb++ = len / 0x100 + 0x80;
1996 write_buf(f, (char*)lenbuf, lb - lenbuf + 1);
1998 write_buf(f, str, len);
2001 /* Send a file-list index using a byte-reduction method. */
2002 void write_ndx(int f, int32 ndx)
2004 static int32 prev_positive = -1, prev_negative = 1;
2005 int32 diff, cnt = 0;
2008 if (protocol_version < 30 || read_batch) {
2013 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
2014 * negative nums as a positive after sending a leading 0xFF. */
2016 diff = ndx - prev_positive;
2017 prev_positive = ndx;
2018 } else if (ndx == NDX_DONE) {
2023 b[cnt++] = (char)0xFF;
2025 diff = ndx - prev_negative;
2026 prev_negative = ndx;
2029 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
2030 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
2031 * & all 4 bytes of the (non-negative) num with the high-bit set. */
2032 if (diff < 0xFE && diff > 0)
2033 b[cnt++] = (char)diff;
2034 else if (diff < 0 || diff > 0x7FFF) {
2035 b[cnt++] = (char)0xFE;
2036 b[cnt++] = (char)((ndx >> 24) | 0x80);
2037 b[cnt++] = (char)ndx;
2038 b[cnt++] = (char)(ndx >> 8);
2039 b[cnt++] = (char)(ndx >> 16);
2041 b[cnt++] = (char)0xFE;
2042 b[cnt++] = (char)(diff >> 8);
2043 b[cnt++] = (char)diff;
2045 write_buf(f, b, cnt);
2048 /* Receive a file-list index using a byte-reduction method. */
2049 int32 read_ndx(int f)
2051 static int32 prev_positive = -1, prev_negative = 1;
2052 int32 *prev_ptr, num;
2055 if (protocol_version < 30)
2059 if (CVAL(b, 0) == 0xFF) {
2061 prev_ptr = &prev_negative;
2062 } else if (CVAL(b, 0) == 0)
2065 prev_ptr = &prev_positive;
2066 if (CVAL(b, 0) == 0xFE) {
2068 if (CVAL(b, 0) & 0x80) {
2069 b[3] = CVAL(b, 0) & ~0x80;
2071 read_buf(f, b+1, 2);
2074 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
2076 num = UVAL(b, 0) + *prev_ptr;
2078 if (prev_ptr == &prev_negative)
2083 /* Read a line of up to bufsiz-1 characters into buf. Strips
2084 * the (required) trailing newline and all carriage returns.
2085 * Returns 1 for success; 0 for I/O error or truncation. */
2086 int read_line_old(int fd, char *buf, size_t bufsiz)
2088 bufsiz--; /* leave room for the null */
2089 while (bufsiz > 0) {
2090 assert(fd != iobuf.in_fd);
2091 if (safe_read(fd, buf, 1) == 0)
2106 void io_printf(int fd, const char *format, ...)
2109 char buf[BIGPATHBUFLEN];
2112 va_start(ap, format);
2113 len = vsnprintf(buf, sizeof buf, format, ap);
2117 exit_cleanup(RERR_STREAMIO);
2119 if (len > (int)sizeof buf) {
2120 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
2121 exit_cleanup(RERR_STREAMIO);
2124 write_sbuf(fd, buf);
2127 /* Setup for multiplexing a MSG_* stream with the data stream. */
2128 void io_start_multiplex_out(int fd)
2130 io_flush(FULL_FLUSH);
2132 if (msgs2stderr && DEBUG_GTE(IO, 2))
2133 rprintf(FINFO, "[%s] io_start_multiplex_out(%d)\n", who_am_i(), fd);
2135 iobuf.out_empty_len = 4; /* See also OUT_MULTIPLEXED */
2136 io_start_buffering_out(fd);
2138 iobuf.raw_data_header_pos = iobuf.out.pos + iobuf.out.len;
2142 /* Setup for multiplexing a MSG_* stream with the data stream. */
2143 void io_start_multiplex_in(int fd)
2145 if (msgs2stderr && DEBUG_GTE(IO, 2))
2146 rprintf(FINFO, "[%s] io_start_multiplex_in(%d)\n", who_am_i(), fd);
2148 iobuf.in_multiplexed = True; /* See also IN_MULTIPLEXED */
2149 io_start_buffering_in(fd);
2152 int io_end_multiplex_in(int mode)
2154 int ret = iobuf.in_multiplexed ? iobuf.in_fd : -1;
2156 if (msgs2stderr && DEBUG_GTE(IO, 2))
2157 rprintf(FINFO, "[%s] io_end_multiplex_in(mode=%d)\n", who_am_i(), mode);
2159 iobuf.in_multiplexed = False;
2160 if (mode == MPLX_SWITCHING)
2161 iobuf.raw_input_ends_before = 0;
2163 assert(iobuf.raw_input_ends_before == 0);
2164 if (mode != MPLX_TO_BUFFERED)
2165 io_end_buffering_in(mode);
2170 int io_end_multiplex_out(int mode)
2172 int ret = iobuf.out_empty_len ? iobuf.out_fd : -1;
2174 if (msgs2stderr && DEBUG_GTE(IO, 2))
2175 rprintf(FINFO, "[%s] io_end_multiplex_out(mode=%d)\n", who_am_i(), mode);
2177 if (mode != MPLX_TO_BUFFERED)
2178 io_end_buffering_out(mode);
2180 io_flush(FULL_FLUSH);
2183 iobuf.out_empty_len = 0;
2188 void start_write_batch(int fd)
2190 /* Some communication has already taken place, but we don't
2191 * enable batch writing until here so that we can write a
2192 * canonical record of the communication even though the
2193 * actual communication so far depends on whether a daemon
2195 write_int(batch_fd, protocol_version);
2196 if (protocol_version >= 30)
2197 write_byte(batch_fd, inc_recurse);
2198 write_int(batch_fd, checksum_seed);
2201 write_batch_monitor_out = fd;
2203 write_batch_monitor_in = fd;
2206 void stop_write_batch(void)
2208 write_batch_monitor_out = -1;
2209 write_batch_monitor_in = -1;