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-2009 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(). */
34 /** If no timeout is specified then use a 60 second select timeout */
35 #define SELECT_TIMEOUT 60
38 extern size_t bwlimit_writemax;
39 extern int io_timeout;
43 extern int am_generator;
44 extern int inc_recurse;
48 extern int file_total;
49 extern int file_old_total;
51 extern int read_batch;
52 extern int protect_args;
53 extern int checksum_seed;
54 extern int protocol_version;
55 extern int remove_source_files;
56 extern int preserve_hard_links;
57 extern struct stats stats;
58 extern struct file_list *cur_flist;
60 extern int filesfrom_convert;
61 extern iconv_t ic_send, ic_recv;
64 int csum_length = SHORT_SUM_LENGTH; /* initial value */
66 int ignore_timeout = 0;
70 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
71 int kluge_around_eof = 0;
78 static int iobuf_f_in = -1;
79 static char *iobuf_in;
80 static size_t iobuf_in_siz;
81 static size_t iobuf_in_ndx;
82 static size_t iobuf_in_remaining;
84 static int iobuf_f_out = -1;
85 static char *iobuf_out;
86 static int iobuf_out_cnt;
88 int flist_forward_from = -1;
90 static int io_multiplexing_out;
91 static int io_multiplexing_in;
92 static time_t last_io_in;
93 static time_t last_io_out;
96 static int write_batch_monitor_in = -1;
97 static int write_batch_monitor_out = -1;
99 static int io_filesfrom_f_in = -1;
100 static int io_filesfrom_f_out = -1;
101 static xbuf ff_buf = EMPTY_XBUF;
102 static char ff_lastchar;
104 static xbuf iconv_buf = EMPTY_XBUF;
106 static int defer_forwarding_messages = 0, keep_defer_forwarding = 0;
107 static int select_timeout = SELECT_TIMEOUT;
108 static int active_filecnt = 0;
109 static OFF_T active_bytecnt = 0;
110 static int first_message = 1;
112 static char int_byte_extra[64] = {
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
116 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
119 #define REMOTE_OPTION_ERROR "rsync: on remote machine: -"
120 #define REMOTE_OPTION_ERROR2 ": unknown option"
122 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
124 static void readfd(int fd, char *buffer, size_t N);
125 static void writefd(int fd, const char *buf, size_t len);
126 static void writefd_unbuffered(int fd, const char *buf, size_t len);
127 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
128 static void read_a_msg(int fd);
130 static 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 got_flist_entry_status(enum festatus status, const char *buf)
146 int ndx = IVAL(buf, 0);
147 struct file_list *flist = flist_for_ndx(ndx, "got_flist_entry_status");
149 if (remove_source_files) {
151 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
155 flist->in_progress--;
159 if (remove_source_files)
160 send_msg(MSG_SUCCESS, buf, 4, 0);
161 if (preserve_hard_links) {
162 struct file_struct *file = flist->files[ndx - flist->ndx_start];
163 if (F_IS_HLINKED(file)) {
164 flist_ndx_push(&hlink_list, ndx);
165 flist->in_progress++;
172 flist->in_progress++;
177 flist_ndx_push(&redo_list, ndx);
184 static void check_timeout(void)
188 if (!io_timeout || ignore_timeout)
192 last_io_in = time(NULL);
198 if (t - last_io_in >= io_timeout) {
199 if (!am_server && !am_daemon) {
200 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
201 (int)(t-last_io_in));
203 exit_cleanup(RERR_TIMEOUT);
207 /* Note the fds used for the main socket (which might really be a pipe
208 * for a local transfer, but we can ignore that). */
209 void io_set_sock_fds(int f_in, int f_out)
215 void set_io_timeout(int secs)
219 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
220 select_timeout = SELECT_TIMEOUT;
222 select_timeout = io_timeout;
224 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
227 /* Setup the fd used to receive MSG_* messages. Only needed during the
228 * early stages of being a local sender (up through the sending of the
229 * file list) or when we're the generator (to fetch the messages from
231 void set_msg_fd_in(int fd)
236 /* Setup the fd used to send our MSG_* messages. Only needed when
237 * we're the receiver (to send our messages to the generator). */
238 void set_msg_fd_out(int fd)
241 set_nonblocking(msg_fd_out);
244 /* Add a message to the pending MSG_* list. */
245 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
247 struct msg_list_item *m;
248 int sz = len + 4 + sizeof m[0] - 1;
250 if (!(m = (struct msg_list_item *)new_array(char, sz)))
251 out_of_memory("msg_list_add");
253 m->convert = convert;
254 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
255 memcpy(m->buf + 4, buf, len);
263 static inline int flush_a_msg(int fd)
265 struct msg_list_item *m = msg_queue.head;
266 int len = IVAL(m->buf, 0) & 0xFFFFFF;
267 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
269 if (!(msg_queue.head = m->next))
270 msg_queue.tail = NULL;
272 defer_forwarding_messages++;
273 mplex_write(fd, tag, m->buf + 4, len, m->convert);
274 defer_forwarding_messages--;
281 static void msg_flush(void)
284 while (msg_queue.head && io_multiplexing_out)
285 stats.total_written += flush_a_msg(sock_f_out) + 4;
287 while (msg_queue.head)
288 (void)flush_a_msg(msg_fd_out);
292 static void check_for_d_option_error(const char *msg)
294 static char rsync263_opts[] = "BCDHIKLPRSTWabceghlnopqrtuvxz";
299 || strncmp(msg, REMOTE_OPTION_ERROR, sizeof REMOTE_OPTION_ERROR - 1) != 0)
302 msg += sizeof REMOTE_OPTION_ERROR - 1;
303 if (*msg == '-' || (colon = strchr(msg, ':')) == NULL
304 || strncmp(colon, REMOTE_OPTION_ERROR2, sizeof REMOTE_OPTION_ERROR2 - 1) != 0)
307 for ( ; *msg != ':'; msg++) {
310 else if (*msg == 'e')
312 else if (strchr(rsync263_opts, *msg) == NULL)
318 "*** Try using \"--old-d\" if remote rsync is <= 2.6.3 ***\n");
322 /* This is used by the generator to limit how many file transfers can
323 * be active at once when --remove-source-files is specified. Without
324 * this, sender-side deletions were mostly happening at the end. */
325 void increment_active_files(int ndx, int itemizing, enum logcode code)
328 /* TODO: tune these limits? */
329 int limit = active_bytecnt >= 128*1024 ? 10 : 50;
330 if (active_filecnt < limit)
332 check_for_finished_files(itemizing, code, 0);
333 if (active_filecnt < limit)
336 io_flush(NORMAL_FLUSH);
338 read_a_msg(msg_fd_in);
342 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
345 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
346 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
348 char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
352 /* We need to convert buf before doing anything else so that we
353 * can include the (converted) byte length in the message header. */
354 if (convert && ic_send != (iconv_t)-1) {
357 INIT_XBUF(outbuf, buffer + 4, 0, sizeof buffer - 4);
358 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
360 iconvbufs(ic_send, &inbuf, &outbuf,
361 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE);
363 rprintf(FERROR, "overflowed conversion buffer in mplex_write");
364 exit_cleanup(RERR_UNSUPPORTED);
367 n = len = outbuf.len;
370 if (n > 1024 - 4) /* BIGPATHBUFLEN can handle 1024 bytes */
371 n = 0; /* We'd rather do 2 writes than too much memcpy(). */
373 memcpy(buffer + 4, buf, n);
375 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
377 keep_defer_forwarding++; /* defer_forwarding_messages++ on return */
378 writefd_unbuffered(fd, buffer, n+4);
379 keep_defer_forwarding--;
382 writefd_unbuffered(fd, buf+n, len-n);
384 if (!--defer_forwarding_messages && !no_flush)
388 int send_msg(enum msgcode code, const char *buf, int len, int convert)
390 if (msg_fd_out < 0) {
391 if (!defer_forwarding_messages)
392 return io_multiplex_write(code, buf, len, convert);
393 if (!io_multiplexing_out)
395 msg_list_add(&msg_queue, code, buf, len, convert);
398 if (defer_forwarding_messages)
399 msg_list_add(&msg_queue, code, buf, len, convert);
401 mplex_write(msg_fd_out, code, buf, len, convert);
405 void send_msg_int(enum msgcode code, int num)
408 SIVAL(numbuf, 0, num);
409 send_msg(code, numbuf, 4, 0);
412 void wait_for_receiver(void)
414 if (io_flush(FULL_FLUSH))
416 read_a_msg(msg_fd_in);
419 int get_redo_num(void)
421 return flist_ndx_pop(&redo_list);
424 int get_hlink_num(void)
426 return flist_ndx_pop(&hlink_list);
430 * When we're the receiver and we have a local --files-from list of names
431 * that needs to be sent over the socket to the sender, we have to do two
432 * things at the same time: send the sender a list of what files we're
433 * processing and read the incoming file+info list from the sender. We do
434 * this by augmenting the read_timeout() function to copy this data. It
435 * uses ff_buf to read a block of data from f_in (when it is ready, since
436 * it might be a pipe) and then blast it out f_out (when it is ready to
437 * receive more data).
439 void io_set_filesfrom_fds(int f_in, int f_out)
441 io_filesfrom_f_in = f_in;
442 io_filesfrom_f_out = f_out;
443 alloc_xbuf(&ff_buf, 2048);
446 alloc_xbuf(&iconv_buf, 1024);
450 /* It's almost always an error to get an EOF when we're trying to read from the
451 * network, because the protocol is (for the most part) self-terminating.
453 * There is one case for the receiver when it is at the end of the transfer
454 * (hanging around reading any keep-alive packets that might come its way): if
455 * the sender dies before the generator's kill-signal comes through, we can end
456 * up here needing to loop until the kill-signal arrives. In this situation,
457 * kluge_around_eof will be < 0.
459 * There is another case for older protocol versions (< 24) where the module
460 * listing was not terminated, so we must ignore an EOF error in that case and
461 * exit. In this situation, kluge_around_eof will be > 0. */
462 static void whine_about_eof(int fd)
464 if (kluge_around_eof && fd == sock_f_in) {
466 if (kluge_around_eof > 0)
468 /* If we're still here after 10 seconds, exit with an error. */
469 for (i = 10*1000/20; i--; )
473 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
474 "(%s bytes received so far) [%s]\n",
475 big_num(stats.total_read), who_am_i());
477 exit_cleanup(RERR_STREAMIO);
480 /* Read from a socket with I/O timeout. return the number of bytes
481 * read. If no bytes can be read then exit, never return a number <= 0.
483 * TODO: If the remote shell connection fails, then current versions
484 * actually report an "unexpected EOF" error here. Since it's a
485 * fairly common mistake to try to use rsh when ssh is required, we
486 * should trap that: if we fail to read any data at all, we should
487 * give a better explanation. We can tell whether the connection has
488 * started by looking e.g. at whether the remote version is known yet. */
489 static int read_timeout(int fd, char *buf, size_t len)
493 io_flush(FULL_FLUSH);
496 /* until we manage to read *something* */
505 if (io_filesfrom_f_out >= 0) {
507 if (ff_buf.len == 0) {
508 if (io_filesfrom_f_in >= 0) {
509 FD_SET(io_filesfrom_f_in, &r_fds);
510 new_fd = io_filesfrom_f_in;
512 io_filesfrom_f_out = -1;
516 FD_SET(io_filesfrom_f_out, &w_fds);
517 new_fd = io_filesfrom_f_out;
523 if (am_sender && inc_recurse && !flist_eof && !defer_forwarding_messages && !cnt
524 && file_total - file_old_total < MAX_FILECNT_LOOKAHEAD
525 && file_total - file_old_total >= MIN_FILECNT_LOOKAHEAD)
528 tv.tv_sec = select_timeout;
533 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
536 if (errno == EBADF) {
537 defer_forwarding_messages = 0;
538 exit_cleanup(RERR_SOCKETIO);
540 if (am_sender && tv.tv_sec == 0)
541 send_extra_file_list(sock_f_out, -1);
547 if (io_filesfrom_f_out >= 0) {
549 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
550 int l = write(io_filesfrom_f_out,
551 ff_buf.buf + ff_buf.pos,
554 if (!(ff_buf.len -= l))
558 } else if (errno != EINTR) {
559 /* XXX should we complain? */
560 io_filesfrom_f_out = -1;
563 } else if (io_filesfrom_f_in >= 0) {
564 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
566 xbuf *ibuf = filesfrom_convert ? &iconv_buf : &ff_buf;
568 xbuf *ibuf = &ff_buf;
570 int l = read(io_filesfrom_f_in, ibuf->buf, ibuf->size);
572 if (l == 0 || errno != EINTR) {
573 /* Send end-of-file marker */
574 memcpy(ff_buf.buf, "\0\0", 2);
575 ff_buf.len = ff_lastchar? 2 : 1;
577 io_filesfrom_f_in = -1;
581 if (filesfrom_convert) {
584 iconvbufs(ic_send, &iconv_buf, &ff_buf,
585 ICB_EXPAND_OUT|ICB_INCLUDE_BAD|ICB_INCLUDE_INCOMPLETE);
590 char *s = ff_buf.buf + l;
591 /* Transform CR and/or LF into '\0' */
592 while (s-- > ff_buf.buf) {
593 if (*s == '\n' || *s == '\r')
598 /* Last buf ended with a '\0', so don't
599 * let this buf start with one. */
600 while (l && ff_buf.buf[ff_buf.pos] == '\0')
606 char *f = ff_buf.buf + ff_buf.pos;
609 /* Eliminate any multi-'\0' runs. */
611 if (!(*t++ = *f++)) {
612 while (f != eob && !*f)
624 if (!FD_ISSET(fd, &r_fds))
627 n = read(fd, buf, len);
631 whine_about_eof(fd); /* Doesn't return. */
632 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
635 /* Don't write errors on a dead socket. */
636 if (fd == sock_f_in) {
638 io_multiplexing_out = 0;
639 rsyserr(FERROR_SOCKET, errno, "read error");
641 rsyserr(FERROR, errno, "read error");
642 exit_cleanup(RERR_STREAMIO);
649 if (fd == sock_f_in && io_timeout)
650 last_io_in = time(NULL);
656 /* Read a line into the "buf" buffer. */
657 int read_line(int fd, char *buf, size_t bufsiz, int flags)
663 if (flags & RL_CONVERT && iconv_buf.size < bufsiz)
664 realloc_xbuf(&iconv_buf, bufsiz + 1024);
669 s = flags & RL_CONVERT ? iconv_buf.buf : buf;
673 eob = s + bufsiz - 1;
675 cnt = read(fd, &ch, 1);
676 if (cnt < 0 && (errno == EWOULDBLOCK
677 || errno == EINTR || errno == EAGAIN)) {
684 tv.tv_sec = select_timeout;
686 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
688 /*if (FD_ISSET(fd, &e_fds))
689 rprintf(FINFO, "select exception on fd %d\n", fd); */
694 if (flags & RL_EOL_NULLS ? ch == '\0' : (ch == '\r' || ch == '\n')) {
695 /* Skip empty lines if dumping comments. */
696 if (flags & RL_DUMP_COMMENTS && s == buf)
705 if (flags & RL_DUMP_COMMENTS && (*buf == '#' || *buf == ';'))
709 if (flags & RL_CONVERT) {
711 INIT_XBUF(outbuf, buf, 0, bufsiz);
713 iconv_buf.len = s - iconv_buf.buf;
714 iconvbufs(ic_recv, &iconv_buf, &outbuf,
715 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE);
716 outbuf.buf[outbuf.len] = '\0';
724 void read_args(int f_in, char *mod_name, char *buf, size_t bufsiz, int rl_nulls,
725 char ***argv_p, int *argc_p, char **request_p)
727 int maxargs = MAX_ARGS;
731 int rl_flags = (rl_nulls ? RL_EOL_NULLS : 0);
734 rl_flags |= (protect_args && ic_recv != (iconv_t)-1 ? RL_CONVERT : 0);
737 if (!(argv = new_array(char *, maxargs)))
738 out_of_memory("read_args");
739 if (mod_name && !protect_args)
740 argv[argc++] = "rsyncd";
743 if (read_line(f_in, buf, bufsiz, rl_flags) == 0)
746 if (argc == maxargs-1) {
748 if (!(argv = realloc_array(argv, char *, maxargs)))
749 out_of_memory("read_args");
754 *request_p = strdup(buf);
758 glob_expand_module(mod_name, buf, &argv, &argc, &maxargs);
760 glob_expand(buf, &argv, &argc, &maxargs);
762 if (!(p = strdup(buf)))
763 out_of_memory("read_args");
765 if (*p == '.' && p[1] == '\0')
771 glob_expand(NULL, NULL, NULL, NULL);
777 int io_start_buffering_out(int f_out)
780 assert(f_out == iobuf_f_out);
783 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
784 out_of_memory("io_start_buffering_out");
790 int io_start_buffering_in(int f_in)
793 assert(f_in == iobuf_f_in);
796 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
797 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
798 out_of_memory("io_start_buffering_in");
803 void io_end_buffering_in(void)
810 iobuf_in_remaining = 0;
814 void io_end_buffering_out(void)
818 io_flush(FULL_FLUSH);
824 void maybe_flush_socket(int important)
826 if (iobuf_out && iobuf_out_cnt
827 && (important || time(NULL) - last_io_out >= 5))
828 io_flush(NORMAL_FLUSH);
831 void maybe_send_keepalive(void)
833 if (time(NULL) - last_io_out >= allowed_lull) {
834 if (!iobuf_out || !iobuf_out_cnt) {
835 if (protocol_version < 29)
836 return; /* there's nothing we can do */
837 if (protocol_version >= 30)
838 send_msg(MSG_NOOP, "", 0, 0);
840 write_int(sock_f_out, cur_flist->used);
841 write_shortint(sock_f_out, ITEM_IS_NEW);
845 io_flush(NORMAL_FLUSH);
849 void start_flist_forward(int f_in)
851 assert(iobuf_out != NULL);
852 assert(iobuf_f_out == msg_fd_out);
853 flist_forward_from = f_in;
856 void stop_flist_forward()
858 flist_forward_from = -1;
859 io_flush(FULL_FLUSH);
862 /* Continue trying to read len bytes until all have been read.
863 * Used to read raw bytes from a multiplexed source. */
864 static void read_loop(int fd, char *buf, size_t len)
867 int n = read_timeout(fd, buf, len);
874 /* Read a message from a multiplexed source. */
875 static void read_a_msg(int fd)
877 char line[BIGPATHBUFLEN];
879 int tag, flist_parent = -1, save_msg_fd_in = msg_fd_in;
881 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
882 * to this routine from writefd_unbuffered(). */
885 read_loop(fd, line, 4);
888 msg_bytes = tag & 0xFFFFFF;
889 tag = (tag >> 24) - MPLEX_BASE;
895 if (msg_bytes > iobuf_in_siz) {
896 if (!(iobuf_in = realloc_array(iobuf_in, char, msg_bytes)))
897 out_of_memory("read_a_msg");
898 iobuf_in_siz = msg_bytes;
900 read_loop(fd, iobuf_in, msg_bytes);
901 iobuf_in_remaining = msg_bytes;
905 if (msg_bytes > 1 || !am_generator)
908 read_loop(fd, line, 1);
909 stats.total_read = read_varlong(fd, 3);
914 if (msg_bytes != 4 || !am_generator)
916 read_loop(fd, line, 4);
917 got_flist_entry_status(FES_REDO, line);
920 if (msg_bytes != 4 || !am_generator || !inc_recurse)
922 read_loop(fd, line, 4);
923 /* Read extra file list from receiver. */
924 if (DEBUG_GTE(FLIST, 2)) {
925 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
926 who_am_i(), IVAL(line, 0));
928 flist_parent = IVAL(line, 0);
931 if (msg_bytes != 0 || !am_generator || !inc_recurse)
936 if (msg_bytes != 4 || am_sender)
938 read_loop(fd, line, 4);
939 io_error |= IVAL(line, 0);
941 send_msg_int(MSG_IO_ERROR, IVAL(line, 0));
945 maybe_send_keepalive();
951 if (am_sender && am_server)
952 write_del_stats(sock_f_out);
955 if (msg_bytes >= sizeof line)
958 read_loop(fd, line, msg_bytes);
959 send_msg(MSG_DELETED, line, msg_bytes, 1);
963 if (ic_recv != (iconv_t)-1) {
968 INIT_CONST_XBUF(outbuf, line);
969 INIT_XBUF(inbuf, ibuf, 0, (size_t)-1);
972 inbuf.len = msg_bytes > sizeof ibuf
973 ? sizeof ibuf : msg_bytes;
974 read_loop(fd, inbuf.buf, inbuf.len);
975 if (!(msg_bytes -= inbuf.len)
976 && !ibuf[inbuf.len-1])
977 inbuf.len--, add_null = 1;
978 if (iconvbufs(ic_send, &inbuf, &outbuf,
979 ICB_INCLUDE_BAD | ICB_INCLUDE_INCOMPLETE) < 0)
983 if (outbuf.len == outbuf.size)
985 outbuf.buf[outbuf.len++] = '\0';
987 msg_bytes = outbuf.len;
990 read_loop(fd, line, msg_bytes);
991 /* A directory name was sent with the trailing null */
992 if (msg_bytes > 0 && !line[msg_bytes-1])
993 log_delete(line, S_IFDIR);
995 line[msg_bytes] = '\0';
996 log_delete(line, S_IFREG);
1000 if (msg_bytes != 4) {
1002 rprintf(FERROR, "invalid multi-message %d:%lu [%s%s]\n",
1003 tag, (unsigned long)msg_bytes, who_am_i(),
1004 inc_recurse ? "/inc" : "");
1005 exit_cleanup(RERR_STREAMIO);
1007 read_loop(fd, line, 4);
1009 got_flist_entry_status(FES_SUCCESS, line);
1011 successful_send(IVAL(line, 0));
1016 read_loop(fd, line, 4);
1018 got_flist_entry_status(FES_NO_SEND, line);
1020 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1022 case MSG_ERROR_SOCKET:
1023 case MSG_ERROR_UTF8:
1028 if (tag == MSG_ERROR_SOCKET)
1029 io_multiplexing_out = 0;
1033 case MSG_ERROR_XFER:
1035 if (msg_bytes >= sizeof line) {
1038 "multiplexing overflow %d:%lu [%s%s]\n",
1039 tag, (unsigned long)msg_bytes, who_am_i(),
1040 inc_recurse ? "/inc" : "");
1041 exit_cleanup(RERR_STREAMIO);
1043 read_loop(fd, line, msg_bytes);
1044 rwrite((enum logcode)tag, line, msg_bytes, !am_generator);
1045 if (first_message) {
1046 if (list_only && !am_sender && tag == 1) {
1047 line[msg_bytes] = '\0';
1048 check_for_d_option_error(line);
1054 rprintf(FERROR, "unexpected tag %d [%s%s]\n",
1055 tag, who_am_i(), inc_recurse ? "/inc" : "");
1056 exit_cleanup(RERR_STREAMIO);
1059 msg_fd_in = save_msg_fd_in;
1062 if (flist_parent >= 0) {
1063 struct file_list *flist = recv_file_list(fd);
1064 flist->parent_ndx = flist_parent;
1065 #ifdef SUPPORT_HARD_LINKS
1066 if (preserve_hard_links)
1067 match_hard_links(flist);
1072 /* Read from the file descriptor handling multiplexing and return the
1073 * number of bytes read. Never returns <= 0. */
1074 static int readfd_unbuffered(int fd, char *buf, size_t len)
1078 if (!iobuf_in || fd != iobuf_f_in)
1079 return read_timeout(fd, buf, len);
1081 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
1082 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
1087 if (iobuf_in_remaining) {
1088 len = MIN(len, iobuf_in_remaining);
1089 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
1090 iobuf_in_ndx += len;
1091 iobuf_in_remaining -= len;
1098 if (iobuf_in_remaining == 0)
1099 io_flush(NORMAL_FLUSH);
1104 /* Do a buffered read from fd. Don't return until all N bytes have
1105 * been read. If all N can't be read then exit with an error. */
1106 static void readfd(int fd, char *buffer, size_t N)
1112 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1116 if (fd == write_batch_monitor_in) {
1117 if ((size_t)write(batch_fd, buffer, total) != total)
1118 exit_cleanup(RERR_FILEIO);
1121 if (fd == flist_forward_from)
1122 writefd(iobuf_f_out, buffer, total);
1124 if (fd == sock_f_in)
1125 stats.total_read += total;
1128 unsigned short read_shortint(int f)
1132 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1135 int32 read_int(int f)
1142 #if SIZEOF_INT32 > 4
1143 if (num & (int32)0x80000000)
1144 num |= ~(int32)0xffffffff;
1149 int32 read_varint(int f)
1159 readfd(f, (char*)&ch, 1);
1160 extra = int_byte_extra[ch / 4];
1162 uchar bit = ((uchar)1<<(8-extra));
1163 if (extra >= (int)sizeof u.b) {
1164 rprintf(FERROR, "Overflow in read_varint()\n");
1165 exit_cleanup(RERR_STREAMIO);
1167 readfd(f, u.b, extra);
1168 u.b[extra] = ch & (bit-1);
1171 #if CAREFUL_ALIGNMENT
1174 #if SIZEOF_INT32 > 4
1175 if (u.x & (int32)0x80000000)
1176 u.x |= ~(int32)0xffffffff;
1181 int64 read_varlong(int f, uchar min_bytes)
1190 #if SIZEOF_INT64 < 8
1195 readfd(f, b2, min_bytes);
1196 memcpy(u.b, b2+1, min_bytes-1);
1197 extra = int_byte_extra[CVAL(b2, 0) / 4];
1199 uchar bit = ((uchar)1<<(8-extra));
1200 if (min_bytes + extra > (int)sizeof u.b) {
1201 rprintf(FERROR, "Overflow in read_varlong()\n");
1202 exit_cleanup(RERR_STREAMIO);
1204 readfd(f, u.b + min_bytes - 1, extra);
1205 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1206 #if SIZEOF_INT64 < 8
1207 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1208 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1209 exit_cleanup(RERR_UNSUPPORTED);
1213 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1214 #if SIZEOF_INT64 < 8
1216 #elif CAREFUL_ALIGNMENT
1217 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1222 int64 read_longint(int f)
1224 #if SIZEOF_INT64 >= 8
1227 int32 num = read_int(f);
1229 if (num != (int32)0xffffffff)
1232 #if SIZEOF_INT64 < 8
1233 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1234 exit_cleanup(RERR_UNSUPPORTED);
1237 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1241 void read_buf(int f, char *buf, size_t len)
1246 void read_sbuf(int f, char *buf, size_t len)
1248 readfd(f, buf, len);
1252 uchar read_byte(int f)
1255 readfd(f, (char *)&c, 1);
1259 int read_vstring(int f, char *buf, int bufsize)
1261 int len = read_byte(f);
1264 len = (len & ~0x80) * 0x100 + read_byte(f);
1266 if (len >= bufsize) {
1267 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1273 readfd(f, buf, len);
1278 /* Populate a sum_struct with values from the socket. This is
1279 * called by both the sender and the receiver. */
1280 void read_sum_head(int f, struct sum_struct *sum)
1282 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
1283 sum->count = read_int(f);
1284 if (sum->count < 0) {
1285 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1286 (long)sum->count, who_am_i());
1287 exit_cleanup(RERR_PROTOCOL);
1289 sum->blength = read_int(f);
1290 if (sum->blength < 0 || sum->blength > max_blength) {
1291 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1292 (long)sum->blength, who_am_i());
1293 exit_cleanup(RERR_PROTOCOL);
1295 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1296 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1297 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1298 sum->s2length, who_am_i());
1299 exit_cleanup(RERR_PROTOCOL);
1301 sum->remainder = read_int(f);
1302 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1303 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1304 (long)sum->remainder, who_am_i());
1305 exit_cleanup(RERR_PROTOCOL);
1309 /* Send the values from a sum_struct over the socket. Set sum to
1310 * NULL if there are no checksums to send. This is called by both
1311 * the generator and the sender. */
1312 void write_sum_head(int f, struct sum_struct *sum)
1314 static struct sum_struct null_sum;
1319 write_int(f, sum->count);
1320 write_int(f, sum->blength);
1321 if (protocol_version >= 27)
1322 write_int(f, sum->s2length);
1323 write_int(f, sum->remainder);
1327 * Sleep after writing to limit I/O bandwidth usage.
1329 * @todo Rather than sleeping after each write, it might be better to
1330 * use some kind of averaging. The current algorithm seems to always
1331 * use a bit less bandwidth than specified, because it doesn't make up
1332 * for slow periods. But arguably this is a feature. In addition, we
1333 * ought to take the time used to write the data into account.
1335 * During some phases of big transfers (file FOO is uptodate) this is
1336 * called with a small bytes_written every time. As the kernel has to
1337 * round small waits up to guarantee that we actually wait at least the
1338 * requested number of microseconds, this can become grossly inaccurate.
1339 * We therefore keep track of the bytes we've written over time and only
1340 * sleep when the accumulated delay is at least 1 tenth of a second.
1342 static void sleep_for_bwlimit(int bytes_written)
1344 static struct timeval prior_tv;
1345 static long total_written = 0;
1346 struct timeval tv, start_tv;
1347 long elapsed_usec, sleep_usec;
1349 #define ONE_SEC 1000000L /* # of microseconds in a second */
1351 if (!bwlimit_writemax)
1354 total_written += bytes_written;
1356 gettimeofday(&start_tv, NULL);
1357 if (prior_tv.tv_sec) {
1358 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1359 + (start_tv.tv_usec - prior_tv.tv_usec);
1360 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1361 if (total_written < 0)
1365 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1366 if (sleep_usec < ONE_SEC / 10) {
1367 prior_tv = start_tv;
1371 tv.tv_sec = sleep_usec / ONE_SEC;
1372 tv.tv_usec = sleep_usec % ONE_SEC;
1373 select(0, NULL, NULL, NULL, &tv);
1375 gettimeofday(&prior_tv, NULL);
1376 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1377 + (prior_tv.tv_usec - start_tv.tv_usec);
1378 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1381 static const char *what_fd_is(int fd)
1383 static char buf[20];
1385 if (fd == sock_f_out)
1387 else if (fd == msg_fd_out)
1388 return "message fd";
1389 else if (fd == batch_fd)
1390 return "batch file";
1392 snprintf(buf, sizeof buf, "fd %d", fd);
1397 /* Write len bytes to the file descriptor fd, looping as necessary to get
1398 * the job done and also (in certain circumstances) reading any data on
1399 * msg_fd_in to avoid deadlock.
1401 * This function underlies the multiplexing system. The body of the
1402 * application never calls this function directly. */
1403 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1405 size_t n, total = 0;
1406 fd_set w_fds, r_fds, e_fds;
1407 int maxfd, count, cnt, using_r_fds;
1412 defer_forwarding_messages++, defer_inc++;
1414 while (total < len) {
1421 if (msg_fd_in >= 0 && iobuf_in_remaining == 0) {
1423 FD_SET(msg_fd_in, &r_fds);
1424 if (msg_fd_in > maxfd)
1430 tv.tv_sec = select_timeout;
1434 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1435 &w_fds, &e_fds, &tv);
1438 if (count < 0 && errno == EBADF)
1439 exit_cleanup(RERR_SOCKETIO);
1444 /*if (FD_ISSET(fd, &e_fds))
1445 rprintf(FINFO, "select exception on fd %d\n", fd); */
1447 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1448 read_a_msg(msg_fd_in);
1450 if (!FD_ISSET(fd, &w_fds))
1454 if (bwlimit_writemax && n > bwlimit_writemax)
1455 n = bwlimit_writemax;
1456 cnt = write(fd, buf + total, n);
1462 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1468 /* Don't try to write errors back across the stream. */
1469 if (fd == sock_f_out)
1470 io_multiplexing_out = 0;
1471 /* Don't try to write errors down a failing msg pipe. */
1472 if (am_server && fd == msg_fd_out)
1473 exit_cleanup(RERR_STREAMIO);
1474 rsyserr(FERROR, errno,
1475 "writefd_unbuffered failed to write %ld bytes to %s [%s]",
1476 (long)len, what_fd_is(fd), who_am_i());
1477 /* If the other side is sending us error messages, try
1478 * to grab any messages they sent before they died. */
1479 while (!am_server && fd == sock_f_out && io_multiplexing_in) {
1483 readfd_unbuffered(iobuf_f_in, buf, sizeof buf);
1485 exit_cleanup(RERR_STREAMIO);
1489 defer_forwarding_messages++, defer_inc++;
1491 if (fd == sock_f_out) {
1492 if (io_timeout || am_generator)
1493 last_io_out = time(NULL);
1494 sleep_for_bwlimit(cnt);
1499 if (keep_defer_forwarding)
1501 if (!(defer_forwarding_messages -= defer_inc) && !no_flush)
1505 int io_flush(int flush_it_all)
1507 int flushed_something = 0;
1512 if (iobuf_out_cnt) {
1513 if (io_multiplexing_out)
1514 mplex_write(iobuf_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1516 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1518 flushed_something = 1;
1521 if (flush_it_all && !defer_forwarding_messages && msg_queue.head) {
1523 flushed_something = 1;
1526 return flushed_something;
1529 static void writefd(int fd, const char *buf, size_t len)
1531 if (fd == sock_f_out)
1532 stats.total_written += len;
1534 if (fd == write_batch_monitor_out)
1535 writefd_unbuffered(batch_fd, buf, len);
1537 if (!iobuf_out || fd != iobuf_f_out) {
1538 writefd_unbuffered(fd, buf, len);
1543 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1545 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1551 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1552 io_flush(NORMAL_FLUSH);
1556 void write_shortint(int f, unsigned short x)
1560 b[1] = (char)(x >> 8);
1564 void write_int(int f, int32 x)
1571 void write_varint(int f, int32 x)
1579 while (cnt > 1 && b[cnt] == 0)
1581 bit = ((uchar)1<<(7-cnt+1));
1582 if (CVAL(b, cnt) >= bit) {
1586 *b = b[cnt] | ~(bit*2-1);
1593 void write_varlong(int f, int64 x, uchar min_bytes)
1600 #if SIZEOF_INT64 >= 8
1601 SIVAL(b, 5, x >> 32);
1603 if (x <= 0x7FFFFFFF && x >= 0)
1604 memset(b + 5, 0, 4);
1606 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1607 exit_cleanup(RERR_UNSUPPORTED);
1611 while (cnt > min_bytes && b[cnt] == 0)
1613 bit = ((uchar)1<<(7-cnt+min_bytes));
1614 if (CVAL(b, cnt) >= bit) {
1617 } else if (cnt > min_bytes)
1618 *b = b[cnt] | ~(bit*2-1);
1626 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1627 * 64-bit types on this platform.
1629 void write_longint(int f, int64 x)
1631 char b[12], * const s = b+4;
1634 if (x <= 0x7FFFFFFF && x >= 0) {
1639 #if SIZEOF_INT64 < 8
1640 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1641 exit_cleanup(RERR_UNSUPPORTED);
1644 SIVAL(s, 4, x >> 32);
1649 void write_buf(int f, const char *buf, size_t len)
1654 /** Write a string to the connection */
1655 void write_sbuf(int f, const char *buf)
1657 writefd(f, buf, strlen(buf));
1660 void write_byte(int f, uchar c)
1662 writefd(f, (char *)&c, 1);
1665 void write_vstring(int f, const char *str, int len)
1667 uchar lenbuf[3], *lb = lenbuf;
1672 "attempting to send over-long vstring (%d > %d)\n",
1674 exit_cleanup(RERR_PROTOCOL);
1676 *lb++ = len / 0x100 + 0x80;
1680 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1682 writefd(f, str, len);
1685 /* Send a file-list index using a byte-reduction method. */
1686 void write_ndx(int f, int32 ndx)
1688 static int32 prev_positive = -1, prev_negative = 1;
1689 int32 diff, cnt = 0;
1692 if (protocol_version < 30 || read_batch) {
1697 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1698 * negative nums as a positive after sending a leading 0xFF. */
1700 diff = ndx - prev_positive;
1701 prev_positive = ndx;
1702 } else if (ndx == NDX_DONE) {
1707 b[cnt++] = (char)0xFF;
1709 diff = ndx - prev_negative;
1710 prev_negative = ndx;
1713 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1714 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1715 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1716 if (diff < 0xFE && diff > 0)
1717 b[cnt++] = (char)diff;
1718 else if (diff < 0 || diff > 0x7FFF) {
1719 b[cnt++] = (char)0xFE;
1720 b[cnt++] = (char)((ndx >> 24) | 0x80);
1721 b[cnt++] = (char)ndx;
1722 b[cnt++] = (char)(ndx >> 8);
1723 b[cnt++] = (char)(ndx >> 16);
1725 b[cnt++] = (char)0xFE;
1726 b[cnt++] = (char)(diff >> 8);
1727 b[cnt++] = (char)diff;
1732 /* Receive a file-list index using a byte-reduction method. */
1733 int32 read_ndx(int f)
1735 static int32 prev_positive = -1, prev_negative = 1;
1736 int32 *prev_ptr, num;
1739 if (protocol_version < 30)
1743 if (CVAL(b, 0) == 0xFF) {
1745 prev_ptr = &prev_negative;
1746 } else if (CVAL(b, 0) == 0)
1749 prev_ptr = &prev_positive;
1750 if (CVAL(b, 0) == 0xFE) {
1752 if (CVAL(b, 0) & 0x80) {
1753 b[3] = CVAL(b, 0) & ~0x80;
1758 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1760 num = UVAL(b, 0) + *prev_ptr;
1762 if (prev_ptr == &prev_negative)
1767 /* Read a line of up to bufsiz-1 characters into buf. Strips
1768 * the (required) trailing newline and all carriage returns.
1769 * Returns 1 for success; 0 for I/O error or truncation. */
1770 int read_line_old(int f, char *buf, size_t bufsiz)
1772 bufsiz--; /* leave room for the null */
1773 while (bufsiz > 0) {
1775 read_buf(f, buf, 1);
1780 if (buf[0] != '\r') {
1789 void io_printf(int fd, const char *format, ...)
1792 char buf[BIGPATHBUFLEN];
1795 va_start(ap, format);
1796 len = vsnprintf(buf, sizeof buf, format, ap);
1800 exit_cleanup(RERR_STREAMIO);
1802 if (len > (int)sizeof buf) {
1803 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1804 exit_cleanup(RERR_STREAMIO);
1807 write_sbuf(fd, buf);
1810 /** Setup for multiplexing a MSG_* stream with the data stream. */
1811 void io_start_multiplex_out(int f)
1813 io_flush(NORMAL_FLUSH);
1814 io_start_buffering_out(f);
1815 io_multiplexing_out = 1;
1818 /** Setup for multiplexing a MSG_* stream with the data stream. */
1819 void io_start_multiplex_in(int f)
1821 io_flush(NORMAL_FLUSH);
1822 io_start_buffering_in(f);
1823 io_multiplexing_in = 1;
1826 /** Write an message to the multiplexed data stream. */
1827 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1829 if (!io_multiplexing_out)
1831 io_flush(NORMAL_FLUSH);
1832 stats.total_written += (len+4);
1833 mplex_write(iobuf_f_out, code, buf, len, convert);
1837 void io_end_multiplex_in(void)
1839 io_multiplexing_in = 0;
1840 io_end_buffering_in();
1843 /** Stop output multiplexing. */
1844 void io_end_multiplex_out(void)
1846 io_multiplexing_out = 0;
1847 io_end_buffering_out();
1850 void start_write_batch(int fd)
1852 /* Some communication has already taken place, but we don't
1853 * enable batch writing until here so that we can write a
1854 * canonical record of the communication even though the
1855 * actual communication so far depends on whether a daemon
1857 write_int(batch_fd, protocol_version);
1858 if (protocol_version >= 30)
1859 write_byte(batch_fd, inc_recurse);
1860 write_int(batch_fd, checksum_seed);
1863 write_batch_monitor_out = fd;
1865 write_batch_monitor_in = fd;
1868 void stop_write_batch(void)
1870 write_batch_monitor_out = -1;
1871 write_batch_monitor_in = -1;