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;
45 extern int io_timeout;
46 extern int allowed_lull;
50 extern int am_generator;
52 extern int read_batch;
53 extern int csum_length;
54 extern int checksum_seed;
55 extern int protocol_version;
56 extern int remove_sent_files;
57 extern int preserve_hard_links;
58 extern char *filesfrom_host;
59 extern struct stats stats;
60 extern struct file_list *the_file_list;
62 const char phase_unknown[] = "unknown";
63 int ignore_timeout = 0;
65 int batch_gen_fd = -1;
68 * The connection might be dropped at some point; perhaps because the
69 * remote instance crashed. Just giving the offset on the stream is
70 * not very helpful. So instead we try to make io_phase_name point to
73 * For buffered/multiplexed I/O these names will be somewhat
74 * approximate; perhaps for ease of support we would rather make the
75 * buffer always flush when a single application-level I/O finishes.
77 * @todo Perhaps we want some simple stack functionality, but there's
78 * no need to overdo it.
80 const char *io_write_phase = phase_unknown;
81 const char *io_read_phase = phase_unknown;
83 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
84 int kluge_around_eof = 0;
91 static int io_multiplexing_out;
92 static int io_multiplexing_in;
93 static time_t last_io_in;
94 static time_t last_io_out;
97 static int write_batch_monitor_in = -1;
98 static int write_batch_monitor_out = -1;
100 static int io_filesfrom_f_in = -1;
101 static int io_filesfrom_f_out = -1;
102 static char io_filesfrom_buf[2048];
103 static char *io_filesfrom_bp;
104 static char io_filesfrom_lastchar;
105 static int io_filesfrom_buflen;
106 static size_t contiguous_write_len = 0;
107 static int select_timeout = SELECT_TIMEOUT;
108 static int active_filecnt = 0;
109 static OFF_T active_bytecnt = 0;
111 static void read_loop(int fd, char *buf, size_t len);
113 struct flist_ndx_item {
114 struct flist_ndx_item *next;
118 struct flist_ndx_list {
119 struct flist_ndx_item *head, *tail;
122 static struct flist_ndx_list redo_list, hlink_list;
124 struct msg_list_item {
125 struct msg_list_item *next;
131 struct msg_list_item *head, *tail;
134 static struct msg_list msg_list;
136 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
138 struct flist_ndx_item *item;
140 if (!(item = new(struct flist_ndx_item)))
141 out_of_memory("flist_ndx_push");
145 lp->tail->next = item;
151 static int flist_ndx_pop(struct flist_ndx_list *lp)
153 struct flist_ndx_item *next;
160 next = lp->head->next;
169 static void check_timeout(void)
173 if (!io_timeout || ignore_timeout)
177 last_io_in = time(NULL);
183 if (t - last_io_in >= io_timeout) {
184 if (!am_server && !am_daemon) {
185 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
186 (int)(t-last_io_in));
188 exit_cleanup(RERR_TIMEOUT);
192 /* Note the fds used for the main socket (which might really be a pipe
193 * for a local transfer, but we can ignore that). */
194 void io_set_sock_fds(int f_in, int f_out)
200 void set_io_timeout(int secs)
204 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
205 select_timeout = SELECT_TIMEOUT;
207 select_timeout = io_timeout;
209 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
212 /* Setup the fd used to receive MSG_* messages. Only needed during the
213 * early stages of being a local sender (up through the sending of the
214 * file list) or when we're the generator (to fetch the messages from
216 void set_msg_fd_in(int fd)
221 /* Setup the fd used to send our MSG_* messages. Only needed when
222 * we're the receiver (to send our messages to the generator). */
223 void set_msg_fd_out(int fd)
226 set_nonblocking(msg_fd_out);
229 /* Add a message to the pending MSG_* list. */
230 static void msg_list_add(int code, char *buf, int len)
232 struct msg_list_item *ml;
234 if (!(ml = new(struct msg_list_item)))
235 out_of_memory("msg_list_add");
237 if (!(ml->buf = new_array(char, len+4)))
238 out_of_memory("msg_list_add");
239 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
240 memcpy(ml->buf+4, buf, len);
243 msg_list.tail->next = ml;
249 /* Read a message from the MSG_* fd and handle it. This is called either
250 * during the early stages of being a local sender (up through the sending
251 * of the file list) or when we're the generator (to fetch the messages
252 * from the receiver). */
253 static void read_msg_fd(void)
260 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
261 * to this routine from writefd_unbuffered(). */
264 read_loop(fd, buf, 4);
267 len = tag & 0xFFFFFF;
268 tag = (tag >> 24) - MPLEX_BASE;
272 if (len != 0 || !am_generator) {
273 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
274 exit_cleanup(RERR_STREAMIO);
276 flist_ndx_push(&redo_list, -1);
279 if (len != 4 || !am_generator) {
280 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
281 exit_cleanup(RERR_STREAMIO);
283 read_loop(fd, buf, 4);
284 if (remove_sent_files)
285 decrement_active_files(IVAL(buf,0));
286 flist_ndx_push(&redo_list, IVAL(buf,0));
289 if (len >= (int)sizeof buf || !am_generator) {
290 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
291 exit_cleanup(RERR_STREAMIO);
293 read_loop(fd, buf, len);
294 io_multiplex_write(MSG_DELETED, buf, len);
297 if (len != 4 || !am_generator) {
298 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
299 exit_cleanup(RERR_STREAMIO);
301 read_loop(fd, buf, len);
302 if (remove_sent_files) {
303 decrement_active_files(IVAL(buf,0));
304 io_multiplex_write(MSG_SUCCESS, buf, len);
306 if (preserve_hard_links)
307 flist_ndx_push(&hlink_list, IVAL(buf,0));
311 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
312 exit_cleanup(RERR_STREAMIO);
314 close_multiplexing_out();
323 read_loop(fd, buf, n);
324 rwrite((enum logcode)tag, buf, n);
329 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
330 exit_cleanup(RERR_STREAMIO);
336 /* This is used by the generator to limit how many file transfers can
337 * be active at once when --remove-sent-files is specified. Without
338 * this, sender-side deletions were mostly happening at the end. */
339 void increment_active_files(int ndx, int itemizing, enum logcode code)
341 /* TODO: tune these limits? */
342 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
344 check_for_finished_hlinks(itemizing, code);
349 active_bytecnt += the_file_list->files[ndx]->length;
352 void decrement_active_files(int ndx)
355 active_bytecnt -= the_file_list->files[ndx]->length;
358 /* Try to push messages off the list onto the wire. If we leave with more
359 * to do, return 0. On error, return -1. If everything flushed, return 1.
360 * This is only active in the receiver. */
361 static int msg_list_flush(int flush_it_all)
363 static int written = 0;
370 while (msg_list.head) {
371 struct msg_list_item *ml = msg_list.head;
372 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
376 if (errno != EWOULDBLOCK && errno != EAGAIN)
381 FD_SET(msg_fd_out, &fds);
382 tv.tv_sec = select_timeout;
384 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
386 } else if ((written += n) == ml->len) {
388 msg_list.head = ml->next;
390 msg_list.tail = NULL;
398 void send_msg(enum msgcode code, char *buf, int len)
400 if (msg_fd_out < 0) {
401 io_multiplex_write(code, buf, len);
404 msg_list_add(code, buf, len);
405 msg_list_flush(NORMAL_FLUSH);
408 int get_redo_num(int itemizing, enum logcode code)
412 check_for_finished_hlinks(itemizing, code);
418 return flist_ndx_pop(&redo_list);
421 int get_hlink_num(void)
423 return flist_ndx_pop(&hlink_list);
427 * When we're the receiver and we have a local --files-from list of names
428 * that needs to be sent over the socket to the sender, we have to do two
429 * things at the same time: send the sender a list of what files we're
430 * processing and read the incoming file+info list from the sender. We do
431 * this by augmenting the read_timeout() function to copy this data. It
432 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
433 * ready, since it might be a pipe) and then blast it out f_out (when it
434 * is ready to receive more data).
436 void io_set_filesfrom_fds(int f_in, int f_out)
438 io_filesfrom_f_in = f_in;
439 io_filesfrom_f_out = f_out;
440 io_filesfrom_bp = io_filesfrom_buf;
441 io_filesfrom_lastchar = '\0';
442 io_filesfrom_buflen = 0;
445 /* It's almost always an error to get an EOF when we're trying to read from the
446 * network, because the protocol is (for the most part) self-terminating.
448 * There is one case for the receiver when it is at the end of the transfer
449 * (hanging around reading any keep-alive packets that might come its way): if
450 * the sender dies before the generator's kill-signal comes through, we can end
451 * up here needing to loop until the kill-signal arrives. In this situation,
452 * kluge_around_eof will be < 0.
454 * There is another case for older protocol versions (< 24) where the module
455 * listing was not terminated, so we must ignore an EOF error in that case and
456 * exit. In this situation, kluge_around_eof will be > 0. */
457 static void whine_about_eof(int fd)
459 if (kluge_around_eof && fd == sock_f_in) {
461 if (kluge_around_eof > 0)
463 /* If we're still here after 10 seconds, exit with an error. */
464 for (i = 10*1000/20; i--; )
468 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
469 "(%.0f bytes received so far) [%s]\n",
470 (double)stats.total_read, who_am_i());
472 exit_cleanup(RERR_STREAMIO);
476 * Read from a socket with I/O timeout. return the number of bytes
477 * read. If no bytes can be read then exit, never return a number <= 0.
479 * TODO: If the remote shell connection fails, then current versions
480 * actually report an "unexpected EOF" error here. Since it's a
481 * fairly common mistake to try to use rsh when ssh is required, we
482 * should trap that: if we fail to read any data at all, we should
483 * give a better explanation. We can tell whether the connection has
484 * started by looking e.g. at whether the remote version is known yet.
486 static int read_timeout(int fd, char *buf, size_t len)
490 io_flush(NORMAL_FLUSH);
493 /* until we manage to read *something* */
503 FD_SET(msg_fd_out, &w_fds);
504 if (msg_fd_out > maxfd)
507 if (io_filesfrom_f_out >= 0) {
509 if (io_filesfrom_buflen == 0) {
510 if (io_filesfrom_f_in >= 0) {
511 FD_SET(io_filesfrom_f_in, &r_fds);
512 new_fd = io_filesfrom_f_in;
514 io_filesfrom_f_out = -1;
518 FD_SET(io_filesfrom_f_out, &w_fds);
519 new_fd = io_filesfrom_f_out;
525 tv.tv_sec = select_timeout;
530 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
534 exit_cleanup(RERR_SOCKETIO);
539 if (msg_list.head && FD_ISSET(msg_fd_out, &w_fds))
540 msg_list_flush(NORMAL_FLUSH);
542 if (io_filesfrom_f_out >= 0) {
543 if (io_filesfrom_buflen) {
544 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
545 int l = write(io_filesfrom_f_out,
547 io_filesfrom_buflen);
549 if (!(io_filesfrom_buflen -= l))
550 io_filesfrom_bp = io_filesfrom_buf;
552 io_filesfrom_bp += l;
554 /* XXX should we complain? */
555 io_filesfrom_f_out = -1;
558 } else if (io_filesfrom_f_in >= 0) {
559 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
560 int l = read(io_filesfrom_f_in,
562 sizeof io_filesfrom_buf);
564 /* Send end-of-file marker */
565 io_filesfrom_buf[0] = '\0';
566 io_filesfrom_buf[1] = '\0';
567 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
568 io_filesfrom_f_in = -1;
571 char *s = io_filesfrom_buf + l;
572 /* Transform CR and/or LF into '\0' */
573 while (s-- > io_filesfrom_buf) {
574 if (*s == '\n' || *s == '\r')
578 if (!io_filesfrom_lastchar) {
579 /* Last buf ended with a '\0', so don't
580 * let this buf start with one. */
581 while (l && !*io_filesfrom_bp)
582 io_filesfrom_bp++, l--;
585 io_filesfrom_bp = io_filesfrom_buf;
587 char *f = io_filesfrom_bp;
590 /* Eliminate any multi-'\0' runs. */
592 if (!(*t++ = *f++)) {
593 while (f != eob && !*f)
597 io_filesfrom_lastchar = f[-1];
599 io_filesfrom_buflen = l;
605 if (!FD_ISSET(fd, &r_fds))
608 n = read(fd, buf, len);
612 whine_about_eof(fd); /* Doesn't return. */
613 if (errno == EINTR || errno == EWOULDBLOCK
617 /* Don't write errors on a dead socket. */
618 if (fd == sock_f_in) {
619 close_multiplexing_out();
620 rsyserr(FSOCKERR, errno, "read error");
622 rsyserr(FERROR, errno, "read error");
623 exit_cleanup(RERR_STREAMIO);
630 if (fd == sock_f_in && io_timeout)
631 last_io_in = time(NULL);
638 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
641 int read_filesfrom_line(int fd, char *fname)
643 char ch, *s, *eob = fname + MAXPATHLEN - 1;
645 int reading_remotely = filesfrom_host != NULL;
646 int nulls = eol_nulls || reading_remotely;
651 cnt = read(fd, &ch, 1);
652 if (cnt < 0 && (errno == EWOULDBLOCK
653 || errno == EINTR || errno == EAGAIN)) {
658 tv.tv_sec = select_timeout;
660 if (!select(fd+1, &fds, NULL, NULL, &tv))
666 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
667 /* Skip empty lines if reading locally. */
668 if (!reading_remotely && s == fname)
678 if (*fname == '#' || *fname == ';')
684 static char *iobuf_out;
685 static int iobuf_out_cnt;
687 void io_start_buffering_out(void)
691 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
692 out_of_memory("io_start_buffering_out");
696 static char *iobuf_in;
697 static size_t iobuf_in_siz;
699 void io_start_buffering_in(void)
703 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
704 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
705 out_of_memory("io_start_buffering_in");
708 void io_end_buffering(void)
710 io_flush(NORMAL_FLUSH);
711 if (!io_multiplexing_out) {
717 void maybe_flush_socket(void)
719 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
720 io_flush(NORMAL_FLUSH);
723 void maybe_send_keepalive(void)
725 if (time(NULL) - last_io_out >= allowed_lull) {
726 if (!iobuf_out || !iobuf_out_cnt) {
727 if (protocol_version < 29)
728 return; /* there's nothing we can do */
729 write_int(sock_f_out, the_file_list->count);
730 write_shortint(sock_f_out, ITEM_IS_NEW);
733 io_flush(NORMAL_FLUSH);
738 * Continue trying to read len bytes - don't return until len has been
741 static void read_loop(int fd, char *buf, size_t len)
744 int n = read_timeout(fd, buf, len);
752 * Read from the file descriptor handling multiplexing - return number
755 * Never returns <= 0.
757 static int readfd_unbuffered(int fd, char *buf, size_t len)
759 static size_t remaining;
760 static size_t iobuf_in_ndx;
763 char line[BIGPATHBUFLEN];
765 if (!iobuf_in || fd != sock_f_in)
766 return read_timeout(fd, buf, len);
768 if (!io_multiplexing_in && remaining == 0) {
769 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
775 len = MIN(len, remaining);
776 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
783 read_loop(fd, line, 4);
786 msg_bytes = tag & 0xFFFFFF;
787 tag = (tag >> 24) - MPLEX_BASE;
791 if (msg_bytes > iobuf_in_siz) {
792 if (!(iobuf_in = realloc_array(iobuf_in, char,
794 out_of_memory("readfd_unbuffered");
795 iobuf_in_siz = msg_bytes;
797 read_loop(fd, iobuf_in, msg_bytes);
798 remaining = msg_bytes;
802 if (msg_bytes >= sizeof line)
804 read_loop(fd, line, msg_bytes);
805 /* A directory name was sent with the trailing null */
806 if (msg_bytes > 0 && !line[msg_bytes-1])
807 log_delete(line, S_IFDIR);
809 line[msg_bytes] = '\0';
810 log_delete(line, S_IFREG);
814 if (msg_bytes != 4) {
815 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
816 tag, (long)msg_bytes, who_am_i());
817 exit_cleanup(RERR_STREAMIO);
819 read_loop(fd, line, msg_bytes);
820 successful_send(IVAL(line, 0));
824 if (msg_bytes >= sizeof line) {
827 "multiplexing overflow %d:%ld [%s]\n",
828 tag, (long)msg_bytes, who_am_i());
829 exit_cleanup(RERR_STREAMIO);
831 read_loop(fd, line, msg_bytes);
832 rwrite((enum logcode)tag, line, msg_bytes);
835 rprintf(FERROR, "unexpected tag %d [%s]\n",
837 exit_cleanup(RERR_STREAMIO);
842 io_flush(NORMAL_FLUSH);
848 * Do a buffered read from @p fd. Don't return until all @p n bytes
849 * have been read. If all @p n can't be read then exit with an
852 static void readfd(int fd, char *buffer, size_t N)
858 cnt = readfd_unbuffered(fd, buffer + total, N-total);
862 if (fd == write_batch_monitor_in) {
863 if ((size_t)write(batch_fd, buffer, total) != total)
864 exit_cleanup(RERR_FILEIO);
868 stats.total_read += total;
871 int read_shortint(int f)
874 readfd(f, (char *)b, 2);
875 return (b[1] << 8) + b[0];
878 int32 read_int(int f)
885 if (num == (int32)0xffffffff)
890 int64 read_longint(int f)
896 if ((int32)num != (int32)0xffffffff)
900 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
901 exit_cleanup(RERR_UNSUPPORTED);
904 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
910 void read_buf(int f,char *buf,size_t len)
915 void read_sbuf(int f,char *buf,size_t len)
921 uchar read_byte(int f)
924 readfd(f, (char *)&c, 1);
928 int read_vstring(int f, char *buf, int bufsize)
930 int len = read_byte(f);
933 len = (len & ~0x80) * 0x100 + read_byte(f);
935 if (len >= bufsize) {
936 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
947 /* Populate a sum_struct with values from the socket. This is
948 * called by both the sender and the receiver. */
949 void read_sum_head(int f, struct sum_struct *sum)
951 sum->count = read_int(f);
952 sum->blength = read_int(f);
953 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
954 rprintf(FERROR, "Invalid block length %ld [%s]\n",
955 (long)sum->blength, who_am_i());
956 exit_cleanup(RERR_PROTOCOL);
958 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
959 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
960 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
961 sum->s2length, who_am_i());
962 exit_cleanup(RERR_PROTOCOL);
964 sum->remainder = read_int(f);
965 if (sum->remainder < 0 || sum->remainder > sum->blength) {
966 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
967 (long)sum->remainder, who_am_i());
968 exit_cleanup(RERR_PROTOCOL);
972 /* Send the values from a sum_struct over the socket. Set sum to
973 * NULL if there are no checksums to send. This is called by both
974 * the generator and the sender. */
975 void write_sum_head(int f, struct sum_struct *sum)
977 static struct sum_struct null_sum;
982 write_int(f, sum->count);
983 write_int(f, sum->blength);
984 if (protocol_version >= 27)
985 write_int(f, sum->s2length);
986 write_int(f, sum->remainder);
990 * Sleep after writing to limit I/O bandwidth usage.
992 * @todo Rather than sleeping after each write, it might be better to
993 * use some kind of averaging. The current algorithm seems to always
994 * use a bit less bandwidth than specified, because it doesn't make up
995 * for slow periods. But arguably this is a feature. In addition, we
996 * ought to take the time used to write the data into account.
998 * During some phases of big transfers (file FOO is uptodate) this is
999 * called with a small bytes_written every time. As the kernel has to
1000 * round small waits up to guarantee that we actually wait at least the
1001 * requested number of microseconds, this can become grossly inaccurate.
1002 * We therefore keep track of the bytes we've written over time and only
1003 * sleep when the accumulated delay is at least 1 tenth of a second.
1005 static void sleep_for_bwlimit(int bytes_written)
1007 static struct timeval prior_tv;
1008 static long total_written = 0;
1009 struct timeval tv, start_tv;
1010 long elapsed_usec, sleep_usec;
1012 #define ONE_SEC 1000000L /* # of microseconds in a second */
1014 if (!bwlimit_writemax)
1017 total_written += bytes_written;
1019 gettimeofday(&start_tv, NULL);
1020 if (prior_tv.tv_sec) {
1021 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1022 + (start_tv.tv_usec - prior_tv.tv_usec);
1023 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1024 if (total_written < 0)
1028 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1029 if (sleep_usec < ONE_SEC / 10) {
1030 prior_tv = start_tv;
1034 tv.tv_sec = sleep_usec / ONE_SEC;
1035 tv.tv_usec = sleep_usec % ONE_SEC;
1036 select(0, NULL, NULL, NULL, &tv);
1038 gettimeofday(&prior_tv, NULL);
1039 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1040 + (prior_tv.tv_usec - start_tv.tv_usec);
1041 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1044 /* Write len bytes to the file descriptor fd, looping as necessary to get
1045 * the job done and also (in certain circumstances) reading any data on
1046 * msg_fd_in to avoid deadlock.
1048 * This function underlies the multiplexing system. The body of the
1049 * application never calls this function directly. */
1050 static void writefd_unbuffered(int fd,char *buf,size_t len)
1052 size_t n, total = 0;
1053 fd_set w_fds, r_fds;
1054 int maxfd, count, cnt, using_r_fds;
1059 while (total < len) {
1064 if (msg_fd_in >= 0 && len-total >= contiguous_write_len) {
1066 FD_SET(msg_fd_in,&r_fds);
1067 if (msg_fd_in > maxfd)
1073 tv.tv_sec = select_timeout;
1077 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1081 if (count < 0 && errno == EBADF)
1082 exit_cleanup(RERR_SOCKETIO);
1087 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1090 if (!FD_ISSET(fd, &w_fds))
1094 if (bwlimit_writemax && n > bwlimit_writemax)
1095 n = bwlimit_writemax;
1096 cnt = write(fd, buf + total, n);
1102 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1108 /* Don't try to write errors back across the stream. */
1109 if (fd == sock_f_out)
1110 close_multiplexing_out();
1111 rsyserr(FERROR, errno,
1112 "writefd_unbuffered failed to write %ld bytes: phase \"%s\" [%s]",
1113 (long)len, io_write_phase, who_am_i());
1114 /* If the other side is sending us error messages, try
1115 * to grab any messages they sent before they died. */
1116 while (fd == sock_f_out && io_multiplexing_in) {
1119 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1120 sizeof io_filesfrom_buf);
1122 exit_cleanup(RERR_STREAMIO);
1127 if (fd == sock_f_out) {
1128 if (io_timeout || am_generator)
1129 last_io_out = time(NULL);
1130 sleep_for_bwlimit(cnt);
1138 * Write an message to a multiplexed stream. If this fails then rsync
1141 static void mplex_write(enum msgcode code, char *buf, size_t len)
1146 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1148 /* When the generator reads messages from the msg_fd_in pipe, it can
1149 * cause output to occur down the socket. Setting contiguous_write_len
1150 * prevents the reading of msg_fd_in once we actually start to write
1151 * this sequence of data (though we might read it before the start). */
1152 if (am_generator && msg_fd_in >= 0)
1153 contiguous_write_len = len + 4;
1155 if (n > sizeof buffer - 4)
1158 memcpy(buffer + 4, buf, n);
1160 writefd_unbuffered(sock_f_out, buffer, n+4);
1166 writefd_unbuffered(sock_f_out, buf, len);
1168 if (am_generator && msg_fd_in >= 0)
1169 contiguous_write_len = 0;
1172 void io_flush(int flush_it_all)
1174 msg_list_flush(flush_it_all);
1176 if (!iobuf_out_cnt || no_flush)
1179 if (io_multiplexing_out)
1180 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1182 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1186 static void writefd(int fd,char *buf,size_t len)
1188 if (fd == msg_fd_out) {
1189 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1190 exit_cleanup(RERR_PROTOCOL);
1193 if (fd == sock_f_out)
1194 stats.total_written += len;
1196 if (fd == write_batch_monitor_out) {
1197 if ((size_t)write(batch_fd, buf, len) != len)
1198 exit_cleanup(RERR_FILEIO);
1201 if (!iobuf_out || fd != sock_f_out) {
1202 writefd_unbuffered(fd, buf, len);
1207 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1209 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1215 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1216 io_flush(NORMAL_FLUSH);
1220 void write_shortint(int f, int x)
1225 writefd(f, (char *)b, 2);
1228 void write_int(int f,int32 x)
1235 void write_int_named(int f, int32 x, const char *phase)
1237 io_write_phase = phase;
1239 io_write_phase = phase_unknown;
1243 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
1244 * 64-bit types on this platform.
1246 void write_longint(int f, int64 x)
1250 if (x <= 0x7FFFFFFF) {
1251 write_int(f, (int)x);
1255 #if SIZEOF_INT64 < 8
1256 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
1257 exit_cleanup(RERR_UNSUPPORTED);
1259 write_int(f, (int32)0xFFFFFFFF);
1260 SIVAL(b,0,(x&0xFFFFFFFF));
1261 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1267 void write_buf(int f,char *buf,size_t len)
1272 /** Write a string to the connection */
1273 void write_sbuf(int f, char *buf)
1275 writefd(f, buf, strlen(buf));
1278 void write_byte(int f, uchar c)
1280 writefd(f, (char *)&c, 1);
1283 void write_vstring(int f, char *str, int len)
1285 uchar lenbuf[3], *lb = lenbuf;
1290 "attempting to send over-long vstring (%d > %d)\n",
1292 exit_cleanup(RERR_PROTOCOL);
1294 *lb++ = len / 0x100 + 0x80;
1298 writefd(f, (char*)lenbuf, lb - lenbuf + 1);
1300 writefd(f, str, len);
1304 * Read a line of up to @p maxlen characters into @p buf (not counting
1305 * the trailing null). Strips the (required) trailing newline and all
1308 * @return 1 for success; 0 for I/O error or truncation.
1310 int read_line(int f, char *buf, size_t maxlen)
1314 read_buf(f, buf, 1);
1319 if (buf[0] != '\r') {
1328 void io_printf(int fd, const char *format, ...)
1331 char buf[BIGPATHBUFLEN];
1334 va_start(ap, format);
1335 len = vsnprintf(buf, sizeof buf, format, ap);
1339 exit_cleanup(RERR_STREAMIO);
1341 if (len > (int)sizeof buf) {
1342 rprintf(FERROR, "io_printf() was too long for the buffer.\n");
1343 exit_cleanup(RERR_STREAMIO);
1346 write_sbuf(fd, buf);
1349 /** Setup for multiplexing a MSG_* stream with the data stream. */
1350 void io_start_multiplex_out(void)
1352 io_flush(NORMAL_FLUSH);
1353 io_start_buffering_out();
1354 io_multiplexing_out = 1;
1357 /** Setup for multiplexing a MSG_* stream with the data stream. */
1358 void io_start_multiplex_in(void)
1360 io_flush(NORMAL_FLUSH);
1361 io_start_buffering_in();
1362 io_multiplexing_in = 1;
1365 /** Write an message to the multiplexed data stream. */
1366 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1368 if (!io_multiplexing_out)
1371 io_flush(NORMAL_FLUSH);
1372 stats.total_written += (len+4);
1373 mplex_write(code, buf, len);
1377 void close_multiplexing_in(void)
1379 io_multiplexing_in = 0;
1382 /** Stop output multiplexing. */
1383 void close_multiplexing_out(void)
1385 io_multiplexing_out = 0;
1388 void start_write_batch(int fd)
1390 write_stream_flags(batch_fd);
1392 /* Some communication has already taken place, but we don't
1393 * enable batch writing until here so that we can write a
1394 * canonical record of the communication even though the
1395 * actual communication so far depends on whether a daemon
1397 write_int(batch_fd, protocol_version);
1398 write_int(batch_fd, checksum_seed);
1401 write_batch_monitor_out = fd;
1403 write_batch_monitor_in = fd;
1406 void stop_write_batch(void)
1408 write_batch_monitor_out = -1;
1409 write_batch_monitor_in = -1;