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, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
24 /* Rsync provides its own multiplexing system, which is used to send
25 * stderr and stdout over a single socket.
27 * For historical reasons this is off during the start of the
28 * connection, but it's switched on quite early using
29 * 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 incremental;
48 extern int read_batch;
49 extern int csum_length;
50 extern int checksum_seed;
51 extern int protocol_version;
52 extern int remove_source_files;
53 extern int preserve_hard_links;
54 extern char *filesfrom_host;
55 extern struct stats stats;
56 extern struct file_list *cur_flist, *first_flist;
58 const char phase_unknown[] = "unknown";
59 int ignore_timeout = 0;
63 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
64 int kluge_around_eof = 0;
71 static int iobuf_f_in = -1;
72 static char *iobuf_in;
73 static size_t iobuf_in_siz;
74 static size_t iobuf_in_ndx;
75 static size_t iobuf_in_remaining;
77 static int iobuf_f_out = -1;
78 static char *iobuf_out;
79 static int iobuf_out_cnt;
81 int flist_forward_from = -1;
83 static int io_multiplexing_out;
84 static int io_multiplexing_in;
85 static time_t last_io_in;
86 static time_t last_io_out;
89 static int write_batch_monitor_in = -1;
90 static int write_batch_monitor_out = -1;
92 static int io_filesfrom_f_in = -1;
93 static int io_filesfrom_f_out = -1;
94 static char io_filesfrom_buf[2048];
95 static char *io_filesfrom_bp;
96 static char io_filesfrom_lastchar;
97 static int io_filesfrom_buflen;
98 static int defer_forwarding_messages = 0;
99 static int select_timeout = SELECT_TIMEOUT;
100 static int active_filecnt = 0;
101 static OFF_T active_bytecnt = 0;
103 static char int_byte_cnt[64] = {
104 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (00 - 3F)/4 */
105 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* (40 - 7F)/4 */
106 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* (80 - BF)/4 */
107 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 9, /* (C0 - FF)/4 */
110 static void readfd(int fd, char *buffer, size_t N);
111 static void writefd(int fd, const char *buf, size_t len);
112 static void writefd_unbuffered(int fd, const char *buf, size_t len);
113 static void decrement_active_files(int ndx);
114 static void decrement_flist_in_progress(int ndx, int redo);
116 struct flist_ndx_item {
117 struct flist_ndx_item *next;
121 struct flist_ndx_list {
122 struct flist_ndx_item *head, *tail;
125 static struct flist_ndx_list redo_list, hlink_list;
127 struct msg_list_item {
128 struct msg_list_item *next;
134 struct msg_list_item *head, *tail;
137 static struct msg_list msg2sndr;
139 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
141 struct flist_ndx_item *item;
143 if (!(item = new(struct flist_ndx_item)))
144 out_of_memory("flist_ndx_push");
148 lp->tail->next = item;
154 static int flist_ndx_pop(struct flist_ndx_list *lp)
156 struct flist_ndx_item *next;
163 next = lp->head->next;
172 static void check_timeout(void)
176 if (!io_timeout || ignore_timeout)
180 last_io_in = time(NULL);
186 if (t - last_io_in >= io_timeout) {
187 if (!am_server && !am_daemon) {
188 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
189 (int)(t-last_io_in));
191 exit_cleanup(RERR_TIMEOUT);
195 /* Note the fds used for the main socket (which might really be a pipe
196 * for a local transfer, but we can ignore that). */
197 void io_set_sock_fds(int f_in, int f_out)
203 void set_io_timeout(int secs)
207 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
208 select_timeout = SELECT_TIMEOUT;
210 select_timeout = io_timeout;
212 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
215 /* Setup the fd used to receive MSG_* messages. Only needed during the
216 * early stages of being a local sender (up through the sending of the
217 * file list) or when we're the generator (to fetch the messages from
219 void set_msg_fd_in(int fd)
224 /* Setup the fd used to send our MSG_* messages. Only needed when
225 * we're the receiver (to send our messages to the generator). */
226 void set_msg_fd_out(int fd)
229 set_nonblocking(msg_fd_out);
232 /* Add a message to the pending MSG_* list. */
233 static void msg_list_add(struct msg_list *lst, int code, const char *buf, int len)
235 struct msg_list_item *m;
236 int sz = len + 4 + sizeof m[0] - 1;
238 if (!(m = (struct msg_list_item *)new_array(char, sz)))
239 out_of_memory("msg_list_add");
242 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
243 memcpy(m->buf + 4, buf, len);
251 static void msg2sndr_flush(void)
253 while (msg2sndr.head && io_multiplexing_out) {
254 struct msg_list_item *m = msg2sndr.head;
255 if (!(msg2sndr.head = m->next))
256 msg2sndr.tail = NULL;
257 stats.total_written += m->len;
258 defer_forwarding_messages = 1;
259 writefd_unbuffered(sock_f_out, m->buf, m->len);
260 defer_forwarding_messages = 0;
265 /* Read a message from the MSG_* fd and handle it. This is called either
266 * during the early stages of being a local sender (up through the sending
267 * of the file list) or when we're the generator (to fetch the messages
268 * from the receiver). */
269 static void read_msg_fd(void)
273 struct file_list *flist;
277 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
278 * to this routine from writefd_unbuffered(). */
281 defer_forwarding_messages++;
286 len = tag & 0xFFFFFF;
287 tag = (tag >> 24) - MPLEX_BASE;
291 if (len != 0 || !am_generator) {
293 rprintf(FERROR, "invalid message %d:%d [%s%s]\n",
294 tag, len, who_am_i(),
295 incremental ? "/incremental" : "");
296 exit_cleanup(RERR_STREAMIO);
301 if (len != 4 || !am_generator)
304 if (remove_source_files)
305 decrement_active_files(IVAL(buf,0));
306 flist_ndx_push(&redo_list, IVAL(buf,0));
308 decrement_flist_in_progress(IVAL(buf,0), 1);
311 if (len != 4 || !am_generator || !incremental)
314 /* Read extra file list from receiver. */
315 assert(iobuf_in != NULL);
316 assert(iobuf_f_in == fd);
317 flist = recv_file_list(fd);
318 flist->parent_ndx = IVAL(buf,0);
321 if (len != 0 || !am_generator || !incremental)
326 if (len >= (int)sizeof buf || !am_generator)
328 readfd(fd, buf, len);
329 send_msg(MSG_DELETED, buf, len);
332 if (len != 4 || !am_generator)
334 readfd(fd, buf, len);
335 if (remove_source_files) {
336 decrement_active_files(IVAL(buf,0));
337 send_msg(MSG_SUCCESS, buf, len);
339 if (preserve_hard_links)
340 flist_ndx_push(&hlink_list, IVAL(buf,0));
342 decrement_flist_in_progress(IVAL(buf,0), 0);
345 if (len != 4 || !am_generator)
347 readfd(fd, buf, len);
349 decrement_flist_in_progress(IVAL(buf,0), 0);
355 if (tag == MSG_SOCKERR)
356 io_end_multiplex_out();
366 rwrite((enum logcode)tag, buf, n);
371 rprintf(FERROR, "unknown message %d:%d [%s]\n",
372 tag, len, who_am_i());
373 exit_cleanup(RERR_STREAMIO);
378 if (!--defer_forwarding_messages)
382 /* This is used by the generator to limit how many file transfers can
383 * be active at once when --remove-source-files is specified. Without
384 * this, sender-side deletions were mostly happening at the end. */
385 void increment_active_files(int ndx, int itemizing, enum logcode code)
387 /* TODO: tune these limits? */
388 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
389 #ifdef SUPPORT_HARD_LINKS
391 check_for_finished_hlinks(itemizing, code);
393 io_flush(NORMAL_FLUSH);
398 active_bytecnt += F_LENGTH(cur_flist->files[ndx]);
401 static void decrement_active_files(int ndx)
403 struct file_list *flist = flist_for_ndx(ndx);
404 assert(flist != NULL);
406 active_bytecnt -= F_LENGTH(flist->files[ndx - flist->ndx_start]);
409 static void decrement_flist_in_progress(int ndx, int redo)
411 struct file_list *flist = cur_flist ? cur_flist : first_flist;
413 while (ndx < flist->ndx_start) {
414 if (flist == first_flist) {
417 "Invalid file index: %d (%d - %d) [%s]\n",
418 ndx, first_flist->ndx_start,
419 first_flist->prev->ndx_start + first_flist->prev->count - 1,
421 exit_cleanup(RERR_PROTOCOL);
425 while (ndx >= flist->ndx_start + flist->count) {
426 if (!(flist = flist->next))
430 flist->in_progress--;
435 /* Write an message to a multiplexed stream. If this fails, rsync exits. */
436 static void mplex_write(int fd, enum msgcode code, const char *buf, size_t len)
441 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
443 if (n > sizeof buffer - 4)
446 memcpy(buffer + 4, buf, n);
448 writefd_unbuffered(fd, buffer, n+4);
454 defer_forwarding_messages++;
455 writefd_unbuffered(fd, buf, len);
456 if (!--defer_forwarding_messages)
461 int send_msg(enum msgcode code, const char *buf, int len)
463 if (msg_fd_out < 0) {
464 if (!defer_forwarding_messages)
465 return io_multiplex_write(code, buf, len);
466 if (!io_multiplexing_out)
468 msg_list_add(&msg2sndr, code, buf, len);
471 mplex_write(msg_fd_out, code, buf, len);
475 void send_msg_int(enum msgcode code, int num)
478 SIVAL(numbuf, 0, num);
479 send_msg(code, numbuf, 4);
482 void wait_for_receiver(void)
484 io_flush(NORMAL_FLUSH);
488 int get_redo_num(void)
490 return flist_ndx_pop(&redo_list);
493 int get_hlink_num(void)
495 return flist_ndx_pop(&hlink_list);
499 * When we're the receiver and we have a local --files-from list of names
500 * that needs to be sent over the socket to the sender, we have to do two
501 * things at the same time: send the sender a list of what files we're
502 * processing and read the incoming file+info list from the sender. We do
503 * this by augmenting the read_timeout() function to copy this data. It
504 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
505 * ready, since it might be a pipe) and then blast it out f_out (when it
506 * is ready to receive more data).
508 void io_set_filesfrom_fds(int f_in, int f_out)
510 io_filesfrom_f_in = f_in;
511 io_filesfrom_f_out = f_out;
512 io_filesfrom_bp = io_filesfrom_buf;
513 io_filesfrom_lastchar = '\0';
514 io_filesfrom_buflen = 0;
517 /* It's almost always an error to get an EOF when we're trying to read from the
518 * network, because the protocol is (for the most part) self-terminating.
520 * There is one case for the receiver when it is at the end of the transfer
521 * (hanging around reading any keep-alive packets that might come its way): if
522 * the sender dies before the generator's kill-signal comes through, we can end
523 * up here needing to loop until the kill-signal arrives. In this situation,
524 * kluge_around_eof will be < 0.
526 * There is another case for older protocol versions (< 24) where the module
527 * listing was not terminated, so we must ignore an EOF error in that case and
528 * exit. In this situation, kluge_around_eof will be > 0. */
529 static void whine_about_eof(int fd)
531 if (kluge_around_eof && fd == sock_f_in) {
533 if (kluge_around_eof > 0)
535 /* If we're still here after 10 seconds, exit with an error. */
536 for (i = 10*1000/20; i--; )
540 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
541 "(%.0f bytes received so far) [%s]\n",
542 (double)stats.total_read, who_am_i());
544 exit_cleanup(RERR_STREAMIO);
548 * Read from a socket with I/O timeout. return the number of bytes
549 * read. If no bytes can be read then exit, never return a number <= 0.
551 * TODO: If the remote shell connection fails, then current versions
552 * actually report an "unexpected EOF" error here. Since it's a
553 * fairly common mistake to try to use rsh when ssh is required, we
554 * should trap that: if we fail to read any data at all, we should
555 * give a better explanation. We can tell whether the connection has
556 * started by looking e.g. at whether the remote version is known yet.
558 static int read_timeout(int fd, char *buf, size_t len)
562 io_flush(FULL_FLUSH);
565 /* until we manage to read *something* */
574 if (io_filesfrom_f_out >= 0) {
576 if (io_filesfrom_buflen == 0) {
577 if (io_filesfrom_f_in >= 0) {
578 FD_SET(io_filesfrom_f_in, &r_fds);
579 new_fd = io_filesfrom_f_in;
581 io_filesfrom_f_out = -1;
585 FD_SET(io_filesfrom_f_out, &w_fds);
586 new_fd = io_filesfrom_f_out;
592 tv.tv_sec = select_timeout;
597 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
601 exit_cleanup(RERR_SOCKETIO);
606 if (io_filesfrom_f_out >= 0) {
607 if (io_filesfrom_buflen) {
608 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
609 int l = write(io_filesfrom_f_out,
611 io_filesfrom_buflen);
613 if (!(io_filesfrom_buflen -= l))
614 io_filesfrom_bp = io_filesfrom_buf;
616 io_filesfrom_bp += l;
618 /* XXX should we complain? */
619 io_filesfrom_f_out = -1;
622 } else if (io_filesfrom_f_in >= 0) {
623 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
624 int l = read(io_filesfrom_f_in,
626 sizeof io_filesfrom_buf);
628 /* Send end-of-file marker */
629 io_filesfrom_buf[0] = '\0';
630 io_filesfrom_buf[1] = '\0';
631 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
632 io_filesfrom_f_in = -1;
635 char *s = io_filesfrom_buf + l;
636 /* Transform CR and/or LF into '\0' */
637 while (s-- > io_filesfrom_buf) {
638 if (*s == '\n' || *s == '\r')
642 if (!io_filesfrom_lastchar) {
643 /* Last buf ended with a '\0', so don't
644 * let this buf start with one. */
645 while (l && !*io_filesfrom_bp)
646 io_filesfrom_bp++, l--;
649 io_filesfrom_bp = io_filesfrom_buf;
651 char *f = io_filesfrom_bp;
654 /* Eliminate any multi-'\0' runs. */
656 if (!(*t++ = *f++)) {
657 while (f != eob && !*f)
661 io_filesfrom_lastchar = f[-1];
663 io_filesfrom_buflen = l;
669 if (!FD_ISSET(fd, &r_fds))
672 n = read(fd, buf, len);
676 whine_about_eof(fd); /* Doesn't return. */
677 if (errno == EINTR || errno == EWOULDBLOCK
681 /* Don't write errors on a dead socket. */
682 if (fd == sock_f_in) {
683 io_end_multiplex_out();
684 rsyserr(FSOCKERR, errno, "read error");
686 rsyserr(FERROR, errno, "read error");
687 exit_cleanup(RERR_STREAMIO);
694 if (fd == sock_f_in && io_timeout)
695 last_io_in = time(NULL);
702 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
705 int read_filesfrom_line(int fd, char *fname)
707 char ch, *s, *eob = fname + MAXPATHLEN - 1;
709 int reading_remotely = filesfrom_host != NULL;
710 int nulls = eol_nulls || reading_remotely;
715 cnt = read(fd, &ch, 1);
716 if (cnt < 0 && (errno == EWOULDBLOCK
717 || errno == EINTR || errno == EAGAIN)) {
724 tv.tv_sec = select_timeout;
726 if (!select(fd+1, &r_fds, NULL, &e_fds, &tv))
728 if (FD_ISSET(fd, &e_fds)) {
729 rsyserr(FINFO, errno,
730 "select exception on fd %d", fd);
736 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
737 /* Skip empty lines if reading locally. */
738 if (!reading_remotely && s == fname)
748 if (*fname == '#' || *fname == ';')
754 int io_start_buffering_out(int f_out)
757 assert(f_out == iobuf_f_out);
760 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
761 out_of_memory("io_start_buffering_out");
767 int io_start_buffering_in(int f_in)
770 assert(f_in == iobuf_f_in);
773 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
774 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
775 out_of_memory("io_start_buffering_in");
780 void io_end_buffering_in(void)
787 iobuf_in_remaining = 0;
791 void io_end_buffering_out(void)
795 io_flush(FULL_FLUSH);
801 void maybe_flush_socket(void)
803 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
804 io_flush(NORMAL_FLUSH);
807 void maybe_send_keepalive(void)
809 if (time(NULL) - last_io_out >= allowed_lull) {
810 if (!iobuf_out || !iobuf_out_cnt) {
811 if (protocol_version < 29)
812 return; /* there's nothing we can do */
813 if (protocol_version >= 30)
814 send_msg(MSG_NOOP, "", 0);
816 write_int(sock_f_out, cur_flist->count);
817 write_shortint(sock_f_out, ITEM_IS_NEW);
821 io_flush(NORMAL_FLUSH);
825 void start_flist_forward(int f_in)
827 assert(iobuf_out != NULL);
828 assert(iobuf_f_out == msg_fd_out);
829 flist_forward_from = f_in;
832 void stop_flist_forward()
834 flist_forward_from = -1;
835 io_flush(FULL_FLUSH);
839 * Continue trying to read len bytes - don't return until len has been
842 static void read_loop(int fd, char *buf, size_t len)
845 int n = read_timeout(fd, buf, len);
853 * Read from the file descriptor handling multiplexing - return number
856 * Never returns <= 0.
858 static int readfd_unbuffered(int fd, char *buf, size_t len)
862 char line[BIGPATHBUFLEN];
864 if (!iobuf_in || fd != iobuf_f_in)
865 return read_timeout(fd, buf, len);
867 if (!io_multiplexing_in && iobuf_in_remaining == 0) {
868 iobuf_in_remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
873 if (iobuf_in_remaining) {
874 len = MIN(len, iobuf_in_remaining);
875 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
877 iobuf_in_remaining -= len;
882 read_loop(fd, line, 4);
885 msg_bytes = tag & 0xFFFFFF;
886 tag = (tag >> 24) - MPLEX_BASE;
890 if (msg_bytes > iobuf_in_siz) {
891 if (!(iobuf_in = realloc_array(iobuf_in, char,
893 out_of_memory("readfd_unbuffered");
894 iobuf_in_siz = msg_bytes;
896 read_loop(fd, iobuf_in, msg_bytes);
897 iobuf_in_remaining = msg_bytes;
902 maybe_send_keepalive();
907 read_loop(fd, line, msg_bytes);
908 io_error |= IVAL(line, 0);
911 if (msg_bytes >= sizeof line)
913 read_loop(fd, line, msg_bytes);
914 /* A directory name was sent with the trailing null */
915 if (msg_bytes > 0 && !line[msg_bytes-1])
916 log_delete(line, S_IFDIR);
918 line[msg_bytes] = '\0';
919 log_delete(line, S_IFREG);
923 if (msg_bytes != 4) {
925 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
926 tag, (long)msg_bytes, who_am_i());
927 exit_cleanup(RERR_STREAMIO);
929 read_loop(fd, line, msg_bytes);
930 successful_send(IVAL(line, 0));
935 read_loop(fd, line, msg_bytes);
936 send_msg_int(MSG_NO_SEND, IVAL(line, 0));
940 if (msg_bytes >= sizeof line) {
943 "multiplexing overflow %d:%ld [%s]\n",
944 tag, (long)msg_bytes, who_am_i());
945 exit_cleanup(RERR_STREAMIO);
947 read_loop(fd, line, msg_bytes);
948 rwrite((enum logcode)tag, line, msg_bytes);
951 rprintf(FERROR, "unexpected tag %d [%s]\n",
953 exit_cleanup(RERR_STREAMIO);
957 if (iobuf_in_remaining == 0)
958 io_flush(NORMAL_FLUSH);
963 /* Do a buffered read from fd. Don't return until all N bytes have
964 * been read. If all N can't be read then exit with an error. */
965 static void readfd(int fd, char *buffer, size_t N)
971 cnt = readfd_unbuffered(fd, buffer + total, N-total);
975 if (fd == write_batch_monitor_in) {
976 if ((size_t)write(batch_fd, buffer, total) != total)
977 exit_cleanup(RERR_FILEIO);
980 if (fd == flist_forward_from)
981 writefd(iobuf_f_out, buffer, total);
984 stats.total_read += total;
987 unsigned short read_shortint(int f)
991 return (UVAL(b, 1) << 8) + UVAL(b, 0);
994 int32 read_int(int f)
1001 #if SIZEOF_INT32 > 4
1002 if (num & (int32)0x80000000)
1003 num |= ~(int32)0xffffffff;
1008 int64 read_longint(int f)
1013 if (protocol_version < 30) {
1016 if ((int32)num != (int32)0xffffffff)
1019 #if SIZEOF_INT64 < 8
1020 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1021 exit_cleanup(RERR_UNSUPPORTED);
1024 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
1029 cnt = int_byte_cnt[CVAL(b, 0) / 4];
1030 #if SIZEOF_INT64 < 8
1031 if (cnt > 5 || (cnt == 5 && (CVAL(b,0)&0x3F || CVAL(b,1)&0x80))) {
1032 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1033 exit_cleanup(RERR_UNSUPPORTED);
1037 readfd(f, b + 3, cnt - 3);
1043 num = NVAL4(b, 0x80);
1046 num = NVAL5(b, 0xC0);
1048 #if SIZEOF_INT64 >= 8
1050 num = NVAL6(b, 0xE0);
1053 num = NVAL7(b, 0xF0);
1056 num = NVAL8(b, 0xF8);
1059 num = NVAL8(b+1, 0);
1063 exit_cleanup(RERR_PROTOCOL); /* impossible... */
1070 void read_buf(int f, char *buf, size_t len)
1075 void read_sbuf(int f, char *buf, size_t len)
1077 readfd(f, buf, len);
1081 uchar read_byte(int f)
1084 readfd(f, (char *)&c, 1);
1088 int read_vstring(int f, char *buf, int bufsize)
1090 int len = read_byte(f);
1093 len = (len & ~0x80) * 0x100 + read_byte(f);
1095 if (len >= bufsize) {
1096 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
1102 readfd(f, buf, len);
1107 /* Populate a sum_struct with values from the socket. This is
1108 * called by both the sender and the receiver. */
1109 void read_sum_head(int f, struct sum_struct *sum)
1111 sum->count = read_int(f);
1112 if (sum->count < 0) {
1113 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
1114 (long)sum->count, who_am_i());
1115 exit_cleanup(RERR_PROTOCOL);
1117 sum->blength = read_int(f);
1118 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
1119 rprintf(FERROR, "Invalid block length %ld [%s]\n",
1120 (long)sum->blength, who_am_i());
1121 exit_cleanup(RERR_PROTOCOL);
1123 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
1124 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
1125 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
1126 sum->s2length, who_am_i());
1127 exit_cleanup(RERR_PROTOCOL);
1129 sum->remainder = read_int(f);
1130 if (sum->remainder < 0 || sum->remainder > sum->blength) {
1131 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
1132 (long)sum->remainder, who_am_i());
1133 exit_cleanup(RERR_PROTOCOL);
1137 /* Send the values from a sum_struct over the socket. Set sum to
1138 * NULL if there are no checksums to send. This is called by both
1139 * the generator and the sender. */
1140 void write_sum_head(int f, struct sum_struct *sum)
1142 static struct sum_struct null_sum;
1147 write_int(f, sum->count);
1148 write_int(f, sum->blength);
1149 if (protocol_version >= 27)
1150 write_int(f, sum->s2length);
1151 write_int(f, sum->remainder);
1155 * Sleep after writing to limit I/O bandwidth usage.
1157 * @todo Rather than sleeping after each write, it might be better to
1158 * use some kind of averaging. The current algorithm seems to always
1159 * use a bit less bandwidth than specified, because it doesn't make up
1160 * for slow periods. But arguably this is a feature. In addition, we
1161 * ought to take the time used to write the data into account.
1163 * During some phases of big transfers (file FOO is uptodate) this is
1164 * called with a small bytes_written every time. As the kernel has to
1165 * round small waits up to guarantee that we actually wait at least the
1166 * requested number of microseconds, this can become grossly inaccurate.
1167 * We therefore keep track of the bytes we've written over time and only
1168 * sleep when the accumulated delay is at least 1 tenth of a second.
1170 static void sleep_for_bwlimit(int bytes_written)
1172 static struct timeval prior_tv;
1173 static long total_written = 0;
1174 struct timeval tv, start_tv;
1175 long elapsed_usec, sleep_usec;
1177 #define ONE_SEC 1000000L /* # of microseconds in a second */
1179 if (!bwlimit_writemax)
1182 total_written += bytes_written;
1184 gettimeofday(&start_tv, NULL);
1185 if (prior_tv.tv_sec) {
1186 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1187 + (start_tv.tv_usec - prior_tv.tv_usec);
1188 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1189 if (total_written < 0)
1193 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1194 if (sleep_usec < ONE_SEC / 10) {
1195 prior_tv = start_tv;
1199 tv.tv_sec = sleep_usec / ONE_SEC;
1200 tv.tv_usec = sleep_usec % ONE_SEC;
1201 select(0, NULL, NULL, NULL, &tv);
1203 gettimeofday(&prior_tv, NULL);
1204 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1205 + (prior_tv.tv_usec - start_tv.tv_usec);
1206 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1209 /* Write len bytes to the file descriptor fd, looping as necessary to get
1210 * the job done and also (in certain circumstances) reading any data on
1211 * msg_fd_in to avoid deadlock.
1213 * This function underlies the multiplexing system. The body of the
1214 * application never calls this function directly. */
1215 static void writefd_unbuffered(int fd, const char *buf, size_t len)
1217 size_t n, total = 0;
1218 fd_set w_fds, r_fds, e_fds;
1219 int maxfd, count, cnt, using_r_fds;
1220 int defer_save = defer_forwarding_messages;
1224 defer_forwarding_messages = 1;
1226 while (total < len) {
1233 if (msg_fd_in >= 0) {
1235 FD_SET(msg_fd_in, &r_fds);
1236 if (msg_fd_in > maxfd)
1242 tv.tv_sec = select_timeout;
1246 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1247 &w_fds, &e_fds, &tv);
1250 if (count < 0 && errno == EBADF)
1251 exit_cleanup(RERR_SOCKETIO);
1256 if (FD_ISSET(fd, &e_fds)) {
1257 rsyserr(FINFO, errno,
1258 "select exception on fd %d", fd);
1261 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1264 if (!FD_ISSET(fd, &w_fds))
1268 if (bwlimit_writemax && n > bwlimit_writemax)
1269 n = bwlimit_writemax;
1270 cnt = write(fd, buf + total, n);
1276 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1282 /* Don't try to write errors back across the stream. */
1283 if (fd == sock_f_out)
1284 io_end_multiplex_out();
1285 rsyserr(FERROR, errno,
1286 "writefd_unbuffered failed to write %ld bytes [%s]",
1287 (long)len, who_am_i());
1288 /* If the other side is sending us error messages, try
1289 * to grab any messages they sent before they died. */
1290 while (fd == sock_f_out && io_multiplexing_in) {
1293 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1294 sizeof io_filesfrom_buf);
1296 exit_cleanup(RERR_STREAMIO);
1300 defer_forwarding_messages = 1;
1302 if (fd == sock_f_out) {
1303 if (io_timeout || am_generator)
1304 last_io_out = time(NULL);
1305 sleep_for_bwlimit(cnt);
1310 if (!(defer_forwarding_messages = defer_save))
1314 void io_flush(int flush_it_all)
1316 if (flush_it_all && !defer_forwarding_messages)
1319 if (!iobuf_out_cnt || no_flush)
1322 if (io_multiplexing_out)
1323 mplex_write(sock_f_out, MSG_DATA, iobuf_out, iobuf_out_cnt);
1325 writefd_unbuffered(iobuf_f_out, iobuf_out, iobuf_out_cnt);
1329 static void writefd(int fd, const char *buf, size_t len)
1331 if (fd == sock_f_out)
1332 stats.total_written += len;
1334 if (fd == write_batch_monitor_out) {
1335 if ((size_t)write(batch_fd, buf, len) != len)
1336 exit_cleanup(RERR_FILEIO);
1339 if (!iobuf_out || fd != iobuf_f_out) {
1340 writefd_unbuffered(fd, buf, len);
1345 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1347 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1353 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1354 io_flush(NORMAL_FLUSH);
1358 void write_shortint(int f, unsigned short x)
1362 b[1] = (char)(x >> 8);
1366 void write_int(int f, int32 x)
1374 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1375 * 64-bit types on this platform.
1377 void write_longint(int f, int64 x)
1381 #if SIZEOF_INT64 < 8
1382 if (x < 0 || x > 0x7FFFFFFF) {
1383 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1384 exit_cleanup(RERR_UNSUPPORTED);
1388 if (protocol_version < 30) {
1389 char * const s = b+4;
1391 #if SIZEOF_INT64 < 8
1394 if (x <= 0x7FFFFFFF && x >= 0) {
1400 SIVAL(s, 4, x >> 32);
1405 } else if (x < ((int32)1<<(3*8-1))) {
1406 b[0] = (char)(x >> 16);
1407 b[1] = (char)(x >> 8);
1410 } else if (x < ((int64)1<<(4*8-2))) {
1411 b[0] = (char)((x >> 24) | 0x80);
1412 b[1] = (char)(x >> 16);
1413 b[2] = (char)(x >> 8);
1416 #if SIZEOF_INT64 < 8
1419 b[1] = (char)(x >> 24);
1420 b[2] = (char)(x >> 16);
1421 b[3] = (char)(x >> 8);
1426 } else if (x < ((int64)1<<(5*8-3))) {
1427 b[0] = (char)((x >> 32) | 0xC0);
1428 b[1] = (char)(x >> 24);
1429 b[2] = (char)(x >> 16);
1430 b[3] = (char)(x >> 8);
1433 } else if (x < ((int64)1<<(6*8-4))) {
1434 b[0] = (char)((x >> 40) | 0xE0);
1435 b[1] = (char)(x >> 32);
1436 b[2] = (char)(x >> 24);
1437 b[3] = (char)(x >> 16);
1438 b[4] = (char)(x >> 8);
1441 } else if (x < ((int64)1<<(7*8-5))) {
1442 b[0] = (char)((x >> 48) | 0xF0);
1443 b[1] = (char)(x >> 40);
1444 b[2] = (char)(x >> 32);
1445 b[3] = (char)(x >> 24);
1446 b[4] = (char)(x >> 16);
1447 b[5] = (char)(x >> 8);
1450 } else if (x < ((int64)1<<(8*8-6))) {
1451 b[0] = (char)((x >> 56) | 0xF8);
1452 b[1] = (char)(x >> 48);
1453 b[2] = (char)(x >> 40);
1454 b[3] = (char)(x >> 32);
1455 b[4] = (char)(x >> 24);
1456 b[5] = (char)(x >> 16);
1457 b[6] = (char)(x >> 8);
1463 b[1] = (char)(x >> 56);
1464 b[2] = (char)(x >> 48);
1465 b[3] = (char)(x >> 40);
1466 b[4] = (char)(x >> 32);
1467 b[5] = (char)(x >> 24);
1468 b[6] = (char)(x >> 16);
1469 b[7] = (char)(x >> 8);
1476 void write_buf(int f, const char *buf, size_t len)
1481 /** Write a string to the connection */
1482 void write_sbuf(int f, const char *buf)
1484 writefd(f, buf, strlen(buf));
1487 void write_byte(int f, uchar c)
1489 writefd(f, (char *)&c, 1);
1492 void write_vstring(int f, const char *str, int len)
1494 uchar lenbuf[3], *lb = lenbuf;
1499 "attempting to send over-long vstring (%d > %d)\n",
1501 exit_cleanup(RERR_PROTOCOL);
1503 *lb++ = len / 0x100 + 0x80;
1507 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1509 writefd(f, str, len);
1512 /* Send a file-list index using a byte-reduction method. */
1513 void write_ndx(int f, int32 ndx)
1515 static int32 prev_positive = -1, prev_negative = 1;
1516 int32 diff, cnt = 0;
1519 if (protocol_version < 30 || read_batch) {
1524 /* Send NDX_DONE as a single-byte 0 with no side effects. Send
1525 * negative nums as a positive after sending a leading 0xFF. */
1527 diff = ndx - prev_positive;
1528 prev_positive = ndx;
1529 } else if (ndx == NDX_DONE) {
1534 b[cnt++] = (char)0xFF;
1536 diff = ndx - prev_negative;
1537 prev_negative = ndx;
1540 /* A diff of 1 - 253 is sent as a one-byte diff; a diff of 254 - 32767
1541 * or 0 is sent as a 0xFE + a two-byte diff; otherwise we send 0xFE
1542 * & all 4 bytes of the (non-negative) num with the high-bit set. */
1543 if (diff < 0xFE && diff > 0)
1544 b[cnt++] = (char)diff;
1545 else if (diff < 0 || diff > 0x7FFF) {
1546 b[cnt++] = (char)0xFE;
1547 b[cnt++] = (char)((ndx >> 24) | 0x80);
1548 b[cnt++] = (char)(ndx >> 16);
1549 b[cnt++] = (char)(ndx >> 8);
1550 b[cnt++] = (char)ndx;
1552 b[cnt++] = (char)0xFE;
1553 b[cnt++] = (char)(diff >> 8);
1554 b[cnt++] = (char)diff;
1559 /* Receive a file-list index using a byte-reduction method. */
1560 int32 read_ndx(int f)
1562 static int32 prev_positive = -1, prev_negative = 1;
1563 int32 *prev_ptr, num;
1566 if (protocol_version < 30)
1570 if (CVAL(b, 0) == 0xFF) {
1572 prev_ptr = &prev_negative;
1573 } else if (CVAL(b, 0) == 0)
1576 prev_ptr = &prev_positive;
1577 if (CVAL(b, 0) == 0xFE) {
1579 if (CVAL(b, 0) & 0x80) {
1581 num = NVAL4(b, 0x80);
1583 num = NVAL2(b, 0) + *prev_ptr;
1585 num = CVAL(b, 0) + *prev_ptr;
1587 if (prev_ptr == &prev_negative)
1593 * Read a line of up to @p maxlen characters into @p buf (not counting
1594 * the trailing null). Strips the (required) trailing newline and all
1597 * @return 1 for success; 0 for I/O error or truncation.
1599 int read_line(int f, char *buf, size_t maxlen)
1603 read_buf(f, buf, 1);
1608 if (buf[0] != '\r') {
1617 void io_printf(int fd, const char *format, ...)
1620 char buf[BIGPATHBUFLEN];
1623 va_start(ap, format);
1624 len = vsnprintf(buf, sizeof buf, format, ap);
1628 exit_cleanup(RERR_STREAMIO);
1630 if (len > (int)sizeof buf) {
1631 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1632 exit_cleanup(RERR_STREAMIO);
1635 write_sbuf(fd, buf);
1638 /** Setup for multiplexing a MSG_* stream with the data stream. */
1639 void io_start_multiplex_out(void)
1641 io_flush(NORMAL_FLUSH);
1642 io_start_buffering_out(sock_f_out);
1643 io_multiplexing_out = 1;
1646 /** Setup for multiplexing a MSG_* stream with the data stream. */
1647 void io_start_multiplex_in(void)
1649 io_flush(NORMAL_FLUSH);
1650 io_start_buffering_in(sock_f_in);
1651 io_multiplexing_in = 1;
1654 /** Write an message to the multiplexed data stream. */
1655 int io_multiplex_write(enum msgcode code, const char *buf, size_t len)
1657 if (!io_multiplexing_out)
1659 io_flush(NORMAL_FLUSH);
1660 stats.total_written += (len+4);
1661 mplex_write(sock_f_out, code, buf, len);
1665 void io_end_multiplex_in(void)
1667 io_multiplexing_in = 0;
1668 io_end_buffering_in();
1671 /** Stop output multiplexing. */
1672 void io_end_multiplex_out(void)
1674 io_multiplexing_out = 0;
1675 io_end_buffering_out();
1678 void start_write_batch(int fd)
1680 /* Some communication has already taken place, but we don't
1681 * enable batch writing until here so that we can write a
1682 * canonical record of the communication even though the
1683 * actual communication so far depends on whether a daemon
1685 write_int(batch_fd, protocol_version);
1686 write_int(batch_fd, checksum_seed);
1689 write_batch_monitor_out = fd;
1691 write_batch_monitor_in = fd;
1694 void stop_write_batch(void)
1696 write_batch_monitor_out = -1;
1697 write_batch_monitor_in = -1;