- bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
- if (!activity) {
- // Most likely, should_stop was set.
+ // Give the socket 30 seconds since last activity before we time out.
+ static const int timeout_secs = 30;
+
+ timespec now;
+ int err = clock_gettime(CLOCK_MONOTONIC, &now);
+ assert(err != -1);
+
+ timespec elapsed = clock_diff(last_activity, now);
+ if (elapsed.tv_sec >= timeout_secs) {
+ // Timeout!
+ log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
+ state = CLOSING_SOCKET;
+ continue;
+ }
+
+ // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
+ // Add a second of slack to account for differences between clocks.
+ timespec timeout = clock_diff(now, last_activity);
+ timeout.tv_sec += timeout_secs + 1;
+ assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
+
+ bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
+ if (activity) {
+ err = clock_gettime(CLOCK_MONOTONIC, &last_activity);
+ assert(err != -1);
+ } else {
+ // OK. Most likely, should_stop was set, or we have timed out.