+static int no_flush;
+
+/*
+ * Read from a socket with IO timeout. return the number of bytes
+ * read. If no bytes can be read then exit, never return a number <= 0.
+ *
+ * TODO: If the remote shell connection fails, then current versions
+ * actually report an "unexpected EOF" error here. Since it's a
+ * fairly common mistake to try to use rsh when ssh is required, we
+ * should trap that: if we fail to read any data at all, we should
+ * give a better explanation. We can tell whether the connection has
+ * started by looking e.g. at whether the remote version is known yet.
+ */
+static int read_timeout(int fd, char *buf, int len)
+{
+ int n, ret=0;
+
+ io_flush();
+
+ while (ret == 0) {
+ fd_set fds;
+ struct timeval tv;
+ int fd_count = fd+1;
+
+ FD_ZERO(&fds);
+ FD_SET(fd, &fds);
+ if (io_error_fd != -1) {
+ FD_SET(io_error_fd, &fds);
+ if (io_error_fd > fd) fd_count = io_error_fd+1;
+ }
+
+ tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
+ tv.tv_usec = 0;
+
+ errno = 0;
+
+ if (select(fd_count, &fds, NULL, NULL, &tv) < 1) {
+ if (errno == EBADF) {
+ exit_cleanup(RERR_SOCKETIO);
+ }
+ check_timeout();
+ continue;
+ }
+
+ if (io_error_fd != -1 && FD_ISSET(io_error_fd, &fds)) {
+ read_error_fd();
+ }
+
+ if (!FD_ISSET(fd, &fds)) continue;
+
+ n = read(fd, buf, len);
+
+ if (n > 0) {
+ buf += n;
+ len -= n;
+ ret += n;
+ if (io_timeout)
+ last_io = time(NULL);
+ continue;
+ }
+
+ if (n == -1 && errno == EINTR) {
+ continue;
+ }
+
+ if (n == -1 &&
+ (errno == EWOULDBLOCK || errno == EAGAIN)) {
+ continue;
+ }
+
+
+ if (n == 0) {
+ if (eof_error) {
+ rprintf(FERROR,
+ "%s: connection to server unexpectedly closed"
+ " (%ld bytes read so far)\n",
+ RSYNC_NAME, stats.total_read);
+ }
+ exit_cleanup(RERR_STREAMIO);
+ }
+
+ /* this prevents us trying to write errors on a dead socket */
+ io_multiplexing_close();
+
+ rprintf(FERROR,"read error: %s\n", strerror(errno));
+ exit_cleanup(RERR_STREAMIO);
+ }
+
+ return ret;
+}
+
+/* continue trying to read len bytes - don't return until len
+ has been read */
+static void read_loop(int fd, char *buf, int len)
+{
+ while (len) {
+ int n = read_timeout(fd, buf, len);