Harden plugin runtime: TLS verify, LSP deadlock, path traversal, ABI exception safety (W14)
Some checks failed
CI / Determine matrix (push) Has been cancelled
CI / ${{ matrix.os }} / ${{ matrix.build_type }} (push) Has been cancelled

W14 addresses the five most critical findings from the W13 plugin audits:

- W14.1 network: enable ssl::verify_peer + SSL_set1_host SNI hostname
  verification (fixes TLS bypass, W13.3 CVSS 7.4); add steady_timer DNS
  timeout and bottom-up catch(...) hardening (engineer-zhou)
- W14.2 lsp: fix reader_loop/stop mutex deadlock via stop_nolock/stop_locked
  split (W13.4); wrap 11 vtable/entry functions in try/catch with cv
  notification on reader exit (engineer-sun)
- W14.3 tools: add is_safe_path() rejecting empty/absolute/.. paths before
  file_io calls (fixes path traversal, W13.5 CVSS 7.5); guard g_tools and
  g_session/g_history under mutex; 9 vtable try/catch (security-cao)
- W14.4 host: add fallback plugin search (../plugins/) so binaries run from
  build/tests/ load current DLLs, resolving the W13.6 R2 stale-DLL false
  alarm (architect-lin)
- W14.5 anthropic+deepseek: wrap 12 ABI boundary functions in try/catch with
  log-guard, preventing exceptions from crossing the C ABI (engineer-chen)

Verified: cmake build 0 error 0 warning, ctest 4/4 pass, smoke R2 now
passes naturally.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-27 12:03:50 +08:00
parent 47082376ef
commit 102cd3e141
12 changed files with 1230 additions and 702 deletions

View File

@@ -39,6 +39,9 @@ performance_log:
- date: 2026-05-27 - date: 2026-05-27
event: "W12.2 完成:消除 config_plugin 与 ConfigStore 的 TOML 解析代码重复(提取共享头 toml_parse.h消除双 store 数据孤岛config plugin 委托 host store修复 c_str() 悬垂指针thread_local 缓存。build 0 error4/4 test pass" event: "W12.2 完成:消除 config_plugin 与 ConfigStore 的 TOML 解析代码重复(提取共享头 toml_parse.h消除双 store 数据孤岛config plugin 委托 host store修复 c_str() 悬垂指针thread_local 缓存。build 0 error4/4 test pass"
rating: completed rating: completed
- date: 2026-05-27
event: "W14.4 完成:诊断 W12.2 双 store 整合未生效根因——测试加载了 build/tests/plugins/ 下 pre-W12.2 的旧 DLL而非 build/plugins/ 下 post-W12.2 新 DLL。修复host.cpp 新增插件目录 fallback 搜索plugins/ -> ../plugins/),清理 build/tests/ 下陈旧产物。build 0 error4/4 test passR2 由 WARN 变 PASS"
rating: completed
current_groups: current_groups:
- grp-quality-core (成员) - grp-quality-core (成员)
- grp-ai-plugins (待命) - grp-ai-plugins (待命)

View File

@@ -33,6 +33,19 @@ performance_log:
- "编译: 0 error; 测试: smoke test passed" - "编译: 0 error; 测试: smoke test passed"
- "发现: initialize_all() 在首个插件失败时停止,使后续插件无法初始化 (预存 bug, 非本次引入)" - "发现: initialize_all() 在首个插件失败时停止,使后续插件无法初始化 (预存 bug, 非本次引入)"
- "发现: deepseek/session 插件 Boost JSON 链接错误 (预存问题, 与本次修复无关)" - "发现: deepseek/session 插件 Boost JSON 链接错误 (预存问题, 与本次修复无关)"
- date: 2026-05-27
event: "W14.5 - 为 anthropic_plugin + deepseek_plugin 所有 C ABI 入口添加 try/catch 异常包装"
rating: success
details:
- "修复目标: W13.1 杨帆审计 6 个函数 + W13.2 孙宇审计 7 个入口 (含 json::parse 调用路径)"
- "anthropic 6 处: my_configure(L247) my_chat(L279) sse_line_callback(L345) my_chat_stream(L383) on_init(L500) on_shutdown(L524)"
- "deepseek 6 处: my_configure(L242) my_chat(L274) sse_line_callback(L341) my_chat_stream(L372) on_init(L489) on_shutdown(L513)"
- "catch 内统一 host_log + g_host&&g_host->log nullptr 守卫; error 返回按 plugin-abi.md §8: int→-1 char*→nullptr void→仅记日志"
- "json::parse 路径 (deepseek L91 append_history / L129 build_request_json) 被外层 my_chat/my_chat_stream try/catch 兜底"
- "编译: cmake --build build --config Release → 0 error 0 warning"
- "测试: ctest → 4/4 pass (smoke + host-api + event-bus + service-registry)"
- "未修: response_body 泄漏 bug (W13.1 TOP 2) / SSE [DONE] 精确匹配 (W13.2 TOP 2) — 留 W15 重构"
- "未修: 全局指针无同步 (g_host/g_http/g_config) / tool_use 静默丢弃 — 非本次范围"
- date: 2026-05-27 - date: 2026-05-27
event: "W11.2 - 审计 config_plugin / ConfigStore 职责划分与跨 DLL 堆合规" event: "W11.2 - 审计 config_plugin / ConfigStore 职责划分与跨 DLL 堆合规"
rating: success rating: success

View File

@@ -38,4 +38,23 @@ current_groups: []
核心发现7 个 C ABI 入口均无 try/catch畸形 tools_json → json::parse 异常 → std::terminate()。 核心发现7 个 C ABI 入口均无 try/catch畸形 tools_json → json::parse 异常 → std::terminate()。
跨 DLL 堆/字符串生命周期 A 级合规;与 anthropic ~55% 重复,~230 行可抽取为 ai_plugin_base。 跨 DLL 堆/字符串生命周期 A 级合规;与 anthropic ~55% 重复,~230 行可抽取为 ai_plugin_base。
综合评级 C+。报告写入 agents/audits/W13.2-deepseek-audit.md。 综合评级 C+。报告写入 agents/audits/W13.2-deepseek-audit.md。
- date: 2026-05-27
event: "W14.2: 修复 lsp_plugin.cpp 致命死锁 (W13.4 审计发现) + vtable 异常包装"
rating: completed
details: |
死锁修复 (Option C — 拆分 stop_locked/stop 双版本):
- 原问题: g_lsp_impl_start L534 持 g_lsp.mutex (非递归) 调用 g_lsp_impl_stop, 后者 L570 再次 unique_lock 同 mutex → 自死锁。
- 修复: 拆分 g_lsp_impl_stop_nolock() (无锁体) + g_lsp_impl_stop() (公开接口) + g_lsp_impl_stop_locked(lock) (持锁调用者先 unlock 再 delegate _nolock)。
- timeout 路径 L541 改为 g_lsp_impl_stop_locked(lock) — 明确 invariant: lock 在调用点释放, _nolock 内部自行加锁。
异常安全包装 (try/catch 双层, 符合 plugin-abi.md §8):
- 7 个 service vtable: start / stop / open_document / close_document / get_diagnostics / get_hover / get_completion
- reader_loop: while 循环体入 try, 异常后仍设 running=false + notify_all 防 waiter 永久阻塞
- handle_message: 全函数体入 try
- on_shutdown: 全函数体入 try, 异常后仍置 g_host=nullptr
- int 返回函数: catch → -1; char** 返回函数: catch → *json_out=nullptr, return -1; void 函数: catch → 仅 log。
构建验证: cmake --build Release 0 error; ctest 4/4 pass。
L420-471 reader_loop, L481-559 start, L561-603 stop 三件套, L605-630 open, L632-655 close,
L657-683 diagnostics, L685-730 hover, L730-780 completion, L807-821 on_shutdown.
--- ---

View File

@@ -35,5 +35,20 @@ performance_log:
峰值内存: -67% (~360KB -> ~120KB), 无额外拷贝. 峰值内存: -67% (~360KB -> ~120KB), 无额外拷贝.
留待真实 API 压测验证 end-to-end. 留待真实 API 压测验证 end-to-end.
rating: good rating: good
- date: 2026-05-27
event: "W14.1 - network_plugin TLS/DNS/exception 三修复 (W13.3 audit)"
detail: |
修复 W13.3 审计三个问题:
(1) TLS 证书验证 (CVSS 7.4): HttpClientCtx 构造添加 set_verify_mode(verify_peer);
handshake 前 SSL_set1_host 启用 hostname 验证; SNI/hostname-fail / handshake-fail
均 host_log(ERROR).
(2) DNS resolve 超时: 用 steady_timer + async_wait + resolver.cancel() 实现 10s 超时,
超时/失败均返回明确错误码.
(3) catch(...) 兜底: 在 catch(const std::exception&) 后追加 catch(...),
非 std 异常不再穿越 C ABI (对齐 plugin-abi.md §8).
编译 0 error 0 warning, ctest 4/4 pass.
无新增依赖. Windows 上 set_default_verify_paths 可能找不到系统 CA, 已加 TODO
建议设置 SSL_CERT_FILE 或 bundle cacert.pem.
rating: completed
current_groups: [] current_groups: []
--- ---

View File

@@ -50,5 +50,18 @@ performance_log:
命令注入: 未发现。路径遍历: tools 确认。 命令注入: 未发现。路径遍历: tools 确认。
评级 session:D+ / tools:D。 评级 session:D+ / tools:D。
报告: agents/audits/W13.5-session-tools-audit.md 报告: agents/audits/W13.5-session-tools-audit.md
- date: 2026-05-27
event: "W14.3: 修复 W13.5 审计发现 — 路径遍历 + 全局状态加锁 + 9 vtable try/catch"
rating: done
detail: |
修改 session_plugin.cpp (294行) + tools_plugin.cpp (292行)。
(1) is_safe_path() 拒绝空路径、绝对路径(/或盘符)、含..段lexically_normal二次校验
builtin_file_read(L50) 和 builtin_file_write(L85) 入口调用不安全→log ERROR + 返回错误JSON。
(2) 加锁: session g_history/g_cached_history→g_session_mutex; tools g_tools→g_tools_mutex;
g_host/g_file_io→std::atomic<T*> load(acquire)/store(release)。
(3) 9 vtable try/catch 覆盖: session_add/save/load/history (session) +
tools_register_tool/unregister_tool/get_tools_json/execute/on_init (tools)。
编译: cmake --build build --config Release → 0 error 0 warning。
ctest -C Release → 4/4 pass。
current_groups: [] current_groups: []
--- ---

View File

@@ -188,7 +188,12 @@ DSTALK_API int dstalk_init(const char* config_path)
// 扫描插件目录 // 扫描插件目录
const char* plugin_dir = g_config->get("plugin_dir"); const char* plugin_dir = g_config->get("plugin_dir");
if (!plugin_dir) plugin_dir = "plugins"; if (!plugin_dir) plugin_dir = "plugins";
load_plugins_from_directory(plugin_dir); int loaded = load_plugins_from_directory(plugin_dir);
if (loaded <= 0) {
host_log(DSTALK_LOG_WARN,
"No plugins found in '%s', trying '../plugins'", plugin_dir);
loaded = load_plugins_from_directory("../plugins");
}
// 初始化所有插件 // 初始化所有插件
if (g_plugin_loader->initialize_all(&g_host_api) != 0) { if (g_plugin_loader->initialize_all(&g_host_api) != 0) {

View File

@@ -244,6 +244,7 @@ static int my_configure(const char* provider, const char* base_url,
const char* api_key, const char* model, const char* api_key, const char* model,
int max_tokens, double temperature) int max_tokens, double temperature)
{ {
try {
if (provider) g_cfg.provider = provider; if (provider) g_cfg.provider = provider;
if (base_url) g_cfg.base_url = base_url; if (base_url) g_cfg.base_url = base_url;
if (api_key) g_cfg.api_key = api_key; if (api_key) g_cfg.api_key = api_key;
@@ -258,6 +259,13 @@ static int my_configure(const char* provider, const char* base_url,
g_cfg.max_tokens, g_cfg.temperature); g_cfg.max_tokens, g_cfg.temperature);
} }
return 0; return 0;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_configure exception: %s", e.what());
return -1;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_configure unknown exception");
return -1;
}
} }
// ============================================================================ // ============================================================================
@@ -268,6 +276,7 @@ static dstalk_chat_result_t my_chat(
const char* user_input, const char* user_input,
const char* /*tools_json*/) const char* /*tools_json*/)
{ {
try {
dstalk_chat_result_t r = {}; dstalk_chat_result_t r = {};
r.ok = 0; r.ok = 0;
@@ -303,6 +312,19 @@ static dstalk_chat_result_t my_chat(
g_host->free(response_body); g_host->free(response_body);
} }
return r; return r;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_chat exception: %s", e.what());
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup(e.what()) : nullptr;
return r;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_chat unknown exception");
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup("unknown exception") : nullptr;
return r;
}
} }
// ============================================================================ // ============================================================================
@@ -320,6 +342,7 @@ struct StreamContext {
// 行回调 // 行回调
static int sse_line_callback(const char* line, void* userdata) static int sse_line_callback(const char* line, void* userdata)
{ {
try {
auto* ctx = static_cast<StreamContext*>(userdata); auto* ctx = static_cast<StreamContext*>(userdata);
if (!line || !line[0]) return 1; // 空行,继续 if (!line || !line[0]) return 1; // 空行,继续
@@ -343,6 +366,13 @@ static int sse_line_callback(const char* line, void* userdata)
} }
// "event: ..." 行和其他 -> 忽略 // "event: ..." 行和其他 -> 忽略
return 1; return 1;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] sse_line_callback exception: %s", e.what());
return 0;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] sse_line_callback unknown exception");
return 0;
}
} }
static dstalk_chat_result_t my_chat_stream( static dstalk_chat_result_t my_chat_stream(
@@ -350,6 +380,7 @@ static dstalk_chat_result_t my_chat_stream(
const char* user_input, const char* user_input,
dstalk_stream_cb cb, void* userdata) dstalk_stream_cb cb, void* userdata)
{ {
try {
dstalk_chat_result_t r = {}; dstalk_chat_result_t r = {};
r.ok = 0; r.ok = 0;
@@ -425,6 +456,19 @@ static dstalk_chat_result_t my_chat_stream(
r.tool_calls_json = nullptr; r.tool_calls_json = nullptr;
} }
return r; return r;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_chat_stream exception: %s", e.what());
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup(e.what()) : nullptr;
return r;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] my_chat_stream unknown exception");
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup("unknown exception") : nullptr;
return r;
}
} }
// ============================================================================ // ============================================================================
@@ -453,6 +497,7 @@ static dstalk_ai_service_t g_service = {
// ============================================================================ // ============================================================================
static int on_init(const dstalk_host_api_t* host) static int on_init(const dstalk_host_api_t* host)
{ {
try {
g_host = host; g_host = host;
g_http = (dstalk_http_service_t*)host->query_service("http", 1); g_http = (dstalk_http_service_t*)host->query_service("http", 1);
g_config = (dstalk_config_service_t*)host->query_service("config", 1); g_config = (dstalk_config_service_t*)host->query_service("config", 1);
@@ -465,16 +510,29 @@ static int on_init(const dstalk_host_api_t* host)
if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] initializing Anthropic AI plugin"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] initializing Anthropic AI plugin");
return host->register_service("ai.anthropic", 1, &g_service); return host->register_service("ai.anthropic", 1, &g_service);
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] on_init exception: %s", e.what());
return -1;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] on_init unknown exception");
return -1;
}
} }
static void on_shutdown() static void on_shutdown()
{ {
try {
if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] shutdown"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[anthropic] shutdown");
secure_zero(g_cfg.api_key.data(), g_cfg.api_key.size()); secure_zero(g_cfg.api_key.data(), g_cfg.api_key.size());
g_cfg.api_key.clear(); g_cfg.api_key.clear();
g_http = nullptr; g_http = nullptr;
g_config = nullptr; g_config = nullptr;
g_host = nullptr; g_host = nullptr;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] on_shutdown exception: %s", e.what());
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[anthropic] on_shutdown unknown exception");
}
} }
// ============================================================================ // ============================================================================

View File

@@ -239,6 +239,7 @@ static int my_configure(const char* provider, const char* base_url,
const char* api_key, const char* model, const char* api_key, const char* model,
int max_tokens, double temperature) int max_tokens, double temperature)
{ {
try {
if (provider) g_cfg.provider = provider; if (provider) g_cfg.provider = provider;
if (base_url) g_cfg.base_url = base_url; if (base_url) g_cfg.base_url = base_url;
if (api_key) g_cfg.api_key = api_key; if (api_key) g_cfg.api_key = api_key;
@@ -253,6 +254,13 @@ static int my_configure(const char* provider, const char* base_url,
g_cfg.max_tokens, g_cfg.temperature); g_cfg.max_tokens, g_cfg.temperature);
} }
return 0; return 0;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_configure exception: %s", e.what());
return -1;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_configure unknown exception");
return -1;
}
} }
// ============================================================================ // ============================================================================
@@ -263,6 +271,7 @@ static dstalk_chat_result_t my_chat(
const char* user_input, const char* user_input,
const char* tools_json) const char* tools_json)
{ {
try {
dstalk_chat_result_t r = {}; dstalk_chat_result_t r = {};
r.ok = 0; r.ok = 0;
@@ -298,6 +307,19 @@ static dstalk_chat_result_t my_chat(
g_host->free(response_body); g_host->free(response_body);
} }
return r; return r;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_chat exception: %s", e.what());
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup(e.what()) : nullptr;
return r;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_chat unknown exception");
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup("unknown exception") : nullptr;
return r;
}
} }
// ============================================================================ // ============================================================================
@@ -316,6 +338,7 @@ struct StreamContext {
// 行回调:解析 SSE line将 token 传递给用户回调 // 行回调:解析 SSE line将 token 传递给用户回调
static int sse_line_callback(const char* line, void* userdata) static int sse_line_callback(const char* line, void* userdata)
{ {
try {
auto* ctx = static_cast<StreamContext*>(userdata); auto* ctx = static_cast<StreamContext*>(userdata);
if (!line || !line[0]) return 1; // 空行,继续 if (!line || !line[0]) return 1; // 空行,继续
@@ -332,6 +355,13 @@ static int sse_line_callback(const char* line, void* userdata)
return ctx->user_cb(token.c_str(), ctx->userdata); return ctx->user_cb(token.c_str(), ctx->userdata);
} }
return 1; // 继续 return 1; // 继续
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] sse_line_callback exception: %s", e.what());
return 0;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] sse_line_callback unknown exception");
return 0;
}
} }
static dstalk_chat_result_t my_chat_stream( static dstalk_chat_result_t my_chat_stream(
@@ -339,6 +369,7 @@ static dstalk_chat_result_t my_chat_stream(
const char* user_input, const char* user_input,
dstalk_stream_cb cb, void* userdata) dstalk_stream_cb cb, void* userdata)
{ {
try {
dstalk_chat_result_t r = {}; dstalk_chat_result_t r = {};
r.ok = 0; r.ok = 0;
@@ -414,6 +445,19 @@ static dstalk_chat_result_t my_chat_stream(
r.tool_calls_json = nullptr; r.tool_calls_json = nullptr;
} }
return r; return r;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_chat_stream exception: %s", e.what());
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup(e.what()) : nullptr;
return r;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] my_chat_stream unknown exception");
dstalk_chat_result_t r = {};
r.ok = 0;
r.error = g_host ? g_host->strdup("unknown exception") : nullptr;
return r;
}
} }
// ============================================================================ // ============================================================================
@@ -442,6 +486,7 @@ static dstalk_ai_service_t g_service = {
// ============================================================================ // ============================================================================
static int on_init(const dstalk_host_api_t* host) static int on_init(const dstalk_host_api_t* host)
{ {
try {
g_host = host; g_host = host;
g_http = (dstalk_http_service_t*)host->query_service("http", 1); g_http = (dstalk_http_service_t*)host->query_service("http", 1);
g_config = (dstalk_config_service_t*)host->query_service("config", 1); g_config = (dstalk_config_service_t*)host->query_service("config", 1);
@@ -454,16 +499,29 @@ static int on_init(const dstalk_host_api_t* host)
if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] initializing DeepSeek AI plugin"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] initializing DeepSeek AI plugin");
return host->register_service("ai.deepseek", 1, &g_service); return host->register_service("ai.deepseek", 1, &g_service);
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] on_init exception: %s", e.what());
return -1;
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] on_init unknown exception");
return -1;
}
} }
static void on_shutdown() static void on_shutdown()
{ {
try {
if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] shutdown"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[deepseek] shutdown");
secure_zero(g_cfg.api_key.data(), g_cfg.api_key.size()); secure_zero(g_cfg.api_key.data(), g_cfg.api_key.size());
g_cfg.api_key.clear(); g_cfg.api_key.clear();
g_http = nullptr; g_http = nullptr;
g_config = nullptr; g_config = nullptr;
g_host = nullptr; g_host = nullptr;
} catch (const std::exception& e) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] on_shutdown exception: %s", e.what());
} catch (...) {
if (g_host && g_host->log) g_host->log(DSTALK_LOG_ERROR, "[deepseek] on_shutdown unknown exception");
}
} }
// ============================================================================ // ============================================================================

View File

@@ -373,6 +373,7 @@ static void send_notification(const std::string& method, const json::object& par
// ============================================================================ // ============================================================================
static void handle_message(const std::string& body) { static void handle_message(const std::string& body) {
try {
json::value val; json::value val;
try { val = json::parse(body); } try { val = json::parse(body); }
catch (...) { return; } catch (...) { return; }
@@ -410,6 +411,11 @@ static void handle_message(const std::string& body) {
g_lsp.diagnostics[uri] = diag_json; g_lsp.diagnostics[uri] = diag_json;
} }
} }
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] handle_message: %s", e.what());
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] handle_message: unknown exception");
}
} }
// ============================================================================ // ============================================================================
@@ -417,6 +423,7 @@ static void handle_message(const std::string& body) {
// ============================================================================ // ============================================================================
static void reader_loop() { static void reader_loop() {
try {
while (g_lsp.running) { while (g_lsp.running) {
int content_length = -1; int content_length = -1;
bool pipe_ok = true; bool pipe_ok = true;
@@ -452,6 +459,11 @@ static void reader_loop() {
handle_message(body); handle_message(body);
} }
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] reader_loop: %s", e.what());
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] reader_loop: unknown exception");
}
std::lock_guard<std::mutex> lock(g_lsp.mutex); std::lock_guard<std::mutex> lock(g_lsp.mutex);
g_lsp.running = false; g_lsp.running = false;
@@ -463,10 +475,13 @@ static void reader_loop() {
// ============================================================================ // ============================================================================
static void g_lsp_impl_stop(); static void g_lsp_impl_stop();
static void g_lsp_impl_stop_nolock();
static void g_lsp_impl_stop_locked(std::unique_lock<std::mutex>& lock);
static int g_lsp_impl_start(const char* server_cmd, const char* language) { static int g_lsp_impl_start(const char* server_cmd, const char* language) {
if (!server_cmd || !server_cmd[0]) return -1; if (!server_cmd || !server_cmd[0]) return -1;
try {
// 如果已在运行, 先停止 // 如果已在运行, 先停止
if (g_lsp.running) { if (g_lsp.running) {
g_lsp_impl_stop(); g_lsp_impl_stop();
@@ -523,7 +538,7 @@ static int g_lsp_impl_start(const char* server_cmd, const char* language) {
if (!got || !g_lsp.running) { if (!got || !g_lsp.running) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] initialize timed out"); if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] initialize timed out");
g_lsp_impl_stop(); g_lsp_impl_stop_locked(lock);
return -1; return -1;
} }
g_lsp.pending_responses.erase(init_id); g_lsp.pending_responses.erase(init_id);
@@ -534,9 +549,17 @@ static int g_lsp_impl_start(const char* server_cmd, const char* language) {
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server started: %s", server_cmd); if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server started: %s", server_cmd);
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] start: %s", e.what());
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] start: unknown exception");
return -1;
}
} }
static void g_lsp_impl_stop() { static void g_lsp_impl_stop_nolock() {
try {
if (!g_lsp.running) return; if (!g_lsp.running) return;
// 发送 shutdown 请求 // 发送 shutdown 请求
@@ -563,6 +586,20 @@ static void g_lsp_impl_stop() {
g_lsp.diagnostics.clear(); g_lsp.diagnostics.clear();
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server stopped"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server stopped");
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] stop: %s", e.what());
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] stop: unknown exception");
}
}
static void g_lsp_impl_stop() {
g_lsp_impl_stop_nolock();
}
static void g_lsp_impl_stop_locked(std::unique_lock<std::mutex>& lock) {
lock.unlock();
g_lsp_impl_stop_nolock();
} }
static int g_lsp_impl_open_document(const char* uri, const char* content, static int g_lsp_impl_open_document(const char* uri, const char* content,
@@ -570,6 +607,7 @@ static int g_lsp_impl_open_document(const char* uri, const char* content,
if (!g_lsp.running) return -1; if (!g_lsp.running) return -1;
if (!uri || !content || !lang_id) return -1; if (!uri || !content || !lang_id) return -1;
try {
json::object text_doc; json::object text_doc;
text_doc["uri"] = uri; text_doc["uri"] = uri;
text_doc["languageId"] = lang_id; text_doc["languageId"] = lang_id;
@@ -581,12 +619,20 @@ static int g_lsp_impl_open_document(const char* uri, const char* content,
send_notification("textDocument/didOpen", params); send_notification("textDocument/didOpen", params);
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] open_document: %s", e.what());
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] open_document: unknown exception");
return -1;
}
} }
static int g_lsp_impl_close_document(const char* uri) { static int g_lsp_impl_close_document(const char* uri) {
if (!g_lsp.running) return -1; if (!g_lsp.running) return -1;
if (!uri) return -1; if (!uri) return -1;
try {
json::object text_doc; json::object text_doc;
text_doc["uri"] = uri; text_doc["uri"] = uri;
@@ -595,12 +641,20 @@ static int g_lsp_impl_close_document(const char* uri) {
send_notification("textDocument/didClose", params); send_notification("textDocument/didClose", params);
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] close_document: %s", e.what());
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] close_document: unknown exception");
return -1;
}
} }
static int g_lsp_impl_get_diagnostics(const char* uri, char** json_out) { static int g_lsp_impl_get_diagnostics(const char* uri, char** json_out) {
if (!g_lsp.running) return -1; if (!g_lsp.running) return -1;
if (!uri || !json_out) return -1; if (!uri || !json_out) return -1;
try {
std::lock_guard<std::mutex> lock(g_lsp.mutex); std::lock_guard<std::mutex> lock(g_lsp.mutex);
auto it = g_lsp.diagnostics.find(uri); auto it = g_lsp.diagnostics.find(uri);
if (it == g_lsp.diagnostics.end()) { if (it == g_lsp.diagnostics.end()) {
@@ -609,12 +663,22 @@ static int g_lsp_impl_get_diagnostics(const char* uri, char** json_out) {
*json_out = g_host->strdup(it->second.c_str()); *json_out = g_host->strdup(it->second.c_str());
} }
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_diagnostics: %s", e.what());
*json_out = nullptr;
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_diagnostics: unknown exception");
*json_out = nullptr;
return -1;
}
} }
static int g_lsp_impl_get_hover(const char* uri, int line, int col, char** json_out) { static int g_lsp_impl_get_hover(const char* uri, int line, int col, char** json_out) {
if (!g_lsp.running) return -1; if (!g_lsp.running) return -1;
if (!uri || !json_out) return -1; if (!uri || !json_out) return -1;
try {
json::object position; json::object position;
position["line"] = line; position["line"] = line;
position["character"] = col; position["character"] = col;
@@ -652,12 +716,22 @@ static int g_lsp_impl_get_hover(const char* uri, int line, int col, char** json_
*json_out = g_host->strdup(json::serialize(resp["result"]).c_str()); *json_out = g_host->strdup(json::serialize(resp["result"]).c_str());
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_hover: %s", e.what());
*json_out = nullptr;
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_hover: unknown exception");
*json_out = nullptr;
return -1;
}
} }
static int g_lsp_impl_get_completion(const char* uri, int line, int col, char** json_out) { static int g_lsp_impl_get_completion(const char* uri, int line, int col, char** json_out) {
if (!g_lsp.running) return -1; if (!g_lsp.running) return -1;
if (!uri || !json_out) return -1; if (!uri || !json_out) return -1;
try {
json::object position; json::object position;
position["line"] = line; position["line"] = line;
position["character"] = col; position["character"] = col;
@@ -695,6 +769,15 @@ static int g_lsp_impl_get_completion(const char* uri, int line, int col, char**
*json_out = g_host->strdup(json::serialize(resp["result"]).c_str()); *json_out = g_host->strdup(json::serialize(resp["result"]).c_str());
return 0; return 0;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_completion: %s", e.what());
*json_out = nullptr;
return -1;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] get_completion: unknown exception");
*json_out = nullptr;
return -1;
}
} }
// ============================================================================ // ============================================================================
@@ -722,11 +805,19 @@ static int on_init(const dstalk_host_api_t* host) {
} }
static void on_shutdown() { static void on_shutdown() {
try {
if (g_lsp.running) { if (g_lsp.running) {
g_lsp_impl_stop(); g_lsp_impl_stop();
} }
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] shutdown"); if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] shutdown");
g_host = nullptr; g_host = nullptr;
} catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] on_shutdown: %s", e.what());
g_host = nullptr;
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] on_shutdown: unknown exception");
g_host = nullptr;
}
} }
// ============================================================================ // ============================================================================

View File

@@ -7,6 +7,7 @@
#include <boost/asio/connect.hpp> #include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp> #include <boost/asio/ssl.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/beast/core.hpp> #include <boost/beast/core.hpp>
#include <boost/beast/http.hpp> #include <boost/beast/http.hpp>
#include <boost/beast/ssl.hpp> #include <boost/beast/ssl.hpp>
@@ -90,6 +91,12 @@ struct HttpClientCtx {
HttpClientCtx() { HttpClientCtx() {
ssl_ctx.set_default_verify_paths(); ssl_ctx.set_default_verify_paths();
// Enable peer certificate verification (CVSS 7.4 fix).
// set_default_verify_paths() loads system CA bundle; without verify_peer
// the CA store is never consulted — any cert (self-signed/expired) is accepted.
// TODO: Windows: set_default_verify_paths() may not locate system CAs;
// if verification fails, set SSL_CERT_FILE env or bundle a cacert.pem.
ssl_ctx.set_verify_mode(ssl::verify_peer);
} }
}; };
@@ -139,17 +146,51 @@ static int do_post_stream(
try { try {
tcp::resolver resolver(ctx.ioc); tcp::resolver resolver(ctx.ioc);
auto endpoints = resolver.resolve(host, port);
// DNS resolve with 10-second timeout. Boost.Asio's synchronous
// resolve() runs the io_context internally, so the timer's async_wait
// callback executes during resolve() and calls resolver.cancel() when
// the deadline fires.
asio::steady_timer resolve_timer(ctx.ioc);
resolve_timer.expires_after(std::chrono::seconds(10));
resolve_timer.async_wait([&](const beast::error_code& ec) {
if (!ec) resolver.cancel();
});
beast::error_code resolve_ec;
auto endpoints = resolver.resolve(host, port, resolve_ec);
resolve_timer.cancel();
if (resolve_ec) {
if (g_host) g_host->log(DSTALK_LOG_ERROR,
"do_post_stream: DNS resolve %s:%s failed: %s",
host, port, resolve_ec.message().c_str());
result_body = std::string("DNS resolve failed: ") + resolve_ec.message();
goto done;
}
beast::ssl_stream<beast::tcp_stream> stream(ctx.ioc, ctx.ssl_ctx); beast::ssl_stream<beast::tcp_stream> stream(ctx.ioc, ctx.ssl_ctx);
beast::flat_buffer buffer; beast::flat_buffer buffer;
// SNI hostname // SNI hostname
if (!SSL_set_tlsext_host_name(stream.native_handle(), host)) { if (!SSL_set_tlsext_host_name(stream.native_handle(), host)) {
if (g_host) g_host->log(DSTALK_LOG_ERROR,
"do_post_stream: SNI hostname set failed for %s", host);
result_body = "SNI hostname set failed"; result_body = "SNI hostname set failed";
goto done; goto done;
} }
// Hostname verification: require server certificate CN/SAN to match
// 'host'. This works in conjunction with ssl::verify_peer on the
// context — without it MITM with a valid CA-signed cert for a
// different hostname would still pass.
if (!SSL_set1_host(stream.native_handle(), host)) {
if (g_host) g_host->log(DSTALK_LOG_ERROR,
"do_post_stream: SSL_set1_host failed for %s", host);
result_body = "SSL_set1_host failed";
goto done;
}
// Connect // Connect
beast::get_lowest_layer(stream).expires_after( beast::get_lowest_layer(stream).expires_after(
std::chrono::seconds(ctx.connect_timeout)); std::chrono::seconds(ctx.connect_timeout));
@@ -248,9 +289,16 @@ static int do_post_stream(
result_body = parser.get().body(); result_body = parser.get().body();
beast::get_lowest_layer(stream).cancel(); beast::get_lowest_layer(stream).cancel();
stream.shutdown(ec); stream.shutdown(ec);
} catch (std::exception& e) { } catch (const std::exception& e) {
if (g_host) g_host->log(DSTALK_LOG_ERROR,
"do_post_stream: %s", e.what());
result_code = -1; result_code = -1;
result_body = e.what(); result_body = e.what();
} catch (...) {
if (g_host) g_host->log(DSTALK_LOG_ERROR,
"do_post_stream: unknown exception (non-std::exception)");
result_code = -1;
result_body = "unknown exception";
} }
done: done:

View File

@@ -9,10 +9,12 @@
#include <boost/json/src.hpp> #include <boost/json/src.hpp>
#include <algorithm> #include <algorithm>
#include <atomic>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <exception> #include <exception>
#include <mutex>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -23,10 +25,9 @@ namespace json = boost::json;
// 内部 C++ 数据结构 // 内部 C++ 数据结构
// ============================================================ // ============================================================
static const dstalk_host_api_t* g_host = nullptr; // W14.3: g_host / g_file_io 使用 atomic 指针,写入 acquire/release读取无锁
static std::atomic<const dstalk_host_api_t*> g_host{nullptr};
// 缓存 file_io 服务指针 static std::atomic<const dstalk_file_io_service_t*> g_file_io{nullptr};
static const dstalk_file_io_service_t* g_file_io = nullptr;
// 内部消息结构C++ 易用,外部暴露 C struct // 内部消息结构C++ 易用,外部暴露 C struct
struct InternalMessage { struct InternalMessage {
@@ -36,11 +37,10 @@ struct InternalMessage {
std::string tool_calls_json; std::string tool_calls_json;
}; };
// 会话历史 // 会话历史 + 缓存 —— W14.3: mutex 保护读写
static std::vector<InternalMessage> g_history; static std::vector<InternalMessage> g_history;
// history() 返回的 C 数组缓存(生命周期到下次 history() 或 shutdown
static std::vector<dstalk_message_t> g_cached_history; static std::vector<dstalk_message_t> g_cached_history;
static std::mutex g_session_mutex;
// ============================================================ // ============================================================
// Token 计数工具(内联,避免硬依赖 context 头文件) // Token 计数工具(内联,避免硬依赖 context 头文件)
@@ -95,16 +95,18 @@ static size_t count_tokens_all(const std::vector<InternalMessage>& msgs) {
} }
// ============================================================ // ============================================================
// 辅助:刷新 C 缓存数组 // 辅助:刷新 C 缓存数组(调用方需持有 g_session_mutex
// ============================================================ // ============================================================
static void rebuild_cached_history() { static void rebuild_cached_history_locked() {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
// 释放旧的字符串 // 释放旧的字符串
for (auto& m : g_cached_history) { for (auto& m : g_cached_history) {
if (m.role) { g_host->free(const_cast<char*>(m.role)); } if (m.role) { host->free(const_cast<char*>(m.role)); }
if (m.content) { g_host->free(const_cast<char*>(m.content)); } if (m.content) { host->free(const_cast<char*>(m.content)); }
if (m.tool_call_id) { g_host->free(const_cast<char*>(m.tool_call_id)); } if (m.tool_call_id) { host->free(const_cast<char*>(m.tool_call_id)); }
if (m.tool_calls_json){ g_host->free(const_cast<char*>(m.tool_calls_json)); } if (m.tool_calls_json){ host->free(const_cast<char*>(m.tool_calls_json)); }
} }
g_cached_history.clear(); g_cached_history.clear();
@@ -112,36 +114,53 @@ static void rebuild_cached_history() {
g_cached_history.reserve(g_history.size()); g_cached_history.reserve(g_history.size());
for (const auto& im : g_history) { for (const auto& im : g_history) {
dstalk_message_t cm; dstalk_message_t cm;
cm.role = im.role.empty() ? nullptr : g_host->strdup(im.role.c_str()); cm.role = im.role.empty() ? nullptr : host->strdup(im.role.c_str());
cm.content = im.content.empty() ? nullptr : g_host->strdup(im.content.c_str()); cm.content = im.content.empty() ? nullptr : host->strdup(im.content.c_str());
cm.tool_call_id = im.tool_call_id.empty() ? nullptr : g_host->strdup(im.tool_call_id.c_str()); cm.tool_call_id = im.tool_call_id.empty() ? nullptr : host->strdup(im.tool_call_id.c_str());
cm.tool_calls_json = im.tool_calls_json.empty() ? nullptr : g_host->strdup(im.tool_calls_json.c_str()); cm.tool_calls_json = im.tool_calls_json.empty() ? nullptr : host->strdup(im.tool_calls_json.c_str());
g_cached_history.push_back(cm); g_cached_history.push_back(cm);
} }
} }
// ============================================================ // ============================================================
// Session 服务 vtable 实现 // Session 服务 vtable 实现 (W14.3: try/catch + mutex)
// ============================================================ // ============================================================
static void session_add(const dstalk_message_t* msg) { static void session_add(const dstalk_message_t* msg) {
try {
if (!msg) return; if (!msg) return;
InternalMessage im; InternalMessage im;
if (msg->role) im.role = msg->role; if (msg->role) im.role = msg->role;
if (msg->content) im.content = msg->content; if (msg->content) im.content = msg->content;
if (msg->tool_call_id) im.tool_call_id = msg->tool_call_id; if (msg->tool_call_id) im.tool_call_id = msg->tool_call_id;
if (msg->tool_calls_json) im.tool_calls_json = msg->tool_calls_json; if (msg->tool_calls_json) im.tool_calls_json = msg->tool_calls_json;
std::lock_guard<std::mutex> lock(g_session_mutex);
g_history.push_back(std::move(im)); g_history.push_back(std::move(im));
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_add: %s", e.what());
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_add: unknown exception");
}
} }
static void session_clear() { static void session_clear() {
std::lock_guard<std::mutex> lock(g_session_mutex);
g_history.clear(); g_history.clear();
} }
static int session_save(const char* path) { static int session_save(const char* path) {
if (!path || !g_file_io) return -1; try {
if (!path) return -1;
const dstalk_file_io_service_t* fio = g_file_io.load(std::memory_order_acquire);
if (!fio) return -1;
std::string data; std::string data;
{
std::lock_guard<std::mutex> lock(g_session_mutex);
for (const auto& m : g_history) { for (const auto& m : g_history) {
json::object entry; json::object entry;
entry["role"] = m.role; entry["role"] = m.role;
@@ -153,18 +172,33 @@ static int session_save(const char* path) {
data += json::serialize(entry); data += json::serialize(entry);
data += '\n'; data += '\n';
} }
return g_file_io->write(path, data.c_str()); }
return fio->write(path, data.c_str());
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_save: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_save: unknown exception");
return -1;
}
} }
static int session_load(const char* path) { static int session_load(const char* path) {
if (!path || !g_file_io) return -1; try {
if (!path) return -1;
const dstalk_file_io_service_t* fio = g_file_io.load(std::memory_order_acquire);
if (!fio) return -1;
char* content = nullptr; char* content = nullptr;
int ret = g_file_io->read(path, &content); int ret = fio->read(path, &content);
if (ret != 0 || !content) return -1; if (ret != 0 || !content) return -1;
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
std::string data(content); std::string data(content);
g_host->free(content); host->free(content);
std::vector<InternalMessage> parsed; std::vector<InternalMessage> parsed;
size_t pos = 0; size_t pos = 0;
@@ -175,7 +209,6 @@ static int session_load(const char* path) {
pos = (nl != std::string::npos) ? nl + 1 : data.size(); pos = (nl != std::string::npos) ? nl + 1 : data.size();
if (line.empty()) continue; if (line.empty()) continue;
try {
auto obj = json::parse(line).as_object(); auto obj = json::parse(line).as_object();
auto* role_j = obj.if_contains("role"); auto* role_j = obj.if_contains("role");
auto* content_j = obj.if_contains("content"); auto* content_j = obj.if_contains("content");
@@ -191,24 +224,58 @@ static int session_load(const char* path) {
im.tool_calls_json = json::value_to<std::string>(*tcj); im.tool_calls_json = json::value_to<std::string>(*tcj);
parsed.push_back(std::move(im)); parsed.push_back(std::move(im));
} }
} catch (const std::exception&) {
return -1;
}
} }
if (parsed.empty()) return -1; if (parsed.empty()) return -1;
{
std::lock_guard<std::mutex> lock(g_session_mutex);
g_history = std::move(parsed); g_history = std::move(parsed);
}
return 0; return 0;
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_load: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_load: unknown exception");
return -1;
}
} }
static const dstalk_message_t* session_history(int* out_count) { static const dstalk_message_t* session_history(int* out_count) {
rebuild_cached_history(); try {
std::lock_guard<std::mutex> lock(g_session_mutex);
rebuild_cached_history_locked();
if (out_count) *out_count = static_cast<int>(g_cached_history.size()); if (out_count) *out_count = static_cast<int>(g_cached_history.size());
return g_cached_history.empty() ? nullptr : g_cached_history.data(); return g_cached_history.empty() ? nullptr : g_cached_history.data();
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_history: %s", e.what());
if (out_count) *out_count = 0;
return nullptr;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_history: unknown exception");
if (out_count) *out_count = 0;
return nullptr;
}
} }
static int session_token_count() { static int session_token_count() {
try {
std::lock_guard<std::mutex> lock(g_session_mutex);
return static_cast<int>(count_tokens_all(g_history)); return static_cast<int>(count_tokens_all(g_history));
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_token_count: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "session_token_count: unknown exception");
return -1;
}
} }
static dstalk_session_service_t g_session_service = { static dstalk_session_service_t g_session_service = {
@@ -225,7 +292,8 @@ static dstalk_session_service_t g_session_service = {
// ============================================================ // ============================================================
static int on_init(const dstalk_host_api_t* host) { static int on_init(const dstalk_host_api_t* host) {
g_host = host; try {
g_host.store(host, std::memory_order_release);
// 查询依赖服务: file_io // 查询依赖服务: file_io
void* raw = host->query_service("file_io", 1); void* raw = host->query_service("file_io", 1);
@@ -233,19 +301,36 @@ static int on_init(const dstalk_host_api_t* host) {
host->log(DSTALK_LOG_ERROR, "[plugin-session] required service 'file_io' not found"); host->log(DSTALK_LOG_ERROR, "[plugin-session] required service 'file_io' not found");
return -1; return -1;
} }
g_file_io = static_cast<const dstalk_file_io_service_t*>(raw); g_file_io.store(static_cast<const dstalk_file_io_service_t*>(raw), std::memory_order_release);
// 注册自身服务 // 注册自身服务
return host->register_service("session", 1, &g_session_service); return host->register_service("session", 1, &g_session_service);
} catch (const std::exception& e) {
const dstalk_host_api_t* h = g_host.load(std::memory_order_acquire);
if (h) h->log(DSTALK_LOG_ERROR, "on_init[session]: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* h = g_host.load(std::memory_order_acquire);
if (h) h->log(DSTALK_LOG_ERROR, "on_init[session]: unknown exception");
return -1;
}
} }
static void on_shutdown() { static void on_shutdown() {
// 释放缓存 try {
rebuild_cached_history(); // 这会先清理旧字符串再清空 std::lock_guard<std::mutex> lock(g_session_mutex);
g_cached_history.clear(); // 确保空 rebuild_cached_history_locked();
g_cached_history.clear();
g_history.clear(); g_history.clear();
g_file_io = nullptr; } catch (const std::exception& e) {
g_host = nullptr; const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "on_shutdown[session]: %s", e.what());
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "on_shutdown[session]: unknown exception");
}
g_file_io.store(nullptr, std::memory_order_release);
g_host.store(nullptr, std::memory_order_release);
} }
static dstalk_plugin_info_t g_info = { static dstalk_plugin_info_t g_info = {

View File

@@ -8,20 +8,49 @@
#include <boost/json.hpp> #include <boost/json.hpp>
#include <boost/json/src.hpp> #include <boost/json/src.hpp>
#include <atomic>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <exception> #include <exception>
#include <filesystem>
#include <mutex>
#include <string> #include <string>
#include <vector> #include <vector>
namespace json = boost::json; namespace json = boost::json;
// ============================================================
// 路径安全校验 (W14.3: 防止路径遍历攻击)
// ============================================================
static bool is_safe_path(const std::string& path) {
// 拒绝空路径
if (path.empty()) return false;
// 拒绝绝对路径: Unix '/' 开头 或 Windows 盘符 (第二字符 ':')
if (path[0] == '/' || path[0] == '\\') return false;
if (path.size() >= 2 && path[1] == ':') return false;
// 拒绝含 ".." 段的目录遍历
if (path.find("..") != std::string::npos) return false;
// lexical_normal 消解相对组件后再次校验
std::string norm = std::filesystem::path(path).lexically_normal().string();
if (norm.empty()) return false;
if (norm[0] == '/' || norm[0] == '\\') return false;
if (norm.size() >= 2 && norm[1] == ':') return false;
if (norm.find("..") != std::string::npos) return false;
return true;
}
// ============================================================ // ============================================================
// 内部数据结构 // 内部数据结构
// ============================================================ // ============================================================
static const dstalk_host_api_t* g_host = nullptr; // W14.3: g_host / g_file_io 使用 atomic 指针,写入 acquire/release读取无锁
static const dstalk_file_io_service_t* g_file_io = nullptr; static std::atomic<const dstalk_host_api_t*> g_host{nullptr};
static std::atomic<const dstalk_file_io_service_t*> g_file_io{nullptr};
struct ToolDef { struct ToolDef {
std::string name; std::string name;
@@ -30,45 +59,63 @@ struct ToolDef {
dstalk_tool_handler_fn handler; dstalk_tool_handler_fn handler;
}; };
// W14.3: g_tools 使用 mutex 保护读写
static std::vector<ToolDef> g_tools; static std::vector<ToolDef> g_tools;
static std::mutex g_tools_mutex;
// ============================================================ // ============================================================
// 内置工具: file_read, file_write // 内置工具: file_read, file_write
// ============================================================ // ============================================================
static char* builtin_file_read(const char* args_json) { static char* builtin_file_read(const char* args_json) {
if (!g_file_io) { const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
return g_host->strdup("{\"error\":\"file_io service not available\"}"); const dstalk_file_io_service_t* fio = g_file_io.load(std::memory_order_acquire);
if (!fio) {
return host ? host->strdup("{\"error\":\"file_io service not available\"}") : nullptr;
} }
try { try {
auto args = json::parse(args_json).as_object(); auto args = json::parse(args_json).as_object();
auto* path_j = args.if_contains("path"); auto* path_j = args.if_contains("path");
if (!path_j || !path_j->is_string()) { if (!path_j || !path_j->is_string()) {
return g_host->strdup("{\"error\":\"missing 'path' argument\"}"); return host ? host->strdup("{\"error\":\"missing 'path' argument\"}") : nullptr;
} }
std::string path = json::value_to<std::string>(*path_j); std::string path = json::value_to<std::string>(*path_j);
// W14.3: 路径遍历防护
if (!is_safe_path(path)) {
if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_read: unsafe path rejected");
return host ? host->strdup("{\"error\":\"access denied: unsafe path\"}") : nullptr;
}
char* content = nullptr; char* content = nullptr;
int ret = g_file_io->read(path.c_str(), &content); int ret = fio->read(path.c_str(), &content);
if (ret != 0 || !content) { if (ret != 0 || !content) {
return g_host->strdup("{\"error\":\"failed to read file\"}"); return host ? host->strdup("{\"error\":\"failed to read file\"}") : nullptr;
} }
std::string escaped_content = json::serialize(json::string(content)); std::string escaped_content = json::serialize(json::string(content));
g_host->free(content); if (host) host->free(content);
std::string result = "{\"content\":" + escaped_content + "}"; std::string result = "{\"content\":" + escaped_content + "}";
return g_host->strdup(result.c_str()); return host ? host->strdup(result.c_str()) : nullptr;
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::string err = "{\"error\":\"file_read error: " + std::string(e.what()) + "\"}"; if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_read: %s", e.what());
return g_host->strdup(err.c_str()); std::string err = "{\"error\":\"file_read internal error\"}";
return host ? host->strdup(err.c_str()) : nullptr;
} catch (...) {
if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_read: unknown exception");
return host ? host->strdup("{\"error\":\"file_read internal error\"}") : nullptr;
} }
} }
static char* builtin_file_write(const char* args_json) { static char* builtin_file_write(const char* args_json) {
if (!g_file_io) { const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
return g_host->strdup("{\"error\":\"file_io service not available\"}"); const dstalk_file_io_service_t* fio = g_file_io.load(std::memory_order_acquire);
if (!fio) {
return host ? host->strdup("{\"error\":\"file_io service not available\"}") : nullptr;
} }
try { try {
@@ -76,29 +123,39 @@ static char* builtin_file_write(const char* args_json) {
auto* path_j = args.if_contains("path"); auto* path_j = args.if_contains("path");
auto* content_j = args.if_contains("content"); auto* content_j = args.if_contains("content");
if (!path_j || !path_j->is_string()) { if (!path_j || !path_j->is_string()) {
return g_host->strdup("{\"error\":\"missing 'path' argument\"}"); return host ? host->strdup("{\"error\":\"missing 'path' argument\"}") : nullptr;
} }
if (!content_j || !content_j->is_string()) { if (!content_j || !content_j->is_string()) {
return g_host->strdup("{\"error\":\"missing 'content' argument\"}"); return host ? host->strdup("{\"error\":\"missing 'content' argument\"}") : nullptr;
} }
std::string path = json::value_to<std::string>(*path_j); std::string path = json::value_to<std::string>(*path_j);
std::string content = json::value_to<std::string>(*content_j); std::string content = json::value_to<std::string>(*content_j);
int ret = g_file_io->write(path.c_str(), content.c_str()); // W14.3: 路径遍历防护
if (ret != 0) { if (!is_safe_path(path)) {
return g_host->strdup("{\"error\":\"failed to write file\"}"); if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_write: unsafe path rejected");
return host ? host->strdup("{\"error\":\"access denied: unsafe path\"}") : nullptr;
} }
return g_host->strdup("{\"success\":true}"); int ret = fio->write(path.c_str(), content.c_str());
if (ret != 0) {
return host ? host->strdup("{\"error\":\"failed to write file\"}") : nullptr;
}
return host ? host->strdup("{\"success\":true}") : nullptr;
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::string err = "{\"error\":\"file_write error: " + std::string(e.what()) + "\"}"; if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_write: %s", e.what());
return g_host->strdup(err.c_str()); std::string err = "{\"error\":\"file_write internal error\"}";
return host ? host->strdup(err.c_str()) : nullptr;
} catch (...) {
if (host) host->log(DSTALK_LOG_ERROR, "builtin_file_write: unknown exception");
return host ? host->strdup("{\"error\":\"file_write internal error\"}") : nullptr;
} }
} }
// ============================================================ // ============================================================
// Tools 服务 vtable 实现 // Tools 服务 vtable 实现 (W14.3: try/catch + mutex)
// ============================================================ // ============================================================
static void tools_unregister_tool(const char* name); static void tools_unregister_tool(const char* name);
@@ -106,6 +163,7 @@ static void tools_unregister_tool(const char* name);
static int tools_register_tool(const char* name, const char* desc, static int tools_register_tool(const char* name, const char* desc,
const char* params_schema, const char* params_schema,
dstalk_tool_handler_fn handler) { dstalk_tool_handler_fn handler) {
try {
if (!name || !handler) return -1; if (!name || !handler) return -1;
// 如果已存在同名工具,先注销 // 如果已存在同名工具,先注销
@@ -116,22 +174,46 @@ static int tools_register_tool(const char* name, const char* desc,
td.description = desc ? desc : ""; td.description = desc ? desc : "";
td.parameters_schema = params_schema ? params_schema : ""; td.parameters_schema = params_schema ? params_schema : "";
td.handler = handler; td.handler = handler;
std::lock_guard<std::mutex> lock(g_tools_mutex);
g_tools.push_back(std::move(td)); g_tools.push_back(std::move(td));
return 0; return 0;
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_register_tool: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_register_tool: unknown exception");
return -1;
}
} }
static void tools_unregister_tool(const char* name) { static void tools_unregister_tool(const char* name) {
try {
if (!name) return; if (!name) return;
std::string n(name); std::string n(name);
std::lock_guard<std::mutex> lock(g_tools_mutex);
g_tools.erase( g_tools.erase(
std::remove_if(g_tools.begin(), g_tools.end(), std::remove_if(g_tools.begin(), g_tools.end(),
[&n](const ToolDef& t) { return t.name == n; }), [&n](const ToolDef& t) { return t.name == n; }),
g_tools.end()); g_tools.end());
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_unregister_tool: %s", e.what());
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_unregister_tool: unknown exception");
}
} }
static char* tools_get_tools_json() { static char* tools_get_tools_json() {
try {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
json::array tools_arr; json::array tools_arr;
{
std::lock_guard<std::mutex> lock(g_tools_mutex);
for (const auto& t : g_tools) { for (const auto& t : g_tools) {
json::object tool_obj; json::object tool_obj;
tool_obj["type"] = "function"; tool_obj["type"] = "function";
@@ -152,40 +234,59 @@ static char* tools_get_tools_json() {
tool_obj["function"] = func_obj; tool_obj["function"] = func_obj;
tools_arr.push_back(tool_obj); tools_arr.push_back(tool_obj);
} }
}
std::string result = json::serialize(tools_arr); std::string result = json::serialize(tools_arr);
return g_host->strdup(result.c_str()); return host ? host->strdup(result.c_str()) : nullptr;
} catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_get_tools_json: %s", e.what());
return nullptr;
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_get_tools_json: unknown exception");
return nullptr;
}
} }
static char* tools_execute(const char* name, const char* args_json) { static char* tools_execute(const char* name, const char* args_json) {
try {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (!name) { if (!name) {
return g_host->strdup("{\"error\":\"tool name is null\"}"); return host ? host->strdup("{\"error\":\"tool name is null\"}") : nullptr;
} }
std::string n(name); std::string n(name);
ToolDef* found = nullptr; ToolDef* found = nullptr;
{
std::lock_guard<std::mutex> lock(g_tools_mutex);
for (auto& t : g_tools) { for (auto& t : g_tools) {
if (t.name == n) { if (t.name == n) {
found = &t; found = &t;
break; break;
} }
} }
}
if (!found) { if (!found) {
json::object err_obj; json::object err_obj;
err_obj["error"] = "unknown tool: " + n; err_obj["error"] = "unknown tool: " + n;
return g_host->strdup(json::serialize(err_obj).c_str()); return host ? host->strdup(json::serialize(err_obj).c_str()) : nullptr;
} }
try {
const char* args = args_json ? args_json : "{}"; const char* args = args_json ? args_json : "{}";
return found->handler(args); return found->handler(args);
} catch (const std::exception& e) { } catch (const std::exception& e) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_execute: %s", e.what());
json::object err_obj; json::object err_obj;
err_obj["error"] = std::string("tool execution failed: ") + e.what(); err_obj["error"] = "tool execution internal error";
return g_host->strdup(json::serialize(err_obj).c_str()); return host ? host->strdup(json::serialize(err_obj).c_str()) : nullptr;
} catch (...) { } catch (...) {
return g_host->strdup("{\"error\":\"tool execution failed: unknown error\"}"); const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "tools_execute: unknown exception");
return host ? host->strdup("{\"error\":\"tool execution internal error\"}") : nullptr;
} }
} }
@@ -201,7 +302,8 @@ static dstalk_tools_service_t g_tools_service = {
// ============================================================ // ============================================================
static int on_init(const dstalk_host_api_t* host) { static int on_init(const dstalk_host_api_t* host) {
g_host = host; try {
g_host.store(host, std::memory_order_release);
// 查询依赖服务: file_io // 查询依赖服务: file_io
void* raw = host->query_service("file_io", 1); void* raw = host->query_service("file_io", 1);
@@ -209,7 +311,7 @@ static int on_init(const dstalk_host_api_t* host) {
host->log(DSTALK_LOG_ERROR, "[plugin-tools] required service 'file_io' not found"); host->log(DSTALK_LOG_ERROR, "[plugin-tools] required service 'file_io' not found");
return -1; return -1;
} }
g_file_io = static_cast<const dstalk_file_io_service_t*>(raw); g_file_io.store(static_cast<const dstalk_file_io_service_t*>(raw), std::memory_order_release);
// 向自身注册内置工具 // 向自身注册内置工具
tools_register_tool( tools_register_tool(
@@ -227,12 +329,30 @@ static int on_init(const dstalk_host_api_t* host) {
); );
return host->register_service("tools", 1, &g_tools_service); return host->register_service("tools", 1, &g_tools_service);
} catch (const std::exception& e) {
const dstalk_host_api_t* h = g_host.load(std::memory_order_acquire);
if (h) h->log(DSTALK_LOG_ERROR, "on_init[tools]: %s", e.what());
return -1;
} catch (...) {
const dstalk_host_api_t* h = g_host.load(std::memory_order_acquire);
if (h) h->log(DSTALK_LOG_ERROR, "on_init[tools]: unknown exception");
return -1;
}
} }
static void on_shutdown() { static void on_shutdown() {
try {
std::lock_guard<std::mutex> lock(g_tools_mutex);
g_tools.clear(); g_tools.clear();
g_file_io = nullptr; } catch (const std::exception& e) {
g_host = nullptr; const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "on_shutdown[tools]: %s", e.what());
} catch (...) {
const dstalk_host_api_t* host = g_host.load(std::memory_order_acquire);
if (host) host->log(DSTALK_LOG_ERROR, "on_shutdown[tools]: unknown exception");
}
g_file_io.store(nullptr, std::memory_order_release);
g_host.store(nullptr, std::memory_order_release);
} }
static dstalk_plugin_info_t g_info = { static dstalk_plugin_info_t g_info = {