ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/network/http/client/client.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define NETWORK_HTTP_CLIENT_SIZE_TEXT_BUFFER_SIZE 32
4
5#include <recast/defer.h>
12
13#include <ascii-chat/otel.h>
15#include <ascii-chat/common.h>
17#include <ascii-chat/version.h>
19#include <libplatform/socket.h>
20
21#include <ascii-chat-deps/bearssl/inc/bearssl.h>
22#ifndef _WIN32
23#include <netdb.h>
24#include <sys/socket.h>
25#include <arpa/inet.h>
26#else
27#include <winsock2.h>
28#include <ws2tcpip.h>
29#endif
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33
34// ============================================================================
35// BearSSL Socket Callbacks
36// ============================================================================
37
41static int sock_read(void *ctx, unsigned char *buf, size_t len) {
42 socket_t *sock = (socket_t *)ctx;
43 ssize_t n = recv(*sock, (char *)buf, (int)len, 0);
44 if (n < 0) {
45 SET_ERRNO_SYS(ERROR_NETWORK, "Failed to receive data from socket");
46 return -1; // Error
47 }
48 if (n == 0) {
49 SET_ERRNO(ERROR_NETWORK, "Connection closed by remote");
50 return -1; // Connection closed
51 }
52 return (int)n;
53}
54
58static int sock_write(void *ctx, const unsigned char *buf, size_t len) {
59 socket_t *sock = (socket_t *)ctx;
60 ssize_t n = send(*sock, (const char *)buf, (int)len, 0);
61 if (n < 0) {
62 SET_ERRNO_SYS(ERROR_NETWORK, "Failed to send data to socket");
63 return -1; // Error
64 }
65 return (int)n;
66}
67
68// ============================================================================
69// HTTP Response Parsing
70// ============================================================================
71
76static char *extract_http_body(const char *response, size_t response_len) {
77 // Find "\r\n\r\n" (end of headers)
78 const char *body_start = strstr(response, "\r\n\r\n");
79 if (!body_start) {
80 log_error("No HTTP body found in response");
81 return NULL;
82 }
83 body_start += 4; // Skip "\r\n\r\n"
84
85 size_t body_len = response_len - (size_t)(body_start - response);
86 const char *transfer_encoding = strstr(response, "Transfer-Encoding:");
87 bool is_chunked = transfer_encoding && strstr(transfer_encoding, "chunked") != NULL;
88
89 if (!is_chunked) {
90 char *body = SAFE_MALLOC(body_len + 1, char *);
91 memcpy(body, body_start, body_len);
92 body[body_len] = '\0';
93 return body;
94 }
95
96 // GitHub commonly uses HTTP/1.1 chunked transfer encoding. The bytes after
97 // the headers are then a sequence of `<hex-size>\\r\\n<data>\\r\\n` chunks,
98 // not the JSON document itself. Decode into a bounded buffer before handing
99 // the body to JSON parsers.
100 SAFE_MALLOC_DEFER_FREE(body, body_len + 1, char *);
101 size_t decoded_len = 0;
102 const char *cursor = body_start;
103 const char *end = response + response_len;
104
105 while (cursor < end) {
106 const char *line_end = strstr(cursor, "\r\n");
107 if (!line_end || line_end >= end) {
108 log_error("Malformed chunked HTTP response: missing chunk size terminator");
109 return NULL;
110 }
111
113 size_t size_text_len = (size_t)(line_end - cursor);
114 const char *extension = memchr(cursor, ';', size_text_len);
115 if (extension) {
116 size_text_len = (size_t)(extension - cursor);
117 }
118 if (size_text_len == 0 || size_text_len >= sizeof(size_text)) {
119 log_error("Malformed chunked HTTP response: invalid chunk size");
120 return NULL;
121 }
122 memcpy(size_text, cursor, size_text_len);
123 size_text[size_text_len] = '\0';
124
125 char *size_end = NULL;
126 unsigned long long chunk_size = strtoull(size_text, &size_end, 16);
127 if (size_end == size_text || *size_end != '\0') {
128 log_error("Malformed chunked HTTP response: invalid chunk size '%s'", size_text);
129 return NULL;
130 }
131
132 cursor = line_end + 2;
133 if (chunk_size == 0) {
134 break;
135 }
136 if (chunk_size > (unsigned long long)(end - cursor) || (size_t)chunk_size > body_len - decoded_len) {
137 log_error("Malformed chunked HTTP response: chunk exceeds response body");
138 return NULL;
139 }
140
141 memcpy(body + decoded_len, cursor, (size_t)chunk_size);
142 decoded_len += (size_t)chunk_size;
143 cursor += (size_t)chunk_size;
144 if (cursor + 2 > end || cursor[0] != '\r' || cursor[1] != '\n') {
145 log_error("Malformed chunked HTTP response: missing chunk terminator");
146 return NULL;
147 }
148 cursor += 2;
149 }
150
151 body[decoded_len] = '\0';
152 char *result = body;
153 body = NULL;
154 return result;
155}
156
157// Return the status code, or -1 for a malformed status line.
158static int parse_http_status(const char *response, size_t length) {
159 if (length < 13 || strncmp(response, "HTTP/1.", sizeof("HTTP/1.") - 1) != 0 || response[7] == '\0' || response[8] != ' ' || response[9] < '0' || response[9] > '9' || response[10] < '0' ||
160 response[10] > '9' || response[11] < '0' || response[11] > '9' || (response[12] != ' ' && response[12] != '\r'))
161 return -1;
162 return (response[9] - '0') * 100 + (response[10] - '0') * 10 + response[11] - '0';
163}
164
165// ============================================================================
166// HTTPS GET Implementation
167// ============================================================================
168
169// Cap response size at 1 MB to prevent unbounded memory growth
170#define HTTPS_MAX_RESPONSE_SIZE (1024 * 1024)
171
172static void free_http_anchors(anchor_list *anchors) {
173 for (size_t i = 0; i < anchors->ptr; i++) {
174 free_ta_contents(&anchors->buf[i]);
175 }
176 SAFE_FREE(anchors->buf);
177}
178
179char *https_get(const char *hostname, const char *path) {
180 ASCII_OTEL_SCOPE(HTTP);
181 ascii_otel_http(&otel_scope, hostname, path);
182 char *body = NULL;
183 if (!hostname || !path) {
184 log_error("Invalid arguments");
185 return NULL;
186 }
187
188 char ascii_hostname[HOSTNAME_BUFFER_SIZE];
189 asciichat_error_t normalized = hostname_to_ascii(hostname, ascii_hostname, sizeof(ascii_hostname));
190 if (normalized != ASCIICHAT_OK)
191 return NULL;
192 hostname = ascii_hostname;
193
194 log_info("HTTPS GET https://%s%s", hostname, path);
195
196 // Load system CA certificates
197 char *pem_data = NULL;
198 size_t pem_size = 0;
199 if (platform_load_system_ca_certs(&pem_data, &pem_size) != 0) {
200 log_error("Failed to load system CA certificates");
201 return NULL;
202 }
203
204 // Parse PEM certificates into BearSSL trust anchors
206 defer(free_http_anchors(&anchors));
207 size_t num_anchors = read_trust_anchors_from_memory(&anchors, (unsigned char *)pem_data, pem_size);
208 /* libplatform allocates the certificate bundle with the regular C
209 * allocator; it must not cross into ascii-chat's optional mimalloc path. */
210 free(pem_data);
211 pem_data = NULL;
212
213 if (num_anchors == 0) {
214 log_error("No trust anchors loaded");
215 return NULL;
216 }
217 log_info("Loaded %zu trust anchors", num_anchors);
218
219 // Resolve hostname using getaddrinfo (modern, non-deprecated API)
220 struct addrinfo hints, *result;
221 memset(&hints, 0, sizeof(hints));
222 hints.ai_family = AF_INET; // IPv4
223 hints.ai_socktype = SOCK_STREAM;
224 hints.ai_protocol = IPPROTO_TCP;
225
226 int dns_result;
227 {
228 ASCII_OTEL_SCOPE_AS(dns_scope, DNS_RESOLVE);
229 if (dns_scope.retained)
230 gotel_attr_string(&dns_scope.scope, "dns.question.name", hostname);
231 dns_result = getaddrinfo(hostname, "443", &hints, &result);
232 if (dns_result && dns_scope.retained)
233 gotel_error(&dns_scope.scope, "dns.error", "DNS lookup failed");
234 }
235 if (dns_result != 0) {
236 log_error("Failed to resolve hostname: %s", hostname);
237 return NULL;
238 }
239
240 defer(if (result) freeaddrinfo(result));
241
242 // Create TCP socket
243 socket_t sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
244 if (sock == INVALID_SOCKET_VALUE) {
245 log_error("Failed to create socket");
246 return NULL;
247 }
248
249 defer(if (sock != INVALID_SOCKET_VALUE) socket_close(sock));
250
251 // Set socket timeouts to avoid blocking indefinitely on stalled connections.
252 // Windows expects a DWORD timeout in milliseconds, while POSIX expects a
253 // struct timeval. Passing timeval to Winsock makes the timeout effectively
254 // a few milliseconds and commonly aborts the TLS handshake.
255#ifdef _WIN32
256 DWORD timeout_ms = 5000;
257 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout_ms, sizeof(timeout_ms));
258 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout_ms, sizeof(timeout_ms));
259#else
260 struct timeval timeout = {.tv_sec = 5, .tv_usec = 0};
261 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
262 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));
263#endif
264
265 // Connect to server
266 if (connect(sock, result->ai_addr, (int)result->ai_addrlen) != 0) {
267 log_error("Failed to connect to %s:443", hostname);
268 return NULL;
269 }
270
271 freeaddrinfo(result);
272 result = NULL;
273
274 log_info("Connected to %s:443", hostname);
275
276 // Initialize BearSSL X.509 minimal validator
277 br_x509_minimal_context xc;
278 br_x509_minimal_init(&xc, &br_sha256_vtable, anchors.buf, anchors.ptr);
279
280 // Initialize BearSSL client context
281 br_ssl_client_context sc;
282 br_ssl_client_init_full(&sc, &xc, anchors.buf, anchors.ptr);
283
284 // Set I/O buffer
285 const size_t iobuf_size = BR_SSL_BUFSIZE_BIDI;
286 SAFE_MALLOC_DEFER_FREE(iobuf, iobuf_size, unsigned char *);
287 br_ssl_engine_set_buffer(&sc.eng, iobuf, BR_SSL_BUFSIZE_BIDI, 1);
288
289 // Initialize I/O context
290 br_sslio_context ioc;
291 br_sslio_init(&ioc, &sc.eng, sock_read, &sock, sock_write, &sock);
292
293 // Start TLS handshake
294 br_ssl_client_reset(&sc, hostname, 0);
295
296 log_info("Starting TLS handshake with %s", hostname);
297
298 // Build HTTP request
299 char request[BUFFER_SIZE_LARGE];
300 int request_len = safe_snprintf(request, sizeof(request),
301 "GET %s HTTP/1.1\r\n"
302 "Host: %s\r\n"
303 "Connection: close\r\n"
304 "User-Agent: ascii-chat/" ASCII_CHAT_VERSION_STRING "\r\n"
305 "\r\n",
306 path, hostname);
307
308 // Send HTTP request over TLS
309 if (br_sslio_write_all(&ioc, request, (size_t)request_len) != 0) {
310 log_error("Failed to send HTTP request");
311 return NULL;
312 }
313
314 br_sslio_flush(&ioc);
315 log_info("Sent HTTP request");
316
317 // Read HTTP response
318 size_t response_capacity = 8192;
319 size_t response_len = 0;
320 SAFE_MALLOC_DEFER_FREE(response_buf, response_capacity, char *);
321
322 while (1) {
323 // Ensure we have space to read
324 if (response_len + 1024 > response_capacity) {
325 response_capacity *= 2;
326 if (response_capacity > HTTPS_MAX_RESPONSE_SIZE) {
327 log_error("Response exceeds maximum size (%d bytes)", HTTPS_MAX_RESPONSE_SIZE);
328 return NULL;
329 }
330 response_buf = SAFE_REALLOC(response_buf, response_capacity, char *);
331 }
332
333 // Read data (reserve 1 byte for null terminator)
334 int n = br_sslio_read(&ioc, response_buf + response_len, response_capacity - response_len - 1);
335 if (n < 0) {
336 // Check for TLS errors
337 int err = br_ssl_engine_last_error(&sc.eng);
338 if (err != BR_ERR_OK) {
339 log_error("TLS error: %d", err);
340 return NULL;
341 }
342 // EOF or connection closed
343 break;
344 }
345 if (n == 0) {
346 break; // EOF
347 }
348
349 response_len += (size_t)n;
350 }
351
352 response_buf[response_len] = '\0';
353 log_info("Received %zu bytes", response_len);
354
355 // Close connection
356 br_sslio_close(&ioc);
357 socket_close(sock);
358 sock = INVALID_SOCKET_VALUE;
359
360 // Parse HTTP response
361 int code = parse_http_status(response_buf, response_len);
362 if (code >= 0 && otel_scope.retained)
363 gotel_http_attributes(&otel_scope.scope, "GET", code);
364 if (code != 200) {
365 if (code < 0)
366 SET_ERRNO(ERROR_NETWORK, "Invalid HTTP response: %s", response_buf);
367 else
368 SET_ERRNO(ERROR_NETWORK, "HTTP request failed: %.50s", response_buf);
369 return NULL;
370 }
371
372 body = extract_http_body(response_buf, response_len);
373 if (body)
374 ascii_otel_http_status(&otel_scope, 200);
375
376 return body;
377}
378
379// NOTE: fetch_github_ssh_keys, fetch_gitlab_ssh_keys, fetch_github_gpg_keys,
380// and fetch_gitlab_gpg_keys have been moved to crypto/keys/https_keys.c
381// They properly belong in the keys module, not the http_client module.
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
br_x509_trust_anchor * buf
Definition pem.h:89
#define ANCHOR_LIST_INIT
Initializer for anchor_list.
Definition pem.h:103
size_t read_trust_anchors_from_memory(anchor_list *dst, const unsigned char *pem_data, size_t pem_len)
Read trust anchors from PEM-encoded data in memory.
Definition pem.c:469
void free_ta_contents(br_x509_trust_anchor *ta)
Free the contents of a trust anchor.
Definition pem.c:448
size_t ptr
Definition pem.h:90
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:77
@ ASCIICHAT_OK
Definition error_codes.h:50
#define HOSTNAME_BUFFER_SIZE
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
char * https_get(const char *hostname, const char *path)
Perform HTTPS GET request.
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:109
int socket_t
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Simple HTTPS client for fetching public keys from GitHub/GitLab.
#define NETWORK_HTTP_CLIENT_SIZE_TEXT_BUFFER_SIZE
#define HTTPS_MAX_RESPONSE_SIZE
int socket_close(socket_t)
void ascii_otel_http(ascii_otel_scope_t *s, const char *hostname, const char *path)
Definition otel.c:974
void ascii_otel_http_status(ascii_otel_scope_t *s, int status)
Definition otel.c:993
#define ASCII_OTEL_SCOPE_AS(variable, id)
Definition otel.h:106
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
BearSSL PEM and trust anchor utilities adapted for in-memory data.
🔤 String Manipulation and Shell Escaping Utilities
Vector type for trust anchors.
Definition pem.h:87
🌐 Production-Grade URL Validation and Parsing