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-2007 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 version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
23 /* Rsync provides its own multiplexing system, which is used to send
24 * stderr and stdout over a single socket.
26 * For historical reasons this is off during the start of the
27 * connection, but it's switched on quite early using
28 * io_start_multiplex_out() and io_start_multiplex_in(). */
32 /** If no timeout is specified then use a 60 second select timeout */
33 #define SELECT_TIMEOUT 60
36 extern size_t bwlimit_writemax;
37 extern int io_timeout;
38 extern int allowed_lull;
42 extern int am_generator;
43 extern int inc_recurse;
47 extern int read_batch;
48 extern int csum_length;
49 extern int checksum_seed;
50 extern int protocol_version;
51 extern int remove_source_files;
52 extern int preserve_hard_links;
53 extern char *filesfrom_host;
54 extern struct stats stats;
55 extern struct file_list *cur_flist, *first_flist;
57 const char phase_unknown[] = "unknown";
58 int ignore_timeout = 0;
62 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
63 int kluge_around_eof = 0;
70 static int iobuf_f_in = -1;
71 static char *iobuf_in;
72 static size_t iobuf_in_siz;
73 static size_t iobuf_in_ndx;
74 static size_t iobuf_in_remaining;
76 static int iobuf_f_out = -1;
77 static char *iobuf_out;
78 static int iobuf_out_cnt;
80 int flist_forward_from = -1;
82 static int io_multiplexing_out;
83 static int io_multiplexing_in;
84 static time_t last_io_in;
85 static time_t last_io_out;
88 static int write_batch_monitor_in = -1;
89 static int write_batch_monitor_out = -1;
91 static int io_filesfrom_f_in = -1;
92 static int io_filesfrom_f_out = -1;
93 static char io_filesfrom_buf[2048];
94 static char *io_filesfrom_bp;
95 static char io_filesfrom_lastchar;
96 static int io_filesfrom_buflen;
97 static int defer_forwarding_messages = 0;
98 static int select_timeout = SELECT_TIMEOUT;
99 static int active_filecnt = 0;
100 static OFF_T active_bytecnt = 0;
102 static char int_byte_extra[64] = {
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
105 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
106 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
109 static void readfd(int fd, char *buffer, size_t N);
110 static void writefd(int fd, const char *buf, size_t len);
111 static void writefd_unbuffered(int fd, const char *buf, size_t len);
112 static void decrement_active_files(int ndx);
113 static void decrement_flist_in_progress(int ndx, int redo);
115 struct flist_ndx_item {
116 struct flist_ndx_item *next;
120 struct flist_ndx_list {
121 struct flist_ndx_item *head, *tail;
124 static struct flist_ndx_list redo_list, hlink_list;
126 struct msg_list_item {
127 struct msg_list_item *next;
133 struct msg_list_item *head, *tail;
136 static struct msg_list msg_queue;
138 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
140 struct flist_ndx_item *item;
142 if (!(item = new(struct flist_ndx_item)))
143 out_of_memory("flist_ndx_push");
147 lp->tail->next = item;
153 static int flist_ndx_pop(struct flist_ndx_list *lp)
155 struct flist_ndx_item *next;
162 next = lp->head->next;
171 static void check_timeout(void)
175 if (!io_timeout || ignore_timeout)
179 last_io_in = time(NULL);
185 if (t - last_io_in >= io_timeout) {
186 if (!am_server && !am_daemon) {
187 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
188 (int)(t-last_io_in));
190 exit_cleanup(RERR_TIMEOUT);
194 /* Note the fds used for the main socket (which might really be a pipe
195 * for a local transfer, but we can ignore that). */
196 void io_set_sock_fds(int f_in, int f_out)
202 void set_io_timeout(int secs)
206 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
207 select_timeout = SELECT_TIMEOUT;
209 select_timeout = io_timeout;
211 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
214 /* Setup the fd used to receive MSG_* messages. Only needed during the
215 * early stages of being a local sender (up through the sending of the
216 * file list) or when we're the generator (to fetch the messages from
218 void set_msg_fd_in(int fd)
223 /* Setup the fd used to send our MSG_* messages. Only needed when
224 * we're the receiver (to send our messages to the generator). */
225 void set_msg_fd_out(int fd)
228 set_nonblocking(msg_fd_out);
231 /* Add a message to the pending MSG_* list. */
232 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
234 struct msg_list_item *m;
235 int sz = len + 4 + sizeof m[0] - 1;
237 if (!(m = (struct msg_list_item *)new_array(char, sz)))
238 out_of_memory("msg_list_add");
241 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
242 memcpy(m->buf + 4, buf, len);
250 static void msg_flush(void)
253 while (msg_queue.head && io_multiplexing_out) {
254 struct msg_list_item *m = msg_queue.head;
255 if (!(msg_queue.head = m->next))
256 msg_queue.tail = NULL;
257 stats.total_written += m->len;
258 defer_forwarding_messages++;
259 writefd_unbuffered(sock_f_out, m->buf, m->len);
260 defer_forwarding_messages--;
264 while (msg_queue.head) {
265 struct msg_list_item *m = msg_queue.head;
266 if (!(msg_queue.head = m->next))
267 msg_queue.tail = NULL;
268 defer_forwarding_messages++;
269 writefd_unbuffered(msg_fd_out, m->buf, m->len);
270 defer_forwarding_messages--;
276 /* Read a message from the MSG_* fd and handle it. This is called either
277 * during the early stages of being a local sender (up through the sending
278 * of the file list) or when we're the generator (to fetch the messages
279 * from the receiver). */
280 static void read_msg_fd(void)
284 struct file_list *flist;
288 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
289 * to this routine from writefd_unbuffered(). */
292 defer_forwarding_messages++;
297 len = tag & 0xFFFFFF;
298 tag = (tag >> 24) - MPLEX_BASE;
302 if (len < 0 || len > 1 || !am_generator) {
304 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
305 tag, len, who_am_i(),
306 inc_recurse ? "/inc" : "");
307 exit_cleanup(RERR_STREAMIO);
310 readfd(fd, buf, len);
311 stats.total_read = read_varlong(fd, 3);
316 if (len != 4 || !am_generator)
319 if (remove_source_files)
320 decrement_active_files(IVAL(buf,0));
321 flist_ndx_push(&redo_list, IVAL(buf,0));
323 decrement_flist_in_progress(IVAL(buf,0), 1);
326 if (len != 4 || !am_generator || !inc_recurse)
329 /* Read extra file list from receiver. */
330 assert(iobuf_in != NULL);
331 assert(iobuf_f_in == fd);
332 flist = recv_file_list(fd);
333 flist->parent_ndx = IVAL(buf,0);
336 if (len != 0 || !am_generator || !inc_recurse)
341 if (len >= (int)sizeof buf || !am_generator)
343 readfd(fd, buf, len);
344 send_msg(MSG_DELETED, buf, len);
347 if (len != 4 || !am_generator)
349 readfd(fd, buf, len);
350 if (remove_source_files) {
351 decrement_active_files(IVAL(buf,0));
352 send_msg(MSG_SUCCESS, buf, len);
354 if (preserve_hard_links)
355 flist_ndx_push(&hlink_list, IVAL(buf,0));
357 decrement_flist_in_progress(IVAL(buf,0), 0);
360 if (len != 4 || !am_generator)
362 readfd(fd, buf, len);
364 decrement_flist_in_progress(IVAL(buf,0), 0);
370 if (tag == MSG_SOCKERR)
371 io_end_multiplex_out();
381 rwrite((enum logcode)tag, buf, n);
386 rprintf(FERROR, "unknown message %d:%d [%s]\n",
387 tag, len, who_am_i());
388 exit_cleanup(RERR_STREAMIO);
393 if (!--defer_forwarding_messages)
397 /* This is used by the generator to limit how many file transfers can
398 * be active at once when --remove-source-files is specified. Without
399 * this, sender-side deletions were mostly happening at the end. */
400 void increment_active_files(int ndx, int itemizing, enum logcode code)
402 /* TODO: tune these limits? */
403 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
404 check_for_finished_files(itemizing, code, 0);
406 io_flush(NORMAL_FLUSH);
412 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
415 static void decrement_active_files(int ndx)
417 struct file_list *flist = flist_for_ndx(ndx);
418 assert(flist != NULL);
420 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
423 static void decrement_flist_in_progress(int ndx, int redo)
425 struct file_list *flist = cur_flist ? cur_flist : first_flist;
427 while (ndx < flist->ndx_start) {
428 if (flist == first_flist) {
431 "Invalid file index: %d (%d - %d) [%s]\n",
432 ndx, first_flist->ndx_start,
433 first_flist->prev->ndx_start + first_flist->prev->count - 1,
435 exit_cleanup(RERR_PROTOCOL);
439 while (ndx >= flist->ndx_start + flist->count) {
440 if (!(flist = flist->next))
444 flist->in_progress--;
449 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
450 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len)
455 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
457 if (n > sizeof buffer - 4)
460 memcpy(buffer + 4, buf, n);
462 writefd_unbuffered(fd, buffer, n+4);
468 defer_forwarding_messages++;
469 writefd_unbuffered(fd, buf, len);
470 if (!--defer_forwarding_messages)
475 int send_msg(enum msgcode code, const char *buf, int len)
477 if (msg_fd_out < 0) {
478 if (!defer_forwarding_messages)
479 return io_multiplex_write(code, buf, len);
480 if (!io_multiplexing_out)
482 msg_list_add(&msg_queue, code, buf, len);
485 if (flist_forward_from >= 0)
486 msg_list_add(&msg_queue, code, buf, len);
488 mplex_write(msg_fd_out, code, buf, len);
492 void send_msg_int(enum msgcode code, int num)
495 SIVAL(numbuf, 0, num);
496 send_msg(code, numbuf, 4);
499 void wait_for_receiver(void)
502 io_flush(NORMAL_FLUSH);
507 int get_redo_num(void)
509 return flist_ndx_pop(&redo_list);
512 int get_hlink_num(void)
514 return flist_ndx_pop(&hlink_list);
518 * When we're the receiver and we have a local --files-from list of names
519 * that needs to be sent over the socket to the sender, we have to do two
520 * things at the same time: send the sender a list of what files we're
521 * processing and read the incoming file+info list from the sender. We do
522 * this by augmenting the read_timeout() function to copy this data. It
523 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
524 * ready, since it might be a pipe) and then blast it out f_out (when it
525 * is ready to receive more data).
527 void io_set_filesfrom_fds(int f_in, int f_out)
529 io_filesfrom_f_in = f_in;
530 io_filesfrom_f_out = f_out;
531 io_filesfrom_bp = io_filesfrom_buf;
532 io_filesfrom_lastchar = '\0';
533 io_filesfrom_buflen = 0;
536 /* It's almost always an error to get an EOF when we're trying to read from the
537 * network, because the protocol is (for the most part) self-terminating.
539 * There is one case for the receiver when it is at the end of the transfer
540 * (hanging around reading any keep-alive packets that might come its way): if
541 * the sender dies before the generator's kill-signal comes through, we can end
542 * up here needing to loop until the kill-signal arrives. In this situation,
543 * kluge_around_eof will be < 0.
545 * There is another case for older protocol versions (< 24) where the module
546 * listing was not terminated, so we must ignore an EOF error in that case and
547 * exit. In this situation, kluge_around_eof will be > 0. */
548 static void whine_about_eof(int fd)
550 if (kluge_around_eof && fd == sock_f_in) {
552 if (kluge_around_eof > 0)
554 /* If we're still here after 10 seconds, exit with an error. */
555 for (i = 10*1000/20; i--; )
559 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
560 "(%.0f bytes received so far) [%s]\n",
561 (double)stats.total_read, who_am_i());
563 exit_cleanup(RERR_STREAMIO);
567 * Read from a socket with I/O timeout. return the number of bytes
568 * read. If no bytes can be read then exit, never return a number <= 0.
570 * TODO: If the remote shell connection fails, then current versions
571 * actually report an "unexpected EOF" error here. Since it's a
572 * fairly common mistake to try to use rsh when ssh is required, we
573 * should trap that: if we fail to read any data at all, we should
574 * give a better explanation. We can tell whether the connection has
575 * started by looking e.g. at whether the remote version is known yet.
577 static int read_timeout(int fd, char *buf, size_t len)
581 io_flush(FULL_FLUSH);
584 /* until we manage to read *something* */
593 if (io_filesfrom_f_out >= 0) {
595 if (io_filesfrom_buflen == 0) {
596 if (io_filesfrom_f_in >= 0) {
597 FD_SET(io_filesfrom_f_in, &r_fds);
598 new_fd = io_filesfrom_f_in;
600 io_filesfrom_f_out = -1;
604 FD_SET(io_filesfrom_f_out, &w_fds);
605 new_fd = io_filesfrom_f_out;
611 tv.tv_sec = select_timeout;
616 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
619 if (errno == EBADF) {
620 defer_forwarding_messages = 0;
621 exit_cleanup(RERR_SOCKETIO);
627 if (io_filesfrom_f_out >= 0) {
628 if (io_filesfrom_buflen) {
629 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
630 int l = write(io_filesfrom_f_out,
632 io_filesfrom_buflen);
634 if (!(io_filesfrom_buflen -= l))
635 io_filesfrom_bp = io_filesfrom_buf;
637 io_filesfrom_bp += l;
639 /* XXX should we complain? */
640 io_filesfrom_f_out = -1;
643 } else if (io_filesfrom_f_in >= 0) {
644 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
645 int l = read(io_filesfrom_f_in,
647 sizeof io_filesfrom_buf);
649 /* Send end-of-file marker */
650 io_filesfrom_buf[0] = '\0';
651 io_filesfrom_buf[1] = '\0';
652 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
653 io_filesfrom_f_in = -1;
656 char *s = io_filesfrom_buf + l;
657 /* Transform CR and/or LF into '\0' */
658 while (s-- > io_filesfrom_buf) {
659 if (*s == '\n' || *s == '\r')
663 if (!io_filesfrom_lastchar) {
664 /* Last buf ended with a '\0', so don't
665 * let this buf start with one. */
666 while (l && !*io_filesfrom_bp)
667 io_filesfrom_bp++, l--;
670 io_filesfrom_bp = io_filesfrom_buf;
672 char *f = io_filesfrom_bp;
675 /* Eliminate any multi-'\0' runs. */
677 if (!(*t++ = *f++)) {
678 while (f != eob && !*f)
682 io_filesfrom_lastchar = f[-1];
684 io_filesfrom_buflen = l;
690 if (!FD_ISSET(fd, &r_fds))
693 n = read(fd, buf, len);
697 whine_about_eof(fd); /* Doesn't return. */
698 if (errno == EINTR || errno == EWOULDBLOCK
702 /* Don't write errors on a dead socket. */
703 if (fd == sock_f_in) {
704 io_end_multiplex_out();
705 rsyserr(FSOCKERR, errno, "read error");
707 rsyserr(FERROR, errno, "read error");
708 exit_cleanup(RERR_STREAMIO);
715 if (fd == sock_f_in && io_timeout)
716 last_io_in = time(NULL);
723 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
726 int read_filesfrom_line(int fd, char *fname)
728 char ch, *s, *eob = fname + MAXPATHLEN - 1;
730 int reading_remotely = filesfrom_host != NULL;
731 int nulls = eol_nulls || reading_remotely;
736 cnt = read(fd, &ch, 1);
737 if (cnt < 0 && (errno == EWOULDBLOCK
738 || errno == EINTR || errno == EAGAIN)) {
745 tv.tv_sec = select_timeout;
747 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
749 if (FD_ISSET(fd, &e_fds)) {
750 rsyserr(FINFO, errno,
751 "select exception on fd %d", fd);
757 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
758 /* Skip empty lines if reading locally. */
759 if (!reading_remotely && s == fname)
769 if (*fname == '#' || *fname == ';')
775 int io_start_buffering_out(int f_out)
778 assert(f_out == iobuf_f_out);
781 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
782 out_of_memory("io_start_buffering_out");
788 int io_start_buffering_in(int f_in)
791 assert(f_in == iobuf_f_in);
794 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
795 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
796 out_of_memory("io_start_buffering_in");
801 void io_end_buffering_in(void)
808 iobuf_in_remaining = 0;
812 void io_end_buffering_out(void)
816 io_flush(FULL_FLUSH);
822 void maybe_flush_socket(int important)
824 if (iobuf_out && iobuf_out_cnt
825 && (important || time(NULL) - last_io_out >= 5))
826 io_flush(NORMAL_FLUSH);
829 void maybe_send_keepalive(void)
831 if (time(NULL) - last_io_out >= allowed_lull) {
832 if (!iobuf_out || !iobuf_out_cnt) {
833 if (protocol_version < 29)
834 return; /* there's nothing we can do */
835 if (protocol_version >= 30)
836 send_msg(MSG_NOOP, "", 0);
838 write_int(sock_f_out, cur_flist->count);
839 write_shortint(sock_f_out, ITEM_IS_NEW);
843 io_flush(NORMAL_FLUSH);
847 void start_flist_forward(int f_in)
849 assert(iobuf_out != NULL);
850 assert(iobuf_f_out == msg_fd_out);
851 flist_forward_from = f_in;
854 void stop_flist_forward()
856 flist_forward_from = -1;
857 io_flush(FULL_FLUSH);
861 * Continue trying to read len bytes - don't return until len has been
864 static void read_loop(int fd, char *buf, size_t len)
867 int n = read_timeout(fd, buf, len);
875 * Read from the file descriptor handling multiplexing - return number
878 * Never returns <= 0.
880 static int readfd_unbuffered(int fd, char *buf, size_t len)
884 char line[BIGPATHBUFLEN];
886 if (!iobuf_in || fd != iobuf_f_in)
887 return read_timeout(fd, buf, len);
889 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
890 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
895 if (iobuf_in_remaining) {
896 len = MIN(len, iobuf_in_remaining);
897 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
899 iobuf_in_remaining -= len;
904 read_loop(fd, line, 4);
907 msg_bytes = tag & 0xFFFFFF;
908 tag = (tag >> 24) - MPLEX_BASE;
912 if (msg_bytes > iobuf_in_siz) {
913 if (!(iobuf_in = realloc_array(iobuf_in, char,
915 out_of_memory("readfd_unbuffered");
916 iobuf_in_siz = msg_bytes;
918 read_loop(fd, iobuf_in, msg_bytes);
919 iobuf_in_remaining = msg_bytes;
924 maybe_send_keepalive();
929 read_loop(fd, line, msg_bytes);
930 io_error |= IVAL(line, 0);
933 if (msg_bytes >= sizeof line)
935 read_loop(fd, line, msg_bytes);
936 /* A directory name was sent with the trailing null */
937 if (msg_bytes > 0 && !line[msg_bytes-1])
938 log_delete(line, S_IFDIR);
940 line[msg_bytes] = '\0';
941 log_delete(line, S_IFREG);
945 if (msg_bytes != 4) {
947 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
948 tag, (long)msg_bytes, who_am_i());
949 exit_cleanup(RERR_STREAMIO);
951 read_loop(fd, line, msg_bytes);
952 successful_send(IVAL(line, 0));
957 read_loop(fd, line, msg_bytes);
958 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
962 if (msg_bytes >= sizeof line) {
965 "multiplexing overflow %d:%ld [%s]\n",
966 tag, (long)msg_bytes, who_am_i());
967 exit_cleanup(RERR_STREAMIO);
969 read_loop(fd, line, msg_bytes);
970 rwrite((enum logcode)tag, line, msg_bytes);
973 rprintf(FERROR, "unexpected tag %d [%s]\n",
975 exit_cleanup(RERR_STREAMIO);
979 if (iobuf_in_remaining == 0)
980 io_flush(NORMAL_FLUSH);
985 /* Do a buffered read from fd. Don't return until all N bytes have
986 * been read. If all N can't be read then exit with an error. */
987 static void readfd(int fd, char *buffer, size_t N)
993 cnt = readfd_unbuffered(fd, buffer + total, N-total);
997 if (fd == write_batch_monitor_in) {
998 if ((size_t)write(batch_fd, buffer, total) != total)
999 exit_cleanup(RERR_FILEIO);
1002 if (fd == flist_forward_from)
1003 writefd(iobuf_f_out, buffer, total);
1005 if (fd == sock_f_in)
1006 stats.total_read += total;
1009 unsigned short read_shortint(int f)
1013 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1016 int32 read_int(int f)
1023 #if SIZEOF_INT32 > 4
1024 if (num & (int32)0x80000000)
1025 num |= ~(int32)0xffffffff;
1030 int32 read_varint(int f)
1040 readfd(f, (char*)&ch, 1);
1041 extra = int_byte_extra[ch / 4];
1043 uchar bit = ((uchar)1<<(8-extra));
1044 if (extra >= (int)sizeof u.b) {
1045 rprintf(FERROR, "Overflow in read_varint()\n");
1046 exit_cleanup(RERR_STREAMIO);
1048 readfd(f, u.b, extra);
1049 u.b[extra] = ch & (bit-1);
1052 #if CAREFUL_ALIGNMENT
1055 #if SIZEOF_INT32 > 4
1056 if (u.x & (int32)0x80000000)
1057 u.x |= ~(int32)0xffffffff;
1062 int64 read_varlong(int f, uchar min_bytes)
1071 #if SIZEOF_INT64 < 8
1076 readfd(f, b2, min_bytes);
1077 memcpy(u.b, b2+1, min_bytes-1);
1078 extra = int_byte_extra[CVAL(b2, 0) / 4];
1080 uchar bit = ((uchar)1<<(8-extra));
1081 if (min_bytes + extra > (int)sizeof u.b) {
1082 rprintf(FERROR, "Overflow in read_varlong()\n");
1083 exit_cleanup(RERR_STREAMIO);
1085 readfd(f, u.b + min_bytes - 1, extra);
1086 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1087 #if SIZEOF_INT64 < 8
1088 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1089 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1090 exit_cleanup(RERR_UNSUPPORTED);
1094 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1095 #if SIZEOF_INT64 < 8
1097 #elif CAREFUL_ALIGNMENT
1098 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1103 int64 read_longint(int f)
1105 #if SIZEOF_INT64 >= 8
1108 int32 num = read_int(f);
1110 if (num != (int32)0xffffffff)
1113 #if SIZEOF_INT64 < 8
1114 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1115 exit_cleanup(RERR_UNSUPPORTED);
1118 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1122 void read_buf(int f, char *buf, size_t len)
1127 void read_sbuf(int f, char *buf, size_t len)
1129 readfd(f, buf, len);
1133 uchar read_byte(int f)
1136 readfd(f, (char *)&c, 1);
1140 int read_vstring(int f, char *buf, int bufsize)
1142 int len = read_byte(f);
1145 len = (len & ~0x80) * 0x100 + read_byte(f);
1147 if (len >= bufsize) {
1148 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1154 readfd(f, buf, len);
1159 /* Populate a sum_struct with values from the socket. This is
1160 * called by both the sender and the receiver. */
1161 void read_sum_head(int f, struct sum_struct *sum)
1163 sum->count = read_int(f);
1164 if (sum->count < 0) {
1165 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1166 (long)sum->count, who_am_i());
1167 exit_cleanup(RERR_PROTOCOL);
1169 sum->blength = read_int(f);
1170 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1171 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1172 (long)sum->blength, who_am_i());
1173 exit_cleanup(RERR_PROTOCOL);
1175 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1176 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1177 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1178 sum->s2length, who_am_i());
1179 exit_cleanup(RERR_PROTOCOL);
1181 sum->remainder = read_int(f);
1182 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1183 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1184 (long)sum->remainder, who_am_i());
1185 exit_cleanup(RERR_PROTOCOL);
1189 /* Send the values from a sum_struct over the socket. Set sum to
1190 * NULL if there are no checksums to send. This is called by both
1191 * the generator and the sender. */
1192 void write_sum_head(int f, struct sum_struct *sum)
1194 static struct sum_struct null_sum;
1199 write_int(f, sum->count);
1200 write_int(f, sum->blength);
1201 if (protocol_version >= 27)
1202 write_int(f, sum->s2length);
1203 write_int(f, sum->remainder);
1207 * Sleep after writing to limit I/O bandwidth usage.
1209 * @todo Rather than sleeping after each write, it might be better to
1210 * use some kind of averaging. The current algorithm seems to always
1211 * use a bit less bandwidth than specified, because it doesn't make up
1212 * for slow periods. But arguably this is a feature. In addition, we
1213 * ought to take the time used to write the data into account.
1215 * During some phases of big transfers (file FOO is uptodate) this is
1216 * called with a small bytes_written every time. As the kernel has to
1217 * round small waits up to guarantee that we actually wait at least the
1218 * requested number of microseconds, this can become grossly inaccurate.
1219 * We therefore keep track of the bytes we've written over time and only
1220 * sleep when the accumulated delay is at least 1 tenth of a second.
1222 static void sleep_for_bwlimit(int bytes_written)
1224 static struct timeval prior_tv;
1225 static long total_written = 0;
1226 struct timeval tv, start_tv;
1227 long elapsed_usec, sleep_usec;
1229 #define ONE_SEC 1000000L /* # of microseconds in a second */
1231 if (!bwlimit_writemax)
1234 total_written += bytes_written;
1236 gettimeofday(&start_tv, NULL);
1237 if (prior_tv.tv_sec) {
1238 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1239 + (start_tv.tv_usec - prior_tv.tv_usec);
1240 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1241 if (total_written < 0)
1245 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1246 if (sleep_usec < ONE_SEC / 10) {
1247 prior_tv = start_tv;
1251 tv.tv_sec = sleep_usec / ONE_SEC;
1252 tv.tv_usec = sleep_usec % ONE_SEC;
1253 select(0, NULL, NULL, NULL, &tv);
1255 gettimeofday(&prior_tv, NULL);
1256 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1257 + (prior_tv.tv_usec - start_tv.tv_usec);
1258 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1261 /* Write len bytes to the file descriptor fd, looping as necessary to get
1262 * the job done and also (in certain circumstances) reading any data on
1263 * msg_fd_in to avoid deadlock.
1265 * This function underlies the multiplexing system. The body of the
1266 * application never calls this function directly. */
1267 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1269 size_t n, total = 0;
1270 fd_set w_fds, r_fds, e_fds;
1271 int maxfd, count, cnt, using_r_fds;
1276 defer_forwarding_messages++, defer_inc++;
1278 while (total < len) {
1285 if (msg_fd_in >= 0) {
1287 FD_SET(msg_fd_in, &r_fds);
1288 if (msg_fd_in > maxfd)
1294 tv.tv_sec = select_timeout;
1298 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1299 &w_fds, &e_fds, &tv);
1302 if (count < 0 && errno == EBADF)
1303 exit_cleanup(RERR_SOCKETIO);
1308 if (FD_ISSET(fd, &e_fds)) {
1309 rsyserr(FINFO, errno,
1310 "select exception on fd %d", fd);
1313 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1316 if (!FD_ISSET(fd, &w_fds))
1320 if (bwlimit_writemax && n > bwlimit_writemax)
1321 n = bwlimit_writemax;
1322 cnt = write(fd, buf + total, n);
1328 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1334 /* Don't try to write errors back across the stream. */
1335 if (fd == sock_f_out)
1336 io_end_multiplex_out();
1337 /* Don't try to write errors down a failing msg pipe. */
1338 if (am_server && fd == msg_fd_out)
1339 exit_cleanup(RERR_STREAMIO);
1340 rsyserr(FERROR, errno,
1341 "writefd_unbuffered failed to write %ld bytes [%s]",
1342 (long)len, who_am_i());
1343 /* If the other side is sending us error messages, try
1344 * to grab any messages they sent before they died. */
1345 while (fd == sock_f_out && io_multiplexing_in) {
1348 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1349 sizeof io_filesfrom_buf);
1351 exit_cleanup(RERR_STREAMIO);
1355 defer_forwarding_messages++, defer_inc++;
1357 if (fd == sock_f_out) {
1358 if (io_timeout || am_generator)
1359 last_io_out = time(NULL);
1360 sleep_for_bwlimit(cnt);
1365 if (!(defer_forwarding_messages -= defer_inc))
1369 void io_flush(int flush_it_all)
1371 if (!iobuf_out_cnt || no_flush)
1374 if (io_multiplexing_out)
1375 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt);
1377 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1380 if (flush_it_all && !defer_forwarding_messages)
1384 static void writefd(int fd, const char *buf, size_t len)
1386 if (fd == sock_f_out)
1387 stats.total_written += len;
1389 if (fd == write_batch_monitor_out) {
1390 if ((size_t)write(batch_fd, buf, len) != len)
1391 exit_cleanup(RERR_FILEIO);
1394 if (!iobuf_out || fd != iobuf_f_out) {
1395 writefd_unbuffered(fd, buf, len);
1400 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1402 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1408 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1409 io_flush(NORMAL_FLUSH);
1413 void write_shortint(int f, unsigned short x)
1417 b[1] = (char)(x >> 8);
1421 void write_int(int f, int32 x)
1428 void write_varint(int f, int32 x)
1436 while (cnt > 1 && b[cnt] == 0)
1438 bit = ((uchar)1<<(7-cnt+1));
1439 if (CVAL(b, cnt) >= bit) {
1443 *b = b[cnt] | ~(bit*2-1);
1450 void write_varlong(int f, int64 x, uchar min_bytes)
1457 #if SIZEOF_INT64 >= 8
1458 SIVAL(b, 5, x >> 32);
1460 if (x <= 0x7FFFFFFF && x >= 0)
1461 memset(b + 5, 0, 4);
1463 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1464 exit_cleanup(RERR_UNSUPPORTED);
1468 while (cnt > min_bytes && b[cnt] == 0)
1470 bit = ((uchar)1<<(7-cnt+min_bytes));
1471 if (CVAL(b, cnt) >= bit) {
1474 } else if (cnt > min_bytes)
1475 *b = b[cnt] | ~(bit*2-1);
1483 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1484 * 64-bit types on this platform.
1486 void write_longint(int f, int64 x)
1488 char b[12], * const s = b+4;
1491 if (x <= 0x7FFFFFFF && x >= 0) {
1496 #if SIZEOF_INT64 < 8
1497 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1498 exit_cleanup(RERR_UNSUPPORTED);
1501 SIVAL(s, 4, x >> 32);
1506 void write_buf(int f, const char *buf, size_t len)
1511 /** Write a string to the connection */
1512 void write_sbuf(int f, const char *buf)
1514 writefd(f, buf, strlen(buf));
1517 void write_byte(int f, uchar c)
1519 writefd(f, (char *)&c, 1);
1522 void write_vstring(int f, const char *str, int len)
1524 uchar lenbuf[3], *lb = lenbuf;
1529 "attempting to send over-long vstring (%d > %d)\n",
1531 exit_cleanup(RERR_PROTOCOL);
1533 *lb++ = len / 0x100 + 0x80;
1537 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1539 writefd(f, str, len);
1542 /* Send a file-list index using a byte-reduction method. */
1543 void write_ndx(int f, int32 ndx)
1545 static int32 prev_positive = -1, prev_negative = 1;
1546 int32 diff, cnt = 0;
1549 if (protocol_version < 30 || read_batch) {
1554 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1555 * negative nums as a positive after sending a leading 0xFF. */
1557 diff = ndx - prev_positive;
1558 prev_positive = ndx;
1559 } else if (ndx == NDX_DONE) {
1564 b[cnt++] = (char)0xFF;
1566 diff = ndx - prev_negative;
1567 prev_negative = ndx;
1570 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1571 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1572 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1573 if (diff < 0xFE && diff > 0)
1574 b[cnt++] = (char)diff;
1575 else if (diff < 0 || diff > 0x7FFF) {
1576 b[cnt++] = (char)0xFE;
1577 b[cnt++] = (char)((ndx >> 24) | 0x80);
1578 b[cnt++] = (char)ndx;
1579 b[cnt++] = (char)(ndx >> 8);
1580 b[cnt++] = (char)(ndx >> 16);
1582 b[cnt++] = (char)0xFE;
1583 b[cnt++] = (char)(diff >> 8);
1584 b[cnt++] = (char)diff;
1589 /* Receive a file-list index using a byte-reduction method. */
1590 int32 read_ndx(int f)
1592 static int32 prev_positive = -1, prev_negative = 1;
1593 int32 *prev_ptr, num;
1596 if (protocol_version < 30)
1600 if (CVAL(b, 0) == 0xFF) {
1602 prev_ptr = &prev_negative;
1603 } else if (CVAL(b, 0) == 0)
1606 prev_ptr = &prev_positive;
1607 if (CVAL(b, 0) == 0xFE) {
1609 if (CVAL(b, 0) & 0x80) {
1610 b[3] = CVAL(b, 0) & ~0x80;
1615 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1617 num = UVAL(b, 0) + *prev_ptr;
1619 if (prev_ptr == &prev_negative)
1625 * Read a line of up to @p maxlen characters into @p buf (not counting
1626 * the trailing null). Strips the (required) trailing newline and all
1629 * @return 1 for success; 0 for I/O error or truncation.
1631 int read_line(int f, char *buf, size_t maxlen)
1635 read_buf(f, buf, 1);
1640 if (buf[0] != '\r') {
1649 void io_printf(int fd, const char *format, ...)
1652 char buf[BIGPATHBUFLEN];
1655 va_start(ap, format);
1656 len = vsnprintf(buf, sizeof buf, format, ap);
1660 exit_cleanup(RERR_STREAMIO);
1662 if (len > (int)sizeof buf) {
1663 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1664 exit_cleanup(RERR_STREAMIO);
1667 write_sbuf(fd, buf);
1670 /** Setup for multiplexing a MSG_* stream with the data stream. */
1671 void io_start_multiplex_out(void)
1673 io_flush(NORMAL_FLUSH);
1674 io_start_buffering_out(sock_f_out);
1675 io_multiplexing_out = 1;
1678 /** Setup for multiplexing a MSG_* stream with the data stream. */
1679 void io_start_multiplex_in(void)
1681 io_flush(NORMAL_FLUSH);
1682 io_start_buffering_in(sock_f_in);
1683 io_multiplexing_in = 1;
1686 /** Write an message to the multiplexed data stream. */
1687 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1689 if (!io_multiplexing_out)
1691 io_flush(NORMAL_FLUSH);
1692 stats.total_written += (len+4);
1693 mplex_write(sock_f_out, code, buf, len);
1697 void io_end_multiplex_in(void)
1699 io_multiplexing_in = 0;
1700 io_end_buffering_in();
1703 /** Stop output multiplexing. */
1704 void io_end_multiplex_out(void)
1706 io_multiplexing_out = 0;
1707 io_end_buffering_out();
1710 void start_write_batch(int fd)
1712 /* Some communication has already taken place, but we don't
1713 * enable batch writing until here so that we can write a
1714 * canonical record of the communication even though the
1715 * actual communication so far depends on whether a daemon
1717 write_int(batch_fd, protocol_version);
1718 write_int(batch_fd, checksum_seed);
1721 write_batch_monitor_out = fd;
1723 write_batch_monitor_in = fd;
1726 void stop_write_batch(void)
1728 write_batch_monitor_out = -1;
1729 write_batch_monitor_in = -1;