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, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
24 /* Rsync provides its own multiplexing system, which is used to send
25 * stderr and stdout over a single socket.
27 * For historical reasons this is off during the start of the
28 * connection, but it's switched on quite early using
29 * io_start_multiplex_out() and io_start_multiplex_in(). */
33 /** If no timeout is specified then use a 60 second select timeout */
34 #define SELECT_TIMEOUT 60
37 extern size_t bwlimit_writemax;
38 extern int io_timeout;
39 extern int allowed_lull;
43 extern int am_generator;
45 extern int read_batch;
46 extern int csum_length;
47 extern int checksum_seed;
48 extern int protocol_version;
49 extern int remove_source_files;
50 extern int preserve_hard_links;
51 extern char *filesfrom_host;
52 extern struct stats stats;
53 extern struct file_list *the_file_list;
55 const char phase_unknown[] = "unknown";
56 int ignore_timeout = 0;
58 int batch_gen_fd = -1;
60 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
61 int kluge_around_eof = 0;
68 static int io_multiplexing_out;
69 static int io_multiplexing_in;
70 static time_t last_io_in;
71 static time_t last_io_out;
74 static int write_batch_monitor_in = -1;
75 static int write_batch_monitor_out = -1;
77 static int io_filesfrom_f_in = -1;
78 static int io_filesfrom_f_out = -1;
79 static char io_filesfrom_buf[2048];
80 static char *io_filesfrom_bp;
81 static char io_filesfrom_lastchar;
82 static int io_filesfrom_buflen;
83 static int defer_forwarding_messages = 0;
84 static int select_timeout = SELECT_TIMEOUT;
85 static int active_filecnt = 0;
86 static OFF_T active_bytecnt = 0;
88 static char int_byte_cnt[64] = {
89 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (00 - 3F)/4 */
90 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (40 - 7F)/4 */
91 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* (80 - BF)/4 */
92 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 9, /* (C0 - FF)/4 */
95 static void read_loop(int fd, char *buf, size_t len);
97 struct flist_ndx_item {
98 struct flist_ndx_item *next;
102 struct flist_ndx_list {
103 struct flist_ndx_item *head, *tail;
106 static struct flist_ndx_list redo_list, hlink_list;
108 struct msg_list_item {
109 struct msg_list_item *next;
115 struct msg_list_item *head, *tail;
118 static struct msg_list msg2genr, msg2sndr;
120 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
122 struct flist_ndx_item *item;
124 if (!(item = new(struct flist_ndx_item)))
125 out_of_memory("flist_ndx_push");
129 lp->tail->next = item;
135 static int flist_ndx_pop(struct flist_ndx_list *lp)
137 struct flist_ndx_item *next;
144 next = lp->head->next;
153 static void check_timeout(void)
157 if (!io_timeout || ignore_timeout)
161 last_io_in = time(NULL);
167 if (t - last_io_in >= io_timeout) {
168 if (!am_server && !am_daemon) {
169 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
170 (int)(t-last_io_in));
172 exit_cleanup(RERR_TIMEOUT);
176 /* Note the fds used for the main socket (which might really be a pipe
177 * for a local transfer, but we can ignore that). */
178 void io_set_sock_fds(int f_in, int f_out)
184 void set_io_timeout(int secs)
188 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
189 select_timeout = SELECT_TIMEOUT;
191 select_timeout = io_timeout;
193 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
196 /* Setup the fd used to receive MSG_* messages. Only needed during the
197 * early stages of being a local sender (up through the sending of the
198 * file list) or when we're the generator (to fetch the messages from
200 void set_msg_fd_in(int fd)
205 /* Setup the fd used to send our MSG_* messages. Only needed when
206 * we're the receiver (to send our messages to the generator). */
207 void set_msg_fd_out(int fd)
210 set_nonblocking(msg_fd_out);
213 /* Add a message to the pending MSG_* list. */
214 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
216 struct msg_list_item *m;
217 int sz = len + 4 + sizeof m[0] - 1;
219 if (!(m = (struct msg_list_item *)new_array(char, sz)))
220 out_of_memory("msg_list_add");
223 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
224 memcpy(m->buf + 4, buf, len);
232 /* Read a message from the MSG_* fd and handle it. This is called either
233 * during the early stages of being a local sender (up through the sending
234 * of the file list) or when we're the generator (to fetch the messages
235 * from the receiver). */
236 static void read_msg_fd(void)
243 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
244 * to this routine from writefd_unbuffered(). */
247 read_loop(fd, buf, 4);
250 len = tag & 0xFFFFFF;
251 tag = (tag >> 24) - MPLEX_BASE;
255 if (len != 0 || !am_generator) {
256 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
257 exit_cleanup(RERR_STREAMIO);
259 flist_ndx_push(&redo_list, -1);
262 if (len != 4 || !am_generator) {
263 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
264 exit_cleanup(RERR_STREAMIO);
266 read_loop(fd, buf, 4);
267 if (remove_source_files)
268 decrement_active_files(IVAL(buf,0));
269 flist_ndx_push(&redo_list, IVAL(buf,0));
272 if (len >= (int)sizeof buf || !am_generator) {
273 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
274 exit_cleanup(RERR_STREAMIO);
276 read_loop(fd, buf, len);
277 send_msg(MSG_DELETED, buf, len);
280 if (len != 4 || !am_generator) {
281 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
282 exit_cleanup(RERR_STREAMIO);
284 read_loop(fd, buf, len);
285 if (remove_source_files) {
286 decrement_active_files(IVAL(buf,0));
287 send_msg(MSG_SUCCESS, buf, len);
289 if (preserve_hard_links)
290 flist_ndx_push(&hlink_list, IVAL(buf,0));
295 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
296 exit_cleanup(RERR_STREAMIO);
298 if (tag == MSG_SOCKERR)
299 close_multiplexing_out();
308 read_loop(fd, buf, n);
309 rwrite((enum logcode)tag, buf, n);
314 rprintf(FERROR, "unknown message %d:%d [%s]\n",
315 tag, len, who_am_i());
316 exit_cleanup(RERR_STREAMIO);
322 /* This is used by the generator to limit how many file transfers can
323 * be active at once when --remove-source-files is specified. Without
324 * this, sender-side deletions were mostly happening at the end. */
325 void increment_active_files(int ndx, int itemizing, enum logcode code)
327 /* TODO: tune these limits? */
328 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
329 #ifdef SUPPORT_HARD_LINKS
331 check_for_finished_hlinks(itemizing, code);
337 active_bytecnt += F_LENGTH(the_file_list->files[ndx]);
340 void decrement_active_files(int ndx)
343 active_bytecnt -= F_LENGTH(the_file_list->files[ndx]);
346 /* Try to push messages off the list onto the wire. If we leave with more
347 * to do, return 0. On error, return -1. If everything flushed, return 1.
348 * This is only active in the receiver. */
349 static int msg2genr_flush(int flush_it_all)
351 static int written = 0;
358 while (msg2genr.head) {
359 struct msg_list_item *m = msg2genr.head;
360 int n = write(msg_fd_out, m->buf + written, m->len - written);
364 if (errno != EWOULDBLOCK && errno != EAGAIN)
369 FD_SET(msg_fd_out, &fds);
370 tv.tv_sec = select_timeout;
372 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
374 } else if ((written += n) == m->len) {
375 msg2genr.head = m->next;
377 msg2genr.tail = NULL;
385 int send_msg(enum msgcode code, const char *buf, int len)
387 if (msg_fd_out < 0) {
388 if (!defer_forwarding_messages)
389 return io_multiplex_write(code, buf, len);
390 if (!io_multiplexing_out)
392 msg_list_add(&msg2sndr, code, buf, len);
395 msg_list_add(&msg2genr, code, buf, len);
396 msg2genr_flush(NORMAL_FLUSH);
400 void send_msg_int(enum msgcode code, int num)
403 SIVAL(numbuf, 0, num);
404 send_msg(code, numbuf, 4);
407 int get_redo_num(int itemizing, enum logcode code)
410 #ifdef SUPPORT_HARD_LINKS
412 check_for_finished_hlinks(itemizing, code);
419 return flist_ndx_pop(&redo_list);
422 int get_hlink_num(void)
424 return flist_ndx_pop(&hlink_list);
428 * When we're the receiver and we have a local --files-from list of names
429 * that needs to be sent over the socket to the sender, we have to do two
430 * things at the same time: send the sender a list of what files we're
431 * processing and read the incoming file+info list from the sender. We do
432 * this by augmenting the read_timeout() function to copy this data. It
433 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
434 * ready, since it might be a pipe) and then blast it out f_out (when it
435 * is ready to receive more data).
437 void io_set_filesfrom_fds(int f_in, int f_out)
439 io_filesfrom_f_in = f_in;
440 io_filesfrom_f_out = f_out;
441 io_filesfrom_bp = io_filesfrom_buf;
442 io_filesfrom_lastchar = '\0';
443 io_filesfrom_buflen = 0;
446 /* It's almost always an error to get an EOF when we're trying to read from the
447 * network, because the protocol is (for the most part) self-terminating.
449 * There is one case for the receiver when it is at the end of the transfer
450 * (hanging around reading any keep-alive packets that might come its way): if
451 * the sender dies before the generator's kill-signal comes through, we can end
452 * up here needing to loop until the kill-signal arrives. In this situation,
453 * kluge_around_eof will be < 0.
455 * There is another case for older protocol versions (< 24) where the module
456 * listing was not terminated, so we must ignore an EOF error in that case and
457 * exit. In this situation, kluge_around_eof will be > 0. */
458 static void whine_about_eof(int fd)
460 if (kluge_around_eof && fd == sock_f_in) {
462 if (kluge_around_eof > 0)
464 /* If we're still here after 10 seconds, exit with an error. */
465 for (i = 10*1000/20; i--; )
469 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
470 "(%.0f bytes received so far) [%s]\n",
471 (double)stats.total_read, who_am_i());
473 exit_cleanup(RERR_STREAMIO);
477 * Read from a socket with I/O timeout. return the number of bytes
478 * read. If no bytes can be read then exit, never return a number <= 0.
480 * TODO: If the remote shell connection fails, then current versions
481 * actually report an "unexpected EOF" error here. Since it's a
482 * fairly common mistake to try to use rsh when ssh is required, we
483 * should trap that: if we fail to read any data at all, we should
484 * give a better explanation. We can tell whether the connection has
485 * started by looking e.g. at whether the remote version is known yet.
487 static int read_timeout(int fd, char *buf, size_t len)
491 io_flush(NORMAL_FLUSH);
494 /* until we manage to read *something* */
504 FD_SET(msg_fd_out, &w_fds);
505 if (msg_fd_out > maxfd)
508 if (io_filesfrom_f_out >= 0) {
510 if (io_filesfrom_buflen == 0) {
511 if (io_filesfrom_f_in >= 0) {
512 FD_SET(io_filesfrom_f_in, &r_fds);
513 new_fd = io_filesfrom_f_in;
515 io_filesfrom_f_out = -1;
519 FD_SET(io_filesfrom_f_out, &w_fds);
520 new_fd = io_filesfrom_f_out;
526 tv.tv_sec = select_timeout;
531 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
535 exit_cleanup(RERR_SOCKETIO);
540 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
541 msg2genr_flush(NORMAL_FLUSH);
543 if (io_filesfrom_f_out >= 0) {
544 if (io_filesfrom_buflen) {
545 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
546 int l = write(io_filesfrom_f_out,
548 io_filesfrom_buflen);
550 if (!(io_filesfrom_buflen -= l))
551 io_filesfrom_bp = io_filesfrom_buf;
553 io_filesfrom_bp += l;
555 /* XXX should we complain? */
556 io_filesfrom_f_out = -1;
559 } else if (io_filesfrom_f_in >= 0) {
560 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
561 int l = read(io_filesfrom_f_in,
563 sizeof io_filesfrom_buf);
565 /* Send end-of-file marker */
566 io_filesfrom_buf[0] = '\0';
567 io_filesfrom_buf[1] = '\0';
568 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
569 io_filesfrom_f_in = -1;
572 char *s = io_filesfrom_buf + l;
573 /* Transform CR and/or LF into '\0' */
574 while (s-- > io_filesfrom_buf) {
575 if (*s == '\n' || *s == '\r')
579 if (!io_filesfrom_lastchar) {
580 /* Last buf ended with a '\0', so don't
581 * let this buf start with one. */
582 while (l && !*io_filesfrom_bp)
583 io_filesfrom_bp++, l--;
586 io_filesfrom_bp = io_filesfrom_buf;
588 char *f = io_filesfrom_bp;
591 /* Eliminate any multi-'\0' runs. */
593 if (!(*t++ = *f++)) {
594 while (f != eob && !*f)
598 io_filesfrom_lastchar = f[-1];
600 io_filesfrom_buflen = l;
606 if (!FD_ISSET(fd, &r_fds))
609 n = read(fd, buf, len);
613 whine_about_eof(fd); /* Doesn't return. */
614 if (errno == EINTR || errno == EWOULDBLOCK
618 /* Don't write errors on a dead socket. */
619 if (fd == sock_f_in) {
620 close_multiplexing_out();
621 rsyserr(FSOCKERR, errno, "read error");
623 rsyserr(FERROR, errno, "read error");
624 exit_cleanup(RERR_STREAMIO);
631 if (fd == sock_f_in && io_timeout)
632 last_io_in = time(NULL);
639 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
642 int read_filesfrom_line(int fd, char *fname)
644 char ch, *s, *eob = fname + MAXPATHLEN - 1;
646 int reading_remotely = filesfrom_host != NULL;
647 int nulls = eol_nulls || reading_remotely;
652 cnt = read(fd, &ch, 1);
653 if (cnt < 0 && (errno == EWOULDBLOCK
654 || errno == EINTR || errno == EAGAIN)) {
661 tv.tv_sec = select_timeout;
663 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
665 if (FD_ISSET(fd, &e_fds)) {
666 rsyserr(FINFO, errno,
667 "select exception on fd %d", fd);
673 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
674 /* Skip empty lines if reading locally. */
675 if (!reading_remotely && s == fname)
685 if (*fname == '#' || *fname == ';')
691 static char *iobuf_out;
692 static int iobuf_out_cnt;
694 void io_start_buffering_out(void)
698 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
699 out_of_memory("io_start_buffering_out");
703 static char *iobuf_in;
704 static size_t iobuf_in_siz;
706 void io_start_buffering_in(void)
710 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
711 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
712 out_of_memory("io_start_buffering_in");
715 void io_end_buffering(void)
717 io_flush(NORMAL_FLUSH);
718 if (!io_multiplexing_out) {
724 void maybe_flush_socket(void)
726 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
727 io_flush(NORMAL_FLUSH);
730 void maybe_send_keepalive(void)
732 if (time(NULL) - last_io_out >= allowed_lull) {
733 if (!iobuf_out || !iobuf_out_cnt) {
734 if (protocol_version < 29)
735 return; /* there's nothing we can do */
736 write_int(sock_f_out, the_file_list->count);
737 write_shortint(sock_f_out, ITEM_IS_NEW);
740 io_flush(NORMAL_FLUSH);
745 * Continue trying to read len bytes - don't return until len has been
748 static void read_loop(int fd, char *buf, size_t len)
751 int n = read_timeout(fd, buf, len);
759 * Read from the file descriptor handling multiplexing - return number
762 * Never returns <= 0.
764 static int readfd_unbuffered(int fd, char *buf, size_t len)
766 static size_t remaining;
767 static size_t iobuf_in_ndx;
770 char line[BIGPATHBUFLEN];
772 if (!iobuf_in || fd != sock_f_in)
773 return read_timeout(fd, buf, len);
775 if (!io_multiplexing_in && remaining == 0) {
776 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
782 len = MIN(len, remaining);
783 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
790 read_loop(fd, line, 4);
793 msg_bytes = tag & 0xFFFFFF;
794 tag = (tag >> 24) - MPLEX_BASE;
798 if (msg_bytes > iobuf_in_siz) {
799 if (!(iobuf_in = realloc_array(iobuf_in, char,
801 out_of_memory("readfd_unbuffered");
802 iobuf_in_siz = msg_bytes;
804 read_loop(fd, iobuf_in, msg_bytes);
805 remaining = msg_bytes;
809 if (msg_bytes >= sizeof line)
811 read_loop(fd, line, msg_bytes);
812 /* A directory name was sent with the trailing null */
813 if (msg_bytes > 0 && !line[msg_bytes-1])
814 log_delete(line, S_IFDIR);
816 line[msg_bytes] = '\0';
817 log_delete(line, S_IFREG);
821 if (msg_bytes != 4) {
822 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
823 tag, (long)msg_bytes, who_am_i());
824 exit_cleanup(RERR_STREAMIO);
826 read_loop(fd, line, msg_bytes);
827 successful_send(IVAL(line, 0));
831 if (msg_bytes >= sizeof line) {
834 "multiplexing overflow %d:%ld [%s]\n",
835 tag, (long)msg_bytes, who_am_i());
836 exit_cleanup(RERR_STREAMIO);
838 read_loop(fd, line, msg_bytes);
839 rwrite((enum logcode)tag, line, msg_bytes);
842 rprintf(FERROR, "unexpected tag %d [%s]\n",
844 exit_cleanup(RERR_STREAMIO);
849 io_flush(NORMAL_FLUSH);
855 * Do a buffered read from @p fd. Don't return until all @p n bytes
856 * have been read. If all @p n can't be read then exit with an
859 static void readfd(int fd, char *buffer, size_t N)
865 cnt = readfd_unbuffered(fd, buffer + total, N-total);
869 if (fd == write_batch_monitor_in) {
870 if ((size_t)write(batch_fd, buffer, total) != total)
871 exit_cleanup(RERR_FILEIO);
875 stats.total_read += total;
878 unsigned short read_shortint(int f)
882 return (UVAL(b, 1) << 8) + UVAL(b, 0);
885 int32 read_int(int f)
893 if (num & (int32)0x80000000)
894 num |= ~(int32)0xffffffff;
899 int64 read_longint(int f)
904 if (protocol_version < 30) {
907 if ((int32)num != (int32)0xffffffff)
911 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
912 exit_cleanup(RERR_UNSUPPORTED);
915 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
920 cnt = int_byte_cnt[CVAL(b, 0) / 4];
922 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
923 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
924 exit_cleanup(RERR_UNSUPPORTED);
928 readfd(f, b + 3, cnt - 3);
934 num = NVAL4(b, 0x80);
937 num = NVAL5(b, 0xC0);
939 #if SIZEOF_INT64 >= 8
941 num = NVAL6(b, 0xE0);
944 num = NVAL7(b, 0xF0);
947 num = NVAL8(b, 0xF8);
954 exit_cleanup(RERR_PROTOCOL); /* impossible... */
961 void read_buf(int f, char *buf, size_t len)
966 void read_sbuf(int f, char *buf, size_t len)
972 uchar read_byte(int f)
975 readfd(f, (char *)&c, 1);
979 int read_vstring(int f, char *buf, int bufsize)
981 int len = read_byte(f);
984 len = (len & ~0x80) * 0x100 + read_byte(f);
986 if (len >= bufsize) {
987 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
998 /* Populate a sum_struct with values from the socket. This is
999 * called by both the sender and the receiver. */
1000 void read_sum_head(int f, struct sum_struct *sum)
1002 sum->count = read_int(f);
1003 if (sum->count < 0) {
1004 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1005 (long)sum->count, who_am_i());
1006 exit_cleanup(RERR_PROTOCOL);
1008 sum->blength = read_int(f);
1009 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1010 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1011 (long)sum->blength, who_am_i());
1012 exit_cleanup(RERR_PROTOCOL);
1014 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1015 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1016 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1017 sum->s2length, who_am_i());
1018 exit_cleanup(RERR_PROTOCOL);
1020 sum->remainder = read_int(f);
1021 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1022 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1023 (long)sum->remainder, who_am_i());
1024 exit_cleanup(RERR_PROTOCOL);
1028 /* Send the values from a sum_struct over the socket. Set sum to
1029 * NULL if there are no checksums to send. This is called by both
1030 * the generator and the sender. */
1031 void write_sum_head(int f, struct sum_struct *sum)
1033 static struct sum_struct null_sum;
1038 write_int(f, sum->count);
1039 write_int(f, sum->blength);
1040 if (protocol_version >= 27)
1041 write_int(f, sum->s2length);
1042 write_int(f, sum->remainder);
1046 * Sleep after writing to limit I/O bandwidth usage.
1048 * @todo Rather than sleeping after each write, it might be better to
1049 * use some kind of averaging. The current algorithm seems to always
1050 * use a bit less bandwidth than specified, because it doesn't make up
1051 * for slow periods. But arguably this is a feature. In addition, we
1052 * ought to take the time used to write the data into account.
1054 * During some phases of big transfers (file FOO is uptodate) this is
1055 * called with a small bytes_written every time. As the kernel has to
1056 * round small waits up to guarantee that we actually wait at least the
1057 * requested number of microseconds, this can become grossly inaccurate.
1058 * We therefore keep track of the bytes we've written over time and only
1059 * sleep when the accumulated delay is at least 1 tenth of a second.
1061 static void sleep_for_bwlimit(int bytes_written)
1063 static struct timeval prior_tv;
1064 static long total_written = 0;
1065 struct timeval tv, start_tv;
1066 long elapsed_usec, sleep_usec;
1068 #define ONE_SEC 1000000L /* # of microseconds in a second */
1070 if (!bwlimit_writemax)
1073 total_written += bytes_written;
1075 gettimeofday(&start_tv, NULL);
1076 if (prior_tv.tv_sec) {
1077 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1078 + (start_tv.tv_usec - prior_tv.tv_usec);
1079 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1080 if (total_written < 0)
1084 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1085 if (sleep_usec < ONE_SEC / 10) {
1086 prior_tv = start_tv;
1090 tv.tv_sec = sleep_usec / ONE_SEC;
1091 tv.tv_usec = sleep_usec % ONE_SEC;
1092 select(0, NULL, NULL, NULL, &tv);
1094 gettimeofday(&prior_tv, NULL);
1095 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1096 + (prior_tv.tv_usec - start_tv.tv_usec);
1097 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1100 /* Write len bytes to the file descriptor fd, looping as necessary to get
1101 * the job done and also (in certain circumstances) reading any data on
1102 * msg_fd_in to avoid deadlock.
1104 * This function underlies the multiplexing system. The body of the
1105 * application never calls this function directly. */
1106 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1108 size_t n, total = 0;
1109 fd_set w_fds, r_fds, e_fds;
1110 int maxfd, count, cnt, using_r_fds;
1111 int defer_save = defer_forwarding_messages;
1116 while (total < len) {
1123 if (msg_fd_in >= 0) {
1125 FD_SET(msg_fd_in, &r_fds);
1126 if (msg_fd_in > maxfd)
1132 tv.tv_sec = select_timeout;
1136 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1137 &w_fds, &e_fds, &tv);
1140 if (count < 0 && errno == EBADF)
1141 exit_cleanup(RERR_SOCKETIO);
1146 if (FD_ISSET(fd, &e_fds)) {
1147 rsyserr(FINFO, errno,
1148 "select exception on fd %d", fd);
1151 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1154 if (!FD_ISSET(fd, &w_fds))
1158 if (bwlimit_writemax && n > bwlimit_writemax)
1159 n = bwlimit_writemax;
1160 cnt = write(fd, buf + total, n);
1166 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1172 /* Don't try to write errors back across the stream. */
1173 if (fd == sock_f_out)
1174 close_multiplexing_out();
1175 rsyserr(FERROR, errno,
1176 "writefd_unbuffered failed to write %ld bytes [%s]",
1177 (long)len, who_am_i());
1178 /* If the other side is sending us error messages, try
1179 * to grab any messages they sent before they died. */
1180 while (fd == sock_f_out && io_multiplexing_in) {
1183 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1184 sizeof io_filesfrom_buf);
1186 exit_cleanup(RERR_STREAMIO);
1190 defer_forwarding_messages = 1;
1192 if (fd == sock_f_out) {
1193 if (io_timeout || am_generator)
1194 last_io_out = time(NULL);
1195 sleep_for_bwlimit(cnt);
1199 defer_forwarding_messages = defer_save;
1203 static void msg2sndr_flush(void)
1205 if (defer_forwarding_messages)
1208 while (msg2sndr.head && io_multiplexing_out) {
1209 struct msg_list_item *m = msg2sndr.head;
1210 if (!(msg2sndr.head = m->next))
1211 msg2sndr.tail = NULL;
1212 stats.total_written += m->len;
1213 defer_forwarding_messages = 1;
1214 writefd_unbuffered(sock_f_out, m->buf, m->len);
1215 defer_forwarding_messages = 0;
1221 * Write an message to a multiplexed stream. If this fails then rsync
1224 static void mplex_write(enum msgcode code, const char *buf, size_t len)
1229 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1231 if (n > sizeof buffer - 4)
1234 memcpy(buffer + 4, buf, n);
1236 writefd_unbuffered(sock_f_out, buffer, n+4);
1242 defer_forwarding_messages = 1;
1243 writefd_unbuffered(sock_f_out, buf, len);
1244 defer_forwarding_messages = 0;
1249 void io_flush(int flush_it_all)
1251 msg2genr_flush(flush_it_all);
1254 if (!iobuf_out_cnt || no_flush)
1257 if (io_multiplexing_out)
1258 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1260 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1264 static void writefd(int fd, const char *buf, size_t len)
1266 if (fd == msg_fd_out) {
1267 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1268 exit_cleanup(RERR_PROTOCOL);
1271 if (fd == sock_f_out)
1272 stats.total_written += len;
1274 if (fd == write_batch_monitor_out) {
1275 if ((size_t)write(batch_fd, buf, len) != len)
1276 exit_cleanup(RERR_FILEIO);
1279 if (!iobuf_out || fd != sock_f_out) {
1280 writefd_unbuffered(fd, buf, len);
1285 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1287 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1293 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1294 io_flush(NORMAL_FLUSH);
1298 void write_shortint(int f, unsigned short x)
1302 b[1] = (char)(x >> 8);
1306 void write_int(int f, int32 x)
1314 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1315 * 64-bit types on this platform.
1317 void write_longint(int f, int64 x)
1321 #if SIZEOF_INT64 < 8
1322 if (x < 0 || x > 0x7FFFFFFF) {
1323 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1324 exit_cleanup(RERR_UNSUPPORTED);
1328 if (protocol_version < 30) {
1329 char * const s = b+4;
1331 #if SIZEOF_INT64 < 8
1334 if (x <= 0x7FFFFFFF && x >= 0) {
1340 SIVAL(s, 4, x >> 32);
1345 } else if (x < ((int32)1<<(3*8-1))) {
1346 b[0] = (char)(x >> 16);
1347 b[1] = (char)(x >> 8);
1350 } else if (x < ((int64)1<<(4*8-2))) {
1351 b[0] = (char)((x >> 24) | 0x80);
1352 b[1] = (char)(x >> 16);
1353 b[2] = (char)(x >> 8);
1356 #if SIZEOF_INT64 < 8
1359 b[1] = (char)(x >> 24);
1360 b[2] = (char)(x >> 16);
1361 b[3] = (char)(x >> 8);
1366 } else if (x < ((int64)1<<(5*8-3))) {
1367 b[0] = (char)((x >> 32) | 0xC0);
1368 b[1] = (char)(x >> 24);
1369 b[2] = (char)(x >> 16);
1370 b[3] = (char)(x >> 8);
1373 } else if (x < ((int64)1<<(6*8-4))) {
1374 b[0] = (char)((x >> 40) | 0xE0);
1375 b[1] = (char)(x >> 32);
1376 b[2] = (char)(x >> 24);
1377 b[3] = (char)(x >> 16);
1378 b[4] = (char)(x >> 8);
1381 } else if (x < ((int64)1<<(7*8-5))) {
1382 b[0] = (char)((x >> 48) | 0xF0);
1383 b[1] = (char)(x >> 40);
1384 b[2] = (char)(x >> 32);
1385 b[3] = (char)(x >> 24);
1386 b[4] = (char)(x >> 16);
1387 b[5] = (char)(x >> 8);
1390 } else if (x < ((int64)1<<(8*8-6))) {
1391 b[0] = (char)((x >> 56) | 0xF8);
1392 b[1] = (char)(x >> 48);
1393 b[2] = (char)(x >> 40);
1394 b[3] = (char)(x >> 32);
1395 b[4] = (char)(x >> 24);
1396 b[5] = (char)(x >> 16);
1397 b[6] = (char)(x >> 8);
1403 b[1] = (char)(x >> 56);
1404 b[2] = (char)(x >> 48);
1405 b[3] = (char)(x >> 40);
1406 b[4] = (char)(x >> 32);
1407 b[5] = (char)(x >> 24);
1408 b[6] = (char)(x >> 16);
1409 b[7] = (char)(x >> 8);
1416 void write_buf(int f, const char *buf, size_t len)
1421 /** Write a string to the connection */
1422 void write_sbuf(int f, const char *buf)
1424 writefd(f, buf, strlen(buf));
1427 void write_byte(int f, uchar c)
1429 writefd(f, (char *)&c, 1);
1432 void write_vstring(int f, const char *str, int len)
1434 uchar lenbuf[3], *lb = lenbuf;
1439 "attempting to send over-long vstring (%d > %d)\n",
1441 exit_cleanup(RERR_PROTOCOL);
1443 *lb++ = len / 0x100 + 0x80;
1447 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1449 writefd(f, str, len);
1453 * Read a line of up to @p maxlen characters into @p buf (not counting
1454 * the trailing null). Strips the (required) trailing newline and all
1457 * @return 1 for success; 0 for I/O error or truncation.
1459 int read_line(int f, char *buf, size_t maxlen)
1463 read_buf(f, buf, 1);
1468 if (buf[0] != '\r') {
1477 void io_printf(int fd, const char *format, ...)
1480 char buf[BIGPATHBUFLEN];
1483 va_start(ap, format);
1484 len = vsnprintf(buf, sizeof buf, format, ap);
1488 exit_cleanup(RERR_STREAMIO);
1490 if (len > (int)sizeof buf) {
1491 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1492 exit_cleanup(RERR_STREAMIO);
1495 write_sbuf(fd, buf);
1498 /** Setup for multiplexing a MSG_* stream with the data stream. */
1499 void io_start_multiplex_out(void)
1501 io_flush(NORMAL_FLUSH);
1502 io_start_buffering_out();
1503 io_multiplexing_out = 1;
1506 /** Setup for multiplexing a MSG_* stream with the data stream. */
1507 void io_start_multiplex_in(void)
1509 io_flush(NORMAL_FLUSH);
1510 io_start_buffering_in();
1511 io_multiplexing_in = 1;
1514 /** Write an message to the multiplexed data stream. */
1515 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1517 if (!io_multiplexing_out)
1520 io_flush(NORMAL_FLUSH);
1521 stats.total_written += (len+4);
1522 mplex_write(code, buf, len);
1526 void close_multiplexing_in(void)
1528 io_multiplexing_in = 0;
1531 /** Stop output multiplexing. */
1532 void close_multiplexing_out(void)
1534 io_multiplexing_out = 0;
1537 void start_write_batch(int fd)
1539 /* Some communication has already taken place, but we don't
1540 * enable batch writing until here so that we can write a
1541 * canonical record of the communication even though the
1542 * actual communication so far depends on whether a daemon
1544 write_int(batch_fd, protocol_version);
1545 write_int(batch_fd, checksum_seed);
1548 write_batch_monitor_out = fd;
1550 write_batch_monitor_in = fd;
1553 void stop_write_batch(void)
1555 write_batch_monitor_out = -1;
1556 write_batch_monitor_in = -1;