// VDE 进程外服务模板(C++17)—— `echo` 示例服务。 // // 用途:复制本目录作为自定义进程外服务的起点;保留 CLI/退出码/响应封装, // 把 `echo` 处理逻辑替换为真实算法即可。 // // 契约(与 docs/design/vde-service-protocol.md 一致): // argv: --request --response // request.protocol 必须为 "vde-service/0.1" // request.request_id 必填非空字符串,响应原样回显 // request.operation 固定 "echo" // request.input 可选输入文件路径(按二进制读取) // request.output 必填输出文件路径,必须位于 request.json 所在目录内 // request.args.message 可选,无 input 时写入输出的文本 // request.args.sleep_ms 可选测试钩子(0..300000),用于验证宿主超时终止 // response.outputs[].path 返回相对于 request.json 目录的文件名(不是绝对路径), // 使直接进程模式与容器模式(/vde/work 挂载)都能通过宿主 // outputs 白名单校验。 // // 退出码:0 成功;2 用法错误;3 协议/校验错误;5 输入输出失败。 // // 约束:不依赖 VDE 库;不依赖 (模板需在 MinGW/GCC 8.1 等旧工具链 // 上可独立编译)。生产实现可换正式 JSON 库,但 CLI/响应字段必须保持不变。 #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr int kExitOk = 0; constexpr int kExitUsage = 2; constexpr int kExitProtocol = 3; constexpr int kExitServiceFailed = 5; constexpr const char* kProtocol = "vde-service/0.1"; constexpr const char* kServiceId = "com.vde.template.echo.cpp"; constexpr const char* kOperation = "echo"; constexpr const char* kDefaultMessage = "hello from vde-service template"; constexpr std::size_t kMaxRequestBytes = 16u * 1024u * 1024u; constexpr std::size_t kMaxJsonDepth = 64; constexpr double kMaxSleepMs = 300000.0; // ── 极简 JSON 解析(模板自包含,仅覆盖协议所需子集)────────────────────── struct JsonValue { enum class Kind { Null, Boolean, Number, String, Array, Object }; Kind kind = Kind::Null; bool boolean = false; double number = 0.0; std::string text; std::vector array; std::vector> object; bool is_null() const { return kind == Kind::Null; } bool is_boolean() const { return kind == Kind::Boolean; } bool is_number() const { return kind == Kind::Number; } bool is_string() const { return kind == Kind::String; } bool is_array() const { return kind == Kind::Array; } bool is_object() const { return kind == Kind::Object; } const JsonValue* find(const std::string& key) const { if (kind != Kind::Object) return nullptr; for (const auto& entry : object) { if (entry.first == key) return &entry.second; } return nullptr; } }; void append_utf8(std::string* out, std::uint32_t code_point) { if (code_point <= 0x7Fu) { out->push_back(static_cast(code_point)); } else if (code_point <= 0x7FFu) { out->push_back(static_cast(0xC0u | (code_point >> 6))); out->push_back(static_cast(0x80u | (code_point & 0x3Fu))); } else if (code_point <= 0xFFFFu) { out->push_back(static_cast(0xE0u | (code_point >> 12))); out->push_back(static_cast(0x80u | ((code_point >> 6) & 0x3Fu))); out->push_back(static_cast(0x80u | (code_point & 0x3Fu))); } else { out->push_back(static_cast(0xF0u | (code_point >> 18))); out->push_back(static_cast(0x80u | ((code_point >> 12) & 0x3Fu))); out->push_back(static_cast(0x80u | ((code_point >> 6) & 0x3Fu))); out->push_back(static_cast(0x80u | (code_point & 0x3Fu))); } } class JsonParser { public: explicit JsonParser(const std::string& text) : text_(text) {} bool parse(JsonValue* out, std::string* error) { // Windows 工具常写 UTF-8 BOM;按 RFC 8259 不要求接受,但模板做兼容。 if (text_.size() >= 3 && static_cast(text_[0]) == 0xEF && static_cast(text_[1]) == 0xBB && static_cast(text_[2]) == 0xBF) { pos_ = 3; } skip_whitespace(); if (!parse_value(out, 0, error)) return false; skip_whitespace(); if (pos_ != text_.size()) { set_error("trailing characters after JSON value", error); return false; } return true; } private: bool set_error(const std::string& message, std::string* error) { if (error != nullptr) { *error = message + " at offset " + std::to_string(pos_); } return false; } void skip_whitespace() { while (pos_ < text_.size()) { const char c = text_[pos_]; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { ++pos_; } else { break; } } } bool consume(char expected) { if (pos_ >= text_.size() || text_[pos_] != expected) return false; ++pos_; return true; } bool parse_value(JsonValue* out, std::size_t depth, std::string* error) { if (depth > kMaxJsonDepth) return set_error("JSON nesting too deep", error); if (pos_ >= text_.size()) return set_error("unexpected end of JSON", error); const char c = text_[pos_]; switch (c) { case '{': return parse_object(out, depth, error); case '[': return parse_array(out, depth, error); case '"': { out->kind = JsonValue::Kind::String; return parse_string(&out->text, error); } case 't': if (text_.compare(pos_, 4, "true") != 0) { return set_error("invalid literal (expected true)", error); } pos_ += 4; out->kind = JsonValue::Kind::Boolean; out->boolean = true; return true; case 'f': if (text_.compare(pos_, 5, "false") != 0) { return set_error("invalid literal (expected false)", error); } pos_ += 5; out->kind = JsonValue::Kind::Boolean; out->boolean = false; return true; case 'n': if (text_.compare(pos_, 4, "null") != 0) { return set_error("invalid literal (expected null)", error); } pos_ += 4; out->kind = JsonValue::Kind::Null; return true; default: if (c == '-' || (c >= '0' && c <= '9')) return parse_number(out, error); return set_error(std::string("unexpected character '") + c + "'", error); } return false; } bool parse_object(JsonValue* out, std::size_t depth, std::string* error) { out->kind = JsonValue::Kind::Object; ++pos_; // '{' skip_whitespace(); if (consume('}')) return true; for (;;) { skip_whitespace(); if (pos_ >= text_.size() || text_[pos_] != '"') { return set_error("object key must be a string", error); } std::string key; if (!parse_string(&key, error)) return false; skip_whitespace(); if (!consume(':')) return set_error("expected ':' after object key", error); skip_whitespace(); JsonValue value; if (!parse_value(&value, depth + 1, error)) return false; out->object.emplace_back(std::move(key), std::move(value)); skip_whitespace(); if (consume('}')) return true; if (!consume(',')) return set_error("expected ',' or '}' in object", error); } } bool parse_array(JsonValue* out, std::size_t depth, std::string* error) { out->kind = JsonValue::Kind::Array; ++pos_; // '[' skip_whitespace(); if (consume(']')) return true; for (;;) { JsonValue value; if (!parse_value(&value, depth + 1, error)) return false; out->array.push_back(std::move(value)); skip_whitespace(); if (consume(']')) return true; if (!consume(',')) return set_error("expected ',' or ']' in array", error); skip_whitespace(); } } bool parse_string(std::string* out, std::string* error) { ++pos_; // opening quote out->clear(); while (pos_ < text_.size()) { const unsigned char c = static_cast(text_[pos_]); if (c == '"') { ++pos_; return true; } if (c < 0x20u) return set_error("control character in JSON string", error); if (c != '\\') { out->push_back(static_cast(c)); ++pos_; continue; } ++pos_; if (pos_ >= text_.size()) return set_error("unterminated escape", error); const char escaped = text_[pos_++]; switch (escaped) { case '"': out->push_back('"'); break; case '\\': out->push_back('\\'); break; case '/': out->push_back('/'); break; case 'b': out->push_back('\b'); break; case 'f': out->push_back('\f'); break; case 'n': out->push_back('\n'); break; case 'r': out->push_back('\r'); break; case 't': out->push_back('\t'); break; case 'u': { std::uint32_t code_point = 0; if (!parse_hex4(&code_point, error)) return false; if (code_point >= 0xD800u && code_point <= 0xDBFFu) { if (pos_ + 1 >= text_.size() || text_[pos_] != '\\' || text_[pos_ + 1] != 'u') { return set_error("high surrogate without low surrogate", error); } pos_ += 2; std::uint32_t low = 0; if (!parse_hex4(&low, error)) return false; if (low < 0xDC00u || low > 0xDFFFu) { return set_error("invalid low surrogate", error); } code_point = 0x10000u + ((code_point - 0xD800u) << 10) + (low - 0xDC00u); } append_utf8(out, code_point); break; } default: return set_error("invalid escape sequence", error); } } return set_error("unterminated JSON string", error); } bool parse_hex4(std::uint32_t* out, std::string* error) { if (pos_ + 4 > text_.size()) return set_error("truncated \\u escape", error); std::uint32_t value = 0; for (int i = 0; i < 4; ++i) { const char c = text_[pos_++]; value <<= 4; if (c >= '0' && c <= '9') { value |= static_cast(c - '0'); } else if (c >= 'a' && c <= 'f') { value |= static_cast(c - 'a' + 10); } else if (c >= 'A' && c <= 'F') { value |= static_cast(c - 'A' + 10); } else { return set_error("invalid hex digit in \\u escape", error); } } *out = value; return true; } bool parse_number(JsonValue* out, std::string* error) { const std::size_t begin = pos_; if (text_[pos_] == '-') ++pos_; if (pos_ >= text_.size() || !std::isdigit(static_cast(text_[pos_]))) { return set_error("invalid JSON number", error); } if (text_[pos_] == '0') { ++pos_; } else { while (pos_ < text_.size() && std::isdigit(static_cast(text_[pos_]))) { ++pos_; } } if (pos_ < text_.size() && text_[pos_] == '.') { ++pos_; if (pos_ >= text_.size() || !std::isdigit(static_cast(text_[pos_]))) { return set_error("invalid JSON number fraction", error); } while (pos_ < text_.size() && std::isdigit(static_cast(text_[pos_]))) { ++pos_; } } if (pos_ < text_.size() && (text_[pos_] == 'e' || text_[pos_] == 'E')) { ++pos_; if (pos_ < text_.size() && (text_[pos_] == '+' || text_[pos_] == '-')) ++pos_; if (pos_ >= text_.size() || !std::isdigit(static_cast(text_[pos_]))) { return set_error("invalid JSON number exponent", error); } while (pos_ < text_.size() && std::isdigit(static_cast(text_[pos_]))) { ++pos_; } } const std::string literal = text_.substr(begin, pos_ - begin); char* end = nullptr; const double value = std::strtod(literal.c_str(), &end); if (end == nullptr || *end != '\0' || !std::isfinite(value)) { return set_error("JSON number out of range", error); } out->kind = JsonValue::Kind::Number; out->number = value; return true; } const std::string& text_; std::size_t pos_ = 0; }; // ── 文件与路径辅助 ───────────────────────────────────────────────────── bool read_file(const std::string& path, std::string* out) { if (out == nullptr) return false; out->clear(); std::ifstream in(path, std::ios::binary); if (!in.good()) return false; in.seekg(0, std::ios::end); const std::streamoff size = in.tellg(); if (size < 0 || static_cast(size) > kMaxRequestBytes) return false; in.seekg(0, std::ios::beg); out->resize(static_cast(size)); if (size > 0) in.read(&(*out)[0], size); return in.good() || in.eof(); } bool write_file(const std::string& path, const std::string& content) { std::ofstream out(path, std::ios::binary | std::ios::trunc); if (!out.good()) return false; if (!content.empty()) { out.write(content.data(), static_cast(content.size())); } out.close(); return out.good(); } std::string normalize_path(const std::string& raw) { std::string out; out.reserve(raw.size()); for (char c : raw) { if (c == '\\') c = '/'; if (c == '/' && !out.empty() && out.back() == '/') continue; out.push_back(c); } while (out.size() > 1 && out.back() == '/') out.pop_back(); return out; } std::string parent_dir(const std::string& path) { const std::string normalized = normalize_path(path); const std::size_t pos = normalized.find_last_of('/'); if (pos == std::string::npos) return "."; if (pos == 0) return "/"; return normalized.substr(0, pos); } std::string file_name(const std::string& path) { const std::string normalized = normalize_path(path); const std::size_t pos = normalized.find_last_of('/'); return pos == std::string::npos ? normalized : normalized.substr(pos + 1); } bool is_absolute_path(const std::string& path) { if (path.empty()) return false; if (path[0] == '/') return true; return path.size() >= 3 && std::isalpha(static_cast(path[0])) && path[1] == ':' && (path[2] == '/' || path[2] == '\\'); } bool has_parent_segment(const std::string& path) { std::size_t begin = 0; while (begin <= path.size()) { const std::size_t end = path.find('/', begin); const std::string segment = path.substr(begin, end == std::string::npos ? std::string::npos : end - begin); if (segment == "..") return true; if (end == std::string::npos) break; begin = end + 1; } return false; } bool path_within_dir(const std::string& dir, const std::string& path) { const std::string base = normalize_path(dir); const std::string target = normalize_path(path); if (base.empty() || target.empty()) return false; if (target == base) return false; if (target.size() <= base.size() + 1) return false; if (target.compare(0, base.size(), base) != 0) return false; if (target[base.size()] != '/') return false; return !has_parent_segment(target.substr(base.size() + 1)); } std::string join_path(const std::string& dir, const std::string& relative) { if (dir.empty()) return relative; if (dir.back() == '/' || dir.back() == '\\') return dir + relative; return dir + "/" + relative; } // ── 响应构造 ─────────────────────────────────────────────────────────── std::string json_escape(const std::string& text) { std::string out; out.reserve(text.size() + 8); for (char raw : text) { const unsigned char c = static_cast(raw); switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\b': out += "\\b"; break; case '\f': out += "\\f"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (c < 0x20u) { char buffer[8]; std::snprintf(buffer, sizeof(buffer), "\\u%04x", static_cast(c)); out += buffer; } else { out.push_back(static_cast(c)); } break; } } return out; } std::string error_response(const std::string& request_id, const std::string& code, const std::string& message) { std::string response = "{\"protocol\":\""; response += kProtocol; response += "\",\"request_id\":\""; response += json_escape(request_id); response += "\",\"status\":\"error\",\"service_id\":\""; response += kServiceId; response += "\",\"code\":\""; response += json_escape(code); response += "\",\"message\":\""; response += json_escape(message); response += "\"}"; return response; } std::string ok_response(const std::string& request_id, const std::string& output_name, std::size_t bytes_in, std::size_t bytes_out) { std::string response = "{\"protocol\":\""; response += kProtocol; response += "\",\"request_id\":\""; response += json_escape(request_id); response += "\",\"status\":\"ok\",\"service_id\":\""; response += kServiceId; response += "\",\"outputs\":[{\"path\":\""; response += json_escape(output_name); response += "\",\"format\":\"text\",\"role\":\"result\"}],\"metrics\":{\"bytes_in\":"; response += std::to_string(bytes_in); response += ",\"bytes_out\":"; response += std::to_string(bytes_out); response += "},\"diagnostics\":[\"template echo service: replace 'echo' with real processing\"]}"; return response; } int finish(const std::string& response_path, const std::string& response, int exit_code, bool to_stderr) { if (!response_path.empty() && !write_file(response_path, response)) { std::fprintf(stderr, "[vde-template] error: cannot write response '%s'\n", response_path.c_str()); return kExitProtocol; } if (to_stderr) { std::fprintf(stderr, "[vde-template] %s\n", response.c_str()); } else { std::printf("%s\n", response.c_str()); } return exit_code; } void print_usage() { std::printf( "vde_service_echo (VDE external service template, C++17)\n" "Usage: vde_service_echo --request --response \n" "Exit codes: 0 ok, 2 usage, 3 protocol/validation error, 5 I/O failure.\n"); } } // 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]; const auto next = [&](const char* name) -> std::string { if (i + 1 >= argc) { std::fprintf(stderr, "[vde-template] error: %s needs a value\n", name); std::exit(kExitUsage); } return argv[++i]; }; if (arg == "--request") { request_path = next("--request"); } else if (arg == "--response") { response_path = next("--response"); } else if (arg == "--help" || arg == "-h") { print_usage(); return kExitOk; } else { std::fprintf(stderr, "[vde-template] error: unknown option '%s'\n", arg.c_str()); print_usage(); return kExitUsage; } } if (request_path.empty() || response_path.empty()) { print_usage(); return kExitUsage; } std::string request_text; if (!read_file(request_path, &request_text)) { return finish(response_path, error_response("", "invalid_request", "cannot read request file"), kExitProtocol, true); } JsonValue request; std::string parse_error; if (!JsonParser(request_text).parse(&request, &parse_error) || !request.is_object()) { return finish(response_path, error_response("", "invalid_request", parse_error.empty() ? "request must be a JSON object" : parse_error), kExitProtocol, true); } const JsonValue* request_id_value = request.find("request_id"); const std::string request_id = request_id_value != nullptr && request_id_value->is_string() ? request_id_value->text : std::string(); if (request_id.empty()) { return finish(response_path, error_response("", "invalid_request", "request needs non-empty string 'request_id'"), kExitProtocol, true); } const JsonValue* protocol_value = request.find("protocol"); if (protocol_value == nullptr || !protocol_value->is_string() || protocol_value->text != kProtocol) { return finish(response_path, error_response(request_id, "bad_protocol", std::string("request.protocol must be '") + kProtocol + "'"), kExitProtocol, true); } const JsonValue* operation_value = request.find("operation"); if (operation_value == nullptr || !operation_value->is_string() || operation_value->text.empty()) { return finish(response_path, error_response(request_id, "invalid_request", "request needs non-empty string 'operation'"), kExitProtocol, true); } if (operation_value->text != kOperation) { return finish(response_path, error_response(request_id, "unsupported_operation", std::string("only '") + kOperation + "' is supported, got '" + operation_value->text + "'"), kExitProtocol, true); } const JsonValue* output_value = request.find("output"); if (output_value == nullptr || !output_value->is_string() || output_value->text.empty()) { return finish(response_path, error_response(request_id, "invalid_request", "request needs non-empty string 'output'"), kExitProtocol, true); } std::string message = kDefaultMessage; double sleep_ms = 0.0; const JsonValue* args_value = request.find("args"); if (args_value != nullptr) { if (!args_value->is_object()) { return finish(response_path, error_response(request_id, "invalid_request", "request.args must be a JSON object"), kExitProtocol, true); } const JsonValue* message_value = args_value->find("message"); if (message_value != nullptr) { if (!message_value->is_string()) { return finish(response_path, error_response(request_id, "invalid_request", "request.args.message must be a string"), kExitProtocol, true); } message = message_value->text; } const JsonValue* sleep_value = args_value->find("sleep_ms"); if (sleep_value != nullptr) { if (!sleep_value->is_number()) { return finish(response_path, error_response(request_id, "invalid_request", "request.args.sleep_ms must be a number"), kExitProtocol, true); } sleep_ms = sleep_value->number; } } if (sleep_ms > 0.0) { if (sleep_ms > kMaxSleepMs) sleep_ms = kMaxSleepMs; std::this_thread::sleep_for( std::chrono::milliseconds(static_cast(sleep_ms))); } const std::string request_dir = parent_dir(request_path); const std::string raw_output = normalize_path(output_value->text); if (has_parent_segment(raw_output)) { return finish(response_path, error_response(request_id, "invalid_output_path", "output path must not contain '..'"), kExitProtocol, true); } const std::string output_path = is_absolute_path(raw_output) ? raw_output : join_path(request_dir, raw_output); if (!path_within_dir(request_dir, output_path)) { return finish(response_path, error_response(request_id, "invalid_output_path", "output path must stay inside the request directory"), kExitProtocol, true); } const std::string output_name = file_name(output_path); if (output_name.empty() || output_name == "." || output_name == "..") { return finish(response_path, error_response(request_id, "invalid_output_path", "output path needs a file name"), kExitProtocol, true); } std::string content = message; std::size_t bytes_in = 0; const JsonValue* input_value = request.find("input"); if (input_value != nullptr && !input_value->is_null()) { if (!input_value->is_string()) { return finish(response_path, error_response(request_id, "invalid_request", "request.input must be a string path"), kExitProtocol, true); } if (!input_value->text.empty()) { const std::string raw_input = normalize_path(input_value->text); const std::string input_path = is_absolute_path(raw_input) ? raw_input : join_path(request_dir, raw_input); if (!read_file(input_path, &content)) { return finish(response_path, error_response(request_id, "input_not_found", "cannot read input file '" + input_path + "'"), kExitServiceFailed, true); } bytes_in = content.size(); } } if (!write_file(output_path, content)) { return finish(response_path, error_response(request_id, "output_failed", "cannot write output file '" + output_path + "'"), kExitServiceFailed, true); } return finish(response_path, ok_response(request_id, output_name, bytes_in, content.size()), kExitOk, false); }