请教下Openssl怎么使用异步

zhousitiaoda 2016-06-22 04:48:43
https请求,使用的openssl,网上的例子基本都是同步的,想使用异步,查了下官方资料,貌似本身不提供异步,其异步更多的依赖于socket本身。比如SSL_accept(如果我没理解错的话)

NOTES

The behaviour of SSL_accept() depends on the underlying BIO.

If the underlying BIO is blocking, SSL_accept() will only return once the handshake has been finished or an error occurred.

If the underlying BIO is non-blocking, SSL_accept() will also return when the underlying BIO could not satisfy the needs of SSL_accept() to continue the handshake, indicating the problem by the return value -1. In this case a call to SSL_get_error() with the return value of SSL_accept() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. The calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_accept(). The action depends on the underlying BIO. When using a non-blocking socket, nothing is to be done, but select() can be used to check for the required condition. When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.

如果是这样的话,有没有什么好的框架,自己裸写感觉成本有点高。试了下WSAEventSelect貌似不行,只要有连接进来,只要对新连接返回的socket调用WSAEventSelect就会导致SSL的accept失败。
...全文
457 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
draculacsdn 2016-06-22
  • 打赏
  • 举报
回复
1. 初始化SSL库
SSL_load_error_strings ();
SSL_library_init ();
sslContext = SSL_CTX_new (SSLv23_method ());

//server端需要初始化证书与私钥
string cert = "server.pem", key = "server.pem";
r = SSL_CTX_use_certificate_file(g_sslCtx, cert.c_str(), SSL_FILETYPE_PEM);
r = SSL_CTX_use_PrivateKey_file(g_sslCtx, key.c_str(), SSL_FILETYPE_PEM);
r = SSL_CTX_check_private_key(g_sslCtx);


2. 非阻塞方式建立tcp连接(网上有很多epoll相关例子)

3. 使用已建立连接的socket初始化ssl
ch->ssl_ = SSL_new (g_sslCtx);
int r = SSL_set_fd(ch->ssl_, ch->fd_);
服务器端 SSL_set_accept_state(ch->ssl_);
客户端 SSL_set_connect_state(ch->ssl_);

4. epoll_wait后,如果SSL相关的socket有读写事件需要处理则进行SSL握手,直到握手完成
int r = SSL_do_handshake(ch->ssl_);
if (r == 1) { // 若返回值为1,则SSL握手已完成
  ch->sslConnected_ = true;
  return;
}
int err = SSL_get_error(ch->ssl_, r);
if (err == SSL_ERROR_WANT_WRITE) { //SSL需要在非阻塞socket可写时写入数据
  ch->events_ |= EPOLLOUT;
  ch->events_ &= ~EPOLLIN;
} else if (err == SSL_ERROR_WANT_READ) { //SSL需要在非阻塞socket可读时读入数据
  ch->events_ |= EPOLLIN; //等待socket可读
  ch->events_ &= ~EPOLLOUT; //暂时不关注socket可写状态
} else { //错误
  ERR_print_errors(errBio);
}

5. 握手完成后,进行SSL数据的读写
SSL_write(con->sslHandle, text, len);
SSL_read(con->sslHandle, buf, sizeof buf);


详细可运行的例子参看
https://github.com/yedf/openssl-example/blob/master/async-ssl-svr.cc
https://github.com/yedf/openssl-example/blob/master/async-ssl-cli.cc

handy已经对openssl进行了封装,并且给出了例子,详见
https://github.com/yedf/handy-ssl
Eleven 2016-06-22
  • 打赏
  • 举报
回复
http://www.cnblogs.com/dongfuye/p/4121066.html 请参考一下这个,看看有无帮助~

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧