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[256] = {
89 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 00 - 0F */
90 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 10 - 1F */
91 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 20 - 2F */
92 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 30 - 3F */
93 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 40 - 4F */
94 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 50 - 5F */
95 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 60 - 6F */
96 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 70 - 7F */
97 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* 80 - 8F */
98 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* 90 - 9F */
99 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* A0 - AF */
100 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* B0 - BF */
101 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, /* C0 - CF */
102 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, /* D0 - DF */
103 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, /* E0 - EF */
104 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, /* F0 - FF */
107 static void read_loop(int fd, char *buf, size_t len);
109 struct flist_ndx_item {
110 struct flist_ndx_item *next;
114 struct flist_ndx_list {
115 struct flist_ndx_item *head, *tail;
118 static struct flist_ndx_list redo_list, hlink_list;
120 struct msg_list_item {
121 struct msg_list_item *next;
127 struct msg_list_item *head, *tail;
130 static struct msg_list msg2genr, msg2sndr;
132 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
134 struct flist_ndx_item *item;
136 if (!(item = new(struct flist_ndx_item)))
137 out_of_memory("flist_ndx_push");
141 lp->tail->next = item;
147 static int flist_ndx_pop(struct flist_ndx_list *lp)
149 struct flist_ndx_item *next;
156 next = lp->head->next;
165 static void check_timeout(void)
169 if (!io_timeout || ignore_timeout)
173 last_io_in = time(NULL);
179 if (t - last_io_in >= io_timeout) {
180 if (!am_server && !am_daemon) {
181 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
182 (int)(t-last_io_in));
184 exit_cleanup(RERR_TIMEOUT);
188 /* Note the fds used for the main socket (which might really be a pipe
189 * for a local transfer, but we can ignore that). */
190 void io_set_sock_fds(int f_in, int f_out)
196 void set_io_timeout(int secs)
200 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
201 select_timeout = SELECT_TIMEOUT;
203 select_timeout = io_timeout;
205 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
208 /* Setup the fd used to receive MSG_* messages. Only needed during the
209 * early stages of being a local sender (up through the sending of the
210 * file list) or when we're the generator (to fetch the messages from
212 void set_msg_fd_in(int fd)
217 /* Setup the fd used to send our MSG_* messages. Only needed when
218 * we're the receiver (to send our messages to the generator). */
219 void set_msg_fd_out(int fd)
222 set_nonblocking(msg_fd_out);
225 /* Add a message to the pending MSG_* list. */
226 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
228 struct msg_list_item *m;
229 int sz = len + 4 + sizeof m[0] - 1;
231 if (!(m = (struct msg_list_item *)new_array(char, sz)))
232 out_of_memory("msg_list_add");
235 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
236 memcpy(m->buf + 4, buf, len);
244 /* Read a message from the MSG_* fd and handle it. This is called either
245 * during the early stages of being a local sender (up through the sending
246 * of the file list) or when we're the generator (to fetch the messages
247 * from the receiver). */
248 static void read_msg_fd(void)
255 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
256 * to this routine from writefd_unbuffered(). */
259 read_loop(fd, buf, 4);
262 len = tag & 0xFFFFFF;
263 tag = (tag >> 24) - MPLEX_BASE;
267 if (len != 0 || !am_generator) {
268 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
269 exit_cleanup(RERR_STREAMIO);
271 flist_ndx_push(&redo_list, -1);
274 if (len != 4 || !am_generator) {
275 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
276 exit_cleanup(RERR_STREAMIO);
278 read_loop(fd, buf, 4);
279 if (remove_source_files)
280 decrement_active_files(IVAL(buf,0));
281 flist_ndx_push(&redo_list, IVAL(buf,0));
284 if (len >= (int)sizeof buf || !am_generator) {
285 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
286 exit_cleanup(RERR_STREAMIO);
288 read_loop(fd, buf, len);
289 send_msg(MSG_DELETED, buf, len);
292 if (len != 4 || !am_generator) {
293 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
294 exit_cleanup(RERR_STREAMIO);
296 read_loop(fd, buf, len);
297 if (remove_source_files) {
298 decrement_active_files(IVAL(buf,0));
299 send_msg(MSG_SUCCESS, buf, len);
301 if (preserve_hard_links)
302 flist_ndx_push(&hlink_list, IVAL(buf,0));
307 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
308 exit_cleanup(RERR_STREAMIO);
310 if (tag == MSG_SOCKERR)
311 close_multiplexing_out();
320 read_loop(fd, buf, n);
321 rwrite((enum logcode)tag, buf, n);
326 rprintf(FERROR, "unknown message %d:%d [%s]\n",
327 tag, len, who_am_i());
328 exit_cleanup(RERR_STREAMIO);
334 /* This is used by the generator to limit how many file transfers can
335 * be active at once when --remove-source-files is specified. Without
336 * this, sender-side deletions were mostly happening at the end. */
337 void increment_active_files(int ndx, int itemizing, enum logcode code)
339 /* TODO: tune these limits? */
340 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
341 #ifdef SUPPORT_HARD_LINKS
343 check_for_finished_hlinks(itemizing, code);
349 active_bytecnt += F_LENGTH(the_file_list->files[ndx]);
352 void decrement_active_files(int ndx)
355 active_bytecnt -= F_LENGTH(the_file_list->files[ndx]);
358 /* Try to push messages off the list onto the wire. If we leave with more
359 * to do, return 0. On error, return -1. If everything flushed, return 1.
360 * This is only active in the receiver. */
361 static int msg2genr_flush(int flush_it_all)
363 static int written = 0;
370 while (msg2genr.head) {
371 struct msg_list_item *m = msg2genr.head;
372 int n = write(msg_fd_out, m->buf + written, m->len - written);
376 if (errno != EWOULDBLOCK && errno != EAGAIN)
381 FD_SET(msg_fd_out, &fds);
382 tv.tv_sec = select_timeout;
384 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
386 } else if ((written += n) == m->len) {
387 msg2genr.head = m->next;
389 msg2genr.tail = NULL;
397 int send_msg(enum msgcode code, const char *buf, int len)
399 if (msg_fd_out < 0) {
400 if (!defer_forwarding_messages)
401 return io_multiplex_write(code, buf, len);
402 if (!io_multiplexing_out)
404 msg_list_add(&msg2sndr, code, buf, len);
407 msg_list_add(&msg2genr, code, buf, len);
408 msg2genr_flush(NORMAL_FLUSH);
412 void send_msg_int(enum msgcode code, int num)
415 SIVAL(numbuf, 0, num);
416 send_msg(code, numbuf, 4);
419 int get_redo_num(int itemizing, enum logcode code)
422 #ifdef SUPPORT_HARD_LINKS
424 check_for_finished_hlinks(itemizing, code);
431 return flist_ndx_pop(&redo_list);
434 int get_hlink_num(void)
436 return flist_ndx_pop(&hlink_list);
440 * When we're the receiver and we have a local --files-from list of names
441 * that needs to be sent over the socket to the sender, we have to do two
442 * things at the same time: send the sender a list of what files we're
443 * processing and read the incoming file+info list from the sender. We do
444 * this by augmenting the read_timeout() function to copy this data. It
445 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
446 * ready, since it might be a pipe) and then blast it out f_out (when it
447 * is ready to receive more data).
449 void io_set_filesfrom_fds(int f_in, int f_out)
451 io_filesfrom_f_in = f_in;
452 io_filesfrom_f_out = f_out;
453 io_filesfrom_bp = io_filesfrom_buf;
454 io_filesfrom_lastchar = '\0';
455 io_filesfrom_buflen = 0;
458 /* It's almost always an error to get an EOF when we're trying to read from the
459 * network, because the protocol is (for the most part) self-terminating.
461 * There is one case for the receiver when it is at the end of the transfer
462 * (hanging around reading any keep-alive packets that might come its way): if
463 * the sender dies before the generator's kill-signal comes through, we can end
464 * up here needing to loop until the kill-signal arrives. In this situation,
465 * kluge_around_eof will be < 0.
467 * There is another case for older protocol versions (< 24) where the module
468 * listing was not terminated, so we must ignore an EOF error in that case and
469 * exit. In this situation, kluge_around_eof will be > 0. */
470 static void whine_about_eof(int fd)
472 if (kluge_around_eof && fd == sock_f_in) {
474 if (kluge_around_eof > 0)
476 /* If we're still here after 10 seconds, exit with an error. */
477 for (i = 10*1000/20; i--; )
481 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
482 "(%.0f bytes received so far) [%s]\n",
483 (double)stats.total_read, who_am_i());
485 exit_cleanup(RERR_STREAMIO);
489 * Read from a socket with I/O timeout. return the number of bytes
490 * read. If no bytes can be read then exit, never return a number <= 0.
492 * TODO: If the remote shell connection fails, then current versions
493 * actually report an "unexpected EOF" error here. Since it's a
494 * fairly common mistake to try to use rsh when ssh is required, we
495 * should trap that: if we fail to read any data at all, we should
496 * give a better explanation. We can tell whether the connection has
497 * started by looking e.g. at whether the remote version is known yet.
499 static int read_timeout(int fd, char *buf, size_t len)
503 io_flush(NORMAL_FLUSH);
506 /* until we manage to read *something* */
516 FD_SET(msg_fd_out, &w_fds);
517 if (msg_fd_out > maxfd)
520 if (io_filesfrom_f_out >= 0) {
522 if (io_filesfrom_buflen == 0) {
523 if (io_filesfrom_f_in >= 0) {
524 FD_SET(io_filesfrom_f_in, &r_fds);
525 new_fd = io_filesfrom_f_in;
527 io_filesfrom_f_out = -1;
531 FD_SET(io_filesfrom_f_out, &w_fds);
532 new_fd = io_filesfrom_f_out;
538 tv.tv_sec = select_timeout;
543 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
547 exit_cleanup(RERR_SOCKETIO);
552 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
553 msg2genr_flush(NORMAL_FLUSH);
555 if (io_filesfrom_f_out >= 0) {
556 if (io_filesfrom_buflen) {
557 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
558 int l = write(io_filesfrom_f_out,
560 io_filesfrom_buflen);
562 if (!(io_filesfrom_buflen -= l))
563 io_filesfrom_bp = io_filesfrom_buf;
565 io_filesfrom_bp += l;
567 /* XXX should we complain? */
568 io_filesfrom_f_out = -1;
571 } else if (io_filesfrom_f_in >= 0) {
572 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
573 int l = read(io_filesfrom_f_in,
575 sizeof io_filesfrom_buf);
577 /* Send end-of-file marker */
578 io_filesfrom_buf[0] = '\0';
579 io_filesfrom_buf[1] = '\0';
580 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
581 io_filesfrom_f_in = -1;
584 char *s = io_filesfrom_buf + l;
585 /* Transform CR and/or LF into '\0' */
586 while (s-- > io_filesfrom_buf) {
587 if (*s == '\n' || *s == '\r')
591 if (!io_filesfrom_lastchar) {
592 /* Last buf ended with a '\0', so don't
593 * let this buf start with one. */
594 while (l && !*io_filesfrom_bp)
595 io_filesfrom_bp++, l--;
598 io_filesfrom_bp = io_filesfrom_buf;
600 char *f = io_filesfrom_bp;
603 /* Eliminate any multi-'\0' runs. */
605 if (!(*t++ = *f++)) {
606 while (f != eob && !*f)
610 io_filesfrom_lastchar = f[-1];
612 io_filesfrom_buflen = l;
618 if (!FD_ISSET(fd, &r_fds))
621 n = read(fd, buf, len);
625 whine_about_eof(fd); /* Doesn't return. */
626 if (errno == EINTR || errno == EWOULDBLOCK
630 /* Don't write errors on a dead socket. */
631 if (fd == sock_f_in) {
632 close_multiplexing_out();
633 rsyserr(FSOCKERR, errno, "read error");
635 rsyserr(FERROR, errno, "read error");
636 exit_cleanup(RERR_STREAMIO);
643 if (fd == sock_f_in && io_timeout)
644 last_io_in = time(NULL);
651 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
654 int read_filesfrom_line(int fd, char *fname)
656 char ch, *s, *eob = fname + MAXPATHLEN - 1;
658 int reading_remotely = filesfrom_host != NULL;
659 int nulls = eol_nulls || reading_remotely;
664 cnt = read(fd, &ch, 1);
665 if (cnt < 0 && (errno == EWOULDBLOCK
666 || errno == EINTR || errno == EAGAIN)) {
673 tv.tv_sec = select_timeout;
675 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
677 if (FD_ISSET(fd, &e_fds)) {
678 rsyserr(FINFO, errno,
679 "select exception on fd %d", fd);
685 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
686 /* Skip empty lines if reading locally. */
687 if (!reading_remotely && s == fname)
697 if (*fname == '#' || *fname == ';')
703 static char *iobuf_out;
704 static int iobuf_out_cnt;
706 void io_start_buffering_out(void)
710 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
711 out_of_memory("io_start_buffering_out");
715 static char *iobuf_in;
716 static size_t iobuf_in_siz;
718 void io_start_buffering_in(void)
722 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
723 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
724 out_of_memory("io_start_buffering_in");
727 void io_end_buffering(void)
729 io_flush(NORMAL_FLUSH);
730 if (!io_multiplexing_out) {
736 void maybe_flush_socket(void)
738 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
739 io_flush(NORMAL_FLUSH);
742 void maybe_send_keepalive(void)
744 if (time(NULL) - last_io_out >= allowed_lull) {
745 if (!iobuf_out || !iobuf_out_cnt) {
746 if (protocol_version < 29)
747 return; /* there's nothing we can do */
748 write_int(sock_f_out, the_file_list->count);
749 write_shortint(sock_f_out, ITEM_IS_NEW);
752 io_flush(NORMAL_FLUSH);
757 * Continue trying to read len bytes - don't return until len has been
760 static void read_loop(int fd, char *buf, size_t len)
763 int n = read_timeout(fd, buf, len);
771 * Read from the file descriptor handling multiplexing - return number
774 * Never returns <= 0.
776 static int readfd_unbuffered(int fd, char *buf, size_t len)
778 static size_t remaining;
779 static size_t iobuf_in_ndx;
782 char line[BIGPATHBUFLEN];
784 if (!iobuf_in || fd != sock_f_in)
785 return read_timeout(fd, buf, len);
787 if (!io_multiplexing_in && remaining == 0) {
788 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
794 len = MIN(len, remaining);
795 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
802 read_loop(fd, line, 4);
805 msg_bytes = tag & 0xFFFFFF;
806 tag = (tag >> 24) - MPLEX_BASE;
810 if (msg_bytes > iobuf_in_siz) {
811 if (!(iobuf_in = realloc_array(iobuf_in, char,
813 out_of_memory("readfd_unbuffered");
814 iobuf_in_siz = msg_bytes;
816 read_loop(fd, iobuf_in, msg_bytes);
817 remaining = msg_bytes;
821 if (msg_bytes >= sizeof line)
823 read_loop(fd, line, msg_bytes);
824 /* A directory name was sent with the trailing null */
825 if (msg_bytes > 0 && !line[msg_bytes-1])
826 log_delete(line, S_IFDIR);
828 line[msg_bytes] = '\0';
829 log_delete(line, S_IFREG);
833 if (msg_bytes != 4) {
834 rprintf(FERROR, "invalid multi-message %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 successful_send(IVAL(line, 0));
843 if (msg_bytes >= sizeof line) {
846 "multiplexing overflow %d:%ld [%s]\n",
847 tag, (long)msg_bytes, who_am_i());
848 exit_cleanup(RERR_STREAMIO);
850 read_loop(fd, line, msg_bytes);
851 rwrite((enum logcode)tag, line, msg_bytes);
854 rprintf(FERROR, "unexpected tag %d [%s]\n",
856 exit_cleanup(RERR_STREAMIO);
861 io_flush(NORMAL_FLUSH);
867 * Do a buffered read from @p fd. Don't return until all @p n bytes
868 * have been read. If all @p n can't be read then exit with an
871 static void readfd(int fd, char *buffer, size_t N)
877 cnt = readfd_unbuffered(fd, buffer + total, N-total);
881 if (fd == write_batch_monitor_in) {
882 if ((size_t)write(batch_fd, buffer, total) != total)
883 exit_cleanup(RERR_FILEIO);
887 stats.total_read += total;
890 unsigned short read_shortint(int f)
894 return (UVAL(b, 1) << 8) + UVAL(b, 0);
897 int32 read_int(int f)
905 if (num & (int32)0x80000000)
906 num |= ~(int32)0xffffffff;
911 int64 read_longint(int f)
916 if (protocol_version < 30) {
919 if ((int32)num != (int32)0xffffffff)
923 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
924 exit_cleanup(RERR_UNSUPPORTED);
927 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
932 cnt = int_byte_cnt[CVAL(b, 0)];
934 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
935 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
936 exit_cleanup(RERR_UNSUPPORTED);
940 readfd(f, b + 3, cnt - 3);
946 num = NVAL4(b, 0x80);
949 num = NVAL5(b, 0xC0);
951 #if SIZEOF_INT64 >= 8
953 num = NVAL6(b, 0xE0);
956 num = NVAL7(b, 0xF0);
959 num = NVAL8(b, 0xF8);
966 exit_cleanup(RERR_PROTOCOL); /* impossible... */
973 void read_buf(int f, char *buf, size_t len)
978 void read_sbuf(int f, char *buf, size_t len)
984 uchar read_byte(int f)
987 readfd(f, (char *)&c, 1);
991 int read_vstring(int f, char *buf, int bufsize)
993 int len = read_byte(f);
996 len = (len & ~0x80) * 0x100 + read_byte(f);
998 if (len >= bufsize) {
999 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1005 readfd(f, buf, len);
1010 /* Populate a sum_struct with values from the socket. This is
1011 * called by both the sender and the receiver. */
1012 void read_sum_head(int f, struct sum_struct *sum)
1014 sum->count = read_int(f);
1015 if (sum->count < 0) {
1016 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1017 (long)sum->count, who_am_i());
1018 exit_cleanup(RERR_PROTOCOL);
1020 sum->blength = read_int(f);
1021 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1022 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1023 (long)sum->blength, who_am_i());
1024 exit_cleanup(RERR_PROTOCOL);
1026 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1027 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1028 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1029 sum->s2length, who_am_i());
1030 exit_cleanup(RERR_PROTOCOL);
1032 sum->remainder = read_int(f);
1033 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1034 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1035 (long)sum->remainder, who_am_i());
1036 exit_cleanup(RERR_PROTOCOL);
1040 /* Send the values from a sum_struct over the socket. Set sum to
1041 * NULL if there are no checksums to send. This is called by both
1042 * the generator and the sender. */
1043 void write_sum_head(int f, struct sum_struct *sum)
1045 static struct sum_struct null_sum;
1050 write_int(f, sum->count);
1051 write_int(f, sum->blength);
1052 if (protocol_version >= 27)
1053 write_int(f, sum->s2length);
1054 write_int(f, sum->remainder);
1058 * Sleep after writing to limit I/O bandwidth usage.
1060 * @todo Rather than sleeping after each write, it might be better to
1061 * use some kind of averaging. The current algorithm seems to always
1062 * use a bit less bandwidth than specified, because it doesn't make up
1063 * for slow periods. But arguably this is a feature. In addition, we
1064 * ought to take the time used to write the data into account.
1066 * During some phases of big transfers (file FOO is uptodate) this is
1067 * called with a small bytes_written every time. As the kernel has to
1068 * round small waits up to guarantee that we actually wait at least the
1069 * requested number of microseconds, this can become grossly inaccurate.
1070 * We therefore keep track of the bytes we've written over time and only
1071 * sleep when the accumulated delay is at least 1 tenth of a second.
1073 static void sleep_for_bwlimit(int bytes_written)
1075 static struct timeval prior_tv;
1076 static long total_written = 0;
1077 struct timeval tv, start_tv;
1078 long elapsed_usec, sleep_usec;
1080 #define ONE_SEC 1000000L /* # of microseconds in a second */
1082 if (!bwlimit_writemax)
1085 total_written += bytes_written;
1087 gettimeofday(&start_tv, NULL);
1088 if (prior_tv.tv_sec) {
1089 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1090 + (start_tv.tv_usec - prior_tv.tv_usec);
1091 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1092 if (total_written < 0)
1096 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1097 if (sleep_usec < ONE_SEC / 10) {
1098 prior_tv = start_tv;
1102 tv.tv_sec = sleep_usec / ONE_SEC;
1103 tv.tv_usec = sleep_usec % ONE_SEC;
1104 select(0, NULL, NULL, NULL, &tv);
1106 gettimeofday(&prior_tv, NULL);
1107 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1108 + (prior_tv.tv_usec - start_tv.tv_usec);
1109 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1112 /* Write len bytes to the file descriptor fd, looping as necessary to get
1113 * the job done and also (in certain circumstances) reading any data on
1114 * msg_fd_in to avoid deadlock.
1116 * This function underlies the multiplexing system. The body of the
1117 * application never calls this function directly. */
1118 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1120 size_t n, total = 0;
1121 fd_set w_fds, r_fds, e_fds;
1122 int maxfd, count, cnt, using_r_fds;
1123 int defer_save = defer_forwarding_messages;
1128 while (total < len) {
1135 if (msg_fd_in >= 0) {
1137 FD_SET(msg_fd_in, &r_fds);
1138 if (msg_fd_in > maxfd)
1144 tv.tv_sec = select_timeout;
1148 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1149 &w_fds, &e_fds, &tv);
1152 if (count < 0 && errno == EBADF)
1153 exit_cleanup(RERR_SOCKETIO);
1158 if (FD_ISSET(fd, &e_fds)) {
1159 rsyserr(FINFO, errno,
1160 "select exception on fd %d", fd);
1163 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1166 if (!FD_ISSET(fd, &w_fds))
1170 if (bwlimit_writemax && n > bwlimit_writemax)
1171 n = bwlimit_writemax;
1172 cnt = write(fd, buf + total, n);
1178 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1184 /* Don't try to write errors back across the stream. */
1185 if (fd == sock_f_out)
1186 close_multiplexing_out();
1187 rsyserr(FERROR, errno,
1188 "writefd_unbuffered failed to write %ld bytes [%s]",
1189 (long)len, who_am_i());
1190 /* If the other side is sending us error messages, try
1191 * to grab any messages they sent before they died. */
1192 while (fd == sock_f_out && io_multiplexing_in) {
1195 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1196 sizeof io_filesfrom_buf);
1198 exit_cleanup(RERR_STREAMIO);
1202 defer_forwarding_messages = 1;
1204 if (fd == sock_f_out) {
1205 if (io_timeout || am_generator)
1206 last_io_out = time(NULL);
1207 sleep_for_bwlimit(cnt);
1211 defer_forwarding_messages = defer_save;
1215 static void msg2sndr_flush(void)
1217 if (defer_forwarding_messages)
1220 while (msg2sndr.head && io_multiplexing_out) {
1221 struct msg_list_item *m = msg2sndr.head;
1222 if (!(msg2sndr.head = m->next))
1223 msg2sndr.tail = NULL;
1224 stats.total_written += m->len;
1225 defer_forwarding_messages = 1;
1226 writefd_unbuffered(sock_f_out, m->buf, m->len);
1227 defer_forwarding_messages = 0;
1233 * Write an message to a multiplexed stream. If this fails then rsync
1236 static void mplex_write(enum msgcode code, const char *buf, size_t len)
1241 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1243 if (n > sizeof buffer - 4)
1246 memcpy(buffer + 4, buf, n);
1248 writefd_unbuffered(sock_f_out, buffer, n+4);
1254 defer_forwarding_messages = 1;
1255 writefd_unbuffered(sock_f_out, buf, len);
1256 defer_forwarding_messages = 0;
1261 void io_flush(int flush_it_all)
1263 msg2genr_flush(flush_it_all);
1266 if (!iobuf_out_cnt || no_flush)
1269 if (io_multiplexing_out)
1270 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1272 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1276 static void writefd(int fd, const char *buf, size_t len)
1278 if (fd == msg_fd_out) {
1279 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1280 exit_cleanup(RERR_PROTOCOL);
1283 if (fd == sock_f_out)
1284 stats.total_written += len;
1286 if (fd == write_batch_monitor_out) {
1287 if ((size_t)write(batch_fd, buf, len) != len)
1288 exit_cleanup(RERR_FILEIO);
1291 if (!iobuf_out || fd != sock_f_out) {
1292 writefd_unbuffered(fd, buf, len);
1297 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1299 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1305 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1306 io_flush(NORMAL_FLUSH);
1310 void write_shortint(int f, unsigned short x)
1314 b[1] = (char)(x >> 8);
1318 void write_int(int f, int32 x)
1326 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1327 * 64-bit types on this platform.
1329 void write_longint(int f, int64 x)
1333 #if SIZEOF_INT64 < 8
1334 if (x < 0 || x > 0x7FFFFFFF) {
1335 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1336 exit_cleanup(RERR_UNSUPPORTED);
1340 if (protocol_version < 30) {
1341 char * const s = b+4;
1343 #if SIZEOF_INT64 < 8
1346 if (x <= 0x7FFFFFFF && x >= 0) {
1352 SIVAL(s, 4, x >> 32);
1357 } else if (x < ((int32)1<<(3*8-1))) {
1358 b[0] = (char)(x >> 16);
1359 b[1] = (char)(x >> 8);
1362 } else if (x < ((int64)1<<(4*8-2))) {
1363 b[0] = (char)((x >> 24) | 0x80);
1364 b[1] = (char)(x >> 16);
1365 b[2] = (char)(x >> 8);
1368 #if SIZEOF_INT64 < 8
1371 b[1] = (char)(x >> 24);
1372 b[2] = (char)(x >> 16);
1373 b[3] = (char)(x >> 8);
1378 } else if (x < ((int64)1<<(5*8-3))) {
1379 b[0] = (char)((x >> 32) | 0xC0);
1380 b[1] = (char)(x >> 24);
1381 b[2] = (char)(x >> 16);
1382 b[3] = (char)(x >> 8);
1385 } else if (x < ((int64)1<<(6*8-4))) {
1386 b[0] = (char)((x >> 40) | 0xE0);
1387 b[1] = (char)(x >> 32);
1388 b[2] = (char)(x >> 24);
1389 b[3] = (char)(x >> 16);
1390 b[4] = (char)(x >> 8);
1393 } else if (x < ((int64)1<<(7*8-5))) {
1394 b[0] = (char)((x >> 48) | 0xF0);
1395 b[1] = (char)(x >> 40);
1396 b[2] = (char)(x >> 32);
1397 b[3] = (char)(x >> 24);
1398 b[4] = (char)(x >> 16);
1399 b[5] = (char)(x >> 8);
1402 } else if (x < ((int64)1<<(8*8-6))) {
1403 b[0] = (char)((x >> 56) | 0xF8);
1404 b[1] = (char)(x >> 48);
1405 b[2] = (char)(x >> 40);
1406 b[3] = (char)(x >> 32);
1407 b[4] = (char)(x >> 24);
1408 b[5] = (char)(x >> 16);
1409 b[6] = (char)(x >> 8);
1415 b[1] = (char)(x >> 56);
1416 b[2] = (char)(x >> 48);
1417 b[3] = (char)(x >> 40);
1418 b[4] = (char)(x >> 32);
1419 b[5] = (char)(x >> 24);
1420 b[6] = (char)(x >> 16);
1421 b[7] = (char)(x >> 8);
1428 void write_buf(int f, const char *buf, size_t len)
1433 /** Write a string to the connection */
1434 void write_sbuf(int f, const char *buf)
1436 writefd(f, buf, strlen(buf));
1439 void write_byte(int f, uchar c)
1441 writefd(f, (char *)&c, 1);
1444 void write_vstring(int f, const char *str, int len)
1446 uchar lenbuf[3], *lb = lenbuf;
1451 "attempting to send over-long vstring (%d > %d)\n",
1453 exit_cleanup(RERR_PROTOCOL);
1455 *lb++ = len / 0x100 + 0x80;
1459 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1461 writefd(f, str, len);
1465 * Read a line of up to @p maxlen characters into @p buf (not counting
1466 * the trailing null). Strips the (required) trailing newline and all
1469 * @return 1 for success; 0 for I/O error or truncation.
1471 int read_line(int f, char *buf, size_t maxlen)
1475 read_buf(f, buf, 1);
1480 if (buf[0] != '\r') {
1489 void io_printf(int fd, const char *format, ...)
1492 char buf[BIGPATHBUFLEN];
1495 va_start(ap, format);
1496 len = vsnprintf(buf, sizeof buf, format, ap);
1500 exit_cleanup(RERR_STREAMIO);
1502 if (len > (int)sizeof buf) {
1503 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1504 exit_cleanup(RERR_STREAMIO);
1507 write_sbuf(fd, buf);
1510 /** Setup for multiplexing a MSG_* stream with the data stream. */
1511 void io_start_multiplex_out(void)
1513 io_flush(NORMAL_FLUSH);
1514 io_start_buffering_out();
1515 io_multiplexing_out = 1;
1518 /** Setup for multiplexing a MSG_* stream with the data stream. */
1519 void io_start_multiplex_in(void)
1521 io_flush(NORMAL_FLUSH);
1522 io_start_buffering_in();
1523 io_multiplexing_in = 1;
1526 /** Write an message to the multiplexed data stream. */
1527 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1529 if (!io_multiplexing_out)
1532 io_flush(NORMAL_FLUSH);
1533 stats.total_written += (len+4);
1534 mplex_write(code, buf, len);
1538 void close_multiplexing_in(void)
1540 io_multiplexing_in = 0;
1543 /** Stop output multiplexing. */
1544 void close_multiplexing_out(void)
1546 io_multiplexing_out = 0;
1549 void start_write_batch(int fd)
1551 write_stream_flags(batch_fd);
1553 /* Some communication has already taken place, but we don't
1554 * enable batch writing until here so that we can write a
1555 * canonical record of the communication even though the
1556 * actual communication so far depends on whether a daemon
1558 write_int(batch_fd, protocol_version);
1559 write_int(batch_fd, checksum_seed);
1562 write_batch_monitor_out = fd;
1564 write_batch_monitor_in = fd;
1567 void stop_write_batch(void)
1569 write_batch_monitor_out = -1;
1570 write_batch_monitor_in = -1;