1 /* -*- c-file-style: "linux" -*-
3 * Copyright (C) 1996-2001 by Andrew Tridgell
4 * Copyright (C) Paul Mackerras 1996
5 * Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 * Socket and pipe I/O utilities used in rsync.
27 * rsync provides its own multiplexing system, which is used to send
28 * stderr and stdout over a single socket. We need this because
29 * stdout normally carries the binary data stream, and stderr all our
32 * For historical reasons this is off during the start of the
33 * connection, but it's switched on quite early using
34 * io_start_multiplex_out() and io_start_multiplex_in().
39 /** If no timeout is specified then use a 60 second select timeout */
40 #define SELECT_TIMEOUT 60
43 extern size_t bwlimit_writemax;
44 extern int io_timeout;
45 extern int allowed_lull;
49 extern int am_generator;
51 extern int read_batch;
52 extern int csum_length;
53 extern int checksum_seed;
54 extern int protocol_version;
55 extern int remove_sent_files;
56 extern int preserve_hard_links;
57 extern char *filesfrom_host;
58 extern struct stats stats;
59 extern struct file_list *the_file_list;
61 const char phase_unknown[] = "unknown";
62 int ignore_timeout = 0;
64 int batch_gen_fd = -1;
67 * The connection might be dropped at some point; perhaps because the
68 * remote instance crashed. Just giving the offset on the stream is
69 * not very helpful. So instead we try to make io_phase_name point to
72 * For buffered/multiplexed I/O these names will be somewhat
73 * approximate; perhaps for ease of support we would rather make the
74 * buffer always flush when a single application-level I/O finishes.
76 * @todo Perhaps we want some simple stack functionality, but there's
77 * no need to overdo it.
79 const char *io_write_phase = phase_unknown;
80 const char *io_read_phase = phase_unknown;
82 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
83 int kluge_around_eof = 0;
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 char io_filesfrom_buf[2048];
102 static char *io_filesfrom_bp;
103 static char io_filesfrom_lastchar;
104 static int io_filesfrom_buflen;
105 static int defer_forwarding_messages = 0;
106 static int select_timeout = SELECT_TIMEOUT;
107 static int active_filecnt = 0;
108 static OFF_T active_bytecnt = 0;
110 static void read_loop(int fd, char *buf, size_t len);
112 struct flist_ndx_item {
113 struct flist_ndx_item *next;
117 struct flist_ndx_list {
118 struct flist_ndx_item *head, *tail;
121 static struct flist_ndx_list redo_list, hlink_list;
123 struct msg_list_item {
124 struct msg_list_item *next;
130 struct msg_list_item *head, *tail;
133 static struct msg_list msg2genr, msg2sndr;
135 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
137 struct flist_ndx_item *item;
139 if (!(item = new(struct flist_ndx_item)))
140 out_of_memory("flist_ndx_push");
144 lp->tail->next = item;
150 static int flist_ndx_pop(struct flist_ndx_list *lp)
152 struct flist_ndx_item *next;
159 next = lp->head->next;
168 static void check_timeout(void)
172 if (!io_timeout || ignore_timeout)
176 last_io_in = time(NULL);
182 if (t - last_io_in >= io_timeout) {
183 if (!am_server && !am_daemon) {
184 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
185 (int)(t-last_io_in));
187 exit_cleanup(RERR_TIMEOUT);
191 /* Note the fds used for the main socket (which might really be a pipe
192 * for a local transfer, but we can ignore that). */
193 void io_set_sock_fds(int f_in, int f_out)
199 void set_io_timeout(int secs)
203 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
204 select_timeout = SELECT_TIMEOUT;
206 select_timeout = io_timeout;
208 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
211 /* Setup the fd used to receive MSG_* messages. Only needed during the
212 * early stages of being a local sender (up through the sending of the
213 * file list) or when we're the generator (to fetch the messages from
215 void set_msg_fd_in(int fd)
220 /* Setup the fd used to send our MSG_* messages. Only needed when
221 * we're the receiver (to send our messages to the generator). */
222 void set_msg_fd_out(int fd)
225 set_nonblocking(msg_fd_out);
228 /* Add a message to the pending MSG_* list. */
229 static void msg_list_add(struct msg_list *lst, int code, char *buf, int len)
231 struct msg_list_item *m;
232 int sz = len + 4 + sizeof m[0] - 1;
234 if (!(m = (struct msg_list_item *)new_array(char, sz)))
235 out_of_memory("msg_list_add");
238 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
239 memcpy(m->buf + 4, buf, len);
247 /* Read a message from the MSG_* fd and handle it. This is called either
248 * during the early stages of being a local sender (up through the sending
249 * of the file list) or when we're the generator (to fetch the messages
250 * from the receiver). */
251 static void read_msg_fd(void)
258 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
259 * to this routine from writefd_unbuffered(). */
262 read_loop(fd, buf, 4);
265 len = tag & 0xFFFFFF;
266 tag = (tag >> 24) - MPLEX_BASE;
270 if (len != 0 || !am_generator) {
271 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
272 exit_cleanup(RERR_STREAMIO);
274 flist_ndx_push(&redo_list, -1);
277 if (len != 4 || !am_generator) {
278 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
279 exit_cleanup(RERR_STREAMIO);
281 read_loop(fd, buf, 4);
282 if (remove_sent_files)
283 decrement_active_files(IVAL(buf,0));
284 flist_ndx_push(&redo_list, IVAL(buf,0));
287 if (len >= (int)sizeof buf || !am_generator) {
288 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
289 exit_cleanup(RERR_STREAMIO);
291 read_loop(fd, buf, len);
292 if (defer_forwarding_messages)
293 msg_list_add(&msg2sndr, MSG_DELETED, buf, len);
295 io_multiplex_write(MSG_DELETED, buf, len);
298 if (len != 4 || !am_generator) {
299 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
300 exit_cleanup(RERR_STREAMIO);
302 read_loop(fd, buf, len);
303 if (remove_sent_files) {
304 decrement_active_files(IVAL(buf,0));
305 if (defer_forwarding_messages)
306 msg_list_add(&msg2sndr, MSG_SUCCESS, buf, len);
308 io_multiplex_write(MSG_SUCCESS, buf, len);
310 if (preserve_hard_links)
311 flist_ndx_push(&hlink_list, IVAL(buf,0));
315 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
316 exit_cleanup(RERR_STREAMIO);
318 close_multiplexing_out();
327 read_loop(fd, buf, n);
328 if (am_generator && am_server && defer_forwarding_messages)
329 msg_list_add(&msg2sndr, tag, buf, n);
331 rwrite((enum logcode)tag, buf, n);
336 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
337 exit_cleanup(RERR_STREAMIO);
343 /* This is used by the generator to limit how many file transfers can
344 * be active at once when --remove-sent-files is specified. Without
345 * this, sender-side deletions were mostly happening at the end. */
346 void increment_active_files(int ndx, int itemizing, enum logcode code)
348 /* TODO: tune these limits? */
349 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
351 check_for_finished_hlinks(itemizing, code);
356 active_bytecnt += the_file_list->files[ndx]->length;
359 void decrement_active_files(int ndx)
362 active_bytecnt -= the_file_list->files[ndx]->length;
365 /* Try to push messages off the list onto the wire. If we leave with more
366 * to do, return 0. On error, return -1. If everything flushed, return 1.
367 * This is only active in the receiver. */
368 static int msg2genr_flush(int flush_it_all)
370 static int written = 0;
377 while (msg2genr.head) {
378 struct msg_list_item *m = msg2genr.head;
379 int n = write(msg_fd_out, m->buf + written, m->len - written);
383 if (errno != EWOULDBLOCK && errno != EAGAIN)
388 FD_SET(msg_fd_out, &fds);
389 tv.tv_sec = select_timeout;
391 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
393 } else if ((written += n) == m->len) {
394 msg2genr.head = m->next;
396 msg2genr.tail = NULL;
404 void send_msg(enum msgcode code, char *buf, int len)
406 if (msg_fd_out < 0) {
407 io_multiplex_write(code, buf, len);
410 msg_list_add(&msg2genr, code, buf, len);
411 msg2genr_flush(NORMAL_FLUSH);
414 int get_redo_num(int itemizing, enum logcode code)
418 check_for_finished_hlinks(itemizing, code);
424 return flist_ndx_pop(&redo_list);
427 int get_hlink_num(void)
429 return flist_ndx_pop(&hlink_list);
433 * When we're the receiver and we have a local --files-from list of names
434 * that needs to be sent over the socket to the sender, we have to do two
435 * things at the same time: send the sender a list of what files we're
436 * processing and read the incoming file+info list from the sender. We do
437 * this by augmenting the read_timeout() function to copy this data. It
438 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
439 * ready, since it might be a pipe) and then blast it out f_out (when it
440 * is ready to receive more data).
442 void io_set_filesfrom_fds(int f_in, int f_out)
444 io_filesfrom_f_in = f_in;
445 io_filesfrom_f_out = f_out;
446 io_filesfrom_bp = io_filesfrom_buf;
447 io_filesfrom_lastchar = '\0';
448 io_filesfrom_buflen = 0;
451 /* It's almost always an error to get an EOF when we're trying to read from the
452 * network, because the protocol is (for the most part) self-terminating.
454 * There is one case for the receiver when it is at the end of the transfer
455 * (hanging around reading any keep-alive packets that might come its way): if
456 * the sender dies before the generator's kill-signal comes through, we can end
457 * up here needing to loop until the kill-signal arrives. In this situation,
458 * kluge_around_eof will be < 0.
460 * There is another case for older protocol versions (< 24) where the module
461 * listing was not terminated, so we must ignore an EOF error in that case and
462 * exit. In this situation, kluge_around_eof will be > 0. */
463 static void whine_about_eof(int fd)
465 if (kluge_around_eof && fd == sock_f_in) {
467 if (kluge_around_eof > 0)
469 /* If we're still here after 10 seconds, exit with an error. */
470 for (i = 10*1000/20; i--; )
474 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
475 "(%.0f bytes received so far) [%s]\n",
476 (double)stats.total_read, who_am_i());
478 exit_cleanup(RERR_STREAMIO);
482 * Read from a socket with I/O timeout. return the number of bytes
483 * read. If no bytes can be read then exit, never return a number <= 0.
485 * TODO: If the remote shell connection fails, then current versions
486 * actually report an "unexpected EOF" error here. Since it's a
487 * fairly common mistake to try to use rsh when ssh is required, we
488 * should trap that: if we fail to read any data at all, we should
489 * give a better explanation. We can tell whether the connection has
490 * started by looking e.g. at whether the remote version is known yet.
492 static int read_timeout(int fd, char *buf, size_t len)
496 io_flush(NORMAL_FLUSH);
499 /* until we manage to read *something* */
509 FD_SET(msg_fd_out, &w_fds);
510 if (msg_fd_out > maxfd)
513 if (io_filesfrom_f_out >= 0) {
515 if (io_filesfrom_buflen == 0) {
516 if (io_filesfrom_f_in >= 0) {
517 FD_SET(io_filesfrom_f_in, &r_fds);
518 new_fd = io_filesfrom_f_in;
520 io_filesfrom_f_out = -1;
524 FD_SET(io_filesfrom_f_out, &w_fds);
525 new_fd = io_filesfrom_f_out;
531 tv.tv_sec = select_timeout;
536 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
540 exit_cleanup(RERR_SOCKETIO);
545 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
546 msg2genr_flush(NORMAL_FLUSH);
548 if (io_filesfrom_f_out >= 0) {
549 if (io_filesfrom_buflen) {
550 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
551 int l = write(io_filesfrom_f_out,
553 io_filesfrom_buflen);
555 if (!(io_filesfrom_buflen -= l))
556 io_filesfrom_bp = io_filesfrom_buf;
558 io_filesfrom_bp += l;
560 /* XXX should we complain? */
561 io_filesfrom_f_out = -1;
564 } else if (io_filesfrom_f_in >= 0) {
565 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
566 int l = read(io_filesfrom_f_in,
568 sizeof io_filesfrom_buf);
570 /* Send end-of-file marker */
571 io_filesfrom_buf[0] = '\0';
572 io_filesfrom_buf[1] = '\0';
573 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
574 io_filesfrom_f_in = -1;
577 char *s = io_filesfrom_buf + l;
578 /* Transform CR and/or LF into '\0' */
579 while (s-- > io_filesfrom_buf) {
580 if (*s == '\n' || *s == '\r')
584 if (!io_filesfrom_lastchar) {
585 /* Last buf ended with a '\0', so don't
586 * let this buf start with one. */
587 while (l && !*io_filesfrom_bp)
588 io_filesfrom_bp++, l--;
591 io_filesfrom_bp = io_filesfrom_buf;
593 char *f = io_filesfrom_bp;
596 /* Eliminate any multi-'\0' runs. */
598 if (!(*t++ = *f++)) {
599 while (f != eob && !*f)
603 io_filesfrom_lastchar = f[-1];
605 io_filesfrom_buflen = l;
611 if (!FD_ISSET(fd, &r_fds))
614 n = read(fd, buf, len);
618 whine_about_eof(fd); /* Doesn't return. */
619 if (errno == EINTR || errno == EWOULDBLOCK
623 /* Don't write errors on a dead socket. */
624 if (fd == sock_f_in) {
625 close_multiplexing_out();
626 rsyserr(FSOCKERR, errno, "read error");
628 rsyserr(FERROR, errno, "read error");
629 exit_cleanup(RERR_STREAMIO);
636 if (fd == sock_f_in && io_timeout)
637 last_io_in = time(NULL);
644 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
647 int read_filesfrom_line(int fd, char *fname)
649 char ch, *s, *eob = fname + MAXPATHLEN - 1;
651 int reading_remotely = filesfrom_host != NULL;
652 int nulls = eol_nulls || reading_remotely;
657 cnt = read(fd, &ch, 1);
658 if (cnt < 0 && (errno == EWOULDBLOCK
659 || errno == EINTR || errno == EAGAIN)) {
664 tv.tv_sec = select_timeout;
666 if (!select(fd+1, &fds, NULL, NULL, &tv))
672 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
673 /* Skip empty lines if reading locally. */
674 if (!reading_remotely && s == fname)
684 if (*fname == '#' || *fname == ';')
690 static char *iobuf_out;
691 static int iobuf_out_cnt;
693 void io_start_buffering_out(void)
697 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
698 out_of_memory("io_start_buffering_out");
702 static char *iobuf_in;
703 static size_t iobuf_in_siz;
705 void io_start_buffering_in(void)
709 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
710 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
711 out_of_memory("io_start_buffering_in");
714 void io_end_buffering(void)
716 io_flush(NORMAL_FLUSH);
717 if (!io_multiplexing_out) {
723 void maybe_flush_socket(void)
725 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
726 io_flush(NORMAL_FLUSH);
729 void maybe_send_keepalive(void)
731 if (time(NULL) - last_io_out >= allowed_lull) {
732 if (!iobuf_out || !iobuf_out_cnt) {
733 if (protocol_version < 29)
734 return; /* there's nothing we can do */
735 write_int(sock_f_out, the_file_list->count);
736 write_shortint(sock_f_out, ITEM_IS_NEW);
739 io_flush(NORMAL_FLUSH);
744 * Continue trying to read len bytes - don't return until len has been
747 static void read_loop(int fd, char *buf, size_t len)
750 int n = read_timeout(fd, buf, len);
758 * Read from the file descriptor handling multiplexing - return number
761 * Never returns <= 0.
763 static int readfd_unbuffered(int fd, char *buf, size_t len)
765 static size_t remaining;
766 static size_t iobuf_in_ndx;
769 char line[BIGPATHBUFLEN];
771 if (!iobuf_in || fd != sock_f_in)
772 return read_timeout(fd, buf, len);
774 if (!io_multiplexing_in && remaining == 0) {
775 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
781 len = MIN(len, remaining);
782 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
789 read_loop(fd, line, 4);
792 msg_bytes = tag & 0xFFFFFF;
793 tag = (tag >> 24) - MPLEX_BASE;
797 if (msg_bytes > iobuf_in_siz) {
798 if (!(iobuf_in = realloc_array(iobuf_in, char,
800 out_of_memory("readfd_unbuffered");
801 iobuf_in_siz = msg_bytes;
803 read_loop(fd, iobuf_in, msg_bytes);
804 remaining = msg_bytes;
808 if (msg_bytes >= sizeof line)
810 read_loop(fd, line, msg_bytes);
811 /* A directory name was sent with the trailing null */
812 if (msg_bytes > 0 && !line[msg_bytes-1])
813 log_delete(line, S_IFDIR);
815 line[msg_bytes] = '\0';
816 log_delete(line, S_IFREG);
820 if (msg_bytes != 4) {
821 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
822 tag, (long)msg_bytes, who_am_i());
823 exit_cleanup(RERR_STREAMIO);
825 read_loop(fd, line, msg_bytes);
826 successful_send(IVAL(line, 0));
830 if (msg_bytes >= sizeof line) {
833 "multiplexing overflow %d:%ld [%s]\n",
834 tag, (long)msg_bytes, who_am_i());
835 exit_cleanup(RERR_STREAMIO);
837 read_loop(fd, line, msg_bytes);
838 rwrite((enum logcode)tag, line, msg_bytes);
841 rprintf(FERROR, "unexpected tag %d [%s]\n",
843 exit_cleanup(RERR_STREAMIO);
848 io_flush(NORMAL_FLUSH);
854 * Do a buffered read from @p fd. Don't return until all @p n bytes
855 * have been read. If all @p n can't be read then exit with an
858 static void readfd(int fd, char *buffer, size_t N)
864 cnt = readfd_unbuffered(fd, buffer + total, N-total);
868 if (fd == write_batch_monitor_in) {
869 if ((size_t)write(batch_fd, buffer, total) != total)
870 exit_cleanup(RERR_FILEIO);
874 stats.total_read += total;
877 int read_shortint(int f)
880 readfd(f, (char *)b, 2);
881 return (b[1] << 8) + b[0];
884 int32 read_int(int f)
891 if (num == (int32)0xffffffff)
896 int64 read_longint(int f)
902 if ((int32)num != (int32)0xffffffff)
906 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
907 exit_cleanup(RERR_UNSUPPORTED);
910 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
916 void read_buf(int f,char *buf,size_t len)
921 void read_sbuf(int f,char *buf,size_t len)
927 uchar read_byte(int f)
930 readfd(f, (char *)&c, 1);
934 int read_vstring(int f, char *buf, int bufsize)
936 int len = read_byte(f);
939 len = (len & ~0x80) * 0x100 + read_byte(f);
941 if (len >= bufsize) {
942 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
953 /* Populate a sum_struct with values from the socket. This is
954 * called by both the sender and the receiver. */
955 void read_sum_head(int f, struct sum_struct *sum)
957 sum->count = read_int(f);
958 if (sum->count < 0) {
959 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
960 (long)sum->count, who_am_i());
961 exit_cleanup(RERR_PROTOCOL);
963 sum->blength = read_int(f);
964 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
965 rprintf(FERROR, "Invalid block length %ld [%s]\n",
966 (long)sum->blength, who_am_i());
967 exit_cleanup(RERR_PROTOCOL);
969 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
970 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
971 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
972 sum->s2length, who_am_i());
973 exit_cleanup(RERR_PROTOCOL);
975 sum->remainder = read_int(f);
976 if (sum->remainder < 0 || sum->remainder > sum->blength) {
977 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
978 (long)sum->remainder, who_am_i());
979 exit_cleanup(RERR_PROTOCOL);
983 /* Send the values from a sum_struct over the socket. Set sum to
984 * NULL if there are no checksums to send. This is called by both
985 * the generator and the sender. */
986 void write_sum_head(int f, struct sum_struct *sum)
988 static struct sum_struct null_sum;
993 write_int(f, sum->count);
994 write_int(f, sum->blength);
995 if (protocol_version >= 27)
996 write_int(f, sum->s2length);
997 write_int(f, sum->remainder);
1001 * Sleep after writing to limit I/O bandwidth usage.
1003 * @todo Rather than sleeping after each write, it might be better to
1004 * use some kind of averaging. The current algorithm seems to always
1005 * use a bit less bandwidth than specified, because it doesn't make up
1006 * for slow periods. But arguably this is a feature. In addition, we
1007 * ought to take the time used to write the data into account.
1009 * During some phases of big transfers (file FOO is uptodate) this is
1010 * called with a small bytes_written every time. As the kernel has to
1011 * round small waits up to guarantee that we actually wait at least the
1012 * requested number of microseconds, this can become grossly inaccurate.
1013 * We therefore keep track of the bytes we've written over time and only
1014 * sleep when the accumulated delay is at least 1 tenth of a second.
1016 static void sleep_for_bwlimit(int bytes_written)
1018 static struct timeval prior_tv;
1019 static long total_written = 0;
1020 struct timeval tv, start_tv;
1021 long elapsed_usec, sleep_usec;
1023 #define ONE_SEC 1000000L /* # of microseconds in a second */
1025 if (!bwlimit_writemax)
1028 total_written += bytes_written;
1030 gettimeofday(&start_tv, NULL);
1031 if (prior_tv.tv_sec) {
1032 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1033 + (start_tv.tv_usec - prior_tv.tv_usec);
1034 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1035 if (total_written < 0)
1039 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1040 if (sleep_usec < ONE_SEC / 10) {
1041 prior_tv = start_tv;
1045 tv.tv_sec = sleep_usec / ONE_SEC;
1046 tv.tv_usec = sleep_usec % ONE_SEC;
1047 select(0, NULL, NULL, NULL, &tv);
1049 gettimeofday(&prior_tv, NULL);
1050 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1051 + (prior_tv.tv_usec - start_tv.tv_usec);
1052 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1055 /* Write len bytes to the file descriptor fd, looping as necessary to get
1056 * the job done and also (in certain circumstances) reading any data on
1057 * msg_fd_in to avoid deadlock.
1059 * This function underlies the multiplexing system. The body of the
1060 * application never calls this function directly. */
1061 static void writefd_unbuffered(int fd,char *buf,size_t len)
1063 size_t n, total = 0;
1064 fd_set w_fds, r_fds;
1065 int maxfd, count, cnt, using_r_fds;
1066 int defer_save = defer_forwarding_messages;
1071 while (total < len) {
1076 if (msg_fd_in >= 0) {
1078 FD_SET(msg_fd_in,&r_fds);
1079 if (msg_fd_in > maxfd)
1085 tv.tv_sec = select_timeout;
1089 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1093 if (count < 0 && errno == EBADF)
1094 exit_cleanup(RERR_SOCKETIO);
1099 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1102 if (!FD_ISSET(fd, &w_fds))
1106 if (bwlimit_writemax && n > bwlimit_writemax)
1107 n = bwlimit_writemax;
1108 cnt = write(fd, buf + total, n);
1114 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1120 /* Don't try to write errors back across the stream. */
1121 if (fd == sock_f_out)
1122 close_multiplexing_out();
1123 rsyserr(FERROR, errno,
1124 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1125 (long)len, io_write_phase, who_am_i());
1126 /* If the other side is sending us error messages, try
1127 * to grab any messages they sent before they died. */
1128 while (fd == sock_f_out && io_multiplexing_in) {
1131 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1132 sizeof io_filesfrom_buf);
1134 exit_cleanup(RERR_STREAMIO);
1138 defer_forwarding_messages = 1;
1140 if (fd == sock_f_out) {
1141 if (io_timeout || am_generator)
1142 last_io_out = time(NULL);
1143 sleep_for_bwlimit(cnt);
1147 defer_forwarding_messages = defer_save;
1151 static void msg2sndr_flush(void)
1153 if (defer_forwarding_messages)
1156 while (msg2sndr.head && io_multiplexing_out) {
1157 struct msg_list_item *m = msg2sndr.head;
1158 if (!(msg2sndr.head = m->next))
1159 msg2sndr.tail = NULL;
1160 stats.total_written += m->len;
1161 defer_forwarding_messages = 1;
1162 writefd_unbuffered(sock_f_out, m->buf, m->len);
1163 defer_forwarding_messages = 0;
1169 * Write an message to a multiplexed stream. If this fails then rsync
1172 static void mplex_write(enum msgcode code, char *buf, size_t len)
1177 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1179 if (n > sizeof buffer - 4)
1182 memcpy(buffer + 4, buf, n);
1184 writefd_unbuffered(sock_f_out, buffer, n+4);
1190 defer_forwarding_messages = 1;
1191 writefd_unbuffered(sock_f_out, buf, len);
1192 defer_forwarding_messages = 0;
1197 void io_flush(int flush_it_all)
1199 msg2genr_flush(flush_it_all);
1202 if (!iobuf_out_cnt || no_flush)
1205 if (io_multiplexing_out)
1206 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1208 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1212 static void writefd(int fd,char *buf,size_t len)
1214 if (fd == msg_fd_out) {
1215 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1216 exit_cleanup(RERR_PROTOCOL);
1219 if (fd == sock_f_out)
1220 stats.total_written += len;
1222 if (fd == write_batch_monitor_out) {
1223 if ((size_t)write(batch_fd, buf, len) != len)
1224 exit_cleanup(RERR_FILEIO);
1227 if (!iobuf_out || fd != sock_f_out) {
1228 writefd_unbuffered(fd, buf, len);
1233 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1235 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1241 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1242 io_flush(NORMAL_FLUSH);
1246 void write_shortint(int f, int x)
1251 writefd(f, (char *)b, 2);
1254 void write_int(int f,int32 x)
1261 void write_int_named(int f, int32 x, const char *phase)
1263 io_write_phase = phase;
1265 io_write_phase = phase_unknown;
1269 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1270 * 64-bit types on this platform.
1272 void write_longint(int f, int64 x)
1276 if (x <= 0x7FFFFFFF) {
1277 write_int(f, (int)x);
1281 #if SIZEOF_INT64 < 8
1282 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1283 exit_cleanup(RERR_UNSUPPORTED);
1285 write_int(f, (int32)0xFFFFFFFF);
1286 SIVAL(b,0,(x&0xFFFFFFFF));
1287 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1293 void write_buf(int f,char *buf,size_t len)
1298 /** Write a string to the connection */
1299 void write_sbuf(int f, char *buf)
1301 writefd(f, buf, strlen(buf));
1304 void write_byte(int f, uchar c)
1306 writefd(f, (char *)&c, 1);
1309 void write_vstring(int f, char *str, int len)
1311 uchar lenbuf[3], *lb = lenbuf;
1316 "attempting to send over-long vstring (%d > %d)\n",
1318 exit_cleanup(RERR_PROTOCOL);
1320 *lb++ = len / 0x100 + 0x80;
1324 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1326 writefd(f, str, len);
1330 * Read a line of up to @p maxlen characters into @p buf (not counting
1331 * the trailing null). Strips the (required) trailing newline and all
1334 * @return 1 for success; 0 for I/O error or truncation.
1336 int read_line(int f, char *buf, size_t maxlen)
1340 read_buf(f, buf, 1);
1345 if (buf[0] != '\r') {
1354 void io_printf(int fd, const char *format, ...)
1357 char buf[BIGPATHBUFLEN];
1360 va_start(ap, format);
1361 len = vsnprintf(buf, sizeof buf, format, ap);
1365 exit_cleanup(RERR_STREAMIO);
1367 if (len > (int)sizeof buf) {
1368 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1369 exit_cleanup(RERR_STREAMIO);
1372 write_sbuf(fd, buf);
1375 /** Setup for multiplexing a MSG_* stream with the data stream. */
1376 void io_start_multiplex_out(void)
1378 io_flush(NORMAL_FLUSH);
1379 io_start_buffering_out();
1380 io_multiplexing_out = 1;
1383 /** Setup for multiplexing a MSG_* stream with the data stream. */
1384 void io_start_multiplex_in(void)
1386 io_flush(NORMAL_FLUSH);
1387 io_start_buffering_in();
1388 io_multiplexing_in = 1;
1391 /** Write an message to the multiplexed data stream. */
1392 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1394 if (!io_multiplexing_out)
1397 io_flush(NORMAL_FLUSH);
1398 stats.total_written += (len+4);
1399 mplex_write(code, buf, len);
1403 void close_multiplexing_in(void)
1405 io_multiplexing_in = 0;
1408 /** Stop output multiplexing. */
1409 void close_multiplexing_out(void)
1411 io_multiplexing_out = 0;
1414 void start_write_batch(int fd)
1416 write_stream_flags(batch_fd);
1418 /* Some communication has already taken place, but we don't
1419 * enable batch writing until here so that we can write a
1420 * canonical record of the communication even though the
1421 * actual communication so far depends on whether a daemon
1423 write_int(batch_fd, protocol_version);
1424 write_int(batch_fd, checksum_seed);
1427 write_batch_monitor_out = fd;
1429 write_batch_monitor_in = fd;
1432 void stop_write_batch(void)
1434 write_batch_monitor_out = -1;
1435 write_batch_monitor_in = -1;