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(). */
266 defer_forwarding_messages++;
271 len = tag & 0xFFFFFF;
272 tag = (tag >> 24) - MPLEX_BASE;
276 if (len != 0 || !am_generator) {
278 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
279 tag, len, who_am_i(),
280 incremental ? "/incremental" : "");
281 exit_cleanup(RERR_STREAMIO);
286 if (len != 4 || !am_generator)
289 if (remove_source_files)
290 decrement_active_files(IVAL(buf,0));
291 flist_ndx_push(&redo_list, IVAL(buf,0));
293 decrement_flist_in_progress(IVAL(buf,0), 1);
296 if (len != 4 || !am_generator || !incremental)
299 /* Read extra file list from receiver. */
300 assert(iobuf_in != NULL);
301 assert(iobuf_f_in == fd);
302 flist = recv_file_list(fd);
303 flist->parent_ndx = IVAL(buf,0);
306 if (len != 0 || !am_generator || !incremental)
311 if (len >= (int)sizeof buf || !am_generator)
313 readfd(fd, buf, len);
314 send_msg(MSG_DELETED, buf, len);
317 if (len != 4 || !am_generator)
319 readfd(fd, buf, len);
320 if (remove_source_files) {
321 decrement_active_files(IVAL(buf,0));
322 send_msg(MSG_SUCCESS, buf, len);
324 if (preserve_hard_links)
325 flist_ndx_push(&hlink_list, IVAL(buf,0));
327 decrement_flist_in_progress(IVAL(buf,0), 0);
330 if (len != 4 || !am_generator)
332 readfd(fd, buf, len);
334 decrement_flist_in_progress(IVAL(buf,0), 0);
340 if (tag == MSG_SOCKERR)
341 io_end_multiplex_out();
351 rwrite((enum logcode)tag, buf, n);
356 rprintf(FERROR, "unknown message %d:%d [%s]\n",
357 tag, len, who_am_i());
358 exit_cleanup(RERR_STREAMIO);
361 defer_forwarding_messages--;
365 /* This is used by the generator to limit how many file transfers can
366 * be active at once when --remove-source-files is specified. Without
367 * this, sender-side deletions were mostly happening at the end. */
368 void increment_active_files(int ndx, int itemizing, enum logcode code)
370 /* TODO: tune these limits? */
371 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
372 #ifdef SUPPORT_HARD_LINKS
374 check_for_finished_hlinks(itemizing, code);
380 active_bytecnt += F_LENGTH(cur_flist->files[ndx]);
383 static void decrement_active_files(int ndx)
385 struct file_list *flist = flist_for_ndx(ndx);
386 assert(flist != NULL);
388 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
391 static void decrement_flist_in_progress(int ndx, int redo)
393 struct file_list *flist = cur_flist ? cur_flist : first_flist;
395 while (ndx < flist->ndx_start) {
396 if (flist == first_flist) {
399 "Invalid file index: %d (%d - %d) [%s]\n",
400 ndx, first_flist->ndx_start,
401 first_flist->prev->ndx_start + first_flist->prev->count - 1,
403 exit_cleanup(RERR_PROTOCOL);
407 while (ndx >= flist->ndx_start + flist->count) {
408 if (!(flist = flist->next))
412 flist->in_progress--;
417 /* Try to push messages off the list onto the wire. If we leave with more
418 * to do, return 0. On error, return -1. If everything flushed, return 1.
419 * This is only active in the receiver. */
420 static int msg2genr_flush(void)
422 if (msg_fd_out < 0 || no_flush || flist_forward_from >= 0)
426 while (msg2genr.head) {
427 struct msg_list_item *m = msg2genr.head;
428 writefd(msg_fd_out, m->buf, m->len);
429 msg2genr.head = m->next;
431 msg2genr.tail = NULL;
435 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
442 int send_msg(enum msgcode code, const char *buf, int len)
444 if (msg_fd_out < 0) {
445 if (!defer_forwarding_messages)
446 return io_multiplex_write(code, buf, len);
447 if (!io_multiplexing_out)
449 msg_list_add(&msg2sndr, code, buf, len);
452 msg_list_add(&msg2genr, code, buf, len);
457 void send_msg_int(enum msgcode code, int num)
460 SIVAL(numbuf, 0, num);
461 send_msg(code, numbuf, 4);
464 void wait_for_receiver(void)
469 int get_redo_num(void)
471 return flist_ndx_pop(&redo_list);
474 int get_hlink_num(void)
476 return flist_ndx_pop(&hlink_list);
480 * When we're the receiver and we have a local --files-from list of names
481 * that needs to be sent over the socket to the sender, we have to do two
482 * things at the same time: send the sender a list of what files we're
483 * processing and read the incoming file+info list from the sender. We do
484 * this by augmenting the read_timeout() function to copy this data. It
485 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
486 * ready, since it might be a pipe) and then blast it out f_out (when it
487 * is ready to receive more data).
489 void io_set_filesfrom_fds(int f_in, int f_out)
491 io_filesfrom_f_in = f_in;
492 io_filesfrom_f_out = f_out;
493 io_filesfrom_bp = io_filesfrom_buf;
494 io_filesfrom_lastchar = '\0';
495 io_filesfrom_buflen = 0;
498 /* It's almost always an error to get an EOF when we're trying to read from the
499 * network, because the protocol is (for the most part) self-terminating.
501 * There is one case for the receiver when it is at the end of the transfer
502 * (hanging around reading any keep-alive packets that might come its way): if
503 * the sender dies before the generator's kill-signal comes through, we can end
504 * up here needing to loop until the kill-signal arrives. In this situation,
505 * kluge_around_eof will be < 0.
507 * There is another case for older protocol versions (< 24) where the module
508 * listing was not terminated, so we must ignore an EOF error in that case and
509 * exit. In this situation, kluge_around_eof will be > 0. */
510 static void whine_about_eof(int fd)
512 if (kluge_around_eof && fd == sock_f_in) {
514 if (kluge_around_eof > 0)
516 /* If we're still here after 10 seconds, exit with an error. */
517 for (i = 10*1000/20; i--; )
521 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
522 "(%.0f bytes received so far) [%s]\n",
523 (double)stats.total_read, who_am_i());
525 exit_cleanup(RERR_STREAMIO);
529 * Read from a socket with I/O timeout. return the number of bytes
530 * read. If no bytes can be read then exit, never return a number <= 0.
532 * TODO: If the remote shell connection fails, then current versions
533 * actually report an "unexpected EOF" error here. Since it's a
534 * fairly common mistake to try to use rsh when ssh is required, we
535 * should trap that: if we fail to read any data at all, we should
536 * give a better explanation. We can tell whether the connection has
537 * started by looking e.g. at whether the remote version is known yet.
539 static int read_timeout(int fd, char *buf, size_t len)
543 io_flush(FULL_FLUSH);
546 /* until we manage to read *something* */
556 FD_SET(msg_fd_out, &w_fds);
557 if (msg_fd_out > maxfd)
560 if (io_filesfrom_f_out >= 0) {
562 if (io_filesfrom_buflen == 0) {
563 if (io_filesfrom_f_in >= 0) {
564 FD_SET(io_filesfrom_f_in, &r_fds);
565 new_fd = io_filesfrom_f_in;
567 io_filesfrom_f_out = -1;
571 FD_SET(io_filesfrom_f_out, &w_fds);
572 new_fd = io_filesfrom_f_out;
578 tv.tv_sec = select_timeout;
583 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
587 exit_cleanup(RERR_SOCKETIO);
592 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
595 if (io_filesfrom_f_out >= 0) {
596 if (io_filesfrom_buflen) {
597 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
598 int l = write(io_filesfrom_f_out,
600 io_filesfrom_buflen);
602 if (!(io_filesfrom_buflen -= l))
603 io_filesfrom_bp = io_filesfrom_buf;
605 io_filesfrom_bp += l;
607 /* XXX should we complain? */
608 io_filesfrom_f_out = -1;
611 } else if (io_filesfrom_f_in >= 0) {
612 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
613 int l = read(io_filesfrom_f_in,
615 sizeof io_filesfrom_buf);
617 /* Send end-of-file marker */
618 io_filesfrom_buf[0] = '\0';
619 io_filesfrom_buf[1] = '\0';
620 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
621 io_filesfrom_f_in = -1;
624 char *s = io_filesfrom_buf + l;
625 /* Transform CR and/or LF into '\0' */
626 while (s-- > io_filesfrom_buf) {
627 if (*s == '\n' || *s == '\r')
631 if (!io_filesfrom_lastchar) {
632 /* Last buf ended with a '\0', so don't
633 * let this buf start with one. */
634 while (l && !*io_filesfrom_bp)
635 io_filesfrom_bp++, l--;
638 io_filesfrom_bp = io_filesfrom_buf;
640 char *f = io_filesfrom_bp;
643 /* Eliminate any multi-'\0' runs. */
645 if (!(*t++ = *f++)) {
646 while (f != eob && !*f)
650 io_filesfrom_lastchar = f[-1];
652 io_filesfrom_buflen = l;
658 if (!FD_ISSET(fd, &r_fds))
661 n = read(fd, buf, len);
665 whine_about_eof(fd); /* Doesn't return. */
666 if (errno == EINTR || errno == EWOULDBLOCK
670 /* Don't write errors on a dead socket. */
671 if (fd == sock_f_in) {
672 io_end_multiplex_out();
673 rsyserr(FSOCKERR, errno, "read error");
675 rsyserr(FERROR, errno, "read error");
676 exit_cleanup(RERR_STREAMIO);
683 if (fd == sock_f_in && io_timeout)
684 last_io_in = time(NULL);
691 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
694 int read_filesfrom_line(int fd, char *fname)
696 char ch, *s, *eob = fname + MAXPATHLEN - 1;
698 int reading_remotely = filesfrom_host != NULL;
699 int nulls = eol_nulls || reading_remotely;
704 cnt = read(fd, &ch, 1);
705 if (cnt < 0 && (errno == EWOULDBLOCK
706 || errno == EINTR || errno == EAGAIN)) {
713 tv.tv_sec = select_timeout;
715 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
717 if (FD_ISSET(fd, &e_fds)) {
718 rsyserr(FINFO, errno,
719 "select exception on fd %d", fd);
725 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
726 /* Skip empty lines if reading locally. */
727 if (!reading_remotely && s == fname)
737 if (*fname == '#' || *fname == ';')
743 int io_start_buffering_out(int f_out)
746 assert(f_out == iobuf_f_out);
749 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
750 out_of_memory("io_start_buffering_out");
756 int io_start_buffering_in(int f_in)
759 assert(f_in == iobuf_f_in);
762 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
763 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
764 out_of_memory("io_start_buffering_in");
769 void io_end_buffering_in(void)
776 iobuf_in_remaining = 0;
780 void io_end_buffering_out(void)
784 io_flush(FULL_FLUSH);
790 void maybe_flush_socket(void)
792 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
793 io_flush(NORMAL_FLUSH);
796 void maybe_send_keepalive(void)
798 if (time(NULL) - last_io_out >= allowed_lull) {
799 if (!iobuf_out || !iobuf_out_cnt) {
800 if (protocol_version < 29)
801 return; /* there's nothing we can do */
802 if (protocol_version >= 30)
803 send_msg(MSG_NOOP, "", 0);
805 write_int(sock_f_out, cur_flist->count);
806 write_shortint(sock_f_out, ITEM_IS_NEW);
810 io_flush(NORMAL_FLUSH);
814 void start_flist_forward(int f_in)
816 assert(iobuf_out != NULL);
817 assert(iobuf_f_out == msg_fd_out);
818 flist_forward_from = f_in;
821 void stop_flist_forward()
823 flist_forward_from = -1;
824 io_flush(FULL_FLUSH);
828 * Continue trying to read len bytes - don't return until len has been
831 static void read_loop(int fd, char *buf, size_t len)
834 int n = read_timeout(fd, buf, len);
842 * Read from the file descriptor handling multiplexing - return number
845 * Never returns <= 0.
847 static int readfd_unbuffered(int fd, char *buf, size_t len)
851 char line[BIGPATHBUFLEN];
853 if (!iobuf_in || fd != iobuf_f_in)
854 return read_timeout(fd, buf, len);
856 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
857 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
862 if (iobuf_in_remaining) {
863 len = MIN(len, iobuf_in_remaining);
864 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
866 iobuf_in_remaining -= len;
871 read_loop(fd, line, 4);
874 msg_bytes = tag & 0xFFFFFF;
875 tag = (tag >> 24) - MPLEX_BASE;
879 if (msg_bytes > iobuf_in_siz) {
880 if (!(iobuf_in = realloc_array(iobuf_in, char,
882 out_of_memory("readfd_unbuffered");
883 iobuf_in_siz = msg_bytes;
885 read_loop(fd, iobuf_in, msg_bytes);
886 iobuf_in_remaining = msg_bytes;
891 maybe_send_keepalive();
896 read_loop(fd, line, msg_bytes);
897 io_error |= IVAL(line, 0);
900 if (msg_bytes >= sizeof line)
902 read_loop(fd, line, msg_bytes);
903 /* A directory name was sent with the trailing null */
904 if (msg_bytes > 0 && !line[msg_bytes-1])
905 log_delete(line, S_IFDIR);
907 line[msg_bytes] = '\0';
908 log_delete(line, S_IFREG);
912 if (msg_bytes != 4) {
914 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
915 tag, (long)msg_bytes, who_am_i());
916 exit_cleanup(RERR_STREAMIO);
918 read_loop(fd, line, msg_bytes);
919 successful_send(IVAL(line, 0));
924 read_loop(fd, line, msg_bytes);
925 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
929 if (msg_bytes >= sizeof line) {
932 "multiplexing overflow %d:%ld [%s]\n",
933 tag, (long)msg_bytes, who_am_i());
934 exit_cleanup(RERR_STREAMIO);
936 read_loop(fd, line, msg_bytes);
937 rwrite((enum logcode)tag, line, msg_bytes);
940 rprintf(FERROR, "unexpected tag %d [%s]\n",
942 exit_cleanup(RERR_STREAMIO);
946 if (iobuf_in_remaining == 0)
947 io_flush(NORMAL_FLUSH);
952 /* Do a buffered read from fd. Don't return until all N bytes have
953 * been read. If all N can't be read then exit with an error. */
954 static void readfd(int fd, char *buffer, size_t N)
960 cnt = readfd_unbuffered(fd, buffer + total, N-total);
964 if (fd == write_batch_monitor_in) {
965 if ((size_t)write(batch_fd, buffer, total) != total)
966 exit_cleanup(RERR_FILEIO);
969 if (fd == flist_forward_from)
970 writefd(iobuf_f_out, buffer, total);
973 stats.total_read += total;
976 unsigned short read_shortint(int f)
980 return (UVAL(b, 1) << 8) + UVAL(b, 0);
983 int32 read_int(int f)
991 if (num & (int32)0x80000000)
992 num |= ~(int32)0xffffffff;
997 int64 read_longint(int f)
1002 if (protocol_version < 30) {
1005 if ((int32)num != (int32)0xffffffff)
1008 #if SIZEOF_INT64 < 8
1009 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1010 exit_cleanup(RERR_UNSUPPORTED);
1013 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1018 cnt = int_byte_cnt[CVAL(b, 0) / 4];
1019 #if SIZEOF_INT64 < 8
1020 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
1021 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1022 exit_cleanup(RERR_UNSUPPORTED);
1026 readfd(f, b + 3, cnt - 3);
1032 num = NVAL4(b, 0x80);
1035 num = NVAL5(b, 0xC0);
1037 #if SIZEOF_INT64 >= 8
1039 num = NVAL6(b, 0xE0);
1042 num = NVAL7(b, 0xF0);
1045 num = NVAL8(b, 0xF8);
1048 num = NVAL8(b+1, 0);
1052 exit_cleanup(RERR_PROTOCOL); /* impossible... */
1059 void read_buf(int f, char *buf, size_t len)
1064 void read_sbuf(int f, char *buf, size_t len)
1066 readfd(f, buf, len);
1070 uchar read_byte(int f)
1073 readfd(f, (char *)&c, 1);
1077 int read_vstring(int f, char *buf, int bufsize)
1079 int len = read_byte(f);
1082 len = (len & ~0x80) * 0x100 + read_byte(f);
1084 if (len >= bufsize) {
1085 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1091 readfd(f, buf, len);
1096 /* Populate a sum_struct with values from the socket. This is
1097 * called by both the sender and the receiver. */
1098 void read_sum_head(int f, struct sum_struct *sum)
1100 sum->count = read_int(f);
1101 if (sum->count < 0) {
1102 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1103 (long)sum->count, who_am_i());
1104 exit_cleanup(RERR_PROTOCOL);
1106 sum->blength = read_int(f);
1107 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1108 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1109 (long)sum->blength, who_am_i());
1110 exit_cleanup(RERR_PROTOCOL);
1112 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1113 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1114 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1115 sum->s2length, who_am_i());
1116 exit_cleanup(RERR_PROTOCOL);
1118 sum->remainder = read_int(f);
1119 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1120 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1121 (long)sum->remainder, who_am_i());
1122 exit_cleanup(RERR_PROTOCOL);
1126 /* Send the values from a sum_struct over the socket. Set sum to
1127 * NULL if there are no checksums to send. This is called by both
1128 * the generator and the sender. */
1129 void write_sum_head(int f, struct sum_struct *sum)
1131 static struct sum_struct null_sum;
1136 write_int(f, sum->count);
1137 write_int(f, sum->blength);
1138 if (protocol_version >= 27)
1139 write_int(f, sum->s2length);
1140 write_int(f, sum->remainder);
1144 * Sleep after writing to limit I/O bandwidth usage.
1146 * @todo Rather than sleeping after each write, it might be better to
1147 * use some kind of averaging. The current algorithm seems to always
1148 * use a bit less bandwidth than specified, because it doesn't make up
1149 * for slow periods. But arguably this is a feature. In addition, we
1150 * ought to take the time used to write the data into account.
1152 * During some phases of big transfers (file FOO is uptodate) this is
1153 * called with a small bytes_written every time. As the kernel has to
1154 * round small waits up to guarantee that we actually wait at least the
1155 * requested number of microseconds, this can become grossly inaccurate.
1156 * We therefore keep track of the bytes we've written over time and only
1157 * sleep when the accumulated delay is at least 1 tenth of a second.
1159 static void sleep_for_bwlimit(int bytes_written)
1161 static struct timeval prior_tv;
1162 static long total_written = 0;
1163 struct timeval tv, start_tv;
1164 long elapsed_usec, sleep_usec;
1166 #define ONE_SEC 1000000L /* # of microseconds in a second */
1168 if (!bwlimit_writemax)
1171 total_written += bytes_written;
1173 gettimeofday(&start_tv, NULL);
1174 if (prior_tv.tv_sec) {
1175 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1176 + (start_tv.tv_usec - prior_tv.tv_usec);
1177 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1178 if (total_written < 0)
1182 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1183 if (sleep_usec < ONE_SEC / 10) {
1184 prior_tv = start_tv;
1188 tv.tv_sec = sleep_usec / ONE_SEC;
1189 tv.tv_usec = sleep_usec % ONE_SEC;
1190 select(0, NULL, NULL, NULL, &tv);
1192 gettimeofday(&prior_tv, NULL);
1193 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1194 + (prior_tv.tv_usec - start_tv.tv_usec);
1195 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1198 /* Write len bytes to the file descriptor fd, looping as necessary to get
1199 * the job done and also (in certain circumstances) reading any data on
1200 * msg_fd_in to avoid deadlock.
1202 * This function underlies the multiplexing system. The body of the
1203 * application never calls this function directly. */
1204 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1206 size_t n, total = 0;
1207 fd_set w_fds, r_fds, e_fds;
1208 int maxfd, count, cnt, using_r_fds;
1209 int defer_save = defer_forwarding_messages;
1214 while (total < len) {
1221 if (msg_fd_in >= 0) {
1223 FD_SET(msg_fd_in, &r_fds);
1224 if (msg_fd_in > maxfd)
1230 tv.tv_sec = select_timeout;
1234 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1235 &w_fds, &e_fds, &tv);
1238 if (count < 0 && errno == EBADF)
1239 exit_cleanup(RERR_SOCKETIO);
1244 if (FD_ISSET(fd, &e_fds)) {
1245 rsyserr(FINFO, errno,
1246 "select exception on fd %d", fd);
1249 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1252 if (!FD_ISSET(fd, &w_fds))
1256 if (bwlimit_writemax && n > bwlimit_writemax)
1257 n = bwlimit_writemax;
1258 cnt = write(fd, buf + total, n);
1264 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1270 /* Don't try to write errors back across the stream. */
1271 if (fd == sock_f_out)
1272 io_end_multiplex_out();
1273 rsyserr(FERROR, errno,
1274 "writefd_unbuffered failed to write %ld bytes [%s]",
1275 (long)len, who_am_i());
1276 /* If the other side is sending us error messages, try
1277 * to grab any messages they sent before they died. */
1278 while (fd == sock_f_out && io_multiplexing_in) {
1281 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1282 sizeof io_filesfrom_buf);
1284 exit_cleanup(RERR_STREAMIO);
1288 defer_forwarding_messages = 1;
1290 if (fd == sock_f_out) {
1291 if (io_timeout || am_generator)
1292 last_io_out = time(NULL);
1293 sleep_for_bwlimit(cnt);
1297 defer_forwarding_messages = defer_save;
1301 static void msg2sndr_flush(void)
1303 if (defer_forwarding_messages)
1306 while (msg2sndr.head && io_multiplexing_out) {
1307 struct msg_list_item *m = msg2sndr.head;
1308 if (!(msg2sndr.head = m->next))
1309 msg2sndr.tail = NULL;
1310 stats.total_written += m->len;
1311 defer_forwarding_messages = 1;
1312 writefd_unbuffered(sock_f_out, m->buf, m->len);
1313 defer_forwarding_messages = 0;
1319 * Write an message to a multiplexed stream. If this fails then rsync
1322 static void mplex_write(enum msgcode code, const char *buf, size_t len)
1327 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1329 if (n > sizeof buffer - 4)
1332 memcpy(buffer + 4, buf, n);
1334 writefd_unbuffered(sock_f_out, buffer, n+4);
1340 defer_forwarding_messages = 1;
1341 writefd_unbuffered(sock_f_out, buf, len);
1342 defer_forwarding_messages = 0;
1347 void io_flush(int flush_it_all)
1354 if (!iobuf_out_cnt || no_flush)
1357 if (io_multiplexing_out)
1358 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1360 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1364 static void writefd(int fd, const char *buf, size_t len)
1366 if (fd == sock_f_out)
1367 stats.total_written += len;
1369 if (fd == write_batch_monitor_out) {
1370 if ((size_t)write(batch_fd, buf, len) != len)
1371 exit_cleanup(RERR_FILEIO);
1374 if (!iobuf_out || fd != iobuf_f_out) {
1375 writefd_unbuffered(fd, buf, len);
1380 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1382 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1388 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1389 io_flush(NORMAL_FLUSH);
1393 void write_shortint(int f, unsigned short x)
1397 b[1] = (char)(x >> 8);
1401 void write_int(int f, int32 x)
1409 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1410 * 64-bit types on this platform.
1412 void write_longint(int f, int64 x)
1416 #if SIZEOF_INT64 < 8
1417 if (x < 0 || x > 0x7FFFFFFF) {
1418 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1419 exit_cleanup(RERR_UNSUPPORTED);
1423 if (protocol_version < 30) {
1424 char * const s = b+4;
1426 #if SIZEOF_INT64 < 8
1429 if (x <= 0x7FFFFFFF && x >= 0) {
1435 SIVAL(s, 4, x >> 32);
1440 } else if (x < ((int32)1<<(3*8-1))) {
1441 b[0] = (char)(x >> 16);
1442 b[1] = (char)(x >> 8);
1445 } else if (x < ((int64)1<<(4*8-2))) {
1446 b[0] = (char)((x >> 24) | 0x80);
1447 b[1] = (char)(x >> 16);
1448 b[2] = (char)(x >> 8);
1451 #if SIZEOF_INT64 < 8
1454 b[1] = (char)(x >> 24);
1455 b[2] = (char)(x >> 16);
1456 b[3] = (char)(x >> 8);
1461 } else if (x < ((int64)1<<(5*8-3))) {
1462 b[0] = (char)((x >> 32) | 0xC0);
1463 b[1] = (char)(x >> 24);
1464 b[2] = (char)(x >> 16);
1465 b[3] = (char)(x >> 8);
1468 } else if (x < ((int64)1<<(6*8-4))) {
1469 b[0] = (char)((x >> 40) | 0xE0);
1470 b[1] = (char)(x >> 32);
1471 b[2] = (char)(x >> 24);
1472 b[3] = (char)(x >> 16);
1473 b[4] = (char)(x >> 8);
1476 } else if (x < ((int64)1<<(7*8-5))) {
1477 b[0] = (char)((x >> 48) | 0xF0);
1478 b[1] = (char)(x >> 40);
1479 b[2] = (char)(x >> 32);
1480 b[3] = (char)(x >> 24);
1481 b[4] = (char)(x >> 16);
1482 b[5] = (char)(x >> 8);
1485 } else if (x < ((int64)1<<(8*8-6))) {
1486 b[0] = (char)((x >> 56) | 0xF8);
1487 b[1] = (char)(x >> 48);
1488 b[2] = (char)(x >> 40);
1489 b[3] = (char)(x >> 32);
1490 b[4] = (char)(x >> 24);
1491 b[5] = (char)(x >> 16);
1492 b[6] = (char)(x >> 8);
1498 b[1] = (char)(x >> 56);
1499 b[2] = (char)(x >> 48);
1500 b[3] = (char)(x >> 40);
1501 b[4] = (char)(x >> 32);
1502 b[5] = (char)(x >> 24);
1503 b[6] = (char)(x >> 16);
1504 b[7] = (char)(x >> 8);
1511 void write_buf(int f, const char *buf, size_t len)
1516 /** Write a string to the connection */
1517 void write_sbuf(int f, const char *buf)
1519 writefd(f, buf, strlen(buf));
1522 void write_byte(int f, uchar c)
1524 writefd(f, (char *)&c, 1);
1527 void write_vstring(int f, const char *str, int len)
1529 uchar lenbuf[3], *lb = lenbuf;
1534 "attempting to send over-long vstring (%d > %d)\n",
1536 exit_cleanup(RERR_PROTOCOL);
1538 *lb++ = len / 0x100 + 0x80;
1542 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1544 writefd(f, str, len);
1547 /* Send a file-list index using a byte-reduction method. */
1548 void write_ndx(int f, int32 ndx)
1550 static int32 prev_positive = -1, prev_negative = 1;
1551 int32 diff, cnt = 0;
1554 if (protocol_version < 30 || read_batch) {
1559 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1560 * negative nums as a positive after sending a leading 0xFF. */
1562 diff = ndx - prev_positive;
1563 prev_positive = ndx;
1564 } else if (ndx == NDX_DONE) {
1569 b[cnt++] = (char)0xFF;
1571 diff = ndx - prev_negative;
1572 prev_negative = ndx;
1575 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1576 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1577 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1578 if (diff < 0xFE && diff > 0)
1579 b[cnt++] = (char)diff;
1580 else if (diff < 0 || diff > 0x7FFF) {
1581 b[cnt++] = (char)0xFE;
1582 b[cnt++] = (char)((ndx >> 24) | 0x80);
1583 b[cnt++] = (char)(ndx >> 16);
1584 b[cnt++] = (char)(ndx >> 8);
1585 b[cnt++] = (char)ndx;
1587 b[cnt++] = (char)0xFE;
1588 b[cnt++] = (char)(diff >> 8);
1589 b[cnt++] = (char)diff;
1594 /* Receive a file-list index using a byte-reduction method. */
1595 int32 read_ndx(int f)
1597 static int32 prev_positive = -1, prev_negative = 1;
1598 int32 *prev_ptr, num;
1601 if (protocol_version < 30)
1605 if (CVAL(b, 0) == 0xFF) {
1607 prev_ptr = &prev_negative;
1608 } else if (CVAL(b, 0) == 0)
1611 prev_ptr = &prev_positive;
1612 if (CVAL(b, 0) == 0xFE) {
1614 if (CVAL(b, 0) & 0x80) {
1616 num = NVAL4(b, 0x80);
1618 num = NVAL2(b, 0) + *prev_ptr;
1620 num = CVAL(b, 0) + *prev_ptr;
1622 if (prev_ptr == &prev_negative)
1628 * Read a line of up to @p maxlen characters into @p buf (not counting
1629 * the trailing null). Strips the (required) trailing newline and all
1632 * @return 1 for success; 0 for I/O error or truncation.
1634 int read_line(int f, char *buf, size_t maxlen)
1638 read_buf(f, buf, 1);
1643 if (buf[0] != '\r') {
1652 void io_printf(int fd, const char *format, ...)
1655 char buf[BIGPATHBUFLEN];
1658 va_start(ap, format);
1659 len = vsnprintf(buf, sizeof buf, format, ap);
1663 exit_cleanup(RERR_STREAMIO);
1665 if (len > (int)sizeof buf) {
1666 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1667 exit_cleanup(RERR_STREAMIO);
1670 write_sbuf(fd, buf);
1673 /** Setup for multiplexing a MSG_* stream with the data stream. */
1674 void io_start_multiplex_out(void)
1676 io_flush(NORMAL_FLUSH);
1677 io_start_buffering_out(sock_f_out);
1678 io_multiplexing_out = 1;
1681 /** Setup for multiplexing a MSG_* stream with the data stream. */
1682 void io_start_multiplex_in(void)
1684 io_flush(NORMAL_FLUSH);
1685 io_start_buffering_in(sock_f_in);
1686 io_multiplexing_in = 1;
1689 /** Write an message to the multiplexed data stream. */
1690 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1692 if (!io_multiplexing_out)
1694 io_flush(NORMAL_FLUSH);
1695 stats.total_written += (len+4);
1696 mplex_write(code, buf, len);
1700 void io_end_multiplex_in(void)
1702 io_multiplexing_in = 0;
1703 io_end_buffering_in();
1706 /** Stop output multiplexing. */
1707 void io_end_multiplex_out(void)
1709 io_multiplexing_out = 0;
1710 io_end_buffering_out();
1713 void start_write_batch(int fd)
1715 /* Some communication has already taken place, but we don't
1716 * enable batch writing until here so that we can write a
1717 * canonical record of the communication even though the
1718 * actual communication so far depends on whether a daemon
1720 write_int(batch_fd, protocol_version);
1721 write_int(batch_fd, checksum_seed);
1724 write_batch_monitor_out = fd;
1726 write_batch_monitor_in = fd;
1729 void stop_write_batch(void)
1731 write_batch_monitor_out = -1;
1732 write_batch_monitor_in = -1;