BIO_do_handshake return 0

BIO_do_handshake return 0

本文关键字:return do BIO handshake      更新时间:2023-10-16

我试图写一个非阻塞连接,当我执行BIO_do_handshake()时,使用下面的代码它总是返回0。我知道你不一定需要'do_handshake()',但似乎所有事情都应该做,以确保握手完成。

我应该调用BIO_should_retry()吗?

void SSLAdaptor::Connect( SSL_CTX *ctx
                        , const std::string &hostname
                        , int port
                        , bool nonBlocking )
{
struct hostent *hp;
struct sockaddr_in addr;
SOCKET sockFD;
if( !( hp = gethostbyname( hostname.c_str() ) ) )
{
    return;
}
memset( &addr, 0, sizeof( addr ) );
addr.sin_addr= *( struct in_addr* )hp->h_addr_list[0];
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
if( ( sockFD =socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) <0 )
{
    return;
}
if(connect(sockFD,(struct sockaddr *)&addr, sizeof(addr))<0)
{
    return;
}
SSL *ssl;
BIO *sbio;
ssl = SSL_new( ctx );
sbio = BIO_new_socket( sockFD, BIO_NOCLOSE );
SSL_set_bio( ssl, sbio, sbio );
if( SSL_connect( ssl ) <= 0 )
{
     return;
}
long hsReturn = BIO_do_handshake( sbio );
if ( hsReturn <= 0 ) 
{
    return;
}
}

我的(非阻塞)BIO读取返回垃圾:实际:↨♥+o 1E¿={û²∙ìφáD'öQñ↨▼≈☺预期:这是一个测试消息

int SSLSocket::BIORead( std::string &buffer, const int size )
{
int bytesRead = -1;
std::vector<char> readBuffer(size);
std::cout << "Before BIO_read() call" << std::endl;
bytesRead = BIO_read( m_bio, readBuffer.data(), size );
std::cout << "After BIO_read() call" << std::endl;
std::cout << "BIO_read() read   : " << bytesRead << " bytes" << std::endl;
std::string tmpBuffer = std::string( readBuffer.begin(), readBuffer.end() );
std::cout << "BIO_read() buffer : " << tmpBuffer << " bytes" << std::endl;
if ( bytesRead < 0 ) 
{
    //  Check if should retry read, if not then an error on the connection
    //  has occurred and the user notified.
    if ( BIO_should_retry( m_bio ) )
    {
        bytesRead = 0;
    }
    else
    {
      // real error
      bytesRead = -1;
  }
}
else if ( bytesRead == 0 ) 
{
    //  Nothing was read
    bytesRead = 0;
}
else
{
    buffer = std::string( readBuffer.begin(), readBuffer.end() );
}
return bytesRead;
}

SSL_connect已经进行了握手,但是您必须正确地使用非阻塞套接字,例如检查SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE并等待所需的条件,只要SSL_connect返回<0。所以不需要调用BIO_do_handshake