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 incremental;
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 msg2genr, 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 /* Read a message from the MSG_* fd and handle it. This is called either
252 * during the early stages of being a local sender (up through the sending
253 * of the file list) or when we're the generator (to fetch the messages
254 * from the receiver). */
255 static void read_msg_fd(void)
259 struct file_list *flist;
263 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
264 * to this routine from writefd_unbuffered(). */
270 len = tag & 0xFFFFFF;
271 tag = (tag >> 24) - MPLEX_BASE;
275 if (len != 0 || !am_generator) {
277 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
278 tag, len, who_am_i(),
279 incremental ? "/incremental" : "");
280 exit_cleanup(RERR_STREAMIO);
285 if (len != 4 || !am_generator)
288 if (remove_source_files)
289 decrement_active_files(IVAL(buf,0));
290 flist_ndx_push(&redo_list, IVAL(buf,0));
292 decrement_flist_in_progress(IVAL(buf,0), 1);
295 if (len != 4 || !am_generator || !incremental)
298 /* Read extra file list from receiver. */
299 assert(iobuf_in != NULL);
300 assert(iobuf_f_in == fd);
301 flist = recv_file_list(fd);
302 flist->parent_ndx = IVAL(buf,0);
305 if (len != 0 || !am_generator || !incremental)
310 if (len >= (int)sizeof buf || !am_generator)
312 readfd(fd, buf, len);
313 send_msg(MSG_DELETED, buf, len);
316 if (len != 4 || !am_generator)
318 readfd(fd, buf, len);
319 if (remove_source_files) {
320 decrement_active_files(IVAL(buf,0));
321 send_msg(MSG_SUCCESS, buf, len);
323 if (preserve_hard_links)
324 flist_ndx_push(&hlink_list, IVAL(buf,0));
326 decrement_flist_in_progress(IVAL(buf,0), 0);
329 if (len != 4 || !am_generator)
331 readfd(fd, buf, len);
333 decrement_flist_in_progress(IVAL(buf,0), 0);
339 if (tag == MSG_SOCKERR)
340 io_end_multiplex_out();
350 rwrite((enum logcode)tag, buf, n);
355 rprintf(FERROR, "unknown message %d:%d [%s]\n",
356 tag, len, who_am_i());
357 exit_cleanup(RERR_STREAMIO);
363 /* This is used by the generator to limit how many file transfers can
364 * be active at once when --remove-source-files is specified. Without
365 * this, sender-side deletions were mostly happening at the end. */
366 void increment_active_files(int ndx, int itemizing, enum logcode code)
368 /* TODO: tune these limits? */
369 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
370 #ifdef SUPPORT_HARD_LINKS
372 check_for_finished_hlinks(itemizing, code);
378 active_bytecnt += F_LENGTH(cur_flist->files[ndx]);
381 static void decrement_active_files(int ndx)
383 struct file_list *flist = flist_for_ndx(ndx);
384 assert(flist != NULL);
386 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
389 static void decrement_flist_in_progress(int ndx, int redo)
391 struct file_list *flist = cur_flist ? cur_flist : first_flist;
393 while (ndx < flist->ndx_start) {
394 if (flist == first_flist) {
397 "Invalid file index: %d (%d - %d) [%s]\n",
398 ndx, first_flist->ndx_start,
399 first_flist->prev->ndx_start + first_flist->prev->count - 1,
401 exit_cleanup(RERR_PROTOCOL);
405 while (ndx >= flist->ndx_start + flist->count) {
406 if (!(flist = flist->next))
410 flist->in_progress--;
415 /* Try to push messages off the list onto the wire. If we leave with more
416 * to do, return 0. On error, return -1. If everything flushed, return 1.
417 * This is only active in the receiver. */
418 static int msg2genr_flush(void)
420 if (msg_fd_out < 0 || no_flush || flist_forward_from >= 0)
424 while (msg2genr.head) {
425 struct msg_list_item *m = msg2genr.head;
426 writefd(msg_fd_out, m->buf, m->len);
427 msg2genr.head = m->next;
429 msg2genr.tail = NULL;
433 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
440 int send_msg(enum msgcode code, const char *buf, int len)
442 if (msg_fd_out < 0) {
443 if (!defer_forwarding_messages)
444 return io_multiplex_write(code, buf, len);
445 if (!io_multiplexing_out)
447 msg_list_add(&msg2sndr, code, buf, len);
450 msg_list_add(&msg2genr, code, buf, len);
455 void send_msg_int(enum msgcode code, int num)
458 SIVAL(numbuf, 0, num);
459 send_msg(code, numbuf, 4);
462 void wait_for_receiver(void)
467 int get_redo_num(void)
469 return flist_ndx_pop(&redo_list);
472 int get_hlink_num(void)
474 return flist_ndx_pop(&hlink_list);
478 * When we're the receiver and we have a local --files-from list of names
479 * that needs to be sent over the socket to the sender, we have to do two
480 * things at the same time: send the sender a list of what files we're
481 * processing and read the incoming file+info list from the sender. We do
482 * this by augmenting the read_timeout() function to copy this data. It
483 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
484 * ready, since it might be a pipe) and then blast it out f_out (when it
485 * is ready to receive more data).
487 void io_set_filesfrom_fds(int f_in, int f_out)
489 io_filesfrom_f_in = f_in;
490 io_filesfrom_f_out = f_out;
491 io_filesfrom_bp = io_filesfrom_buf;
492 io_filesfrom_lastchar = '\0';
493 io_filesfrom_buflen = 0;
496 /* It's almost always an error to get an EOF when we're trying to read from the
497 * network, because the protocol is (for the most part) self-terminating.
499 * There is one case for the receiver when it is at the end of the transfer
500 * (hanging around reading any keep-alive packets that might come its way): if
501 * the sender dies before the generator's kill-signal comes through, we can end
502 * up here needing to loop until the kill-signal arrives. In this situation,
503 * kluge_around_eof will be < 0.
505 * There is another case for older protocol versions (< 24) where the module
506 * listing was not terminated, so we must ignore an EOF error in that case and
507 * exit. In this situation, kluge_around_eof will be > 0. */
508 static void whine_about_eof(int fd)
510 if (kluge_around_eof && fd == sock_f_in) {
512 if (kluge_around_eof > 0)
514 /* If we're still here after 10 seconds, exit with an error. */
515 for (i = 10*1000/20; i--; )
519 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
520 "(%.0f bytes received so far) [%s]\n",
521 (double)stats.total_read, who_am_i());
523 exit_cleanup(RERR_STREAMIO);
527 * Read from a socket with I/O timeout. return the number of bytes
528 * read. If no bytes can be read then exit, never return a number <= 0.
530 * TODO: If the remote shell connection fails, then current versions
531 * actually report an "unexpected EOF" error here. Since it's a
532 * fairly common mistake to try to use rsh when ssh is required, we
533 * should trap that: if we fail to read any data at all, we should
534 * give a better explanation. We can tell whether the connection has
535 * started by looking e.g. at whether the remote version is known yet.
537 static int read_timeout(int fd, char *buf, size_t len)
541 io_flush(FULL_FLUSH);
544 /* until we manage to read *something* */
554 FD_SET(msg_fd_out, &w_fds);
555 if (msg_fd_out > maxfd)
558 if (io_filesfrom_f_out >= 0) {
560 if (io_filesfrom_buflen == 0) {
561 if (io_filesfrom_f_in >= 0) {
562 FD_SET(io_filesfrom_f_in, &r_fds);
563 new_fd = io_filesfrom_f_in;
565 io_filesfrom_f_out = -1;
569 FD_SET(io_filesfrom_f_out, &w_fds);
570 new_fd = io_filesfrom_f_out;
576 tv.tv_sec = select_timeout;
581 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
585 exit_cleanup(RERR_SOCKETIO);
590 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
593 if (io_filesfrom_f_out >= 0) {
594 if (io_filesfrom_buflen) {
595 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
596 int l = write(io_filesfrom_f_out,
598 io_filesfrom_buflen);
600 if (!(io_filesfrom_buflen -= l))
601 io_filesfrom_bp = io_filesfrom_buf;
603 io_filesfrom_bp += l;
605 /* XXX should we complain? */
606 io_filesfrom_f_out = -1;
609 } else if (io_filesfrom_f_in >= 0) {
610 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
611 int l = read(io_filesfrom_f_in,
613 sizeof io_filesfrom_buf);
615 /* Send end-of-file marker */
616 io_filesfrom_buf[0] = '\0';
617 io_filesfrom_buf[1] = '\0';
618 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
619 io_filesfrom_f_in = -1;
622 char *s = io_filesfrom_buf + l;
623 /* Transform CR and/or LF into '\0' */
624 while (s-- > io_filesfrom_buf) {
625 if (*s == '\n' || *s == '\r')
629 if (!io_filesfrom_lastchar) {
630 /* Last buf ended with a '\0', so don't
631 * let this buf start with one. */
632 while (l && !*io_filesfrom_bp)
633 io_filesfrom_bp++, l--;
636 io_filesfrom_bp = io_filesfrom_buf;
638 char *f = io_filesfrom_bp;
641 /* Eliminate any multi-'\0' runs. */
643 if (!(*t++ = *f++)) {
644 while (f != eob && !*f)
648 io_filesfrom_lastchar = f[-1];
650 io_filesfrom_buflen = l;
656 if (!FD_ISSET(fd, &r_fds))
659 n = read(fd, buf, len);
663 whine_about_eof(fd); /* Doesn't return. */
664 if (errno == EINTR || errno == EWOULDBLOCK
668 /* Don't write errors on a dead socket. */
669 if (fd == sock_f_in) {
670 io_end_multiplex_out();
671 rsyserr(FSOCKERR, errno, "read error");
673 rsyserr(FERROR, errno, "read error");
674 exit_cleanup(RERR_STREAMIO);
681 if (fd == sock_f_in && io_timeout)
682 last_io_in = time(NULL);
689 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
692 int read_filesfrom_line(int fd, char *fname)
694 char ch, *s, *eob = fname + MAXPATHLEN - 1;
696 int reading_remotely = filesfrom_host != NULL;
697 int nulls = eol_nulls || reading_remotely;
702 cnt = read(fd, &ch, 1);
703 if (cnt < 0 && (errno == EWOULDBLOCK
704 || errno == EINTR || errno == EAGAIN)) {
711 tv.tv_sec = select_timeout;
713 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
715 if (FD_ISSET(fd, &e_fds)) {
716 rsyserr(FINFO, errno,
717 "select exception on fd %d", fd);
723 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
724 /* Skip empty lines if reading locally. */
725 if (!reading_remotely && s == fname)
735 if (*fname == '#' || *fname == ';')
741 int io_start_buffering_out(int f_out)
744 assert(f_out == iobuf_f_out);
747 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
748 out_of_memory("io_start_buffering_out");
754 int io_start_buffering_in(int f_in)
757 assert(f_in == iobuf_f_in);
760 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
761 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
762 out_of_memory("io_start_buffering_in");
767 void io_end_buffering_in(void)
774 iobuf_in_remaining = 0;
778 void io_end_buffering_out(void)
782 io_flush(FULL_FLUSH);
788 void maybe_flush_socket(void)
790 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
791 io_flush(NORMAL_FLUSH);
794 void maybe_send_keepalive(void)
796 if (time(NULL) - last_io_out >= allowed_lull) {
797 if (!iobuf_out || !iobuf_out_cnt) {
798 if (protocol_version < 29)
799 return; /* there's nothing we can do */
800 if (protocol_version >= 30)
801 send_msg(MSG_NOOP, "", 0);
803 write_int(sock_f_out, cur_flist->count);
804 write_shortint(sock_f_out, ITEM_IS_NEW);
808 io_flush(NORMAL_FLUSH);
812 void start_flist_forward(int f_in)
814 assert(iobuf_out != NULL);
815 assert(iobuf_f_out == msg_fd_out);
816 flist_forward_from = f_in;
819 void stop_flist_forward()
821 flist_forward_from = -1;
822 io_flush(FULL_FLUSH);
826 * Continue trying to read len bytes - don't return until len has been
829 static void read_loop(int fd, char *buf, size_t len)
832 int n = read_timeout(fd, buf, len);
840 * Read from the file descriptor handling multiplexing - return number
843 * Never returns <= 0.
845 static int readfd_unbuffered(int fd, char *buf, size_t len)
849 char line[BIGPATHBUFLEN];
851 if (!iobuf_in || fd != iobuf_f_in)
852 return read_timeout(fd, buf, len);
854 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
855 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
860 if (iobuf_in_remaining) {
861 len = MIN(len, iobuf_in_remaining);
862 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
864 iobuf_in_remaining -= len;
869 read_loop(fd, line, 4);
872 msg_bytes = tag & 0xFFFFFF;
873 tag = (tag >> 24) - MPLEX_BASE;
877 if (msg_bytes > iobuf_in_siz) {
878 if (!(iobuf_in = realloc_array(iobuf_in, char,
880 out_of_memory("readfd_unbuffered");
881 iobuf_in_siz = msg_bytes;
883 read_loop(fd, iobuf_in, msg_bytes);
884 iobuf_in_remaining = msg_bytes;
889 maybe_send_keepalive();
894 read_loop(fd, line, msg_bytes);
895 io_error |= IVAL(line, 0);
898 if (msg_bytes >= sizeof line)
900 read_loop(fd, line, msg_bytes);
901 /* A directory name was sent with the trailing null */
902 if (msg_bytes > 0 && !line[msg_bytes-1])
903 log_delete(line, S_IFDIR);
905 line[msg_bytes] = '\0';
906 log_delete(line, S_IFREG);
910 if (msg_bytes != 4) {
912 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
913 tag, (long)msg_bytes, who_am_i());
914 exit_cleanup(RERR_STREAMIO);
916 read_loop(fd, line, msg_bytes);
917 successful_send(IVAL(line, 0));
922 read_loop(fd, line, msg_bytes);
923 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
927 if (msg_bytes >= sizeof line) {
930 "multiplexing overflow %d:%ld [%s]\n",
931 tag, (long)msg_bytes, who_am_i());
932 exit_cleanup(RERR_STREAMIO);
934 read_loop(fd, line, msg_bytes);
935 rwrite((enum logcode)tag, line, msg_bytes);
938 rprintf(FERROR, "unexpected tag %d [%s]\n",
940 exit_cleanup(RERR_STREAMIO);
944 if (iobuf_in_remaining == 0)
945 io_flush(NORMAL_FLUSH);
950 /* Do a buffered read from fd. Don't return until all N bytes have
951 * been read. If all N can't be read then exit with an error. */
952 static void readfd(int fd, char *buffer, size_t N)
958 cnt = readfd_unbuffered(fd, buffer + total, N-total);
962 if (fd == write_batch_monitor_in) {
963 if ((size_t)write(batch_fd, buffer, total) != total)
964 exit_cleanup(RERR_FILEIO);
967 if (fd == flist_forward_from)
968 writefd(iobuf_f_out, buffer, total);
971 stats.total_read += total;
974 unsigned short read_shortint(int f)
978 return (UVAL(b, 1) << 8) + UVAL(b, 0);
981 int32 read_int(int f)
989 if (num & (int32)0x80000000)
990 num |= ~(int32)0xffffffff;
995 int64 read_longint(int f)
1000 if (protocol_version < 30) {
1003 if ((int32)num != (int32)0xffffffff)
1006 #if SIZEOF_INT64 < 8
1007 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1008 exit_cleanup(RERR_UNSUPPORTED);
1011 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1016 cnt = int_byte_cnt[CVAL(b, 0) / 4];
1017 #if SIZEOF_INT64 < 8
1018 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
1019 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1020 exit_cleanup(RERR_UNSUPPORTED);
1024 readfd(f, b + 3, cnt - 3);
1030 num = NVAL4(b, 0x80);
1033 num = NVAL5(b, 0xC0);
1035 #if SIZEOF_INT64 >= 8
1037 num = NVAL6(b, 0xE0);
1040 num = NVAL7(b, 0xF0);
1043 num = NVAL8(b, 0xF8);
1046 num = NVAL8(b+1, 0);
1050 exit_cleanup(RERR_PROTOCOL); /* impossible... */
1057 void read_buf(int f, char *buf, size_t len)
1062 void read_sbuf(int f, char *buf, size_t len)
1064 readfd(f, buf, len);
1068 uchar read_byte(int f)
1071 readfd(f, (char *)&c, 1);
1075 int read_vstring(int f, char *buf, int bufsize)
1077 int len = read_byte(f);
1080 len = (len & ~0x80) * 0x100 + read_byte(f);
1082 if (len >= bufsize) {
1083 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1089 readfd(f, buf, len);
1094 /* Populate a sum_struct with values from the socket. This is
1095 * called by both the sender and the receiver. */
1096 void read_sum_head(int f, struct sum_struct *sum)
1098 sum->count = read_int(f);
1099 if (sum->count < 0) {
1100 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1101 (long)sum->count, who_am_i());
1102 exit_cleanup(RERR_PROTOCOL);
1104 sum->blength = read_int(f);
1105 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1106 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1107 (long)sum->blength, who_am_i());
1108 exit_cleanup(RERR_PROTOCOL);
1110 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1111 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1112 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1113 sum->s2length, who_am_i());
1114 exit_cleanup(RERR_PROTOCOL);
1116 sum->remainder = read_int(f);
1117 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1118 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1119 (long)sum->remainder, who_am_i());
1120 exit_cleanup(RERR_PROTOCOL);
1124 /* Send the values from a sum_struct over the socket. Set sum to
1125 * NULL if there are no checksums to send. This is called by both
1126 * the generator and the sender. */
1127 void write_sum_head(int f, struct sum_struct *sum)
1129 static struct sum_struct null_sum;
1134 write_int(f, sum->count);
1135 write_int(f, sum->blength);
1136 if (protocol_version >= 27)
1137 write_int(f, sum->s2length);
1138 write_int(f, sum->remainder);
1142 * Sleep after writing to limit I/O bandwidth usage.
1144 * @todo Rather than sleeping after each write, it might be better to
1145 * use some kind of averaging. The current algorithm seems to always
1146 * use a bit less bandwidth than specified, because it doesn't make up
1147 * for slow periods. But arguably this is a feature. In addition, we
1148 * ought to take the time used to write the data into account.
1150 * During some phases of big transfers (file FOO is uptodate) this is
1151 * called with a small bytes_written every time. As the kernel has to
1152 * round small waits up to guarantee that we actually wait at least the
1153 * requested number of microseconds, this can become grossly inaccurate.
1154 * We therefore keep track of the bytes we've written over time and only
1155 * sleep when the accumulated delay is at least 1 tenth of a second.
1157 static void sleep_for_bwlimit(int bytes_written)
1159 static struct timeval prior_tv;
1160 static long total_written = 0;
1161 struct timeval tv, start_tv;
1162 long elapsed_usec, sleep_usec;
1164 #define ONE_SEC 1000000L /* # of microseconds in a second */
1166 if (!bwlimit_writemax)
1169 total_written += bytes_written;
1171 gettimeofday(&start_tv, NULL);
1172 if (prior_tv.tv_sec) {
1173 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1174 + (start_tv.tv_usec - prior_tv.tv_usec);
1175 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1176 if (total_written < 0)
1180 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1181 if (sleep_usec < ONE_SEC / 10) {
1182 prior_tv = start_tv;
1186 tv.tv_sec = sleep_usec / ONE_SEC;
1187 tv.tv_usec = sleep_usec % ONE_SEC;
1188 select(0, NULL, NULL, NULL, &tv);
1190 gettimeofday(&prior_tv, NULL);
1191 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1192 + (prior_tv.tv_usec - start_tv.tv_usec);
1193 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1196 /* Write len bytes to the file descriptor fd, looping as necessary to get
1197 * the job done and also (in certain circumstances) reading any data on
1198 * msg_fd_in to avoid deadlock.
1200 * This function underlies the multiplexing system. The body of the
1201 * application never calls this function directly. */
1202 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1204 size_t n, total = 0;
1205 fd_set w_fds, r_fds, e_fds;
1206 int maxfd, count, cnt, using_r_fds;
1207 int defer_save = defer_forwarding_messages;
1212 while (total < len) {
1219 if (msg_fd_in >= 0) {
1221 FD_SET(msg_fd_in, &r_fds);
1222 if (msg_fd_in > maxfd)
1228 tv.tv_sec = select_timeout;
1232 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1233 &w_fds, &e_fds, &tv);
1236 if (count < 0 && errno == EBADF)
1237 exit_cleanup(RERR_SOCKETIO);
1242 if (FD_ISSET(fd, &e_fds)) {
1243 rsyserr(FINFO, errno,
1244 "select exception on fd %d", fd);
1247 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1250 if (!FD_ISSET(fd, &w_fds))
1254 if (bwlimit_writemax && n > bwlimit_writemax)
1255 n = bwlimit_writemax;
1256 cnt = write(fd, buf + total, n);
1262 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1268 /* Don't try to write errors back across the stream. */
1269 if (fd == sock_f_out)
1270 io_end_multiplex_out();
1271 rsyserr(FERROR, errno,
1272 "writefd_unbuffered failed to write %ld bytes [%s]",
1273 (long)len, who_am_i());
1274 /* If the other side is sending us error messages, try
1275 * to grab any messages they sent before they died. */
1276 while (fd == sock_f_out && io_multiplexing_in) {
1279 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1280 sizeof io_filesfrom_buf);
1282 exit_cleanup(RERR_STREAMIO);
1286 defer_forwarding_messages = 1;
1288 if (fd == sock_f_out) {
1289 if (io_timeout || am_generator)
1290 last_io_out = time(NULL);
1291 sleep_for_bwlimit(cnt);
1295 defer_forwarding_messages = defer_save;
1299 static void msg2sndr_flush(void)
1301 if (defer_forwarding_messages)
1304 while (msg2sndr.head && io_multiplexing_out) {
1305 struct msg_list_item *m = msg2sndr.head;
1306 if (!(msg2sndr.head = m->next))
1307 msg2sndr.tail = NULL;
1308 stats.total_written += m->len;
1309 defer_forwarding_messages = 1;
1310 writefd_unbuffered(sock_f_out, m->buf, m->len);
1311 defer_forwarding_messages = 0;
1317 * Write an message to a multiplexed stream. If this fails then rsync
1320 static void mplex_write(enum msgcode code, const char *buf, size_t len)
1325 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1327 if (n > sizeof buffer - 4)
1330 memcpy(buffer + 4, buf, n);
1332 writefd_unbuffered(sock_f_out, buffer, n+4);
1338 defer_forwarding_messages = 1;
1339 writefd_unbuffered(sock_f_out, buf, len);
1340 defer_forwarding_messages = 0;
1345 void io_flush(int flush_it_all)
1352 if (!iobuf_out_cnt || no_flush)
1355 if (io_multiplexing_out)
1356 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1358 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1362 static void writefd(int fd, const char *buf, size_t len)
1364 if (fd == sock_f_out)
1365 stats.total_written += len;
1367 if (fd == write_batch_monitor_out) {
1368 if ((size_t)write(batch_fd, buf, len) != len)
1369 exit_cleanup(RERR_FILEIO);
1372 if (!iobuf_out || fd != iobuf_f_out) {
1373 writefd_unbuffered(fd, buf, len);
1378 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1380 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1386 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1387 io_flush(NORMAL_FLUSH);
1391 void write_shortint(int f, unsigned short x)
1395 b[1] = (char)(x >> 8);
1399 void write_int(int f, int32 x)
1407 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1408 * 64-bit types on this platform.
1410 void write_longint(int f, int64 x)
1414 #if SIZEOF_INT64 < 8
1415 if (x < 0 || x > 0x7FFFFFFF) {
1416 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1417 exit_cleanup(RERR_UNSUPPORTED);
1421 if (protocol_version < 30) {
1422 char * const s = b+4;
1424 #if SIZEOF_INT64 < 8
1427 if (x <= 0x7FFFFFFF && x >= 0) {
1433 SIVAL(s, 4, x >> 32);
1438 } else if (x < ((int32)1<<(3*8-1))) {
1439 b[0] = (char)(x >> 16);
1440 b[1] = (char)(x >> 8);
1443 } else if (x < ((int64)1<<(4*8-2))) {
1444 b[0] = (char)((x >> 24) | 0x80);
1445 b[1] = (char)(x >> 16);
1446 b[2] = (char)(x >> 8);
1449 #if SIZEOF_INT64 < 8
1452 b[1] = (char)(x >> 24);
1453 b[2] = (char)(x >> 16);
1454 b[3] = (char)(x >> 8);
1459 } else if (x < ((int64)1<<(5*8-3))) {
1460 b[0] = (char)((x >> 32) | 0xC0);
1461 b[1] = (char)(x >> 24);
1462 b[2] = (char)(x >> 16);
1463 b[3] = (char)(x >> 8);
1466 } else if (x < ((int64)1<<(6*8-4))) {
1467 b[0] = (char)((x >> 40) | 0xE0);
1468 b[1] = (char)(x >> 32);
1469 b[2] = (char)(x >> 24);
1470 b[3] = (char)(x >> 16);
1471 b[4] = (char)(x >> 8);
1474 } else if (x < ((int64)1<<(7*8-5))) {
1475 b[0] = (char)((x >> 48) | 0xF0);
1476 b[1] = (char)(x >> 40);
1477 b[2] = (char)(x >> 32);
1478 b[3] = (char)(x >> 24);
1479 b[4] = (char)(x >> 16);
1480 b[5] = (char)(x >> 8);
1483 } else if (x < ((int64)1<<(8*8-6))) {
1484 b[0] = (char)((x >> 56) | 0xF8);
1485 b[1] = (char)(x >> 48);
1486 b[2] = (char)(x >> 40);
1487 b[3] = (char)(x >> 32);
1488 b[4] = (char)(x >> 24);
1489 b[5] = (char)(x >> 16);
1490 b[6] = (char)(x >> 8);
1496 b[1] = (char)(x >> 56);
1497 b[2] = (char)(x >> 48);
1498 b[3] = (char)(x >> 40);
1499 b[4] = (char)(x >> 32);
1500 b[5] = (char)(x >> 24);
1501 b[6] = (char)(x >> 16);
1502 b[7] = (char)(x >> 8);
1509 void write_buf(int f, const char *buf, size_t len)
1514 /** Write a string to the connection */
1515 void write_sbuf(int f, const char *buf)
1517 writefd(f, buf, strlen(buf));
1520 void write_byte(int f, uchar c)
1522 writefd(f, (char *)&c, 1);
1525 void write_vstring(int f, const char *str, int len)
1527 uchar lenbuf[3], *lb = lenbuf;
1532 "attempting to send over-long vstring (%d > %d)\n",
1534 exit_cleanup(RERR_PROTOCOL);
1536 *lb++ = len / 0x100 + 0x80;
1540 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1542 writefd(f, str, len);
1545 /* Send a file-list index using a byte-reduction method. */
1546 void write_ndx(int f, int32 ndx)
1548 static int32 prev_positive = -1, prev_negative = 1;
1549 int32 diff, cnt = 0;
1552 if (protocol_version < 30 || read_batch) {
1557 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1558 * negative nums as a positive after sending a leading 0xFF. */
1560 diff = ndx - prev_positive;
1561 prev_positive = ndx;
1562 } else if (ndx == NDX_DONE) {
1567 b[cnt++] = (char)0xFF;
1569 diff = ndx - prev_negative;
1570 prev_negative = ndx;
1573 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1574 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1575 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1576 if (diff < 0xFE && diff > 0)
1577 b[cnt++] = (char)diff;
1578 else if (diff < 0 || diff > 0x7FFF) {
1579 b[cnt++] = (char)0xFE;
1580 b[cnt++] = (char)((ndx >> 24) | 0x80);
1581 b[cnt++] = (char)(ndx >> 16);
1582 b[cnt++] = (char)(ndx >> 8);
1583 b[cnt++] = (char)ndx;
1585 b[cnt++] = (char)0xFE;
1586 b[cnt++] = (char)(diff >> 8);
1587 b[cnt++] = (char)diff;
1592 /* Receive a file-list index using a byte-reduction method. */
1593 int32 read_ndx(int f)
1595 static int32 prev_positive = -1, prev_negative = 1;
1596 int32 *prev_ptr, num;
1599 if (protocol_version < 30)
1603 if (CVAL(b, 0) == 0xFF) {
1605 prev_ptr = &prev_negative;
1606 } else if (CVAL(b, 0) == 0)
1609 prev_ptr = &prev_positive;
1610 if (CVAL(b, 0) == 0xFE) {
1612 if (CVAL(b, 0) & 0x80) {
1614 num = NVAL4(b, 0x80);
1616 num = NVAL2(b, 0) + *prev_ptr;
1618 num = CVAL(b, 0) + *prev_ptr;
1620 if (prev_ptr == &prev_negative)
1626 * Read a line of up to @p maxlen characters into @p buf (not counting
1627 * the trailing null). Strips the (required) trailing newline and all
1630 * @return 1 for success; 0 for I/O error or truncation.
1632 int read_line(int f, char *buf, size_t maxlen)
1636 read_buf(f, buf, 1);
1641 if (buf[0] != '\r') {
1650 void io_printf(int fd, const char *format, ...)
1653 char buf[BIGPATHBUFLEN];
1656 va_start(ap, format);
1657 len = vsnprintf(buf, sizeof buf, format, ap);
1661 exit_cleanup(RERR_STREAMIO);
1663 if (len > (int)sizeof buf) {
1664 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1665 exit_cleanup(RERR_STREAMIO);
1668 write_sbuf(fd, buf);
1671 /** Setup for multiplexing a MSG_* stream with the data stream. */
1672 void io_start_multiplex_out(void)
1674 io_flush(NORMAL_FLUSH);
1675 io_start_buffering_out(sock_f_out);
1676 io_multiplexing_out = 1;
1679 /** Setup for multiplexing a MSG_* stream with the data stream. */
1680 void io_start_multiplex_in(void)
1682 io_flush(NORMAL_FLUSH);
1683 io_start_buffering_in(sock_f_in);
1684 io_multiplexing_in = 1;
1687 /** Write an message to the multiplexed data stream. */
1688 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1690 if (!io_multiplexing_out)
1692 io_flush(NORMAL_FLUSH);
1693 stats.total_written += (len+4);
1694 mplex_write(code, buf, len);
1698 void io_end_multiplex_in(void)
1700 io_multiplexing_in = 0;
1701 io_end_buffering_in();
1704 /** Stop output multiplexing. */
1705 void io_end_multiplex_out(void)
1707 io_multiplexing_out = 0;
1708 io_end_buffering_out();
1711 void start_write_batch(int fd)
1713 /* Some communication has already taken place, but we don't
1714 * enable batch writing until here so that we can write a
1715 * canonical record of the communication even though the
1716 * actual communication so far depends on whether a daemon
1718 write_int(batch_fd, protocol_version);
1719 write_int(batch_fd, checksum_seed);
1722 write_batch_monitor_out = fd;
1724 write_batch_monitor_in = fd;
1727 void stop_write_batch(void)
1729 write_batch_monitor_out = -1;
1730 write_batch_monitor_in = -1;