+/* 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;
+
+ 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,"unexpected EOF in read_timeout\n");
+ }
+ 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;
+}