/* * plugin_fetch - SCORPIOX BOT open-source URL fetch & HTML-to-Markdown connector * * One clean-room C99 binary with the four contracts a SCORPIOX BOT connector * plugin implements: * * 1. --meta / SX_PLUGIN_META=1 -> one line of JSON discovery metadata * (unauthenticated, so the node can always discover it) * 2. --mcp -> MCP JSON-RPC 2.0 over stdio: * initialize / notifications/initialized / tools/list / tools/call. * One tool: fetch {url, max_length=5000, start_index=0, raw=false}. * 3. ?action=... (+ POST JSON body) -> JSON node API (node auth required) * 4. GET (default) -> responsive dark/light HTML page: * a URL Preview & Fetch Tester that calls the same engine as --mcp. * * The tool is a clean-room C port of the behaviour of modelcontextprotocol * `servers/src/fetch` (the fetch MCP server): it follows up to 5 redirects * (every hop re-checked), refuses private / loopback / link-local / * special-purpose addresses unless the operator allows them, caps the body it * reads, truncates long results with a start_index footer, returns * markdown/text bodies as-is, and prefixes non-simplifiable bodies with a * "cannot be simplified" notice. The HTML->Markdown converter is the * web-readability-shaped subset in fetch_md.c. * * HTTP/HTTPS transport is built in (no libcurl, no OpenSSL): POSIX uses our * own getaddrinfo + a non-blocking connect to a PRE-VALIDATED IP with * vendored mbedTLS 3.6.7 over custom BIOs (TLS 1.2+; certificate and hostname * verified against a CA bundle — FETCH_TLS_CA_FILE or the first system * bundle; there is deliberately no insecure bypass). _WIN32 uses WinHTTP * (system root store, -lwinhttp) so the static PE needs zero DLLs. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502 and * winhttp/ws2tcpip gate helpers on newer values; Apple needs _DARWIN_C_SOURCE * under -std=c99; MinGW needs its printf for %zu. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) # define _DARWIN_C_SOURCE 1 #endif #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) # define __USE_MINGW_ANSI_STDIO 1 #endif #include #include #include #include #include #if defined(_WIN32) /* MinGW splits what one POSIX header covers into three: declares * _setmode/_fileno, declares the _O_* constants _setmode takes, * declares _mkdir. windows.h pulls in none of them. */ # include # include # include # include #endif #include #include #include "bot_theme_plugin.h" #include "ui_html.h" #include "fetch_http.h" #include "fetch_md.h" #include "sxmcp.h" #define PLUGIN_SLUG "fetch" #define PLUGIN_ID "plugin_fetch" #define PLUGIN_VER "1.0.0" #if defined(_WIN32) # define sx_mkdir(p) _mkdir(p) # define SX_PATHSEP '\\' #else # include # define sx_mkdir(p) mkdir((p), 0755) # define SX_PATHSEP '/' #endif void tool_result_free(tool_result *r) { if (!r) return; free(r->text); free(r->raw_html); memset(r, 0, sizeof *r); } /* ------------------------------------------------------------------ */ /* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and the */ /* HTML page never call this; every JSON action does. */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth; char qpwd[256] = {0}; const char *qs; if (!np || !*np) return; /* open node: no gate */ xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (sx_strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Connector dir + persisted policy */ /* ------------------------------------------------------------------ */ static void connector_dir(char *out, size_t outsz) { const char *env = getenv("SX_CONNECTOR_DIR"); struct stat st; if (env && *env) { snprintf(out, outsz, "%s", env); return; } if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && access("/workspace", W_OK) == 0) { snprintf(out, outsz, "/workspace/.scorpiox/connectors/fetch"); return; } #if defined(_WIN32) { const char *la = getenv("LOCALAPPDATA"); if (la && *la) { snprintf(out, outsz, "%s\\scorpiox\\connectors\\fetch", la); return; } } #endif { const char *home = getenv("HOME"); if (!home || !*home) home = "/root"; snprintf(out, outsz, "%s/.scorpiox/connectors/fetch", home); } } static int mkdirs(const char *path) { char buf[1200]; size_t i, n; struct stat st; snprintf(buf, sizeof buf, "%s", path); n = strlen(buf); for (i = 1; i < n; i++) { if (buf[i] == '/' || buf[i] == '\\') { char save = buf[i]; buf[i] = '\0'; if (i > 2) sx_mkdir(buf); buf[i] = save; } } sx_mkdir(buf); return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); } static void policy_path(char *out, size_t outsz) { char dir[1000]; connector_dir(dir, sizeof dir); snprintf(out, outsz, "%s%cconfig.json", dir, SX_PATHSEP); } static int policy_read_allow_private(void) { char p[1200]; FILE *f; long sz; char *txt; int v = 0; char *k; policy_path(p, sizeof p); f = fopen(p, "rb"); if (!f) return 0; fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz < 0 || sz > 65536) { fclose(f); return 0; } txt = (char *)sx_malloc((size_t)sz + 1); if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) { free(txt); fclose(f); return 0; } txt[sz] = '\0'; fclose(f); k = strstr(txt, "\"allow_private\""); if (k) { k += strlen("\"allow_private\""); while (*k && (unsigned char)*k <= ' ') k++; if (*k == ':') { k++; while (*k && (unsigned char)*k <= ' ') k++; if (strncmp(k, "true", 4) == 0) v = 1; } } free(txt); return v; } /* Cached for the process lifetime (the fetch legs ask per request). */ int fx_policy_allow_private(void) { static int cached = -1; if (cached < 0) cached = policy_read_allow_private(); return cached; } static int policy_set_allow_private(int on) { char dir[1000], p[1200], tmp[1300]; FILE *f; connector_dir(dir, sizeof dir); if (!mkdirs(dir)) return 0; policy_path(p, sizeof p); snprintf(tmp, sizeof tmp, "%s.tmp", p); f = fopen(tmp, "wb"); if (!f) return 0; fprintf(f, "{\"allow_private\":%s,\"updated_at\":%lld}\n", on ? "true" : "false", (long long)time(NULL)); fclose(f); remove(p); if (rename(tmp, p) != 0) { remove(tmp); return 0; } return 1; } /* ------------------------------------------------------------------ */ /* The fetch engine (shared by --mcp, ?action=fetch and the UI) */ /* ------------------------------------------------------------------ */ void fetch_tool_run(const char *url, long max_length, long start_index, int raw, tool_result *out) { fx_response resp; char *content = NULL; /* heap: what gets chunked */ size_t content_len = 0; char prefix[2200]; char *title = NULL; size_t title_len = 0; memset(out, 0, sizeof *out); prefix[0] = '\0'; if (!url || !url[0]) { snprintf(out->error, sizeof out->error, "url is required"); return; } if (max_length <= 0) max_length = 5000; if (max_length > 100000) max_length = 100000; if (start_index < 0) start_index = 0; if (fx_fetch(url, &resp) != 0) { snprintf(out->error, sizeof out->error, "%s", resp.error[0] ? resp.error : "fetch failed"); fx_response_free(&resp); return; } out->status = resp.status; snprintf(out->content_type, sizeof out->content_type, "%s", resp.content_type); out->bytes_read = resp.body_len; snprintf(out->final_url, sizeof out->final_url, "%s", resp.url); { size_t cap = resp.body_len; if (cap > 400000) cap = 400000; /* the UI Raw tab only */ out->raw_html = fx_strndup(resp.body ? resp.body : "", cap); } out->redirected = resp.hops > 0; if (resp.status >= 400) { snprintf(out->error, sizeof out->error, "Failed to fetch %s - status code %d", resp.url, resp.status); fx_response_free(&resp); return; } if (resp.hops > 0) snprintf(prefix, sizeof prefix, "Redirecting from %s to %s\n\n", resp.first_url, resp.url); { char ctlower[128]; int is_md = 0, is_html = 0; size_t i; const char *ct = resp.content_type; for (i = 0; ct && ct[i] && i < sizeof ctlower - 1; i++) ctlower[i] = (char)tolower((unsigned char)ct[i]); ctlower[i] = '\0'; { char *sc = strchr(ctlower, ';'); if (sc) *sc = '\0'; } is_md = strcmp(ctlower, "text/markdown") == 0; is_html = strstr(ctlower, "text/html") != NULL || strstr(ctlower, "application/xhtml+xml") != NULL || (!ctlower[0] && fx_body_looks_like_html(resp.body, resp.body_len)); if (is_md) { content = fx_strndup(resp.body, resp.body_len); content_len = resp.body_len; prefix[0] = '\0'; /* markdown is returned verbatim */ } else if (is_html && !raw) { char *md = fx_html_to_markdown(resp.body, resp.body_len, &content_len); title = fx_html_title(resp.body, resp.body_len, &title_len); if (title && title_len && !fx_md_starts_with_title(md, content_len, title, title_len)) { size_t hl = 2 + title_len + 2; char *cat = (char *)sx_malloc(hl + content_len + 1); cat[0] = '#'; cat[1] = ' '; memcpy(cat + 2, title, title_len); cat[2 + title_len] = '\n'; cat[3 + title_len] = '\n'; if (content_len) memcpy(cat + hl, md, content_len); cat[hl + content_len] = '\0'; free(md); md = cat; content_len = hl + content_len; } if (title && title_len) snprintf(out->title, sizeof out->title, "%s", title); content = md; if (!content[0] && content_len == 0) { free(content); content = sx_strdup(""); } } else { content = fx_strndup(resp.body, resp.body_len); content_len = resp.body_len; if (!raw) { char declared[280]; snprintf(declared, sizeof declared, "Content type %s cannot be simplified to markdown, " "but here is the raw content:\n", resp.content_type[0] ? resp.content_type : "(not declared)"); { size_t nl = strlen(declared); char *cat = (char *)sx_malloc(nl + content_len + 1); memcpy(cat, declared, nl); if (content_len) memcpy(cat + nl, content, content_len); cat[nl + content_len] = '\0'; free(content); content = cat; content_len = nl + content_len; } } } } fx_response_free(&resp); free(title); /* Truncation footer, upstream-shaped. */ { size_t si = (size_t)start_index; size_t ml = (size_t)max_length; buf_t b; buf_init(&b); buf_addf(&b, "%sContents of %s:\n", prefix, out->final_url[0] ? out->final_url : url); if (si >= content_len) { buf_add(&b, "No more content available."); } else { size_t take = content_len - si; if (take > ml) take = ml; buf_bput(&b, content + si, take); if (take == ml && si + take < content_len) buf_addf(&b, "\n\nContent truncated. Call the fetch tool " "with a start_index of %zu to get more content.", si + take); } out->text = b.p ? b.p : sx_strdup(""); out->text_len = b.n; out->content_len = content_len; } free(content); out->ok = 1; } /* ------------------------------------------------------------------ */ /* --mcp mode */ /* ------------------------------------------------------------------ */ static const char *FETCH_TOOL_SCHEMA = "{\"type\":\"object\",\"properties\":{" "\"url\":{\"type\":\"string\",\"description\":\"URL to fetch\"}," "\"max_length\":{\"type\":\"integer\",\"description\":\"Maximum number of characters to return.\",\"minimum\":1,\"maximum\":100000}," "\"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}," "\"raw\":{\"type\":\"boolean\",\"description\":\"Get the actual HTML content of the requested page, without simplification.\"}" "},\"required\":[\"url\"]}"; static void mcp_tools_list(FILE *out, const char *id_raw) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[", id_raw); fprintf(out, "{\"name\":\"fetch\",\"description\":\"Fetches a URL from the internet " "and optionally extracts its content as markdown. Follows up to 5 " "redirects, refuses private/loopback/link-local addresses unless the " "operator allows them, and truncates long results with a start_index " "hint.\",\"inputSchema\":%s," "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false," "\"idempotentHint\":true,\"openWorldHint\":true}}", FETCH_TOOL_SCHEMA); fprintf(out, "]}}\n"); fflush(out); } static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params) { const char *name = NULL; yyjson_val *args = NULL; const char *url = NULL; long max_length = 5000, start_index = 0; int raw = 0; tool_result r; if (params) { yyjson_val *v; name = yyjson_get_str(yyjson_obj_get(params, "name")); args = yyjson_obj_get(params, "arguments"); if (args) { url = yyjson_get_str(yyjson_obj_get(args, "url")); v = yyjson_obj_get(args, "max_length"); if (yyjson_is_int(v)) max_length = (long)yyjson_get_int(v); else if (yyjson_is_str(v) && yyjson_get_str(v)) max_length = atol(yyjson_get_str(v)); v = yyjson_obj_get(args, "start_index"); if (yyjson_is_int(v)) start_index = (long)yyjson_get_int(v); else if (yyjson_is_str(v) && yyjson_get_str(v)) start_index = atol(yyjson_get_str(v)); v = yyjson_obj_get(args, "raw"); if (yyjson_is_true(v) || (yyjson_is_str(v) && yyjson_get_str(v) && strcmp(yyjson_get_str(v), "true") == 0)) raw = 1; } } if (!name || strcmp(name, "fetch") != 0) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," "\"message\":\"unknown tool\"}}\n", id_raw); fflush(out); return; } memset(&r, 0, sizeof r); fetch_tool_run(url, max_length, start_index, raw, &r); fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" "[{\"type\":\"text\",\"text\":", id_raw); if (r.ok) { json_escape(out, r.text ? r.text : ""); fprintf(out, "}],\"isError\":false}}\n"); } else { json_escape(out, r.error[0] ? r.error : "fetch failed"); fprintf(out, "}],\"isError\":true}}\n"); } fflush(out); tool_result_free(&r); } /* Copy the raw JSON-RPC id token (number or string) so the reply echoes the * same type. */ static int json_id_raw(const char *line, char *out, size_t outsz) { const char *p = strstr(line, "\"id\""); size_t i = 0; if (!p) return 0; p += 4; while (*p && (unsigned char)*p <= ' ') p++; if (*p != ':') return 0; p++; while (*p && (unsigned char)*p <= ' ') p++; if (*p == '"') { out[i++] = *p++; while (*p && i + 2 < outsz) { out[i++] = *p; if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } else if (*p == '"') { p++; out[i++] = '"'; break; } else p++; } out[i] = '\0'; return i > 1; } while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; return i > 0; } static void mcp_server_info(FILE *out, const char *id_raw) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", id_raw, PLUGIN_SLUG, PLUGIN_VER); fflush(out); } int run_mcp(void) { char line[65536]; setvbuf(stdout, NULL, _IOLBF, 0); while (fgets(line, sizeof line, stdin)) { yyjson_doc *doc; yyjson_val *root, *m, *params; const char *method; char id_raw[128] = ""; if (!strchr(line, '{')) continue; doc = yyjson_read(line, strlen(line), 0); if (!doc) continue; root = yyjson_doc_get_root(doc); m = yyjson_obj_get(root, "method"); method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; params = yyjson_obj_get(root, "params"); if (!method) { yyjson_doc_free(doc); continue; } if (strncmp(method, "notifications/", 14) == 0) { yyjson_doc_free(doc); continue; } if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { yyjson_doc_free(doc); continue; } if (strcmp(method, "initialize") == 0) { mcp_server_info(stdout, id_raw); } else if (strcmp(method, "tools/list") == 0) { mcp_tools_list(stdout, id_raw); } else if (strcmp(method, "tools/call") == 0) { mcp_tool_call(stdout, id_raw, params); } else if (strcmp(method, "ping") == 0) { fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); fflush(stdout); } else { fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," "\"message\":\"method not found\"}}\n", id_raw); fflush(stdout); } yyjson_doc_free(doc); } return 0; } /* ------------------------------------------------------------------ */ /* Discovery metadata */ /* ------------------------------------------------------------------ */ static int run_meta(void) { puts("{\"name\":\"fetch\",\"desc\":\"URL to Markdown\",\"kind\":\"mcp\"," "\"mcp\":true,\"daemon\":false,\"menus\":false,\"verified\":\"live\"}"); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* JSON node API */ /* ------------------------------------------------------------------ */ static void json_headers(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } /* Walk the generated page and splice the shared bot theme in at the two * control bytes tools/gen_ui.py left behind: 0x01 becomes the pre-paint * script plus the token stylesheet, 0x02 the sx-theme handoff. Injecting here * (rather than pasting the macros into ui.html) is what keeps the theme from * drifting away from the rest of the bot. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); p++; } else { putchar(*p++); } } } static char *read_body(void) { const char *cl = getenv("CONTENT_LENGTH"); long n; char *buf; size_t got = 0; if (!cl || !*cl) return NULL; n = atol(cl); if (n <= 0 || n > 2 * 1024 * 1024) return NULL; buf = (char *)sx_malloc((size_t)n + 1); while (got < (size_t)n) { size_t r = fread(buf + got, 1, (size_t)n - got, stdin); if (r == 0) break; got += r; } buf[got] = '\0'; return buf; } static int json_str_field(const char *json, const char *key, char *out, size_t outsz) { yyjson_doc *doc; yyjson_val *v; int found = 0; if (!json) return 0; doc = yyjson_read(json, strlen(json), 0); if (!doc) return 0; v = yyjson_obj_get(yyjson_doc_get_root(doc), key); if (yyjson_is_str(v) && yyjson_get_str(v)) { snprintf(out, outsz, "%s", yyjson_get_str(v)); found = 1; } else if (yyjson_is_int(v)) { snprintf(out, outsz, "%lld", (long long)yyjson_get_int(v)); found = 1; } else if (yyjson_is_bool(v)) { snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); found = 1; } yyjson_doc_free(doc); return found; } static void emit_tool_json(const tool_result *r, const char *url_arg) { json_headers(); if (!r->ok) { fputs("{\"ok\":false,\"error\":", stdout); json_escape(stdout, r->error[0] ? r->error : "fetch failed"); fputs("}\n", stdout); return; } fputs("{\"ok\":true,\"url\":", stdout); json_escape(stdout, r->final_url[0] ? r->final_url : (url_arg ? url_arg : "")); fprintf(stdout, ",\"status_code\":%d,\"redirected\":%s,\"content_type\":", r->status, r->redirected ? "true" : "false"); json_escape(stdout, r->content_type); fprintf(stdout, ",\"bytes_read\":%zu,\"content_length\":%zu,\"title\":", r->bytes_read, r->content_len); if (r->title[0]) json_escape(stdout, r->title); else fputs("null", stdout); fputs(",\"text\":", stdout); json_escape(stdout, r->text ? r->text : ""); fputs(",\"raw_html\":", stdout); json_escape(stdout, r->raw_html ? r->raw_html : ""); fputs("}\n", stdout); } static void api_info(void) { json_headers(); fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," "\"menus\":false,\"verified\":\"live\",\"tools\":[\"fetch\"],\"tool_schema\":", stdout); fputs(FETCH_TOOL_SCHEMA, stdout); fprintf(stdout, ",\"allow_private\":%s", policy_read_allow_private() ? "true" : "false"); fputs(",\"ssrf_policy\":\"private/loopback/link-local/special-purpose refused unless allowed\"," "\"tls\":\"verify-peer + CA bundle (POSIX mbedTLS); WinHTTP system root store (Windows)\"," "\"max_body_bytes\":", stdout); fprintf(stdout, "%u", FX_MAX_BODY); fputs(",\"max_length_cap\":100000,\"max_redirects\":5}\n", stdout); } static int api_dispatch(const char *action, const char *qs, const char *body) { if (!action[0] || strcmp(action, "fetch") == 0) { char url[2048] = ""; char nbuf[64] = ""; long max_length = 5000, start_index = 0; int raw = 0; tool_result r; if (!(body && json_str_field(body, "url", url, sizeof url)) && !(qs && *qs && get_query_val(qs, "url", url, sizeof url))) url[0] = '\0'; if ((qs && *qs && get_query_val(qs, "max_length", nbuf, sizeof nbuf)) || (body && json_str_field(body, "max_length", nbuf, sizeof nbuf))) max_length = atol(nbuf); if ((qs && *qs && get_query_val(qs, "start_index", nbuf, sizeof nbuf)) || (body && json_str_field(body, "start_index", nbuf, sizeof nbuf))) start_index = atol(nbuf); if ((qs && *qs && get_query_val(qs, "raw", nbuf, sizeof nbuf)) || (body && json_str_field(body, "raw", nbuf, sizeof nbuf))) raw = (strcmp(nbuf, "1") == 0 || strcmp(nbuf, "true") == 0); memset(&r, 0, sizeof r); fetch_tool_run(url, max_length, start_index, raw, &r); emit_tool_json(&r, url); tool_result_free(&r); return 0; } if (strcmp(action, "info") == 0) { api_info(); return 0; } if (strcmp(action, "policy") == 0) { char val[16] = ""; json_headers(); if ((qs && *qs && get_query_val(qs, "allow_private", val, sizeof val)) || (body && json_str_field(body, "allow_private", val, sizeof val))) { int on = (strcmp(val, "1") == 0 || strcmp(val, "true") == 0); if (!policy_set_allow_private(on)) { fputs("{\"ok\":false,\"error\":\"policy_write_failed\"}\n", stdout); return 0; } fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", on ? "true" : "false"); } else { fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", policy_read_allow_private() ? "true" : "false"); } return 0; } json_headers(); fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); return 0; } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64] = ""; char *body = NULL; int have_action = 0; #if defined(_WIN32) { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI * framing — force binary stdio. */ int mode = _O_BINARY; _setmode(_fileno(stdout), mode); _setmode(_fileno(stdin), mode); } { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); } #endif if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) return run_meta(); if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); if (argc > 1 && strcmp(argv[1], "--schema") == 0) { puts(FETCH_TOOL_SCHEMA); return 0; } if (argc > 1 && strcmp(argv[1], "--version") == 0) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } /* --selftest [addr ...] -> " denied=<0|1>" per line, reading stdin * when no addresses are given. Pure policy, no DNS and no sockets, so the * suite can assert the whole SSRF matrix (including the IPv6 special * ranges) on a machine with no network at all. */ /* --selftest [addr ...] -> " denied=<0|1>" per line. With no * address arguments it reads them from stdin instead. Pure policy: no DNS * and no sockets, so the suite can assert the whole SSRF matrix * (including the IPv6 special ranges) on a machine with no network at * all, and a named-address call never waits on a terminal. */ if (argc > 1 && strcmp(argv[1], "--selftest") == 0) { char line[256]; int i; setvbuf(stdout, NULL, _IOLBF, 0); if (argc > 2) { for (i = 2; i < argc; i++) printf("%s denied=%d\n", argv[i], fx_ip_is_denied(argv[i]) ? 1 : 0); return 0; } while (fgets(line, sizeof line, stdin)) { char *p = line, *e; while (*p == ' ' || *p == '\t') p++; e = p + strlen(p); while (e > p && (e[-1] == '\n' || e[-1] == '\r' || e[-1] == ' ' || e[-1] == '\t')) *--e = '\0'; if (*p == '#') continue; /* comment line */ printf("%s denied=%d\n", p, fx_ip_is_denied(p) ? 1 : 0); } return 0; } qs = getenv("QUERY_STRING"); if (!qs) qs = ""; have_action = get_query_val(qs, "action", action, sizeof action); { /* ?format=json is the other documented way to ask for the JSON API. * Match it as a whole parameter with an exact value, never as a raw * substring, so a url= parameter that merely contains the text * "format=json" cannot flip the page into the API. */ char fmt[24] = ""; if (!have_action && get_query_val(qs, "format", fmt, sizeof fmt) && strcmp(fmt, "json") == 0) { snprintf(action, sizeof action, "fetch"); have_action = 1; } } { const char *rm = getenv("REQUEST_METHOD"); int is_post = rm && strcmp(rm, "POST") == 0; if (have_action || is_post) { require_node_auth(); body = read_body(); if (body) { char jact[64] = ""; if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) snprintf(action, sizeof action, "%s", jact); else if (!action[0]) snprintf(action, sizeof action, "fetch"); } else if (!action[0]) { snprintf(action, sizeof action, "fetch"); } return api_dispatch(action, qs, body); } } /* HTML UI */ fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); return 0; }