ssl是secure socket layer的意思, 是一个协议, 主要是为了让socket层的通信更安全。 大名鼎鼎的openssl就是ssl协议的开源实现。所以, 可以预期, tc_sslmgr中基本是对openssl的api的封装。看头文件包含就知道了:
#include "util/tc_sslmgr.h"
#include "util/tc_buffer.h"
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
类SSLManager实现了对ssl相关元素的管理, 是个单例, 看下:
class SSLManager : public TC_Singleton<SSLManager>
{
public:
static void GlobalInit();
SSLManager();
~SSLManager();
bool AddCtx(const std::string& name,
const std::string& cafile,
const std::string& certfile,
const std::string& keyfile,
bool verifyClient);
SSL_CTX* GetCtx(const std::string& name) const;
private:
typedef std::map<std::string, SSL_CTX*> CTX_MAP;
CTX_MAP _ctxSet;
};
} // end namespace tars
这种单例方式看起来有点特别, 不过我们很早以前就说过这种方式了。
来看常见的初始化和销毁:
SSLManager::SSLManager()
{
}
void SSLManager::GlobalInit()
{
(void)SSL_library_init();
OpenSSL_add_all_algorithms();
ERR_load_ERR_strings();
SSL_load_error_strings();
}
SSLManager::~SSLManager()
{
for (CTX_MAP::iterator it(_ctxSet.begin());
it != _ctxSet.end();
++ it)
{
SSL_CTX_free(it->second);
}
ERR_free_strings();
EVP_cleanup();
}
在使用第三方库的时候, 一定要注意init, alloc这样的字眼, 通常需要clean, free它们。 虽然有的地方发库有自动clean和free的机智, 但还是要留心。下面说4个我见过的case:
case1: 在现公司, 见过这样一个问题, 初始化后, 没有释放, 最后资源耗尽, 性能下降。当时不得不临时定期重启服务, 暂时规避问题。这是服务器, 可以重启, 如果是case2中的嵌入式设备, 就蛋疼了。
case2: 当然, init之类的通常也是不可少的。 在前东家的时候, 某代码中少了init之类的操作, 结果导致低概率core dump, 最后花了一个星期左右才彻底解决这个不得不解决的概率core dump问题。 做嵌入式就是这样, 卖出去的东西, 无法召回。 万一之一出现的core dump问题, 是个天大的问题, 这意味着, 卖出1亿台手机, 就有1万台经常死机, 想想就觉得可怕。 当时那个问题, 花了3天的时间才重现并找到可用于分析的core dump文件, 然后发现core dump的位置在第三方库中(少了init), 然后又花了3天的时间去验证修改是否生效, 怎么会有这个问题呢? 原因是: 不正确使用第三方库所致。解决办法是: 加初始化init语句。
case3: 后来, 在现公司, 出现过一个进程中的多次初始化init行为(每个请求来, 都init了一次), 导致服务成功率不高, 后来改成每个进程只初始化一次, 服务的整体成功率立即达到3个9.
case4: 也要注意, 不要多次释放, 我在某公司实习的时候, 见过多次释放, 结果程序crash了, 呵呵哒。
扯远了。
看下其余操作:
bool SSLManager::AddCtx(const std::string& name,
const std::string& cafile,
const std::string& certfile,
const std::string& keyfile,
bool verifyClient)
{
if (_ctxSet.count(name))
return false;
SSL_CTX* ctx = SSL_CTX_new(SSLv23_method());
if (!ctx)
return false;
#define RETURN_IF_FAIL(call) \
if ((call) <= 0) { \
ERR_print_errors_fp(stderr); \
return false;\
}
if (verifyClient)
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
else
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
SSL_CTX_clear_options(ctx, SSL_OP_LEGACY_SERVER_CONNECT);
SSL_CTX_clear_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
RETURN_IF_FAIL (SSL_CTX_set_session_id_context(ctx, (const unsigned char*)ctx, sizeof ctx));
if (!cafile.empty())
RETURN_IF_FAIL (SSL_CTX_load_verify_locations(ctx, cafile.data(), NULL));
// 客户端可以不提供证书的
if (!certfile.empty())
RETURN_IF_FAIL (SSL_CTX_use_certificate_file(ctx, certfile.data(), SSL_FILETYPE_PEM));
if (!keyfile.empty())
{
RETURN_IF_FAIL (SSL_CTX_use_PrivateKey_file(ctx, keyfile.data(), SSL_FILETYPE_PEM));
RETURN_IF_FAIL (SSL_CTX_check_private_key(ctx));
}
#undef RETURN_IF_FAIL
return _ctxSet.insert(std::make_pair(name, ctx)).second;
}
SSL_CTX* SSLManager::GetCtx(const std::string& name) const
{
CTX_MAP::const_iterator it = _ctxSet.find(name);
return it == _ctxSet.end() ? NULL: it->second;
}
SSL* NewSSL(const std::string& ctxName)
{
SSL_CTX* ctx = SSLManager::getInstance()->GetCtx(ctxName);
if (!ctx)
return NULL;
SSL* ssl = SSL_new(ctx);
SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // allow retry ssl-write with different args
SSL_set_bio(ssl, BIO_new(BIO_s_mem()), BIO_new(BIO_s_mem()));
BIO_set_mem_eof_return(SSL_get_rbio(ssl), -1);
BIO_set_mem_eof_return(SSL_get_wbio(ssl), -1);
return ssl;
}
void GetMemData(BIO* bio, TC_Buffer& buf)
{
while (true)
{
buf.AssureSpace(16 * 1024);
int bytes = BIO_read(bio, buf.WriteAddr(), buf.WritableSize());
if (bytes <= 0)
return;
buf.Produce(bytes);
}
// never here
}
void GetSSLHead(const char* data, char& type, unsigned short& ver, unsigned short& len)
{
type = data[0];
ver = *(unsigned short*)(data + 1);
len = *(unsigned short*)(data + 3);
ver = ntohs(ver);
len = ntohs(len);
}
bool DoSSLRead(SSL* ssl, std::string& out)
{
while (true)
{
char plainBuf[32 * 1024];
ERR_clear_error();
int bytes = SSL_read(ssl, plainBuf, sizeof plainBuf);
if (bytes > 0)
{
out.append(plainBuf, bytes);
}
else
{
int err = SSL_get_error(ssl, bytes);
// when peer issued renegotiation, here will demand us to send handshake data.
// write to mem bio will always success, only need to check whether has data to send.
//assert (err != SSL_ERROR_WANT_WRITE);
if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_ZERO_RETURN)
{
printf("DoSSLRead err %d\n", err);
return false;
}
break;
}
}
return true;
}
还是封装! 如果对ssl协议和实现有兴趣, 可以看看openssl中的实现, 至于tc_sslmgr中, 是看不到什么东西的, 它仅仅是封装而已。