scorpiox-bot-plugin-fetch
←plugin_fetch.cc
851 lines · 30 KBHEADBlameDownload
1/*
2 * plugin_fetch - SCORPIOX BOT open-source URL fetch & HTML-to-Markdown connector
3 *
4 * One clean-room C99 binary with the four contracts a SCORPIOX BOT connector
5 * plugin implements:
6 *
7 * 1. --meta / SX_PLUGIN_META=1 -> one line of JSON discovery metadata
8 * (unauthenticated, so the node can always discover it)
9 * 2. --mcp -> MCP JSON-RPC 2.0 over stdio:
10 * initialize / notifications/initialized / tools/list / tools/call.
11 * One tool: fetch {url, max_length=5000, start_index=0, raw=false}.
12 * 3. ?action=... (+ POST JSON body) -> JSON node API (node auth required)
13 * 4. GET (default) -> responsive dark/light HTML page:
14 * a URL Preview & Fetch Tester that calls the same engine as --mcp.
15 *
16 * The tool is a clean-room C port of the behaviour of modelcontextprotocol
17 * `servers/src/fetch` (the fetch MCP server): it follows up to 5 redirects
18 * (every hop re-checked), refuses private / loopback / link-local /
19 * special-purpose addresses unless the operator allows them, caps the body it
20 * reads, truncates long results with a start_index footer, returns
21 * markdown/text bodies as-is, and prefixes non-simplifiable bodies with a
22 * "cannot be simplified" notice. The HTML->Markdown converter is the
23 * web-readability-shaped subset in fetch_md.c.
24 *
25 * HTTP/HTTPS transport is built in (no libcurl, no OpenSSL): POSIX uses our
26 * own getaddrinfo + a non-blocking connect to a PRE-VALIDATED IP with
27 * vendored mbedTLS 3.6.7 over custom BIOs (TLS 1.2+; certificate and hostname
28 * verified against a CA bundle — FETCH_TLS_CA_FILE or the first system
29 * bundle; there is deliberately no insecure bypass). _WIN32 uses WinHTTP
30 * (system root store, -lwinhttp) so the static PE needs zero DLLs.
31 *
32 * MIT License. Copyright (c) 2026 SCORPIOX INC.
33 */
34
35/* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502 and
36 * winhttp/ws2tcpip gate helpers on newer values; Apple needs _DARWIN_C_SOURCE
37 * under -std=c99; MinGW needs its printf for %zu. */
38#if defined(_WIN32) && !defined(_WIN32_WINNT)
39# define _WIN32_WINNT 0x0601
40#endif
41#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE)
42# define _DARWIN_C_SOURCE 1
43#endif
44#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO)
45# define __USE_MINGW_ANSI_STDIO 1
46#endif
47
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <ctype.h>
52#include <time.h>
53
54#if defined(_WIN32)
55 /* MinGW splits what one POSIX header covers into three: <io.h> declares
56 * _setmode/_fileno, <fcntl.h> declares the _O_* constants _setmode takes,
57 * <direct.h> declares _mkdir. windows.h pulls in none of them. */
58# include <windows.h>
59# include <io.h>
60# include <fcntl.h>
61# include <direct.h>
62#endif
63#include <sys/stat.h>
64#include <sys/types.h>
65
66#include "bot_theme_plugin.h"
67#include "ui_html.h"
68#include "fetch_http.h"
69#include "fetch_md.h"
70#include "sxmcp.h"
71
72#define PLUGIN_SLUG "fetch"
73#define PLUGIN_ID "plugin_fetch"
74#define PLUGIN_VER "1.0.0"
75
76#if defined(_WIN32)
77# define sx_mkdir(p) _mkdir(p)
78# define SX_PATHSEP '\\'
79#else
80# include <unistd.h>
81# define sx_mkdir(p) mkdir((p), 0755)
82# define SX_PATHSEP '/'
83#endif
84
85void tool_result_free(tool_result *r)
86{
87 if (!r) return;
88 free(r->text);
89 free(r->raw_html);
90 memset(r, 0, sizeof *r);
91}
92
93/* ------------------------------------------------------------------ */
94/* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and the */
95/* HTML page never call this; every JSON action does. */
96/* ------------------------------------------------------------------ */
97
98static void require_node_auth(void)
99{
100 const char *np = getenv("BOT_PASSWORD");
101 const char *xp, *auth;
102 char qpwd[256] = {0};
103 const char *qs;
104
105 if (!np || !*np) return; /* open node: no gate */
106 xp = getenv("HTTP_X_BOT_PASSWORD");
107 if (xp && strcmp(xp, np) == 0) return;
108 auth = getenv("HTTP_AUTHORIZATION");
109 if (auth) {
110 while (*auth == ' ') auth++;
111 if (sx_strncasecmp(auth, "Bearer ", 7) == 0) {
112 auth += 7;
113 while (*auth == ' ') auth++;
114 if (strcmp(auth, np) == 0) return;
115 }
116 }
117 qs = getenv("QUERY_STRING");
118 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
119 return;
120
121 fputs("Status: 401 Unauthorized\r\n"
122 "Content-Type: application/json; charset=utf-8\r\n\r\n"
123 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
124 exit(0);
125}
126
127/* ------------------------------------------------------------------ */
128/* Connector dir + persisted policy */
129/* ------------------------------------------------------------------ */
130
131static void connector_dir(char *out, size_t outsz)
132{
133 const char *env = getenv("SX_CONNECTOR_DIR");
134 struct stat st;
135
136 if (env && *env) { snprintf(out, outsz, "%s", env); return; }
137 if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) &&
138 access("/workspace", W_OK) == 0) {
139 snprintf(out, outsz, "/workspace/.scorpiox/connectors/fetch");
140 return;
141 }
142#if defined(_WIN32)
143 {
144 const char *la = getenv("LOCALAPPDATA");
145 if (la && *la) {
146 snprintf(out, outsz, "%s\\scorpiox\\connectors\\fetch", la);
147 return;
148 }
149 }
150#endif
151 {
152 const char *home = getenv("HOME");
153 if (!home || !*home) home = "/root";
154 snprintf(out, outsz, "%s/.scorpiox/connectors/fetch", home);
155 }
156}
157
158static int mkdirs(const char *path)
159{
160 char buf[1200];
161 size_t i, n;
162 struct stat st;
163 snprintf(buf, sizeof buf, "%s", path);
164 n = strlen(buf);
165 for (i = 1; i < n; i++) {
166 if (buf[i] == '/' || buf[i] == '\\') {
167 char save = buf[i];
168 buf[i] = '\0';
169 if (i > 2) sx_mkdir(buf);
170 buf[i] = save;
171 }
172 }
173 sx_mkdir(buf);
174 return stat(buf, &st) == 0 && S_ISDIR(st.st_mode);
175}
176
177static void policy_path(char *out, size_t outsz)
178{
179 char dir[1000];
180 connector_dir(dir, sizeof dir);
181 snprintf(out, outsz, "%s%cconfig.json", dir, SX_PATHSEP);
182}
183
184static int policy_read_allow_private(void)
185{
186 char p[1200];
187 FILE *f;
188 long sz;
189 char *txt;
190 int v = 0;
191 char *k;
192
193 policy_path(p, sizeof p);
194 f = fopen(p, "rb");
195 if (!f) return 0;
196 fseek(f, 0, SEEK_END);
197 sz = ftell(f);
198 fseek(f, 0, SEEK_SET);
199 if (sz < 0 || sz > 65536) { fclose(f); return 0; }
200 txt = (char *)sx_malloc((size_t)sz + 1);
201 if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) { free(txt); fclose(f); return 0; }
202 txt[sz] = '\0';
203 fclose(f);
204 k = strstr(txt, "\"allow_private\"");
205 if (k) {
206 k += strlen("\"allow_private\"");
207 while (*k && (unsigned char)*k <= ' ') k++;
208 if (*k == ':') {
209 k++;
210 while (*k && (unsigned char)*k <= ' ') k++;
211 if (strncmp(k, "true", 4) == 0) v = 1;
212 }
213 }
214 free(txt);
215 return v;
216}
217
218/* Cached for the process lifetime (the fetch legs ask per request). */
219int fx_policy_allow_private(void)
220{
221 static int cached = -1;
222 if (cached < 0) cached = policy_read_allow_private();
223 return cached;
224}
225
226static int policy_set_allow_private(int on)
227{
228 char dir[1000], p[1200], tmp[1300];
229 FILE *f;
230 connector_dir(dir, sizeof dir);
231 if (!mkdirs(dir)) return 0;
232 policy_path(p, sizeof p);
233 snprintf(tmp, sizeof tmp, "%s.tmp", p);
234 f = fopen(tmp, "wb");
235 if (!f) return 0;
236 fprintf(f, "{\"allow_private\":%s,\"updated_at\":%lld}\n",
237 on ? "true" : "false", (long long)time(NULL));
238 fclose(f);
239 remove(p);
240 if (rename(tmp, p) != 0) { remove(tmp); return 0; }
241 return 1;
242}
243
244/* ------------------------------------------------------------------ */
245/* The fetch engine (shared by --mcp, ?action=fetch and the UI) */
246/* ------------------------------------------------------------------ */
247
248void fetch_tool_run(const char *url, long max_length, long start_index, int raw,
249 tool_result *out)
250{
251 fx_response resp;
252 char *content = NULL; /* heap: what gets chunked */
253 size_t content_len = 0;
254 char prefix[2200];
255 char *title = NULL;
256 size_t title_len = 0;
257
258 memset(out, 0, sizeof *out);
259 prefix[0] = '\0';
260
261 if (!url || !url[0]) {
262 snprintf(out->error, sizeof out->error, "url is required");
263 return;
264 }
265 if (max_length <= 0) max_length = 5000;
266 if (max_length > 100000) max_length = 100000;
267 if (start_index < 0) start_index = 0;
268
269 if (fx_fetch(url, &resp) != 0) {
270 snprintf(out->error, sizeof out->error, "%s",
271 resp.error[0] ? resp.error : "fetch failed");
272 fx_response_free(&resp);
273 return;
274 }
275 out->status = resp.status;
276 snprintf(out->content_type, sizeof out->content_type, "%s", resp.content_type);
277 out->bytes_read = resp.body_len;
278 snprintf(out->final_url, sizeof out->final_url, "%s", resp.url);
279 {
280 size_t cap = resp.body_len;
281 if (cap > 400000) cap = 400000; /* the UI Raw tab only */
282 out->raw_html = fx_strndup(resp.body ? resp.body : "", cap);
283 }
284 out->redirected = resp.hops > 0;
285
286 if (resp.status >= 400) {
287 snprintf(out->error, sizeof out->error,
288 "Failed to fetch %s - status code %d", resp.url, resp.status);
289 fx_response_free(&resp);
290 return;
291 }
292 if (resp.hops > 0)
293 snprintf(prefix, sizeof prefix, "Redirecting from %s to %s\n\n",
294 resp.first_url, resp.url);
295
296 {
297 char ctlower[128];
298 int is_md = 0, is_html = 0;
299 size_t i;
300 const char *ct = resp.content_type;
301 for (i = 0; ct && ct[i] && i < sizeof ctlower - 1; i++)
302 ctlower[i] = (char)tolower((unsigned char)ct[i]);
303 ctlower[i] = '\0';
304 {
305 char *sc = strchr(ctlower, ';');
306 if (sc) *sc = '\0';
307 }
308 is_md = strcmp(ctlower, "text/markdown") == 0;
309 is_html = strstr(ctlower, "text/html") != NULL ||
310 strstr(ctlower, "application/xhtml+xml") != NULL ||
311 (!ctlower[0] && fx_body_looks_like_html(resp.body, resp.body_len));
312
313 if (is_md) {
314 content = fx_strndup(resp.body, resp.body_len);
315 content_len = resp.body_len;
316 prefix[0] = '\0'; /* markdown is returned verbatim */
317 } else if (is_html && !raw) {
318 char *md = fx_html_to_markdown(resp.body, resp.body_len, &content_len);
319 title = fx_html_title(resp.body, resp.body_len, &title_len);
320 if (title && title_len &&
321 !fx_md_starts_with_title(md, content_len, title, title_len)) {
322 size_t hl = 2 + title_len + 2;
323 char *cat = (char *)sx_malloc(hl + content_len + 1);
324 cat[0] = '#'; cat[1] = ' ';
325 memcpy(cat + 2, title, title_len);
326 cat[2 + title_len] = '\n';
327 cat[3 + title_len] = '\n';
328 if (content_len) memcpy(cat + hl, md, content_len);
329 cat[hl + content_len] = '\0';
330 free(md);
331 md = cat;
332 content_len = hl + content_len;
333 }
334 if (title && title_len)
335 snprintf(out->title, sizeof out->title, "%s", title);
336 content = md;
337 if (!content[0] && content_len == 0) {
338 free(content);
339 content = sx_strdup("");
340 }
341 } else {
342 content = fx_strndup(resp.body, resp.body_len);
343 content_len = resp.body_len;
344 if (!raw) {
345 char declared[280];
346 snprintf(declared, sizeof declared,
347 "Content type %s cannot be simplified to markdown, "
348 "but here is the raw content:\n",
349 resp.content_type[0] ? resp.content_type : "(not declared)");
350 {
351 size_t nl = strlen(declared);
352 char *cat = (char *)sx_malloc(nl + content_len + 1);
353 memcpy(cat, declared, nl);
354 if (content_len) memcpy(cat + nl, content, content_len);
355 cat[nl + content_len] = '\0';
356 free(content);
357 content = cat;
358 content_len = nl + content_len;
359 }
360 }
361 }
362 }
363 fx_response_free(&resp);
364 free(title);
365
366 /* Truncation footer, upstream-shaped. */
367 {
368 size_t si = (size_t)start_index;
369 size_t ml = (size_t)max_length;
370 buf_t b;
371 buf_init(&b);
372 buf_addf(&b, "%sContents of %s:\n",
373 prefix, out->final_url[0] ? out->final_url : url);
374 if (si >= content_len) {
375 buf_add(&b, "<error>No more content available.</error>");
376 } else {
377 size_t take = content_len - si;
378 if (take > ml) take = ml;
379 buf_bput(&b, content + si, take);
380 if (take == ml && si + take < content_len)
381 buf_addf(&b, "\n\n<error>Content truncated. Call the fetch tool "
382 "with a start_index of %zu to get more content.</error>",
383 si + take);
384 }
385 out->text = b.p ? b.p : sx_strdup("");
386 out->text_len = b.n;
387 out->content_len = content_len;
388 }
389 free(content);
390 out->ok = 1;
391}
392
393/* ------------------------------------------------------------------ */
394/* --mcp mode */
395/* ------------------------------------------------------------------ */
396
397static const char *FETCH_TOOL_SCHEMA =
398 "{\"type\":\"object\",\"properties\":{"
399 "\"url\":{\"type\":\"string\",\"description\":\"URL to fetch\"},"
400 "\"max_length\":{\"type\":\"integer\",\"description\":\"Maximum number of characters to return.\",\"minimum\":1,\"maximum\":100000},"
401 "\"start_index\":{\"type\":\"integer\",\"description\":\"On return output starting at this character index, useful if a previous fetch was truncated and more context is required.\",\"minimum\":0},"
402 "\"raw\":{\"type\":\"boolean\",\"description\":\"Get the actual HTML content of the requested page, without simplification.\"}"
403 "},\"required\":[\"url\"]}";
404
405static void mcp_tools_list(FILE *out, const char *id_raw)
406{
407 fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[", id_raw);
408 fprintf(out, "{\"name\":\"fetch\",\"description\":\"Fetches a URL from the internet "
409 "and optionally extracts its content as markdown. Follows up to 5 "
410 "redirects, refuses private/loopback/link-local addresses unless the "
411 "operator allows them, and truncates long results with a start_index "
412 "hint.\",\"inputSchema\":%s,"
413 "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,"
414 "\"idempotentHint\":true,\"openWorldHint\":true}}",
415 FETCH_TOOL_SCHEMA);
416 fprintf(out, "]}}\n");
417 fflush(out);
418}
419
420static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params)
421{
422 const char *name = NULL;
423 yyjson_val *args = NULL;
424 const char *url = NULL;
425 long max_length = 5000, start_index = 0;
426 int raw = 0;
427 tool_result r;
428
429 if (params) {
430 yyjson_val *v;
431 name = yyjson_get_str(yyjson_obj_get(params, "name"));
432 args = yyjson_obj_get(params, "arguments");
433 if (args) {
434 url = yyjson_get_str(yyjson_obj_get(args, "url"));
435 v = yyjson_obj_get(args, "max_length");
436 if (yyjson_is_int(v)) max_length = (long)yyjson_get_int(v);
437 else if (yyjson_is_str(v) && yyjson_get_str(v))
438 max_length = atol(yyjson_get_str(v));
439 v = yyjson_obj_get(args, "start_index");
440 if (yyjson_is_int(v)) start_index = (long)yyjson_get_int(v);
441 else if (yyjson_is_str(v) && yyjson_get_str(v))
442 start_index = atol(yyjson_get_str(v));
443 v = yyjson_obj_get(args, "raw");
444 if (yyjson_is_true(v) ||
445 (yyjson_is_str(v) && yyjson_get_str(v) &&
446 strcmp(yyjson_get_str(v), "true") == 0))
447 raw = 1;
448 }
449 }
450 if (!name || strcmp(name, "fetch") != 0) {
451 fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602,"
452 "\"message\":\"unknown tool\"}}\n", id_raw);
453 fflush(out);
454 return;
455 }
456
457 memset(&r, 0, sizeof r);
458 fetch_tool_run(url, max_length, start_index, raw, &r);
459
460 fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":"
461 "[{\"type\":\"text\",\"text\":", id_raw);
462 if (r.ok) {
463 json_escape(out, r.text ? r.text : "");
464 fprintf(out, "}],\"isError\":false}}\n");
465 } else {
466 json_escape(out, r.error[0] ? r.error : "fetch failed");
467 fprintf(out, "}],\"isError\":true}}\n");
468 }
469 fflush(out);
470 tool_result_free(&r);
471}
472
473/* Copy the raw JSON-RPC id token (number or string) so the reply echoes the
474 * same type. */
475static int json_id_raw(const char *line, char *out, size_t outsz)
476{
477 const char *p = strstr(line, "\"id\"");
478 size_t i = 0;
479 if (!p) return 0;
480 p += 4;
481 while (*p && (unsigned char)*p <= ' ') p++;
482 if (*p != ':') return 0;
483 p++;
484 while (*p && (unsigned char)*p <= ' ') p++;
485 if (*p == '"') {
486 out[i++] = *p++;
487 while (*p && i + 2 < outsz) {
488 out[i++] = *p;
489 if (*p == '\\' && p[1]) { p++; out[i++] = *p++; }
490 else if (*p == '"') { p++; out[i++] = '"'; break; }
491 else p++;
492 }
493 out[i] = '\0';
494 return i > 1;
495 }
496 while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') &&
497 i + 1 < outsz)
498 out[i++] = *p++;
499 out[i] = '\0';
500 return i > 0;
501}
502
503static void mcp_server_info(FILE *out, const char *id_raw)
504{
505 fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{"
506 "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}},"
507 "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n",
508 id_raw, PLUGIN_SLUG, PLUGIN_VER);
509 fflush(out);
510}
511
512int run_mcp(void)
513{
514 char line[65536];
515 setvbuf(stdout, NULL, _IOLBF, 0);
516 while (fgets(line, sizeof line, stdin)) {
517 yyjson_doc *doc;
518 yyjson_val *root, *m, *params;
519 const char *method;
520 char id_raw[128] = "";
521
522 if (!strchr(line, '{')) continue;
523 doc = yyjson_read(line, strlen(line), 0);
524 if (!doc) continue;
525 root = yyjson_doc_get_root(doc);
526 m = yyjson_obj_get(root, "method");
527 method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL;
528 params = yyjson_obj_get(root, "params");
529 if (!method) { yyjson_doc_free(doc); continue; }
530 if (strncmp(method, "notifications/", 14) == 0) {
531 yyjson_doc_free(doc);
532 continue;
533 }
534 if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) {
535 yyjson_doc_free(doc);
536 continue;
537 }
538
539 if (strcmp(method, "initialize") == 0) {
540 mcp_server_info(stdout, id_raw);
541 } else if (strcmp(method, "tools/list") == 0) {
542 mcp_tools_list(stdout, id_raw);
543 } else if (strcmp(method, "tools/call") == 0) {
544 mcp_tool_call(stdout, id_raw, params);
545 } else if (strcmp(method, "ping") == 0) {
546 fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw);
547 fflush(stdout);
548 } else {
549 fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601,"
550 "\"message\":\"method not found\"}}\n", id_raw);
551 fflush(stdout);
552 }
553 yyjson_doc_free(doc);
554 }
555 return 0;
556}
557
558/* ------------------------------------------------------------------ */
559/* Discovery metadata */
560/* ------------------------------------------------------------------ */
561
562static int run_meta(void)
563{
564 puts("{\"name\":\"fetch\",\"desc\":\"URL to Markdown\",\"kind\":\"mcp\","
565 "\"mcp\":true,\"daemon\":false,\"menus\":false,\"verified\":\"live\"}");
566 fflush(stdout);
567 return 0;
568}
569
570/* ------------------------------------------------------------------ */
571/* JSON node API */
572/* ------------------------------------------------------------------ */
573
574static void json_headers(void)
575{
576 fputs("Content-Type: application/json; charset=utf-8\r\n"
577 "Cache-Control: no-store\r\n"
578 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
579}
580
581/* Walk the generated page and splice the shared bot theme in at the two
582 * control bytes tools/gen_ui.py left behind: 0x01 becomes the pre-paint
583 * script plus the token stylesheet, 0x02 the sx-theme handoff. Injecting here
584 * (rather than pasting the macros into ui.html) is what keeps the theme from
585 * drifting away from the rest of the bot. */
586static void emit_ui(void)
587{
588 const char *p = UI_HTML;
589
590 while (*p) {
591 if (*p == '\001') {
592 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
593 "</style>", stdout);
594 p++;
595 } else if (*p == '\002') {
596 fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout);
597 p++;
598 } else {
599 putchar(*p++);
600 }
601 }
602}
603
604static char *read_body(void)
605{
606 const char *cl = getenv("CONTENT_LENGTH");
607 long n;
608 char *buf;
609 size_t got = 0;
610 if (!cl || !*cl) return NULL;
611 n = atol(cl);
612 if (n <= 0 || n > 2 * 1024 * 1024) return NULL;
613 buf = (char *)sx_malloc((size_t)n + 1);
614 while (got < (size_t)n) {
615 size_t r = fread(buf + got, 1, (size_t)n - got, stdin);
616 if (r == 0) break;
617 got += r;
618 }
619 buf[got] = '\0';
620 return buf;
621}
622
623static int json_str_field(const char *json, const char *key, char *out, size_t outsz)
624{
625 yyjson_doc *doc;
626 yyjson_val *v;
627 int found = 0;
628 if (!json) return 0;
629 doc = yyjson_read(json, strlen(json), 0);
630 if (!doc) return 0;
631 v = yyjson_obj_get(yyjson_doc_get_root(doc), key);
632 if (yyjson_is_str(v) && yyjson_get_str(v)) {
633 snprintf(out, outsz, "%s", yyjson_get_str(v));
634 found = 1;
635 } else if (yyjson_is_int(v)) {
636 snprintf(out, outsz, "%lld", (long long)yyjson_get_int(v));
637 found = 1;
638 } else if (yyjson_is_bool(v)) {
639 snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false");
640 found = 1;
641 }
642 yyjson_doc_free(doc);
643 return found;
644}
645
646static void emit_tool_json(const tool_result *r, const char *url_arg)
647{
648 json_headers();
649 if (!r->ok) {
650 fputs("{\"ok\":false,\"error\":", stdout);
651 json_escape(stdout, r->error[0] ? r->error : "fetch failed");
652 fputs("}\n", stdout);
653 return;
654 }
655 fputs("{\"ok\":true,\"url\":", stdout);
656 json_escape(stdout, r->final_url[0] ? r->final_url : (url_arg ? url_arg : ""));
657 fprintf(stdout, ",\"status_code\":%d,\"redirected\":%s,\"content_type\":",
658 r->status, r->redirected ? "true" : "false");
659 json_escape(stdout, r->content_type);
660 fprintf(stdout, ",\"bytes_read\":%zu,\"content_length\":%zu,\"title\":",
661 r->bytes_read, r->content_len);
662 if (r->title[0]) json_escape(stdout, r->title); else fputs("null", stdout);
663 fputs(",\"text\":", stdout);
664 json_escape(stdout, r->text ? r->text : "");
665 fputs(",\"raw_html\":", stdout);
666 json_escape(stdout, r->raw_html ? r->raw_html : "");
667 fputs("}\n", stdout);
668}
669
670static void api_info(void)
671{
672 json_headers();
673 fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG
674 "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true,"
675 "\"menus\":false,\"verified\":\"live\",\"tools\":[\"fetch\"],\"tool_schema\":",
676 stdout);
677 fputs(FETCH_TOOL_SCHEMA, stdout);
678 fprintf(stdout, ",\"allow_private\":%s", policy_read_allow_private() ? "true" : "false");
679 fputs(",\"ssrf_policy\":\"private/loopback/link-local/special-purpose refused unless allowed\","
680 "\"tls\":\"verify-peer + CA bundle (POSIX mbedTLS); WinHTTP system root store (Windows)\","
681 "\"max_body_bytes\":", stdout);
682 fprintf(stdout, "%u", FX_MAX_BODY);
683 fputs(",\"max_length_cap\":100000,\"max_redirects\":5}\n", stdout);
684}
685
686static int api_dispatch(const char *action, const char *qs, const char *body)
687{
688 if (!action[0] || strcmp(action, "fetch") == 0) {
689 char url[2048] = "";
690 char nbuf[64] = "";
691 long max_length = 5000, start_index = 0;
692 int raw = 0;
693 tool_result r;
694
695 if (!(body && json_str_field(body, "url", url, sizeof url)) &&
696 !(qs && *qs && get_query_val(qs, "url", url, sizeof url)))
697 url[0] = '\0';
698 if ((qs && *qs && get_query_val(qs, "max_length", nbuf, sizeof nbuf)) ||
699 (body && json_str_field(body, "max_length", nbuf, sizeof nbuf)))
700 max_length = atol(nbuf);
701 if ((qs && *qs && get_query_val(qs, "start_index", nbuf, sizeof nbuf)) ||
702 (body && json_str_field(body, "start_index", nbuf, sizeof nbuf)))
703 start_index = atol(nbuf);
704 if ((qs && *qs && get_query_val(qs, "raw", nbuf, sizeof nbuf)) ||
705 (body && json_str_field(body, "raw", nbuf, sizeof nbuf)))
706 raw = (strcmp(nbuf, "1") == 0 || strcmp(nbuf, "true") == 0);
707
708 memset(&r, 0, sizeof r);
709 fetch_tool_run(url, max_length, start_index, raw, &r);
710 emit_tool_json(&r, url);
711 tool_result_free(&r);
712 return 0;
713 }
714
715 if (strcmp(action, "info") == 0) { api_info(); return 0; }
716
717 if (strcmp(action, "policy") == 0) {
718 char val[16] = "";
719 json_headers();
720 if ((qs && *qs && get_query_val(qs, "allow_private", val, sizeof val)) ||
721 (body && json_str_field(body, "allow_private", val, sizeof val))) {
722 int on = (strcmp(val, "1") == 0 || strcmp(val, "true") == 0);
723 if (!policy_set_allow_private(on)) {
724 fputs("{\"ok\":false,\"error\":\"policy_write_failed\"}\n", stdout);
725 return 0;
726 }
727 fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n",
728 on ? "true" : "false");
729 } else {
730 fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n",
731 policy_read_allow_private() ? "true" : "false");
732 }
733 return 0;
734 }
735
736 json_headers();
737 fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout);
738 return 0;
739}
740
741/* ------------------------------------------------------------------ */
742/* main */
743/* ------------------------------------------------------------------ */
744
745int main(int argc, char **argv)
746{
747 const char *qs;
748 char action[64] = "";
749 char *body = NULL;
750 int have_action = 0;
751
752#if defined(_WIN32)
753 { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI
754 * framing — force binary stdio. */
755 int mode = _O_BINARY;
756 _setmode(_fileno(stdout), mode);
757 _setmode(_fileno(stdin), mode);
758 }
759 {
760 WSADATA wsa;
761 WSAStartup(MAKEWORD(2, 2), &wsa);
762 }
763#endif
764
765 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META"))
766 return run_meta();
767 if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp();
768 if (argc > 1 && strcmp(argv[1], "--schema") == 0) {
769 puts(FETCH_TOOL_SCHEMA);
770 return 0;
771 }
772 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
773 printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
774 return 0;
775 }
776 /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line, reading stdin
777 * when no addresses are given. Pure policy, no DNS and no sockets, so the
778 * suite can assert the whole SSRF matrix (including the IPv6 special
779 * ranges) on a machine with no network at all. */
780 /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line. With no
781 * address arguments it reads them from stdin instead. Pure policy: no DNS
782 * and no sockets, so the suite can assert the whole SSRF matrix
783 * (including the IPv6 special ranges) on a machine with no network at
784 * all, and a named-address call never waits on a terminal. */
785 if (argc > 1 && strcmp(argv[1], "--selftest") == 0) {
786 char line[256];
787 int i;
788 setvbuf(stdout, NULL, _IOLBF, 0);
789 if (argc > 2) {
790 for (i = 2; i < argc; i++)
791 printf("%s denied=%d\n", argv[i], fx_ip_is_denied(argv[i]) ? 1 : 0);
792 return 0;
793 }
794 while (fgets(line, sizeof line, stdin)) {
795 char *p = line, *e;
796 while (*p == ' ' || *p == '\t') p++;
797 e = p + strlen(p);
798 while (e > p && (e[-1] == '\n' || e[-1] == '\r' ||
799 e[-1] == ' ' || e[-1] == '\t')) *--e = '\0';
800 if (*p == '#') continue; /* comment line */
801 printf("%s denied=%d\n", p, fx_ip_is_denied(p) ? 1 : 0);
802 }
803 return 0;
804 }
805 qs = getenv("QUERY_STRING");
806 if (!qs) qs = "";
807
808 have_action = get_query_val(qs, "action", action, sizeof action);
809 {
810 /* ?format=json is the other documented way to ask for the JSON API.
811 * Match it as a whole parameter with an exact value, never as a raw
812 * substring, so a url= parameter that merely contains the text
813 * "format=json" cannot flip the page into the API. */
814 char fmt[24] = "";
815 if (!have_action && get_query_val(qs, "format", fmt, sizeof fmt) &&
816 strcmp(fmt, "json") == 0) {
817 snprintf(action, sizeof action, "fetch");
818 have_action = 1;
819 }
820 }
821
822 {
823 const char *rm = getenv("REQUEST_METHOD");
824 int is_post = rm && strcmp(rm, "POST") == 0;
825 if (have_action || is_post) {
826 require_node_auth();
827 body = read_body();
828 if (body) {
829 char jact[64] = "";
830 if (json_str_field(body, "action", jact, sizeof jact) && jact[0])
831 snprintf(action, sizeof action, "%s", jact);
832 else if (!action[0])
833 snprintf(action, sizeof action, "fetch");
834 } else if (!action[0]) {
835 snprintf(action, sizeof action, "fetch");
836 }
837 return api_dispatch(action, qs, body);
838 }
839 }
840
841 /* HTML UI */
842 fputs("Content-Type: text/html; charset=utf-8\r\n"
843 "Cache-Control: no-store\r\n"
844 "X-Content-Type-Options: nosniff\r\n"
845 "X-Frame-Options: SAMEORIGIN\r\n"
846 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
847 "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
848 "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
849 emit_ui();
850 return 0;
851}