Reuse the Linux OpenSSL TlsChannel implementation (platform guard widened to __linux__); the trust anchor lives in the app-private filesDir, injected via TlsSetAnchorDir in nativeInit before the connection thread starts. COMMAND_TLS_ENABLE/DISABLE save/remove the anchor, hot-reload and reconnect only when the transport actually changes, so the master menu takes effect within seconds without restarting the app. Login reports RES_TLS, refreshed before each re-login. The reconnect flag is consumed before the drop check and cleared before reconnecting so a switch racing a disconnect cannot cause an extra reconnect/login cycle. Cross-compile OpenSSL 3.5.0 per ABI with build_openssl_android.sh (NDK clang + MSYS2 perl/make), integrated into build_android_libs.ps1 (-OpenSslOnly). Static libs and per-ABI headers are tracked like the existing libzstd/libsign prebuilts; --exclude-libs keeps OpenSSL symbols private to libyama.so, isolated from the Java-layer Conscrypt. Co-Authored-By: Qoder <noreply@qoder.com>
604 lines
21 KiB
C++
604 lines
21 KiB
C++
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。Linux 与 Android 编译(共用 OpenSSL 实现)。
|
||
//
|
||
// 与 Windows 的 Schannel 实现语义对齐:
|
||
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
|
||
// - 信任锚严格钉扎:证书链只按信任锚文件里的证书校验,不含系统根库;
|
||
// - 不校主机名(客户端按 IP 连接,与 Windows 版一致)、不做吊销检查;
|
||
// - 信任锚「存在即已配置」:读取/解析失败一律 TlsLoadError()=true → 调用方拒绝连接。
|
||
//
|
||
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
|
||
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
|
||
// 接收线程在 select 前优先消费。
|
||
#if defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
|
||
|
||
#include "TlsChannel.h"
|
||
|
||
#include "common/commands.h" // SOCKET_ERROR / closesocket 等 POSIX 兼容宏
|
||
#include "common/logger.h" // Mprintf
|
||
|
||
#include <openssl/err.h>
|
||
#include <openssl/pem.h>
|
||
#include <openssl/ssl.h>
|
||
#include <openssl/x509.h>
|
||
#include <openssl/x509_vfy.h>
|
||
|
||
#include <cerrno>
|
||
#include <chrono>
|
||
#include <cstdlib>
|
||
#include <cstring>
|
||
#include <fstream>
|
||
#include <iterator>
|
||
#include <mutex>
|
||
#include <string>
|
||
#include <vector>
|
||
|
||
#include <fcntl.h>
|
||
#include <sys/stat.h>
|
||
#include <sys/types.h>
|
||
#include <unistd.h>
|
||
|
||
namespace {
|
||
|
||
const char* const kAnchorName = "yama-ca.pem";
|
||
|
||
// 进程级 TLS 状态。两平台都可由 TlsReload() 热切换(Windows 版改造前是 call_once)
|
||
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
|
||
std::mutex g_stateMtx; // 保护下面四项
|
||
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
|
||
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
|
||
bool g_tlsError = false; // 信任锚存在但加载失败:拒绝连接(fail-closed)
|
||
SSL_CTX* g_tlsCtx = nullptr; // 进程级上下文(线程安全,可被多条连接共享)
|
||
std::string g_anchorPath; // 仅用于日志
|
||
#ifdef __ANDROID__
|
||
std::string g_anchorDir; // 信任锚目录,由 TlsSetAnchorDir 注入(App filesDir)
|
||
#endif
|
||
|
||
// 配置目录:
|
||
// Linux:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost);
|
||
// Android:App 私有 filesDir(TlsSetAnchorDir 注入),无「程序目录」回退。
|
||
std::string ConfigDir()
|
||
{
|
||
#ifdef __ANDROID__
|
||
return g_anchorDir;
|
||
#else
|
||
const char* xdg = getenv("XDG_CONFIG_HOME");
|
||
if (xdg && xdg[0])
|
||
return std::string(xdg) + "/ghost";
|
||
const char* home = getenv("HOME");
|
||
if (!home || !home[0])
|
||
return std::string();
|
||
return std::string(home) + "/.config/ghost";
|
||
#endif
|
||
}
|
||
|
||
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。Android 无此概念,返回空。
|
||
std::string ExeDir()
|
||
{
|
||
#ifdef __ANDROID__
|
||
return std::string();
|
||
#else
|
||
char buf[4096];
|
||
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
|
||
if (n <= 0)
|
||
return std::string();
|
||
buf[n] = '\0';
|
||
char* slash = strrchr(buf, '/');
|
||
if (!slash)
|
||
return std::string();
|
||
*slash = '\0';
|
||
return std::string(buf);
|
||
#endif
|
||
}
|
||
|
||
// 信任锚候选路径(按优先级),只返回已经存在的那个:
|
||
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
|
||
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
|
||
bool FindAnchorPath(std::string& out)
|
||
{
|
||
std::vector<std::string> cands;
|
||
std::string dir = ConfigDir();
|
||
if (!dir.empty())
|
||
cands.push_back(dir + "/" + kAnchorName);
|
||
std::string exed = ExeDir();
|
||
if (!exed.empty())
|
||
cands.push_back(exed + "/" + kAnchorName);
|
||
for (size_t i = 0; i < cands.size(); ++i) {
|
||
if (access(cands[i].c_str(), F_OK) == 0) {
|
||
out = cands[i];
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// 递归 mkdir -p(已存在视为成功)。
|
||
bool MkdirP(const std::string& path, mode_t mode)
|
||
{
|
||
if (path.empty())
|
||
return false;
|
||
struct stat st;
|
||
if (stat(path.c_str(), &st) == 0)
|
||
return S_ISDIR(st.st_mode);
|
||
size_t slash = path.find_last_of('/');
|
||
if (slash != std::string::npos && slash > 0) {
|
||
if (!MkdirP(path.substr(0, slash), mode))
|
||
return false;
|
||
}
|
||
if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST)
|
||
return false;
|
||
return true;
|
||
}
|
||
|
||
// 把 PEM(可含多张证书)或 DER 信任锚写入 store。返回加入的证书数。
|
||
int LoadAnchors(const std::string& data, X509_STORE* store)
|
||
{
|
||
int added = 0;
|
||
if (data.find("-----BEGIN") != std::string::npos) {
|
||
BIO* bio = BIO_new_mem_buf(data.data(), (int)data.size());
|
||
if (bio) {
|
||
for (;;) {
|
||
X509* cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
|
||
if (!cert)
|
||
break;
|
||
if (X509_STORE_add_cert(store, cert) == 1)
|
||
++added;
|
||
else
|
||
ERR_clear_error(); // 重复证书等:忽略该张,继续读后面的
|
||
X509_free(cert);
|
||
}
|
||
BIO_free(bio);
|
||
}
|
||
ERR_clear_error();
|
||
}
|
||
if (added == 0) {
|
||
// 退回 DER(单张)
|
||
const unsigned char* p = (const unsigned char*)data.data();
|
||
X509* cert = d2i_X509(NULL, &p, (long)data.size());
|
||
if (cert) {
|
||
if (X509_STORE_add_cert(store, cert) == 1)
|
||
++added;
|
||
else
|
||
ERR_clear_error();
|
||
X509_free(cert);
|
||
}
|
||
ERR_clear_error();
|
||
}
|
||
return added;
|
||
}
|
||
|
||
enum BuildResult
|
||
{
|
||
BUILD_PLAINTEXT, // 没有信任锚文件 → 明文模式
|
||
BUILD_READY, // *outCtx 为新建上下文,调用方接管所有权
|
||
BUILD_INVALID, // 文件存在但读不了/解析不出证书(err 说明原因)
|
||
};
|
||
|
||
// 按当前信任锚文件构建一份新的 TLS 上下文。不读写任何全局状态,便于「先构建、成功再替换」。
|
||
BuildResult BuildState(SSL_CTX** outCtx, std::string& anchorPath, std::string& err, int& certs)
|
||
{
|
||
*outCtx = nullptr;
|
||
certs = 0;
|
||
anchorPath.clear();
|
||
|
||
std::string path;
|
||
if (!FindAnchorPath(path)) {
|
||
// 无证书 → 明文(默认,与老客户端一致)
|
||
return BUILD_PLAINTEXT;
|
||
}
|
||
anchorPath = path;
|
||
|
||
// 证书已配置:管理员已「颁发」,必须走 TLS;读取/解析失败即拒绝连接(fail-closed),
|
||
// 不能静默回退明文。
|
||
std::ifstream f(path.c_str(), std::ios::binary);
|
||
if (!f) {
|
||
err = "cannot open " + path + ": " + strerror(errno);
|
||
return BUILD_INVALID;
|
||
}
|
||
std::string pem((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||
|
||
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
|
||
if (!ctx) {
|
||
err = "SSL_CTX_new failed";
|
||
return BUILD_INVALID;
|
||
}
|
||
|
||
// TLS 1.2 钉扎:与 Windows 客户端(SP_PROT_TLS1_2_CLIENT)及两套服务端(Schannel
|
||
// SP_PROT_TLS1_2_SERVER / Go MinVersion=TLS1.2)保持一致。
|
||
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
|
||
SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
|
||
|
||
// SSL_VERIFY_PEER + 自定义 store = 严格钉扎到信任锚(不含系统根库),链校验在握手内
|
||
// 完成,失败即握手失败。verify 回调传 NULL 使用默认行为(只验链,不校主机名)。
|
||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
||
SSL_CTX_set_verify_depth(ctx, 8);
|
||
|
||
// 对端不打招呼就断开(不发 close_notify)在这里是常态:服务端关闭子连接时不发,
|
||
// 客户端自己也同样不发(见 CloseHandles 的说明)。OpenSSL 3.0 起这种 unexpected EOF
|
||
// 被归为 SSL_ERROR_SSL 协议错误,于是每结束一个终端/文件传输子连接都会记一条
|
||
// 「SSL_read failed」——线上日志看着像 TLS 坏了。打开这个选项让它按正常关闭处理
|
||
// (SSL_read 返回 0),与 Recv 的文档语义以及 Windows 版的行为一致。
|
||
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
|
||
SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
|
||
#endif
|
||
|
||
X509_STORE* store = X509_STORE_new();
|
||
certs = store ? LoadAnchors(pem, store) : 0;
|
||
if (!store || certs <= 0) {
|
||
if (store)
|
||
X509_STORE_free(store);
|
||
SSL_CTX_free(ctx);
|
||
certs = 0;
|
||
err = "trust anchor " + path + " present but empty/invalid";
|
||
return BUILD_INVALID;
|
||
}
|
||
SSL_CTX_set_cert_store(ctx, store); // ctx 接管 store 所有权
|
||
|
||
*outCtx = ctx;
|
||
return BUILD_READY;
|
||
}
|
||
|
||
// 替换全局状态并释放旧上下文(调用方持 g_stateMtx)。SSL 对象在 SSL_new 时已递增
|
||
// SSL_CTX 的引用计数,所以已经建立的连接不会因为这里释放旧 ctx 而失效。
|
||
void InstallStateLocked(SSL_CTX* ctx, bool enabled, bool error, const std::string& anchor)
|
||
{
|
||
SSL_CTX* old = g_tlsCtx;
|
||
g_tlsCtx = ctx;
|
||
g_tlsEnabled = enabled;
|
||
g_tlsError = error;
|
||
g_anchorPath = anchor;
|
||
if (old)
|
||
SSL_CTX_free(old);
|
||
}
|
||
|
||
// 首次加载(调用方持锁):锚存在但无效时置 fail-closed。
|
||
void EnsureInitLocked()
|
||
{
|
||
if (g_inited)
|
||
return;
|
||
g_inited = true;
|
||
|
||
SSL_CTX* ctx = nullptr;
|
||
std::string anchor, err;
|
||
int certs = 0;
|
||
switch (BuildState(&ctx, anchor, err, certs)) {
|
||
case BUILD_PLAINTEXT:
|
||
InstallStateLocked(nullptr, false, false, anchor);
|
||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||
break;
|
||
case BUILD_READY:
|
||
InstallStateLocked(ctx, true, false, anchor);
|
||
Mprintf("[TLS] enabled: trust anchor loaded (%s, %d cert(s)), all connections use TLS\n",
|
||
anchor.c_str(), certs);
|
||
break;
|
||
case BUILD_INVALID:
|
||
InstallStateLocked(nullptr, false, true, anchor);
|
||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||
break;
|
||
}
|
||
}
|
||
|
||
} // namespace
|
||
|
||
#ifdef __ANDROID__
|
||
// 注入信任锚目录(App filesDir)。nativeInit 在启动连接线程前调用一次;此后不再变更,
|
||
// 故 ConfigDir() 的无锁读取与这里的写入不存在实际竞争(见 TlsChannel.h 契约)。
|
||
void TlsSetAnchorDir(const std::string& dir)
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||
g_anchorDir = dir;
|
||
}
|
||
#endif
|
||
|
||
bool TlsEnabled()
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||
EnsureInitLocked();
|
||
return g_tlsEnabled;
|
||
}
|
||
|
||
bool TlsLoadError()
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||
EnsureInitLocked();
|
||
return g_tlsError;
|
||
}
|
||
|
||
bool TlsReload(std::string& err)
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||
EnsureInitLocked(); // 未初始化就先按启动语义建立基态,保持 fail-closed 行为
|
||
|
||
SSL_CTX* ctx = nullptr;
|
||
std::string anchor;
|
||
int certs = 0;
|
||
BuildResult r = BuildState(&ctx, anchor, err, certs);
|
||
if (r == BUILD_INVALID) {
|
||
// 保留原状态:一次坏下发不该让正在工作的客户端失联(下次启动仍会 fail-closed)。
|
||
Mprintf("[TLS] reload FAILED: %s; keeping current transport (%s)\n",
|
||
err.c_str(), g_tlsEnabled ? "TLS" : "plaintext");
|
||
return false;
|
||
}
|
||
if (r == BUILD_PLAINTEXT) {
|
||
InstallStateLocked(nullptr, false, false, anchor);
|
||
Mprintf("[TLS] reloaded: no trust anchor, transport is now plaintext\n");
|
||
return true;
|
||
}
|
||
InstallStateLocked(ctx, true, false, anchor);
|
||
Mprintf("[TLS] reloaded: trust anchor %s (%d cert(s)), transport is now TLS\n",
|
||
anchor.c_str(), certs);
|
||
return true;
|
||
}
|
||
|
||
// ---- 信任锚下发 / 撤销(服务端 COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE)----
|
||
|
||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err)
|
||
{
|
||
if (pem.empty()) {
|
||
err = "empty certificate payload";
|
||
return false;
|
||
}
|
||
|
||
// 先验证再落盘:文件一旦写进去,下次启动就会被无条件信任,坏锚等于把客户端锁死
|
||
// (fail-closed 连不上,也没法再从服务端改回来)。宁可拒绝一次下发。
|
||
{
|
||
X509_STORE* probe = X509_STORE_new();
|
||
int n = probe ? LoadAnchors(pem, probe) : 0;
|
||
if (probe)
|
||
X509_STORE_free(probe);
|
||
if (n <= 0) {
|
||
err = "payload is not a valid PEM/DER certificate";
|
||
return false;
|
||
}
|
||
}
|
||
|
||
std::string dir = ConfigDir();
|
||
if (dir.empty()) {
|
||
dir = ExeDir(); // 无 HOME 的极端环境:退回程序目录
|
||
if (dir.empty()) {
|
||
err = "cannot resolve config directory";
|
||
return false;
|
||
}
|
||
}
|
||
if (!MkdirP(dir, 0700)) {
|
||
err = "cannot create directory " + dir + ": " + strerror(errno);
|
||
return false;
|
||
}
|
||
|
||
std::string path = dir + "/" + kAnchorName;
|
||
std::string tmp = path + ".tmp";
|
||
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||
if (fd < 0) {
|
||
err = "cannot create " + tmp + ": " + strerror(errno);
|
||
return false;
|
||
}
|
||
size_t off = 0;
|
||
while (off < pem.size()) {
|
||
ssize_t w = write(fd, pem.data() + off, pem.size() - off);
|
||
if (w <= 0) {
|
||
if (w < 0 && errno == EINTR)
|
||
continue;
|
||
err = "cannot write " + tmp + ": " + strerror(errno);
|
||
close(fd);
|
||
unlink(tmp.c_str());
|
||
return false;
|
||
}
|
||
off += (size_t)w;
|
||
}
|
||
fsync(fd);
|
||
close(fd);
|
||
|
||
// 原子替换 + 收紧权限(目录可能已由 LinuxConfig 以 0755 创建)
|
||
if (rename(tmp.c_str(), path.c_str()) != 0) {
|
||
err = "cannot replace " + path + ": " + strerror(errno);
|
||
unlink(tmp.c_str());
|
||
return false;
|
||
}
|
||
chmod(path.c_str(), 0600);
|
||
|
||
Mprintf("[TLS] trust anchor saved to %s\n", path.c_str());
|
||
return true;
|
||
}
|
||
|
||
bool TlsTrustAnchorRemove(std::string& err)
|
||
{
|
||
std::vector<std::string> paths;
|
||
std::string dir = ConfigDir();
|
||
if (!dir.empty())
|
||
paths.push_back(dir + "/" + kAnchorName);
|
||
std::string exed = ExeDir();
|
||
if (!exed.empty())
|
||
paths.push_back(exed + "/" + kAnchorName);
|
||
|
||
bool removed = false;
|
||
for (size_t i = 0; i < paths.size(); ++i) {
|
||
if (unlink(paths[i].c_str()) == 0) {
|
||
removed = true;
|
||
Mprintf("[TLS] trust anchor removed: %s\n", paths[i].c_str());
|
||
} else if (errno != ENOENT) {
|
||
err = "cannot remove " + paths[i] + ": " + strerror(errno);
|
||
return false;
|
||
}
|
||
}
|
||
if (!removed) {
|
||
err = "no trust anchor configured";
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// ---- TlsChannel ----
|
||
|
||
void TlsChannel::CloseHandles()
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
if (m_ssl) {
|
||
SSL_free(m_ssl); // 不发送 close_notify:与 Windows 的 DeleteSecurityContext 同语义
|
||
m_ssl = nullptr;
|
||
}
|
||
m_fd = -1;
|
||
m_ready = false;
|
||
}
|
||
|
||
bool TlsChannel::Handshake(int sock, const char* sni, const std::string& /*host*/,
|
||
const std::string& /*configured*/)
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||
|
||
// 在状态锁内取一份上下文:SSL_new 会递增 SSL_CTX 引用计数,此后即使 TlsReload()
|
||
// 把全局上下文换掉(旧 ctx 被 SSL_CTX_free),本次握手的 SSL 仍然安全。
|
||
SSL* ssl = nullptr;
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||
EnsureInitLocked();
|
||
if (g_tlsCtx)
|
||
ssl = SSL_new(g_tlsCtx);
|
||
}
|
||
if (!ssl) {
|
||
Mprintf("[TLS] handshake called but no TLS context is available\n");
|
||
return false;
|
||
}
|
||
if (SSL_set_fd(ssl, sock) != 1) {
|
||
Mprintf("[TLS] SSL_set_fd failed\n");
|
||
SSL_free(ssl);
|
||
return false;
|
||
}
|
||
// SNI:反代(nginx)据此按域名分流到正确的 server 块。证书校验仍是自定义 store 里的
|
||
// 信任锚(SSL_VERIFY_PEER + 不校主机名),与直连主控端口时完全一致。
|
||
if (sni && *sni)
|
||
SSL_set_tlsext_host_name(ssl, sni);
|
||
SSL_set_connect_state(ssl);
|
||
|
||
// 阻塞 socket:正常路径不会出现 WANT_READ/WANT_WRITE,但这两种情况必须重试。
|
||
// 关键坑:调用方给 socket 设了 SO_RCVTIMEO(IOCPClient 的握手超时,15s)。读超时后
|
||
// recv 返回 EAGAIN,OpenSSL 报的是 WANT_READ 而不是 SYSCALL——无脑 continue 会把
|
||
// 「对端只收不发」变成永久重试:握手既不结束、也不失败、更不打一行日志,主循环就
|
||
// 停摆在这里(2026-11-07 实机复现:frps 侧连接 ESTAB、Recv-Q 空、客户端零日志)。
|
||
// 所以这里给整个握手一个总时限,超时按失败处理,交回外层重连。
|
||
const auto hsStart = std::chrono::steady_clock::now();
|
||
const auto hsDeadline = std::chrono::seconds(30); // > 内核读超时(15s),留一次重试余量
|
||
for (;;) {
|
||
ERR_clear_error();
|
||
int r = SSL_do_handshake(ssl);
|
||
if (r == 1)
|
||
break;
|
||
int e = SSL_get_error(ssl, r);
|
||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) {
|
||
if (std::chrono::steady_clock::now() - hsStart > hsDeadline) {
|
||
Mprintf("[TLS] handshake timed out after %llds (peer silent), aborting\n",
|
||
(long long)std::chrono::duration_cast<std::chrono::seconds>(
|
||
std::chrono::steady_clock::now() - hsStart).count());
|
||
SSL_free(ssl);
|
||
return false;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
if (e == SSL_ERROR_SSL) {
|
||
unsigned long err = ERR_peek_last_error();
|
||
char ebuf[256] = {0};
|
||
if (err)
|
||
ERR_error_string_n(err, ebuf, sizeof(ebuf));
|
||
Mprintf("[TLS] handshake failed: %s\n", ebuf[0] ? ebuf : "SSL error");
|
||
} else if (e == SSL_ERROR_SYSCALL) {
|
||
Mprintf("[TLS] handshake failed: syscall error (%s)\n", strerror(errno));
|
||
} else {
|
||
Mprintf("[TLS] handshake failed: SSL_get_error=%d (peer closed?)\n", e);
|
||
}
|
||
SSL_free(ssl);
|
||
return false;
|
||
}
|
||
|
||
// 单向 TLS:链必须钉扎到信任锚,且服务端确实出示了证书。默认 verify 只验链不校主机名,
|
||
// 与 Windows 版(CertGetCertificateChain 只验链)行为一致。
|
||
long vr = SSL_get_verify_result(ssl);
|
||
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
|
||
X509* peer = SSL_get1_peer_certificate(ssl);
|
||
#else
|
||
X509* peer = SSL_get_peer_certificate(ssl);
|
||
#endif
|
||
if (!peer || vr != X509_V_OK) {
|
||
Mprintf("[TLS] server certificate not trusted against trust anchor (%s)\n",
|
||
X509_verify_cert_error_string(vr));
|
||
if (peer)
|
||
X509_free(peer);
|
||
SSL_free(ssl);
|
||
return false;
|
||
}
|
||
X509_free(peer);
|
||
|
||
m_ssl = ssl;
|
||
m_fd = sock;
|
||
m_ready = true;
|
||
Mprintf("[TLS] handshake OK (%s, server cert trusted)\n", SSL_get_version(ssl));
|
||
return true;
|
||
}
|
||
|
||
int TlsChannel::Recv(int sock, char* out, int outLen)
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
if (!m_ready || outLen <= 0) {
|
||
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
|
||
(int)m_ready, outLen);
|
||
return SOCKET_ERROR;
|
||
}
|
||
(void)sock; // SSL 已绑定 fd
|
||
|
||
for (;;) {
|
||
ERR_clear_error();
|
||
int n = SSL_read(m_ssl, out, outLen);
|
||
if (n > 0)
|
||
return n;
|
||
int e = SSL_get_error(m_ssl, n);
|
||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||
continue;
|
||
if (e == SSL_ERROR_ZERO_RETURN)
|
||
return 0; // close_notify:对端正常关闭
|
||
if (e == SSL_ERROR_SYSCALL && ERR_peek_last_error() == 0)
|
||
return 0; // 对端未发 close_notify 就断开(unexpected EOF),按关闭处理
|
||
|
||
Mprintf("[TLS] SSL_read failed: SSL_get_error=%d (%s)\n", e, strerror(errno));
|
||
return SOCKET_ERROR;
|
||
}
|
||
}
|
||
|
||
int TlsChannel::Send(int sock, const char* data, int len)
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
if (!m_ready)
|
||
return SOCKET_ERROR;
|
||
if (len <= 0)
|
||
return 0;
|
||
(void)sock; // SSL 已绑定 fd
|
||
|
||
int total = 0;
|
||
while (total < len) {
|
||
ERR_clear_error();
|
||
int n = SSL_write(m_ssl, data + total, len - total);
|
||
if (n > 0) {
|
||
total += n;
|
||
continue;
|
||
}
|
||
int e = SSL_get_error(m_ssl, n);
|
||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||
continue;
|
||
|
||
Mprintf("[TLS] SSL_write failed: SSL_get_error=%d (%s), sent=%d/%d\n",
|
||
e, strerror(errno), total, len);
|
||
return total > 0 ? total : SOCKET_ERROR;
|
||
}
|
||
return total;
|
||
}
|
||
|
||
bool TlsChannel::HasPending() const
|
||
{
|
||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||
if (!m_ready || !m_ssl)
|
||
return false;
|
||
// SSL_pending: 已解密未交付的明文;SSL_has_pending: 内部还缓冲着未处理的记录字节。
|
||
// 任一为真都说明 select 看不到但可以立刻读,必须优先消费。
|
||
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
|
||
}
|
||
|
||
#endif // __linux__(含 Android)
|