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-2008 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 3 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, visit the http://fsf.org website.
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(). */
33 /** If no timeout is specified then use a 60 second select timeout */
34 #define SELECT_TIMEOUT 60
37 extern size_t bwlimit_writemax;
38 extern int io_timeout;
39 extern int allowed_lull;
43 extern int am_generator;
44 extern int inc_recurse;
49 extern int read_batch;
50 extern int csum_length;
51 extern int protect_args;
52 extern int checksum_seed;
53 extern int protocol_version;
54 extern int remove_source_files;
55 extern int preserve_hard_links;
56 extern struct stats stats;
57 extern struct file_list *cur_flist;
59 extern int filesfrom_convert;
60 extern iconv_t ic_send, ic_recv;
63 const char phase_unknown[] = "unknown";
64 int ignore_timeout = 0;
68 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
69 int kluge_around_eof = 0;
76 static int iobuf_f_in = -1;
77 static char *iobuf_in;
78 static size_t iobuf_in_siz;
79 static size_t iobuf_in_ndx;
80 static size_t iobuf_in_remaining;
82 static int iobuf_f_out = -1;
83 static char *iobuf_out;
84 static int iobuf_out_cnt;
86 int flist_forward_from = -1;
88 static int io_multiplexing_out;
89 static int io_multiplexing_in;
90 static time_t last_io_in;
91 static time_t last_io_out;
94 static int write_batch_monitor_in = -1;
95 static int write_batch_monitor_out = -1;
97 static int io_filesfrom_f_in = -1;
98 static int io_filesfrom_f_out = -1;
99 static xbuf ff_buf = EMPTY_XBUF;
100 static char ff_lastchar;
102 static xbuf iconv_buf = EMPTY_XBUF;
104 static int defer_forwarding_messages = 0, keep_defer_forwarding = 0;
105 static int select_timeout = SELECT_TIMEOUT;
106 static int active_filecnt = 0;
107 static OFF_T active_bytecnt = 0;
108 static int first_message = 1;
110 static char int_byte_extra[64] = {
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
113 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
114 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
117 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
118 #define REMOTE_OPTION_ERROR2 ": unknown option"
120 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
122 static void readfd(int fd, char *buffer, size_t N);
123 static void writefd(int fd, const char *buf, size_t len);
124 static void writefd_unbuffered(int fd, const char *buf, size_t len);
125 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
127 static flist_ndx_list redo_list, hlink_list;
129 struct msg_list_item {
130 struct msg_list_item *next;
136 struct msg_list_item *head, *tail;
139 static struct msg_list msg_queue;
141 static void got_flist_entry_status(enum festatus status, const char *buf)
143 int ndx = IVAL(buf, 0);
144 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
146 if (remove_source_files) {
148 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
152 flist->in_progress--;
156 if (remove_source_files)
157 send_msg(MSG_SUCCESS, buf, 4, 0);
158 if (preserve_hard_links) {
159 struct file_struct *file = flist->files[ndx - flist->ndx_start];
160 if (F_IS_HLINKED(file)) {
161 flist_ndx_push(&hlink_list, ndx);
162 flist->in_progress++;
169 flist_ndx_push(&redo_list, ndx);
176 static void check_timeout(void)
180 if (!io_timeout || ignore_timeout)
184 last_io_in = time(NULL);
190 if (t - last_io_in >= io_timeout) {
191 if (!am_server && !am_daemon) {
192 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
193 (int)(t-last_io_in));
195 exit_cleanup(RERR_TIMEOUT);
199 /* Note the fds used for the main socket (which might really be a pipe
200 * for a local transfer, but we can ignore that). */
201 void io_set_sock_fds(int f_in, int f_out)
207 void set_io_timeout(int secs)
211 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
212 select_timeout = SELECT_TIMEOUT;
214 select_timeout = io_timeout;
216 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
219 /* Setup the fd used to receive MSG_* messages. Only needed during the
220 * early stages of being a local sender (up through the sending of the
221 * file list) or when we're the generator (to fetch the messages from
223 void set_msg_fd_in(int fd)
228 /* Setup the fd used to send our MSG_* messages. Only needed when
229 * we're the receiver (to send our messages to the generator). */
230 void set_msg_fd_out(int fd)
233 set_nonblocking(msg_fd_out);
236 /* Add a message to the pending MSG_* list. */
237 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
239 struct msg_list_item *m;
240 int sz = len + 4 + sizeof m[0] - 1;
242 if (!(m = (struct msg_list_item *)new_array(char, sz)))
243 out_of_memory("msg_list_add");
245 m->convert = convert;
246 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
247 memcpy(m->buf + 4, buf, len);
255 static inline int flush_a_msg(int fd)
257 struct msg_list_item *m = msg_queue.head;
258 int len = IVAL(m->buf, 0) & 0xFFFFFF;
259 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
261 if (!(msg_queue.head = m->next))
262 msg_queue.tail = NULL;
264 defer_forwarding_messages++;
265 mplex_write(fd, tag, m->buf + 4, len, m->convert);
266 defer_forwarding_messages--;
273 static void msg_flush(void)
276 while (msg_queue.head && io_multiplexing_out)
277 stats.total_written += flush_a_msg(sock_f_out) + 4;
279 while (msg_queue.head)
280 (void)flush_a_msg(msg_fd_out);
284 static void check_for_d_option_error(const char *msg)
286 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
291 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
294 msg += sizeof REMOTE_OPTION_ERROR - 1;
295 if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
296 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
299 for ( ; *msg != ':'; msg++) {
302 else if (*msg == 'e')
304 else if (strchr(rsync263_opts, *msg) == NULL)
310 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
314 /* Read a message from the MSG_* fd and handle it. This is called either
315 * during the early stages of being a local sender (up through the sending
316 * of the file list) or when we're the generator (to fetch the messages
317 * from the receiver). */
318 static void read_msg_fd(void)
322 struct file_list *flist;
326 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
327 * to this routine from writefd_unbuffered(). */
330 defer_forwarding_messages++;
335 len = tag & 0xFFFFFF;
336 tag = (tag >> 24) - MPLEX_BASE;
340 if (len < 0 || len > 1 || !am_generator) {
342 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
343 tag, len, who_am_i(),
344 inc_recurse ? "/inc" : "");
345 exit_cleanup(RERR_STREAMIO);
348 readfd(fd, buf, len);
349 stats.total_read = read_varlong(fd, 3);
354 if (len != 4 || !am_generator)
357 got_flist_entry_status(FES_REDO, buf);
360 if (len != 4 || !am_generator || !inc_recurse)
363 /* Read extra file list from receiver. */
364 assert(iobuf_in != NULL);
365 assert(iobuf_f_in == fd);
367 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
368 who_am_i(), IVAL(buf,0));
370 flist = recv_file_list(fd);
371 flist->parent_ndx = IVAL(buf,0);
372 #ifdef SUPPORT_HARD_LINKS
373 if (preserve_hard_links)
374 match_hard_links(flist);
378 if (len != 0 || !am_generator || !inc_recurse)
385 readfd(fd, buf, len);
386 io_error |= IVAL(buf, 0);
389 if (len >= (int)sizeof buf || !am_generator)
391 readfd(fd, buf, len);
392 send_msg(MSG_DELETED, buf, len, 1);
395 if (len != 4 || !am_generator)
398 got_flist_entry_status(FES_SUCCESS, buf);
401 if (len != 4 || !am_generator)
404 got_flist_entry_status(FES_NO_SEND, buf);
406 case MSG_ERROR_SOCKET:
411 if (tag == MSG_ERROR_SOCKET)
412 io_end_multiplex_out();
424 rwrite((enum logcode)tag, buf, n, !am_generator);
429 rprintf(FERROR, "unknown message %d:%d [%s]\n",
430 tag, len, who_am_i());
431 exit_cleanup(RERR_STREAMIO);
436 if (!--defer_forwarding_messages && !no_flush)
440 /* This is used by the generator to limit how many file transfers can
441 * be active at once when --remove-source-files is specified. Without
442 * this, sender-side deletions were mostly happening at the end. */
443 void increment_active_files(int ndx, int itemizing, enum logcode code)
445 /* TODO: tune these limits? */
446 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
447 check_for_finished_files(itemizing, code, 0);
449 io_flush(NORMAL_FLUSH);
455 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
458 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
459 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
461 char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
465 /* We need to convert buf before doing anything else so that we
466 * can include the (converted) byte length in the message header. */
467 if (convert && ic_send != (iconv_t)-1) {
470 INIT_XBUF(outbuf, buffer + 4, 0, sizeof buffer - 4);
471 INIT_XBUF(inbuf, (char*)buf, len, -1);
473 iconvbufs(ic_send, &inbuf, &outbuf,
474 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE);
476 rprintf(FERROR, "overflowed conversion buffer in mplex_write");
477 exit_cleanup(RERR_UNSUPPORTED);
480 n = len = outbuf.len;
483 if (n > 1024 - 4) /* BIGPATHBUFLEN can handle 1024 bytes */
484 n = 0; /* We'd rather do 2 writes than too much memcpy(). */
486 memcpy(buffer + 4, buf, n);
488 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
490 keep_defer_forwarding++; /* defer_forwarding_messages++ on return */
491 writefd_unbuffered(fd, buffer, n+4);
492 keep_defer_forwarding--;
495 writefd_unbuffered(fd, buf+n, len-n);
497 if (!--defer_forwarding_messages && !no_flush)
501 int send_msg(enum msgcode code, const char *buf, int len, int convert)
503 if (msg_fd_out < 0) {
504 if (!defer_forwarding_messages)
505 return io_multiplex_write(code, buf, len, convert);
506 if (!io_multiplexing_out)
508 msg_list_add(&msg_queue, code, buf, len, convert);
511 if (flist_forward_from >= 0)
512 msg_list_add(&msg_queue, code, buf, len, convert);
514 mplex_write(msg_fd_out, code, buf, len, convert);
518 void send_msg_int(enum msgcode code, int num)
521 SIVAL(numbuf, 0, num);
522 send_msg(code, numbuf, 4, 0);
525 void wait_for_receiver(void)
527 if (io_flush(NORMAL_FLUSH))
532 int get_redo_num(void)
534 return flist_ndx_pop(&redo_list);
537 int get_hlink_num(void)
539 return flist_ndx_pop(&hlink_list);
543 * When we're the receiver and we have a local --files-from list of names
544 * that needs to be sent over the socket to the sender, we have to do two
545 * things at the same time: send the sender a list of what files we're
546 * processing and read the incoming file+info list from the sender. We do
547 * this by augmenting the read_timeout() function to copy this data. It
548 * uses ff_buf to read a block of data from f_in (when it is ready, since
549 * it might be a pipe) and then blast it out f_out (when it is ready to
550 * receive more data).
552 void io_set_filesfrom_fds(int f_in, int f_out)
554 io_filesfrom_f_in = f_in;
555 io_filesfrom_f_out = f_out;
556 alloc_xbuf(&ff_buf, 2048);
559 alloc_xbuf(&iconv_buf, 1024);
563 /* It's almost always an error to get an EOF when we're trying to read from the
564 * network, because the protocol is (for the most part) self-terminating.
566 * There is one case for the receiver when it is at the end of the transfer
567 * (hanging around reading any keep-alive packets that might come its way): if
568 * the sender dies before the generator's kill-signal comes through, we can end
569 * up here needing to loop until the kill-signal arrives. In this situation,
570 * kluge_around_eof will be < 0.
572 * There is another case for older protocol versions (< 24) where the module
573 * listing was not terminated, so we must ignore an EOF error in that case and
574 * exit. In this situation, kluge_around_eof will be > 0. */
575 static void whine_about_eof(int fd)
577 if (kluge_around_eof && fd == sock_f_in) {
579 if (kluge_around_eof > 0)
581 /* If we're still here after 10 seconds, exit with an error. */
582 for (i = 10*1000/20; i--; )
586 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
587 "(%.0f bytes received so far) [%s]\n",
588 (double)stats.total_read, who_am_i());
590 exit_cleanup(RERR_STREAMIO);
594 * Read from a socket with I/O timeout. return the number of bytes
595 * read. If no bytes can be read then exit, never return a number <= 0.
597 * TODO: If the remote shell connection fails, then current versions
598 * actually report an "unexpected EOF" error here. Since it's a
599 * fairly common mistake to try to use rsh when ssh is required, we
600 * should trap that: if we fail to read any data at all, we should
601 * give a better explanation. We can tell whether the connection has
602 * started by looking e.g. at whether the remote version is known yet.
604 static int read_timeout(int fd, char *buf, size_t len)
608 io_flush(FULL_FLUSH);
611 /* until we manage to read *something* */
620 if (io_filesfrom_f_out >= 0) {
622 if (ff_buf.len == 0) {
623 if (io_filesfrom_f_in >= 0) {
624 FD_SET(io_filesfrom_f_in, &r_fds);
625 new_fd = io_filesfrom_f_in;
627 io_filesfrom_f_out = -1;
631 FD_SET(io_filesfrom_f_out, &w_fds);
632 new_fd = io_filesfrom_f_out;
638 tv.tv_sec = select_timeout;
643 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
646 if (errno == EBADF) {
647 defer_forwarding_messages = 0;
648 exit_cleanup(RERR_SOCKETIO);
654 if (io_filesfrom_f_out >= 0) {
656 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
657 int l = write(io_filesfrom_f_out,
658 ff_buf.buf + ff_buf.pos,
661 if (!(ff_buf.len -= l))
665 } else if (errno != EINTR) {
666 /* XXX should we complain? */
667 io_filesfrom_f_out = -1;
670 } else if (io_filesfrom_f_in >= 0) {
671 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
673 xbuf *ibuf = filesfrom_convert ? &iconv_buf : &ff_buf;
675 xbuf *ibuf = &ff_buf;
677 int l = read(io_filesfrom_f_in, ibuf->buf, ibuf->size);
679 if (l == 0 || errno != EINTR) {
680 /* Send end-of-file marker */
681 memcpy(ff_buf.buf, "\0\0", 2);
682 ff_buf.len = ff_lastchar? 2 : 1;
684 io_filesfrom_f_in = -1;
688 if (filesfrom_convert) {
691 iconvbufs(ic_send, &iconv_buf, &ff_buf,
692 ICB_EXPAND_OUT|ICB_INCLUDE_BAD|ICB_INCLUDE_INCOMPLETE);
697 char *s = ff_buf.buf + l;
698 /* Transform CR and/or LF into '\0' */
699 while (s-- > ff_buf.buf) {
700 if (*s == '\n' || *s == '\r')
705 /* Last buf ended with a '\0', so don't
706 * let this buf start with one. */
707 while (l && ff_buf.buf[ff_buf.pos] == '\0')
713 char *f = ff_buf.buf + ff_buf.pos;
716 /* Eliminate any multi-'\0' runs. */
718 if (!(*t++ = *f++)) {
719 while (f != eob && !*f)
731 if (!FD_ISSET(fd, &r_fds))
734 n = read(fd, buf, len);
738 whine_about_eof(fd); /* Doesn't return. */
739 if (errno == EINTR || errno == EWOULDBLOCK
743 /* Don't write errors on a dead socket. */
744 if (fd == sock_f_in) {
745 io_end_multiplex_out();
746 rsyserr(FERROR_SOCKET, errno, "read error");
748 rsyserr(FERROR, errno, "read error");
749 exit_cleanup(RERR_STREAMIO);
756 if (fd == sock_f_in && io_timeout)
757 last_io_in = time(NULL);
763 /* Read a line into the "buf" buffer. */
764 int read_line(int fd, char *buf, size_t bufsiz, int flags)
770 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
771 realloc_xbuf(&iconv_buf, bufsiz + 1024);
776 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
780 eob = s + bufsiz - 1;
782 cnt = read(fd, &ch, 1);
783 if (cnt < 0 && (errno == EWOULDBLOCK
784 || errno == EINTR || errno == EAGAIN)) {
791 tv.tv_sec = select_timeout;
793 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
795 /*if (FD_ISSET(fd, &e_fds))
796 rprintf(FINFO, "select exception on fd %d\n", fd); */
801 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
802 /* Skip empty lines if dumping comments. */
803 if (flags & RL_DUMP_COMMENTS && s == buf)
812 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
816 if (flags & RL_CONVERT) {
818 INIT_XBUF(outbuf, buf, 0, bufsiz);
820 iconv_buf.len = s - iconv_buf.buf;
821 iconvbufs(ic_recv, &iconv_buf, &outbuf,
822 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE);
823 outbuf.buf[outbuf.len] = '\0';
831 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
832 char ***argv_p, int *argc_p, char **request_p)
834 int maxargs = MAX_ARGS;
838 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
841 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
844 if (!(argv = new_array(char *, maxargs)))
845 out_of_memory("read_args");
846 if (mod_name && !protect_args)
847 argv[argc++] = "rsyncd";
850 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
853 if (argc == maxargs-1) {
855 if (!(argv = realloc_array(argv, char *, maxargs)))
856 out_of_memory("read_args");
861 *request_p = strdup(buf);
865 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
867 glob_expand(buf, &argv, &argc, &maxargs);
869 if (!(p = strdup(buf)))
870 out_of_memory("read_args");
872 if (*p == '.' && p[1] == '\0')
878 glob_expand(NULL, NULL, NULL, NULL);
884 int io_start_buffering_out(int f_out)
887 assert(f_out == iobuf_f_out);
890 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
891 out_of_memory("io_start_buffering_out");
897 int io_start_buffering_in(int f_in)
900 assert(f_in == iobuf_f_in);
903 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
904 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
905 out_of_memory("io_start_buffering_in");
910 void io_end_buffering_in(void)
917 iobuf_in_remaining = 0;
921 void io_end_buffering_out(void)
925 io_flush(FULL_FLUSH);
931 void maybe_flush_socket(int important)
933 if (iobuf_out && iobuf_out_cnt
934 && (important || time(NULL) - last_io_out >= 5))
935 io_flush(NORMAL_FLUSH);
938 void maybe_send_keepalive(void)
940 if (time(NULL) - last_io_out >= allowed_lull) {
941 if (!iobuf_out || !iobuf_out_cnt) {
942 if (protocol_version < 29)
943 return; /* there's nothing we can do */
944 if (protocol_version >= 30)
945 send_msg(MSG_NOOP, "", 0, 0);
947 write_int(sock_f_out, cur_flist->used);
948 write_shortint(sock_f_out, ITEM_IS_NEW);
952 io_flush(NORMAL_FLUSH);
956 void start_flist_forward(int f_in)
958 assert(iobuf_out != NULL);
959 assert(iobuf_f_out == msg_fd_out);
960 flist_forward_from = f_in;
963 void stop_flist_forward()
965 flist_forward_from = -1;
966 io_flush(FULL_FLUSH);
970 * Continue trying to read len bytes - don't return until len has been
973 static void read_loop(int fd, char *buf, size_t len)
976 int n = read_timeout(fd, buf, len);
984 * Read from the file descriptor handling multiplexing - return number
987 * Never returns <= 0.
989 static int readfd_unbuffered(int fd, char *buf, size_t len)
993 char line[BIGPATHBUFLEN];
995 if (!iobuf_in || fd != iobuf_f_in)
996 return read_timeout(fd, buf, len);
998 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
999 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
1004 if (iobuf_in_remaining) {
1005 len = MIN(len, iobuf_in_remaining);
1006 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
1007 iobuf_in_ndx += len;
1008 iobuf_in_remaining -= len;
1013 read_loop(fd, line, 4);
1014 tag = IVAL(line, 0);
1016 msg_bytes = tag & 0xFFFFFF;
1017 tag = (tag >> 24) - MPLEX_BASE;
1021 if (msg_bytes > iobuf_in_siz) {
1022 if (!(iobuf_in = realloc_array(iobuf_in, char,
1024 out_of_memory("readfd_unbuffered");
1025 iobuf_in_siz = msg_bytes;
1027 read_loop(fd, iobuf_in, msg_bytes);
1028 iobuf_in_remaining = msg_bytes;
1033 maybe_send_keepalive();
1038 read_loop(fd, line, msg_bytes);
1039 send_msg_int(MSG_IO_ERROR, IVAL(line, 0));
1040 io_error |= IVAL(line, 0);
1043 if (msg_bytes >= sizeof line)
1046 if (ic_recv != (iconv_t)-1) {
1052 INIT_CONST_XBUF(outbuf, line);
1053 INIT_XBUF(inbuf, ibuf, 0, -1);
1056 inbuf.len = msg_bytes > sizeof ibuf
1057 ? sizeof ibuf : msg_bytes;
1058 read_loop(fd, inbuf.buf, inbuf.len);
1059 if (!(msg_bytes -= inbuf.len)
1060 && !ibuf[inbuf.len-1])
1061 inbuf.len--, add_null = 1;
1062 if (iconvbufs(ic_send, &inbuf, &outbuf,
1063 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE) < 0)
1068 if (outbuf.len == outbuf.size)
1070 outbuf.buf[outbuf.len++] = '\0';
1072 msg_bytes = outbuf.len;
1075 read_loop(fd, line, msg_bytes);
1076 /* A directory name was sent with the trailing null */
1077 if (msg_bytes > 0 && !line[msg_bytes-1])
1078 log_delete(line, S_IFDIR);
1080 line[msg_bytes] = '\0';
1081 log_delete(line, S_IFREG);
1085 if (msg_bytes != 4) {
1087 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
1088 tag, (long)msg_bytes, who_am_i());
1089 exit_cleanup(RERR_STREAMIO);
1091 read_loop(fd, line, msg_bytes);
1092 successful_send(IVAL(line, 0));
1097 read_loop(fd, line, msg_bytes);
1098 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1102 case MSG_ERROR_XFER:
1104 if (msg_bytes >= sizeof line) {
1107 "multiplexing overflow %d:%ld [%s]\n",
1108 tag, (long)msg_bytes, who_am_i());
1109 exit_cleanup(RERR_STREAMIO);
1111 read_loop(fd, line, msg_bytes);
1112 rwrite((enum logcode)tag, line, msg_bytes, 1);
1113 if (first_message) {
1114 if (list_only && !am_sender && tag == 1) {
1115 line[msg_bytes] = '\0';
1116 check_for_d_option_error(line);
1122 rprintf(FERROR, "unexpected tag %d [%s]\n",
1124 exit_cleanup(RERR_STREAMIO);
1128 if (iobuf_in_remaining == 0)
1129 io_flush(NORMAL_FLUSH);
1134 /* Do a buffered read from fd. Don't return until all N bytes have
1135 * been read. If all N can't be read then exit with an error. */
1136 static void readfd(int fd, char *buffer, size_t N)
1142 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1146 if (fd == write_batch_monitor_in) {
1147 if ((size_t)write(batch_fd, buffer, total) != total)
1148 exit_cleanup(RERR_FILEIO);
1151 if (fd == flist_forward_from)
1152 writefd(iobuf_f_out, buffer, total);
1154 if (fd == sock_f_in)
1155 stats.total_read += total;
1158 unsigned short read_shortint(int f)
1162 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1165 int32 read_int(int f)
1172 #if SIZEOF_INT32 > 4
1173 if (num & (int32)0x80000000)
1174 num |= ~(int32)0xffffffff;
1179 int32 read_varint(int f)
1189 readfd(f, (char*)&ch, 1);
1190 extra = int_byte_extra[ch / 4];
1192 uchar bit = ((uchar)1<<(8-extra));
1193 if (extra >= (int)sizeof u.b) {
1194 rprintf(FERROR, "Overflow in read_varint()\n");
1195 exit_cleanup(RERR_STREAMIO);
1197 readfd(f, u.b, extra);
1198 u.b[extra] = ch & (bit-1);
1201 #if CAREFUL_ALIGNMENT
1204 #if SIZEOF_INT32 > 4
1205 if (u.x & (int32)0x80000000)
1206 u.x |= ~(int32)0xffffffff;
1211 int64 read_varlong(int f, uchar min_bytes)
1220 #if SIZEOF_INT64 < 8
1225 readfd(f, b2, min_bytes);
1226 memcpy(u.b, b2+1, min_bytes-1);
1227 extra = int_byte_extra[CVAL(b2, 0) / 4];
1229 uchar bit = ((uchar)1<<(8-extra));
1230 if (min_bytes + extra > (int)sizeof u.b) {
1231 rprintf(FERROR, "Overflow in read_varlong()\n");
1232 exit_cleanup(RERR_STREAMIO);
1234 readfd(f, u.b + min_bytes - 1, extra);
1235 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1236 #if SIZEOF_INT64 < 8
1237 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1238 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1239 exit_cleanup(RERR_UNSUPPORTED);
1243 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1244 #if SIZEOF_INT64 < 8
1246 #elif CAREFUL_ALIGNMENT
1247 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1252 int64 read_longint(int f)
1254 #if SIZEOF_INT64 >= 8
1257 int32 num = read_int(f);
1259 if (num != (int32)0xffffffff)
1262 #if SIZEOF_INT64 < 8
1263 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1264 exit_cleanup(RERR_UNSUPPORTED);
1267 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1271 void read_buf(int f, char *buf, size_t len)
1276 void read_sbuf(int f, char *buf, size_t len)
1278 readfd(f, buf, len);
1282 uchar read_byte(int f)
1285 readfd(f, (char *)&c, 1);
1289 int read_vstring(int f, char *buf, int bufsize)
1291 int len = read_byte(f);
1294 len = (len & ~0x80) * 0x100 + read_byte(f);
1296 if (len >= bufsize) {
1297 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1303 readfd(f, buf, len);
1308 /* Populate a sum_struct with values from the socket. This is
1309 * called by both the sender and the receiver. */
1310 void read_sum_head(int f, struct sum_struct *sum)
1312 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1313 sum->count = read_int(f);
1314 if (sum->count < 0) {
1315 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1316 (long)sum->count, who_am_i());
1317 exit_cleanup(RERR_PROTOCOL);
1319 sum->blength = read_int(f);
1320 if (sum->blength < 0 || sum->blength > max_blength) {
1321 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1322 (long)sum->blength, who_am_i());
1323 exit_cleanup(RERR_PROTOCOL);
1325 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1326 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1327 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1328 sum->s2length, who_am_i());
1329 exit_cleanup(RERR_PROTOCOL);
1331 sum->remainder = read_int(f);
1332 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1333 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1334 (long)sum->remainder, who_am_i());
1335 exit_cleanup(RERR_PROTOCOL);
1339 /* Send the values from a sum_struct over the socket. Set sum to
1340 * NULL if there are no checksums to send. This is called by both
1341 * the generator and the sender. */
1342 void write_sum_head(int f, struct sum_struct *sum)
1344 static struct sum_struct null_sum;
1349 write_int(f, sum->count);
1350 write_int(f, sum->blength);
1351 if (protocol_version >= 27)
1352 write_int(f, sum->s2length);
1353 write_int(f, sum->remainder);
1357 * Sleep after writing to limit I/O bandwidth usage.
1359 * @todo Rather than sleeping after each write, it might be better to
1360 * use some kind of averaging. The current algorithm seems to always
1361 * use a bit less bandwidth than specified, because it doesn't make up
1362 * for slow periods. But arguably this is a feature. In addition, we
1363 * ought to take the time used to write the data into account.
1365 * During some phases of big transfers (file FOO is uptodate) this is
1366 * called with a small bytes_written every time. As the kernel has to
1367 * round small waits up to guarantee that we actually wait at least the
1368 * requested number of microseconds, this can become grossly inaccurate.
1369 * We therefore keep track of the bytes we've written over time and only
1370 * sleep when the accumulated delay is at least 1 tenth of a second.
1372 static void sleep_for_bwlimit(int bytes_written)
1374 static struct timeval prior_tv;
1375 static long total_written = 0;
1376 struct timeval tv, start_tv;
1377 long elapsed_usec, sleep_usec;
1379 #define ONE_SEC 1000000L /* # of microseconds in a second */
1381 if (!bwlimit_writemax)
1384 total_written += bytes_written;
1386 gettimeofday(&start_tv, NULL);
1387 if (prior_tv.tv_sec) {
1388 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1389 + (start_tv.tv_usec - prior_tv.tv_usec);
1390 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1391 if (total_written < 0)
1395 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1396 if (sleep_usec < ONE_SEC / 10) {
1397 prior_tv = start_tv;
1401 tv.tv_sec = sleep_usec / ONE_SEC;
1402 tv.tv_usec = sleep_usec % ONE_SEC;
1403 select(0, NULL, NULL, NULL, &tv);
1405 gettimeofday(&prior_tv, NULL);
1406 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1407 + (prior_tv.tv_usec - start_tv.tv_usec);
1408 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1411 /* Write len bytes to the file descriptor fd, looping as necessary to get
1412 * the job done and also (in certain circumstances) reading any data on
1413 * msg_fd_in to avoid deadlock.
1415 * This function underlies the multiplexing system. The body of the
1416 * application never calls this function directly. */
1417 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1419 size_t n, total = 0;
1420 fd_set w_fds, r_fds, e_fds;
1421 int maxfd, count, cnt, using_r_fds;
1426 defer_forwarding_messages++, defer_inc++;
1428 while (total < len) {
1435 if (msg_fd_in >= 0) {
1437 FD_SET(msg_fd_in, &r_fds);
1438 if (msg_fd_in > maxfd)
1444 tv.tv_sec = select_timeout;
1448 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1449 &w_fds, &e_fds, &tv);
1452 if (count < 0 && errno == EBADF)
1453 exit_cleanup(RERR_SOCKETIO);
1458 /*if (FD_ISSET(fd, &e_fds))
1459 rprintf(FINFO, "select exception on fd %d\n", fd); */
1461 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1464 if (!FD_ISSET(fd, &w_fds))
1468 if (bwlimit_writemax && n > bwlimit_writemax)
1469 n = bwlimit_writemax;
1470 cnt = write(fd, buf + total, n);
1476 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1482 /* Don't try to write errors back across the stream. */
1483 if (fd == sock_f_out)
1484 io_end_multiplex_out();
1485 /* Don't try to write errors down a failing msg pipe. */
1486 if (am_server && fd == msg_fd_out)
1487 exit_cleanup(RERR_STREAMIO);
1488 rsyserr(FERROR, errno,
1489 "writefd_unbuffered failed to write %ld bytes [%s]",
1490 (long)len, who_am_i());
1491 /* If the other side is sending us error messages, try
1492 * to grab any messages they sent before they died. */
1493 while (!am_server && fd == sock_f_out && io_multiplexing_in) {
1497 readfd_unbuffered(sock_f_in, buf, sizeof buf);
1499 exit_cleanup(RERR_STREAMIO);
1503 defer_forwarding_messages++, defer_inc++;
1505 if (fd == sock_f_out) {
1506 if (io_timeout || am_generator)
1507 last_io_out = time(NULL);
1508 sleep_for_bwlimit(cnt);
1513 if (keep_defer_forwarding)
1515 if (!(defer_forwarding_messages -= defer_inc) && !no_flush)
1519 int io_flush(int flush_it_all)
1521 int flushed_something = 0;
1526 if (iobuf_out_cnt) {
1527 if (io_multiplexing_out)
1528 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1530 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1532 flushed_something = 1;
1535 if (flush_it_all && !defer_forwarding_messages && msg_queue.head) {
1537 flushed_something = 1;
1540 return flushed_something;
1543 static void writefd(int fd, const char *buf, size_t len)
1545 if (fd == sock_f_out)
1546 stats.total_written += len;
1548 if (fd == write_batch_monitor_out) {
1549 if ((size_t)write(batch_fd, buf, len) != len)
1550 exit_cleanup(RERR_FILEIO);
1553 if (!iobuf_out || fd != iobuf_f_out) {
1554 writefd_unbuffered(fd, buf, len);
1559 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1561 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1567 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1568 io_flush(NORMAL_FLUSH);
1572 void write_shortint(int f, unsigned short x)
1576 b[1] = (char)(x >> 8);
1580 void write_int(int f, int32 x)
1587 void write_varint(int f, int32 x)
1595 while (cnt > 1 && b[cnt] == 0)
1597 bit = ((uchar)1<<(7-cnt+1));
1598 if (CVAL(b, cnt) >= bit) {
1602 *b = b[cnt] | ~(bit*2-1);
1609 void write_varlong(int f, int64 x, uchar min_bytes)
1616 #if SIZEOF_INT64 >= 8
1617 SIVAL(b, 5, x >> 32);
1619 if (x <= 0x7FFFFFFF && x >= 0)
1620 memset(b + 5, 0, 4);
1622 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1623 exit_cleanup(RERR_UNSUPPORTED);
1627 while (cnt > min_bytes && b[cnt] == 0)
1629 bit = ((uchar)1<<(7-cnt+min_bytes));
1630 if (CVAL(b, cnt) >= bit) {
1633 } else if (cnt > min_bytes)
1634 *b = b[cnt] | ~(bit*2-1);
1642 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1643 * 64-bit types on this platform.
1645 void write_longint(int f, int64 x)
1647 char b[12], * const s = b+4;
1650 if (x <= 0x7FFFFFFF && x >= 0) {
1655 #if SIZEOF_INT64 < 8
1656 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1657 exit_cleanup(RERR_UNSUPPORTED);
1660 SIVAL(s, 4, x >> 32);
1665 void write_buf(int f, const char *buf, size_t len)
1670 /** Write a string to the connection */
1671 void write_sbuf(int f, const char *buf)
1673 writefd(f, buf, strlen(buf));
1676 void write_byte(int f, uchar c)
1678 writefd(f, (char *)&c, 1);
1681 void write_vstring(int f, const char *str, int len)
1683 uchar lenbuf[3], *lb = lenbuf;
1688 "attempting to send over-long vstring (%d > %d)\n",
1690 exit_cleanup(RERR_PROTOCOL);
1692 *lb++ = len / 0x100 + 0x80;
1696 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1698 writefd(f, str, len);
1701 /* Send a file-list index using a byte-reduction method. */
1702 void write_ndx(int f, int32 ndx)
1704 static int32 prev_positive = -1, prev_negative = 1;
1705 int32 diff, cnt = 0;
1708 if (protocol_version < 30 || read_batch) {
1713 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1714 * negative nums as a positive after sending a leading 0xFF. */
1716 diff = ndx - prev_positive;
1717 prev_positive = ndx;
1718 } else if (ndx == NDX_DONE) {
1723 b[cnt++] = (char)0xFF;
1725 diff = ndx - prev_negative;
1726 prev_negative = ndx;
1729 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1730 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1731 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1732 if (diff < 0xFE && diff > 0)
1733 b[cnt++] = (char)diff;
1734 else if (diff < 0 || diff > 0x7FFF) {
1735 b[cnt++] = (char)0xFE;
1736 b[cnt++] = (char)((ndx >> 24) | 0x80);
1737 b[cnt++] = (char)ndx;
1738 b[cnt++] = (char)(ndx >> 8);
1739 b[cnt++] = (char)(ndx >> 16);
1741 b[cnt++] = (char)0xFE;
1742 b[cnt++] = (char)(diff >> 8);
1743 b[cnt++] = (char)diff;
1748 /* Receive a file-list index using a byte-reduction method. */
1749 int32 read_ndx(int f)
1751 static int32 prev_positive = -1, prev_negative = 1;
1752 int32 *prev_ptr, num;
1755 if (protocol_version < 30)
1759 if (CVAL(b, 0) == 0xFF) {
1761 prev_ptr = &prev_negative;
1762 } else if (CVAL(b, 0) == 0)
1765 prev_ptr = &prev_positive;
1766 if (CVAL(b, 0) == 0xFE) {
1768 if (CVAL(b, 0) & 0x80) {
1769 b[3] = CVAL(b, 0) & ~0x80;
1774 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1776 num = UVAL(b, 0) + *prev_ptr;
1778 if (prev_ptr == &prev_negative)
1783 /* Read a line of up to bufsiz-1 characters into buf. Strips
1784 * the (required) trailing newline and all carriage returns.
1785 * Returns 1 for success; 0 for I/O error or truncation. */
1786 int read_line_old(int f, char *buf, size_t bufsiz)
1788 bufsiz--; /* leave room for the null */
1789 while (bufsiz > 0) {
1791 read_buf(f, buf, 1);
1796 if (buf[0] != '\r') {
1805 void io_printf(int fd, const char *format, ...)
1808 char buf[BIGPATHBUFLEN];
1811 va_start(ap, format);
1812 len = vsnprintf(buf, sizeof buf, format, ap);
1816 exit_cleanup(RERR_STREAMIO);
1818 if (len > (int)sizeof buf) {
1819 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1820 exit_cleanup(RERR_STREAMIO);
1823 write_sbuf(fd, buf);
1826 /** Setup for multiplexing a MSG_* stream with the data stream. */
1827 void io_start_multiplex_out(void)
1829 io_flush(NORMAL_FLUSH);
1830 io_start_buffering_out(sock_f_out);
1831 io_multiplexing_out = 1;
1834 /** Setup for multiplexing a MSG_* stream with the data stream. */
1835 void io_start_multiplex_in(void)
1837 io_flush(NORMAL_FLUSH);
1838 io_start_buffering_in(sock_f_in);
1839 io_multiplexing_in = 1;
1842 /** Write an message to the multiplexed data stream. */
1843 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1845 if (!io_multiplexing_out)
1847 io_flush(NORMAL_FLUSH);
1848 stats.total_written += (len+4);
1849 mplex_write(sock_f_out, code, buf, len, convert);
1853 void io_end_multiplex_in(void)
1855 io_multiplexing_in = 0;
1856 io_end_buffering_in();
1859 /** Stop output multiplexing. */
1860 void io_end_multiplex_out(void)
1862 io_multiplexing_out = 0;
1863 io_end_buffering_out();
1866 void start_write_batch(int fd)
1868 /* Some communication has already taken place, but we don't
1869 * enable batch writing until here so that we can write a
1870 * canonical record of the communication even though the
1871 * actual communication so far depends on whether a daemon
1873 write_int(batch_fd, protocol_version);
1874 if (protocol_version >= 30)
1875 write_byte(batch_fd, inc_recurse);
1876 write_int(batch_fd, checksum_seed);
1879 write_batch_monitor_out = fd;
1881 write_batch_monitor_in = fd;
1884 void stop_write_batch(void)
1886 write_batch_monitor_out = -1;
1887 write_batch_monitor_in = -1;