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;
56 extern struct stats stats;
59 const char phase_unknown[] = "unknown";
62 * The connection might be dropped at some point; perhaps because the
63 * remote instance crashed. Just giving the offset on the stream is
64 * not very helpful. So instead we try to make io_phase_name point to
67 * For buffered/multiplexed I/O these names will be somewhat
68 * approximate; perhaps for ease of support we would rather make the
69 * buffer always flush when a single application-level I/O finishes.
71 * @todo Perhaps we want some simple stack functionality, but there's
72 * no need to overdo it.
74 const char *io_write_phase = phase_unknown;
75 const char *io_read_phase = phase_unknown;
77 /** Ignore EOF errors while reading a module listing if the remote
78 version is 24 or less. */
79 int kludge_around_eof = False;
84 static int io_filesfrom_f_in = -1;
85 static int io_filesfrom_f_out = -1;
86 static char io_filesfrom_buf[2048];
87 static char *io_filesfrom_bp;
88 static char io_filesfrom_lastchar;
89 static int io_filesfrom_buflen;
91 static void read_loop(int fd, char *buf, size_t len);
94 struct redo_list *next;
98 static struct redo_list *redo_list_head;
99 static struct redo_list *redo_list_tail;
102 struct msg_list *next;
107 static struct msg_list *msg_list_head;
108 static struct msg_list *msg_list_tail;
110 static void redo_list_add(int num)
112 struct redo_list *rl;
114 if (!(rl = new(struct redo_list)))
115 exit_cleanup(RERR_MALLOC);
119 redo_list_tail->next = rl;
125 static void check_timeout(void)
133 last_io = time(NULL);
139 if (last_io && io_timeout && (t-last_io) >= io_timeout) {
140 if (!am_server && !am_daemon) {
141 rprintf(FERROR, "io timeout after %d seconds - exiting\n",
144 exit_cleanup(RERR_TIMEOUT);
148 /** Setup the fd used to receive MSG_* messages. Only needed when
149 * we're the generator because the sender and receiver both use the
150 * multiplexed I/O setup. */
151 void set_msg_fd_in(int fd)
156 /** Setup the fd used to send our MSG_* messages. Only needed when
157 * we're the receiver because the generator and the sender both use
158 * the multiplexed I/O setup. */
159 void set_msg_fd_out(int fd)
162 set_nonblocking(msg_fd_out);
165 /* Add a message to the pending MSG_* list. */
166 static void msg_list_add(int code, char *buf, int len)
170 if (!(ml = new(struct msg_list)))
171 exit_cleanup(RERR_MALLOC);
173 if (!(ml->buf = new_array(char, len+4)))
174 exit_cleanup(RERR_MALLOC);
175 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
176 memcpy(ml->buf+4, buf, len);
179 msg_list_tail->next = ml;
185 void send_msg(enum msgcode code, char *buf, int len)
187 msg_list_add(code, buf, len);
188 msg_list_push(NORMAL_FLUSH);
191 /** Read a message from the MSG_* fd and dispatch it. This is only
192 * called by the generator. */
193 static void read_msg_fd(void)
200 /* Temporarily disable msg_fd_in. This is needed because we
201 * may call a write routine that could try to call us back. */
204 read_loop(fd, buf, 4);
207 len = tag & 0xFFFFFF;
208 tag = (tag >> 24) - MPLEX_BASE;
213 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
214 exit_cleanup(RERR_STREAMIO);
220 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
221 exit_cleanup(RERR_STREAMIO);
223 read_loop(fd, buf, 4);
224 redo_list_add(IVAL(buf,0));
233 read_loop(fd, buf, n);
234 rwrite((enum logcode)tag, buf, n);
239 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
240 exit_cleanup(RERR_STREAMIO);
246 /* Try to push messages off the list onto the wire. If we leave with more
247 * to do, return 0. On error, return -1. If everything flushed, return 1.
248 * This is only called by the receiver. */
249 int msg_list_push(int flush_it_all)
251 static int written = 0;
258 while (msg_list_head) {
259 struct msg_list *ml = msg_list_head;
260 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
264 if (errno != EWOULDBLOCK && errno != EAGAIN)
269 FD_SET(msg_fd_out, &fds);
270 tv.tv_sec = io_timeout ? io_timeout : SELECT_TIMEOUT;
272 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
274 } else if ((written += n) == ml->len) {
276 msg_list_head = ml->next;
278 msg_list_tail = NULL;
286 int get_redo_num(void)
288 struct redo_list *next;
291 while (!redo_list_head)
294 num = redo_list_head->num;
295 next = redo_list_head->next;
296 free(redo_list_head);
297 redo_list_head = next;
299 redo_list_tail = NULL;
305 * When we're the receiver and we have a local --files-from list of names
306 * that needs to be sent over the socket to the sender, we have to do two
307 * things at the same time: send the sender a list of what files we're
308 * processing and read the incoming file+info list from the sender. We do
309 * this by augmenting the read_timeout() function to copy this data. It
310 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
311 * ready, since it might be a pipe) and then blast it out f_out (when it
312 * is ready to receive more data).
314 void io_set_filesfrom_fds(int f_in, int f_out)
316 io_filesfrom_f_in = f_in;
317 io_filesfrom_f_out = f_out;
318 io_filesfrom_bp = io_filesfrom_buf;
319 io_filesfrom_lastchar = '\0';
320 io_filesfrom_buflen = 0;
324 * It's almost always an error to get an EOF when we're trying to read
325 * from the network, because the protocol is self-terminating.
327 * However, there is one unfortunate cases where it is not, which is
328 * rsync <2.4.6 sending a list of modules on a server, since the list
329 * is terminated by closing the socket. So, for the section of the
330 * program where that is a problem (start_socket_client),
331 * kludge_around_eof is True and we just exit.
333 static void whine_about_eof(void)
335 if (kludge_around_eof)
338 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
339 "(%.0f bytes read so far)\n",
340 (double)stats.total_read);
342 exit_cleanup(RERR_STREAMIO);
347 static void die_from_readerr(int err)
349 /* this prevents us trying to write errors on a dead socket */
350 io_multiplexing_close();
352 rsyserr(FERROR, err, "read error");
353 exit_cleanup(RERR_STREAMIO);
358 * Read from a socket with I/O timeout. return the number of bytes
359 * read. If no bytes can be read then exit, never return a number <= 0.
361 * TODO: If the remote shell connection fails, then current versions
362 * actually report an "unexpected EOF" error here. Since it's a
363 * fairly common mistake to try to use rsh when ssh is required, we
364 * should trap that: if we fail to read any data at all, we should
365 * give a better explanation. We can tell whether the connection has
366 * started by looking e.g. at whether the remote version is known yet.
368 static int read_timeout(int fd, char *buf, size_t len)
372 io_flush(NORMAL_FLUSH);
375 /* until we manage to read *something* */
383 if (msg_fd_in >= 0) {
384 FD_SET(msg_fd_in, &r_fds);
385 if (msg_fd_in >= fd_count)
386 fd_count = msg_fd_in+1;
388 if (io_filesfrom_f_out >= 0) {
390 if (io_filesfrom_buflen == 0) {
391 if (io_filesfrom_f_in >= 0) {
392 FD_SET(io_filesfrom_f_in, &r_fds);
393 new_fd = io_filesfrom_f_in;
395 io_filesfrom_f_out = -1;
400 FD_SET(io_filesfrom_f_out, &w_fds);
401 new_fd = io_filesfrom_f_out;
403 if (new_fd >= fd_count)
407 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
412 count = select(fd_count, &r_fds,
413 io_filesfrom_buflen? &w_fds : NULL,
417 msg_list_push(NORMAL_FLUSH);
422 if (errno == EBADF) {
423 exit_cleanup(RERR_SOCKETIO);
428 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
431 if (io_filesfrom_f_out >= 0) {
432 if (io_filesfrom_buflen) {
433 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
434 int l = write(io_filesfrom_f_out,
436 io_filesfrom_buflen);
438 if (!(io_filesfrom_buflen -= l))
439 io_filesfrom_bp = io_filesfrom_buf;
441 io_filesfrom_bp += l;
443 /* XXX should we complain? */
444 io_filesfrom_f_out = -1;
447 } else if (io_filesfrom_f_in >= 0) {
448 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
449 int l = read(io_filesfrom_f_in,
451 sizeof io_filesfrom_buf);
453 /* Send end-of-file marker */
454 io_filesfrom_buf[0] = '\0';
455 io_filesfrom_buf[1] = '\0';
456 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
457 io_filesfrom_f_in = -1;
459 extern int eol_nulls;
461 char *s = io_filesfrom_buf + l;
462 /* Transform CR and/or LF into '\0' */
463 while (s-- > io_filesfrom_buf) {
464 if (*s == '\n' || *s == '\r')
468 if (!io_filesfrom_lastchar) {
469 /* Last buf ended with a '\0', so don't
470 * let this buf start with one. */
471 while (l && !*io_filesfrom_bp)
472 io_filesfrom_bp++, l--;
475 io_filesfrom_bp = io_filesfrom_buf;
477 char *f = io_filesfrom_bp;
480 /* Eliminate any multi-'\0' runs. */
482 if (!(*t++ = *f++)) {
483 while (f != eob && !*f)
487 io_filesfrom_lastchar = f[-1];
489 io_filesfrom_buflen = l;
495 if (!FD_ISSET(fd, &r_fds)) continue;
497 n = read(fd, buf, len);
504 last_io = time(NULL);
508 return -1; /* doesn't return */
510 if (errno == EINTR || errno == EWOULDBLOCK
513 die_from_readerr(errno);
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 extern int io_timeout;
529 extern int eol_nulls;
530 extern char *remote_filesfrom_file;
531 int reading_remotely = remote_filesfrom_file != NULL;
532 int nulls = eol_nulls || reading_remotely;
537 cnt = read(fd, &ch, 1);
538 if (cnt < 0 && (errno == EWOULDBLOCK
539 || errno == EINTR || errno == EAGAIN)) {
544 tv.tv_sec = io_timeout? io_timeout : SELECT_TIMEOUT;
546 if (!select(fd+1, &fds, NULL, NULL, &tv))
552 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
553 /* Skip empty lines if reading locally. */
554 if (!reading_remotely && s == fname)
564 if (*fname == '#' || *fname == ';')
572 * Continue trying to read len bytes - don't return until len has been
575 static void read_loop(int fd, char *buf, size_t len)
578 int n = read_timeout(fd, buf, len);
587 * Read from the file descriptor handling multiplexing - return number
590 * Never returns <= 0.
592 static int read_unbuffered(int fd, char *buf, size_t len)
594 static size_t remaining;
598 static size_t bufferIdx = 0;
599 static size_t bufferSz;
601 if (fd != multiplex_in_fd)
602 return read_timeout(fd, buf, len);
604 if (!io_multiplexing_in && remaining == 0) {
606 bufferSz = 2 * IO_BUFFER_SIZE;
607 buffer = new_array(char, bufferSz);
608 if (!buffer) out_of_memory("read_unbuffered");
610 remaining = read_timeout(fd, buffer, bufferSz);
616 len = MIN(len, remaining);
617 memcpy(buf, buffer + bufferIdx, len);
624 read_loop(fd, line, 4);
627 remaining = tag & 0xFFFFFF;
628 tag = (tag >> 24) - MPLEX_BASE;
632 if (!buffer || remaining > bufferSz) {
633 buffer = realloc_array(buffer, char, remaining);
634 if (!buffer) out_of_memory("read_unbuffered");
635 bufferSz = remaining;
637 read_loop(fd, buffer, remaining);
642 if (remaining >= sizeof line) {
643 rprintf(FERROR, "multiplexing overflow %d:%ld\n\n",
644 tag, (long)remaining);
645 exit_cleanup(RERR_STREAMIO);
647 read_loop(fd, line, remaining);
648 rwrite((enum logcode)tag, line, remaining);
652 rprintf(FERROR, "unexpected tag %d\n", tag);
653 exit_cleanup(RERR_STREAMIO);
658 io_flush(NORMAL_FLUSH);
666 * Do a buffered read from @p fd. Don't return until all @p n bytes
667 * have been read. If all @p n can't be read then exit with an
670 static void readfd(int fd, char *buffer, size_t N)
676 ret = read_unbuffered(fd, buffer + total, N-total);
680 stats.total_read += total;
684 int32 read_int(int f)
691 if (ret == (int32)0xffffffff) return -1;
695 int64 read_longint(int f)
701 if ((int32)ret != (int32)0xffffffff) {
706 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
707 exit_cleanup(RERR_UNSUPPORTED);
710 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
716 void read_buf(int f,char *buf,size_t len)
721 void read_sbuf(int f,char *buf,size_t len)
727 unsigned char read_byte(int f)
730 read_buf(f, (char *)&c, 1);
736 * Sleep after writing to limit I/O bandwidth usage.
738 * @todo Rather than sleeping after each write, it might be better to
739 * use some kind of averaging. The current algorithm seems to always
740 * use a bit less bandwidth than specified, because it doesn't make up
741 * for slow periods. But arguably this is a feature. In addition, we
742 * ought to take the time used to write the data into account.
744 * During some phases of big transfers (file FOO is uptodate) this is
745 * called with a small bytes_written every time. As the kernel has to
746 * round small waits up to guarantee that we actually wait at least the
747 * requested number of microseconds, this can become grossly inaccurate.
748 * We therefore keep track of the bytes we've written over time and only
749 * sleep when the accumulated delay is at least 1 tenth of a second.
751 static void sleep_for_bwlimit(int bytes_written)
753 static struct timeval prior_tv;
754 static long total_written = 0;
755 struct timeval tv, start_tv;
756 long elapsed_usec, sleep_usec;
758 #define ONE_SEC 1000000L /* # of microseconds in a second */
763 total_written += bytes_written;
765 gettimeofday(&start_tv, NULL);
766 if (prior_tv.tv_sec) {
767 elapsed_usec = (start_tv.tv_sec - prior_tv.tv_sec) * ONE_SEC
768 + (start_tv.tv_usec - prior_tv.tv_usec);
769 total_written -= elapsed_usec * bwlimit / (ONE_SEC/1024);
770 if (total_written < 0)
774 sleep_usec = total_written * (ONE_SEC/1024) / bwlimit;
775 if (sleep_usec < ONE_SEC / 10) {
780 tv.tv_sec = sleep_usec / ONE_SEC;
781 tv.tv_usec = sleep_usec % ONE_SEC;
782 select(0, NULL, NULL, NULL, &tv);
784 gettimeofday(&prior_tv, NULL);
785 elapsed_usec = (prior_tv.tv_sec - start_tv.tv_sec) * ONE_SEC
786 + (prior_tv.tv_usec - start_tv.tv_usec);
787 total_written = (sleep_usec - elapsed_usec) * bwlimit / (ONE_SEC/1024);
792 * Write len bytes to the file descriptor @p fd.
794 * This function underlies the multiplexing system. The body of the
795 * application never calls this function directly.
797 static void writefd_unbuffered(int fd,char *buf,size_t len)
804 msg_list_push(NORMAL_FLUSH);
808 while (total < len) {
813 if (msg_fd_in >= 0) {
815 FD_SET(msg_fd_in,&r_fds);
816 if (msg_fd_in > fd_count)
817 fd_count = msg_fd_in;
820 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
824 count = select(fd_count+1, msg_fd_in >= 0 ? &r_fds : NULL,
828 msg_list_push(NORMAL_FLUSH);
833 if (errno == EBADF) {
834 exit_cleanup(RERR_SOCKETIO);
839 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
842 if (FD_ISSET(fd, &w_fds)) {
844 size_t n = len-total;
845 if (bwlimit && n > bwlimit_writemax)
846 n = bwlimit_writemax;
847 ret = write(fd,buf+total,n);
852 if (errno == EWOULDBLOCK || errno == EAGAIN) {
859 /* Don't try to write errors back
860 * across the stream */
861 io_multiplexing_close();
862 rsyserr(FERROR, errno,
863 "writefd_unbuffered failed to write %ld bytes: phase \"%s\"",
864 (long) len, io_write_phase);
865 exit_cleanup(RERR_STREAMIO);
868 sleep_for_bwlimit(ret);
873 last_io = time(NULL);
881 static char *io_buffer;
882 static int io_buffer_count;
884 void io_start_buffering_out(int fd)
886 if (io_buffer) return;
887 multiplex_out_fd = fd;
888 io_buffer = new_array(char, IO_BUFFER_SIZE);
889 if (!io_buffer) out_of_memory("writefd");
893 void io_start_buffering_in(int fd)
895 multiplex_in_fd = fd;
899 * Write an message to a multiplexed stream. If this fails then rsync
902 static void mplex_write(int fd, enum msgcode code, char *buf, size_t len)
907 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
909 if (n > (sizeof buffer - 4)) {
910 n = sizeof buffer - 4;
913 memcpy(&buffer[4], buf, n);
914 writefd_unbuffered(fd, buffer, n+4);
920 writefd_unbuffered(fd, buf, len);
925 void io_flush(int flush_it_all)
927 int fd = multiplex_out_fd;
929 msg_list_push(flush_it_all);
931 if (!io_buffer_count || no_flush)
934 if (io_multiplexing_out)
935 mplex_write(fd, MSG_DATA, io_buffer, io_buffer_count);
937 writefd_unbuffered(fd, io_buffer, io_buffer_count);
942 void io_end_buffering(void)
944 io_flush(NORMAL_FLUSH);
945 if (!io_multiplexing_out) {
951 static void writefd(int fd,char *buf,size_t len)
953 stats.total_written += len;
955 msg_list_push(NORMAL_FLUSH);
957 if (!io_buffer || fd != multiplex_out_fd) {
958 writefd_unbuffered(fd, buf, len);
963 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
965 memcpy(io_buffer+io_buffer_count, buf, n);
968 io_buffer_count += n;
971 if (io_buffer_count == IO_BUFFER_SIZE)
972 io_flush(NORMAL_FLUSH);
977 void write_int(int f,int32 x)
985 void write_int_named(int f, int32 x, const char *phase)
987 io_write_phase = phase;
989 io_write_phase = phase_unknown;
994 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
995 * 64-bit types on this platform.
997 void write_longint(int f, int64 x)
1001 if (x <= 0x7FFFFFFF) {
1002 write_int(f, (int)x);
1007 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
1008 exit_cleanup(RERR_UNSUPPORTED);
1010 write_int(f, (int32)0xFFFFFFFF);
1011 SIVAL(b,0,(x&0xFFFFFFFF));
1012 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
1018 void write_buf(int f,char *buf,size_t len)
1023 /** Write a string to the connection */
1024 static void write_sbuf(int f,char *buf)
1026 write_buf(f, buf, strlen(buf));
1030 void write_byte(int f,unsigned char c)
1032 write_buf(f,(char *)&c,1);
1038 * Read a line of up to @p maxlen characters into @p buf (not counting
1039 * the trailing null). Strips the (required) trailing newline and all
1042 * @return 1 for success; 0 for I/O error or truncation.
1044 int read_line(int f, char *buf, size_t maxlen)
1048 read_buf(f, buf, 1);
1053 if (buf[0] != '\r') {
1063 void io_printf(int fd, const char *format, ...)
1069 va_start(ap, format);
1070 len = vsnprintf(buf, sizeof buf, format, ap);
1073 if (len < 0) 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) return 0;
1101 io_flush(NORMAL_FLUSH);
1102 stats.total_written += (len+4);
1103 mplex_write(multiplex_out_fd, code, buf, len);
1107 /** Stop output multiplexing. */
1108 void io_multiplexing_close(void)
1110 io_multiplexing_out = 0;