openssl使用sni支持多域名、多证书服务
程序员文章站
2022-03-06 18:58:04
...
map<string,SSL_CTX*> g_ctxMap;
SSL_CTX* serverSslCtx = NULL;
static int serverNameCallback(SSL * ssl, int * ad, void * arg)
{
if(ssl == NULL)
return SSL_TLSEXT_ERR_NOACK;
const char * servername = SSL_get_servername(ssl,TLSEXT_NAMETYPE_host_name);
SSL_CTX* ctx = NULL;
if (servername && strlen(servername) > 0)
{
//从g_ctxMap中找到servername对应的SSL_CTX
_OUTPUT(INFO, "%s name = %s\n", __FUNCTION__, servername);
}
else
{
//选一个默认的SSL_CTX
_OUTPUT(INFO, "%s name is NULL\n", __FUNCTION__);
}
SSL_set_SSL_CTX(ssl, ctx);
SSL_set_verify(ssl, SSL_CTX_get_verify_mode(ctx),
SSL_CTX_get_verify_callback(ctx));
SSL_set_verify_depth(ssl, SSL_CTX_get_verify_depth(ctx));
SSL_set_options(ssl, SSL_CTX_get_options(ctx));
return SSL_TLSEXT_ERR_OK;
}
//初始化一个通用的SSL_CTX,设置好回调函数
//接受客户端的连接sock,与通用SSL_CTX绑定,后面收到包就会触发回调,再根据域名绑定对应的SSL_CTX
serverSslCtx = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_set_tlsext_servername_callback(serverSslCtx, serverNameCallback);