How to correctly handle a non blocking connection in a multithreaded platform(async poll on SSL_read and SSL_Write) with openssl

Viewed 39

Consider the following code:

int SSLWrapper::read() {
  while (true) {
    int ssl_error = SSL_ERROR_NONE;
    {
      std::lock_guard<std::mutex> ssl_lock(ssl_mutex_);
      if (!ssl_) {
        return -1;
      }
      int result = SSL_READ(...);
      if (result > 0) {
        return result;
      }
      ssl_error = ::SSL_get_error(ssl_, result);
    }
    if (!waitUntilSocketBecomesReadyForIO(ssl_error)) {
      return -1;
    }
  }
}

Where waitUntilSocketBecomesReadyForIO waits for IO availability based on SSL_ERROR_WANT_* return code using poll(POLLIN/POLLOUT)

another thread may pop in, and use the same code snippet with SSL_Write. So

  1. Is it safe to call poll() from different threads on the same file descriptor?
  2. What's going to happen if SSL_Read returned with SSL_ERROR_WANT_READ, and at the same time, SSL_Write returned with the very same result? Once the socket is signaled with POLLIN revent, which one of the poll()s is going to unblock itself? if both, how do I know which operation caused the POLLIN, and more importantly, should I call SSL_read(to move forward with SSL_Read) or SSL_write(to move forward with SSL_Write)? Thanks!
0 Answers
Related