【发布时间】:2014-08-07 11:31:03
【问题描述】:
我尝试使用 OpenSSL 在 Windows 上设置 SSL 连接。我的步骤如下:
- 创建 TCP 套接字 BIO。
- 使用 TCP 连接到服务器。
- 将此 BIO 添加到 SSL 实例。
- 升级到 SSL 的连接。
但是,当我尝试使用最近连接到 TCP 套接字的 BIO 调用 SSL_connect 时,我在 Windows 上收到带有 WSAENOTCONN 的 SSL_ERROR_SYSCALL。
我的代码如下。
this->TcpSocket = BIO_new(BIO_s_connect());
BIO_set_nbio(this->TcpSocket, 1);
BIO_set_conn_hostname(this->TcpSocket, hostname);
BIO_set_conn_port(this->TcpSocket, port);
int connectionResult;
while ((connectionResult = BIO_do_connect(this->TcpSocket)) <= 0 && BIO_should_retry(this->TcpSocket))
{
auto retryType = BIO_retry_type(this->TcpSocket);
if (retryType & BIO_FLAGS_READ != 0
|| retryType & BIO_FLAGS_WRITE != 0)
{
auto handle = BIO_get_fd(this->TcpSocket, NULL);
fd_set handles;
handles.fd_count = 1;
handles.fd_array[0] = handle;
timeval timeout;
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
if (retryType & BIO_FLAGS_READ != 0)
select(handle + 1, &handles, NULL, NULL, &timeout);
else
select(handle + 1, NULL, &handles, NULL, &timeout);
}
else
Thread::Sleep(50);
}
this->SslContext = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_verify(this->SslContext, SSL_VERIFY_NONE, NULL);
this->SslSocket = SSL_new(this->SslContext);
SSL_set_bio(this->SslSocket, this->TcpSocket, this->TcpSocket);
int sslConnectResult;
while ((sslConnectResult = SSL_connect(this->SslSocket)) == -1)
{
auto now = time(NULL);
int sslConnectErrorCode = SSL_get_error(this->SslSocket, sslConnectResult);
switch (sslConnectErrorCode)
{
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
if (now >= deadline)
throw SocketTimeoutException();
else
this->WaitForTcpSocket(deadline - now);
break;
case SSL_ERROR_SYSCALL:
{
auto err = GetLastError();
this->RaiseOpenSSLException();
}
break;
default:
this->RaiseOpenSSLException();
}
}
错误的原因是什么?我知道这意味着客户端与服务器断开连接。但我不明白为什么。我有良好的互联网连接,服务器也很稳定,所以不太可能是网络连接的原因。
【问题讨论】:
标签: c++ sockets ssl tcp openssl