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
42 static int io_multiplexing_out;
43 static int io_multiplexing_in;
44 static int multiplex_in_fd = -1;
45 static int multiplex_out_fd = -1;
46 static time_t last_io;
50 extern size_t bwlimit_writemax;
52 extern int io_timeout;
57 extern char *remote_filesfrom_file;
58 extern struct stats stats;
60 const char phase_unknown[] = "unknown";
61 int select_timeout = SELECT_TIMEOUT;
64 * The connection might be dropped at some point; perhaps because the
65 * remote instance crashed. Just giving the offset on the stream is
66 * not very helpful. So instead we try to make io_phase_name point to
69 * For buffered/multiplexed I/O these names will be somewhat
70 * approximate; perhaps for ease of support we would rather make the
71 * buffer always flush when a single application-level I/O finishes.
73 * @todo Perhaps we want some simple stack functionality, but there's
74 * no need to overdo it.
76 const char *io_write_phase = phase_unknown;
77 const char *io_read_phase = phase_unknown;
79 /** Ignore EOF errors while reading a module listing if the remote
80 version is 24 or less. */
81 int kludge_around_eof = False;
86 static int io_filesfrom_f_in = -1;
87 static int io_filesfrom_f_out = -1;
88 static char io_filesfrom_buf[2048];
89 static char *io_filesfrom_bp;
90 static char io_filesfrom_lastchar;
91 static int io_filesfrom_buflen;
93 static void read_loop(int fd, char *buf, size_t len);
96 struct redo_list *next;
100 static struct redo_list *redo_list_head;
101 static struct redo_list *redo_list_tail;
104 struct msg_list *next;
109 static struct msg_list *msg_list_head;
110 static struct msg_list *msg_list_tail;
112 static void redo_list_add(int num)
114 struct redo_list *rl;
116 if (!(rl = new(struct redo_list)))
117 exit_cleanup(RERR_MALLOC);
121 redo_list_tail->next = rl;
127 static void check_timeout(void)
135 last_io = time(NULL);
141 if (last_io && io_timeout && (t-last_io) >= io_timeout) {
142 if (!am_server && !am_daemon) {
143 rprintf(FERROR, "io timeout after %d seconds - exiting\n",
146 exit_cleanup(RERR_TIMEOUT);
150 /** Setup the fd used to receive MSG_* messages. Only needed when
151 * we're the generator because the sender and receiver both use the
152 * multiplexed I/O setup. */
153 void set_msg_fd_in(int fd)
158 /** Setup the fd used to send our MSG_* messages. Only needed when
159 * we're the receiver because the generator and the sender both use
160 * the multiplexed I/O setup. */
161 void set_msg_fd_out(int fd)
164 set_nonblocking(msg_fd_out);
167 /* Add a message to the pending MSG_* list. */
168 static void msg_list_add(int code, char *buf, int len)
172 if (!(ml = new(struct msg_list)))
173 exit_cleanup(RERR_MALLOC);
175 if (!(ml->buf = new_array(char, len+4)))
176 exit_cleanup(RERR_MALLOC);
177 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
178 memcpy(ml->buf+4, buf, len);
181 msg_list_tail->next = ml;
187 void send_msg(enum msgcode code, char *buf, int len)
189 msg_list_add(code, buf, len);
190 msg_list_push(NORMAL_FLUSH);
193 /** Read a message from the MSG_* fd and dispatch it. This is only
194 * called by the generator. */
195 static void read_msg_fd(void)
202 /* Temporarily disable msg_fd_in. This is needed to avoid looping back
203 * to this routine from read_timeout() and writefd_unbuffered(). */
206 read_loop(fd, buf, 4);
209 len = tag & 0xFFFFFF;
210 tag = (tag >> 24) - MPLEX_BASE;
215 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
216 exit_cleanup(RERR_STREAMIO);
222 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
223 exit_cleanup(RERR_STREAMIO);
225 read_loop(fd, buf, 4);
226 redo_list_add(IVAL(buf,0));
235 read_loop(fd, buf, n);
236 rwrite((enum logcode)tag, buf, n);
241 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
242 exit_cleanup(RERR_STREAMIO);
248 /* Try to push messages off the list onto the wire. If we leave with more
249 * to do, return 0. On error, return -1. If everything flushed, return 1.
250 * This is only active in the receiver. */
251 int msg_list_push(int flush_it_all)
253 static int written = 0;
260 while (msg_list_head) {
261 struct msg_list *ml = msg_list_head;
262 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
266 if (errno != EWOULDBLOCK && errno != EAGAIN)
271 FD_SET(msg_fd_out, &fds);
272 tv.tv_sec = select_timeout;
274 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
276 } else if ((written += n) == ml->len) {
278 msg_list_head = ml->next;
280 msg_list_tail = NULL;
288 int get_redo_num(void)
290 struct redo_list *next;
293 while (!redo_list_head)
296 num = redo_list_head->num;
297 next = redo_list_head->next;
298 free(redo_list_head);
299 redo_list_head = next;
301 redo_list_tail = NULL;
307 * When we're the receiver and we have a local --files-from list of names
308 * that needs to be sent over the socket to the sender, we have to do two
309 * things at the same time: send the sender a list of what files we're
310 * processing and read the incoming file+info list from the sender. We do
311 * this by augmenting the read_timeout() function to copy this data. It
312 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
313 * ready, since it might be a pipe) and then blast it out f_out (when it
314 * is ready to receive more data).
316 void io_set_filesfrom_fds(int f_in, int f_out)
318 io_filesfrom_f_in = f_in;
319 io_filesfrom_f_out = f_out;
320 io_filesfrom_bp = io_filesfrom_buf;
321 io_filesfrom_lastchar = '\0';
322 io_filesfrom_buflen = 0;
326 * It's almost always an error to get an EOF when we're trying to read
327 * from the network, because the protocol is self-terminating.
329 * However, there is one unfortunate cases where it is not, which is
330 * rsync <2.4.6 sending a list of modules on a server, since the list
331 * is terminated by closing the socket. So, for the section of the
332 * program where that is a problem (start_socket_client),
333 * kludge_around_eof is True and we just exit.
335 static void whine_about_eof(void)
337 if (kludge_around_eof)
340 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
341 "(%.0f bytes read so far)\n",
342 (double)stats.total_read);
344 exit_cleanup(RERR_STREAMIO);
348 static void die_from_readerr(int err)
350 /* this prevents us trying to write errors on a dead socket */
351 io_multiplexing_close();
353 rsyserr(FERROR, err, "read error");
354 exit_cleanup(RERR_STREAMIO);
359 * Read from a socket with I/O timeout. return the number of bytes
360 * read. If no bytes can be read then exit, never return a number <= 0.
362 * TODO: If the remote shell connection fails, then current versions
363 * actually report an "unexpected EOF" error here. Since it's a
364 * fairly common mistake to try to use rsh when ssh is required, we
365 * should trap that: if we fail to read any data at all, we should
366 * give a better explanation. We can tell whether the connection has
367 * started by looking e.g. at whether the remote version is known yet.
369 static int read_timeout(int fd, char *buf, size_t len)
373 io_flush(NORMAL_FLUSH);
376 /* until we manage to read *something* */
384 if (msg_fd_in >= 0) {
385 FD_SET(msg_fd_in, &r_fds);
386 if (msg_fd_in > maxfd)
388 } else if (msg_list_head) {
389 FD_SET(msg_fd_out, &w_fds);
390 if (msg_fd_out > maxfd)
393 if (io_filesfrom_f_out >= 0) {
395 if (io_filesfrom_buflen == 0) {
396 if (io_filesfrom_f_in >= 0) {
397 FD_SET(io_filesfrom_f_in, &r_fds);
398 new_fd = io_filesfrom_f_in;
400 io_filesfrom_f_out = -1;
405 FD_SET(io_filesfrom_f_out, &w_fds);
406 new_fd = io_filesfrom_f_out;
412 tv.tv_sec = select_timeout;
417 count = select(maxfd + 1, &r_fds,
418 io_filesfrom_buflen? &w_fds : NULL,
423 exit_cleanup(RERR_SOCKETIO);
428 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
430 else if (msg_list_head && FD_ISSET(msg_fd_out, &w_fds))
431 msg_list_push(NORMAL_FLUSH);
433 if (io_filesfrom_f_out >= 0) {
434 if (io_filesfrom_buflen) {
435 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
436 int l = write(io_filesfrom_f_out,
438 io_filesfrom_buflen);
440 if (!(io_filesfrom_buflen -= l))
441 io_filesfrom_bp = io_filesfrom_buf;
443 io_filesfrom_bp += l;
445 /* XXX should we complain? */
446 io_filesfrom_f_out = -1;
449 } else if (io_filesfrom_f_in >= 0) {
450 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
451 int l = read(io_filesfrom_f_in,
453 sizeof io_filesfrom_buf);
455 /* Send end-of-file marker */
456 io_filesfrom_buf[0] = '\0';
457 io_filesfrom_buf[1] = '\0';
458 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
459 io_filesfrom_f_in = -1;
462 char *s = io_filesfrom_buf + l;
463 /* Transform CR and/or LF into '\0' */
464 while (s-- > io_filesfrom_buf) {
465 if (*s == '\n' || *s == '\r')
469 if (!io_filesfrom_lastchar) {
470 /* Last buf ended with a '\0', so don't
471 * let this buf start with one. */
472 while (l && !*io_filesfrom_bp)
473 io_filesfrom_bp++, l--;
476 io_filesfrom_bp = io_filesfrom_buf;
478 char *f = io_filesfrom_bp;
481 /* Eliminate any multi-'\0' runs. */
483 if (!(*t++ = *f++)) {
484 while (f != eob && !*f)
488 io_filesfrom_lastchar = f[-1];
490 io_filesfrom_buflen = l;
496 if (!FD_ISSET(fd, &r_fds))
499 n = read(fd, buf, len);
503 whine_about_eof(); /* Doesn't return. */
504 if (errno == EINTR || errno == EWOULDBLOCK
507 die_from_readerr(errno); /* Doesn't return. */
514 last_io = time(NULL);
521 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
524 int read_filesfrom_line(int fd, char *fname)
526 char ch, *s, *eob = fname + MAXPATHLEN - 1;
528 int reading_remotely = remote_filesfrom_file != NULL;
529 int nulls = eol_nulls || reading_remotely;
534 cnt = read(fd, &ch, 1);
535 if (cnt < 0 && (errno == EWOULDBLOCK
536 || errno == EINTR || errno == EAGAIN)) {
541 tv.tv_sec = select_timeout;
543 if (!select(fd+1, &fds, NULL, NULL, &tv))
549 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
550 /* Skip empty lines if reading locally. */
551 if (!reading_remotely && s == fname)
561 if (*fname == '#' || *fname == ';')
569 * Continue trying to read len bytes - don't return until len has been
572 static void read_loop(int fd, char *buf, size_t len)
575 int n = read_timeout(fd, buf, len);
584 * Read from the file descriptor handling multiplexing - return number
587 * Never returns <= 0.
589 static int readfd_unbuffered(int fd, char *buf, size_t len)
591 static size_t remaining;
595 static size_t bufferIdx = 0;
596 static size_t bufferSz;
598 if (fd != multiplex_in_fd)
599 return read_timeout(fd, buf, len);
601 if (!io_multiplexing_in && remaining == 0) {
603 bufferSz = 2 * IO_BUFFER_SIZE;
604 buffer = new_array(char, bufferSz);
606 out_of_memory("readfd_unbuffered");
608 remaining = read_timeout(fd, buffer, bufferSz);
614 len = MIN(len, remaining);
615 memcpy(buf, buffer + bufferIdx, len);
622 read_loop(fd, line, 4);
625 remaining = tag & 0xFFFFFF;
626 tag = (tag >> 24) - MPLEX_BASE;
630 if (!buffer || remaining > bufferSz) {
631 buffer = realloc_array(buffer, char, remaining);
633 out_of_memory("readfd_unbuffered");
634 bufferSz = remaining;
636 read_loop(fd, buffer, remaining);
641 if (remaining >= sizeof line) {
642 rprintf(FERROR, "multiplexing overflow %d:%ld\n\n",
643 tag, (long)remaining);
644 exit_cleanup(RERR_STREAMIO);
646 read_loop(fd, line, remaining);
647 rwrite((enum logcode)tag, line, remaining);
651 rprintf(FERROR, "unexpected tag %d\n", tag);
652 exit_cleanup(RERR_STREAMIO);
657 io_flush(NORMAL_FLUSH);
665 * Do a buffered read from @p fd. Don't return until all @p n bytes
666 * have been read. If all @p n can't be read then exit with an
669 static void readfd(int fd, char *buffer, size_t N)
675 ret = readfd_unbuffered(fd, buffer + total, N-total);
679 stats.total_read += total;
683 int32 read_int(int f)
690 if (ret == (int32)0xffffffff)
695 int64 read_longint(int f)
701 if ((int32)ret != (int32)0xffffffff)
705 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
706 exit_cleanup(RERR_UNSUPPORTED);
709 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
715 void read_buf(int f,char *buf,size_t len)
720 void read_sbuf(int f,char *buf,size_t len)
726 unsigned char read_byte(int f)
729 read_buf(f, (char *)&c, 1);
735 * Sleep after writing to limit I/O bandwidth usage.
737 * @todo Rather than sleeping after each write, it might be better to
738 * use some kind of averaging. The current algorithm seems to always
739 * use a bit less bandwidth than specified, because it doesn't make up
740 * for slow periods. But arguably this is a feature. In addition, we
741 * ought to take the time used to write the data into account.
743 * During some phases of big transfers (file FOO is uptodate) this is
744 * called with a small bytes_written every time. As the kernel has to
745 * round small waits up to guarantee that we actually wait at least the
746 * requested number of microseconds, this can become grossly inaccurate.
747 * We therefore keep track of the bytes we've written over time and only
748 * sleep when the accumulated delay is at least 1 tenth of a second.
750 static void sleep_for_bwlimit(int bytes_written)
752 static struct timeval prior_tv;
753 static long total_written = 0;
754 struct timeval tv, start_tv;
755 long elapsed_usec, sleep_usec;
757 #define ONE_SEC 1000000L /* # of microseconds in a second */
762 total_written += bytes_written;
764 gettimeofday(&start_tv, NULL);
765 if (prior_tv.tv_sec) {
766 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
767 + (start_tv.tv_usec - prior_tv.tv_usec);
768 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
769 if (total_written < 0)
773 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
774 if (sleep_usec < ONE_SEC / 10) {
779 tv.tv_sec = sleep_usec / ONE_SEC;
780 tv.tv_usec = sleep_usec % ONE_SEC;
781 select(0, NULL, NULL, NULL, &tv);
783 gettimeofday(&prior_tv, NULL);
784 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
785 + (prior_tv.tv_usec - start_tv.tv_usec);
786 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
791 * Write len bytes to the file descriptor @p fd.
793 * This function underlies the multiplexing system. The body of the
794 * application never calls this function directly.
796 static void writefd_unbuffered(int fd,char *buf,size_t len)
800 int maxfd, count, ret;
803 if (fd == msg_fd_out) {
804 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
805 exit_cleanup(RERR_PROTOCOL);
810 while (total < len) {
815 if (msg_fd_in >= 0) {
817 FD_SET(msg_fd_in,&r_fds);
818 if (msg_fd_in > maxfd)
822 tv.tv_sec = select_timeout;
826 count = select(maxfd + 1, msg_fd_in >= 0 ? &r_fds : NULL,
830 if (count < 0 && errno == EBADF)
831 exit_cleanup(RERR_SOCKETIO);
836 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
839 if (!FD_ISSET(fd, &w_fds))
843 if (bwlimit && n > bwlimit_writemax)
844 n = bwlimit_writemax;
845 ret = write(fd, buf + total, n);
851 if (errno == EWOULDBLOCK || errno == EAGAIN) {
857 /* Don't try to write errors back across the stream. */
858 io_multiplexing_close();
859 rsyserr(FERROR, errno,
860 "writefd_unbuffered failed to write %ld bytes: phase \"%s\"",
861 (long)len, io_write_phase);
862 exit_cleanup(RERR_STREAMIO);
865 sleep_for_bwlimit(ret);
870 last_io = time(NULL);
877 static char *io_buffer;
878 static int io_buffer_count;
880 void io_start_buffering_out(int fd)
884 multiplex_out_fd = fd;
885 io_buffer = new_array(char, IO_BUFFER_SIZE);
887 out_of_memory("writefd");
891 void io_start_buffering_in(int fd)
893 multiplex_in_fd = fd;
897 * Write an message to a multiplexed stream. If this fails then rsync
900 static void mplex_write(int fd, enum msgcode code, char *buf, size_t len)
905 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
907 if (n > sizeof buffer - 4)
908 n = sizeof buffer - 4;
910 memcpy(&buffer[4], buf, n);
911 writefd_unbuffered(fd, buffer, n+4);
917 writefd_unbuffered(fd, buf, len);
921 void io_flush(int flush_it_all)
923 int fd = multiplex_out_fd;
925 msg_list_push(flush_it_all);
927 if (!io_buffer_count || no_flush)
930 if (io_multiplexing_out)
931 mplex_write(fd, MSG_DATA, io_buffer, io_buffer_count);
933 writefd_unbuffered(fd, io_buffer, io_buffer_count);
938 void io_end_buffering(void)
940 io_flush(NORMAL_FLUSH);
941 if (!io_multiplexing_out) {
947 static void writefd(int fd,char *buf,size_t len)
949 stats.total_written += len;
951 if (fd == msg_fd_out) {
952 rprintf(FERROR, "Internal error: wrong write used in receiver.\n");
953 exit_cleanup(RERR_PROTOCOL);
956 if (!io_buffer || fd != multiplex_out_fd) {
957 writefd_unbuffered(fd, buf, len);
962 int n = MIN((int)len, IO_BUFFER_SIZE-io_buffer_count);
964 memcpy(io_buffer+io_buffer_count, buf, n);
967 io_buffer_count += n;
970 if (io_buffer_count == IO_BUFFER_SIZE)
971 io_flush(NORMAL_FLUSH);
976 void write_int(int f,int32 x)
984 void write_int_named(int f, int32 x, const char *phase)
986 io_write_phase = phase;
988 io_write_phase = phase_unknown;
993 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
994 * 64-bit types on this platform.
996 void write_longint(int f, int64 x)
1000 if (x <= 0x7FFFFFFF) {
1001 write_int(f, (int)x);
1006 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
1007 exit_cleanup(RERR_UNSUPPORTED);
1009 write_int(f, (int32)0xFFFFFFFF);
1010 SIVAL(b,0,(x&0xFFFFFFFF));
1011 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1017 void write_buf(int f,char *buf,size_t len)
1022 /** Write a string to the connection */
1023 static void write_sbuf(int f,char *buf)
1025 write_buf(f, buf, strlen(buf));
1029 void write_byte(int f,unsigned char c)
1031 write_buf(f,(char *)&c,1);
1037 * Read a line of up to @p maxlen characters into @p buf (not counting
1038 * the trailing null). Strips the (required) trailing newline and all
1041 * @return 1 for success; 0 for I/O error or truncation.
1043 int read_line(int f, char *buf, size_t maxlen)
1047 read_buf(f, buf, 1);
1052 if (buf[0] != '\r') {
1062 void io_printf(int fd, const char *format, ...)
1068 va_start(ap, format);
1069 len = vsnprintf(buf, sizeof buf, format, ap);
1073 exit_cleanup(RERR_STREAMIO);
1075 write_sbuf(fd, buf);
1079 /** Setup for multiplexing a MSG_* stream with the data stream. */
1080 void io_start_multiplex_out(int fd)
1082 multiplex_out_fd = fd;
1083 io_flush(NORMAL_FLUSH);
1084 io_start_buffering_out(fd);
1085 io_multiplexing_out = 1;
1088 /** Setup for multiplexing a MSG_* stream with the data stream. */
1089 void io_start_multiplex_in(int fd)
1091 multiplex_in_fd = fd;
1092 io_flush(NORMAL_FLUSH);
1093 io_multiplexing_in = 1;
1096 /** Write an message to the multiplexed data stream. */
1097 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1099 if (!io_multiplexing_out)
1102 io_flush(NORMAL_FLUSH);
1103 stats.total_written += (len+4);
1104 mplex_write(multiplex_out_fd, code, buf, len);
1108 /** Stop output multiplexing. */
1109 void io_multiplexing_close(void)
1111 io_multiplexing_out = 0;