#include "grpc_cpp_client.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct xburner_grpc_client { std::shared_ptr channel; std::shared_ptr certificate_provider; }; static void write_error(char *err_buf, size_t err_buf_len, const char *fmt, ...) { va_list ap; if (err_buf == nullptr || err_buf_len == 0) return; va_start(ap, fmt); (void)vsnprintf(err_buf, err_buf_len, fmt, ap); va_end(ap); } static std::string slice_to_string(const uint8_t *ptr, uint32_t len) { if (ptr == nullptr || len == 0) return {}; return std::string(reinterpret_cast(ptr), len); } static std::string read_file(const char *path, char *err_buf, size_t err_buf_len) { std::ifstream file(path, std::ios::binary); if (!file) { write_error(err_buf, err_buf_len, "failed to open CA file `%s`", path); return {}; } return std::string(std::istreambuf_iterator(file), std::istreambuf_iterator()); } static std::shared_ptr build_credentials(const xburner_grpc_client_config_t *config, std::shared_ptr *out_provider, char *err_buf, size_t err_buf_len) { if (config->use_tls == 0) return grpc::InsecureChannelCredentials(); if (config->insecure_skip_verify == 0 && config->ca_file == nullptr) { return grpc::SslCredentials(grpc::SslCredentialsOptions{}); } grpc::experimental::TlsChannelCredentialsOptions options; if (config->insecure_skip_verify != 0) { options.set_verify_server_certs(false); } if (config->ca_file != nullptr) { const std::string root_certs = read_file(config->ca_file, err_buf, err_buf_len); if (root_certs.empty()) return nullptr; auto provider = std::make_shared( root_certs); options.set_certificate_provider(provider); options.watch_root_certs(); *out_provider = provider; } return grpc::experimental::TlsCredentials(options); } static std::string lower_copy(std::string value) { std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) { return static_cast(std::tolower(ch)); }); return value; } static bool contains_any(const std::string &haystack, std::initializer_list needles) { for (const char *needle : needles) { if (haystack.find(needle) != std::string::npos) return true; } return false; } static uint16_t classify_transport_code(const std::string &diag) { const auto lower = lower_copy(diag); if (contains_any(lower, {"dns", "name resolution", "resolver"})) return 1; if (contains_any(lower, {"certificate", "peer name", "ssl", "tls"})) return 3; if (contains_any(lower, {"connection refused", "failed to connect", "connection attempt timed out", "connection reset"})) return 2; if (contains_any(lower, {"sendmsg", "broken pipe"})) return 4; if (contains_any(lower, {"recvmsg", "socket closed"})) return 5; return 0; } static uint16_t classify_timeout_phase(const std::string &diag) { const auto lower = lower_copy(diag); if (contains_any(lower, {"connect", "resolver", "connection attempt"})) { return 1; } return 2; } static int copy_byte_buffer(const grpc::ByteBuffer &buffer, uint32_t capture_body_max_bytes, const uint8_t **out_body_ptr, uint32_t *out_body_len, uint8_t *out_body_truncated, char *err_buf, size_t err_buf_len) { std::vector slices; grpc::Status dump_status = buffer.Dump(&slices); if (!dump_status.ok()) { write_error(err_buf, err_buf_len, "failed to dump response body: %s", dump_status.error_message().c_str()); return 1; } const size_t payload_len = buffer.Length(); const size_t capture_len = std::min(payload_len, static_cast(capture_body_max_bytes)); if (out_body_truncated != nullptr) { *out_body_truncated = payload_len > capture_len ? 1 : 0; } if (capture_len == 0) { if (out_body_ptr != nullptr) *out_body_ptr = nullptr; if (out_body_len != nullptr) *out_body_len = 0; return 0; } uint8_t *captured = static_cast(std::malloc(capture_len)); if (captured == nullptr) { write_error(err_buf, err_buf_len, "malloc failed for response body"); return 1; } size_t copied = 0; for (const grpc::Slice &slice : slices) { if (copied >= capture_len) break; const size_t to_copy = std::min(capture_len - copied, slice.size()); std::memcpy(captured + copied, slice.begin(), to_copy); copied += to_copy; } if (out_body_ptr != nullptr) *out_body_ptr = captured; if (out_body_len != nullptr) *out_body_len = static_cast(copied); return 0; } static std::string metadata_value(const std::multimap &metadata, const char *key) { const auto range = metadata.equal_range(key); if (range.first == range.second) return {}; return std::string(range.first->second.data(), range.first->second.length()); } extern "C" int xburner_grpc_client_create(const xburner_grpc_client_config_t *config, xburner_grpc_client_t **out_client, char *err_buf, size_t err_buf_len) { if (config == nullptr || config->authority == nullptr || out_client == nullptr) { write_error(err_buf, err_buf_len, "invalid grpc client config"); return 1; } auto *client = new (std::nothrow) xburner_grpc_client(); if (client == nullptr) { write_error(err_buf, err_buf_len, "failed to allocate grpc client"); return 1; } grpc::ChannelArguments args; if (config->server_name != nullptr) { args.SetSslTargetNameOverride(config->server_name); } auto credentials = build_credentials(config, &client->certificate_provider, err_buf, err_buf_len); if (!credentials) { delete client; return 1; } client->channel = grpc::CreateCustomChannel(config->authority, credentials, args); if (!client->channel) { write_error(err_buf, err_buf_len, "failed to create grpc channel"); delete client; return 1; } *out_client = client; return 0; } extern "C" void xburner_grpc_client_destroy(xburner_grpc_client_t *client) { delete client; } extern "C" int xburner_grpc_client_unary( xburner_grpc_client_t *client, const uint8_t *path_ptr, uint32_t path_len, const xburner_grpc_header_t *headers, uint32_t header_count, const uint8_t *body_ptr, uint32_t body_len, uint32_t timeout_ms, uint32_t connect_timeout_ms, uint32_t capture_body_max_bytes, xburner_grpc_unary_result_t *out_result, const uint8_t **out_body_ptr, uint32_t *out_body_len, const uint8_t **out_grpc_message_ptr, uint32_t *out_grpc_message_len, char *err_buf, size_t err_buf_len) { if (client == nullptr || client->channel == nullptr || path_ptr == nullptr || path_len == 0 || out_result == nullptr) { write_error(err_buf, err_buf_len, "invalid grpc unary call input"); return 1; } std::memset(out_result, 0, sizeof(*out_result)); if (out_body_ptr != nullptr) *out_body_ptr = nullptr; if (out_body_len != nullptr) *out_body_len = 0; if (out_grpc_message_ptr != nullptr) *out_grpc_message_ptr = nullptr; if (out_grpc_message_len != nullptr) *out_grpc_message_len = 0; const std::string method = std::string(reinterpret_cast(path_ptr), path_len); grpc::ClientContext context; for (uint32_t index = 0; index < header_count; index += 1) { context.AddMetadata( slice_to_string(headers[index].key_ptr, headers[index].key_len), slice_to_string(headers[index].value_ptr, headers[index].value_len)); } uint32_t deadline_budget_ms = timeout_ms != 0 ? timeout_ms : connect_timeout_ms; if (deadline_budget_ms != 0) { context.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(deadline_budget_ms)); } grpc::Slice request_slice = body_len == 0 ? grpc::Slice("", 0, grpc::Slice::STATIC_SLICE) : grpc::Slice(body_ptr, body_len); grpc::ByteBuffer request(&request_slice, 1); grpc::ByteBuffer response; const auto started = std::chrono::steady_clock::now(); const grpc::Status status = grpc::internal::BlockingUnaryCall( client->channel.get(), grpc::internal::RpcMethod(method.c_str(), nullptr, grpc::internal::RpcMethod::NORMAL_RPC), &context, request, &response); const auto finished = std::chrono::steady_clock::now(); const auto elapsed = std::chrono::duration_cast(finished - started); out_result->duration_nanos = static_cast(elapsed.count()); out_result->bytes_sent = body_len; out_result->bytes_received = response.Length(); out_result->success = status.ok() ? 1 : 0; const std::string diagnostic = context.debug_error_string(); out_result->transport_code = classify_transport_code(diagnostic); if (out_result->transport_code == 6) { out_result->timeout_phase = classify_timeout_phase(diagnostic); } std::string grpc_message = status.error_message(); const auto &trailers = context.GetServerTrailingMetadata(); const std::string trailer_grpc_status = metadata_value(trailers, "grpc-status"); const std::string trailer_grpc_message = metadata_value(trailers, "grpc-message"); uint16_t grpc_status = status.ok() ? 0 : static_cast(status.error_code()); if (!trailer_grpc_status.empty()) { grpc_status = static_cast(std::strtoul(trailer_grpc_status.c_str(), nullptr, 10)); } if (!trailer_grpc_message.empty()) { grpc_message = trailer_grpc_message; } out_result->grpc_status = grpc_status; out_result->deadline_exceeded = grpc_status == static_cast(grpc::StatusCode::DEADLINE_EXCEEDED) ? 1 : 0; out_result->http_status = out_result->transport_code == 0 ? 200 : 0; if (!grpc_message.empty()) { const size_t message_len = grpc_message.size(); uint8_t *message = static_cast(std::malloc(message_len)); if (message == nullptr) { write_error(err_buf, err_buf_len, "malloc failed for grpc message"); return 1; } std::memcpy(message, grpc_message.data(), message_len); if (out_grpc_message_ptr != nullptr) *out_grpc_message_ptr = message; if (out_grpc_message_len != nullptr) { *out_grpc_message_len = static_cast(message_len); } } if (!status.ok()) { return 0; } if (copy_byte_buffer(response, capture_body_max_bytes, out_body_ptr, out_body_len, &out_result->body_truncated, err_buf, err_buf_len) != 0) { return 1; } return 0; } extern "C" void xburner_grpc_buffer_free(const uint8_t *ptr) { std::free(const_cast(ptr)); }