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;
45 extern int read_batch;
46 extern int csum_length;
47 extern int checksum_seed;
48 extern int protocol_version;
49 extern int remove_sent_files;
50 extern int preserve_hard_links;
51 extern char *filesfrom_host;
52 extern struct stats stats;
53 extern struct file_list *the_file_list;
55 const char phase_unknown[] = "unknown";
56 int ignore_timeout = 0;
58 int batch_gen_fd = -1;
60 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
61 int kluge_around_eof = 0;
68 static int io_multiplexing_out;
69 static int io_multiplexing_in;
70 static time_t last_io_in;
71 static time_t last_io_out;
74 static int write_batch_monitor_in = -1;
75 static int write_batch_monitor_out = -1;
77 static int io_filesfrom_f_in = -1;
78 static int io_filesfrom_f_out = -1;
79 static char io_filesfrom_buf[2048];
80 static char *io_filesfrom_bp;
81 static char io_filesfrom_lastchar;
82 static int io_filesfrom_buflen;
83 static int defer_forwarding_messages = 0;
84 static int select_timeout = SELECT_TIMEOUT;
85 static int active_filecnt = 0;
86 static OFF_T active_bytecnt = 0;
88 static void read_loop(int fd, char *buf, size_t len);
90 struct flist_ndx_item {
91 struct flist_ndx_item *next;
95 struct flist_ndx_list {
96 struct flist_ndx_item *head, *tail;
99 static struct flist_ndx_list redo_list, hlink_list;
101 struct msg_list_item {
102 struct msg_list_item *next;
108 struct msg_list_item *head, *tail;
111 static struct msg_list msg2genr, msg2sndr;
113 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
115 struct flist_ndx_item *item;
117 if (!(item = new(struct flist_ndx_item)))
118 out_of_memory("flist_ndx_push");
122 lp->tail->next = item;
128 static int flist_ndx_pop(struct flist_ndx_list *lp)
130 struct flist_ndx_item *next;
137 next = lp->head->next;
146 static void check_timeout(void)
150 if (!io_timeout || ignore_timeout)
154 last_io_in = time(NULL);
160 if (t - last_io_in >= io_timeout) {
161 if (!am_server && !am_daemon) {
162 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
163 (int)(t-last_io_in));
165 exit_cleanup(RERR_TIMEOUT);
169 /* Note the fds used for the main socket (which might really be a pipe
170 * for a local transfer, but we can ignore that). */
171 void io_set_sock_fds(int f_in, int f_out)
177 void set_io_timeout(int secs)
181 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
182 select_timeout = SELECT_TIMEOUT;
184 select_timeout = io_timeout;
186 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
189 /* Setup the fd used to receive MSG_* messages. Only needed during the
190 * early stages of being a local sender (up through the sending of the
191 * file list) or when we're the generator (to fetch the messages from
193 void set_msg_fd_in(int fd)
198 /* Setup the fd used to send our MSG_* messages. Only needed when
199 * we're the receiver (to send our messages to the generator). */
200 void set_msg_fd_out(int fd)
203 set_nonblocking(msg_fd_out);
206 /* Add a message to the pending MSG_* list. */
207 static void msg_list_add(struct msg_list *lst, int code, char *buf, int len)
209 struct msg_list_item *m;
210 int sz = len + 4 + sizeof m[0] - 1;
212 if (!(m = (struct msg_list_item *)new_array(char, sz)))
213 out_of_memory("msg_list_add");
216 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
217 memcpy(m->buf + 4, buf, len);
225 /* Read a message from the MSG_* fd and handle it. This is called either
226 * during the early stages of being a local sender (up through the sending
227 * of the file list) or when we're the generator (to fetch the messages
228 * from the receiver). */
229 static void read_msg_fd(void)
236 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
237 * to this routine from writefd_unbuffered(). */
240 read_loop(fd, buf, 4);
243 len = tag & 0xFFFFFF;
244 tag = (tag >> 24) - MPLEX_BASE;
248 if (len != 0 || !am_generator) {
249 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
250 exit_cleanup(RERR_STREAMIO);
252 flist_ndx_push(&redo_list, -1);
255 if (len != 4 || !am_generator) {
256 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
257 exit_cleanup(RERR_STREAMIO);
259 read_loop(fd, buf, 4);
260 if (remove_sent_files)
261 decrement_active_files(IVAL(buf,0));
262 flist_ndx_push(&redo_list, IVAL(buf,0));
265 if (len >= (int)sizeof buf || !am_generator) {
266 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
267 exit_cleanup(RERR_STREAMIO);
269 read_loop(fd, buf, len);
270 if (defer_forwarding_messages)
271 msg_list_add(&msg2sndr, MSG_DELETED, buf, len);
273 io_multiplex_write(MSG_DELETED, buf, len);
276 if (len != 4 || !am_generator) {
277 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
278 exit_cleanup(RERR_STREAMIO);
280 read_loop(fd, buf, len);
281 if (remove_sent_files) {
282 decrement_active_files(IVAL(buf,0));
283 if (defer_forwarding_messages)
284 msg_list_add(&msg2sndr, MSG_SUCCESS, buf, len);
286 io_multiplex_write(MSG_SUCCESS, buf, len);
288 if (preserve_hard_links)
289 flist_ndx_push(&hlink_list, IVAL(buf,0));
293 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
294 exit_cleanup(RERR_STREAMIO);
296 close_multiplexing_out();
305 read_loop(fd, buf, n);
306 if (am_generator && am_server && defer_forwarding_messages)
307 msg_list_add(&msg2sndr, tag, buf, n);
309 rwrite((enum logcode)tag, buf, n);
314 rprintf(FERROR, "unknown message %d:%d [%s]\n",
315 tag, len, who_am_i());
316 exit_cleanup(RERR_STREAMIO);
322 /* This is used by the generator to limit how many file transfers can
323 * be active at once when --remove-sent-files is specified. Without
324 * this, sender-side deletions were mostly happening at the end. */
325 void increment_active_files(int ndx, int itemizing, enum logcode code)
327 /* TODO: tune these limits? */
328 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
330 check_for_finished_hlinks(itemizing, code);
335 active_bytecnt += the_file_list->files[ndx]->length;
338 void decrement_active_files(int ndx)
341 active_bytecnt -= the_file_list->files[ndx]->length;
344 /* Try to push messages off the list onto the wire. If we leave with more
345 * to do, return 0. On error, return -1. If everything flushed, return 1.
346 * This is only active in the receiver. */
347 static int msg2genr_flush(int flush_it_all)
349 static int written = 0;
356 while (msg2genr.head) {
357 struct msg_list_item *m = msg2genr.head;
358 int n = write(msg_fd_out, m->buf + written, m->len - written);
362 if (errno != EWOULDBLOCK && errno != EAGAIN)
367 FD_SET(msg_fd_out, &fds);
368 tv.tv_sec = select_timeout;
370 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
372 } else if ((written += n) == m->len) {
373 msg2genr.head = m->next;
375 msg2genr.tail = NULL;
383 void send_msg(enum msgcode code, char *buf, int len)
385 if (msg_fd_out < 0) {
386 io_multiplex_write(code, buf, len);
389 msg_list_add(&msg2genr, code, buf, len);
390 msg2genr_flush(NORMAL_FLUSH);
393 int get_redo_num(int itemizing, enum logcode code)
397 check_for_finished_hlinks(itemizing, code);
403 return flist_ndx_pop(&redo_list);
406 int get_hlink_num(void)
408 return flist_ndx_pop(&hlink_list);
412 * When we're the receiver and we have a local --files-from list of names
413 * that needs to be sent over the socket to the sender, we have to do two
414 * things at the same time: send the sender a list of what files we're
415 * processing and read the incoming file+info list from the sender. We do
416 * this by augmenting the read_timeout() function to copy this data. It
417 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
418 * ready, since it might be a pipe) and then blast it out f_out (when it
419 * is ready to receive more data).
421 void io_set_filesfrom_fds(int f_in, int f_out)
423 io_filesfrom_f_in = f_in;
424 io_filesfrom_f_out = f_out;
425 io_filesfrom_bp = io_filesfrom_buf;
426 io_filesfrom_lastchar = '\0';
427 io_filesfrom_buflen = 0;
430 /* It's almost always an error to get an EOF when we're trying to read from the
431 * network, because the protocol is (for the most part) self-terminating.
433 * There is one case for the receiver when it is at the end of the transfer
434 * (hanging around reading any keep-alive packets that might come its way): if
435 * the sender dies before the generator's kill-signal comes through, we can end
436 * up here needing to loop until the kill-signal arrives. In this situation,
437 * kluge_around_eof will be < 0.
439 * There is another case for older protocol versions (< 24) where the module
440 * listing was not terminated, so we must ignore an EOF error in that case and
441 * exit. In this situation, kluge_around_eof will be > 0. */
442 static void whine_about_eof(int fd)
444 if (kluge_around_eof && fd == sock_f_in) {
446 if (kluge_around_eof > 0)
448 /* If we're still here after 10 seconds, exit with an error. */
449 for (i = 10*1000/20; i--; )
453 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
454 "(%.0f bytes received so far) [%s]\n",
455 (double)stats.total_read, who_am_i());
457 exit_cleanup(RERR_STREAMIO);
461 * Read from a socket with I/O timeout. return the number of bytes
462 * read. If no bytes can be read then exit, never return a number <= 0.
464 * TODO: If the remote shell connection fails, then current versions
465 * actually report an "unexpected EOF" error here. Since it's a
466 * fairly common mistake to try to use rsh when ssh is required, we
467 * should trap that: if we fail to read any data at all, we should
468 * give a better explanation. We can tell whether the connection has
469 * started by looking e.g. at whether the remote version is known yet.
471 static int read_timeout(int fd, char *buf, size_t len)
475 io_flush(NORMAL_FLUSH);
478 /* until we manage to read *something* */
488 FD_SET(msg_fd_out, &w_fds);
489 if (msg_fd_out > maxfd)
492 if (io_filesfrom_f_out >= 0) {
494 if (io_filesfrom_buflen == 0) {
495 if (io_filesfrom_f_in >= 0) {
496 FD_SET(io_filesfrom_f_in, &r_fds);
497 new_fd = io_filesfrom_f_in;
499 io_filesfrom_f_out = -1;
503 FD_SET(io_filesfrom_f_out, &w_fds);
504 new_fd = io_filesfrom_f_out;
510 tv.tv_sec = select_timeout;
515 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
519 exit_cleanup(RERR_SOCKETIO);
524 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
525 msg2genr_flush(NORMAL_FLUSH);
527 if (io_filesfrom_f_out >= 0) {
528 if (io_filesfrom_buflen) {
529 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
530 int l = write(io_filesfrom_f_out,
532 io_filesfrom_buflen);
534 if (!(io_filesfrom_buflen -= l))
535 io_filesfrom_bp = io_filesfrom_buf;
537 io_filesfrom_bp += l;
539 /* XXX should we complain? */
540 io_filesfrom_f_out = -1;
543 } else if (io_filesfrom_f_in >= 0) {
544 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
545 int l = read(io_filesfrom_f_in,
547 sizeof io_filesfrom_buf);
549 /* Send end-of-file marker */
550 io_filesfrom_buf[0] = '\0';
551 io_filesfrom_buf[1] = '\0';
552 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
553 io_filesfrom_f_in = -1;
556 char *s = io_filesfrom_buf + l;
557 /* Transform CR and/or LF into '\0' */
558 while (s-- > io_filesfrom_buf) {
559 if (*s == '\n' || *s == '\r')
563 if (!io_filesfrom_lastchar) {
564 /* Last buf ended with a '\0', so don't
565 * let this buf start with one. */
566 while (l && !*io_filesfrom_bp)
567 io_filesfrom_bp++, l--;
570 io_filesfrom_bp = io_filesfrom_buf;
572 char *f = io_filesfrom_bp;
575 /* Eliminate any multi-'\0' runs. */
577 if (!(*t++ = *f++)) {
578 while (f != eob && !*f)
582 io_filesfrom_lastchar = f[-1];
584 io_filesfrom_buflen = l;
590 if (!FD_ISSET(fd, &r_fds))
593 n = read(fd, buf, len);
597 whine_about_eof(fd); /* Doesn't return. */
598 if (errno == EINTR || errno == EWOULDBLOCK
602 /* Don't write errors on a dead socket. */
603 if (fd == sock_f_in) {
604 close_multiplexing_out();
605 rsyserr(FSOCKERR, errno, "read error");
607 rsyserr(FERROR, errno, "read error");
608 exit_cleanup(RERR_STREAMIO);
615 if (fd == sock_f_in && io_timeout)
616 last_io_in = time(NULL);
623 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
626 int read_filesfrom_line(int fd, char *fname)
628 char ch, *s, *eob = fname + MAXPATHLEN - 1;
630 int reading_remotely = filesfrom_host != NULL;
631 int nulls = eol_nulls || reading_remotely;
636 cnt = read(fd, &ch, 1);
637 if (cnt < 0 && (errno == EWOULDBLOCK
638 || errno == EINTR || errno == EAGAIN)) {
643 tv.tv_sec = select_timeout;
645 if (!select(fd+1, &fds, NULL, NULL, &tv))
651 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
652 /* Skip empty lines if reading locally. */
653 if (!reading_remotely && s == fname)
663 if (*fname == '#' || *fname == ';')
669 static char *iobuf_out;
670 static int iobuf_out_cnt;
672 void io_start_buffering_out(void)
676 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
677 out_of_memory("io_start_buffering_out");
681 static char *iobuf_in;
682 static size_t iobuf_in_siz;
684 void io_start_buffering_in(void)
688 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
689 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
690 out_of_memory("io_start_buffering_in");
693 void io_end_buffering(void)
695 io_flush(NORMAL_FLUSH);
696 if (!io_multiplexing_out) {
702 void maybe_flush_socket(void)
704 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
705 io_flush(NORMAL_FLUSH);
708 void maybe_send_keepalive(void)
710 if (time(NULL) - last_io_out >= allowed_lull) {
711 if (!iobuf_out || !iobuf_out_cnt) {
712 if (protocol_version < 29)
713 return; /* there's nothing we can do */
714 write_int(sock_f_out, the_file_list->count);
715 write_shortint(sock_f_out, ITEM_IS_NEW);
718 io_flush(NORMAL_FLUSH);
723 * Continue trying to read len bytes - don't return until len has been
726 static void read_loop(int fd, char *buf, size_t len)
729 int n = read_timeout(fd, buf, len);
737 * Read from the file descriptor handling multiplexing - return number
740 * Never returns <= 0.
742 static int readfd_unbuffered(int fd, char *buf, size_t len)
744 static size_t remaining;
745 static size_t iobuf_in_ndx;
748 char line[BIGPATHBUFLEN];
750 if (!iobuf_in || fd != sock_f_in)
751 return read_timeout(fd, buf, len);
753 if (!io_multiplexing_in && remaining == 0) {
754 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
760 len = MIN(len, remaining);
761 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
768 read_loop(fd, line, 4);
771 msg_bytes = tag & 0xFFFFFF;
772 tag = (tag >> 24) - MPLEX_BASE;
776 if (msg_bytes > iobuf_in_siz) {
777 if (!(iobuf_in = realloc_array(iobuf_in, char,
779 out_of_memory("readfd_unbuffered");
780 iobuf_in_siz = msg_bytes;
782 read_loop(fd, iobuf_in, msg_bytes);
783 remaining = msg_bytes;
787 if (msg_bytes >= sizeof line)
789 read_loop(fd, line, msg_bytes);
790 /* A directory name was sent with the trailing null */
791 if (msg_bytes > 0 && !line[msg_bytes-1])
792 log_delete(line, S_IFDIR);
794 line[msg_bytes] = '\0';
795 log_delete(line, S_IFREG);
799 if (msg_bytes != 4) {
800 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
801 tag, (long)msg_bytes, who_am_i());
802 exit_cleanup(RERR_STREAMIO);
804 read_loop(fd, line, msg_bytes);
805 successful_send(IVAL(line, 0));
809 if (msg_bytes >= sizeof line) {
812 "multiplexing overflow %d:%ld [%s]\n",
813 tag, (long)msg_bytes, who_am_i());
814 exit_cleanup(RERR_STREAMIO);
816 read_loop(fd, line, msg_bytes);
817 rwrite((enum logcode)tag, line, msg_bytes);
820 rprintf(FERROR, "unexpected tag %d [%s]\n",
822 exit_cleanup(RERR_STREAMIO);
827 io_flush(NORMAL_FLUSH);
833 * Do a buffered read from @p fd. Don't return until all @p n bytes
834 * have been read. If all @p n can't be read then exit with an
837 static void readfd(int fd, char *buffer, size_t N)
843 cnt = readfd_unbuffered(fd, buffer + total, N-total);
847 if (fd == write_batch_monitor_in) {
848 if ((size_t)write(batch_fd, buffer, total) != total)
849 exit_cleanup(RERR_FILEIO);
853 stats.total_read += total;
856 int read_shortint(int f)
859 readfd(f, (char *)b, 2);
860 return (b[1] << 8) + b[0];
863 int32 read_int(int f)
870 if (num == (int32)0xffffffff)
875 int64 read_longint(int f)
881 if ((int32)num != (int32)0xffffffff)
885 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
886 exit_cleanup(RERR_UNSUPPORTED);
889 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
895 void read_buf(int f,char *buf,size_t len)
900 void read_sbuf(int f,char *buf,size_t len)
906 uchar read_byte(int f)
909 readfd(f, (char *)&c, 1);
913 int read_vstring(int f, char *buf, int bufsize)
915 int len = read_byte(f);
918 len = (len & ~0x80) * 0x100 + read_byte(f);
920 if (len >= bufsize) {
921 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
932 /* Populate a sum_struct with values from the socket. This is
933 * called by both the sender and the receiver. */
934 void read_sum_head(int f, struct sum_struct *sum)
936 sum->count = read_int(f);
937 if (sum->count < 0) {
938 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
939 (long)sum->count, who_am_i());
940 exit_cleanup(RERR_PROTOCOL);
942 sum->blength = read_int(f);
943 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
944 rprintf(FERROR, "Invalid block length %ld [%s]\n",
945 (long)sum->blength, who_am_i());
946 exit_cleanup(RERR_PROTOCOL);
948 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
949 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
950 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
951 sum->s2length, who_am_i());
952 exit_cleanup(RERR_PROTOCOL);
954 sum->remainder = read_int(f);
955 if (sum->remainder < 0 || sum->remainder > sum->blength) {
956 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
957 (long)sum->remainder, who_am_i());
958 exit_cleanup(RERR_PROTOCOL);
962 /* Send the values from a sum_struct over the socket. Set sum to
963 * NULL if there are no checksums to send. This is called by both
964 * the generator and the sender. */
965 void write_sum_head(int f, struct sum_struct *sum)
967 static struct sum_struct null_sum;
972 write_int(f, sum->count);
973 write_int(f, sum->blength);
974 if (protocol_version >= 27)
975 write_int(f, sum->s2length);
976 write_int(f, sum->remainder);
980 * Sleep after writing to limit I/O bandwidth usage.
982 * @todo Rather than sleeping after each write, it might be better to
983 * use some kind of averaging. The current algorithm seems to always
984 * use a bit less bandwidth than specified, because it doesn't make up
985 * for slow periods. But arguably this is a feature. In addition, we
986 * ought to take the time used to write the data into account.
988 * During some phases of big transfers (file FOO is uptodate) this is
989 * called with a small bytes_written every time. As the kernel has to
990 * round small waits up to guarantee that we actually wait at least the
991 * requested number of microseconds, this can become grossly inaccurate.
992 * We therefore keep track of the bytes we've written over time and only
993 * sleep when the accumulated delay is at least 1 tenth of a second.
995 static void sleep_for_bwlimit(int bytes_written)
997 static struct timeval prior_tv;
998 static long total_written = 0;
999 struct timeval tv, start_tv;
1000 long elapsed_usec, sleep_usec;
1002 #define ONE_SEC 1000000L /* # of microseconds in a second */
1004 if (!bwlimit_writemax)
1007 total_written += bytes_written;
1009 gettimeofday(&start_tv, NULL);
1010 if (prior_tv.tv_sec) {
1011 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1012 + (start_tv.tv_usec - prior_tv.tv_usec);
1013 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1014 if (total_written < 0)
1018 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1019 if (sleep_usec < ONE_SEC / 10) {
1020 prior_tv = start_tv;
1024 tv.tv_sec = sleep_usec / ONE_SEC;
1025 tv.tv_usec = sleep_usec % ONE_SEC;
1026 select(0, NULL, NULL, NULL, &tv);
1028 gettimeofday(&prior_tv, NULL);
1029 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1030 + (prior_tv.tv_usec - start_tv.tv_usec);
1031 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1034 /* Write len bytes to the file descriptor fd, looping as necessary to get
1035 * the job done and also (in certain circumstances) reading any data on
1036 * msg_fd_in to avoid deadlock.
1038 * This function underlies the multiplexing system. The body of the
1039 * application never calls this function directly. */
1040 static void writefd_unbuffered(int fd,char *buf,size_t len)
1042 size_t n, total = 0;
1043 fd_set w_fds, r_fds;
1044 int maxfd, count, cnt, using_r_fds;
1045 int defer_save = defer_forwarding_messages;
1050 while (total < len) {
1055 if (msg_fd_in >= 0) {
1057 FD_SET(msg_fd_in,&r_fds);
1058 if (msg_fd_in > maxfd)
1064 tv.tv_sec = select_timeout;
1068 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1072 if (count < 0 && errno == EBADF)
1073 exit_cleanup(RERR_SOCKETIO);
1078 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1081 if (!FD_ISSET(fd, &w_fds))
1085 if (bwlimit_writemax && n > bwlimit_writemax)
1086 n = bwlimit_writemax;
1087 cnt = write(fd, buf + total, n);
1093 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1099 /* Don't try to write errors back across the stream. */
1100 if (fd == sock_f_out)
1101 close_multiplexing_out();
1102 rsyserr(FERROR, errno,
1103 "writefd_unbuffered failed to write %ld bytes [%s]",
1104 (long)len, who_am_i());
1105 /* If the other side is sending us error messages, try
1106 * to grab any messages they sent before they died. */
1107 while (fd == sock_f_out && io_multiplexing_in) {
1110 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1111 sizeof io_filesfrom_buf);
1113 exit_cleanup(RERR_STREAMIO);
1117 defer_forwarding_messages = 1;
1119 if (fd == sock_f_out) {
1120 if (io_timeout || am_generator)
1121 last_io_out = time(NULL);
1122 sleep_for_bwlimit(cnt);
1126 defer_forwarding_messages = defer_save;
1130 static void msg2sndr_flush(void)
1132 if (defer_forwarding_messages)
1135 while (msg2sndr.head && io_multiplexing_out) {
1136 struct msg_list_item *m = msg2sndr.head;
1137 if (!(msg2sndr.head = m->next))
1138 msg2sndr.tail = NULL;
1139 stats.total_written += m->len;
1140 defer_forwarding_messages = 1;
1141 writefd_unbuffered(sock_f_out, m->buf, m->len);
1142 defer_forwarding_messages = 0;
1148 * Write an message to a multiplexed stream. If this fails then rsync
1151 static void mplex_write(enum msgcode code, char *buf, size_t len)
1156 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1158 if (n > sizeof buffer - 4)
1161 memcpy(buffer + 4, buf, n);
1163 writefd_unbuffered(sock_f_out, buffer, n+4);
1169 defer_forwarding_messages = 1;
1170 writefd_unbuffered(sock_f_out, buf, len);
1171 defer_forwarding_messages = 0;
1176 void io_flush(int flush_it_all)
1178 msg2genr_flush(flush_it_all);
1181 if (!iobuf_out_cnt || no_flush)
1184 if (io_multiplexing_out)
1185 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1187 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1191 static void writefd(int fd,char *buf,size_t len)
1193 if (fd == msg_fd_out) {
1194 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1195 exit_cleanup(RERR_PROTOCOL);
1198 if (fd == sock_f_out)
1199 stats.total_written += len;
1201 if (fd == write_batch_monitor_out) {
1202 if ((size_t)write(batch_fd, buf, len) != len)
1203 exit_cleanup(RERR_FILEIO);
1206 if (!iobuf_out || fd != sock_f_out) {
1207 writefd_unbuffered(fd, buf, len);
1212 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1214 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1220 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1221 io_flush(NORMAL_FLUSH);
1225 void write_shortint(int f, int x)
1230 writefd(f, (char *)b, 2);
1233 void write_int(int f,int32 x)
1241 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1242 * 64-bit types on this platform.
1244 void write_longint(int f, int64 x)
1248 if (x <= 0x7FFFFFFF) {
1249 write_int(f, (int)x);
1253 #if SIZEOF_INT64 < 8
1254 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1255 exit_cleanup(RERR_UNSUPPORTED);
1257 write_int(f, (int32)0xFFFFFFFF);
1258 SIVAL(b,0,(x&0xFFFFFFFF));
1259 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1265 void write_buf(int f,char *buf,size_t len)
1270 /** Write a string to the connection */
1271 void write_sbuf(int f, char *buf)
1273 writefd(f, buf, strlen(buf));
1276 void write_byte(int f, uchar c)
1278 writefd(f, (char *)&c, 1);
1281 void write_vstring(int f, char *str, int len)
1283 uchar lenbuf[3], *lb = lenbuf;
1288 "attempting to send over-long vstring (%d > %d)\n",
1290 exit_cleanup(RERR_PROTOCOL);
1292 *lb++ = len / 0x100 + 0x80;
1296 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1298 writefd(f, str, len);
1302 * Read a line of up to @p maxlen characters into @p buf (not counting
1303 * the trailing null). Strips the (required) trailing newline and all
1306 * @return 1 for success; 0 for I/O error or truncation.
1308 int read_line(int f, char *buf, size_t maxlen)
1312 read_buf(f, buf, 1);
1317 if (buf[0] != '\r') {
1326 void io_printf(int fd, const char *format, ...)
1329 char buf[BIGPATHBUFLEN];
1332 va_start(ap, format);
1333 len = vsnprintf(buf, sizeof buf, format, ap);
1337 exit_cleanup(RERR_STREAMIO);
1339 if (len > (int)sizeof buf) {
1340 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1341 exit_cleanup(RERR_STREAMIO);
1344 write_sbuf(fd, buf);
1347 /** Setup for multiplexing a MSG_* stream with the data stream. */
1348 void io_start_multiplex_out(void)
1350 io_flush(NORMAL_FLUSH);
1351 io_start_buffering_out();
1352 io_multiplexing_out = 1;
1355 /** Setup for multiplexing a MSG_* stream with the data stream. */
1356 void io_start_multiplex_in(void)
1358 io_flush(NORMAL_FLUSH);
1359 io_start_buffering_in();
1360 io_multiplexing_in = 1;
1363 /** Write an message to the multiplexed data stream. */
1364 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1366 if (!io_multiplexing_out)
1369 io_flush(NORMAL_FLUSH);
1370 stats.total_written += (len+4);
1371 mplex_write(code, buf, len);
1375 void close_multiplexing_in(void)
1377 io_multiplexing_in = 0;
1380 /** Stop output multiplexing. */
1381 void close_multiplexing_out(void)
1383 io_multiplexing_out = 0;
1386 void start_write_batch(int fd)
1388 write_stream_flags(batch_fd);
1390 /* Some communication has already taken place, but we don't
1391 * enable batch writing until here so that we can write a
1392 * canonical record of the communication even though the
1393 * actual communication so far depends on whether a daemon
1395 write_int(batch_fd, protocol_version);
1396 write_int(batch_fd, checksum_seed);
1399 write_batch_monitor_out = fd;
1401 write_batch_monitor_in = fd;
1404 void stop_write_batch(void)
1406 write_batch_monitor_out = -1;
1407 write_batch_monitor_in = -1;