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 3 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, visit the http://fsf.org website.
22 /* Rsync provides its own multiplexing system, which is used to send
23 * stderr and stdout over a single socket.
25 * For historical reasons this is off during the start of the
26 * connection, but it's switched on quite early using
27 * io_start_multiplex_out() and io_start_multiplex_in(). */
31 /** If no timeout is specified then use a 60 second select timeout */
32 #define SELECT_TIMEOUT 60
35 extern size_t bwlimit_writemax;
36 extern int io_timeout;
37 extern int allowed_lull;
41 extern int am_generator;
42 extern int inc_recurse;
46 extern int read_batch;
47 extern int csum_length;
48 extern int checksum_seed;
49 extern int protocol_version;
50 extern int remove_source_files;
51 extern int preserve_hard_links;
52 extern char *filesfrom_host;
53 extern struct stats stats;
54 extern struct file_list *cur_flist, *first_flist;
56 extern iconv_t ic_send, ic_recv;
59 const char phase_unknown[] = "unknown";
60 int ignore_timeout = 0;
64 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
65 int kluge_around_eof = 0;
72 static int iobuf_f_in = -1;
73 static char *iobuf_in;
74 static size_t iobuf_in_siz;
75 static size_t iobuf_in_ndx;
76 static size_t iobuf_in_remaining;
78 static int iobuf_f_out = -1;
79 static char *iobuf_out;
80 static int iobuf_out_cnt;
82 int flist_forward_from = -1;
84 static int io_multiplexing_out;
85 static int io_multiplexing_in;
86 static time_t last_io_in;
87 static time_t last_io_out;
90 static int write_batch_monitor_in = -1;
91 static int write_batch_monitor_out = -1;
93 static int io_filesfrom_f_in = -1;
94 static int io_filesfrom_f_out = -1;
95 static char io_filesfrom_buf[2048];
97 static char iconv_buf[sizeof io_filesfrom_buf / 2];
99 static char *io_filesfrom_bp;
100 static char io_filesfrom_lastchar;
101 static int io_filesfrom_buflen;
102 static int defer_forwarding_messages = 0;
103 static int select_timeout = SELECT_TIMEOUT;
104 static int active_filecnt = 0;
105 static OFF_T active_bytecnt = 0;
107 static char int_byte_extra[64] = {
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
110 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
111 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
114 static void readfd(int fd, char *buffer, size_t N);
115 static void writefd(int fd, const char *buf, size_t len);
116 static void writefd_unbuffered(int fd, const char *buf, size_t len);
117 static void decrement_active_files(int ndx);
118 static void decrement_flist_in_progress(int ndx, int redo);
119 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
121 struct flist_ndx_item {
122 struct flist_ndx_item *next;
126 struct flist_ndx_list {
127 struct flist_ndx_item *head, *tail;
130 static struct flist_ndx_list redo_list, hlink_list;
132 struct msg_list_item {
133 struct msg_list_item *next;
139 struct msg_list_item *head, *tail;
142 static struct msg_list msg_queue;
144 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
146 struct flist_ndx_item *item;
148 if (!(item = new(struct flist_ndx_item)))
149 out_of_memory("flist_ndx_push");
153 lp->tail->next = item;
159 static int flist_ndx_pop(struct flist_ndx_list *lp)
161 struct flist_ndx_item *next;
168 next = lp->head->next;
177 static void check_timeout(void)
181 if (!io_timeout || ignore_timeout)
185 last_io_in = time(NULL);
191 if (t - last_io_in >= io_timeout) {
192 if (!am_server && !am_daemon) {
193 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
194 (int)(t-last_io_in));
196 exit_cleanup(RERR_TIMEOUT);
200 /* Note the fds used for the main socket (which might really be a pipe
201 * for a local transfer, but we can ignore that). */
202 void io_set_sock_fds(int f_in, int f_out)
208 void set_io_timeout(int secs)
212 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
213 select_timeout = SELECT_TIMEOUT;
215 select_timeout = io_timeout;
217 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
220 /* Setup the fd used to receive MSG_* messages. Only needed during the
221 * early stages of being a local sender (up through the sending of the
222 * file list) or when we're the generator (to fetch the messages from
224 void set_msg_fd_in(int fd)
229 /* Setup the fd used to send our MSG_* messages. Only needed when
230 * we're the receiver (to send our messages to the generator). */
231 void set_msg_fd_out(int fd)
234 set_nonblocking(msg_fd_out);
237 /* Add a message to the pending MSG_* list. */
238 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
240 struct msg_list_item *m;
241 int sz = len + 4 + sizeof m[0] - 1;
243 if (!(m = (struct msg_list_item *)new_array(char, sz)))
244 out_of_memory("msg_list_add");
246 m->convert = convert;
247 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
248 memcpy(m->buf + 4, buf, len);
256 static void msg_flush(void)
259 while (msg_queue.head && io_multiplexing_out) {
260 struct msg_list_item *m = msg_queue.head;
261 int len = IVAL(m->buf, 0) & 0xFFFFFF;
262 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
263 if (!(msg_queue.head = m->next))
264 msg_queue.tail = NULL;
265 stats.total_written += len + 4;
266 defer_forwarding_messages++;
267 mplex_write(sock_f_out, tag, m->buf + 4, len, m->convert);
268 defer_forwarding_messages--;
272 while (msg_queue.head) {
273 struct msg_list_item *m = msg_queue.head;
274 int len = IVAL(m->buf, 0) & 0xFFFFFF;
275 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
276 if (!(msg_queue.head = m->next))
277 msg_queue.tail = NULL;
278 defer_forwarding_messages++;
279 mplex_write(msg_fd_out, tag, m->buf + 4, len, m->convert);
280 defer_forwarding_messages--;
286 /* Read a message from the MSG_* fd and handle it. This is called either
287 * during the early stages of being a local sender (up through the sending
288 * of the file list) or when we're the generator (to fetch the messages
289 * from the receiver). */
290 static void read_msg_fd(void)
294 struct file_list *flist;
298 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
299 * to this routine from writefd_unbuffered(). */
302 defer_forwarding_messages++;
307 len = tag & 0xFFFFFF;
308 tag = (tag >> 24) - MPLEX_BASE;
312 if (len < 0 || len > 1 || !am_generator) {
314 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
315 tag, len, who_am_i(),
316 inc_recurse ? "/inc" : "");
317 exit_cleanup(RERR_STREAMIO);
320 readfd(fd, buf, len);
321 stats.total_read = read_varlong(fd, 3);
326 if (len != 4 || !am_generator)
329 if (remove_source_files)
330 decrement_active_files(IVAL(buf,0));
331 flist_ndx_push(&redo_list, IVAL(buf,0));
333 decrement_flist_in_progress(IVAL(buf,0), 1);
336 if (len != 4 || !am_generator || !inc_recurse)
339 /* Read extra file list from receiver. */
340 assert(iobuf_in != NULL);
341 assert(iobuf_f_in == fd);
343 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
344 who_am_i(), IVAL(buf,0));
346 flist = recv_file_list(fd);
347 flist->parent_ndx = IVAL(buf,0);
350 if (len != 0 || !am_generator || !inc_recurse)
355 if (len >= (int)sizeof buf || !am_generator)
357 readfd(fd, buf, len);
358 send_msg(MSG_DELETED, buf, len, 1);
361 if (len != 4 || !am_generator)
363 readfd(fd, buf, len);
364 if (remove_source_files) {
365 decrement_active_files(IVAL(buf,0));
366 send_msg(MSG_SUCCESS, buf, len, 0);
368 if (preserve_hard_links)
369 flist_ndx_push(&hlink_list, IVAL(buf,0));
371 decrement_flist_in_progress(IVAL(buf,0), 0);
374 if (len != 4 || !am_generator)
376 readfd(fd, buf, len);
378 decrement_flist_in_progress(IVAL(buf,0), 0);
384 if (tag == MSG_SOCKERR)
385 io_end_multiplex_out();
395 rwrite((enum logcode)tag, buf, n, !am_generator);
400 rprintf(FERROR, "unknown message %d:%d [%s]\n",
401 tag, len, who_am_i());
402 exit_cleanup(RERR_STREAMIO);
407 if (!--defer_forwarding_messages)
411 /* This is used by the generator to limit how many file transfers can
412 * be active at once when --remove-source-files is specified. Without
413 * this, sender-side deletions were mostly happening at the end. */
414 void increment_active_files(int ndx, int itemizing, enum logcode code)
416 /* TODO: tune these limits? */
417 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
418 check_for_finished_files(itemizing, code, 0);
420 io_flush(NORMAL_FLUSH);
426 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
429 static void decrement_active_files(int ndx)
431 struct file_list *flist = flist_for_ndx(ndx);
432 assert(flist != NULL);
434 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
437 static void decrement_flist_in_progress(int ndx, int redo)
439 struct file_list *flist = cur_flist ? cur_flist : first_flist;
441 while (ndx < flist->ndx_start) {
442 if (flist == first_flist) {
445 "Invalid file index: %d (%d - %d) [%s]\n",
446 ndx, first_flist->ndx_start,
447 first_flist->prev->ndx_start + first_flist->prev->used - 1,
449 exit_cleanup(RERR_PROTOCOL);
453 while (ndx >= flist->ndx_start + flist->used) {
454 if (!(flist = flist->next))
458 flist->in_progress--;
463 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
464 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
466 char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
469 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
472 if (convert && ic_send == (iconv_t)-1)
476 if (convert || n > 1024 - 4) /* BIGPATHBUFLEN can handle 1024 bytes */
479 memcpy(buffer + 4, buf, n);
481 writefd_unbuffered(fd, buffer, n+4);
488 iconv(ic_send, NULL, 0, NULL, 0);
489 defer_forwarding_messages++;
491 ICONV_CONST char *ibuf = (ICONV_CONST char *)buf;
493 size_t ocnt = sizeof buffer;
494 while (len && iconv(ic_send, &ibuf,&len,
495 &obuf,&ocnt) == (size_t)-1) {
496 if (errno == E2BIG || !ocnt)
502 writefd_unbuffered(fd, buffer, n);
504 if (!--defer_forwarding_messages)
509 defer_forwarding_messages++;
510 writefd_unbuffered(fd, buf, len);
511 if (!--defer_forwarding_messages)
516 int send_msg(enum msgcode code, const char *buf, int len, int convert)
518 if (msg_fd_out < 0) {
519 if (!defer_forwarding_messages)
520 return io_multiplex_write(code, buf, len, convert);
521 if (!io_multiplexing_out)
523 msg_list_add(&msg_queue, code, buf, len, convert);
526 if (flist_forward_from >= 0)
527 msg_list_add(&msg_queue, code, buf, len, convert);
529 mplex_write(msg_fd_out, code, buf, len, convert);
533 void send_msg_int(enum msgcode code, int num)
536 SIVAL(numbuf, 0, num);
537 send_msg(code, numbuf, 4, 0);
540 void wait_for_receiver(void)
543 io_flush(NORMAL_FLUSH);
548 int get_redo_num(void)
550 return flist_ndx_pop(&redo_list);
553 int get_hlink_num(void)
555 return flist_ndx_pop(&hlink_list);
559 * When we're the receiver and we have a local --files-from list of names
560 * that needs to be sent over the socket to the sender, we have to do two
561 * things at the same time: send the sender a list of what files we're
562 * processing and read the incoming file+info list from the sender. We do
563 * this by augmenting the read_timeout() function to copy this data. It
564 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
565 * ready, since it might be a pipe) and then blast it out f_out (when it
566 * is ready to receive more data).
568 void io_set_filesfrom_fds(int f_in, int f_out)
570 io_filesfrom_f_in = f_in;
571 io_filesfrom_f_out = f_out;
572 io_filesfrom_bp = io_filesfrom_buf;
573 io_filesfrom_lastchar = '\0';
574 io_filesfrom_buflen = 0;
577 /* It's almost always an error to get an EOF when we're trying to read from the
578 * network, because the protocol is (for the most part) self-terminating.
580 * There is one case for the receiver when it is at the end of the transfer
581 * (hanging around reading any keep-alive packets that might come its way): if
582 * the sender dies before the generator's kill-signal comes through, we can end
583 * up here needing to loop until the kill-signal arrives. In this situation,
584 * kluge_around_eof will be < 0.
586 * There is another case for older protocol versions (< 24) where the module
587 * listing was not terminated, so we must ignore an EOF error in that case and
588 * exit. In this situation, kluge_around_eof will be > 0. */
589 static void whine_about_eof(int fd)
591 if (kluge_around_eof && fd == sock_f_in) {
593 if (kluge_around_eof > 0)
595 /* If we're still here after 10 seconds, exit with an error. */
596 for (i = 10*1000/20; i--; )
600 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
601 "(%.0f bytes received so far) [%s]\n",
602 (double)stats.total_read, who_am_i());
604 exit_cleanup(RERR_STREAMIO);
608 * Read from a socket with I/O timeout. return the number of bytes
609 * read. If no bytes can be read then exit, never return a number <= 0.
611 * TODO: If the remote shell connection fails, then current versions
612 * actually report an "unexpected EOF" error here. Since it's a
613 * fairly common mistake to try to use rsh when ssh is required, we
614 * should trap that: if we fail to read any data at all, we should
615 * give a better explanation. We can tell whether the connection has
616 * started by looking e.g. at whether the remote version is known yet.
618 static int read_timeout(int fd, char *buf, size_t len)
622 io_flush(FULL_FLUSH);
625 /* until we manage to read *something* */
634 if (io_filesfrom_f_out >= 0) {
636 if (io_filesfrom_buflen == 0) {
637 if (io_filesfrom_f_in >= 0) {
638 FD_SET(io_filesfrom_f_in, &r_fds);
639 new_fd = io_filesfrom_f_in;
641 io_filesfrom_f_out = -1;
645 FD_SET(io_filesfrom_f_out, &w_fds);
646 new_fd = io_filesfrom_f_out;
652 tv.tv_sec = select_timeout;
657 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
660 if (errno == EBADF) {
661 defer_forwarding_messages = 0;
662 exit_cleanup(RERR_SOCKETIO);
668 if (io_filesfrom_f_out >= 0) {
669 if (io_filesfrom_buflen) {
670 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
671 int l = write(io_filesfrom_f_out,
673 io_filesfrom_buflen);
675 if (!(io_filesfrom_buflen -= l))
676 io_filesfrom_bp = io_filesfrom_buf;
678 io_filesfrom_bp += l;
679 } else if (errno != EINTR) {
680 /* XXX should we complain? */
681 io_filesfrom_f_out = -1;
684 } else if (io_filesfrom_f_in >= 0) {
685 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
686 int l = read(io_filesfrom_f_in,
688 sizeof io_filesfrom_buf);
690 if (l == 0 || errno != EINTR) {
691 /* Send end-of-file marker */
692 io_filesfrom_buf[0] = '\0';
693 io_filesfrom_buf[1] = '\0';
694 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
695 io_filesfrom_f_in = -1;
699 char *s = io_filesfrom_buf + l;
700 /* Transform CR and/or LF into '\0' */
701 while (s-- > io_filesfrom_buf) {
702 if (*s == '\n' || *s == '\r')
706 if (!io_filesfrom_lastchar) {
707 /* Last buf ended with a '\0', so don't
708 * let this buf start with one. */
709 while (l && !*io_filesfrom_bp)
710 io_filesfrom_bp++, l--;
713 io_filesfrom_bp = io_filesfrom_buf;
715 char *f = io_filesfrom_bp;
718 /* Eliminate any multi-'\0' runs. */
720 if (!(*t++ = *f++)) {
721 while (f != eob && !*f)
725 io_filesfrom_lastchar = f[-1];
727 io_filesfrom_buflen = l;
733 if (!FD_ISSET(fd, &r_fds))
736 n = read(fd, buf, len);
740 whine_about_eof(fd); /* Doesn't return. */
741 if (errno == EINTR || errno == EWOULDBLOCK
745 /* Don't write errors on a dead socket. */
746 if (fd == sock_f_in) {
747 io_end_multiplex_out();
748 rsyserr(FSOCKERR, errno, "read error");
750 rsyserr(FERROR, errno, "read error");
751 exit_cleanup(RERR_STREAMIO);
758 if (fd == sock_f_in && io_timeout)
759 last_io_in = time(NULL);
765 /* Read a line into the "fname" buffer (which must be at least MAXPATHLEN
766 * characters long). */
767 int read_filesfrom_line(int fd, char *fname)
769 char ch, *s, *eob = fname + MAXPATHLEN - 1;
771 int reading_remotely = filesfrom_host != NULL;
772 int nulls = eol_nulls || reading_remotely;
777 cnt = read(fd, &ch, 1);
778 if (cnt < 0 && (errno == EWOULDBLOCK
779 || errno == EINTR || errno == EAGAIN)) {
786 tv.tv_sec = select_timeout;
788 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
790 if (FD_ISSET(fd, &e_fds)) {
791 rsyserr(FINFO, errno,
792 "select exception on fd %d", fd);
798 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
799 /* Skip empty lines if reading locally. */
800 if (!reading_remotely && s == fname)
810 if (*fname == '#' || *fname == ';')
816 int io_start_buffering_out(int f_out)
819 assert(f_out == iobuf_f_out);
822 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
823 out_of_memory("io_start_buffering_out");
829 int io_start_buffering_in(int f_in)
832 assert(f_in == iobuf_f_in);
835 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
836 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
837 out_of_memory("io_start_buffering_in");
842 void io_end_buffering_in(void)
849 iobuf_in_remaining = 0;
853 void io_end_buffering_out(void)
857 io_flush(FULL_FLUSH);
863 void maybe_flush_socket(int important)
865 if (iobuf_out && iobuf_out_cnt
866 && (important || time(NULL) - last_io_out >= 5))
867 io_flush(NORMAL_FLUSH);
870 void maybe_send_keepalive(void)
872 if (time(NULL) - last_io_out >= allowed_lull) {
873 if (!iobuf_out || !iobuf_out_cnt) {
874 if (protocol_version < 29)
875 return; /* there's nothing we can do */
876 if (protocol_version >= 30)
877 send_msg(MSG_NOOP, "", 0, 0);
879 write_int(sock_f_out, cur_flist->used);
880 write_shortint(sock_f_out, ITEM_IS_NEW);
884 io_flush(NORMAL_FLUSH);
888 void start_flist_forward(int f_in)
890 assert(iobuf_out != NULL);
891 assert(iobuf_f_out == msg_fd_out);
892 flist_forward_from = f_in;
895 void stop_flist_forward()
897 flist_forward_from = -1;
898 io_flush(FULL_FLUSH);
902 * Continue trying to read len bytes - don't return until len has been
905 static void read_loop(int fd, char *buf, size_t len)
908 int n = read_timeout(fd, buf, len);
916 * Read from the file descriptor handling multiplexing - return number
919 * Never returns <= 0.
921 static int readfd_unbuffered(int fd, char *buf, size_t len)
925 char line[BIGPATHBUFLEN];
927 if (!iobuf_in || fd != iobuf_f_in)
928 return read_timeout(fd, buf, len);
930 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
931 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
936 if (iobuf_in_remaining) {
937 len = MIN(len, iobuf_in_remaining);
938 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
940 iobuf_in_remaining -= len;
945 read_loop(fd, line, 4);
948 msg_bytes = tag & 0xFFFFFF;
949 tag = (tag >> 24) - MPLEX_BASE;
953 if (msg_bytes > iobuf_in_siz) {
954 if (!(iobuf_in = realloc_array(iobuf_in, char,
956 out_of_memory("readfd_unbuffered");
957 iobuf_in_siz = msg_bytes;
959 read_loop(fd, iobuf_in, msg_bytes);
960 iobuf_in_remaining = msg_bytes;
965 maybe_send_keepalive();
970 read_loop(fd, line, msg_bytes);
971 io_error |= IVAL(line, 0);
974 if (msg_bytes >= sizeof line)
977 if (ic_recv != (iconv_t)-1) {
978 ICONV_CONST char *ibuf;
980 size_t icnt, ocnt = sizeof line - 1;
982 iconv(ic_send, NULL, 0, NULL, 0);
984 icnt = msg_bytes > sizeof iconv_buf
985 ? sizeof iconv_buf : msg_bytes;
986 read_loop(fd, iconv_buf, icnt);
987 if (!(msg_bytes -= icnt) && !iconv_buf[icnt-1])
988 icnt--, add_null = 1;
989 ibuf = (ICONV_CONST char *)iconv_buf;
990 if (iconv(ic_send, &ibuf,&icnt,
991 &obuf,&ocnt) == (size_t)-1)
992 goto overflow; // XXX
996 msg_bytes = obuf - line;
999 read_loop(fd, line, msg_bytes);
1000 /* A directory name was sent with the trailing null */
1001 if (msg_bytes > 0 && !line[msg_bytes-1])
1002 log_delete(line, S_IFDIR);
1004 line[msg_bytes] = '\0';
1005 log_delete(line, S_IFREG);
1009 if (msg_bytes != 4) {
1011 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
1012 tag, (long)msg_bytes, who_am_i());
1013 exit_cleanup(RERR_STREAMIO);
1015 read_loop(fd, line, msg_bytes);
1016 successful_send(IVAL(line, 0));
1021 read_loop(fd, line, msg_bytes);
1022 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1026 if (msg_bytes >= sizeof line) {
1029 "multiplexing overflow %d:%ld [%s]\n",
1030 tag, (long)msg_bytes, who_am_i());
1031 exit_cleanup(RERR_STREAMIO);
1033 read_loop(fd, line, msg_bytes);
1034 rwrite((enum logcode)tag, line, msg_bytes, 1);
1037 rprintf(FERROR, "unexpected tag %d [%s]\n",
1039 exit_cleanup(RERR_STREAMIO);
1043 if (iobuf_in_remaining == 0)
1044 io_flush(NORMAL_FLUSH);
1049 /* Do a buffered read from fd. Don't return until all N bytes have
1050 * been read. If all N can't be read then exit with an error. */
1051 static void readfd(int fd, char *buffer, size_t N)
1057 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1061 if (fd == write_batch_monitor_in) {
1062 if ((size_t)write(batch_fd, buffer, total) != total)
1063 exit_cleanup(RERR_FILEIO);
1066 if (fd == flist_forward_from)
1067 writefd(iobuf_f_out, buffer, total);
1069 if (fd == sock_f_in)
1070 stats.total_read += total;
1073 unsigned short read_shortint(int f)
1077 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1080 int32 read_int(int f)
1087 #if SIZEOF_INT32 > 4
1088 if (num & (int32)0x80000000)
1089 num |= ~(int32)0xffffffff;
1094 int32 read_varint(int f)
1104 readfd(f, (char*)&ch, 1);
1105 extra = int_byte_extra[ch / 4];
1107 uchar bit = ((uchar)1<<(8-extra));
1108 if (extra >= (int)sizeof u.b) {
1109 rprintf(FERROR, "Overflow in read_varint()\n");
1110 exit_cleanup(RERR_STREAMIO);
1112 readfd(f, u.b, extra);
1113 u.b[extra] = ch & (bit-1);
1116 #if CAREFUL_ALIGNMENT
1119 #if SIZEOF_INT32 > 4
1120 if (u.x & (int32)0x80000000)
1121 u.x |= ~(int32)0xffffffff;
1126 int64 read_varlong(int f, uchar min_bytes)
1135 #if SIZEOF_INT64 < 8
1140 readfd(f, b2, min_bytes);
1141 memcpy(u.b, b2+1, min_bytes-1);
1142 extra = int_byte_extra[CVAL(b2, 0) / 4];
1144 uchar bit = ((uchar)1<<(8-extra));
1145 if (min_bytes + extra > (int)sizeof u.b) {
1146 rprintf(FERROR, "Overflow in read_varlong()\n");
1147 exit_cleanup(RERR_STREAMIO);
1149 readfd(f, u.b + min_bytes - 1, extra);
1150 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1151 #if SIZEOF_INT64 < 8
1152 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1153 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1154 exit_cleanup(RERR_UNSUPPORTED);
1158 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1159 #if SIZEOF_INT64 < 8
1161 #elif CAREFUL_ALIGNMENT
1162 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1167 int64 read_longint(int f)
1169 #if SIZEOF_INT64 >= 8
1172 int32 num = read_int(f);
1174 if (num != (int32)0xffffffff)
1177 #if SIZEOF_INT64 < 8
1178 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1179 exit_cleanup(RERR_UNSUPPORTED);
1182 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1186 void read_buf(int f, char *buf, size_t len)
1191 void read_sbuf(int f, char *buf, size_t len)
1193 readfd(f, buf, len);
1197 uchar read_byte(int f)
1200 readfd(f, (char *)&c, 1);
1204 int read_vstring(int f, char *buf, int bufsize)
1206 int len = read_byte(f);
1209 len = (len & ~0x80) * 0x100 + read_byte(f);
1211 if (len >= bufsize) {
1212 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1218 readfd(f, buf, len);
1223 /* Populate a sum_struct with values from the socket. This is
1224 * called by both the sender and the receiver. */
1225 void read_sum_head(int f, struct sum_struct *sum)
1227 sum->count = read_int(f);
1228 if (sum->count < 0) {
1229 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1230 (long)sum->count, who_am_i());
1231 exit_cleanup(RERR_PROTOCOL);
1233 sum->blength = read_int(f);
1234 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1235 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1236 (long)sum->blength, who_am_i());
1237 exit_cleanup(RERR_PROTOCOL);
1239 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1240 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1241 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1242 sum->s2length, who_am_i());
1243 exit_cleanup(RERR_PROTOCOL);
1245 sum->remainder = read_int(f);
1246 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1247 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1248 (long)sum->remainder, who_am_i());
1249 exit_cleanup(RERR_PROTOCOL);
1253 /* Send the values from a sum_struct over the socket. Set sum to
1254 * NULL if there are no checksums to send. This is called by both
1255 * the generator and the sender. */
1256 void write_sum_head(int f, struct sum_struct *sum)
1258 static struct sum_struct null_sum;
1263 write_int(f, sum->count);
1264 write_int(f, sum->blength);
1265 if (protocol_version >= 27)
1266 write_int(f, sum->s2length);
1267 write_int(f, sum->remainder);
1271 * Sleep after writing to limit I/O bandwidth usage.
1273 * @todo Rather than sleeping after each write, it might be better to
1274 * use some kind of averaging. The current algorithm seems to always
1275 * use a bit less bandwidth than specified, because it doesn't make up
1276 * for slow periods. But arguably this is a feature. In addition, we
1277 * ought to take the time used to write the data into account.
1279 * During some phases of big transfers (file FOO is uptodate) this is
1280 * called with a small bytes_written every time. As the kernel has to
1281 * round small waits up to guarantee that we actually wait at least the
1282 * requested number of microseconds, this can become grossly inaccurate.
1283 * We therefore keep track of the bytes we've written over time and only
1284 * sleep when the accumulated delay is at least 1 tenth of a second.
1286 static void sleep_for_bwlimit(int bytes_written)
1288 static struct timeval prior_tv;
1289 static long total_written = 0;
1290 struct timeval tv, start_tv;
1291 long elapsed_usec, sleep_usec;
1293 #define ONE_SEC 1000000L /* # of microseconds in a second */
1295 if (!bwlimit_writemax)
1298 total_written += bytes_written;
1300 gettimeofday(&start_tv, NULL);
1301 if (prior_tv.tv_sec) {
1302 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1303 + (start_tv.tv_usec - prior_tv.tv_usec);
1304 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1305 if (total_written < 0)
1309 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1310 if (sleep_usec < ONE_SEC / 10) {
1311 prior_tv = start_tv;
1315 tv.tv_sec = sleep_usec / ONE_SEC;
1316 tv.tv_usec = sleep_usec % ONE_SEC;
1317 select(0, NULL, NULL, NULL, &tv);
1319 gettimeofday(&prior_tv, NULL);
1320 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1321 + (prior_tv.tv_usec - start_tv.tv_usec);
1322 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1325 /* Write len bytes to the file descriptor fd, looping as necessary to get
1326 * the job done and also (in certain circumstances) reading any data on
1327 * msg_fd_in to avoid deadlock.
1329 * This function underlies the multiplexing system. The body of the
1330 * application never calls this function directly. */
1331 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1333 size_t n, total = 0;
1334 fd_set w_fds, r_fds, e_fds;
1335 int maxfd, count, cnt, using_r_fds;
1340 defer_forwarding_messages++, defer_inc++;
1342 while (total < len) {
1349 if (msg_fd_in >= 0) {
1351 FD_SET(msg_fd_in, &r_fds);
1352 if (msg_fd_in > maxfd)
1358 tv.tv_sec = select_timeout;
1362 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1363 &w_fds, &e_fds, &tv);
1366 if (count < 0 && errno == EBADF)
1367 exit_cleanup(RERR_SOCKETIO);
1372 if (FD_ISSET(fd, &e_fds)) {
1373 rsyserr(FINFO, errno,
1374 "select exception on fd %d", fd);
1377 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1380 if (!FD_ISSET(fd, &w_fds))
1384 if (bwlimit_writemax && n > bwlimit_writemax)
1385 n = bwlimit_writemax;
1386 cnt = write(fd, buf + total, n);
1392 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1398 /* Don't try to write errors back across the stream. */
1399 if (fd == sock_f_out)
1400 io_end_multiplex_out();
1401 /* Don't try to write errors down a failing msg pipe. */
1402 if (am_server && fd == msg_fd_out)
1403 exit_cleanup(RERR_STREAMIO);
1404 rsyserr(FERROR, errno,
1405 "writefd_unbuffered failed to write %ld bytes [%s]",
1406 (long)len, who_am_i());
1407 /* If the other side is sending us error messages, try
1408 * to grab any messages they sent before they died. */
1409 while (fd == sock_f_out && io_multiplexing_in) {
1412 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1413 sizeof io_filesfrom_buf);
1415 exit_cleanup(RERR_STREAMIO);
1419 defer_forwarding_messages++, defer_inc++;
1421 if (fd == sock_f_out) {
1422 if (io_timeout || am_generator)
1423 last_io_out = time(NULL);
1424 sleep_for_bwlimit(cnt);
1429 if (!(defer_forwarding_messages -= defer_inc))
1433 void io_flush(int flush_it_all)
1435 if (!iobuf_out_cnt || no_flush)
1438 if (io_multiplexing_out)
1439 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1441 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1444 if (flush_it_all && !defer_forwarding_messages)
1448 static void writefd(int fd, const char *buf, size_t len)
1450 if (fd == sock_f_out)
1451 stats.total_written += len;
1453 if (fd == write_batch_monitor_out) {
1454 if ((size_t)write(batch_fd, buf, len) != len)
1455 exit_cleanup(RERR_FILEIO);
1458 if (!iobuf_out || fd != iobuf_f_out) {
1459 writefd_unbuffered(fd, buf, len);
1464 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1466 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1472 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1473 io_flush(NORMAL_FLUSH);
1477 void write_shortint(int f, unsigned short x)
1481 b[1] = (char)(x >> 8);
1485 void write_int(int f, int32 x)
1492 void write_varint(int f, int32 x)
1500 while (cnt > 1 && b[cnt] == 0)
1502 bit = ((uchar)1<<(7-cnt+1));
1503 if (CVAL(b, cnt) >= bit) {
1507 *b = b[cnt] | ~(bit*2-1);
1514 void write_varlong(int f, int64 x, uchar min_bytes)
1521 #if SIZEOF_INT64 >= 8
1522 SIVAL(b, 5, x >> 32);
1524 if (x <= 0x7FFFFFFF && x >= 0)
1525 memset(b + 5, 0, 4);
1527 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1528 exit_cleanup(RERR_UNSUPPORTED);
1532 while (cnt > min_bytes && b[cnt] == 0)
1534 bit = ((uchar)1<<(7-cnt+min_bytes));
1535 if (CVAL(b, cnt) >= bit) {
1538 } else if (cnt > min_bytes)
1539 *b = b[cnt] | ~(bit*2-1);
1547 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1548 * 64-bit types on this platform.
1550 void write_longint(int f, int64 x)
1552 char b[12], * const s = b+4;
1555 if (x <= 0x7FFFFFFF && x >= 0) {
1560 #if SIZEOF_INT64 < 8
1561 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1562 exit_cleanup(RERR_UNSUPPORTED);
1565 SIVAL(s, 4, x >> 32);
1570 void write_buf(int f, const char *buf, size_t len)
1575 /** Write a string to the connection */
1576 void write_sbuf(int f, const char *buf)
1578 writefd(f, buf, strlen(buf));
1581 void write_byte(int f, uchar c)
1583 writefd(f, (char *)&c, 1);
1586 void write_vstring(int f, const char *str, int len)
1588 uchar lenbuf[3], *lb = lenbuf;
1593 "attempting to send over-long vstring (%d > %d)\n",
1595 exit_cleanup(RERR_PROTOCOL);
1597 *lb++ = len / 0x100 + 0x80;
1601 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1603 writefd(f, str, len);
1606 /* Send a file-list index using a byte-reduction method. */
1607 void write_ndx(int f, int32 ndx)
1609 static int32 prev_positive = -1, prev_negative = 1;
1610 int32 diff, cnt = 0;
1613 if (protocol_version < 30 || read_batch) {
1618 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1619 * negative nums as a positive after sending a leading 0xFF. */
1621 diff = ndx - prev_positive;
1622 prev_positive = ndx;
1623 } else if (ndx == NDX_DONE) {
1628 b[cnt++] = (char)0xFF;
1630 diff = ndx - prev_negative;
1631 prev_negative = ndx;
1634 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1635 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1636 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1637 if (diff < 0xFE && diff > 0)
1638 b[cnt++] = (char)diff;
1639 else if (diff < 0 || diff > 0x7FFF) {
1640 b[cnt++] = (char)0xFE;
1641 b[cnt++] = (char)((ndx >> 24) | 0x80);
1642 b[cnt++] = (char)ndx;
1643 b[cnt++] = (char)(ndx >> 8);
1644 b[cnt++] = (char)(ndx >> 16);
1646 b[cnt++] = (char)0xFE;
1647 b[cnt++] = (char)(diff >> 8);
1648 b[cnt++] = (char)diff;
1653 /* Receive a file-list index using a byte-reduction method. */
1654 int32 read_ndx(int f)
1656 static int32 prev_positive = -1, prev_negative = 1;
1657 int32 *prev_ptr, num;
1660 if (protocol_version < 30)
1664 if (CVAL(b, 0) == 0xFF) {
1666 prev_ptr = &prev_negative;
1667 } else if (CVAL(b, 0) == 0)
1670 prev_ptr = &prev_positive;
1671 if (CVAL(b, 0) == 0xFE) {
1673 if (CVAL(b, 0) & 0x80) {
1674 b[3] = CVAL(b, 0) & ~0x80;
1679 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1681 num = UVAL(b, 0) + *prev_ptr;
1683 if (prev_ptr == &prev_negative)
1689 * Read a line of up to @p maxlen characters into @p buf (not counting
1690 * the trailing null). Strips the (required) trailing newline and all
1693 * @return 1 for success; 0 for I/O error or truncation.
1695 int read_line(int f, char *buf, size_t maxlen)
1699 read_buf(f, buf, 1);
1704 if (buf[0] != '\r') {
1713 void io_printf(int fd, const char *format, ...)
1716 char buf[BIGPATHBUFLEN];
1719 va_start(ap, format);
1720 len = vsnprintf(buf, sizeof buf, format, ap);
1724 exit_cleanup(RERR_STREAMIO);
1726 if (len > (int)sizeof buf) {
1727 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1728 exit_cleanup(RERR_STREAMIO);
1731 write_sbuf(fd, buf);
1734 /** Setup for multiplexing a MSG_* stream with the data stream. */
1735 void io_start_multiplex_out(void)
1737 io_flush(NORMAL_FLUSH);
1738 io_start_buffering_out(sock_f_out);
1739 io_multiplexing_out = 1;
1742 /** Setup for multiplexing a MSG_* stream with the data stream. */
1743 void io_start_multiplex_in(void)
1745 io_flush(NORMAL_FLUSH);
1746 io_start_buffering_in(sock_f_in);
1747 io_multiplexing_in = 1;
1750 /** Write an message to the multiplexed data stream. */
1751 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1753 if (!io_multiplexing_out)
1755 io_flush(NORMAL_FLUSH);
1756 stats.total_written += (len+4);
1757 mplex_write(sock_f_out, code, buf, len, convert);
1761 void io_end_multiplex_in(void)
1763 io_multiplexing_in = 0;
1764 io_end_buffering_in();
1767 /** Stop output multiplexing. */
1768 void io_end_multiplex_out(void)
1770 io_multiplexing_out = 0;
1771 io_end_buffering_out();
1774 void start_write_batch(int fd)
1776 /* Some communication has already taken place, but we don't
1777 * enable batch writing until here so that we can write a
1778 * canonical record of the communication even though the
1779 * actual communication so far depends on whether a daemon
1781 write_int(batch_fd, protocol_version);
1782 write_int(batch_fd, checksum_seed);
1785 write_batch_monitor_out = fd;
1787 write_batch_monitor_in = fd;
1790 void stop_write_batch(void)
1792 write_batch_monitor_out = -1;
1793 write_batch_monitor_in = -1;