// tests/plugin/external/test_service_helper.cpp // 进程外服务协议测试用「可控服务」。 // 通过环境变量 VDE_TEST_SERVICE_MODE 选择行为(宿主经清单 sandbox.env_allow 透传): // ok(默认)/ crash / badjson / status_error / spam / env_echo / noresponse // memory_hog(分配大内存直到失败)/ cpu_hog(长时间占用 CPU) // spawn_child(尝试派生子进程)/ leave_child(派生长寿子进程后退出,测 kill_on_close) // 内部 child 模式:--child-ok(立即退出)/ --leave-child (写 pid 后 sleep) // 仅用于测试:不链接 VDE 库;协议契约见 docs/design/vde-service-protocol.md。 #include "service_common.h" #include #include #include #include #include #include #include #include #if defined(_WIN32) #include #else #include #include #include #include #include #endif using namespace vde_service; namespace { bool file_exists(const std::string& path) { std::ifstream in(path, std::ios::binary); return in.good(); } std::string env_or_empty(const char* name) { const char* value = std::getenv(name); return value ? std::string(value) : std::string(); } std::string protocol_prefix() { std::string prefix = "{\"protocol\":\""; prefix += protocol_name(); prefix += "/"; prefix += protocol_version(); prefix += "\",\"request_id\":\""; return prefix; } std::string make_response(const std::string& request_id, const std::string& status) { std::string response = protocol_prefix(); response += escape(request_id); response += "\",\"status\":\""; response += status; response += "\",\"outputs\":[]}"; return response; } std::string make_error_response(const std::string& request_id, const std::string& code, const std::string& message) { std::string response = protocol_prefix(); response += escape(request_id); response += "\",\"status\":\"error\",\"code\":\""; response += escape(code); response += "\",\"message\":\""; response += escape(message); response += "\"}"; return response; } std::string make_ok_metrics_response(const std::string& request_id, const std::string& metrics) { std::string response = protocol_prefix(); response += escape(request_id); response += "\",\"status\":\"ok\",\"outputs\":[],\"metrics\":"; response += metrics; response += "}"; return response; } std::string make_env_response(const std::string& request_id) { const std::string secret = env_or_empty("VDE_SECRET_TOKEN").empty() ? "absent" : "present"; const std::string allowed = env_or_empty("VDE_ALLOWED_TEST_VAR").empty() ? "absent" : "present"; return make_ok_metrics_response(request_id, "{\"secret\":\"" + secret + "\",\"allowed\":\"" + allowed + "\"}"); } bool write_pid_file(const std::string& path, long long pid) { return write_file(path, std::to_string(pid) + "\n"); } long long current_pid() { #if defined(_WIN32) return static_cast(GetCurrentProcessId()); #else return static_cast(getpid()); #endif } int run_child_ok() { return 0; } int run_leave_child(const std::string& pid_file) { if (pid_file.empty()) return 2; if (!write_pid_file(pid_file, current_pid())) return 3; std::this_thread::sleep_for(std::chrono::seconds(60)); return 0; } bool spawn_helper(const std::string& helper_exe, const std::string& extra_args) { #if defined(_WIN32) std::string command = "\"" + helper_exe + "\" " + extra_args; STARTUPINFOA startup{}; startup.cb = sizeof(startup); PROCESS_INFORMATION process{}; std::vector command_line(command.begin(), command.end()); command_line.push_back('\0'); const BOOL created = CreateProcessA(nullptr, command_line.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process); if (!created) return false; WaitForSingleObject(process.hProcess, 10000); CloseHandle(process.hThread); CloseHandle(process.hProcess); return true; #else const pid_t pid = fork(); if (pid < 0) return false; if (pid == 0) { execl(helper_exe.c_str(), helper_exe.c_str(), extra_args.empty() ? nullptr : extra_args.c_str(), static_cast(nullptr)); _exit(127); } int status = 0; waitpid(pid, &status, 0); return true; #endif } bool spawn_leave_child(const std::string& helper_exe, const std::string& pid_file) { #if defined(_WIN32) // 非阻塞:不等待长寿子进程(否则服务自身会挂到超时) const std::string command = "\"" + helper_exe + "\" --leave-child \"" + pid_file + "\""; STARTUPINFOA startup{}; startup.cb = sizeof(startup); PROCESS_INFORMATION process{}; std::vector command_line(command.begin(), command.end()); command_line.push_back('\0'); const BOOL created = CreateProcessA(nullptr, command_line.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process); if (!created) return false; CloseHandle(process.hThread); CloseHandle(process.hProcess); return true; #else const std::string args = "--leave-child \"" + pid_file + "\""; const pid_t pid = fork(); if (pid < 0) return false; if (pid == 0) { execl(helper_exe.c_str(), helper_exe.c_str(), "--leave-child", pid_file.c_str(), static_cast(nullptr)); _exit(127); } // 父进程不 wait:子进程独立运行,等待 pid 文件出现由调用方轮询 return true; #endif } int memory_hog(const std::string& request_id, const std::string& response_path) { const std::size_t chunk_bytes = 16u * 1024u * 1024u; const std::size_t max_chunks = 32; // 最多 512 MB std::vector> chunks; try { for (std::size_t i = 0; i < max_chunks; ++i) { chunks.emplace_back(chunk_bytes, static_cast(i)); for (std::size_t j = 0; j < chunk_bytes; j += 4096) chunks.back()[j] = 1; } } catch (const std::exception&) { write_file(response_path, make_error_response(request_id, "oom", "allocation failed under memory limit")); return 3; } catch (...) { write_file(response_path, make_error_response(request_id, "oom", "allocation failed")); return 3; } write_file(response_path, make_ok_metrics_response(request_id, "{\"allocated_mb\":" + std::to_string(chunks.size() * 16) + "}")); return 0; } int cpu_hog(const std::string& request_id, const std::string& response_path) { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); volatile unsigned long long counter = 0; while (std::chrono::steady_clock::now() < deadline) { for (int i = 0; i < 100000; ++i) counter += static_cast(i); } write_file(response_path, make_ok_metrics_response(request_id, "{\"cpu_spin\":1}")); return 0; } int spawn_child_mode(const std::string& request_id, const std::string& response_path, const std::string& helper_exe) { if (helper_exe.empty()) { write_file(response_path, make_error_response(request_id, "spawn_blocked", "helper_exe missing in request")); return 3; } const bool spawned = spawn_helper(helper_exe, "--child-ok"); if (!spawned) { write_file(response_path, make_error_response(request_id, "spawn_blocked", "child process creation was blocked")); return 3; } write_file(response_path, make_ok_metrics_response(request_id, "{\"child\":\"ok\"}")); return 0; } int leave_child_mode(const std::string& request_id, const std::string& response_path, const std::string& helper_exe, const std::string& pid_file) { if (helper_exe.empty() || pid_file.empty()) { write_file(response_path, make_error_response(request_id, "spawn_blocked", "helper_exe/pid_file missing in request")); return 3; } if (!spawn_leave_child(helper_exe, pid_file)) { write_file(response_path, make_error_response(request_id, "spawn_blocked", "grandchild creation was blocked")); return 3; } for (int i = 0; i < 200; ++i) { if (file_exists(pid_file)) break; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } write_file(response_path, make_ok_metrics_response(request_id, "{\"child\":\"left\"}")); return 0; } } // namespace int main(int argc, char** argv) { std::string request_path; std::string response_path; for (int i = 1; i < argc; ++i) { const std::string arg = argv[i]; if (arg == "--request" && i + 1 < argc) request_path = argv[++i]; else if (arg == "--response" && i + 1 < argc) response_path = argv[++i]; else if (arg == "--child-ok") return run_child_ok(); else if (arg == "--leave-child" && i + 1 < argc) return run_leave_child(argv[++i]); } if (request_path.empty() || response_path.empty()) { std::fprintf(stderr, "[test-service] usage: --request --response \n"); return 2; } std::string request; if (!read_file(request_path, &request)) { std::fprintf(stderr, "[test-service] cannot read request\n"); return 3; } const std::string request_id = find_string(request, "request_id"); const std::string helper_exe = find_string(request, "helper_exe"); const std::string pid_file = find_string(request, "pid_file"); const std::string mode = env_or_empty("VDE_TEST_SERVICE_MODE"); if (mode == "crash") { std::fprintf(stderr, "[test-service] simulated crash\n"); return 7; } if (mode == "badjson") { write_file(response_path, "{ this is not valid json"); return 0; } if (mode == "noresponse") { return 0; } if (mode == "status_error") { write_file(response_path, make_error_response(request_id, "unsupported_operation", "simulated protocol error")); return 3; } if (mode == "spam") { std::string blob(600000, 'X'); std::fwrite(blob.data(), 1, blob.size(), stdout); std::fwrite(blob.data(), 1, blob.size(), stderr); std::fflush(stdout); std::fflush(stderr); write_file(response_path, make_response(request_id, "ok")); return 0; } if (mode == "env_echo") { write_file(response_path, make_env_response(request_id)); return 0; } if (mode == "write_probe") { // 尝试在当前工作目录新建文件:filesystem=read_only 策略应阻止 const char* probe_name = "sandbox_write_probe.txt"; bool blocked = false; { std::ofstream probe(probe_name, std::ios::binary | std::ios::trunc); if (!probe) { blocked = true; } else { probe << "probe\n"; } } write_file(response_path, make_ok_metrics_response(request_id, std::string("{\"write_blocked\":\"") + (blocked ? "yes" : "no") + "\"}")); return 0; } if (mode == "memory_hog") return memory_hog(request_id, response_path); if (mode == "cpu_hog") return cpu_hog(request_id, response_path); if (mode == "spawn_child") return spawn_child_mode(request_id, response_path, helper_exe); if (mode == "leave_child") return leave_child_mode(request_id, response_path, helper_exe, pid_file); write_file(response_path, make_response(request_id, "ok")); return 0; }