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;
66 /* Ignore an EOF error if non-zero. See whine_about_eof(). */
67 int kluge_around_eof = 0;
74 static int io_multiplexing_out;
75 static int io_multiplexing_in;
76 static time_t last_io_in;
77 static time_t last_io_out;
80 static int write_batch_monitor_in = -1;
81 static int write_batch_monitor_out = -1;
83 static int io_filesfrom_f_in = -1;
84 static int io_filesfrom_f_out = -1;
85 static char io_filesfrom_buf[2048];
86 static char *io_filesfrom_bp;
87 static char io_filesfrom_lastchar;
88 static int io_filesfrom_buflen;
89 static int defer_forwarding_messages = 0;
90 static int select_timeout = SELECT_TIMEOUT;
91 static int active_filecnt = 0;
92 static OFF_T active_bytecnt = 0;
94 static void read_loop(int fd, char *buf, size_t len);
96 struct flist_ndx_item {
97 struct flist_ndx_item *next;
101 struct flist_ndx_list {
102 struct flist_ndx_item *head, *tail;
105 static struct flist_ndx_list redo_list, hlink_list;
107 struct msg_list_item {
108 struct msg_list_item *next;
114 struct msg_list_item *head, *tail;
117 static struct msg_list msg2genr, msg2sndr;
119 static void flist_ndx_push(struct flist_ndx_list *lp, int ndx)
121 struct flist_ndx_item *item;
123 if (!(item = new(struct flist_ndx_item)))
124 out_of_memory("flist_ndx_push");
128 lp->tail->next = item;
134 static int flist_ndx_pop(struct flist_ndx_list *lp)
136 struct flist_ndx_item *next;
143 next = lp->head->next;
152 static void check_timeout(void)
156 if (!io_timeout || ignore_timeout)
160 last_io_in = time(NULL);
166 if (t - last_io_in >= io_timeout) {
167 if (!am_server && !am_daemon) {
168 rprintf(FERROR, "io timeout after %d seconds -- exiting\n",
169 (int)(t-last_io_in));
171 exit_cleanup(RERR_TIMEOUT);
175 /* Note the fds used for the main socket (which might really be a pipe
176 * for a local transfer, but we can ignore that). */
177 void io_set_sock_fds(int f_in, int f_out)
183 void set_io_timeout(int secs)
187 if (!io_timeout || io_timeout > SELECT_TIMEOUT)
188 select_timeout = SELECT_TIMEOUT;
190 select_timeout = io_timeout;
192 allowed_lull = read_batch ? 0 : (io_timeout + 1) / 2;
195 /* Setup the fd used to receive MSG_* messages. Only needed during the
196 * early stages of being a local sender (up through the sending of the
197 * file list) or when we're the generator (to fetch the messages from
199 void set_msg_fd_in(int fd)
204 /* Setup the fd used to send our MSG_* messages. Only needed when
205 * we're the receiver (to send our messages to the generator). */
206 void set_msg_fd_out(int fd)
209 set_nonblocking(msg_fd_out);
212 /* Add a message to the pending MSG_* list. */
213 static void msg_list_add(struct msg_list *lst, int code, char *buf, int len)
215 struct msg_list_item *m;
216 int sz = len + 4 + sizeof m[0] - 1;
218 if (!(m = (struct msg_list_item *)new_array(char, sz)))
219 out_of_memory("msg_list_add");
222 SIVAL(m->buf, 0, ((code+MPLEX_BASE)<<24) | len);
223 memcpy(m->buf + 4, buf, len);
231 /* Read a message from the MSG_* fd and handle it. This is called either
232 * during the early stages of being a local sender (up through the sending
233 * of the file list) or when we're the generator (to fetch the messages
234 * from the receiver). */
235 static void read_msg_fd(void)
242 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
243 * to this routine from writefd_unbuffered(). */
246 read_loop(fd, buf, 4);
249 len = tag & 0xFFFFFF;
250 tag = (tag >> 24) - MPLEX_BASE;
254 if (len != 0 || !am_generator) {
255 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
256 exit_cleanup(RERR_STREAMIO);
258 flist_ndx_push(&redo_list, -1);
261 if (len != 4 || !am_generator) {
262 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
263 exit_cleanup(RERR_STREAMIO);
265 read_loop(fd, buf, 4);
266 if (remove_sent_files)
267 decrement_active_files(IVAL(buf,0));
268 flist_ndx_push(&redo_list, IVAL(buf,0));
271 if (len >= (int)sizeof buf || !am_generator) {
272 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
273 exit_cleanup(RERR_STREAMIO);
275 read_loop(fd, buf, len);
276 if (defer_forwarding_messages)
277 msg_list_add(&msg2sndr, MSG_DELETED, buf, len);
279 io_multiplex_write(MSG_DELETED, buf, len);
282 if (len != 4 || !am_generator) {
283 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
284 exit_cleanup(RERR_STREAMIO);
286 read_loop(fd, buf, len);
287 if (remove_sent_files) {
288 decrement_active_files(IVAL(buf,0));
289 if (defer_forwarding_messages)
290 msg_list_add(&msg2sndr, MSG_SUCCESS, buf, len);
292 io_multiplex_write(MSG_SUCCESS, buf, len);
294 if (preserve_hard_links)
295 flist_ndx_push(&hlink_list, IVAL(buf,0));
299 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
300 exit_cleanup(RERR_STREAMIO);
302 close_multiplexing_out();
311 read_loop(fd, buf, n);
312 if (am_generator && am_server && defer_forwarding_messages)
313 msg_list_add(&msg2sndr, tag, buf, n);
315 rwrite((enum logcode)tag, buf, n);
320 rprintf(FERROR, "unknown message %d:%d [%s]\n",
321 tag, len, who_am_i());
322 exit_cleanup(RERR_STREAMIO);
328 /* This is used by the generator to limit how many file transfers can
329 * be active at once when --remove-sent-files is specified. Without
330 * this, sender-side deletions were mostly happening at the end. */
331 void increment_active_files(int ndx, int itemizing, enum logcode code)
333 /* TODO: tune these limits? */
334 while (active_filecnt >= (active_bytecnt >= 128*1024 ? 10 : 50)) {
336 check_for_finished_hlinks(itemizing, code);
341 active_bytecnt += the_file_list->files[ndx]->length;
344 void decrement_active_files(int ndx)
347 active_bytecnt -= the_file_list->files[ndx]->length;
350 /* Try to push messages off the list onto the wire. If we leave with more
351 * to do, return 0. On error, return -1. If everything flushed, return 1.
352 * This is only active in the receiver. */
353 static int msg2genr_flush(int flush_it_all)
355 static int written = 0;
362 while (msg2genr.head) {
363 struct msg_list_item *m = msg2genr.head;
364 int n = write(msg_fd_out, m->buf + written, m->len - written);
368 if (errno != EWOULDBLOCK && errno != EAGAIN)
373 FD_SET(msg_fd_out, &fds);
374 tv.tv_sec = select_timeout;
376 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
378 } else if ((written += n) == m->len) {
379 msg2genr.head = m->next;
381 msg2genr.tail = NULL;
389 void send_msg(enum msgcode code, char *buf, int len)
391 if (msg_fd_out < 0) {
392 io_multiplex_write(code, buf, len);
395 msg_list_add(&msg2genr, code, buf, len);
396 msg2genr_flush(NORMAL_FLUSH);
399 int get_redo_num(int itemizing, enum logcode code)
403 check_for_finished_hlinks(itemizing, code);
409 return flist_ndx_pop(&redo_list);
412 int get_hlink_num(void)
414 return flist_ndx_pop(&hlink_list);
418 * When we're the receiver and we have a local --files-from list of names
419 * that needs to be sent over the socket to the sender, we have to do two
420 * things at the same time: send the sender a list of what files we're
421 * processing and read the incoming file+info list from the sender. We do
422 * this by augmenting the read_timeout() function to copy this data. It
423 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
424 * ready, since it might be a pipe) and then blast it out f_out (when it
425 * is ready to receive more data).
427 void io_set_filesfrom_fds(int f_in, int f_out)
429 io_filesfrom_f_in = f_in;
430 io_filesfrom_f_out = f_out;
431 io_filesfrom_bp = io_filesfrom_buf;
432 io_filesfrom_lastchar = '\0';
433 io_filesfrom_buflen = 0;
436 /* It's almost always an error to get an EOF when we're trying to read from the
437 * network, because the protocol is (for the most part) self-terminating.
439 * There is one case for the receiver when it is at the end of the transfer
440 * (hanging around reading any keep-alive packets that might come its way): if
441 * the sender dies before the generator's kill-signal comes through, we can end
442 * up here needing to loop until the kill-signal arrives. In this situation,
443 * kluge_around_eof will be < 0.
445 * There is another case for older protocol versions (< 24) where the module
446 * listing was not terminated, so we must ignore an EOF error in that case and
447 * exit. In this situation, kluge_around_eof will be > 0. */
448 static void whine_about_eof(int fd)
450 if (kluge_around_eof && fd == sock_f_in) {
452 if (kluge_around_eof > 0)
454 /* If we're still here after 10 seconds, exit with an error. */
455 for (i = 10*1000/20; i--; )
459 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
460 "(%.0f bytes received so far) [%s]\n",
461 (double)stats.total_read, who_am_i());
463 exit_cleanup(RERR_STREAMIO);
467 * Read from a socket with I/O timeout. return the number of bytes
468 * read. If no bytes can be read then exit, never return a number <= 0.
470 * TODO: If the remote shell connection fails, then current versions
471 * actually report an "unexpected EOF" error here. Since it's a
472 * fairly common mistake to try to use rsh when ssh is required, we
473 * should trap that: if we fail to read any data at all, we should
474 * give a better explanation. We can tell whether the connection has
475 * started by looking e.g. at whether the remote version is known yet.
477 static int read_timeout(int fd, char *buf, size_t len)
481 io_flush(NORMAL_FLUSH);
484 /* until we manage to read *something* */
494 FD_SET(msg_fd_out, &w_fds);
495 if (msg_fd_out > maxfd)
498 if (io_filesfrom_f_out >= 0) {
500 if (io_filesfrom_buflen == 0) {
501 if (io_filesfrom_f_in >= 0) {
502 FD_SET(io_filesfrom_f_in, &r_fds);
503 new_fd = io_filesfrom_f_in;
505 io_filesfrom_f_out = -1;
509 FD_SET(io_filesfrom_f_out, &w_fds);
510 new_fd = io_filesfrom_f_out;
516 tv.tv_sec = select_timeout;
521 count = select(maxfd + 1, &r_fds, &w_fds, NULL, &tv);
525 exit_cleanup(RERR_SOCKETIO);
530 if (msg2genr.head && FD_ISSET(msg_fd_out, &w_fds))
531 msg2genr_flush(NORMAL_FLUSH);
533 if (io_filesfrom_f_out >= 0) {
534 if (io_filesfrom_buflen) {
535 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
536 int l = write(io_filesfrom_f_out,
538 io_filesfrom_buflen);
540 if (!(io_filesfrom_buflen -= l))
541 io_filesfrom_bp = io_filesfrom_buf;
543 io_filesfrom_bp += l;
545 /* XXX should we complain? */
546 io_filesfrom_f_out = -1;
549 } else if (io_filesfrom_f_in >= 0) {
550 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
551 int l = read(io_filesfrom_f_in,
553 sizeof io_filesfrom_buf);
555 /* Send end-of-file marker */
556 io_filesfrom_buf[0] = '\0';
557 io_filesfrom_buf[1] = '\0';
558 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
559 io_filesfrom_f_in = -1;
562 char *s = io_filesfrom_buf + l;
563 /* Transform CR and/or LF into '\0' */
564 while (s-- > io_filesfrom_buf) {
565 if (*s == '\n' || *s == '\r')
569 if (!io_filesfrom_lastchar) {
570 /* Last buf ended with a '\0', so don't
571 * let this buf start with one. */
572 while (l && !*io_filesfrom_bp)
573 io_filesfrom_bp++, l--;
576 io_filesfrom_bp = io_filesfrom_buf;
578 char *f = io_filesfrom_bp;
581 /* Eliminate any multi-'\0' runs. */
583 if (!(*t++ = *f++)) {
584 while (f != eob && !*f)
588 io_filesfrom_lastchar = f[-1];
590 io_filesfrom_buflen = l;
596 if (!FD_ISSET(fd, &r_fds))
599 n = read(fd, buf, len);
603 whine_about_eof(fd); /* Doesn't return. */
604 if (errno == EINTR || errno == EWOULDBLOCK
608 /* Don't write errors on a dead socket. */
609 if (fd == sock_f_in) {
610 close_multiplexing_out();
611 rsyserr(FSOCKERR, errno, "read error");
613 rsyserr(FERROR, errno, "read error");
614 exit_cleanup(RERR_STREAMIO);
621 if (fd == sock_f_in && io_timeout)
622 last_io_in = time(NULL);
629 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
632 int read_filesfrom_line(int fd, char *fname)
634 char ch, *s, *eob = fname + MAXPATHLEN - 1;
636 int reading_remotely = filesfrom_host != NULL;
637 int nulls = eol_nulls || reading_remotely;
642 cnt = read(fd, &ch, 1);
643 if (cnt < 0 && (errno == EWOULDBLOCK
644 || errno == EINTR || errno == EAGAIN)) {
649 tv.tv_sec = select_timeout;
651 if (!select(fd+1, &fds, NULL, NULL, &tv))
657 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
658 /* Skip empty lines if reading locally. */
659 if (!reading_remotely && s == fname)
669 if (*fname == '#' || *fname == ';')
675 static char *iobuf_out;
676 static int iobuf_out_cnt;
678 void io_start_buffering_out(void)
682 if (!(iobuf_out = new_array(char, IO_BUFFER_SIZE)))
683 out_of_memory("io_start_buffering_out");
687 static char *iobuf_in;
688 static size_t iobuf_in_siz;
690 void io_start_buffering_in(void)
694 iobuf_in_siz = 2 * IO_BUFFER_SIZE;
695 if (!(iobuf_in = new_array(char, iobuf_in_siz)))
696 out_of_memory("io_start_buffering_in");
699 void io_end_buffering(void)
701 io_flush(NORMAL_FLUSH);
702 if (!io_multiplexing_out) {
708 void maybe_flush_socket(void)
710 if (iobuf_out && iobuf_out_cnt && time(NULL) - last_io_out >= 5)
711 io_flush(NORMAL_FLUSH);
714 void maybe_send_keepalive(void)
716 if (time(NULL) - last_io_out >= allowed_lull) {
717 if (!iobuf_out || !iobuf_out_cnt) {
718 if (protocol_version < 29)
719 return; /* there's nothing we can do */
720 write_int(sock_f_out, the_file_list->count);
721 write_shortint(sock_f_out, ITEM_IS_NEW);
724 io_flush(NORMAL_FLUSH);
729 * Continue trying to read len bytes - don't return until len has been
732 static void read_loop(int fd, char *buf, size_t len)
735 int n = read_timeout(fd, buf, len);
743 * Read from the file descriptor handling multiplexing - return number
746 * Never returns <= 0.
748 static int readfd_unbuffered(int fd, char *buf, size_t len)
750 static size_t remaining;
751 static size_t iobuf_in_ndx;
754 char line[BIGPATHBUFLEN];
756 if (!iobuf_in || fd != sock_f_in)
757 return read_timeout(fd, buf, len);
759 if (!io_multiplexing_in && remaining == 0) {
760 remaining = read_timeout(fd, iobuf_in, iobuf_in_siz);
766 len = MIN(len, remaining);
767 memcpy(buf, iobuf_in + iobuf_in_ndx, len);
774 read_loop(fd, line, 4);
777 msg_bytes = tag & 0xFFFFFF;
778 tag = (tag >> 24) - MPLEX_BASE;
782 if (msg_bytes > iobuf_in_siz) {
783 if (!(iobuf_in = realloc_array(iobuf_in, char,
785 out_of_memory("readfd_unbuffered");
786 iobuf_in_siz = msg_bytes;
788 read_loop(fd, iobuf_in, msg_bytes);
789 remaining = msg_bytes;
793 if (msg_bytes >= sizeof line)
795 read_loop(fd, line, msg_bytes);
796 /* A directory name was sent with the trailing null */
797 if (msg_bytes > 0 && !line[msg_bytes-1])
798 log_delete(line, S_IFDIR);
800 line[msg_bytes] = '\0';
801 log_delete(line, S_IFREG);
805 if (msg_bytes != 4) {
806 rprintf(FERROR, "invalid multi-message %d:%ld [%s]\n",
807 tag, (long)msg_bytes, who_am_i());
808 exit_cleanup(RERR_STREAMIO);
810 read_loop(fd, line, msg_bytes);
811 successful_send(IVAL(line, 0));
815 if (msg_bytes >= sizeof line) {
818 "multiplexing overflow %d:%ld [%s]\n",
819 tag, (long)msg_bytes, who_am_i());
820 exit_cleanup(RERR_STREAMIO);
822 read_loop(fd, line, msg_bytes);
823 rwrite((enum logcode)tag, line, msg_bytes);
826 rprintf(FERROR, "unexpected tag %d [%s]\n",
828 exit_cleanup(RERR_STREAMIO);
833 io_flush(NORMAL_FLUSH);
839 * Do a buffered read from @p fd. Don't return until all @p n bytes
840 * have been read. If all @p n can't be read then exit with an
843 static void readfd(int fd, char *buffer, size_t N)
849 cnt = readfd_unbuffered(fd, buffer + total, N-total);
853 if (fd == write_batch_monitor_in) {
854 if ((size_t)write(batch_fd, buffer, total) != total)
855 exit_cleanup(RERR_FILEIO);
859 stats.total_read += total;
862 int read_shortint(int f)
865 readfd(f, (char *)b, 2);
866 return (b[1] << 8) + b[0];
869 int32 read_int(int f)
876 if (num == (int32)0xffffffff)
881 int64 read_longint(int f)
887 if ((int32)num != (int32)0xffffffff)
891 rprintf(FERROR, "Integer overflow: attempted 64-bit offset\n");
892 exit_cleanup(RERR_UNSUPPORTED);
895 num = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
901 void read_buf(int f,char *buf,size_t len)
906 void read_sbuf(int f,char *buf,size_t len)
912 uchar read_byte(int f)
915 readfd(f, (char *)&c, 1);
919 int read_vstring(int f, char *buf, int bufsize)
921 int len = read_byte(f);
924 len = (len & ~0x80) * 0x100 + read_byte(f);
926 if (len >= bufsize) {
927 rprintf(FERROR, "over-long vstring received (%d > %d)\n",
938 /* Populate a sum_struct with values from the socket. This is
939 * called by both the sender and the receiver. */
940 void read_sum_head(int f, struct sum_struct *sum)
942 sum->count = read_int(f);
943 if (sum->count < 0) {
944 rprintf(FERROR, "Invalid checksum count %ld [%s]\n",
945 (long)sum->count, who_am_i());
946 exit_cleanup(RERR_PROTOCOL);
948 sum->blength = read_int(f);
949 if (sum->blength < 0 || sum->blength > MAX_BLOCK_SIZE) {
950 rprintf(FERROR, "Invalid block length %ld [%s]\n",
951 (long)sum->blength, who_am_i());
952 exit_cleanup(RERR_PROTOCOL);
954 sum->s2length = protocol_version < 27 ? csum_length : (int)read_int(f);
955 if (sum->s2length < 0 || sum->s2length > MD4_SUM_LENGTH) {
956 rprintf(FERROR, "Invalid checksum length %d [%s]\n",
957 sum->s2length, who_am_i());
958 exit_cleanup(RERR_PROTOCOL);
960 sum->remainder = read_int(f);
961 if (sum->remainder < 0 || sum->remainder > sum->blength) {
962 rprintf(FERROR, "Invalid remainder length %ld [%s]\n",
963 (long)sum->remainder, who_am_i());
964 exit_cleanup(RERR_PROTOCOL);
968 /* Send the values from a sum_struct over the socket. Set sum to
969 * NULL if there are no checksums to send. This is called by both
970 * the generator and the sender. */
971 void write_sum_head(int f, struct sum_struct *sum)
973 static struct sum_struct null_sum;
978 write_int(f, sum->count);
979 write_int(f, sum->blength);
980 if (protocol_version >= 27)
981 write_int(f, sum->s2length);
982 write_int(f, sum->remainder);
986 * Sleep after writing to limit I/O bandwidth usage.
988 * @todo Rather than sleeping after each write, it might be better to
989 * use some kind of averaging. The current algorithm seems to always
990 * use a bit less bandwidth than specified, because it doesn't make up
991 * for slow periods. But arguably this is a feature. In addition, we
992 * ought to take the time used to write the data into account.
994 * During some phases of big transfers (file FOO is uptodate) this is
995 * called with a small bytes_written every time. As the kernel has to
996 * round small waits up to guarantee that we actually wait at least the
997 * requested number of microseconds, this can become grossly inaccurate.
998 * We therefore keep track of the bytes we've written over time and only
999 * sleep when the accumulated delay is at least 1 tenth of a second.
1001 static void sleep_for_bwlimit(int bytes_written)
1003 static struct timeval prior_tv;
1004 static long total_written = 0;
1005 struct timeval tv, start_tv;
1006 long elapsed_usec, sleep_usec;
1008 #define ONE_SEC 1000000L /* # of microseconds in a second */
1010 if (!bwlimit_writemax)
1013 total_written += bytes_written;
1015 gettimeofday(&start_tv, NULL);
1016 if (prior_tv.tv_sec) {
1017 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
1018 + (start_tv.tv_usec - prior_tv.tv_usec);
1019 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
1020 if (total_written < 0)
1024 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
1025 if (sleep_usec < ONE_SEC / 10) {
1026 prior_tv = start_tv;
1030 tv.tv_sec = sleep_usec / ONE_SEC;
1031 tv.tv_usec = sleep_usec % ONE_SEC;
1032 select(0, NULL, NULL, NULL, &tv);
1034 gettimeofday(&prior_tv, NULL);
1035 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
1036 + (prior_tv.tv_usec - start_tv.tv_usec);
1037 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
1040 /* Write len bytes to the file descriptor fd, looping as necessary to get
1041 * the job done and also (in certain circumstances) reading any data on
1042 * msg_fd_in to avoid deadlock.
1044 * This function underlies the multiplexing system. The body of the
1045 * application never calls this function directly. */
1046 static void writefd_unbuffered(int fd,char *buf,size_t len)
1048 size_t n, total = 0;
1049 fd_set w_fds, r_fds;
1050 int maxfd, count, cnt, using_r_fds;
1051 int defer_save = defer_forwarding_messages;
1056 while (total < len) {
1061 if (msg_fd_in >= 0) {
1063 FD_SET(msg_fd_in,&r_fds);
1064 if (msg_fd_in > maxfd)
1070 tv.tv_sec = select_timeout;
1074 count = select(maxfd + 1, using_r_fds ? &r_fds : NULL,
1078 if (count < 0 && errno == EBADF)
1079 exit_cleanup(RERR_SOCKETIO);
1084 if (using_r_fds && FD_ISSET(msg_fd_in, &r_fds))
1087 if (!FD_ISSET(fd, &w_fds))
1091 if (bwlimit_writemax && n > bwlimit_writemax)
1092 n = bwlimit_writemax;
1093 cnt = write(fd, buf + total, n);
1099 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1105 /* Don't try to write errors back across the stream. */
1106 if (fd == sock_f_out)
1107 close_multiplexing_out();
1108 rsyserr(FERROR, errno,
1109 "writefd_unbuffered failed to write %ld bytes [%s]",
1110 (long)len, who_am_i());
1111 /* If the other side is sending us error messages, try
1112 * to grab any messages they sent before they died. */
1113 while (fd == sock_f_out && io_multiplexing_in) {
1116 readfd_unbuffered(sock_f_in, io_filesfrom_buf,
1117 sizeof io_filesfrom_buf);
1119 exit_cleanup(RERR_STREAMIO);
1123 defer_forwarding_messages = 1;
1125 if (fd == sock_f_out) {
1126 if (io_timeout || am_generator)
1127 last_io_out = time(NULL);
1128 sleep_for_bwlimit(cnt);
1132 defer_forwarding_messages = defer_save;
1136 static void msg2sndr_flush(void)
1138 if (defer_forwarding_messages)
1141 while (msg2sndr.head && io_multiplexing_out) {
1142 struct msg_list_item *m = msg2sndr.head;
1143 if (!(msg2sndr.head = m->next))
1144 msg2sndr.tail = NULL;
1145 stats.total_written += m->len;
1146 defer_forwarding_messages = 1;
1147 writefd_unbuffered(sock_f_out, m->buf, m->len);
1148 defer_forwarding_messages = 0;
1154 * Write an message to a multiplexed stream. If this fails then rsync
1157 static void mplex_write(enum msgcode code, char *buf, size_t len)
1162 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
1164 if (n > sizeof buffer - 4)
1167 memcpy(buffer + 4, buf, n);
1169 writefd_unbuffered(sock_f_out, buffer, n+4);
1175 defer_forwarding_messages = 1;
1176 writefd_unbuffered(sock_f_out, buf, len);
1177 defer_forwarding_messages = 0;
1182 void io_flush(int flush_it_all)
1184 msg2genr_flush(flush_it_all);
1187 if (!iobuf_out_cnt || no_flush)
1190 if (io_multiplexing_out)
1191 mplex_write(MSG_DATA, iobuf_out, iobuf_out_cnt);
1193 writefd_unbuffered(sock_f_out, iobuf_out, iobuf_out_cnt);
1197 static void writefd(int fd,char *buf,size_t len)
1199 if (fd == msg_fd_out) {
1200 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
1201 exit_cleanup(RERR_PROTOCOL);
1204 if (fd == sock_f_out)
1205 stats.total_written += len;
1207 if (fd == write_batch_monitor_out) {
1208 if ((size_t)write(batch_fd, buf, len) != len)
1209 exit_cleanup(RERR_FILEIO);
1212 if (!iobuf_out || fd != sock_f_out) {
1213 writefd_unbuffered(fd, buf, len);
1218 int n = MIN((int)len, IO_BUFFER_SIZE - iobuf_out_cnt);
1220 memcpy(iobuf_out+iobuf_out_cnt, buf, n);
1226 if (iobuf_out_cnt == IO_BUFFER_SIZE)
1227 io_flush(NORMAL_FLUSH);
1231 void write_shortint(int f, int x)
1236 writefd(f, (char *)b, 2);
1239 void write_int(int f,int32 x)
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;