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 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)
338 "%s: connection unexpectedly closed "
339 "(%.0f bytes read so far)\n",
340 RSYNC_NAME, (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 rprintf(FERROR, "%s: read error: %s\n",
353 RSYNC_NAME, strerror(err));
354 exit_cleanup(RERR_STREAMIO);
359 * Read from a socket with IO 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 >= fd_count)
387 fd_count = msg_fd_in+1;
389 if (io_filesfrom_f_out >= 0) {
391 if (io_filesfrom_buflen == 0) {
392 if (io_filesfrom_f_in >= 0) {
393 FD_SET(io_filesfrom_f_in, &r_fds);
394 new_fd = io_filesfrom_f_in;
396 io_filesfrom_f_out = -1;
401 FD_SET(io_filesfrom_f_out, &w_fds);
402 new_fd = io_filesfrom_f_out;
404 if (new_fd >= fd_count)
408 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
413 count = select(fd_count, &r_fds,
414 io_filesfrom_buflen? &w_fds : NULL,
418 msg_list_push(NORMAL_FLUSH);
423 if (errno == EBADF) {
424 exit_cleanup(RERR_SOCKETIO);
429 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
432 if (io_filesfrom_f_out >= 0) {
433 if (io_filesfrom_buflen) {
434 if (FD_ISSET(io_filesfrom_f_out, &w_fds)) {
435 int l = write(io_filesfrom_f_out,
437 io_filesfrom_buflen);
439 if (!(io_filesfrom_buflen -= l))
440 io_filesfrom_bp = io_filesfrom_buf;
442 io_filesfrom_bp += l;
444 /* XXX should we complain? */
445 io_filesfrom_f_out = -1;
448 } else if (io_filesfrom_f_in >= 0) {
449 if (FD_ISSET(io_filesfrom_f_in, &r_fds)) {
450 int l = read(io_filesfrom_f_in,
452 sizeof io_filesfrom_buf);
454 /* Send end-of-file marker */
455 io_filesfrom_buf[0] = '\0';
456 io_filesfrom_buf[1] = '\0';
457 io_filesfrom_buflen = io_filesfrom_lastchar? 2 : 1;
458 io_filesfrom_f_in = -1;
460 extern int eol_nulls;
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)) continue;
498 n = read(fd, buf, len);
505 last_io = time(NULL);
509 return -1; /* doesn't return */
511 if (errno == EINTR || errno == EWOULDBLOCK ||
514 die_from_readerr(errno);
522 * Read a line into the "fname" buffer (which must be at least MAXPATHLEN
525 int read_filesfrom_line(int fd, char *fname)
527 char ch, *s, *eob = fname + MAXPATHLEN - 1;
529 extern int io_timeout;
530 extern int eol_nulls;
531 extern char *remote_filesfrom_file;
532 int reading_remotely = remote_filesfrom_file != NULL;
533 int nulls = eol_nulls || reading_remotely;
538 cnt = read(fd, &ch, 1);
539 if (cnt < 0 && (errno == EWOULDBLOCK
540 || errno == EINTR || errno == EAGAIN)) {
545 tv.tv_sec = io_timeout? io_timeout : SELECT_TIMEOUT;
547 if (!select(fd+1, &fds, NULL, NULL, &tv))
553 if (nulls? !ch : (ch == '\r' || ch == '\n')) {
554 /* Skip empty lines if reading locally. */
555 if (!reading_remotely && s == fname)
565 if (*fname == '#' || *fname == ';')
573 * Continue trying to read len bytes - don't return until len has been
576 static void read_loop(int fd, char *buf, size_t len)
579 int n = read_timeout(fd, buf, len);
588 * Read from the file descriptor handling multiplexing - return number
591 * Never returns <= 0.
593 static int read_unbuffered(int fd, char *buf, size_t len)
595 static size_t remaining;
599 static size_t bufferIdx = 0;
600 static size_t bufferSz;
602 if (fd != multiplex_in_fd)
603 return read_timeout(fd, buf, len);
605 if (!io_multiplexing_in && remaining == 0) {
607 bufferSz = 2 * IO_BUFFER_SIZE;
608 buffer = new_array(char, bufferSz);
609 if (!buffer) out_of_memory("read_unbuffered");
611 remaining = read_timeout(fd, buffer, bufferSz);
617 len = MIN(len, remaining);
618 memcpy(buf, buffer + bufferIdx, len);
625 read_loop(fd, line, 4);
628 remaining = tag & 0xFFFFFF;
629 tag = (tag >> 24) - MPLEX_BASE;
633 if (!buffer || remaining > bufferSz) {
634 buffer = realloc_array(buffer, char, remaining);
635 if (!buffer) out_of_memory("read_unbuffered");
636 bufferSz = remaining;
638 read_loop(fd, buffer, remaining);
643 if (remaining >= sizeof line) {
644 rprintf(FERROR, "multiplexing overflow %d:%ld\n\n",
645 tag, (long)remaining);
646 exit_cleanup(RERR_STREAMIO);
648 read_loop(fd, line, remaining);
649 rwrite((enum logcode)tag, line, remaining);
653 rprintf(FERROR, "unexpected tag %d\n", tag);
654 exit_cleanup(RERR_STREAMIO);
659 io_flush(NORMAL_FLUSH);
667 * Do a buffered read from @p fd. Don't return until all @p n bytes
668 * have been read. If all @p n can't be read then exit with an
671 static void readfd(int fd, char *buffer, size_t N)
677 ret = read_unbuffered(fd, buffer + total, N-total);
681 stats.total_read += total;
685 int32 read_int(int f)
692 if (ret == (int32)0xffffffff) return -1;
696 int64 read_longint(int f)
702 if ((int32)ret != (int32)0xffffffff) {
707 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
708 exit_cleanup(RERR_UNSUPPORTED);
711 ret = IVAL(b,0) | (((int64)IVAL(b,4))<<32);
717 void read_buf(int f,char *buf,size_t len)
722 void read_sbuf(int f,char *buf,size_t len)
728 unsigned char read_byte(int f)
731 read_buf(f, (char *)&c, 1);
737 * Sleep after writing to limit I/O bandwidth usage.
739 * @todo Rather than sleeping after each write, it might be better to
740 * use some kind of averaging. The current algorithm seems to always
741 * use a bit less bandwidth than specified, because it doesn't make up
742 * for slow periods. But arguably this is a feature. In addition, we
743 * ought to take the time used to write the data into account.
745 static void sleep_for_bwlimit(int bytes_written)
752 assert(bytes_written > 0);
755 tv.tv_usec = bytes_written * 1000 / bwlimit;
756 tv.tv_sec = tv.tv_usec / 1000000;
757 tv.tv_usec = tv.tv_usec % 1000000;
759 select(0, NULL, NULL, NULL, &tv);
764 * Write len bytes to the file descriptor @p fd.
766 * This function underlies the multiplexing system. The body of the
767 * application never calls this function directly.
769 static void writefd_unbuffered(int fd,char *buf,size_t len)
776 msg_list_push(NORMAL_FLUSH);
780 while (total < len) {
785 if (msg_fd_in >= 0) {
787 FD_SET(msg_fd_in,&r_fds);
788 if (msg_fd_in > fd_count)
789 fd_count = msg_fd_in;
792 tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
796 count = select(fd_count+1, msg_fd_in >= 0 ? &r_fds : NULL,
800 msg_list_push(NORMAL_FLUSH);
805 if (errno == EBADF) {
806 exit_cleanup(RERR_SOCKETIO);
811 if (msg_fd_in >= 0 && FD_ISSET(msg_fd_in, &r_fds))
814 if (FD_ISSET(fd, &w_fds)) {
816 size_t n = len-total;
817 ret = write(fd,buf+total,n);
822 if (errno == EWOULDBLOCK || errno == EAGAIN) {
829 /* Don't try to write errors back
830 * across the stream */
831 io_multiplexing_close();
832 rprintf(FERROR, RSYNC_NAME
833 ": writefd_unbuffered failed to write %ld bytes: phase \"%s\": %s\n",
834 (long) len, io_write_phase,
836 exit_cleanup(RERR_STREAMIO);
839 sleep_for_bwlimit(ret);
844 last_io = time(NULL);
852 static char *io_buffer;
853 static int io_buffer_count;
855 void io_start_buffering_out(int fd)
857 if (io_buffer) return;
858 multiplex_out_fd = fd;
859 io_buffer = new_array(char, IO_BUFFER_SIZE);
860 if (!io_buffer) out_of_memory("writefd");
864 void io_start_buffering_in(int fd)
866 multiplex_in_fd = fd;
870 * Write an message to a multiplexed stream. If this fails then rsync
873 static void mplex_write(int fd, enum msgcode code, char *buf, size_t len)
878 SIVAL(buffer, 0, ((MPLEX_BASE + (int)code)<<24) + len);
880 if (n > (sizeof buffer - 4)) {
881 n = sizeof buffer - 4;
884 memcpy(&buffer[4], buf, n);
885 writefd_unbuffered(fd, buffer, n+4);
891 writefd_unbuffered(fd, buf, len);
896 void io_flush(int flush_it_all)
898 int fd = multiplex_out_fd;
900 msg_list_push(flush_it_all);
902 if (!io_buffer_count || no_flush)
905 if (io_multiplexing_out)
906 mplex_write(fd, MSG_DATA, io_buffer, io_buffer_count);
908 writefd_unbuffered(fd, io_buffer, io_buffer_count);
913 void io_end_buffering(void)
915 io_flush(NORMAL_FLUSH);
916 if (!io_multiplexing_out) {
922 static void writefd(int fd,char *buf,size_t len)
924 stats.total_written += len;
926 msg_list_push(NORMAL_FLUSH);
928 if (!io_buffer || fd != multiplex_out_fd) {
929 writefd_unbuffered(fd, buf, len);
934 int n = MIN((int) len, IO_BUFFER_SIZE-io_buffer_count);
936 memcpy(io_buffer+io_buffer_count, buf, n);
939 io_buffer_count += n;
942 if (io_buffer_count == IO_BUFFER_SIZE)
943 io_flush(NORMAL_FLUSH);
948 void write_int(int f,int32 x)
956 void write_int_named(int f, int32 x, const char *phase)
958 io_write_phase = phase;
960 io_write_phase = phase_unknown;
965 * Note: int64 may actually be a 32-bit type if ./configure couldn't find any
966 * 64-bit types on this platform.
968 void write_longint(int f, int64 x)
972 if (x <= 0x7FFFFFFF) {
973 write_int(f, (int)x);
978 rprintf(FERROR,"Integer overflow - attempted 64 bit offset\n");
979 exit_cleanup(RERR_UNSUPPORTED);
981 write_int(f, (int32)0xFFFFFFFF);
982 SIVAL(b,0,(x&0xFFFFFFFF));
983 SIVAL(b,4,((x>>32)&0xFFFFFFFF));
989 void write_buf(int f,char *buf,size_t len)
994 /** Write a string to the connection */
995 static void write_sbuf(int f,char *buf)
997 write_buf(f, buf, strlen(buf));
1001 void write_byte(int f,unsigned char c)
1003 write_buf(f,(char *)&c,1);
1009 * Read a line of up to @p maxlen characters into @p buf. Does not
1010 * contain a trailing newline or carriage return.
1012 * @return 1 for success; 0 for io error or truncation.
1014 int read_line(int f, char *buf, size_t maxlen)
1018 read_buf(f, buf, 1);
1021 if (buf[0] == '\n') {
1025 if (buf[0] != '\r') {
1039 void io_printf(int fd, const char *format, ...)
1045 va_start(ap, format);
1046 len = vsnprintf(buf, sizeof buf, format, ap);
1049 if (len < 0) exit_cleanup(RERR_STREAMIO);
1051 write_sbuf(fd, buf);
1055 /** Setup for multiplexing a MSG_* stream with the data stream. */
1056 void io_start_multiplex_out(int fd)
1058 multiplex_out_fd = fd;
1059 io_flush(NORMAL_FLUSH);
1060 io_start_buffering_out(fd);
1061 io_multiplexing_out = 1;
1064 /** Setup for multiplexing a MSG_* stream with the data stream. */
1065 void io_start_multiplex_in(int fd)
1067 multiplex_in_fd = fd;
1068 io_flush(NORMAL_FLUSH);
1069 io_multiplexing_in = 1;
1072 /** Write an message to the multiplexed data stream. */
1073 int io_multiplex_write(enum msgcode code, char *buf, size_t len)
1075 if (!io_multiplexing_out) return 0;
1077 io_flush(NORMAL_FLUSH);
1078 stats.total_written += (len+4);
1079 mplex_write(multiplex_out_fd, code, buf, len);
1083 /** Stop output multiplexing. */
1084 void io_multiplexing_close(void)
1086 io_multiplexing_out = 0;