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;
44 extern int inc_recurse;
48 extern int read_batch;
49 extern int csum_length;
50 extern int checksum_seed;
51 extern int protocol_version;
52 extern int remove_source_files;
53 extern int preserve_hard_links;
54 extern char *filesfrom_host;
55 extern struct stats stats;
56 extern struct file_list *cur_flist, *first_flist;
58 const char phase_unknown[] = "unknown";
59 int ignore_timeout = 0;
63 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
64 int kluge_around_eof = 0;
71 static int iobuf_f_in = -1;
72 static char *iobuf_in;
73 static size_t iobuf_in_siz;
74 static size_t iobuf_in_ndx;
75 static size_t iobuf_in_remaining;
77 static int iobuf_f_out = -1;
78 static char *iobuf_out;
79 static int iobuf_out_cnt;
81 int flist_forward_from = -1;
83 static int io_multiplexing_out;
84 static int io_multiplexing_in;
85 static time_t last_io_in;
86 static time_t last_io_out;
89 static int write_batch_monitor_in = -1;
90 static int write_batch_monitor_out = -1;
92 static int io_filesfrom_f_in = -1;
93 static int io_filesfrom_f_out = -1;
94 static char io_filesfrom_buf[2048];
95 static char *io_filesfrom_bp;
96 static char io_filesfrom_lastchar;
97 static int io_filesfrom_buflen;
98 static int defer_forwarding_messages = 0;
99 static int select_timeout = SELECT_TIMEOUT;
100 static int active_filecnt = 0;
101 static OFF_T active_bytecnt = 0;
103 static char int_byte_cnt[64] = {
104 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (00 - 3F)/4 */
105 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (40 - 7F)/4 */
106 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* (80 - BF)/4 */
107 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 9, /* (C0 - FF)/4 */
110 static void readfd(int fd, char *buffer, size_t N);
111 static void writefd(int fd, const char *buf, size_t len);
112 static void writefd_unbuffered(int fd, const char *buf, size_t len);
113 static void decrement_active_files(int ndx);
114 static void decrement_flist_in_progress(int ndx, int redo);
116 struct flist_ndx_item {
117 struct flist_ndx_item *next;
121 struct flist_ndx_list {
122 struct flist_ndx_item *head, *tail;
125 static struct flist_ndx_list redo_list, hlink_list;
127 struct msg_list_item {
128 struct msg_list_item *next;
134 struct msg_list_item *head, *tail;
137 static struct msg_list msg2sndr;
139 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
141 struct flist_ndx_item *item;
143 if (!(item = new(struct flist_ndx_item)))
144 out_of_memory("flist_ndx_push");
148 lp->tail->next = item;
154 static int flist_ndx_pop(struct flist_ndx_list *lp)
156 struct flist_ndx_item *next;
163 next = lp->head->next;
172 static void check_timeout(void)
176 if (!io_timeout || ignore_timeout)
180 last_io_in = time(NULL);
186 if (t - last_io_in >= io_timeout) {
187 if (!am_server && !am_daemon) {
188 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
189 (int)(t-last_io_in));
191 exit_cleanup(RERR_TIMEOUT);
195 /* Note the fds used for the main socket (which might really be a pipe
196 * for a local transfer, but we can ignore that). */
197 void io_set_sock_fds(int f_in, int f_out)
203 void set_io_timeout(int secs)
207 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
208 select_timeout = SELECT_TIMEOUT;
210 select_timeout = io_timeout;
212 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
215 /* Setup the fd used to receive MSG_* messages. Only needed during the
216 * early stages of being a local sender (up through the sending of the
217 * file list) or when we're the generator (to fetch the messages from
219 void set_msg_fd_in(int fd)
224 /* Setup the fd used to send our MSG_* messages. Only needed when
225 * we're the receiver (to send our messages to the generator). */
226 void set_msg_fd_out(int fd)
229 set_nonblocking(msg_fd_out);
232 /* Add a message to the pending MSG_* list. */
233 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
235 struct msg_list_item *m;
236 int sz = len + 4 + sizeof m[0] - 1;
238 if (!(m = (struct msg_list_item *)new_array(char, sz)))
239 out_of_memory("msg_list_add");
242 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
243 memcpy(m->buf + 4, buf, len);
251 static void msg2sndr_flush(void)
253 while (msg2sndr.head && io_multiplexing_out) {
254 struct msg_list_item *m = msg2sndr.head;
255 if (!(msg2sndr.head = m->next))
256 msg2sndr.tail = NULL;
257 stats.total_written += m->len;
258 defer_forwarding_messages = 1;
259 writefd_unbuffered(sock_f_out, m->buf, m->len);
260 defer_forwarding_messages = 0;
265 /* Read a message from the MSG_* fd and handle it. This is called either
266 * during the early stages of being a local sender (up through the sending
267 * of the file list) or when we're the generator (to fetch the messages
268 * from the receiver). */
269 static void read_msg_fd(void)
273 struct file_list *flist;
277 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
278 * to this routine from writefd_unbuffered(). */
281 defer_forwarding_messages++;
286 len = tag & 0xFFFFFF;
287 tag = (tag >> 24) - MPLEX_BASE;
291 if (len < 0 || len > 1 || !am_generator) {
293 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
294 tag, len, who_am_i(),
295 inc_recurse ? "/inc" : "");
296 exit_cleanup(RERR_STREAMIO);
299 readfd(fd, buf, len);
300 stats.total_read = read_longint(fd);
305 if (len != 4 || !am_generator)
308 if (remove_source_files)
309 decrement_active_files(IVAL(buf,0));
310 flist_ndx_push(&redo_list, IVAL(buf,0));
312 decrement_flist_in_progress(IVAL(buf,0), 1);
315 if (len != 4 || !am_generator || !inc_recurse)
318 /* Read extra file list from receiver. */
319 assert(iobuf_in != NULL);
320 assert(iobuf_f_in == fd);
321 flist = recv_file_list(fd);
322 flist->parent_ndx = IVAL(buf,0);
325 if (len != 0 || !am_generator || !inc_recurse)
330 if (len >= (int)sizeof buf || !am_generator)
332 readfd(fd, buf, len);
333 send_msg(MSG_DELETED, buf, len);
336 if (len != 4 || !am_generator)
338 readfd(fd, buf, len);
339 if (remove_source_files) {
340 decrement_active_files(IVAL(buf,0));
341 send_msg(MSG_SUCCESS, buf, len);
343 if (preserve_hard_links)
344 flist_ndx_push(&hlink_list, IVAL(buf,0));
346 decrement_flist_in_progress(IVAL(buf,0), 0);
349 if (len != 4 || !am_generator)
351 readfd(fd, buf, len);
353 decrement_flist_in_progress(IVAL(buf,0), 0);
359 if (tag == MSG_SOCKERR)
360 io_end_multiplex_out();
370 rwrite((enum logcode)tag, buf, n);
375 rprintf(FERROR, "unknown message %d:%d [%s]\n",
376 tag, len, who_am_i());
377 exit_cleanup(RERR_STREAMIO);
382 if (!--defer_forwarding_messages)
386 /* This is used by the generator to limit how many file transfers can
387 * be active at once when --remove-source-files is specified. Without
388 * this, sender-side deletions were mostly happening at the end. */
389 void increment_active_files(int ndx, int itemizing, enum logcode code)
391 /* TODO: tune these limits? */
392 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
393 #ifdef SUPPORT_HARD_LINKS
395 check_for_finished_hlinks(itemizing, code);
397 io_flush(NORMAL_FLUSH);
402 active_bytecnt += F_LENGTH(cur_flist->files[ndx]);
405 static void decrement_active_files(int ndx)
407 struct file_list *flist = flist_for_ndx(ndx);
408 assert(flist != NULL);
410 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
413 static void decrement_flist_in_progress(int ndx, int redo)
415 struct file_list *flist = cur_flist ? cur_flist : first_flist;
417 while (ndx < flist->ndx_start) {
418 if (flist == first_flist) {
421 "Invalid file index: %d (%d - %d) [%s]\n",
422 ndx, first_flist->ndx_start,
423 first_flist->prev->ndx_start + first_flist->prev->count - 1,
425 exit_cleanup(RERR_PROTOCOL);
429 while (ndx >= flist->ndx_start + flist->count) {
430 if (!(flist = flist->next))
434 flist->in_progress--;
439 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
440 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len)
445 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
447 if (n > sizeof buffer - 4)
450 memcpy(buffer + 4, buf, n);
452 writefd_unbuffered(fd, buffer, n+4);
458 defer_forwarding_messages++;
459 writefd_unbuffered(fd, buf, len);
460 if (!--defer_forwarding_messages)
465 int send_msg(enum msgcode code, const char *buf, int len)
467 if (msg_fd_out < 0) {
468 if (!defer_forwarding_messages)
469 return io_multiplex_write(code, buf, len);
470 if (!io_multiplexing_out)
472 msg_list_add(&msg2sndr, code, buf, len);
475 mplex_write(msg_fd_out, code, buf, len);
479 void send_msg_int(enum msgcode code, int num)
482 SIVAL(numbuf, 0, num);
483 send_msg(code, numbuf, 4);
486 void wait_for_receiver(void)
489 io_flush(NORMAL_FLUSH);
494 int get_redo_num(void)
496 return flist_ndx_pop(&redo_list);
499 int get_hlink_num(void)
501 return flist_ndx_pop(&hlink_list);
505 * When we're the receiver and we have a local --files-from list of names
506 * that needs to be sent over the socket to the sender, we have to do two
507 * things at the same time: send the sender a list of what files we're
508 * processing and read the incoming file+info list from the sender. We do
509 * this by augmenting the read_timeout() function to copy this data. It
510 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
511 * ready, since it might be a pipe) and then blast it out f_out (when it
512 * is ready to receive more data).
514 void io_set_filesfrom_fds(int f_in, int f_out)
516 io_filesfrom_f_in = f_in;
517 io_filesfrom_f_out = f_out;
518 io_filesfrom_bp = io_filesfrom_buf;
519 io_filesfrom_lastchar = '\0';
520 io_filesfrom_buflen = 0;
523 /* It's almost always an error to get an EOF when we're trying to read from the
524 * network, because the protocol is (for the most part) self-terminating.
526 * There is one case for the receiver when it is at the end of the transfer
527 * (hanging around reading any keep-alive packets that might come its way): if
528 * the sender dies before the generator's kill-signal comes through, we can end
529 * up here needing to loop until the kill-signal arrives. In this situation,
530 * kluge_around_eof will be < 0.
532 * There is another case for older protocol versions (< 24) where the module
533 * listing was not terminated, so we must ignore an EOF error in that case and
534 * exit. In this situation, kluge_around_eof will be > 0. */
535 static void whine_about_eof(int fd)
537 if (kluge_around_eof && fd == sock_f_in) {
539 if (kluge_around_eof > 0)
541 /* If we're still here after 10 seconds, exit with an error. */
542 for (i = 10*1000/20; i--; )
546 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
547 "(%.0f bytes received so far) [%s]\n",
548 (double)stats.total_read, who_am_i());
550 exit_cleanup(RERR_STREAMIO);
554 * Read from a socket with I/O timeout. return the number of bytes
555 * read. If no bytes can be read then exit, never return a number <= 0.
557 * TODO: If the remote shell connection fails, then current versions
558 * actually report an "unexpected EOF" error here. Since it's a
559 * fairly common mistake to try to use rsh when ssh is required, we
560 * should trap that: if we fail to read any data at all, we should
561 * give a better explanation. We can tell whether the connection has
562 * started by looking e.g. at whether the remote version is known yet.
564 static int read_timeout(int fd, char *buf, size_t len)
568 io_flush(FULL_FLUSH);
571 /* until we manage to read *something* */
580 if (io_filesfrom_f_out >= 0) {
582 if (io_filesfrom_buflen == 0) {
583 if (io_filesfrom_f_in >= 0) {
584 FD_SET(io_filesfrom_f_in, &r_fds);
585 new_fd = io_filesfrom_f_in;
587 io_filesfrom_f_out = -1;
591 FD_SET(io_filesfrom_f_out, &w_fds);
592 new_fd = io_filesfrom_f_out;
598 tv.tv_sec = select_timeout;
603 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
606 if (errno == EBADF) {
607 defer_forwarding_messages = 0;
608 exit_cleanup(RERR_SOCKETIO);
614 if (io_filesfrom_f_out >= 0) {
615 if (io_filesfrom_buflen) {
616 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
617 int l = write(io_filesfrom_f_out,
619 io_filesfrom_buflen);
621 if (!(io_filesfrom_buflen -= l))
622 io_filesfrom_bp = io_filesfrom_buf;
624 io_filesfrom_bp += l;
626 /* XXX should we complain? */
627 io_filesfrom_f_out = -1;
630 } else if (io_filesfrom_f_in >= 0) {
631 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
632 int l = read(io_filesfrom_f_in,
634 sizeof io_filesfrom_buf);
636 /* Send end-of-file marker */
637 io_filesfrom_buf[0] = '\0';
638 io_filesfrom_buf[1] = '\0';
639 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
640 io_filesfrom_f_in = -1;
643 char *s = io_filesfrom_buf + l;
644 /* Transform CR and/or LF into '\0' */
645 while (s-- > io_filesfrom_buf) {
646 if (*s == '\n' || *s == '\r')
650 if (!io_filesfrom_lastchar) {
651 /* Last buf ended with a '\0', so don't
652 * let this buf start with one. */
653 while (l && !*io_filesfrom_bp)
654 io_filesfrom_bp++, l--;
657 io_filesfrom_bp = io_filesfrom_buf;
659 char *f = io_filesfrom_bp;
662 /* Eliminate any multi-'\0' runs. */
664 if (!(*t++ = *f++)) {
665 while (f != eob && !*f)
669 io_filesfrom_lastchar = f[-1];
671 io_filesfrom_buflen = l;
677 if (!FD_ISSET(fd, &r_fds))
680 n = read(fd, buf, len);
684 whine_about_eof(fd); /* Doesn't return. */
685 if (errno == EINTR || errno == EWOULDBLOCK
689 /* Don't write errors on a dead socket. */
690 if (fd == sock_f_in) {
691 io_end_multiplex_out();
692 rsyserr(FSOCKERR, errno, "read error");
694 rsyserr(FERROR, errno, "read error");
695 exit_cleanup(RERR_STREAMIO);
702 if (fd == sock_f_in && io_timeout)
703 last_io_in = time(NULL);
710 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
713 int read_filesfrom_line(int fd, char *fname)
715 char ch, *s, *eob = fname + MAXPATHLEN - 1;
717 int reading_remotely = filesfrom_host != NULL;
718 int nulls = eol_nulls || reading_remotely;
723 cnt = read(fd, &ch, 1);
724 if (cnt < 0 && (errno == EWOULDBLOCK
725 || errno == EINTR || errno == EAGAIN)) {
732 tv.tv_sec = select_timeout;
734 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
736 if (FD_ISSET(fd, &e_fds)) {
737 rsyserr(FINFO, errno,
738 "select exception on fd %d", fd);
744 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
745 /* Skip empty lines if reading locally. */
746 if (!reading_remotely && s == fname)
756 if (*fname == '#' || *fname == ';')
762 int io_start_buffering_out(int f_out)
765 assert(f_out == iobuf_f_out);
768 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
769 out_of_memory("io_start_buffering_out");
775 int io_start_buffering_in(int f_in)
778 assert(f_in == iobuf_f_in);
781 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
782 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
783 out_of_memory("io_start_buffering_in");
788 void io_end_buffering_in(void)
795 iobuf_in_remaining = 0;
799 void io_end_buffering_out(void)
803 io_flush(FULL_FLUSH);
809 void maybe_flush_socket(void)
811 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
812 io_flush(NORMAL_FLUSH);
815 void maybe_send_keepalive(void)
817 if (time(NULL) - last_io_out >= allowed_lull) {
818 if (!iobuf_out || !iobuf_out_cnt) {
819 if (protocol_version < 29)
820 return; /* there's nothing we can do */
821 if (protocol_version >= 30)
822 send_msg(MSG_NOOP, "", 0);
824 write_int(sock_f_out, cur_flist->count);
825 write_shortint(sock_f_out, ITEM_IS_NEW);
829 io_flush(NORMAL_FLUSH);
833 void start_flist_forward(int f_in)
835 assert(iobuf_out != NULL);
836 assert(iobuf_f_out == msg_fd_out);
837 flist_forward_from = f_in;
840 void stop_flist_forward()
842 flist_forward_from = -1;
843 io_flush(FULL_FLUSH);
847 * Continue trying to read len bytes - don't return until len has been
850 static void read_loop(int fd, char *buf, size_t len)
853 int n = read_timeout(fd, buf, len);
861 * Read from the file descriptor handling multiplexing - return number
864 * Never returns <= 0.
866 static int readfd_unbuffered(int fd, char *buf, size_t len)
870 char line[BIGPATHBUFLEN];
872 if (!iobuf_in || fd != iobuf_f_in)
873 return read_timeout(fd, buf, len);
875 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
876 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
881 if (iobuf_in_remaining) {
882 len = MIN(len, iobuf_in_remaining);
883 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
885 iobuf_in_remaining -= len;
890 read_loop(fd, line, 4);
893 msg_bytes = tag & 0xFFFFFF;
894 tag = (tag >> 24) - MPLEX_BASE;
898 if (msg_bytes > iobuf_in_siz) {
899 if (!(iobuf_in = realloc_array(iobuf_in, char,
901 out_of_memory("readfd_unbuffered");
902 iobuf_in_siz = msg_bytes;
904 read_loop(fd, iobuf_in, msg_bytes);
905 iobuf_in_remaining = msg_bytes;
910 maybe_send_keepalive();
915 read_loop(fd, line, msg_bytes);
916 io_error |= IVAL(line, 0);
919 if (msg_bytes >= sizeof line)
921 read_loop(fd, line, msg_bytes);
922 /* A directory name was sent with the trailing null */
923 if (msg_bytes > 0 && !line[msg_bytes-1])
924 log_delete(line, S_IFDIR);
926 line[msg_bytes] = '\0';
927 log_delete(line, S_IFREG);
931 if (msg_bytes != 4) {
933 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
934 tag, (long)msg_bytes, who_am_i());
935 exit_cleanup(RERR_STREAMIO);
937 read_loop(fd, line, msg_bytes);
938 successful_send(IVAL(line, 0));
943 read_loop(fd, line, msg_bytes);
944 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
948 if (msg_bytes >= sizeof line) {
951 "multiplexing overflow %d:%ld [%s]\n",
952 tag, (long)msg_bytes, who_am_i());
953 exit_cleanup(RERR_STREAMIO);
955 read_loop(fd, line, msg_bytes);
956 rwrite((enum logcode)tag, line, msg_bytes);
959 rprintf(FERROR, "unexpected tag %d [%s]\n",
961 exit_cleanup(RERR_STREAMIO);
965 if (iobuf_in_remaining == 0)
966 io_flush(NORMAL_FLUSH);
971 /* Do a buffered read from fd. Don't return until all N bytes have
972 * been read. If all N can't be read then exit with an error. */
973 static void readfd(int fd, char *buffer, size_t N)
979 cnt = readfd_unbuffered(fd, buffer + total, N-total);
983 if (fd == write_batch_monitor_in) {
984 if ((size_t)write(batch_fd, buffer, total) != total)
985 exit_cleanup(RERR_FILEIO);
988 if (fd == flist_forward_from)
989 writefd(iobuf_f_out, buffer, total);
992 stats.total_read += total;
995 unsigned short read_shortint(int f)
999 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1002 int32 read_int(int f)
1009 #if SIZEOF_INT32 > 4
1010 if (num & (int32)0x80000000)
1011 num |= ~(int32)0xffffffff;
1016 int64 read_longint(int f)
1021 if (protocol_version < 30) {
1024 if ((int32)num != (int32)0xffffffff)
1027 #if SIZEOF_INT64 < 8
1028 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1029 exit_cleanup(RERR_UNSUPPORTED);
1032 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1037 cnt = int_byte_cnt[CVAL(b, 0) / 4];
1038 #if SIZEOF_INT64 < 8
1039 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
1040 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1041 exit_cleanup(RERR_UNSUPPORTED);
1045 readfd(f, b + 3, cnt - 3);
1051 num = NVAL4(b, 0x80);
1054 num = NVAL5(b, 0xC0);
1056 #if SIZEOF_INT64 >= 8
1058 num = NVAL6(b, 0xE0);
1061 num = NVAL7(b, 0xF0);
1064 num = NVAL8(b, 0xF8);
1067 num = NVAL8(b+1, 0);
1071 exit_cleanup(RERR_PROTOCOL); /* impossible... */
1078 void read_buf(int f, char *buf, size_t len)
1083 void read_sbuf(int f, char *buf, size_t len)
1085 readfd(f, buf, len);
1089 uchar read_byte(int f)
1092 readfd(f, (char *)&c, 1);
1096 int read_vstring(int f, char *buf, int bufsize)
1098 int len = read_byte(f);
1101 len = (len & ~0x80) * 0x100 + read_byte(f);
1103 if (len >= bufsize) {
1104 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1110 readfd(f, buf, len);
1115 /* Populate a sum_struct with values from the socket. This is
1116 * called by both the sender and the receiver. */
1117 void read_sum_head(int f, struct sum_struct *sum)
1119 sum->count = read_int(f);
1120 if (sum->count < 0) {
1121 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1122 (long)sum->count, who_am_i());
1123 exit_cleanup(RERR_PROTOCOL);
1125 sum->blength = read_int(f);
1126 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1127 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1128 (long)sum->blength, who_am_i());
1129 exit_cleanup(RERR_PROTOCOL);
1131 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1132 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1133 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1134 sum->s2length, who_am_i());
1135 exit_cleanup(RERR_PROTOCOL);
1137 sum->remainder = read_int(f);
1138 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1139 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1140 (long)sum->remainder, who_am_i());
1141 exit_cleanup(RERR_PROTOCOL);
1145 /* Send the values from a sum_struct over the socket. Set sum to
1146 * NULL if there are no checksums to send. This is called by both
1147 * the generator and the sender. */
1148 void write_sum_head(int f, struct sum_struct *sum)
1150 static struct sum_struct null_sum;
1155 write_int(f, sum->count);
1156 write_int(f, sum->blength);
1157 if (protocol_version >= 27)
1158 write_int(f, sum->s2length);
1159 write_int(f, sum->remainder);
1163 * Sleep after writing to limit I/O bandwidth usage.
1165 * @todo Rather than sleeping after each write, it might be better to
1166 * use some kind of averaging. The current algorithm seems to always
1167 * use a bit less bandwidth than specified, because it doesn't make up
1168 * for slow periods. But arguably this is a feature. In addition, we
1169 * ought to take the time used to write the data into account.
1171 * During some phases of big transfers (file FOO is uptodate) this is
1172 * called with a small bytes_written every time. As the kernel has to
1173 * round small waits up to guarantee that we actually wait at least the
1174 * requested number of microseconds, this can become grossly inaccurate.
1175 * We therefore keep track of the bytes we've written over time and only
1176 * sleep when the accumulated delay is at least 1 tenth of a second.
1178 static void sleep_for_bwlimit(int bytes_written)
1180 static struct timeval prior_tv;
1181 static long total_written = 0;
1182 struct timeval tv, start_tv;
1183 long elapsed_usec, sleep_usec;
1185 #define ONE_SEC 1000000L /* # of microseconds in a second */
1187 if (!bwlimit_writemax)
1190 total_written += bytes_written;
1192 gettimeofday(&start_tv, NULL);
1193 if (prior_tv.tv_sec) {
1194 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1195 + (start_tv.tv_usec - prior_tv.tv_usec);
1196 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1197 if (total_written < 0)
1201 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1202 if (sleep_usec < ONE_SEC / 10) {
1203 prior_tv = start_tv;
1207 tv.tv_sec = sleep_usec / ONE_SEC;
1208 tv.tv_usec = sleep_usec % ONE_SEC;
1209 select(0, NULL, NULL, NULL, &tv);
1211 gettimeofday(&prior_tv, NULL);
1212 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1213 + (prior_tv.tv_usec - start_tv.tv_usec);
1214 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1217 /* Write len bytes to the file descriptor fd, looping as necessary to get
1218 * the job done and also (in certain circumstances) reading any data on
1219 * msg_fd_in to avoid deadlock.
1221 * This function underlies the multiplexing system. The body of the
1222 * application never calls this function directly. */
1223 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1225 size_t n, total = 0;
1226 fd_set w_fds, r_fds, e_fds;
1227 int maxfd, count, cnt, using_r_fds;
1228 int defer_save = defer_forwarding_messages;
1232 defer_forwarding_messages = 1;
1234 while (total < len) {
1241 if (msg_fd_in >= 0) {
1243 FD_SET(msg_fd_in, &r_fds);
1244 if (msg_fd_in > maxfd)
1250 tv.tv_sec = select_timeout;
1254 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1255 &w_fds, &e_fds, &tv);
1258 if (count < 0 && errno == EBADF)
1259 exit_cleanup(RERR_SOCKETIO);
1264 if (FD_ISSET(fd, &e_fds)) {
1265 rsyserr(FINFO, errno,
1266 "select exception on fd %d", fd);
1269 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1272 if (!FD_ISSET(fd, &w_fds))
1276 if (bwlimit_writemax && n > bwlimit_writemax)
1277 n = bwlimit_writemax;
1278 cnt = write(fd, buf + total, n);
1284 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1290 /* Don't try to write errors back across the stream. */
1291 if (fd == sock_f_out)
1292 io_end_multiplex_out();
1293 /* Don't try to write errors down a failing msg pipe. */
1294 if (am_server && fd == msg_fd_out)
1295 exit_cleanup(RERR_STREAMIO);
1296 rsyserr(FERROR, errno,
1297 "writefd_unbuffered failed to write %ld bytes [%s]",
1298 (long)len, who_am_i());
1299 /* If the other side is sending us error messages, try
1300 * to grab any messages they sent before they died. */
1301 while (fd == sock_f_out && io_multiplexing_in) {
1304 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1305 sizeof io_filesfrom_buf);
1307 exit_cleanup(RERR_STREAMIO);
1311 defer_forwarding_messages = 1;
1313 if (fd == sock_f_out) {
1314 if (io_timeout || am_generator)
1315 last_io_out = time(NULL);
1316 sleep_for_bwlimit(cnt);
1321 if (!(defer_forwarding_messages = defer_save))
1325 void io_flush(int flush_it_all)
1327 if (flush_it_all && !defer_forwarding_messages)
1330 if (!iobuf_out_cnt || no_flush)
1333 if (io_multiplexing_out)
1334 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt);
1336 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1340 static void writefd(int fd, const char *buf, size_t len)
1342 if (fd == sock_f_out)
1343 stats.total_written += len;
1345 if (fd == write_batch_monitor_out) {
1346 if ((size_t)write(batch_fd, buf, len) != len)
1347 exit_cleanup(RERR_FILEIO);
1350 if (!iobuf_out || fd != iobuf_f_out) {
1351 writefd_unbuffered(fd, buf, len);
1356 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1358 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1364 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1365 io_flush(NORMAL_FLUSH);
1369 void write_shortint(int f, unsigned short x)
1373 b[1] = (char)(x >> 8);
1377 void write_int(int f, int32 x)
1385 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1386 * 64-bit types on this platform.
1388 void write_longint(int f, int64 x)
1392 #if SIZEOF_INT64 < 8
1393 if (x < 0 || x > 0x7FFFFFFF) {
1394 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1395 exit_cleanup(RERR_UNSUPPORTED);
1399 if (protocol_version < 30) {
1400 char * const s = b+4;
1402 #if SIZEOF_INT64 < 8
1405 if (x <= 0x7FFFFFFF && x >= 0) {
1411 SIVAL(s, 4, x >> 32);
1416 } else if (x < ((int32)1<<(3*8-1))) {
1417 b[0] = (char)(x >> 16);
1418 b[1] = (char)(x >> 8);
1421 } else if (x < ((int64)1<<(4*8-2))) {
1422 b[0] = (char)((x >> 24) | 0x80);
1423 b[1] = (char)(x >> 16);
1424 b[2] = (char)(x >> 8);
1427 #if SIZEOF_INT64 < 8
1430 b[1] = (char)(x >> 24);
1431 b[2] = (char)(x >> 16);
1432 b[3] = (char)(x >> 8);
1437 } else if (x < ((int64)1<<(5*8-3))) {
1438 b[0] = (char)((x >> 32) | 0xC0);
1439 b[1] = (char)(x >> 24);
1440 b[2] = (char)(x >> 16);
1441 b[3] = (char)(x >> 8);
1444 } else if (x < ((int64)1<<(6*8-4))) {
1445 b[0] = (char)((x >> 40) | 0xE0);
1446 b[1] = (char)(x >> 32);
1447 b[2] = (char)(x >> 24);
1448 b[3] = (char)(x >> 16);
1449 b[4] = (char)(x >> 8);
1452 } else if (x < ((int64)1<<(7*8-5))) {
1453 b[0] = (char)((x >> 48) | 0xF0);
1454 b[1] = (char)(x >> 40);
1455 b[2] = (char)(x >> 32);
1456 b[3] = (char)(x >> 24);
1457 b[4] = (char)(x >> 16);
1458 b[5] = (char)(x >> 8);
1461 } else if (x < ((int64)1<<(8*8-6))) {
1462 b[0] = (char)((x >> 56) | 0xF8);
1463 b[1] = (char)(x >> 48);
1464 b[2] = (char)(x >> 40);
1465 b[3] = (char)(x >> 32);
1466 b[4] = (char)(x >> 24);
1467 b[5] = (char)(x >> 16);
1468 b[6] = (char)(x >> 8);
1474 b[1] = (char)(x >> 56);
1475 b[2] = (char)(x >> 48);
1476 b[3] = (char)(x >> 40);
1477 b[4] = (char)(x >> 32);
1478 b[5] = (char)(x >> 24);
1479 b[6] = (char)(x >> 16);
1480 b[7] = (char)(x >> 8);
1487 void write_buf(int f, const char *buf, size_t len)
1492 /** Write a string to the connection */
1493 void write_sbuf(int f, const char *buf)
1495 writefd(f, buf, strlen(buf));
1498 void write_byte(int f, uchar c)
1500 writefd(f, (char *)&c, 1);
1503 void write_vstring(int f, const char *str, int len)
1505 uchar lenbuf[3], *lb = lenbuf;
1510 "attempting to send over-long vstring (%d > %d)\n",
1512 exit_cleanup(RERR_PROTOCOL);
1514 *lb++ = len / 0x100 + 0x80;
1518 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1520 writefd(f, str, len);
1523 /* Send a file-list index using a byte-reduction method. */
1524 void write_ndx(int f, int32 ndx)
1526 static int32 prev_positive = -1, prev_negative = 1;
1527 int32 diff, cnt = 0;
1530 if (protocol_version < 30 || read_batch) {
1535 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1536 * negative nums as a positive after sending a leading 0xFF. */
1538 diff = ndx - prev_positive;
1539 prev_positive = ndx;
1540 } else if (ndx == NDX_DONE) {
1545 b[cnt++] = (char)0xFF;
1547 diff = ndx - prev_negative;
1548 prev_negative = ndx;
1551 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1552 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1553 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1554 if (diff < 0xFE && diff > 0)
1555 b[cnt++] = (char)diff;
1556 else if (diff < 0 || diff > 0x7FFF) {
1557 b[cnt++] = (char)0xFE;
1558 b[cnt++] = (char)((ndx >> 24) | 0x80);
1559 b[cnt++] = (char)(ndx >> 16);
1560 b[cnt++] = (char)(ndx >> 8);
1561 b[cnt++] = (char)ndx;
1563 b[cnt++] = (char)0xFE;
1564 b[cnt++] = (char)(diff >> 8);
1565 b[cnt++] = (char)diff;
1570 /* Receive a file-list index using a byte-reduction method. */
1571 int32 read_ndx(int f)
1573 static int32 prev_positive = -1, prev_negative = 1;
1574 int32 *prev_ptr, num;
1577 if (protocol_version < 30)
1581 if (CVAL(b, 0) == 0xFF) {
1583 prev_ptr = &prev_negative;
1584 } else if (CVAL(b, 0) == 0)
1587 prev_ptr = &prev_positive;
1588 if (CVAL(b, 0) == 0xFE) {
1590 if (CVAL(b, 0) & 0x80) {
1592 num = NVAL4(b, 0x80);
1594 num = NVAL2(b, 0) + *prev_ptr;
1596 num = CVAL(b, 0) + *prev_ptr;
1598 if (prev_ptr == &prev_negative)
1604 * Read a line of up to @p maxlen characters into @p buf (not counting
1605 * the trailing null). Strips the (required) trailing newline and all
1608 * @return 1 for success; 0 for I/O error or truncation.
1610 int read_line(int f, char *buf, size_t maxlen)
1614 read_buf(f, buf, 1);
1619 if (buf[0] != '\r') {
1628 void io_printf(int fd, const char *format, ...)
1631 char buf[BIGPATHBUFLEN];
1634 va_start(ap, format);
1635 len = vsnprintf(buf, sizeof buf, format, ap);
1639 exit_cleanup(RERR_STREAMIO);
1641 if (len > (int)sizeof buf) {
1642 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1643 exit_cleanup(RERR_STREAMIO);
1646 write_sbuf(fd, buf);
1649 /** Setup for multiplexing a MSG_* stream with the data stream. */
1650 void io_start_multiplex_out(void)
1652 io_flush(NORMAL_FLUSH);
1653 io_start_buffering_out(sock_f_out);
1654 io_multiplexing_out = 1;
1657 /** Setup for multiplexing a MSG_* stream with the data stream. */
1658 void io_start_multiplex_in(void)
1660 io_flush(NORMAL_FLUSH);
1661 io_start_buffering_in(sock_f_in);
1662 io_multiplexing_in = 1;
1665 /** Write an message to the multiplexed data stream. */
1666 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1668 if (!io_multiplexing_out)
1670 io_flush(NORMAL_FLUSH);
1671 stats.total_written += (len+4);
1672 mplex_write(sock_f_out, code, buf, len);
1676 void io_end_multiplex_in(void)
1678 io_multiplexing_in = 0;
1679 io_end_buffering_in();
1682 /** Stop output multiplexing. */
1683 void io_end_multiplex_out(void)
1685 io_multiplexing_out = 0;
1686 io_end_buffering_out();
1689 void start_write_batch(int fd)
1691 /* Some communication has already taken place, but we don't
1692 * enable batch writing until here so that we can write a
1693 * canonical record of the communication even though the
1694 * actual communication so far depends on whether a daemon
1696 write_int(batch_fd, protocol_version);
1697 write_int(batch_fd, checksum_seed);
1700 write_batch_monitor_out = fd;
1702 write_batch_monitor_in = fd;
1705 void stop_write_batch(void)
1707 write_batch_monitor_out = -1;
1708 write_batch_monitor_in = -1;