+ }
+
+ return -1;
+}
+
+static int poll_restart(struct pollfd *fds, int nfds, int timeout)
+{
+ struct timespec ts, cur;
+ int msec = timeout % 1000;
+ int ret;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+
+ ts.tv_nsec += msec * 1000000;
+ if (ts.tv_nsec > 1000000000) {
+ ts.tv_sec++;
+ ts.tv_nsec -= 1000000000;
+ }
+ ts.tv_sec += timeout / 1000;
+
+ while (1) {
+ ret = poll(fds, nfds, timeout);
+ if (ret == EAGAIN)
+ continue;
+
+ if (ret != EINTR)
+ return ret;
+
+ clock_gettime(CLOCK_MONOTONIC, &cur);
+ timeout = (ts.tv_sec - cur.tv_sec) * 1000;
+ timeout += (ts.tv_nsec - cur.tv_nsec) / 1000000;
+ if (timeout <= 0)
+ return 0;
+ }
+}
+
+int usock_inet_timeout(int type, const char *host, const char *service,
+ void *addr, int timeout)
+{
+ int socktype = ((type & 0xff) == USOCK_TCP) ? SOCK_STREAM : SOCK_DGRAM;
+ bool server = !!(type & USOCK_SERVER);
+ struct addrinfo *result, *rp;
+ struct addrinfo hints = {
+ .ai_family = (type & USOCK_IPV6ONLY) ? AF_INET6 :
+ (type & USOCK_IPV4ONLY) ? AF_INET : AF_UNSPEC,
+ .ai_socktype = socktype,
+ .ai_flags = AI_ADDRCONFIG
+ | ((type & USOCK_SERVER) ? AI_PASSIVE : 0)
+ | ((type & USOCK_NUMERIC) ? AI_NUMERICHOST : 0),
+ };
+ struct addrinfo *rp_v6 = NULL;
+ struct addrinfo *rp_v4 = NULL;
+ struct pollfd pfds[2] = {
+ { .fd = -1, .events = POLLOUT },
+ { .fd = -1, .events = POLLOUT },
+ };
+ int sock = -1;
+ int i;
+
+ if (getaddrinfo(host, service, &hints, &result))
+ return -1;
+
+ if (timeout <= 0 || server) {
+ sock = usock_inet_notimeout(type, result, addr);
+ goto free_addrinfo;
+ }