const std = @import("std"); const config = @import("../config.zig"); const curl_c = @import("http_exec_c.zig"); const http_common = @import("http_exec_common.zig"); const http_state = @import("http_state.zig"); const http_tls = @import("http_exec_tls.zig"); const CookieJar = http_state.CookieJar; const OwnedHeader = http_state.OwnedHeader; const clearOwnedHeaders = http_state.clearOwnedHeaders; const TlsContext = http_tls.TlsContext; const CurlResolvedUrl = struct { url: []u8, resolve_host: ?[]u8 = null, resolve_address: ?[]u8 = null, resolve_port: u16 = 0, fn deinit(self: *CurlResolvedUrl, allocator: std.mem.Allocator) void { allocator.free(self.url); if (self.resolve_host) |value| allocator.free(value); if (self.resolve_address) |value| allocator.free(value); self.* = undefined; } }; pub fn executeRequestCurl( allocator: std.mem.Allocator, tls_context: *TlsContext, cookie_jar: ?*CookieJar, normalized_url: []const u8, method: config.HttpMethod, extra_headers: []const std.http.Header, body: ?[]const u8, connect_timeout_ms: u32, timeout_ms: u32, capture_body_max_bytes: u32, ) !http_common.RequestExecution { var curl_url = try resolveUrlForCurl(allocator, normalized_url, tls_context); defer curl_url.deinit(allocator); const client = try tls_context.ensureCurlClient(); var curl_headers = try allocator.alloc(curl_c.c.xburner_http_curl_header_t, extra_headers.len); defer allocator.free(curl_headers); for (extra_headers, 0..) |header, index| { curl_headers[index] = .{ .key_ptr = header.name.ptr, .key_len = @intCast(header.name.len), .value_ptr = header.value.ptr, .value_len = @intCast(header.value.len), }; } var result: curl_c.c.xburner_http_curl_result_t = std.mem.zeroes(curl_c.c.xburner_http_curl_result_t); var body_ptr: ?[*c]const u8 = null; var body_len: u32 = 0; var headers_ptr: ?[*c]const u8 = null; var headers_len: u32 = 0; var error_kind: curl_c.c.xburner_http_curl_error_kind_t = curl_c.c.XBURNER_HTTP_CURL_ERROR_NONE; var err_buf: [256]u8 = undefined; if (curl_c.c.xburner_http_curl_client_request( client, &.{ .url_ptr = curl_url.url.ptr, .url_len = @intCast(curl_url.url.len), .method_ptr = @tagName(method).ptr, .method_len = @intCast(@tagName(method).len), .headers_ptr = if (curl_headers.len == 0) null else curl_headers.ptr, .headers_len = @intCast(curl_headers.len), .body_ptr = if (body) |payload| payload.ptr else null, .body_len = if (body) |payload| @intCast(payload.len) else 0, .connect_timeout_ms = connect_timeout_ms, .timeout_ms = timeout_ms, .capture_body_max_bytes = capture_body_max_bytes, .http_version = toCurlHttpVersion(tls_context.http_version), .insecure_skip_verify = @intFromBool(tls_context.insecure_skip_verify), .ca_file_ptr = if (tls_context.ca_file) |path| path.ptr else null, .ca_file_len = if (tls_context.ca_file) |path| @intCast(path.len) else 0, .resolve_host_ptr = if (curl_url.resolve_host) |value| value.ptr else null, .resolve_host_len = if (curl_url.resolve_host) |value| @intCast(value.len) else 0, .resolve_address_ptr = if (curl_url.resolve_address) |value| value.ptr else null, .resolve_address_len = if (curl_url.resolve_address) |value| @intCast(value.len) else 0, .resolve_port = curl_url.resolve_port, }, &result, @ptrCast(&body_ptr), &body_len, @ptrCast(&headers_ptr), &headers_len, &error_kind, &err_buf, err_buf.len, ) != 0) { return error.CurlBackendFailed; } defer if (body_ptr) |ptr| curl_c.c.xburner_http_curl_buffer_free(ptr); defer if (headers_ptr) |ptr| curl_c.c.xburner_http_curl_buffer_free(ptr); if (error_kind != curl_c.c.XBURNER_HTTP_CURL_ERROR_NONE) { return mapCurlError(error_kind); } var copied_headers: []OwnedHeader = &.{}; if (headers_ptr != null and headers_len != 0) { copied_headers = try parseCurlResponseHeaders(allocator, headers_ptr.?[0..headers_len]); } if (cookie_jar) |jar| try jar.updateFromHeaders(copied_headers); return .{ .status_code = result.status_code, .duration_nanos = result.duration_nanos, .bytes_sent = result.bytes_sent, .bytes_received = result.bytes_received, .success = result.success != 0, .body_truncated = result.body_truncated != 0, .headers = copied_headers, .captured_body = if (body_ptr != null and body_len != 0) try allocator.dupe(u8, body_ptr.?[0..body_len]) else null, }; } fn toCurlHttpVersion(version: config.HttpVersion) curl_c.c.xburner_http_version_t { return switch (version) { .auto => curl_c.c.XBURNER_HTTP_VERSION_AUTO, .http11 => curl_c.c.XBURNER_HTTP_VERSION_1_1, .http2 => curl_c.c.XBURNER_HTTP_VERSION_2, }; } fn mapCurlError(error_kind: curl_c.c.xburner_http_curl_error_kind_t) anyerror { return switch (error_kind) { curl_c.c.XBURNER_HTTP_CURL_ERROR_DNS => error.UnknownHostName, curl_c.c.XBURNER_HTTP_CURL_ERROR_CONNECT => error.ConnectionRefused, curl_c.c.XBURNER_HTTP_CURL_ERROR_TLS => error.TlsCertificateNotVerified, curl_c.c.XBURNER_HTTP_CURL_ERROR_WRITE => error.WriteFailed, curl_c.c.XBURNER_HTTP_CURL_ERROR_READ => error.ReadFailed, curl_c.c.XBURNER_HTTP_CURL_ERROR_TIMEOUT_CONNECT => error.ConnectionTimedOut, curl_c.c.XBURNER_HTTP_CURL_ERROR_TIMEOUT_IO => error.Timeout, curl_c.c.XBURNER_HTTP_CURL_ERROR_PROTOCOL => error.HttpHeadersInvalid, else => error.HttpHeadersInvalid, }; } fn parseCurlResponseHeaders(allocator: std.mem.Allocator, raw_headers: []const u8) ![]OwnedHeader { var headers = std.ArrayList(OwnedHeader).empty; defer headers.deinit(allocator); var lines = std.mem.splitSequence(u8, raw_headers, "\r\n"); while (lines.next()) |line| { if (line.len == 0) continue; const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; const name = std.mem.trim(u8, line[0..colon], " \t"); const value = std.mem.trim(u8, line[colon + 1 ..], " \t"); try headers.append(allocator, .{ .name = try allocator.dupe(u8, name), .value = try allocator.dupe(u8, value), }); } return try headers.toOwnedSlice(allocator); } fn resolveUrlForCurl(allocator: std.mem.Allocator, normalized_url: []const u8, tls_context: *const TlsContext) !CurlResolvedUrl { if (tls_context.server_name == null or tls_context.insecure_skip_verify) { return .{ .url = try allocator.dupe(u8, normalized_url) }; } const uri = try std.Uri.parse(normalized_url); var host_buffer: [std.Uri.host_name_max]u8 = undefined; const original_host = try uri.getHost(&host_buffer); const server_name = tls_context.server_name.?; if (std.ascii.eqlIgnoreCase(original_host, server_name)) { return .{ .url = try allocator.dupe(u8, normalized_url) }; } const port: u16 = uri.port orelse if (std.mem.eql(u8, uri.scheme, "https")) 443 else 80; const request_target = try http_tls.buildRequestTarget(allocator, &uri); defer allocator.free(request_target); const authority = try formatUrlAuthority(allocator, server_name, port); defer allocator.free(authority); return .{ .url = try std.fmt.allocPrint(allocator, "{s}://{s}{s}", .{ uri.scheme, authority, request_target }), .resolve_host = try allocator.dupe(u8, server_name), .resolve_address = try allocator.dupe(u8, original_host), .resolve_port = port, }; } fn formatUrlAuthority(allocator: std.mem.Allocator, host: []const u8, port: u16) ![]u8 { const needs_brackets = std.mem.indexOfScalar(u8, host, ':') != null; return if (needs_brackets) try std.fmt.allocPrint(allocator, "[{s}]:{d}", .{ host, port }) else try std.fmt.allocPrint(allocator, "{s}:{d}", .{ host, port }); } test "parse curl response headers copies name and value pairs" { const raw = "content-type: application/json\r\n" ++ "set-cookie: sid=abc\r\n"; const headers = try parseCurlResponseHeaders(std.testing.allocator, raw); defer clearOwnedHeaders(std.testing.allocator, headers); try std.testing.expectEqual(@as(usize, 2), headers.len); try std.testing.expectEqualStrings("content-type", headers[0].name); try std.testing.expectEqualStrings("application/json", headers[0].value); try std.testing.expectEqualStrings("set-cookie", headers[1].name); try std.testing.expectEqualStrings("sid=abc", headers[1].value); } test "resolve url for curl rewrites host when server_name override is set" { var tls_context = try TlsContext.init(std.testing.allocator, &.{ .version = .auto, .defaults = .{ .tls = .{ .server_name = "service.internal" }, }, .requests = &.{}, }); defer tls_context.deinit(); var resolved = try resolveUrlForCurl(std.testing.allocator, "https://127.0.0.1:8443/api", &tls_context); defer resolved.deinit(std.testing.allocator); try std.testing.expectEqualStrings("https://service.internal:8443/api", resolved.url); try std.testing.expectEqualStrings("service.internal", resolved.resolve_host.?); try std.testing.expectEqualStrings("127.0.0.1", resolved.resolve_address.?); try std.testing.expectEqual(@as(u16, 8443), resolved.resolve_port); }