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 IO 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 IO 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 IO 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 IO 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 IO 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 exit_cleanup(RERR_STREAMIO);
217 exit_cleanup(RERR_STREAMIO);
218 read_loop(fd, buf, 4);
219 redo_list_add(IVAL(buf,0));
228 read_loop(fd, buf, n);
229 rwrite((enum logcode)tag, buf, n);
234 exit_cleanup(RERR_STREAMIO);
240 /* Try to push messages off the list onto the wire. If we leave with more
241 * to do, return 0. On error, return -1. If everything flushed, return 1.
242 * This is only called by the receiver. */
243 int msg_list_push(int flush_it_all)
245 static int written = 0;
252 while (msg_list_head) {
253 struct msg_list *ml = msg_list_head;
254 int n = write(msg_fd_out, ml->buf + written, ml->len - written);
258 if (errno != EWOULDBLOCK && errno != EAGAIN)
263 FD_SET(msg_fd_out, &fds);
264 tv.tv_sec = io_timeout ? io_timeout : SELECT_TIMEOUT;
266 if (!select(msg_fd_out+1, NULL, &fds, NULL, &tv))
268 } else if ((written += n) == ml->len) {
270 msg_list_head = ml->next;
272 msg_list_tail = NULL;
280 int get_redo_num(void)
282 struct redo_list *next;
285 while (!redo_list_head)
288 num = redo_list_head->num;
289 next = redo_list_head->next;
290 free(redo_list_head);
291 redo_list_head = next;
293 redo_list_tail = NULL;
299 * When we're the receiver and we have a local --files-from list of names
300 * that needs to be sent over the socket to the sender, we have to do two
301 * things at the same time: send the sender a list of what files we're
302 * processing and read the incoming file+info list from the sender. We do
303 * this by augmenting the read_timeout() function to copy this data. It
304 * uses the io_filesfrom_buf to read a block of data from f_in (when it is
305 * ready, since it might be a pipe) and then blast it out f_out (when it
306 * is ready to receive more data).
308 void io_set_filesfrom_fds(int f_in, int f_out)
310 io_filesfrom_f_in = f_in;
311 io_filesfrom_f_out = f_out;
312 io_filesfrom_bp = io_filesfrom_buf;
313 io_filesfrom_lastchar = '\0';
314 io_filesfrom_buflen = 0;
318 * It's almost always an error to get an EOF when we're trying to read
319 * from the network, because the protocol is self-terminating.
321 * However, there is one unfortunate cases where it is not, which is
322 * rsync <2.4.6 sending a list of modules on a server, since the list
323 * is terminated by closing the socket. So, for the section of the
324 * program where that is a problem (start_socket_client),
325 * kludge_around_eof is True and we just exit.
327 static void whine_about_eof(void)
329 if (kludge_around_eof)
333 "%s: connection unexpectedly closed "
334 "(%.0f bytes read so far)\n",
335 RSYNC_NAME, (double)stats.total_read);
337 exit_cleanup(RERR_STREAMIO);
342 static void die_from_readerr(int err)
344 /* this prevents us trying to write errors on a dead socket */
345 io_multiplexing_close();
347 rprintf(FERROR, "%s: read error: %s\n",
348 RSYNC_NAME, strerror(err));
349 exit_cleanup(RERR_STREAMIO);
354 * Read from a socket with IO timeout. return the number of bytes
355 * read. If no bytes can be read then exit, never return a number <= 0.
357 * TODO: If the remote shell connection fails, then current versions
358 * actually report an "unexpected EOF" error here. Since it's a
359 * fairly common mistake to try to use rsh when ssh is required, we
360 * should trap that: if we fail to read any data at all, we should
361 * give a better explanation. We can tell whether the connection has
362 * started by looking e.g. at whether the remote version is known yet.
364 static int read_timeout(int fd, char *buf, size_t len)
368 io_flush(NORMAL_FLUSH);
371 /* until we manage to read *something* */
379 if (msg_fd_in >= 0) {
380 FD_SET(msg_fd_in, &r_fds);
381 if (msg_fd_in >= fd_count)
382 fd_count = msg_fd_in+1;
384 if (io_filesfrom_f_out >= 0) {
386 if (io_filesfrom_buflen == 0) {
387 if (io_filesfrom_f_in >= 0) {
388 FD_SET(io_filesfrom_f_in, &r_fds);
389 new_fd = io_filesfrom_f_in;
391 io_filesfrom_f_out = -1;
396 FD_SET(io_filesfrom_f_out, &w_fds);
397 new_fd = io_filesfrom_f_out;
399 if (new_fd >= fd_count)
403 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
408 count = select(fd_count, &r_fds,
409 io_filesfrom_buflen? &w_fds : NULL,
413 msg_list_push(NORMAL_FLUSH);
418 if (errno == EBADF) {
419 exit_cleanup(RERR_SOCKETIO);
424 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
427 if (io_filesfrom_f_out >= 0) {
428 if (io_filesfrom_buflen) {
429 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
430 int l = write(io_filesfrom_f_out,
432 io_filesfrom_buflen);
434 if (!(io_filesfrom_buflen -= l))
435 io_filesfrom_bp = io_filesfrom_buf;
437 io_filesfrom_bp += l;
439 /* XXX should we complain? */
440 io_filesfrom_f_out = -1;
443 } else if (io_filesfrom_f_in >= 0) {
444 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
445 int l = read(io_filesfrom_f_in,
447 sizeof io_filesfrom_buf);
449 /* Send end-of-file marker */
450 io_filesfrom_buf[0] = '\0';
451 io_filesfrom_buf[1] = '\0';
452 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
453 io_filesfrom_f_in = -1;
455 extern int eol_nulls;
457 char *s = io_filesfrom_buf + l;
458 /* Transform CR and/or LF into '\0' */
459 while (s-- > io_filesfrom_buf) {
460 if (*s == '\n' || *s == '\r')
464 if (!io_filesfrom_lastchar) {
465 /* Last buf ended with a '\0', so don't
466 * let this buf start with one. */
467 while (l && !*io_filesfrom_bp)
468 io_filesfrom_bp++, l--;
471 io_filesfrom_bp = io_filesfrom_buf;
473 char *f = io_filesfrom_bp;
476 /* Eliminate any multi-'\0' runs. */
478 if (!(*t++ = *f++)) {
479 while (f != eob && !*f)
483 io_filesfrom_lastchar = f[-1];
485 io_filesfrom_buflen = l;
491 if (!FD_ISSET(fd, &r_fds)) continue;
493 n = read(fd, buf, len);
500 last_io = time(NULL);
504 return -1; /* doesn't return */
506 if (errno == EINTR || errno == EWOULDBLOCK ||
509 die_from_readerr(errno);
517 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
520 int read_filesfrom_line(int fd, char *fname)
522 char ch, *s, *eob = fname + MAXPATHLEN - 1;
524 extern int io_timeout;
525 extern int eol_nulls;
526 extern char *remote_filesfrom_file;
527 int reading_remotely = remote_filesfrom_file != NULL;
528 int nulls = eol_nulls || reading_remotely;
533 cnt = read(fd, &ch, 1);
534 if (cnt < 0 && (errno == EWOULDBLOCK
535 || errno == EINTR || errno == EAGAIN)) {
540 tv.tv_sec = io_timeout? io_timeout : SELECT_TIMEOUT;
542 if (!select(fd+1, &fds, NULL, NULL, &tv))
548 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
549 /* Skip empty lines if reading locally. */
550 if (!reading_remotely && s == fname)
560 if (*fname == '#' || *fname == ';')
568 * Continue trying to read len bytes - don't return until len has been
571 static void read_loop(int fd, char *buf, size_t len)
574 int n = read_timeout(fd, buf, len);
583 * Read from the file descriptor handling multiplexing - return number
586 * Never returns <= 0.
588 static int read_unbuffered(int fd, char *buf, size_t len)
590 static size_t remaining;
594 static size_t bufferIdx = 0;
595 static size_t bufferSz;
597 if (fd != multiplex_in_fd)
598 return read_timeout(fd, buf, len);
600 if (!io_multiplexing_in && remaining == 0) {
602 bufferSz = 2 * IO_BUFFER_SIZE;
603 buffer = new_array(char, bufferSz);
604 if (!buffer) out_of_memory("read_unbuffered");
606 remaining = read_timeout(fd, buffer, bufferSz);
612 len = MIN(len, remaining);
613 memcpy(buf, buffer + bufferIdx, len);
620 read_loop(fd, line, 4);
623 remaining = tag & 0xFFFFFF;
624 tag = (tag >> 24) - MPLEX_BASE;
628 if (!buffer || remaining > bufferSz) {
629 buffer = realloc_array(buffer, char, remaining);
630 if (!buffer) out_of_memory("read_unbuffered");
631 bufferSz = remaining;
633 read_loop(fd, buffer, remaining);
638 if (remaining >= sizeof line) {
639 rprintf(FERROR, "multiplexing overflow %d:%ld\n\n",
640 tag, (long)remaining);
641 exit_cleanup(RERR_STREAMIO);
643 read_loop(fd, line, remaining);
644 rwrite((enum logcode)tag, line, remaining);
648 rprintf(FERROR, "unexpected tag %d\n", tag);
649 exit_cleanup(RERR_STREAMIO);
654 io_flush(NORMAL_FLUSH);
662 * Do a buffered read from @p fd. Don't return until all @p n bytes
663 * have been read. If all @p n can't be read then exit with an
666 static void readfd(int fd, char *buffer, size_t N)
672 ret = read_unbuffered(fd, buffer + total, N-total);
676 stats.total_read += total;
680 int32 read_int(int f)
687 if (ret == (int32)0xffffffff) return -1;
691 int64 read_longint(int f)
697 if ((int32)ret != (int32)0xffffffff) {
702 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
703 exit_cleanup(RERR_UNSUPPORTED);
706 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
712 void read_buf(int f,char *buf,size_t len)
717 void read_sbuf(int f,char *buf,size_t len)
723 unsigned char read_byte(int f)
726 read_buf(f, (char *)&c, 1);
732 * Sleep after writing to limit I/O bandwidth usage.
734 * @todo Rather than sleeping after each write, it might be better to
735 * use some kind of averaging. The current algorithm seems to always
736 * use a bit less bandwidth than specified, because it doesn't make up
737 * for slow periods. But arguably this is a feature. In addition, we
738 * ought to take the time used to write the data into account.
740 static void sleep_for_bwlimit(int bytes_written)
747 assert(bytes_written > 0);
750 tv.tv_usec = bytes_written * 1000 / bwlimit;
751 tv.tv_sec = tv.tv_usec / 1000000;
752 tv.tv_usec = tv.tv_usec % 1000000;
754 select(0, NULL, NULL, NULL, &tv);
759 * Write len bytes to the file descriptor @p fd.
761 * This function underlies the multiplexing system. The body of the
762 * application never calls this function directly.
764 static void writefd_unbuffered(int fd,char *buf,size_t len)
771 msg_list_push(NORMAL_FLUSH);
775 while (total < len) {
780 if (msg_fd_in >= 0) {
782 FD_SET(msg_fd_in,&r_fds);
783 if (msg_fd_in > fd_count)
784 fd_count = msg_fd_in;
787 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
791 count = select(fd_count+1, msg_fd_in >= 0 ? &r_fds : NULL,
795 msg_list_push(NORMAL_FLUSH);
800 if (errno == EBADF) {
801 exit_cleanup(RERR_SOCKETIO);
806 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
809 if (FD_ISSET(fd, &w_fds)) {
811 size_t n = len-total;
812 ret = write(fd,buf+total,n);
817 if (errno == EWOULDBLOCK || errno == EAGAIN) {
824 /* Don't try to write errors back
825 * across the stream */
826 io_multiplexing_close();
827 rprintf(FERROR, RSYNC_NAME
828 ": writefd_unbuffered failed to write %ld bytes: phase \"%s\": %s\n",
829 (long) len, io_write_phase,
831 exit_cleanup(RERR_STREAMIO);
834 sleep_for_bwlimit(ret);
839 last_io = time(NULL);
847 static char *io_buffer;
848 static int io_buffer_count;
850 void io_start_buffering_out(int fd)
852 if (io_buffer) return;
853 multiplex_out_fd = fd;
854 io_buffer = new_array(char, IO_BUFFER_SIZE);
855 if (!io_buffer) out_of_memory("writefd");
859 void io_start_buffering_in(int fd)
861 multiplex_in_fd = fd;
865 * Write an message to a multiplexed stream. If this fails then rsync
868 static void mplex_write(int fd, enum msgcode code, char *buf, size_t len)
873 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
875 if (n > (sizeof buffer - 4)) {
876 n = sizeof buffer - 4;
879 memcpy(&buffer[4], buf, n);
880 writefd_unbuffered(fd, buffer, n+4);
886 writefd_unbuffered(fd, buf, len);
891 void io_flush(int flush_it_all)
893 int fd = multiplex_out_fd;
895 msg_list_push(flush_it_all);
897 if (!io_buffer_count || no_flush)
900 if (io_multiplexing_out)
901 mplex_write(fd, MSG_DATA, io_buffer, io_buffer_count);
903 writefd_unbuffered(fd, io_buffer, io_buffer_count);
908 void io_end_buffering(void)
910 io_flush(NORMAL_FLUSH);
911 if (!io_multiplexing_out) {
917 static void writefd(int fd,char *buf,size_t len)
919 stats.total_written += len;
921 msg_list_push(NORMAL_FLUSH);
923 if (!io_buffer || fd != multiplex_out_fd) {
924 writefd_unbuffered(fd, buf, len);
929 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
931 memcpy(io_buffer+io_buffer_count, buf, n);
934 io_buffer_count += n;
937 if (io_buffer_count == IO_BUFFER_SIZE)
938 io_flush(NORMAL_FLUSH);
943 void write_int(int f,int32 x)
951 void write_int_named(int f, int32 x, const char *phase)
953 io_write_phase = phase;
955 io_write_phase = phase_unknown;
960 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
961 * 64-bit types on this platform.
963 void write_longint(int f, int64 x)
967 if (x <= 0x7FFFFFFF) {
968 write_int(f, (int)x);
973 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
974 exit_cleanup(RERR_UNSUPPORTED);
976 write_int(f, (int32)0xFFFFFFFF);
977 SIVAL(b,0,(x&0xFFFFFFFF));
978 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
984 void write_buf(int f,char *buf,size_t len)
989 /** Write a string to the connection */
990 static void write_sbuf(int f,char *buf)
992 write_buf(f, buf, strlen(buf));
996 void write_byte(int f,unsigned char c)
998 write_buf(f,(char *)&c,1);
1004 * Read a line of up to @p maxlen characters into @p buf. Does not
1005 * contain a trailing newline or carriage return.
1007 * @return 1 for success; 0 for io error or truncation.
1009 int read_line(int f, char *buf, size_t maxlen)
1013 read_buf(f, buf, 1);
1016 if (buf[0] == '\n') {
1020 if (buf[0] != '\r') {
1034 void io_printf(int fd, const char *format, ...)
1040 va_start(ap, format);
1041 len = vsnprintf(buf, sizeof buf, format, ap);
1044 if (len < 0) exit_cleanup(RERR_STREAMIO);
1046 write_sbuf(fd, buf);
1050 /** Setup for multiplexing a MSG_* stream with the data stream. */
1051 void io_start_multiplex_out(int fd)
1053 multiplex_out_fd = fd;
1054 io_flush(NORMAL_FLUSH);
1055 io_start_buffering_out(fd);
1056 io_multiplexing_out = 1;
1059 /** Setup for multiplexing a MSG_* stream with the data stream. */
1060 void io_start_multiplex_in(int fd)
1062 multiplex_in_fd = fd;
1063 io_flush(NORMAL_FLUSH);
1064 io_multiplexing_in = 1;
1067 /** Write an message to the multiplexed data stream. */
1068 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1070 if (!io_multiplexing_out) return 0;
1072 io_flush(NORMAL_FLUSH);
1073 stats.total_written += (len+4);
1074 mplex_write(multiplex_out_fd, code, buf, len);
1078 /** Stop output multiplexing. */
1079 void io_multiplexing_close(void)
1081 io_multiplexing_out = 0;