Example #1
0
/*
 * Internal function used for waiting a specific amount of ms
 * in Curl_socket_ready() and Curl_poll() when no file descriptor
 * is provided to wait on, just being used to delay execution.
 * WinSock select() and poll() timeout mechanisms need a valid
 * socket descriptor in a not null file descriptor set to work.
 * Waiting indefinitely with this function is not allowed, a
 * zero or negative timeout value will return immediately.
 * Timeout resolution, accuracy, as well as maximum supported
 * value is system dependent, neither factor is a citical issue
 * for the intended use of this function in the library.
 * On non-DOS and non-Winsock platforms, when compiled with
 * CURL_ACKNOWLEDGE_EINTR defined, EINTR condition is honored
 * and function might exit early without awaiting full timeout,
 * otherwise EINTR will be ignored and full timeout will elapse.
 *
 * Return values:
 *   -1 = system call error, invalid timeout value, or interrupted
 *    0 = specified timeout has elapsed
 */
int Curl_wait_ms(int timeout_ms)
{
#if !defined(MSDOS) && !defined(USE_WINSOCK)
#ifndef HAVE_POLL_FINE
  struct timeval pending_tv;
#endif
  struct timeval initial_tv;
  int pending_ms;
  int error;
#endif
  int r = 0;

  if(!timeout_ms)
    return 0;
  if(timeout_ms < 0) {
    SET_SOCKERRNO(EINVAL);
    return -1;
  }
#if defined(MSDOS)
  delay(timeout_ms);
#elif defined(USE_WINSOCK)
  Sleep(timeout_ms);
#else
  pending_ms = timeout_ms;
  initial_tv = curlx_tvnow();
  do {
#if defined(HAVE_POLL_FINE)
    r = poll(NULL, 0, pending_ms);
#else
    pending_tv.tv_sec = pending_ms / 1000;
    pending_tv.tv_usec = (pending_ms % 1000) * 1000;
    r = select(0, NULL, NULL, NULL, &pending_tv);
#endif /* HAVE_POLL_FINE */
    if(r != -1)
      break;
    error = SOCKERRNO;
    if(error && error_not_EINTR)
      break;
    pending_ms = timeout_ms - elapsed_ms;
    if(pending_ms <= 0)
      break;
  } while(r == -1);
#endif /* USE_WINSOCK */
  if(r)
    r = -1;
  return r;
}
Example #2
0
/*
 * gethostbyname_thread() resolves a name, calls the Curl_addrinfo4_callback
 * and then exits.
 *
 * For builds without ARES/ENABLE_IPV6, create a resolver thread and wait on
 * it.
 */
static unsigned __stdcall gethostbyname_thread (void *arg)
{
    struct connectdata *conn = (struct connectdata*) arg;
    struct thread_data *td = (struct thread_data*) conn->async.os_specific;
    struct hostent *he;
    int    rc = 0;

    /* Duplicate the passed mutex and event handles.
     * This allows us to use it even after the container gets destroyed
     * due to a resolver timeout.
     */
    struct thread_sync_data tsd = { 0,0,0,NULL };

    if(!init_thread_sync_data(td, conn->async.hostname, &tsd)) {
        /* thread synchronization data initialization failed */
        return (unsigned)-1;
    }

    conn->async.status = NO_DATA;  /* pending status */
    SET_SOCKERRNO(conn->async.status);

    /* Signaling that we have initialized all copies of data and handles we
       need */
    SetEvent(td->event_thread_started);

    he = gethostbyname (tsd.hostname);

    /* is parent thread waiting for us and are we able to access conn members? */
    if(acquire_thread_sync(&tsd)) {
        /* Mark that we have obtained the information, and that we are calling
         * back with it. */
        SetEvent(td->event_resolved);
        if(he) {
            rc = Curl_addrinfo4_callback(conn, CURL_ASYNC_SUCCESS, he);
        }
        else {
            rc = Curl_addrinfo4_callback(conn, SOCKERRNO, NULL);
        }
        release_thread_sync(&tsd);
    }

    /* clean up */
    destroy_thread_sync_data(&tsd);

    return (rc);
    /* An implicit _endthreadex() here */
}
Example #3
0
int select_wrapper(int nfds, fd_set *rd, fd_set *wr, fd_set *exc,
                   struct timeval *tv)
{
  if(nfds < 0) {
    SET_SOCKERRNO(EINVAL);
    return -1;
  }
#ifdef USE_WINSOCK
  /*
   * Winsock select() requires that at least one of the three fd_set
   * pointers is not NULL and points to a non-empty fdset. IOW Winsock
   * select() can not be used to sleep without a single fd_set.
   */
  if(!nfds) {
    Sleep(1000*tv->tv_sec + tv->tv_usec/1000);
    return 0;
  }
#endif
  return select(nfds, rd, wr, exc, tv);
}
Example #4
0
/*
 * verifyconnect() returns TRUE if the connect really has happened.
 */
static bool verifyconnect(curl_socket_t sockfd, int *error)
{
    bool rc = TRUE;
#ifdef SO_ERROR
    int err = 0;
    curl_socklen_t errSize = sizeof(err);

#ifdef WIN32
    /*
     * In October 2003 we effectively nullified this function on Windows due to
     * problems with it using all CPU in multi-threaded cases.
     *
     * In May 2004, we bring it back to offer more info back on connect failures.
     * Gisle Vanem could reproduce the former problems with this function, but
     * could avoid them by adding this SleepEx() call below:
     *
     *    "I don't have Rational Quantify, but the hint from his post was
     *    ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
     *    just Sleep(0) would be enough?) would release whatever
     *    mutex/critical-section the ntdll call is waiting on.
     *
     *    Someone got to verify this on Win-NT 4.0, 2000."
     */

#ifdef _WIN32_WCE
    Sleep(0);
#else
    SleepEx(0, FALSE);
#endif

#endif

    if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
        err = SOCKERRNO;
#ifdef _WIN32_WCE
    /* Old WinCE versions don't support SO_ERROR */
    if(WSAENOPROTOOPT == err) {
        SET_SOCKERRNO(0);
        err = 0;
    }
#endif
#ifdef __minix
    /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
    if(EBADIOCTL == err) {
        SET_SOCKERRNO(0);
        err = 0;
    }
#endif
    if((0 == err) || (EISCONN == err))
        /* we are connected, awesome! */
        rc = TRUE;
    else
        /* This wasn't a successful connect */
        rc = FALSE;
    if(error)
        *error = err;
#else
    (void)sockfd;
    if(error)
        *error = SOCKERRNO;
#endif
    return rc;
}
Example #5
0
CURLcode Curl_is_connected(struct connectdata *conn,
                           int sockindex,
                           bool *connected)
{
  struct SessionHandle *data = conn->data;
  CURLcode result = CURLE_OK;
  long allow;
  int error = 0;
  struct timeval now;
  int rc;
  int i;

  DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);

  *connected = FALSE; /* a very negative world view is best */

  if(conn->bits.tcpconnect[sockindex]) {
    /* we are connected already! */
    *connected = TRUE;
    return CURLE_OK;
  }

  now = Curl_tvnow();

  /* figure out how long time we have left to connect */
  allow = Curl_timeleft(data, &now, TRUE);

  if(allow < 0) {
    /* time-out, bail out, go home */
    failf(data, "Connection time-out");
    return CURLE_OPERATION_TIMEDOUT;
  }

  for(i=0; i<2; i++) {
    if(conn->tempsock[i] == CURL_SOCKET_BAD)
      continue;

#ifdef mpeix
    /* Call this function once now, and ignore the results. We do this to
       "clear" the error state on the socket so that we can later read it
       reliably. This is reported necessary on the MPE/iX operating system. */
    (void)verifyconnect(conn->tempsock[i], NULL);
#endif

    /* check socket for connect */
    rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0);

    if(rc == 0) { /* no connection yet */
      if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
        infof(data, "After %ldms connect time, move on!\n",
              conn->timeoutms_per_addr);
        error = ETIMEDOUT;
      }

      /* should we try another protocol family? */
      if(i == 0 && conn->tempaddr[1] == NULL &&
         curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) {
        trynextip(conn, sockindex, 1);
      }
    }
    else if(rc == CURL_CSELECT_OUT) {
      if(verifyconnect(conn->tempsock[i], &error)) {
        /* we are connected with TCP, awesome! */
        int other = i ^ 1;

        /* use this socket from now on */
        conn->sock[sockindex] = conn->tempsock[i];
        conn->ip_addr = conn->tempaddr[i];
        conn->tempsock[i] = CURL_SOCKET_BAD;

        /* close the other socket, if open */
        if(conn->tempsock[other] != CURL_SOCKET_BAD) {
          Curl_closesocket(conn, conn->tempsock[other]);
          conn->tempsock[other] = CURL_SOCKET_BAD;
        }

        /* see if we need to do any proxy magic first once we connected */
        result = Curl_connected_proxy(conn, sockindex);
        if(result)
          return result;

        conn->bits.tcpconnect[sockindex] = TRUE;

        *connected = TRUE;
        if(sockindex == FIRSTSOCKET)
          Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
        Curl_updateconninfo(conn, conn->sock[sockindex]);
        Curl_verboseconnect(conn);

        return CURLE_OK;
      }
      else
        infof(data, "Connection failed\n");
    }
    else if(rc & CURL_CSELECT_ERR)
      (void)verifyconnect(conn->tempsock[i], &error);

    /*
     * The connection failed here, we should attempt to connect to the "next
     * address" for the given host. But first remember the latest error.
     */
    if(error) {
      data->state.os_errno = error;
      SET_SOCKERRNO(error);
      if(conn->tempaddr[i]) {
        char ipaddress[MAX_IPADR_LEN];
        Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
        infof(data, "connect to %s port %ld failed: %s\n",
              ipaddress, conn->port, Curl_strerror(conn, error));

        conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
                                   allow : allow / 2;

        result = trynextip(conn, sockindex, i);
      }
    }
  }

  if(result) {
    /* no more addresses to try */

    /* if the first address family runs out of addresses to try before
       the happy eyeball timeout, go ahead and try the next family now */
    if(conn->tempaddr[1] == NULL) {
      result = trynextip(conn, sockindex, 1);
      if(!result)
        return result;
    }

    failf(data, "Failed to connect to %s port %ld: %s",
          conn->bits.proxy?conn->proxy.name:conn->host.name,
          conn->port, Curl_strerror(conn, error));
  }

  return result;
}
Example #6
0
/**
 * Create a socket for outbound connection to dst_addr:dst_port.
 *
 * The socket is non-blocking and TCP sockets has SIGPIPE disabled if
 * possible.  On Linux it's not possible and should be disabled for
 * each send(2) individually.
 */
SOCKET
proxy_connected_socket(int sdom, int stype,
                       ipX_addr_t *dst_addr, u16_t dst_port)
{
    struct sockaddr_in6 dst_sin6;
    struct sockaddr_in dst_sin;
    struct sockaddr *pdst_sa;
    socklen_t dst_sa_len;
    void *pdst_addr;
    const struct sockaddr *psrc_sa;
    socklen_t src_sa_len;
    int status;
    int sockerr;
    SOCKET s;

    LWIP_ASSERT1(sdom == PF_INET || sdom == PF_INET6);
    LWIP_ASSERT1(stype == SOCK_STREAM || stype == SOCK_DGRAM);

    DPRINTF(("---> %s ", stype == SOCK_STREAM ? "TCP" : "UDP"));
    if (sdom == PF_INET6) {
        pdst_sa = (struct sockaddr *)&dst_sin6;
        pdst_addr = (void *)&dst_sin6.sin6_addr;

        memset(&dst_sin6, 0, sizeof(dst_sin6));
#if HAVE_SA_LEN
        dst_sin6.sin6_len =
#endif
            dst_sa_len = sizeof(dst_sin6);
        dst_sin6.sin6_family = AF_INET6;
        memcpy(&dst_sin6.sin6_addr, &dst_addr->ip6, sizeof(ip6_addr_t));
        dst_sin6.sin6_port = htons(dst_port);

        DPRINTF(("[%RTnaipv6]:%d ", &dst_sin6.sin6_addr, dst_port));
    }
    else { /* sdom = PF_INET */
        pdst_sa = (struct sockaddr *)&dst_sin;
        pdst_addr = (void *)&dst_sin.sin_addr;

        memset(&dst_sin, 0, sizeof(dst_sin));
#if HAVE_SA_LEN
        dst_sin.sin_len =
#endif
            dst_sa_len = sizeof(dst_sin);
        dst_sin.sin_family = AF_INET;
        dst_sin.sin_addr.s_addr = dst_addr->ip4.addr; /* byte-order? */
        dst_sin.sin_port = htons(dst_port);

        DPRINTF(("%RTnaipv4:%d ", dst_sin.sin_addr.s_addr, dst_port));
    }

    s = proxy_create_socket(sdom, stype);
    if (s == INVALID_SOCKET) {
        return INVALID_SOCKET;
    }
    DPRINTF(("socket %d\n", s));

    /* TODO: needs locking if dynamic modifyvm is allowed */
    if (sdom == PF_INET6) {
        psrc_sa = (const struct sockaddr *)g_proxy_options->src6;
        src_sa_len = sizeof(struct sockaddr_in6);
    }
    else {
        psrc_sa = (const struct sockaddr *)g_proxy_options->src4;
        src_sa_len = sizeof(struct sockaddr_in);
    }
    if (psrc_sa != NULL) {
        status = bind(s, psrc_sa, src_sa_len);
        if (status == SOCKET_ERROR) {
            sockerr = SOCKERRNO();
            DPRINTF(("socket %d: bind: %R[sockerr]\n", s, sockerr));
            closesocket(s);
            SET_SOCKERRNO(sockerr);
            return INVALID_SOCKET;
        }
    }

    status = connect(s, pdst_sa, dst_sa_len);
    if (status == SOCKET_ERROR
#if !defined(RT_OS_WINDOWS)
        && SOCKERRNO() != EINPROGRESS
#else
        && SOCKERRNO() != EWOULDBLOCK
#endif
        )
    {
        sockerr = SOCKERRNO();
        DPRINTF(("socket %d: connect: %R[sockerr]\n", s, sockerr));
        closesocket(s);
        SET_SOCKERRNO(sockerr);
        return INVALID_SOCKET;
    }

    return s;
}
Example #7
0
/*
 * Curl_wait_for_resolv() waits for a resolve to finish. This function should
 * be avoided since using this risk getting the multi interface to "hang".
 *
 * If 'entry' is non-NULL, make it point to the resolved dns entry
 *
 * This is the version for resolves-in-a-thread.
 */
CURLcode Curl_wait_for_resolv(struct connectdata *conn,
                              struct Curl_dns_entry **entry)
{
  struct thread_data   *td = (struct thread_data*) conn->async.os_specific;
  struct SessionHandle *data = conn->data;
  long   timeout;
  DWORD  status, ticks;
  CURLcode rc;

  DEBUGASSERT(conn && td);

  /* now, see if there's a connect timeout or a regular timeout to
     use instead of the default one */
  timeout =
    conn->data->set.connecttimeout ? conn->data->set.connecttimeout :
    conn->data->set.timeout ? conn->data->set.timeout :
    CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
  ticks = GetTickCount();

  /* wait for the thread to resolve the name */
  status = WaitForSingleObject(td->event_resolved, timeout);

  /* mark that we are now done waiting */
  ReleaseMutex(td->mutex_waiting);

  /* close our handle to the mutex, no point in hanging on to it */
  CloseHandle(td->mutex_waiting);
  td->mutex_waiting = NULL;

  /* close the event handle, it's useless now */
  CloseHandle(td->event_resolved);
  td->event_resolved = NULL;

  /* has the resolver thread succeeded in resolving our query ? */
  if (status == WAIT_OBJECT_0) {
    /* wait for the thread to exit, it's in the callback sequence */
    if (WaitForSingleObject(td->thread_hnd, 5000) == WAIT_TIMEOUT) {
      TerminateThread(td->thread_hnd, 0);
      conn->async.done = TRUE;
      td->thread_status = (DWORD)-1;
      TRACE(("%s() thread stuck?!, ", THREAD_NAME));
    }
    else {
      /* Thread finished before timeout; propagate Winsock error to this
       * thread.  'conn->async.done = TRUE' is set in
       * Curl_addrinfo4/6_callback().
       */
      SET_SOCKERRNO(conn->async.status);
      GetExitCodeThread(td->thread_hnd, &td->thread_status);
      TRACE(("%s() status %lu, thread retval %lu, ",
             THREAD_NAME, status, td->thread_status));
    }
  }
  else {
    conn->async.done = TRUE;
    td->thread_status = (DWORD)-1;
    TRACE(("%s() timeout, ", THREAD_NAME));
  }

  TRACE(("elapsed %lu ms\n", GetTickCount()-ticks));

  if(entry)
    *entry = conn->async.dns;

  rc = CURLE_OK;

  if (!conn->async.dns) {
    /* a name was not resolved */
    if (td->thread_status == CURLE_OUT_OF_MEMORY) {
      rc = CURLE_OUT_OF_MEMORY;
      failf(data, "Could not resolve host: %s", curl_easy_strerror(rc));
    }
    else if(conn->async.done) {
      if(conn->bits.httpproxy) {
        failf(data, "Could not resolve proxy: %s; %s",
              conn->proxy.dispname, Curl_strerror(conn, conn->async.status));
        rc = CURLE_COULDNT_RESOLVE_PROXY;
      }
      else {
        failf(data, "Could not resolve host: %s; %s",
              conn->host.name, Curl_strerror(conn, conn->async.status));
        rc = CURLE_COULDNT_RESOLVE_HOST;
      }
    }
    else if (td->thread_status == (DWORD)-1 || conn->async.status == NO_DATA) {
      failf(data, "Resolving host timed out: %s", conn->host.name);
      rc = CURLE_OPERATION_TIMEDOUT;
    }
    else
      rc = CURLE_OPERATION_TIMEDOUT;
  }

  Curl_destroy_thread_data(&conn->async);

  if(!conn->async.dns)
    conn->bits.close = TRUE;

  return (rc);
}
Example #8
0
CURLcode Curl_is_connected(struct connectdata *conn,
                           int sockindex,
                           bool *connected)
{
  int rc;
  struct SessionHandle *data = conn->data;
  CURLcode code = CURLE_OK;
  curl_socket_t sockfd = conn->sock[sockindex];
  long allow = DEFAULT_CONNECT_TIMEOUT;
  int error = 0;
  struct timeval now;

  DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);

  *connected = FALSE; /* a very negative world view is best */

  if(conn->bits.tcpconnect[sockindex]) {
    /* we are connected already! */
    *connected = TRUE;
    return CURLE_OK;
  }

  now = Curl_tvnow();

  /* figure out how long time we have left to connect */
  allow = Curl_timeleft(data, &now, TRUE);

  if(allow < 0) {
    /* time-out, bail out, go home */
    failf(data, "Connection time-out");
    return CURLE_OPERATION_TIMEDOUT;
  }

  /* check for connect without timeout as we want to return immediately */
  rc = waitconnect(conn, sockfd, 0);
  if(WAITCONN_TIMEOUT == rc) {
    if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
      infof(data, "After %ldms connect time, move on!\n",
            conn->timeoutms_per_addr);
      goto next;
    }

    /* not an error, but also no connection yet */
    return code;
  }

  if(WAITCONN_CONNECTED == rc) {
    if(verifyconnect(sockfd, &error)) {
      /* we are connected with TCP, awesome! */

      /* see if we need to do any proxy magic first once we connected */
      code = Curl_connected_proxy(conn);
      if(code)
        return code;

      conn->bits.tcpconnect[sockindex] = TRUE;
      *connected = TRUE;
      if(sockindex == FIRSTSOCKET)
        Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
      Curl_verboseconnect(conn);
      Curl_updateconninfo(conn, sockfd);

      return CURLE_OK;
    }
    /* nope, not connected for real */
  }
  else {
    /* nope, not connected  */
    if(WAITCONN_FDSET_ERROR == rc) {
      (void)verifyconnect(sockfd, &error);
      infof(data, "%s\n",Curl_strerror(conn, error));
    }
    else
      infof(data, "Connection failed\n");
  }

  /*
   * The connection failed here, we should attempt to connect to the "next
   * address" for the given host. But first remember the latest error.
   */
  if(error) {
    data->state.os_errno = error;
    SET_SOCKERRNO(error);
  }
  next:

  conn->timeoutms_per_addr = conn->ip_addr->ai_next == NULL ?
                             allow : allow / 2;
  code = trynextip(conn, sockindex, connected);

  if(code) {
    error = SOCKERRNO;
    data->state.os_errno = error;
    failf(data, "Failed connect to %s:%ld; %s",
          conn->host.name, conn->port, Curl_strerror(conn, error));
  }

  return code;
}
Example #9
0
int
Curl_getaddrinfo_ex(const char *nodename,
                    const char *servname,
                    const struct addrinfo *hints,
                    Curl_addrinfo **result)
{
  const struct addrinfo *ai;
  struct addrinfo *aihead;
  Curl_addrinfo *cafirst = NULL;
  Curl_addrinfo *calast = NULL;
  Curl_addrinfo *ca;
  size_t ss_size;
  int error;

  *result = NULL; /* assume failure */

  error = getaddrinfo(nodename, servname, hints, &aihead);
  if(error)
    return error;

  /* traverse the addrinfo list */

  for(ai = aihead; ai != NULL; ai = ai->ai_next) {

    /* ignore elements with unsupported address family, */
    /* settle family-specific sockaddr structure size.  */
    if(ai->ai_family == AF_INET)
      ss_size = sizeof(struct sockaddr_in);
#ifdef ENABLE_IPV6
    else if(ai->ai_family == AF_INET6)
      ss_size = sizeof(struct sockaddr_in6);
#endif
    else
      continue;

    /* ignore elements without required address info */
    if((ai->ai_addr == NULL) || !(ai->ai_addrlen > 0))
      continue;

    /* ignore elements with bogus address size */
    if((size_t)ai->ai_addrlen < ss_size)
      continue;

    if((ca = malloc(sizeof(Curl_addrinfo))) == NULL) {
      error = EAI_MEMORY;
      break;
    }

    /* copy each structure member individually, member ordering, */
    /* size, or padding might be different for each platform.    */

    ca->ai_flags     = ai->ai_flags;
    ca->ai_family    = ai->ai_family;
    ca->ai_socktype  = ai->ai_socktype;
    ca->ai_protocol  = ai->ai_protocol;
    ca->ai_addrlen   = (curl_socklen_t)ss_size;
    ca->ai_addr      = NULL;
    ca->ai_canonname = NULL;
    ca->ai_next      = NULL;

    if((ca->ai_addr = malloc(ss_size)) == NULL) {
      error = EAI_MEMORY;
      free(ca);
      break;
    }
    memcpy(ca->ai_addr, ai->ai_addr, ss_size);

    if(ai->ai_canonname != NULL) {
      if((ca->ai_canonname = strdup(ai->ai_canonname)) == NULL) {
        error = EAI_MEMORY;
        free(ca->ai_addr);
        free(ca);
        break;
      }
    }

    /* if the return list is empty, this becomes the first element */
    if(!cafirst)
      cafirst = ca;

    /* add this element last in the return list */
    if(calast)
      calast->ai_next = ca;
    calast = ca;

  }

  /* destroy the addrinfo list */
  if(aihead)
    freeaddrinfo(aihead);

  /* if we failed, also destroy the Curl_addrinfo list */
  if(error) {
    Curl_freeaddrinfo(cafirst);
    cafirst = NULL;
  }
  else if(!cafirst) {
#ifdef EAI_NONAME
    /* rfc3493 conformant */
    error = EAI_NONAME;
#else
    /* rfc3493 obsoleted */
    error = EAI_NODATA;
#endif
#ifdef USE_WINSOCK
    SET_SOCKERRNO(error);
#endif
  }

  *result = cafirst;

  /* This is not a CURLcode */
  return error;
}
Example #10
0
/*
 * This is a wrapper around select().  It uses poll() when a fine
 * poll() is available, in order to avoid limits with FD_SETSIZE,
 * otherwise select() is used.  An error is returned if select() is
 * being used and a the number of file descriptors is larger than
 * FD_SETSIZE.  A NULL timeout pointer makes this function wait
 * indefinitely, unles no valid file descriptor is given, when this
 * happens the NULL timeout is ignored and the function times out
 * immediately.  When compiled with CURL_ACKNOWLEDGE_EINTR defined,
 * EINTR condition is honored and function might exit early without
 * awaiting timeout, otherwise EINTR will be ignored.
 *
 * Return values:
 *   -1 = system call error or nfds > FD_SETSIZE
 *    0 = timeout
 *    N = number of file descriptors kept in file descriptor sets.
 */
int Curl_select(int nfds,
                fd_set *fds_read, fd_set *fds_write, fd_set *fds_excep,
                struct timeval *timeout)
{
  struct timeval initial_tv;
  int timeout_ms;
  int pending_ms;
  int error;
  int r;
#ifdef HAVE_POLL_FINE
  struct pollfd small_fds[SMALL_POLLNFDS];
  struct pollfd *poll_fds;
  int ix;
  int fd;
  int poll_nfds = 0;
#else
  struct timeval pending_tv;
  struct timeval *ptimeout;
#endif
  int ret = 0;

  if ((nfds < 0) ||
     ((nfds > 0) && (!fds_read && !fds_write && !fds_excep))) {
    SET_SOCKERRNO(EINVAL);
    return -1;
  }

  if (timeout) {
    if ((timeout->tv_sec < 0) ||
        (timeout->tv_usec < 0) ||
        (timeout->tv_usec >= 1000000)) {
      SET_SOCKERRNO(EINVAL);
      return -1;
    }
    timeout_ms = (int)(timeout->tv_sec * 1000) + (int)(timeout->tv_usec / 1000);
  }
  else {
    timeout_ms = -1;
  }

  if ((!nfds) || (!fds_read && !fds_write && !fds_excep)) {
    r = wait_ms(timeout_ms);
    return r;
  }

  pending_ms = timeout_ms;
  initial_tv = curlx_tvnow();

#ifdef HAVE_POLL_FINE

  if (fds_read || fds_write || fds_excep) {
    fd = nfds;
    while (fd--) {
      if ((fds_read && (0 != FD_ISSET(fd, fds_read))) ||
          (fds_write && (0 != FD_ISSET(fd, fds_write))) ||
          (fds_excep && (0 != FD_ISSET(fd, fds_excep))))
        poll_nfds++;
    }
  }

  if (!poll_nfds)
    poll_fds = NULL;
  else if (poll_nfds <= SMALL_POLLNFDS)
    poll_fds = small_fds;
  else {
    poll_fds = calloc((size_t)poll_nfds, sizeof(struct pollfd));
    if (!poll_fds) {
      SET_SOCKERRNO(ENOBUFS);
      return -1;
    }
  }

  if (poll_fds) {
    ix = 0;
    fd = nfds;
    while (fd--) {
      poll_fds[ix].events = 0;
      if (fds_read && (0 != FD_ISSET(fd, fds_read)))
        poll_fds[ix].events |= (POLLRDNORM|POLLIN);
      if (fds_write && (0 != FD_ISSET(fd, fds_write)))
        poll_fds[ix].events |= (POLLWRNORM|POLLOUT);
      if (fds_excep && (0 != FD_ISSET(fd, fds_excep)))
        poll_fds[ix].events |= (POLLRDBAND|POLLPRI);
      if (poll_fds[ix].events) {
        poll_fds[ix].fd = fd;
        poll_fds[ix].revents = 0;
        ix++;
      }
    }
  }

  do {
    if (timeout_ms < 0)
      pending_ms = -1;
    r = poll(poll_fds, poll_nfds, pending_ms);
  } while ((r == -1) && (error = SOCKERRNO) &&
           (error != EINVAL) && error_not_EINTR &&
           ((timeout_ms < 0) || ((pending_ms = timeout_ms - elapsed_ms) > 0)));

  if (r < 0)
    ret = -1;

  if (r > 0) {
    ix = poll_nfds;
    while (ix--) {
      if (poll_fds[ix].revents & POLLNVAL) {
        SET_SOCKERRNO(EBADF);
        ret = -1;
        break;
      }
    }
  }

  if (!ret) {
    ix = poll_nfds;
    while (ix--) {
      if (fds_read && (0 != FD_ISSET(poll_fds[ix].fd, fds_read))) {
        if (0 == (poll_fds[ix].revents & (POLLRDNORM|POLLERR|POLLHUP|POLLIN)))
          FD_CLR(poll_fds[ix].fd, fds_read);
        else
          ret++;
      }
      if (fds_write && (0 != FD_ISSET(poll_fds[ix].fd, fds_write))) {
        if (0 == (poll_fds[ix].revents & (POLLWRNORM|POLLERR|POLLHUP|POLLOUT)))
          FD_CLR(poll_fds[ix].fd, fds_write);
        else
          ret++;
      }
      if (fds_excep && (0 != FD_ISSET(poll_fds[ix].fd, fds_excep))) {
        if (0 == (poll_fds[ix].revents & (POLLRDBAND|POLLERR|POLLHUP|POLLPRI)))
          FD_CLR(poll_fds[ix].fd, fds_excep);
        else
          ret++;
      }
    }
  }

  if (poll_fds && (poll_nfds > SMALL_POLLNFDS))
    free(poll_fds);

#else  /* HAVE_POLL_FINE */

  VERIFY_NFDS(nfds);

  ptimeout = (timeout_ms < 0) ? NULL : &pending_tv;

  do {
    if (ptimeout) {
      pending_tv.tv_sec = pending_ms / 1000;
      pending_tv.tv_usec = (pending_ms % 1000) * 1000;
    }
    r = select(nfds, fds_read, fds_write, fds_excep, ptimeout);
  } while ((r == -1) && (error = SOCKERRNO) &&
           (error != EINVAL) && (error != EBADF) && error_not_EINTR &&
           ((timeout_ms < 0) || ((pending_ms = timeout_ms - elapsed_ms) > 0)));

  if (r < 0)
    ret = -1;
  else
    ret = r;

#endif  /* HAVE_POLL_FINE */

  return ret;
}