ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
http.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define MCP_SERVER_HTTP_ORIGIN_BUFFER_SIZE 2048
4#define MCP_SERVER_HTTP_TYPE_BUFFER_SIZE 128
5#define MCP_SERVER_HTTP_ACCEPT_BUFFER_SIZE 512
6#define MCP_SERVER_HTTP_VERSION_BUFFER_SIZE 64
7
8#include "mcp.h"
9#include "windows_service.h"
16#include <libplatform/systemd.h>
17#include <options/options.h>
18#include <sodium.h>
19#include <stdlib.h>
20#include <string.h>
21#include <sys/stat.h>
22#include <time.h>
23#include <uv.h>
24
25static const char *shared_header(const http_request_info_t *info,
26 const char *name) {
27 for (size_t i = 0; i < info->header_count; ++i)
28 if (!platform_strcasecmp(info->headers[i].name, name))
29 return info->headers[i].value;
30 return NULL;
31}
32
34 if (s && s->shared_http)
36}
37
38static void shared_http_finish(http_response_t *response, unsigned status) {
39 (void)http_response_set_status(response, status);
40 ASCII_OTEL_SCOPE(MCP_HTTP_RESPONSE);
41 ASCII_OTEL_ATTR_INT("http.response.status_code", status);
42 ASCII_OTEL_ATTR_INT("http.response.body.size",
43 (int64_t)http_response_body_length(response));
45 (void)http_response_finish(response);
46}
47
48static void shared_http_wakeup(void *user_data) {
49 mcp_server_t *s = user_data;
50 for (unsigned i = 0; i < s->policy.max_jobs; ++i) {
51 mcp_job_t *j = &s->jobs[i];
52 if (!j->renderer_job.started || !j->connection ||
54 continue;
55 http_response_t *response = j->connection;
56 if (http_response_is_cancelled(response)) {
57 j->connection = NULL;
58 http_response_release(&response);
59 continue;
60 }
61 if (s->policy.restricted &&
62 mcp_download_finalize(&s->policy, j->response, (int64_t)time(NULL)) !=
64 yyjson_mut_val *root = yyjson_mut_doc_get_root(j->response);
65 yyjson_mut_obj_remove_str(root, "result");
66 yyjson_mut_val *error = yyjson_mut_obj(j->response);
67 yyjson_mut_obj_add_int(j->response, error, "code", -32603);
68 yyjson_mut_obj_add_str(j->response, error, "message",
69 "Cannot publish download");
70 yyjson_mut_obj_add_val(j->response, root, "error", error);
71 }
72 size_t length = 0;
73 char *body = mcp_response_encode_toon(j->response, &length);
74 if (body) {
75 (void)http_response_set_status(response, 200);
76 (void)http_response_write(response, body, length);
77 shared_http_finish(response, 200);
78 free(body);
79 } else {
80 /* Always terminate the retained transport before releasing its slot. */
81 shared_http_finish(response, 500);
82 }
83 j->connection = NULL;
84 http_response_release(&response);
85 }
86 mcp_jobs_reap(s, false);
87}
88
89static void shared_http_request(http_request_t *request,
90 http_response_t *response, void *user_data) {
91 mcp_server_t *s = user_data;
92 const http_request_info_t *info = http_request_info(request);
93 const char *origin = shared_header(info, "origin");
94 if (origin && (!s->policy.origin || strcmp(origin, s->policy.origin))) {
95 shared_http_finish(response, 403);
96 return;
97 }
98 if (s->policy.restricted &&
99 !strncmp(info->path, "/downloads/", sizeof("/downloads/") - 1)) {
100 if (strcmp(info->method, "GET")) {
101 shared_http_finish(response, 405);
102 return;
103 }
104 const char *name = info->path + sizeof("/downloads/") - 1;
105 int64_t expires = 0;
106 char path[PLATFORM_MAX_PATH_LENGTH];
107 int n = safe_snprintf(path, sizeof(path), "%s/%s", s->policy.downloads_dir,
108 name);
109 if (n < 0 || (size_t)n >= sizeof(path) ||
110 !mcp_download_name(name, &expires) || expires <= (int64_t)time(NULL)) {
111 shared_http_finish(response, 404);
112 return;
113 }
114 uv_fs_t fs = {0};
115 int rc =
116 uv_fs_open(NULL, &fs, path, UV_FS_O_RDONLY | UV_FS_O_NOFOLLOW, 0, NULL);
117 uv_fs_req_cleanup(&fs);
118 if (rc < 0) {
119 shared_http_finish(response, 404);
120 return;
121 }
122 uv_file file = rc;
123 rc = uv_fs_fstat(NULL, &fs, file, NULL);
124 size_t size = rc == 0 ? (size_t)fs.statbuf.st_size : 0;
125 uv_fs_req_cleanup(&fs);
126 if (!size || size > MCP_MAX_DOWNLOAD) {
127 uv_fs_close(NULL, &fs, file, NULL);
128 uv_fs_req_cleanup(&fs);
129 shared_http_finish(response, size > MCP_MAX_DOWNLOAD ? 413 : 404);
130 return;
131 }
132 char *contents = SAFE_MALLOC(size, char *);
133 uv_buf_t buffer = uv_buf_init(contents, (unsigned)size);
134 rc = contents ? uv_fs_read(NULL, &fs, file, &buffer, 1, 0, NULL) : -1;
135 uv_fs_req_cleanup(&fs);
136 uv_fs_close(NULL, &fs, file, NULL);
137 uv_fs_req_cleanup(&fs);
138 if (rc != (int)size ||
139 http_response_write(response, contents, size) != ASCIICHAT_OK) {
140 SAFE_FREE(contents);
141 shared_http_finish(response, 500);
142 return;
143 }
144 SAFE_FREE(contents);
145 const char *extension = strrchr(name, '.');
147 response, "Content-Type",
148 mcp_output_mime(extension ? extension + 1 : "")) != ASCIICHAT_OK ||
149 http_response_set_header(response, "Cache-Control", "no-store") !=
150 ASCIICHAT_OK) {
151 shared_http_finish(response, 500);
152 return;
153 }
154 shared_http_finish(response, 200);
155 return;
156 }
157 if (strcmp(info->path, "/mcp")) {
158 shared_http_finish(response, 404);
159 return;
160 }
161 if (strcmp(info->method, "POST")) {
162 shared_http_finish(response, 405);
163 return;
164 }
165 if (http_response_set_header(response, "Content-Type",
166 "text/toon; charset=utf-8") != ASCIICHAT_OK) {
167 shared_http_finish(response, 500);
168 return;
169 }
170 const char *type = shared_header(info, "content-type");
171 if (!type ||
172 strncmp(type, "application/json", sizeof("application/json") - 1)) {
173 shared_http_finish(response, 415);
174 return;
175 }
176 const char *accept = shared_header(info, "accept");
177 if (!accept || !strstr(accept, "text/toon") ||
178 !strstr(accept, "text/event-stream")) {
179 shared_http_finish(response, 406);
180 return;
181 }
182 const char *version = shared_header(info, "mcp-protocol-version");
183 if (version && strcmp(version, "2025-11-25") &&
184 strcmp(version, "2025-06-18") && strcmp(version, "2025-03-26")) {
185 shared_http_finish(response, 400);
186 return;
187 }
188 size_t length = 0;
189 const char *body = http_request_body(request, &length);
190 yyjson_doc *doc = body ? yyjson_read(body, length, 0) : NULL;
191 if (!doc) {
192 yyjson_mut_doc *error = mcp_error(NULL, -32700, "Parse error");
193 char *encoded = mcp_response_encode_toon(error, &length);
194 yyjson_mut_doc_free(error);
195 if (encoded) {
196 (void)http_response_write(response, encoded, length);
197 free(encoded);
198 }
199 shared_http_finish(response, 400);
200 return;
201 }
202 char session_id[MCP_SESSION_ID_LENGTH + 1] = {0};
203 const char *session = shared_header(info, "mcp-session-id");
204 if (session) {
205 if (strlen(session) != MCP_SESSION_ID_LENGTH) {
206 yyjson_doc_free(doc);
207 shared_http_finish(response, 400);
208 return;
209 }
210 for (size_t i = 0; i < MCP_SESSION_ID_LENGTH; ++i) {
211 if (!((session[i] >= '0' && session[i] <= '9') ||
212 (session[i] >= 'a' && session[i] <= 'f'))) {
213 yyjson_doc_free(doc);
214 shared_http_finish(response, 400);
215 return;
216 }
217 }
218 SAFE_STRNCPY(session_id, session, sizeof(session_id));
219 }
220 bool issue_session = false;
221 yyjson_val *root = yyjson_doc_get_root(doc),
222 *method = mcp_get(root, "method");
223 if (yyjson_is_str(method) && yyjson_equals_str(method, "initialize") &&
224 mcp_get(root, "id")) {
225 unsigned char random[16];
226 randombytes_buf(random, sizeof(random));
227 sodium_bin2hex(session_id, sizeof(session_id), random, sizeof(random));
228 issue_session = true;
229 }
230 bool pending = false;
231 yyjson_mut_doc *reply = mcp_dispatch(s, doc, response, session_id, &pending);
232 yyjson_doc_free(doc);
233 if (pending) {
234 http_response_t *retained = NULL;
235 if (http_response_retain(response, &retained) != ASCIICHAT_OK) {
236 shared_http_finish(response, 503);
237 return;
238 }
239 for (unsigned i = 0; i < s->policy.max_jobs; ++i)
240 if (s->jobs[i].renderer_job.started && s->jobs[i].connection == response)
241 s->jobs[i].connection = retained;
242 return;
243 }
244 size_t encoded_length = 0;
245 bool has_reply = reply != NULL;
246 char *encoded =
247 reply ? mcp_response_encode_toon(reply, &encoded_length) : NULL;
248 if (reply)
249 yyjson_mut_doc_free(reply);
250 if (encoded) {
251 (void)http_response_write(response, encoded, encoded_length);
252 free(encoded);
253 }
254 if (issue_session && http_response_set_header(response, "MCP-Session-Id",
256 shared_http_finish(response, 500);
257 return;
258 }
259 shared_http_finish(response, has_reply ? (encoded ? 200 : 500) : 202);
260}
261
263 http_server_config_t config = {
264 .bind_address = s->policy.address,
265 .bind_address6 = s->policy.address6,
266 .port = (uint16_t)s->policy.port,
267 .enable_http1 = true,
268 .enable_http2 = true,
269 .tls_cert_path = s->policy.tls_cert[0] ? s->policy.tls_cert : NULL,
270 .tls_key_path = s->policy.tls_key[0] ? s->policy.tls_key : NULL,
271 .tls_key_password =
272 s->policy.tls_password[0] ? s->policy.tls_password : NULL,
273 .max_connections = s->policy.max_jobs * 4U,
274 .max_request_body_bytes = MCP_MAX_INPUT,
275 .max_response_body_bytes = MCP_MAX_DOWNLOAD,
276 .on_request = shared_http_request,
277 .on_wakeup = shared_http_wakeup,
278 .user_data = s};
279 if (!config.max_connections)
280 config.max_connections = 1;
281 asciichat_error_t result = http_server_init(&s->shared_http, &config);
282 if (result != ASCIICHAT_OK)
283 return result;
284 result = http_server_start(s->shared_http);
285 if (result != ASCIICHAT_OK) {
287 return result;
288 }
289 platform_systemd_notify_status("MCP HTTP listener started");
290 platform_systemd_notify_ready();
292 nat_upnp_context_t *mapping = NULL;
293 if (GET_OPTION(enable_upnp)) {
295 nat_upnp_open((uint16_t)s->policy.port, "ascii-chat MCP", &mapping);
296 if (err != ASCIICHAT_OK)
297 LOG_ERRNO_IF_SET("MCP port forwarding unavailable");
298 }
300 uv_sleep(16);
301 mcp_jobs_reap(s, false);
302 if (mapping && time_get_ns() >= mapping->refresh_at_ns) {
303 asciichat_error_t err = nat_upnp_refresh(mapping);
304 if (err != ASCIICHAT_OK)
305 LOG_ERRNO_IF_SET("MCP mapping renewal failed");
306 }
307 }
308 for (unsigned i = 0; i < s->policy.max_jobs; ++i)
309 if (s->jobs[i].renderer_job.started)
313 nat_upnp_close(&mapping);
314 mcp_jobs_reap(s, true);
315 return ASCIICHAT_OK;
316}
Application-level callbacks for library code.
#define APP_CALLBACK_BOOL(callback_name)
#define LOG_ERRNO_IF_SET(message)
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
asciichat_error_t mcp_download_finalize(const mcp_policy_t *policy, yyjson_mut_doc *doc, int64_t now)
Definition downloads.c:77
bool mcp_download_name(const char *name, int64_t *expires)
Definition downloads.c:25
const char * mcp_output_mime(const char *extension)
Definition downloads.c:11
unsigned short uint16_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
#define GET_OPTION(field)
Definition options.h:1339
void mcp_http_wake(mcp_server_t *s)
Definition http.c:33
asciichat_error_t mcp_http_run(mcp_server_t *s)
Definition http.c:262
bool http_renderer_job_is_done(const http_renderer_job_t *job)
void http_renderer_job_cancel(http_renderer_job_t *job)
struct http_request http_request_t
struct http_request_info http_request_info_t
struct http_response http_response_t
@ STATS_COUNTER_MCP_HTTP_RESPONSES
const void * http_request_body(const http_request_t *r, size_t *n)
asciichat_error_t http_server_init(http_server_t **out, const http_server_config_t *cfg)
asciichat_error_t http_response_set_status(http_response_t *r, unsigned s)
asciichat_error_t http_server_wakeup(http_server_t *s)
void http_server_stop(http_server_t *s)
void http_server_destroy(http_server_t **p)
asciichat_error_t http_response_set_header(http_response_t *r, const char *n, const char *v)
asciichat_error_t http_response_retain(http_response_t *r, http_response_t **retained)
bool http_response_is_cancelled(const http_response_t *r)
asciichat_error_t http_server_start(http_server_t *s)
size_t http_response_body_length(const http_response_t *r)
asciichat_error_t http_response_write(http_response_t *r, const void *d, size_t n)
const http_request_info_t * http_request_info(const http_request_t *r)
void http_response_release(http_response_t **response)
asciichat_error_t http_response_finish(http_response_t *r)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
bool should_exit(void)
Definition main.c:260
#define MCP_MAX_INPUT
Definition mcp.h:30
yyjson_mut_doc * mcp_error(yyjson_val *id, int code, const char *message)
yyjson_mut_doc * mcp_dispatch(mcp_server_t *server, yyjson_doc *message, void *connection, const char *session_id, bool *pending)
struct mcp_server mcp_server_t
The useful part of mcp job is in server, message, response, request: together they describe what is p...
struct mcp_job mcp_job_t
When code needs to work with mcp policy, it keeps hosted, restricted, address, address6 here instead ...
#define MCP_MAX_DOWNLOAD
Definition mcp.h:32
char * mcp_response_encode_toon(yyjson_mut_doc *response, size_t *length)
Definition stdio.c:20
#define MCP_SESSION_ID_LENGTH
Definition mcp.h:33
void mcp_jobs_reap(mcp_server_t *server, bool all)
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
uint8_t session_id[SESSION_ID_SIZE]
int platform_strcasecmp(const char *s1, const char *s2)
📊 Status screen display and management for server/discovery service modes
🔤 String Manipulation and Shell Escaping Utilities
void * connection
Definition mcp.h:72
yyjson_mut_doc * response
Definition mcp.h:67
http_renderer_job_t renderer_job
Definition mcp.h:71
const char * tls_key
Definition mcp.h:41
const char * tls_password
Definition mcp.h:41
const char * address
Definition mcp.h:39
unsigned max_jobs
Definition mcp.h:42
const char * tls_cert
Definition mcp.h:41
char downloads_dir[PLATFORM_MAX_PATH_LENGTH]
Definition mcp.h:45
const char * address6
Definition mcp.h:40
const char * origin
Definition mcp.h:43
int port
Definition mcp.h:44
bool restricted
Definition mcp.h:38
http_server_t * shared_http
Definition mcp.h:90
atomic_t stopping
Definition mcp.h:91
mcp_job_t * jobs
Definition mcp.h:88
mcp_policy_t policy
Definition mcp.h:87
uint64_t refresh_at_ns
Next renewal or retry deadline.
Definition upnp.h:48
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t nat_upnp_refresh(nat_upnp_context_t *ctx)
Refresh port mapping (e.g., for long-running servers).
Definition upnp.c:303
void nat_upnp_close(nat_upnp_context_t **ctx)
Close port mapping and clean up.
Definition upnp.c:240
asciichat_error_t nat_upnp_open(uint16_t internal_port, const char *description, nat_upnp_context_t **ctx)
Discover and open port via UPnP.
Definition upnp.c:194
UPnP/NAT-PMP port mapping for TCP and UDP connectivity.
struct nat_upnp_context nat_upnp_context_t
Handle to UPnP context.
void windows_service_ready(void)