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 size_t contiguous_write_len = 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 msg_list;
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(int code, char *buf, int len)
231 struct msg_list_item *ml;
233 if (!(ml = new(struct msg_list_item)))
234 out_of_memory("msg_list_add");
236 if (!(ml->buf = new_array(char, len+4)))
237 out_of_memory("msg_list_add");
238 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
239 memcpy(ml->buf+4, buf, len);
242 msg_list.tail->next = ml;
248 /* Read a message from the MSG_* fd and handle it. This is called either
249 * during the early stages of being a local sender (up through the sending
250 * of the file list) or when we're the generator (to fetch the messages
251 * from the receiver). */
252 static void read_msg_fd(void)
259 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
260 * to this routine from writefd_unbuffered(). */
263 read_loop(fd, buf, 4);
266 len = tag & 0xFFFFFF;
267 tag = (tag >> 24) - MPLEX_BASE;
271 if (len != 0 || !am_generator) {
272 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
273 exit_cleanup(RERR_STREAMIO);
275 flist_ndx_push(&redo_list, -1);
278 if (len != 4 || !am_generator) {
279 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
280 exit_cleanup(RERR_STREAMIO);
282 read_loop(fd, buf, 4);
283 if (remove_sent_files)
284 decrement_active_files(IVAL(buf,0));
285 flist_ndx_push(&redo_list, IVAL(buf,0));
288 if (len >= (int)sizeof buf || !am_generator) {
289 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
290 exit_cleanup(RERR_STREAMIO);
292 read_loop(fd, buf, len);
293 io_multiplex_write(MSG_DELETED, buf, len);
296 if (len != 4 || !am_generator) {
297 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
298 exit_cleanup(RERR_STREAMIO);
300 read_loop(fd, buf, len);
301 if (remove_sent_files) {
302 decrement_active_files(IVAL(buf,0));
303 io_multiplex_write(MSG_SUCCESS, buf, len);
305 if (preserve_hard_links)
306 flist_ndx_push(&hlink_list, IVAL(buf,0));
310 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
311 exit_cleanup(RERR_STREAMIO);
313 close_multiplexing_out();
322 read_loop(fd, buf, n);
323 rwrite((enum logcode)tag, buf, n);
328 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
329 exit_cleanup(RERR_STREAMIO);
335 /* This is used by the generator to limit how many file transfers can
336 * be active at once when --remove-sent-files is specified. Without
337 * this, sender-side deletions were mostly happening at the end. */
338 void increment_active_files(int ndx, int itemizing, enum logcode code)
340 /* TODO: tune these limits? */
341 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
343 check_for_finished_hlinks(itemizing, code);
348 active_bytecnt += the_file_list->files[ndx]->length;
351 void decrement_active_files(int ndx)
354 active_bytecnt -= the_file_list->files[ndx]->length;
357 /* Try to push messages off the list onto the wire. If we leave with more
358 * to do, return 0. On error, return -1. If everything flushed, return 1.
359 * This is only active in the receiver. */
360 static int msg_list_flush(int flush_it_all)
362 static int written = 0;
369 while (msg_list.head) {
370 struct msg_list_item *ml = msg_list.head;
371 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
375 if (errno != EWOULDBLOCK && errno != EAGAIN)
380 FD_SET(msg_fd_out, &fds);
381 tv.tv_sec = select_timeout;
383 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
385 } else if ((written += n) == ml->len) {
387 msg_list.head = ml->next;
389 msg_list.tail = NULL;
397 void send_msg(enum msgcode code, char *buf, int len)
399 if (msg_fd_out < 0) {
400 io_multiplex_write(code, buf, len);
403 msg_list_add(code, buf, len);
404 msg_list_flush(NORMAL_FLUSH);
407 int get_redo_num(int itemizing, enum logcode code)
411 check_for_finished_hlinks(itemizing, code);
417 return flist_ndx_pop(&redo_list);
420 int get_hlink_num(void)
422 return flist_ndx_pop(&hlink_list);
426 * When we're the receiver and we have a local --files-from list of names
427 * that needs to be sent over the socket to the sender, we have to do two
428 * things at the same time: send the sender a list of what files we're
429 * processing and read the incoming file+info list from the sender. We do
430 * this by augmenting the read_timeout() function to copy this data. It
431 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
432 * ready, since it might be a pipe) and then blast it out f_out (when it
433 * is ready to receive more data).
435 void io_set_filesfrom_fds(int f_in, int f_out)
437 io_filesfrom_f_in = f_in;
438 io_filesfrom_f_out = f_out;
439 io_filesfrom_bp = io_filesfrom_buf;
440 io_filesfrom_lastchar = '\0';
441 io_filesfrom_buflen = 0;
444 /* It's almost always an error to get an EOF when we're trying to read from the
445 * network, because the protocol is (for the most part) self-terminating.
447 * There is one case for the receiver when it is at the end of the transfer
448 * (hanging around reading any keep-alive packets that might come its way): if
449 * the sender dies before the generator's kill-signal comes through, we can end
450 * up here needing to loop until the kill-signal arrives. In this situation,
451 * kluge_around_eof will be < 0.
453 * There is another case for older protocol versions (< 24) where the module
454 * listing was not terminated, so we must ignore an EOF error in that case and
455 * exit. In this situation, kluge_around_eof will be > 0. */
456 static void whine_about_eof(int fd)
458 if (kluge_around_eof && fd == sock_f_in) {
460 if (kluge_around_eof > 0)
462 /* If we're still here after 10 seconds, exit with an error. */
463 for (i = 10*1000/20; i--; )
467 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
468 "(%.0f bytes received so far) [%s]\n",
469 (double)stats.total_read, who_am_i());
471 exit_cleanup(RERR_STREAMIO);
475 * Read from a socket with I/O timeout. return the number of bytes
476 * read. If no bytes can be read then exit, never return a number <= 0.
478 * TODO: If the remote shell connection fails, then current versions
479 * actually report an "unexpected EOF" error here. Since it's a
480 * fairly common mistake to try to use rsh when ssh is required, we
481 * should trap that: if we fail to read any data at all, we should
482 * give a better explanation. We can tell whether the connection has
483 * started by looking e.g. at whether the remote version is known yet.
485 static int read_timeout(int fd, char *buf, size_t len)
489 io_flush(NORMAL_FLUSH);
492 /* until we manage to read *something* */
502 FD_SET(msg_fd_out, &w_fds);
503 if (msg_fd_out > maxfd)
506 if (io_filesfrom_f_out >= 0) {
508 if (io_filesfrom_buflen == 0) {
509 if (io_filesfrom_f_in >= 0) {
510 FD_SET(io_filesfrom_f_in, &r_fds);
511 new_fd = io_filesfrom_f_in;
513 io_filesfrom_f_out = -1;
517 FD_SET(io_filesfrom_f_out, &w_fds);
518 new_fd = io_filesfrom_f_out;
524 tv.tv_sec = select_timeout;
529 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
533 exit_cleanup(RERR_SOCKETIO);
538 if (msg_list.head && FD_ISSET(msg_fd_out, &w_fds))
539 msg_list_flush(NORMAL_FLUSH);
541 if (io_filesfrom_f_out >= 0) {
542 if (io_filesfrom_buflen) {
543 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
544 int l = write(io_filesfrom_f_out,
546 io_filesfrom_buflen);
548 if (!(io_filesfrom_buflen -= l))
549 io_filesfrom_bp = io_filesfrom_buf;
551 io_filesfrom_bp += l;
553 /* XXX should we complain? */
554 io_filesfrom_f_out = -1;
557 } else if (io_filesfrom_f_in >= 0) {
558 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
559 int l = read(io_filesfrom_f_in,
561 sizeof io_filesfrom_buf);
563 /* Send end-of-file marker */
564 io_filesfrom_buf[0] = '\0';
565 io_filesfrom_buf[1] = '\0';
566 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
567 io_filesfrom_f_in = -1;
570 char *s = io_filesfrom_buf + l;
571 /* Transform CR and/or LF into '\0' */
572 while (s-- > io_filesfrom_buf) {
573 if (*s == '\n' || *s == '\r')
577 if (!io_filesfrom_lastchar) {
578 /* Last buf ended with a '\0', so don't
579 * let this buf start with one. */
580 while (l && !*io_filesfrom_bp)
581 io_filesfrom_bp++, l--;
584 io_filesfrom_bp = io_filesfrom_buf;
586 char *f = io_filesfrom_bp;
589 /* Eliminate any multi-'\0' runs. */
591 if (!(*t++ = *f++)) {
592 while (f != eob && !*f)
596 io_filesfrom_lastchar = f[-1];
598 io_filesfrom_buflen = l;
604 if (!FD_ISSET(fd, &r_fds))
607 n = read(fd, buf, len);
611 whine_about_eof(fd); /* Doesn't return. */
612 if (errno == EINTR || errno == EWOULDBLOCK
616 /* Don't write errors on a dead socket. */
617 if (fd == sock_f_in) {
618 close_multiplexing_out();
619 rsyserr(FSOCKERR, errno, "read error");
621 rsyserr(FERROR, errno, "read error");
622 exit_cleanup(RERR_STREAMIO);
629 if (fd == sock_f_in && io_timeout)
630 last_io_in = time(NULL);
637 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
640 int read_filesfrom_line(int fd, char *fname)
642 char ch, *s, *eob = fname + MAXPATHLEN - 1;
644 int reading_remotely = filesfrom_host != NULL;
645 int nulls = eol_nulls || reading_remotely;
650 cnt = read(fd, &ch, 1);
651 if (cnt < 0 && (errno == EWOULDBLOCK
652 || errno == EINTR || errno == EAGAIN)) {
657 tv.tv_sec = select_timeout;
659 if (!select(fd+1, &fds, NULL, NULL, &tv))
665 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
666 /* Skip empty lines if reading locally. */
667 if (!reading_remotely && s == fname)
677 if (*fname == '#' || *fname == ';')
683 static char *iobuf_out;
684 static int iobuf_out_cnt;
686 void io_start_buffering_out(void)
690 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
691 out_of_memory("io_start_buffering_out");
695 static char *iobuf_in;
696 static size_t iobuf_in_siz;
698 void io_start_buffering_in(void)
702 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
703 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
704 out_of_memory("io_start_buffering_in");
707 void io_end_buffering(void)
709 io_flush(NORMAL_FLUSH);
710 if (!io_multiplexing_out) {
716 void maybe_flush_socket(void)
718 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
719 io_flush(NORMAL_FLUSH);
722 void maybe_send_keepalive(void)
724 if (time(NULL) - last_io_out >= allowed_lull) {
725 if (!iobuf_out || !iobuf_out_cnt) {
726 if (protocol_version < 29)
727 return; /* there's nothing we can do */
728 write_int(sock_f_out, the_file_list->count);
729 write_shortint(sock_f_out, ITEM_IS_NEW);
732 io_flush(NORMAL_FLUSH);
737 * Continue trying to read len bytes - don't return until len has been
740 static void read_loop(int fd, char *buf, size_t len)
743 int n = read_timeout(fd, buf, len);
751 * Read from the file descriptor handling multiplexing - return number
754 * Never returns <= 0.
756 static int readfd_unbuffered(int fd, char *buf, size_t len)
758 static size_t remaining;
759 static size_t iobuf_in_ndx;
762 char line[BIGPATHBUFLEN];
764 if (!iobuf_in || fd != sock_f_in)
765 return read_timeout(fd, buf, len);
767 if (!io_multiplexing_in && remaining == 0) {
768 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
774 len = MIN(len, remaining);
775 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
782 read_loop(fd, line, 4);
785 msg_bytes = tag & 0xFFFFFF;
786 tag = (tag >> 24) - MPLEX_BASE;
790 if (msg_bytes > iobuf_in_siz) {
791 if (!(iobuf_in = realloc_array(iobuf_in, char,
793 out_of_memory("readfd_unbuffered");
794 iobuf_in_siz = msg_bytes;
796 read_loop(fd, iobuf_in, msg_bytes);
797 remaining = msg_bytes;
801 if (msg_bytes >= sizeof line)
803 read_loop(fd, line, msg_bytes);
804 /* A directory name was sent with the trailing null */
805 if (msg_bytes > 0 && !line[msg_bytes-1])
806 log_delete(line, S_IFDIR);
808 line[msg_bytes] = '\0';
809 log_delete(line, S_IFREG);
813 if (msg_bytes != 4) {
814 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
815 tag, (long)msg_bytes, who_am_i());
816 exit_cleanup(RERR_STREAMIO);
818 read_loop(fd, line, msg_bytes);
819 successful_send(IVAL(line, 0));
823 if (msg_bytes >= sizeof line) {
826 "multiplexing overflow %d:%ld [%s]\n",
827 tag, (long)msg_bytes, who_am_i());
828 exit_cleanup(RERR_STREAMIO);
830 read_loop(fd, line, msg_bytes);
831 rwrite((enum logcode)tag, line, msg_bytes);
834 rprintf(FERROR, "unexpected tag %d [%s]\n",
836 exit_cleanup(RERR_STREAMIO);
841 io_flush(NORMAL_FLUSH);
847 * Do a buffered read from @p fd. Don't return until all @p n bytes
848 * have been read. If all @p n can't be read then exit with an
851 static void readfd(int fd, char *buffer, size_t N)
857 cnt = readfd_unbuffered(fd, buffer + total, N-total);
861 if (fd == write_batch_monitor_in) {
862 if ((size_t)write(batch_fd, buffer, total) != total)
863 exit_cleanup(RERR_FILEIO);
867 stats.total_read += total;
870 int read_shortint(int f)
873 readfd(f, (char *)b, 2);
874 return (b[1] << 8) + b[0];
877 int32 read_int(int f)
884 if (num == (int32)0xffffffff)
889 int64 read_longint(int f)
895 if ((int32)num != (int32)0xffffffff)
899 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
900 exit_cleanup(RERR_UNSUPPORTED);
903 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
909 void read_buf(int f,char *buf,size_t len)
914 void read_sbuf(int f,char *buf,size_t len)
920 uchar read_byte(int f)
923 readfd(f, (char *)&c, 1);
927 int read_vstring(int f, char *buf, int bufsize)
929 int len = read_byte(f);
932 len = (len & ~0x80) * 0x100 + read_byte(f);
934 if (len >= bufsize) {
935 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
946 /* Populate a sum_struct with values from the socket. This is
947 * called by both the sender and the receiver. */
948 void read_sum_head(int f, struct sum_struct *sum)
950 sum->count = read_int(f);
951 if (sum->count < 0) {
952 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
953 (long)sum->count, who_am_i());
954 exit_cleanup(RERR_PROTOCOL);
956 sum->blength = read_int(f);
957 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
958 rprintf(FERROR, "Invalid block length %ld [%s]\n",
959 (long)sum->blength, who_am_i());
960 exit_cleanup(RERR_PROTOCOL);
962 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
963 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
964 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
965 sum->s2length, who_am_i());
966 exit_cleanup(RERR_PROTOCOL);
968 sum->remainder = read_int(f);
969 if (sum->remainder < 0 || sum->remainder > sum->blength) {
970 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
971 (long)sum->remainder, who_am_i());
972 exit_cleanup(RERR_PROTOCOL);
976 /* Send the values from a sum_struct over the socket. Set sum to
977 * NULL if there are no checksums to send. This is called by both
978 * the generator and the sender. */
979 void write_sum_head(int f, struct sum_struct *sum)
981 static struct sum_struct null_sum;
986 write_int(f, sum->count);
987 write_int(f, sum->blength);
988 if (protocol_version >= 27)
989 write_int(f, sum->s2length);
990 write_int(f, sum->remainder);
994 * Sleep after writing to limit I/O bandwidth usage.
996 * @todo Rather than sleeping after each write, it might be better to
997 * use some kind of averaging. The current algorithm seems to always
998 * use a bit less bandwidth than specified, because it doesn't make up
999 * for slow periods. But arguably this is a feature. In addition, we
1000 * ought to take the time used to write the data into account.
1002 * During some phases of big transfers (file FOO is uptodate) this is
1003 * called with a small bytes_written every time. As the kernel has to
1004 * round small waits up to guarantee that we actually wait at least the
1005 * requested number of microseconds, this can become grossly inaccurate.
1006 * We therefore keep track of the bytes we've written over time and only
1007 * sleep when the accumulated delay is at least 1 tenth of a second.
1009 static void sleep_for_bwlimit(int bytes_written)
1011 static struct timeval prior_tv;
1012 static long total_written = 0;
1013 struct timeval tv, start_tv;
1014 long elapsed_usec, sleep_usec;
1016 #define ONE_SEC 1000000L /* # of microseconds in a second */
1018 if (!bwlimit_writemax)
1021 total_written += bytes_written;
1023 gettimeofday(&start_tv, NULL);
1024 if (prior_tv.tv_sec) {
1025 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1026 + (start_tv.tv_usec - prior_tv.tv_usec);
1027 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1028 if (total_written < 0)
1032 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1033 if (sleep_usec < ONE_SEC / 10) {
1034 prior_tv = start_tv;
1038 tv.tv_sec = sleep_usec / ONE_SEC;
1039 tv.tv_usec = sleep_usec % ONE_SEC;
1040 select(0, NULL, NULL, NULL, &tv);
1042 gettimeofday(&prior_tv, NULL);
1043 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1044 + (prior_tv.tv_usec - start_tv.tv_usec);
1045 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1048 /* Write len bytes to the file descriptor fd, looping as necessary to get
1049 * the job done and also (in certain circumstances) reading any data on
1050 * msg_fd_in to avoid deadlock.
1052 * This function underlies the multiplexing system. The body of the
1053 * application never calls this function directly. */
1054 static void writefd_unbuffered(int fd,char *buf,size_t len)
1056 size_t n, total = 0;
1057 fd_set w_fds, r_fds;
1058 int maxfd, count, cnt, using_r_fds;
1063 while (total < len) {
1068 if (msg_fd_in >= 0 && len-total >= contiguous_write_len) {
1070 FD_SET(msg_fd_in,&r_fds);
1071 if (msg_fd_in > maxfd)
1077 tv.tv_sec = select_timeout;
1081 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1085 if (count < 0 && errno == EBADF)
1086 exit_cleanup(RERR_SOCKETIO);
1091 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1094 if (!FD_ISSET(fd, &w_fds))
1098 if (bwlimit_writemax && n > bwlimit_writemax)
1099 n = bwlimit_writemax;
1100 cnt = write(fd, buf + total, n);
1106 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1112 /* Don't try to write errors back across the stream. */
1113 if (fd == sock_f_out)
1114 close_multiplexing_out();
1115 rsyserr(FERROR, errno,
1116 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1117 (long)len, io_write_phase, who_am_i());
1118 /* If the other side is sending us error messages, try
1119 * to grab any messages they sent before they died. */
1120 while (fd == sock_f_out && io_multiplexing_in) {
1123 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1124 sizeof io_filesfrom_buf);
1126 exit_cleanup(RERR_STREAMIO);
1131 if (fd == sock_f_out) {
1132 if (io_timeout || am_generator)
1133 last_io_out = time(NULL);
1134 sleep_for_bwlimit(cnt);
1142 * Write an message to a multiplexed stream. If this fails then rsync
1145 static void mplex_write(enum msgcode code, char *buf, size_t len)
1150 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1152 /* When the generator reads messages from the msg_fd_in pipe, it can
1153 * cause output to occur down the socket. Setting contiguous_write_len
1154 * prevents the reading of msg_fd_in once we actually start to write
1155 * this sequence of data (though we might read it before the start). */
1156 if (am_generator && msg_fd_in >= 0)
1157 contiguous_write_len = len + 4;
1159 if (n > sizeof buffer - 4)
1162 memcpy(buffer + 4, buf, n);
1164 writefd_unbuffered(sock_f_out, buffer, n+4);
1170 writefd_unbuffered(sock_f_out, buf, len);
1172 if (am_generator && msg_fd_in >= 0)
1173 contiguous_write_len = 0;
1176 void io_flush(int flush_it_all)
1178 msg_list_flush(flush_it_all);
1180 if (!iobuf_out_cnt || no_flush)
1183 if (io_multiplexing_out)
1184 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1186 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1190 static void writefd(int fd,char *buf,size_t len)
1192 if (fd == msg_fd_out) {
1193 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1194 exit_cleanup(RERR_PROTOCOL);
1197 if (fd == sock_f_out)
1198 stats.total_written += len;
1200 if (fd == write_batch_monitor_out) {
1201 if ((size_t)write(batch_fd, buf, len) != len)
1202 exit_cleanup(RERR_FILEIO);
1205 if (!iobuf_out || fd != sock_f_out) {
1206 writefd_unbuffered(fd, buf, len);
1211 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1213 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1219 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1220 io_flush(NORMAL_FLUSH);
1224 void write_shortint(int f, int x)
1229 writefd(f, (char *)b, 2);
1232 void write_int(int f,int32 x)
1239 void write_int_named(int f, int32 x, const char *phase)
1241 io_write_phase = phase;
1243 io_write_phase = phase_unknown;
1247 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1248 * 64-bit types on this platform.
1250 void write_longint(int f, int64 x)
1254 if (x <= 0x7FFFFFFF) {
1255 write_int(f, (int)x);
1259 #if SIZEOF_INT64 < 8
1260 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1261 exit_cleanup(RERR_UNSUPPORTED);
1263 write_int(f, (int32)0xFFFFFFFF);
1264 SIVAL(b,0,(x&0xFFFFFFFF));
1265 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1271 void write_buf(int f,char *buf,size_t len)
1276 /** Write a string to the connection */
1277 void write_sbuf(int f, char *buf)
1279 writefd(f, buf, strlen(buf));
1282 void write_byte(int f, uchar c)
1284 writefd(f, (char *)&c, 1);
1287 void write_vstring(int f, char *str, int len)
1289 uchar lenbuf[3], *lb = lenbuf;
1294 "attempting to send over-long vstring (%d > %d)\n",
1296 exit_cleanup(RERR_PROTOCOL);
1298 *lb++ = len / 0x100 + 0x80;
1302 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1304 writefd(f, str, len);
1308 * Read a line of up to @p maxlen characters into @p buf (not counting
1309 * the trailing null). Strips the (required) trailing newline and all
1312 * @return 1 for success; 0 for I/O error or truncation.
1314 int read_line(int f, char *buf, size_t maxlen)
1318 read_buf(f, buf, 1);
1323 if (buf[0] != '\r') {
1332 void io_printf(int fd, const char *format, ...)
1335 char buf[BIGPATHBUFLEN];
1338 va_start(ap, format);
1339 len = vsnprintf(buf, sizeof buf, format, ap);
1343 exit_cleanup(RERR_STREAMIO);
1345 if (len > (int)sizeof buf) {
1346 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1347 exit_cleanup(RERR_STREAMIO);
1350 write_sbuf(fd, buf);
1353 /** Setup for multiplexing a MSG_* stream with the data stream. */
1354 void io_start_multiplex_out(void)
1356 io_flush(NORMAL_FLUSH);
1357 io_start_buffering_out();
1358 io_multiplexing_out = 1;
1361 /** Setup for multiplexing a MSG_* stream with the data stream. */
1362 void io_start_multiplex_in(void)
1364 io_flush(NORMAL_FLUSH);
1365 io_start_buffering_in();
1366 io_multiplexing_in = 1;
1369 /** Write an message to the multiplexed data stream. */
1370 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1372 if (!io_multiplexing_out)
1375 io_flush(NORMAL_FLUSH);
1376 stats.total_written += (len+4);
1377 mplex_write(code, buf, len);
1381 void close_multiplexing_in(void)
1383 io_multiplexing_in = 0;
1386 /** Stop output multiplexing. */
1387 void close_multiplexing_out(void)
1389 io_multiplexing_out = 0;
1392 void start_write_batch(int fd)
1394 write_stream_flags(batch_fd);
1396 /* Some communication has already taken place, but we don't
1397 * enable batch writing until here so that we can write a
1398 * canonical record of the communication even though the
1399 * actual communication so far depends on whether a daemon
1401 write_int(batch_fd, protocol_version);
1402 write_int(batch_fd, checksum_seed);
1405 write_batch_monitor_out = fd;
1407 write_batch_monitor_in = fd;
1410 void stop_write_batch(void)
1412 write_batch_monitor_out = -1;
1413 write_batch_monitor_in = -1;