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 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(). */
32 /** If no timeout is specified then use a 60 second select timeout */
33 #define SELECT_TIMEOUT 60
36 extern size_t bwlimit_writemax;
37 extern int io_timeout;
38 extern int allowed_lull;
42 extern int am_generator;
43 extern int inc_recurse;
47 extern int read_batch;
48 extern int csum_length;
49 extern int checksum_seed;
50 extern int protocol_version;
51 extern int remove_source_files;
52 extern int preserve_hard_links;
53 extern char *filesfrom_host;
54 extern struct stats stats;
55 extern struct file_list *cur_flist, *first_flist;
57 extern iconv_t ic_send, ic_recv;
60 const char phase_unknown[] = "unknown";
61 int ignore_timeout = 0;
65 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
66 int kluge_around_eof = 0;
73 static int iobuf_f_in = -1;
74 static char *iobuf_in;
75 static size_t iobuf_in_siz;
76 static size_t iobuf_in_ndx;
77 static size_t iobuf_in_remaining;
79 static int iobuf_f_out = -1;
80 static char *iobuf_out;
81 static int iobuf_out_cnt;
83 int flist_forward_from = -1;
85 static int io_multiplexing_out;
86 static int io_multiplexing_in;
87 static time_t last_io_in;
88 static time_t last_io_out;
91 static int write_batch_monitor_in = -1;
92 static int write_batch_monitor_out = -1;
94 static int io_filesfrom_f_in = -1;
95 static int io_filesfrom_f_out = -1;
96 static char io_filesfrom_buf[2048];
98 static char iconv_buf[sizeof io_filesfrom_buf / 2];
100 static char *io_filesfrom_bp;
101 static char io_filesfrom_lastchar;
102 static int io_filesfrom_buflen;
103 static int defer_forwarding_messages = 0;
104 static int select_timeout = SELECT_TIMEOUT;
105 static int active_filecnt = 0;
106 static OFF_T active_bytecnt = 0;
108 static char int_byte_extra[64] = {
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (00 - 3F)/4 */
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* (40 - 7F)/4 */
111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* (80 - BF)/4 */
112 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, /* (C0 - FF)/4 */
115 enum festatus { FES_SUCCESS, FES_REDO, FES_NO_SEND };
117 static void readfd(int fd, char *buffer, size_t N);
118 static void writefd(int fd, const char *buf, size_t len);
119 static void writefd_unbuffered(int fd, const char *buf, size_t len);
120 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert);
122 struct flist_ndx_item {
123 struct flist_ndx_item *next;
127 struct flist_ndx_list {
128 struct flist_ndx_item *head, *tail;
131 static struct flist_ndx_list redo_list, hlink_list;
133 struct msg_list_item {
134 struct msg_list_item *next;
140 struct msg_list_item *head, *tail;
143 static struct msg_list msg_queue;
145 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
147 struct flist_ndx_item *item;
149 if (!(item = new(struct flist_ndx_item)))
150 out_of_memory("flist_ndx_push");
154 lp->tail->next = item;
160 static int flist_ndx_pop(struct flist_ndx_list *lp)
162 struct flist_ndx_item *next;
169 next = lp->head->next;
178 static void got_flist_entry_status(enum festatus status, const char *buf)
180 int ndx = IVAL(buf, 0);
181 struct file_list *flist = flist_for_ndx(ndx);
183 assert(flist != NULL);
184 assert(ndx >= flist->ndx_start);
186 if (remove_source_files) {
188 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
192 flist->in_progress--;
196 if (remove_source_files)
197 send_msg(MSG_SUCCESS, buf, 4, 0);
198 if (preserve_hard_links) {
199 struct file_struct *file = flist->files[ndx - flist->ndx_start];
200 if (F_IS_HLINKED(file))
201 flist_ndx_push(&hlink_list, ndx);
207 flist_ndx_push(&redo_list, ndx);
214 static void check_timeout(void)
218 if (!io_timeout || ignore_timeout)
222 last_io_in = time(NULL);
228 if (t - last_io_in >= io_timeout) {
229 if (!am_server && !am_daemon) {
230 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
231 (int)(t-last_io_in));
233 exit_cleanup(RERR_TIMEOUT);
237 /* Note the fds used for the main socket (which might really be a pipe
238 * for a local transfer, but we can ignore that). */
239 void io_set_sock_fds(int f_in, int f_out)
245 void set_io_timeout(int secs)
249 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
250 select_timeout = SELECT_TIMEOUT;
252 select_timeout = io_timeout;
254 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
257 /* Setup the fd used to receive MSG_* messages. Only needed during the
258 * early stages of being a local sender (up through the sending of the
259 * file list) or when we're the generator (to fetch the messages from
261 void set_msg_fd_in(int fd)
266 /* Setup the fd used to send our MSG_* messages. Only needed when
267 * we're the receiver (to send our messages to the generator). */
268 void set_msg_fd_out(int fd)
271 set_nonblocking(msg_fd_out);
274 /* Add a message to the pending MSG_* list. */
275 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len, int convert)
277 struct msg_list_item *m;
278 int sz = len + 4 + sizeof m[0] - 1;
280 if (!(m = (struct msg_list_item *)new_array(char, sz)))
281 out_of_memory("msg_list_add");
283 m->convert = convert;
284 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
285 memcpy(m->buf + 4, buf, len);
293 static void msg_flush(void)
296 while (msg_queue.head && io_multiplexing_out) {
297 struct msg_list_item *m = msg_queue.head;
298 int len = IVAL(m->buf, 0) & 0xFFFFFF;
299 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
300 if (!(msg_queue.head = m->next))
301 msg_queue.tail = NULL;
302 stats.total_written += len + 4;
303 defer_forwarding_messages++;
304 mplex_write(sock_f_out, tag, m->buf + 4, len, m->convert);
305 defer_forwarding_messages--;
309 while (msg_queue.head) {
310 struct msg_list_item *m = msg_queue.head;
311 int len = IVAL(m->buf, 0) & 0xFFFFFF;
312 int tag = *((uchar*)m->buf+3) - MPLEX_BASE;
313 if (!(msg_queue.head = m->next))
314 msg_queue.tail = NULL;
315 defer_forwarding_messages++;
316 mplex_write(msg_fd_out, tag, m->buf + 4, len, m->convert);
317 defer_forwarding_messages--;
323 /* Read a message from the MSG_* fd and handle it. This is called either
324 * during the early stages of being a local sender (up through the sending
325 * of the file list) or when we're the generator (to fetch the messages
326 * from the receiver). */
327 static void read_msg_fd(void)
331 struct file_list *flist;
335 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
336 * to this routine from writefd_unbuffered(). */
339 defer_forwarding_messages++;
344 len = tag & 0xFFFFFF;
345 tag = (tag >> 24) - MPLEX_BASE;
349 if (len < 0 || len > 1 || !am_generator) {
351 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
352 tag, len, who_am_i(),
353 inc_recurse ? "/inc" : "");
354 exit_cleanup(RERR_STREAMIO);
357 readfd(fd, buf, len);
358 stats.total_read = read_varlong(fd, 3);
363 if (len != 4 || !am_generator)
366 got_flist_entry_status(FES_REDO, buf);
369 if (len != 4 || !am_generator || !inc_recurse)
372 /* Read extra file list from receiver. */
373 assert(iobuf_in != NULL);
374 assert(iobuf_f_in == fd);
376 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
377 who_am_i(), IVAL(buf,0));
379 flist = recv_file_list(fd);
380 flist->parent_ndx = IVAL(buf,0);
383 if (len != 0 || !am_generator || !inc_recurse)
388 if (len >= (int)sizeof buf || !am_generator)
390 readfd(fd, buf, len);
391 send_msg(MSG_DELETED, buf, len, 1);
394 if (len != 4 || !am_generator)
397 got_flist_entry_status(FES_SUCCESS, buf);
400 if (len != 4 || !am_generator)
403 got_flist_entry_status(FES_NO_SEND, buf);
409 if (tag == MSG_SOCKERR)
410 io_end_multiplex_out();
420 rwrite((enum logcode)tag, buf, n, !am_generator);
425 rprintf(FERROR, "unknown message %d:%d [%s]\n",
426 tag, len, who_am_i());
427 exit_cleanup(RERR_STREAMIO);
432 if (!--defer_forwarding_messages)
436 /* This is used by the generator to limit how many file transfers can
437 * be active at once when --remove-source-files is specified. Without
438 * this, sender-side deletions were mostly happening at the end. */
439 void increment_active_files(int ndx, int itemizing, enum logcode code)
441 /* TODO: tune these limits? */
442 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
443 check_for_finished_files(itemizing, code, 0);
445 io_flush(NORMAL_FLUSH);
451 active_bytecnt += F_LENGTH(cur_flist->files[ndx - cur_flist->ndx_start]);
454 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
455 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len, int convert)
457 char buffer[BIGPATHBUFLEN]; /* Oversized for use by iconv code. */
460 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
463 if (convert && ic_send == (iconv_t)-1)
467 if (convert || n > 1024 - 4) /* BIGPATHBUFLEN can handle 1024 bytes */
470 memcpy(buffer + 4, buf, n);
472 writefd_unbuffered(fd, buffer, n+4);
479 iconv(ic_send, NULL, 0, NULL, 0);
480 defer_forwarding_messages++;
482 ICONV_CONST char *ibuf = (ICONV_CONST char *)buf;
484 size_t ocnt = sizeof buffer;
485 while (len && iconv(ic_send, &ibuf,&len,
486 &obuf,&ocnt) == (size_t)-1) {
487 if (errno == E2BIG || !ocnt)
493 writefd_unbuffered(fd, buffer, n);
495 if (!--defer_forwarding_messages)
500 defer_forwarding_messages++;
501 writefd_unbuffered(fd, buf, len);
502 if (!--defer_forwarding_messages)
507 int send_msg(enum msgcode code, const char *buf, int len, int convert)
509 if (msg_fd_out < 0) {
510 if (!defer_forwarding_messages)
511 return io_multiplex_write(code, buf, len, convert);
512 if (!io_multiplexing_out)
514 msg_list_add(&msg_queue, code, buf, len, convert);
517 if (flist_forward_from >= 0)
518 msg_list_add(&msg_queue, code, buf, len, convert);
520 mplex_write(msg_fd_out, code, buf, len, convert);
524 void send_msg_int(enum msgcode code, int num)
527 SIVAL(numbuf, 0, num);
528 send_msg(code, numbuf, 4, 0);
531 void wait_for_receiver(void)
534 io_flush(NORMAL_FLUSH);
539 int get_redo_num(void)
541 return flist_ndx_pop(&redo_list);
544 int get_hlink_num(void)
546 return flist_ndx_pop(&hlink_list);
550 * When we're the receiver and we have a local --files-from list of names
551 * that needs to be sent over the socket to the sender, we have to do two
552 * things at the same time: send the sender a list of what files we're
553 * processing and read the incoming file+info list from the sender. We do
554 * this by augmenting the read_timeout() function to copy this data. It
555 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
556 * ready, since it might be a pipe) and then blast it out f_out (when it
557 * is ready to receive more data).
559 void io_set_filesfrom_fds(int f_in, int f_out)
561 io_filesfrom_f_in = f_in;
562 io_filesfrom_f_out = f_out;
563 io_filesfrom_bp = io_filesfrom_buf;
564 io_filesfrom_lastchar = '\0';
565 io_filesfrom_buflen = 0;
568 /* It's almost always an error to get an EOF when we're trying to read from the
569 * network, because the protocol is (for the most part) self-terminating.
571 * There is one case for the receiver when it is at the end of the transfer
572 * (hanging around reading any keep-alive packets that might come its way): if
573 * the sender dies before the generator's kill-signal comes through, we can end
574 * up here needing to loop until the kill-signal arrives. In this situation,
575 * kluge_around_eof will be < 0.
577 * There is another case for older protocol versions (< 24) where the module
578 * listing was not terminated, so we must ignore an EOF error in that case and
579 * exit. In this situation, kluge_around_eof will be > 0. */
580 static void whine_about_eof(int fd)
582 if (kluge_around_eof && fd == sock_f_in) {
584 if (kluge_around_eof > 0)
586 /* If we're still here after 10 seconds, exit with an error. */
587 for (i = 10*1000/20; i--; )
591 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
592 "(%.0f bytes received so far) [%s]\n",
593 (double)stats.total_read, who_am_i());
595 exit_cleanup(RERR_STREAMIO);
599 * Read from a socket with I/O timeout. return the number of bytes
600 * read. If no bytes can be read then exit, never return a number <= 0.
602 * TODO: If the remote shell connection fails, then current versions
603 * actually report an "unexpected EOF" error here. Since it's a
604 * fairly common mistake to try to use rsh when ssh is required, we
605 * should trap that: if we fail to read any data at all, we should
606 * give a better explanation. We can tell whether the connection has
607 * started by looking e.g. at whether the remote version is known yet.
609 static int read_timeout(int fd, char *buf, size_t len)
613 io_flush(FULL_FLUSH);
616 /* until we manage to read *something* */
625 if (io_filesfrom_f_out >= 0) {
627 if (io_filesfrom_buflen == 0) {
628 if (io_filesfrom_f_in >= 0) {
629 FD_SET(io_filesfrom_f_in, &r_fds);
630 new_fd = io_filesfrom_f_in;
632 io_filesfrom_f_out = -1;
636 FD_SET(io_filesfrom_f_out, &w_fds);
637 new_fd = io_filesfrom_f_out;
643 tv.tv_sec = select_timeout;
648 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
651 if (errno == EBADF) {
652 defer_forwarding_messages = 0;
653 exit_cleanup(RERR_SOCKETIO);
659 if (io_filesfrom_f_out >= 0) {
660 if (io_filesfrom_buflen) {
661 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
662 int l = write(io_filesfrom_f_out,
664 io_filesfrom_buflen);
666 if (!(io_filesfrom_buflen -= l))
667 io_filesfrom_bp = io_filesfrom_buf;
669 io_filesfrom_bp += l;
670 } else if (errno != EINTR) {
671 /* XXX should we complain? */
672 io_filesfrom_f_out = -1;
675 } else if (io_filesfrom_f_in >= 0) {
676 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
677 int l = read(io_filesfrom_f_in,
679 sizeof io_filesfrom_buf);
681 if (l == 0 || errno != EINTR) {
682 /* Send end-of-file marker */
683 io_filesfrom_buf[0] = '\0';
684 io_filesfrom_buf[1] = '\0';
685 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
686 io_filesfrom_f_in = -1;
690 char *s = io_filesfrom_buf + l;
691 /* Transform CR and/or LF into '\0' */
692 while (s-- > io_filesfrom_buf) {
693 if (*s == '\n' || *s == '\r')
697 if (!io_filesfrom_lastchar) {
698 /* Last buf ended with a '\0', so don't
699 * let this buf start with one. */
700 while (l && !*io_filesfrom_bp)
701 io_filesfrom_bp++, l--;
704 io_filesfrom_bp = io_filesfrom_buf;
706 char *f = io_filesfrom_bp;
709 /* Eliminate any multi-'\0' runs. */
711 if (!(*t++ = *f++)) {
712 while (f != eob && !*f)
716 io_filesfrom_lastchar = f[-1];
718 io_filesfrom_buflen = l;
724 if (!FD_ISSET(fd, &r_fds))
727 n = read(fd, buf, len);
731 whine_about_eof(fd); /* Doesn't return. */
732 if (errno == EINTR || errno == EWOULDBLOCK
736 /* Don't write errors on a dead socket. */
737 if (fd == sock_f_in) {
738 io_end_multiplex_out();
739 rsyserr(FSOCKERR, errno, "read error");
741 rsyserr(FERROR, errno, "read error");
742 exit_cleanup(RERR_STREAMIO);
749 if (fd == sock_f_in && io_timeout)
750 last_io_in = time(NULL);
756 /* Read a line into the "fname" buffer (which must be at least MAXPATHLEN
757 * characters long). */
758 int read_filesfrom_line(int fd, char *fname)
760 char ch, *s, *eob = fname + MAXPATHLEN - 1;
762 int reading_remotely = filesfrom_host != NULL;
763 int nulls = eol_nulls || reading_remotely;
768 cnt = read(fd, &ch, 1);
769 if (cnt < 0 && (errno == EWOULDBLOCK
770 || errno == EINTR || errno == EAGAIN)) {
777 tv.tv_sec = select_timeout;
779 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
781 if (FD_ISSET(fd, &e_fds)) {
782 rsyserr(FINFO, errno,
783 "select exception on fd %d", fd);
789 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
790 /* Skip empty lines if reading locally. */
791 if (!reading_remotely && s == fname)
801 if (*fname == '#' || *fname == ';')
807 int io_start_buffering_out(int f_out)
810 assert(f_out == iobuf_f_out);
813 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
814 out_of_memory("io_start_buffering_out");
820 int io_start_buffering_in(int f_in)
823 assert(f_in == iobuf_f_in);
826 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
827 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
828 out_of_memory("io_start_buffering_in");
833 void io_end_buffering_in(void)
840 iobuf_in_remaining = 0;
844 void io_end_buffering_out(void)
848 io_flush(FULL_FLUSH);
854 void maybe_flush_socket(int important)
856 if (iobuf_out && iobuf_out_cnt
857 && (important || time(NULL) - last_io_out >= 5))
858 io_flush(NORMAL_FLUSH);
861 void maybe_send_keepalive(void)
863 if (time(NULL) - last_io_out >= allowed_lull) {
864 if (!iobuf_out || !iobuf_out_cnt) {
865 if (protocol_version < 29)
866 return; /* there's nothing we can do */
867 if (protocol_version >= 30)
868 send_msg(MSG_NOOP, "", 0, 0);
870 write_int(sock_f_out, cur_flist->used);
871 write_shortint(sock_f_out, ITEM_IS_NEW);
875 io_flush(NORMAL_FLUSH);
879 void start_flist_forward(int f_in)
881 assert(iobuf_out != NULL);
882 assert(iobuf_f_out == msg_fd_out);
883 flist_forward_from = f_in;
886 void stop_flist_forward()
888 flist_forward_from = -1;
889 io_flush(FULL_FLUSH);
893 * Continue trying to read len bytes - don't return until len has been
896 static void read_loop(int fd, char *buf, size_t len)
899 int n = read_timeout(fd, buf, len);
907 * Read from the file descriptor handling multiplexing - return number
910 * Never returns <= 0.
912 static int readfd_unbuffered(int fd, char *buf, size_t len)
916 char line[BIGPATHBUFLEN];
918 if (!iobuf_in || fd != iobuf_f_in)
919 return read_timeout(fd, buf, len);
921 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
922 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
927 if (iobuf_in_remaining) {
928 len = MIN(len, iobuf_in_remaining);
929 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
931 iobuf_in_remaining -= len;
936 read_loop(fd, line, 4);
939 msg_bytes = tag & 0xFFFFFF;
940 tag = (tag >> 24) - MPLEX_BASE;
944 if (msg_bytes > iobuf_in_siz) {
945 if (!(iobuf_in = realloc_array(iobuf_in, char,
947 out_of_memory("readfd_unbuffered");
948 iobuf_in_siz = msg_bytes;
950 read_loop(fd, iobuf_in, msg_bytes);
951 iobuf_in_remaining = msg_bytes;
956 maybe_send_keepalive();
961 read_loop(fd, line, msg_bytes);
962 io_error |= IVAL(line, 0);
965 if (msg_bytes >= sizeof line)
968 if (ic_recv != (iconv_t)-1) {
969 ICONV_CONST char *ibuf;
971 size_t icnt, ocnt = sizeof line - 1;
973 iconv(ic_send, NULL, 0, NULL, 0);
975 icnt = msg_bytes > sizeof iconv_buf
976 ? sizeof iconv_buf : msg_bytes;
977 read_loop(fd, iconv_buf, icnt);
978 if (!(msg_bytes -= icnt) && !iconv_buf[icnt-1])
979 icnt--, add_null = 1;
980 ibuf = (ICONV_CONST char *)iconv_buf;
981 if (iconv(ic_send, &ibuf,&icnt,
982 &obuf,&ocnt) == (size_t)-1)
983 goto overflow; // XXX
987 msg_bytes = obuf - line;
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:%ld [%s]\n",
1003 tag, (long)msg_bytes, who_am_i());
1004 exit_cleanup(RERR_STREAMIO);
1006 read_loop(fd, line, msg_bytes);
1007 successful_send(IVAL(line, 0));
1012 read_loop(fd, line, msg_bytes);
1013 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
1017 if (msg_bytes >= sizeof line) {
1020 "multiplexing overflow %d:%ld [%s]\n",
1021 tag, (long)msg_bytes, who_am_i());
1022 exit_cleanup(RERR_STREAMIO);
1024 read_loop(fd, line, msg_bytes);
1025 rwrite((enum logcode)tag, line, msg_bytes, 1);
1028 rprintf(FERROR, "unexpected tag %d [%s]\n",
1030 exit_cleanup(RERR_STREAMIO);
1034 if (iobuf_in_remaining == 0)
1035 io_flush(NORMAL_FLUSH);
1040 /* Do a buffered read from fd. Don't return until all N bytes have
1041 * been read. If all N can't be read then exit with an error. */
1042 static void readfd(int fd, char *buffer, size_t N)
1048 cnt = readfd_unbuffered(fd, buffer + total, N-total);
1052 if (fd == write_batch_monitor_in) {
1053 if ((size_t)write(batch_fd, buffer, total) != total)
1054 exit_cleanup(RERR_FILEIO);
1057 if (fd == flist_forward_from)
1058 writefd(iobuf_f_out, buffer, total);
1060 if (fd == sock_f_in)
1061 stats.total_read += total;
1064 unsigned short read_shortint(int f)
1068 return (UVAL(b, 1) << 8) + UVAL(b, 0);
1071 int32 read_int(int f)
1078 #if SIZEOF_INT32 > 4
1079 if (num & (int32)0x80000000)
1080 num |= ~(int32)0xffffffff;
1085 int32 read_varint(int f)
1095 readfd(f, (char*)&ch, 1);
1096 extra = int_byte_extra[ch / 4];
1098 uchar bit = ((uchar)1<<(8-extra));
1099 if (extra >= (int)sizeof u.b) {
1100 rprintf(FERROR, "Overflow in read_varint()\n");
1101 exit_cleanup(RERR_STREAMIO);
1103 readfd(f, u.b, extra);
1104 u.b[extra] = ch & (bit-1);
1107 #if CAREFUL_ALIGNMENT
1110 #if SIZEOF_INT32 > 4
1111 if (u.x & (int32)0x80000000)
1112 u.x |= ~(int32)0xffffffff;
1117 int64 read_varlong(int f, uchar min_bytes)
1126 #if SIZEOF_INT64 < 8
1131 readfd(f, b2, min_bytes);
1132 memcpy(u.b, b2+1, min_bytes-1);
1133 extra = int_byte_extra[CVAL(b2, 0) / 4];
1135 uchar bit = ((uchar)1<<(8-extra));
1136 if (min_bytes + extra > (int)sizeof u.b) {
1137 rprintf(FERROR, "Overflow in read_varlong()\n");
1138 exit_cleanup(RERR_STREAMIO);
1140 readfd(f, u.b + min_bytes - 1, extra);
1141 u.b[min_bytes + extra - 1] = CVAL(b2, 0) & (bit-1);
1142 #if SIZEOF_INT64 < 8
1143 if (min_bytes + extra > 5 || u.b[4] || CVAL(u.b,3) & 0x80) {
1144 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1145 exit_cleanup(RERR_UNSUPPORTED);
1149 u.b[min_bytes + extra - 1] = CVAL(b2, 0);
1150 #if SIZEOF_INT64 < 8
1152 #elif CAREFUL_ALIGNMENT
1153 u.x = IVAL(u.b,0) | (((int64)IVAL(u.b,4))<<32);
1158 int64 read_longint(int f)
1160 #if SIZEOF_INT64 >= 8
1163 int32 num = read_int(f);
1165 if (num != (int32)0xffffffff)
1168 #if SIZEOF_INT64 < 8
1169 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1170 exit_cleanup(RERR_UNSUPPORTED);
1173 return IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1177 void read_buf(int f, char *buf, size_t len)
1182 void read_sbuf(int f, char *buf, size_t len)
1184 readfd(f, buf, len);
1188 uchar read_byte(int f)
1191 readfd(f, (char *)&c, 1);
1195 int read_vstring(int f, char *buf, int bufsize)
1197 int len = read_byte(f);
1200 len = (len & ~0x80) * 0x100 + read_byte(f);
1202 if (len >= bufsize) {
1203 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1209 readfd(f, buf, len);
1214 /* Populate a sum_struct with values from the socket. This is
1215 * called by both the sender and the receiver. */
1216 void read_sum_head(int f, struct sum_struct *sum)
1218 sum->count = read_int(f);
1219 if (sum->count < 0) {
1220 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1221 (long)sum->count, who_am_i());
1222 exit_cleanup(RERR_PROTOCOL);
1224 sum->blength = read_int(f);
1225 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1226 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1227 (long)sum->blength, who_am_i());
1228 exit_cleanup(RERR_PROTOCOL);
1230 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1231 if (sum->s2length < 0 || sum->s2length > MAX_DIGEST_LEN) {
1232 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1233 sum->s2length, who_am_i());
1234 exit_cleanup(RERR_PROTOCOL);
1236 sum->remainder = read_int(f);
1237 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1238 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1239 (long)sum->remainder, who_am_i());
1240 exit_cleanup(RERR_PROTOCOL);
1244 /* Send the values from a sum_struct over the socket. Set sum to
1245 * NULL if there are no checksums to send. This is called by both
1246 * the generator and the sender. */
1247 void write_sum_head(int f, struct sum_struct *sum)
1249 static struct sum_struct null_sum;
1254 write_int(f, sum->count);
1255 write_int(f, sum->blength);
1256 if (protocol_version >= 27)
1257 write_int(f, sum->s2length);
1258 write_int(f, sum->remainder);
1262 * Sleep after writing to limit I/O bandwidth usage.
1264 * @todo Rather than sleeping after each write, it might be better to
1265 * use some kind of averaging. The current algorithm seems to always
1266 * use a bit less bandwidth than specified, because it doesn't make up
1267 * for slow periods. But arguably this is a feature. In addition, we
1268 * ought to take the time used to write the data into account.
1270 * During some phases of big transfers (file FOO is uptodate) this is
1271 * called with a small bytes_written every time. As the kernel has to
1272 * round small waits up to guarantee that we actually wait at least the
1273 * requested number of microseconds, this can become grossly inaccurate.
1274 * We therefore keep track of the bytes we've written over time and only
1275 * sleep when the accumulated delay is at least 1 tenth of a second.
1277 static void sleep_for_bwlimit(int bytes_written)
1279 static struct timeval prior_tv;
1280 static long total_written = 0;
1281 struct timeval tv, start_tv;
1282 long elapsed_usec, sleep_usec;
1284 #define ONE_SEC 1000000L /* # of microseconds in a second */
1286 if (!bwlimit_writemax)
1289 total_written += bytes_written;
1291 gettimeofday(&start_tv, NULL);
1292 if (prior_tv.tv_sec) {
1293 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1294 + (start_tv.tv_usec - prior_tv.tv_usec);
1295 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1296 if (total_written < 0)
1300 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1301 if (sleep_usec < ONE_SEC / 10) {
1302 prior_tv = start_tv;
1306 tv.tv_sec = sleep_usec / ONE_SEC;
1307 tv.tv_usec = sleep_usec % ONE_SEC;
1308 select(0, NULL, NULL, NULL, &tv);
1310 gettimeofday(&prior_tv, NULL);
1311 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1312 + (prior_tv.tv_usec - start_tv.tv_usec);
1313 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1316 /* Write len bytes to the file descriptor fd, looping as necessary to get
1317 * the job done and also (in certain circumstances) reading any data on
1318 * msg_fd_in to avoid deadlock.
1320 * This function underlies the multiplexing system. The body of the
1321 * application never calls this function directly. */
1322 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1324 size_t n, total = 0;
1325 fd_set w_fds, r_fds, e_fds;
1326 int maxfd, count, cnt, using_r_fds;
1331 defer_forwarding_messages++, defer_inc++;
1333 while (total < len) {
1340 if (msg_fd_in >= 0) {
1342 FD_SET(msg_fd_in, &r_fds);
1343 if (msg_fd_in > maxfd)
1349 tv.tv_sec = select_timeout;
1353 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1354 &w_fds, &e_fds, &tv);
1357 if (count < 0 && errno == EBADF)
1358 exit_cleanup(RERR_SOCKETIO);
1363 if (FD_ISSET(fd, &e_fds)) {
1364 rsyserr(FINFO, errno,
1365 "select exception on fd %d", fd);
1368 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1371 if (!FD_ISSET(fd, &w_fds))
1375 if (bwlimit_writemax && n > bwlimit_writemax)
1376 n = bwlimit_writemax;
1377 cnt = write(fd, buf + total, n);
1383 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1389 /* Don't try to write errors back across the stream. */
1390 if (fd == sock_f_out)
1391 io_end_multiplex_out();
1392 /* Don't try to write errors down a failing msg pipe. */
1393 if (am_server && fd == msg_fd_out)
1394 exit_cleanup(RERR_STREAMIO);
1395 rsyserr(FERROR, errno,
1396 "writefd_unbuffered failed to write %ld bytes [%s]",
1397 (long)len, who_am_i());
1398 /* If the other side is sending us error messages, try
1399 * to grab any messages they sent before they died. */
1400 while (fd == sock_f_out && io_multiplexing_in) {
1403 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1404 sizeof io_filesfrom_buf);
1406 exit_cleanup(RERR_STREAMIO);
1410 defer_forwarding_messages++, defer_inc++;
1412 if (fd == sock_f_out) {
1413 if (io_timeout || am_generator)
1414 last_io_out = time(NULL);
1415 sleep_for_bwlimit(cnt);
1420 if (!(defer_forwarding_messages -= defer_inc))
1424 void io_flush(int flush_it_all)
1426 if (!iobuf_out_cnt || no_flush)
1429 if (io_multiplexing_out)
1430 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt, 0);
1432 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1435 if (flush_it_all && !defer_forwarding_messages)
1439 static void writefd(int fd, const char *buf, size_t len)
1441 if (fd == sock_f_out)
1442 stats.total_written += len;
1444 if (fd == write_batch_monitor_out) {
1445 if ((size_t)write(batch_fd, buf, len) != len)
1446 exit_cleanup(RERR_FILEIO);
1449 if (!iobuf_out || fd != iobuf_f_out) {
1450 writefd_unbuffered(fd, buf, len);
1455 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1457 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1463 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1464 io_flush(NORMAL_FLUSH);
1468 void write_shortint(int f, unsigned short x)
1472 b[1] = (char)(x >> 8);
1476 void write_int(int f, int32 x)
1483 void write_varint(int f, int32 x)
1491 while (cnt > 1 && b[cnt] == 0)
1493 bit = ((uchar)1<<(7-cnt+1));
1494 if (CVAL(b, cnt) >= bit) {
1498 *b = b[cnt] | ~(bit*2-1);
1505 void write_varlong(int f, int64 x, uchar min_bytes)
1512 #if SIZEOF_INT64 >= 8
1513 SIVAL(b, 5, x >> 32);
1515 if (x <= 0x7FFFFFFF && x >= 0)
1516 memset(b + 5, 0, 4);
1518 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1519 exit_cleanup(RERR_UNSUPPORTED);
1523 while (cnt > min_bytes && b[cnt] == 0)
1525 bit = ((uchar)1<<(7-cnt+min_bytes));
1526 if (CVAL(b, cnt) >= bit) {
1529 } else if (cnt > min_bytes)
1530 *b = b[cnt] | ~(bit*2-1);
1538 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1539 * 64-bit types on this platform.
1541 void write_longint(int f, int64 x)
1543 char b[12], * const s = b+4;
1546 if (x <= 0x7FFFFFFF && x >= 0) {
1551 #if SIZEOF_INT64 < 8
1552 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1553 exit_cleanup(RERR_UNSUPPORTED);
1556 SIVAL(s, 4, x >> 32);
1561 void write_buf(int f, const char *buf, size_t len)
1566 /** Write a string to the connection */
1567 void write_sbuf(int f, const char *buf)
1569 writefd(f, buf, strlen(buf));
1572 void write_byte(int f, uchar c)
1574 writefd(f, (char *)&c, 1);
1577 void write_vstring(int f, const char *str, int len)
1579 uchar lenbuf[3], *lb = lenbuf;
1584 "attempting to send over-long vstring (%d > %d)\n",
1586 exit_cleanup(RERR_PROTOCOL);
1588 *lb++ = len / 0x100 + 0x80;
1592 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1594 writefd(f, str, len);
1597 /* Send a file-list index using a byte-reduction method. */
1598 void write_ndx(int f, int32 ndx)
1600 static int32 prev_positive = -1, prev_negative = 1;
1601 int32 diff, cnt = 0;
1604 if (protocol_version < 30 || read_batch) {
1609 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1610 * negative nums as a positive after sending a leading 0xFF. */
1612 diff = ndx - prev_positive;
1613 prev_positive = ndx;
1614 } else if (ndx == NDX_DONE) {
1619 b[cnt++] = (char)0xFF;
1621 diff = ndx - prev_negative;
1622 prev_negative = ndx;
1625 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1626 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1627 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1628 if (diff < 0xFE && diff > 0)
1629 b[cnt++] = (char)diff;
1630 else if (diff < 0 || diff > 0x7FFF) {
1631 b[cnt++] = (char)0xFE;
1632 b[cnt++] = (char)((ndx >> 24) | 0x80);
1633 b[cnt++] = (char)ndx;
1634 b[cnt++] = (char)(ndx >> 8);
1635 b[cnt++] = (char)(ndx >> 16);
1637 b[cnt++] = (char)0xFE;
1638 b[cnt++] = (char)(diff >> 8);
1639 b[cnt++] = (char)diff;
1644 /* Receive a file-list index using a byte-reduction method. */
1645 int32 read_ndx(int f)
1647 static int32 prev_positive = -1, prev_negative = 1;
1648 int32 *prev_ptr, num;
1651 if (protocol_version < 30)
1655 if (CVAL(b, 0) == 0xFF) {
1657 prev_ptr = &prev_negative;
1658 } else if (CVAL(b, 0) == 0)
1661 prev_ptr = &prev_positive;
1662 if (CVAL(b, 0) == 0xFE) {
1664 if (CVAL(b, 0) & 0x80) {
1665 b[3] = CVAL(b, 0) & ~0x80;
1670 num = (UVAL(b,0)<<8) + UVAL(b,1) + *prev_ptr;
1672 num = UVAL(b, 0) + *prev_ptr;
1674 if (prev_ptr == &prev_negative)
1680 * Read a line of up to @p maxlen characters into @p buf (not counting
1681 * the trailing null). Strips the (required) trailing newline and all
1684 * @return 1 for success; 0 for I/O error or truncation.
1686 int read_line(int f, char *buf, size_t maxlen)
1690 read_buf(f, buf, 1);
1695 if (buf[0] != '\r') {
1704 void io_printf(int fd, const char *format, ...)
1707 char buf[BIGPATHBUFLEN];
1710 va_start(ap, format);
1711 len = vsnprintf(buf, sizeof buf, format, ap);
1715 exit_cleanup(RERR_STREAMIO);
1717 if (len > (int)sizeof buf) {
1718 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1719 exit_cleanup(RERR_STREAMIO);
1722 write_sbuf(fd, buf);
1725 /** Setup for multiplexing a MSG_* stream with the data stream. */
1726 void io_start_multiplex_out(void)
1728 io_flush(NORMAL_FLUSH);
1729 io_start_buffering_out(sock_f_out);
1730 io_multiplexing_out = 1;
1733 /** Setup for multiplexing a MSG_* stream with the data stream. */
1734 void io_start_multiplex_in(void)
1736 io_flush(NORMAL_FLUSH);
1737 io_start_buffering_in(sock_f_in);
1738 io_multiplexing_in = 1;
1741 /** Write an message to the multiplexed data stream. */
1742 int io_multiplex_write(enum msgcode code, const char *buf, size_t len, int convert)
1744 if (!io_multiplexing_out)
1746 io_flush(NORMAL_FLUSH);
1747 stats.total_written += (len+4);
1748 mplex_write(sock_f_out, code, buf, len, convert);
1752 void io_end_multiplex_in(void)
1754 io_multiplexing_in = 0;
1755 io_end_buffering_in();
1758 /** Stop output multiplexing. */
1759 void io_end_multiplex_out(void)
1761 io_multiplexing_out = 0;
1762 io_end_buffering_out();
1765 void start_write_batch(int fd)
1767 /* Some communication has already taken place, but we don't
1768 * enable batch writing until here so that we can write a
1769 * canonical record of the communication even though the
1770 * actual communication so far depends on whether a daemon
1772 write_int(batch_fd, protocol_version);
1773 write_int(batch_fd, checksum_seed);
1776 write_batch_monitor_out = fd;
1778 write_batch_monitor_in = fd;
1781 void stop_write_batch(void)
1783 write_batch_monitor_out = -1;
1784 write_batch_monitor_in = -1;