Search code examples
clinuxsslopensslnonblocking

SSL_write() and SSL_read() non-blocking problem


int bytes;

bytes = SSL_write(ssl, buf, num);
bytes = SSL_read(ssl, buf, num);

Is it possible that bytes are greater than 0, but SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE appears?


Solution

  • Technically no, in a non-blocking scenario there could be a handshake initiation at anytime from the server or the client. The only time bytes should be greater than 0 is with a successful transfer, the return value should be the actual number of bytes written. if bytes is ==0 then there was an error that can be captured using SSL_get_error_(). something like below might help you capture the error and handle it.

    int sending=1;
    while (sending)
    {
        bytes=SSL_write(ssl,buf,num);
        if(bytes>0)
        {
            sending=0; //we have sent all the bytes
            break;
        }
    //if we get here there was an error
    if(SSL_get_error(ssl,bytes) == SSL_ERROR_WANT_READ || SSL_ERROR_WANT_WRITE)
    {
         printf("there was an error during I/O operation\n");
         //we are still in sending=1 so the IO operation will be attempted again. 
    }
    

    }

    There is probably a better way to do this, but this is some very basic error checking to see what your return values hold. Another note, the SSL_get_error() has to be called from the same thread that the I/O operation takes place from.