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;
51 extern int io_timeout;
55 extern struct stats stats;
58 const char phase_unknown[] = "unknown";
61 * The connection might be dropped at some point; perhaps because the
62 * remote instance crashed. Just giving the offset on the stream is
63 * not very helpful. So instead we try to make io_phase_name point to
66 * For buffered/multiplexed I/O these names will be somewhat
67 * approximate; perhaps for ease of support we would rather make the
68 * buffer always flush when a single application-level I/O finishes.
70 * @todo Perhaps we want some simple stack functionality, but there's
71 * no need to overdo it.
73 const char *io_write_phase = phase_unknown;
74 const char *io_read_phase = phase_unknown;
76 /** Ignore EOF errors while reading a module listing if the remote
77 version is 24 or less. */
78 int kludge_around_eof = False;
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;
90 static void read_loop(int fd, char *buf, size_t len);
93 struct redo_list *next;
97 static struct redo_list *redo_list_head;
98 static struct redo_list *redo_list_tail;
101 struct msg_list *next;
106 static struct msg_list *msg_list_head;
107 static struct msg_list *msg_list_tail;
109 static void redo_list_add(int num)
111 struct redo_list *rl;
113 if (!(rl = new(struct redo_list)))
114 exit_cleanup(RERR_MALLOC);
118 redo_list_tail->next = rl;
124 static void check_timeout(void)
132 last_io = time(NULL);
138 if (last_io && io_timeout && (t-last_io) >= io_timeout) {
139 if (!am_server && !am_daemon) {
140 rprintf(FERROR, "io timeout after %d seconds - exiting\n",
143 exit_cleanup(RERR_TIMEOUT);
147 /** Setup the fd used to receive MSG_* messages. Only needed when
148 * we're the generator because the sender and receiver both use the
149 * multiplexed I/O setup. */
150 void set_msg_fd_in(int fd)
155 /** Setup the fd used to send our MSG_* messages. Only needed when
156 * we're the receiver because the generator and the sender both use
157 * the multiplexed I/O setup. */
158 void set_msg_fd_out(int fd)
161 set_nonblocking(msg_fd_out);
164 /* Add a message to the pending MSG_* list. */
165 static void msg_list_add(int code, char *buf, int len)
169 if (!(ml = new(struct msg_list)))
170 exit_cleanup(RERR_MALLOC);
172 if (!(ml->buf = new_array(char, len+4)))
173 exit_cleanup(RERR_MALLOC);
174 SIVAL(ml->buf, 0, ((code+MPLEX_BASE)<<24) | len);
175 memcpy(ml->buf+4, buf, len);
178 msg_list_tail->next = ml;
184 void send_msg(enum msgcode code, char *buf, int len)
186 msg_list_add(code, buf, len);
187 msg_list_push(NORMAL_FLUSH);
190 /** Read a message from the MSG_* fd and dispatch it. This is only
191 * called by the generator. */
192 static void read_msg_fd(void)
199 /* Temporarily disable msg_fd_in. This is needed because we
200 * may call a write routine that could try to call us back. */
203 read_loop(fd, buf, 4);
206 len = tag & 0xFFFFFF;
207 tag = (tag >> 24) - MPLEX_BASE;
212 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
213 exit_cleanup(RERR_STREAMIO);
219 rprintf(FERROR, "invalid message %d:%d\n", tag, len);
220 exit_cleanup(RERR_STREAMIO);
222 read_loop(fd, buf, 4);
223 redo_list_add(IVAL(buf,0));
232 read_loop(fd, buf, n);
233 rwrite((enum logcode)tag, buf, n);
238 rprintf(FERROR, "unknown message %d:%d\n", tag, len);
239 exit_cleanup(RERR_STREAMIO);
245 /* Try to push messages off the list onto the wire. If we leave with more
246 * to do, return 0. On error, return -1. If everything flushed, return 1.
247 * This is only called by the receiver. */
248 int msg_list_push(int flush_it_all)
250 static int written = 0;
257 while (msg_list_head) {
258 struct msg_list *ml = msg_list_head;
259 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
263 if (errno != EWOULDBLOCK && errno != EAGAIN)
268 FD_SET(msg_fd_out, &fds);
269 tv.tv_sec = io_timeout ? io_timeout : SELECT_TIMEOUT;
271 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
273 } else if ((written += n) == ml->len) {
275 msg_list_head = ml->next;
277 msg_list_tail = NULL;
285 int get_redo_num(void)
287 struct redo_list *next;
290 while (!redo_list_head)
293 num = redo_list_head->num;
294 next = redo_list_head->next;
295 free(redo_list_head);
296 redo_list_head = next;
298 redo_list_tail = NULL;
304 * When we're the receiver and we have a local --files-from list of names
305 * that needs to be sent over the socket to the sender, we have to do two
306 * things at the same time: send the sender a list of what files we're
307 * processing and read the incoming file+info list from the sender. We do
308 * this by augmenting the read_timeout() function to copy this data. It
309 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
310 * ready, since it might be a pipe) and then blast it out f_out (when it
311 * is ready to receive more data).
313 void io_set_filesfrom_fds(int f_in, int f_out)
315 io_filesfrom_f_in = f_in;
316 io_filesfrom_f_out = f_out;
317 io_filesfrom_bp = io_filesfrom_buf;
318 io_filesfrom_lastchar = '\0';
319 io_filesfrom_buflen = 0;
323 * It's almost always an error to get an EOF when we're trying to read
324 * from the network, because the protocol is self-terminating.
326 * However, there is one unfortunate cases where it is not, which is
327 * rsync <2.4.6 sending a list of modules on a server, since the list
328 * is terminated by closing the socket. So, for the section of the
329 * program where that is a problem (start_socket_client),
330 * kludge_around_eof is True and we just exit.
332 static void whine_about_eof(void)
334 if (kludge_around_eof)
337 rprintf(FERROR, RSYNC_NAME ": connection unexpectedly closed "
338 "(%.0f bytes read so far)\n",
339 (double)stats.total_read);
341 exit_cleanup(RERR_STREAMIO);
346 static void die_from_readerr(int err)
348 /* this prevents us trying to write errors on a dead socket */
349 io_multiplexing_close();
351 rsyserr(FERROR, err, "read error");
352 exit_cleanup(RERR_STREAMIO);
357 * Read from a socket with I/O timeout. return the number of bytes
358 * read. If no bytes can be read then exit, never return a number <= 0.
360 * TODO: If the remote shell connection fails, then current versions
361 * actually report an "unexpected EOF" error here. Since it's a
362 * fairly common mistake to try to use rsh when ssh is required, we
363 * should trap that: if we fail to read any data at all, we should
364 * give a better explanation. We can tell whether the connection has
365 * started by looking e.g. at whether the remote version is known yet.
367 static int read_timeout(int fd, char *buf, size_t len)
371 io_flush(NORMAL_FLUSH);
374 /* until we manage to read *something* */
382 if (msg_fd_in >= 0) {
383 FD_SET(msg_fd_in, &r_fds);
384 if (msg_fd_in >= fd_count)
385 fd_count = msg_fd_in+1;
387 if (io_filesfrom_f_out >= 0) {
389 if (io_filesfrom_buflen == 0) {
390 if (io_filesfrom_f_in >= 0) {
391 FD_SET(io_filesfrom_f_in, &r_fds);
392 new_fd = io_filesfrom_f_in;
394 io_filesfrom_f_out = -1;
399 FD_SET(io_filesfrom_f_out, &w_fds);
400 new_fd = io_filesfrom_f_out;
402 if (new_fd >= fd_count)
406 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
411 count = select(fd_count, &r_fds,
412 io_filesfrom_buflen? &w_fds : NULL,
416 msg_list_push(NORMAL_FLUSH);
421 if (errno == EBADF) {
422 exit_cleanup(RERR_SOCKETIO);
427 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
430 if (io_filesfrom_f_out >= 0) {
431 if (io_filesfrom_buflen) {
432 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
433 int l = write(io_filesfrom_f_out,
435 io_filesfrom_buflen);
437 if (!(io_filesfrom_buflen -= l))
438 io_filesfrom_bp = io_filesfrom_buf;
440 io_filesfrom_bp += l;
442 /* XXX should we complain? */
443 io_filesfrom_f_out = -1;
446 } else if (io_filesfrom_f_in >= 0) {
447 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
448 int l = read(io_filesfrom_f_in,
450 sizeof io_filesfrom_buf);
452 /* Send end-of-file marker */
453 io_filesfrom_buf[0] = '\0';
454 io_filesfrom_buf[1] = '\0';
455 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
456 io_filesfrom_f_in = -1;
458 extern int eol_nulls;
460 char *s = io_filesfrom_buf + l;
461 /* Transform CR and/or LF into '\0' */
462 while (s-- > io_filesfrom_buf) {
463 if (*s == '\n' || *s == '\r')
467 if (!io_filesfrom_lastchar) {
468 /* Last buf ended with a '\0', so don't
469 * let this buf start with one. */
470 while (l && !*io_filesfrom_bp)
471 io_filesfrom_bp++, l--;
474 io_filesfrom_bp = io_filesfrom_buf;
476 char *f = io_filesfrom_bp;
479 /* Eliminate any multi-'\0' runs. */
481 if (!(*t++ = *f++)) {
482 while (f != eob && !*f)
486 io_filesfrom_lastchar = f[-1];
488 io_filesfrom_buflen = l;
494 if (!FD_ISSET(fd, &r_fds)) continue;
496 n = read(fd, buf, len);
503 last_io = time(NULL);
507 return -1; /* doesn't return */
509 if (errno == EINTR || errno == EWOULDBLOCK
512 die_from_readerr(errno);
520 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
523 int read_filesfrom_line(int fd, char *fname)
525 char ch, *s, *eob = fname + MAXPATHLEN - 1;
527 extern int io_timeout;
528 extern int eol_nulls;
529 extern char *remote_filesfrom_file;
530 int reading_remotely = remote_filesfrom_file != NULL;
531 int nulls = eol_nulls || reading_remotely;
536 cnt = read(fd, &ch, 1);
537 if (cnt < 0 && (errno == EWOULDBLOCK
538 || errno == EINTR || errno == EAGAIN)) {
543 tv.tv_sec = io_timeout? io_timeout : SELECT_TIMEOUT;
545 if (!select(fd+1, &fds, NULL, NULL, &tv))
551 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
552 /* Skip empty lines if reading locally. */
553 if (!reading_remotely && s == fname)
563 if (*fname == '#' || *fname == ';')
571 * Continue trying to read len bytes - don't return until len has been
574 static void read_loop(int fd, char *buf, size_t len)
577 int n = read_timeout(fd, buf, len);
586 * Read from the file descriptor handling multiplexing - return number
589 * Never returns <= 0.
591 static int read_unbuffered(int fd, char *buf, size_t len)
593 static size_t remaining;
597 static size_t bufferIdx = 0;
598 static size_t bufferSz;
600 if (fd != multiplex_in_fd)
601 return read_timeout(fd, buf, len);
603 if (!io_multiplexing_in && remaining == 0) {
605 bufferSz = 2 * IO_BUFFER_SIZE;
606 buffer = new_array(char, bufferSz);
607 if (!buffer) out_of_memory("read_unbuffered");
609 remaining = read_timeout(fd, buffer, bufferSz);
615 len = MIN(len, remaining);
616 memcpy(buf, buffer + bufferIdx, len);
623 read_loop(fd, line, 4);
626 remaining = tag & 0xFFFFFF;
627 tag = (tag >> 24) - MPLEX_BASE;
631 if (!buffer || remaining > bufferSz) {
632 buffer = realloc_array(buffer, char, remaining);
633 if (!buffer) out_of_memory("read_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 = read_unbuffered(fd, buffer + total, N-total);
679 stats.total_read += total;
683 int32 read_int(int f)
690 if (ret == (int32)0xffffffff) return -1;
694 int64 read_longint(int f)
700 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 static void sleep_for_bwlimit(int bytes_written)
750 assert(bytes_written > 0);
753 tv.tv_usec = bytes_written * 1000 / bwlimit;
754 tv.tv_sec = tv.tv_usec / 1000000;
755 tv.tv_usec = tv.tv_usec % 1000000;
757 select(0, NULL, NULL, NULL, &tv);
762 * Write len bytes to the file descriptor @p fd.
764 * This function underlies the multiplexing system. The body of the
765 * application never calls this function directly.
767 static void writefd_unbuffered(int fd,char *buf,size_t len)
774 msg_list_push(NORMAL_FLUSH);
778 while (total < len) {
783 if (msg_fd_in >= 0) {
785 FD_SET(msg_fd_in,&r_fds);
786 if (msg_fd_in > fd_count)
787 fd_count = msg_fd_in;
790 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
794 count = select(fd_count+1, msg_fd_in >= 0 ? &r_fds : NULL,
798 msg_list_push(NORMAL_FLUSH);
803 if (errno == EBADF) {
804 exit_cleanup(RERR_SOCKETIO);
809 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
812 if (FD_ISSET(fd, &w_fds)) {
814 size_t n = len-total;
815 ret = write(fd,buf+total,n);
820 if (errno == EWOULDBLOCK || errno == EAGAIN) {
827 /* Don't try to write errors back
828 * across the stream */
829 io_multiplexing_close();
830 rsyserr(FERROR, errno,
831 "writefd_unbuffered failed to write %ld bytes: phase \"%s\"",
832 (long) len, io_write_phase);
833 exit_cleanup(RERR_STREAMIO);
836 sleep_for_bwlimit(ret);
841 last_io = time(NULL);
849 static char *io_buffer;
850 static int io_buffer_count;
852 void io_start_buffering_out(int fd)
854 if (io_buffer) return;
855 multiplex_out_fd = fd;
856 io_buffer = new_array(char, IO_BUFFER_SIZE);
857 if (!io_buffer) out_of_memory("writefd");
861 void io_start_buffering_in(int fd)
863 multiplex_in_fd = fd;
867 * Write an message to a multiplexed stream. If this fails then rsync
870 static void mplex_write(int fd, enum msgcode code, char *buf, size_t len)
875 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
877 if (n > (sizeof buffer - 4)) {
878 n = sizeof buffer - 4;
881 memcpy(&buffer[4], buf, n);
882 writefd_unbuffered(fd, buffer, n+4);
888 writefd_unbuffered(fd, buf, len);
893 void io_flush(int flush_it_all)
895 int fd = multiplex_out_fd;
897 msg_list_push(flush_it_all);
899 if (!io_buffer_count || no_flush)
902 if (io_multiplexing_out)
903 mplex_write(fd, MSG_DATA, io_buffer, io_buffer_count);
905 writefd_unbuffered(fd, io_buffer, io_buffer_count);
910 void io_end_buffering(void)
912 io_flush(NORMAL_FLUSH);
913 if (!io_multiplexing_out) {
919 static void writefd(int fd,char *buf,size_t len)
921 stats.total_written += len;
923 msg_list_push(NORMAL_FLUSH);
925 if (!io_buffer || fd != multiplex_out_fd) {
926 writefd_unbuffered(fd, buf, len);
931 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
933 memcpy(io_buffer+io_buffer_count, buf, n);
936 io_buffer_count += n;
939 if (io_buffer_count == IO_BUFFER_SIZE)
940 io_flush(NORMAL_FLUSH);
945 void write_int(int f,int32 x)
953 void write_int_named(int f, int32 x, const char *phase)
955 io_write_phase = phase;
957 io_write_phase = phase_unknown;
962 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
963 * 64-bit types on this platform.
965 void write_longint(int f, int64 x)
969 if (x <= 0x7FFFFFFF) {
970 write_int(f, (int)x);
975 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
976 exit_cleanup(RERR_UNSUPPORTED);
978 write_int(f, (int32)0xFFFFFFFF);
979 SIVAL(b,0,(x&0xFFFFFFFF));
980 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
986 void write_buf(int f,char *buf,size_t len)
991 /** Write a string to the connection */
992 static void write_sbuf(int f,char *buf)
994 write_buf(f, buf, strlen(buf));
998 void write_byte(int f,unsigned char c)
1000 write_buf(f,(char *)&c,1);
1006 * Read a line of up to @p maxlen characters into @p buf (not counting
1007 * the trailing null). Strips the (required) trailing newline and all
1010 * @return 1 for success; 0 for I/O error or truncation.
1012 int read_line(int f, char *buf, size_t maxlen)
1016 read_buf(f, buf, 1);
1021 if (buf[0] != '\r') {
1031 void io_printf(int fd, const char *format, ...)
1037 va_start(ap, format);
1038 len = vsnprintf(buf, sizeof buf, format, ap);
1041 if (len < 0) exit_cleanup(RERR_STREAMIO);
1043 write_sbuf(fd, buf);
1047 /** Setup for multiplexing a MSG_* stream with the data stream. */
1048 void io_start_multiplex_out(int fd)
1050 multiplex_out_fd = fd;
1051 io_flush(NORMAL_FLUSH);
1052 io_start_buffering_out(fd);
1053 io_multiplexing_out = 1;
1056 /** Setup for multiplexing a MSG_* stream with the data stream. */
1057 void io_start_multiplex_in(int fd)
1059 multiplex_in_fd = fd;
1060 io_flush(NORMAL_FLUSH);
1061 io_multiplexing_in = 1;
1064 /** Write an message to the multiplexed data stream. */
1065 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1067 if (!io_multiplexing_out) return 0;
1069 io_flush(NORMAL_FLUSH);
1070 stats.total_written += (len+4);
1071 mplex_write(multiplex_out_fd, code, buf, len);
1075 /** Stop output multiplexing. */
1076 void io_multiplexing_close(void)
1078 io_multiplexing_out = 0;