+static char *read_buffer;
+static char *read_buffer_p;
+static int read_buffer_len;
+static int read_buffer_size;
+static int no_flush;
+static int no_flush_read;
+
+/* 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 */
+static int read_timeout(int fd, char *buf, int len)
+{
+ int n, ret=0;
+
+ no_flush_read++;
+ io_flush();
+ no_flush_read--;
+
+ while (ret == 0) {
+ fd_set fds;
+ struct timeval tv;
+
+ FD_ZERO(&fds);
+ FD_SET(fd, &fds);
+ tv.tv_sec = io_timeout?io_timeout:SELECT_TIMEOUT;
+ tv.tv_usec = 0;
+
+ if (select(fd+1, &fds, NULL, NULL, &tv) != 1) {
+ check_timeout();
+ 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 == EAGAIN || errno == EWOULDBLOCK)) {
+ /* this shouldn't happen, if it does then
+ sleep for a short time to prevent us
+ chewing too much CPU */
+ u_sleep(100);
+ continue;
+ }
+
+ if (n == 0) {
+ if (eof_error) {
+ rprintf(FERROR,"unexpected EOF in read_timeout\n");
+ }
+ exit_cleanup(RERR_STREAMIO);
+ }
+
+ 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)