| 1 | 1 | new file mode 100644 |
| index 0000000..d2681cd | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,19 @@ | ||
| 1 | +# build artefacts | |
| 2 | +plugin_fetch | |
| 3 | +plugin_fetch.exe | |
| 4 | +plugin_fetch.musl | |
| 5 | +plugin_fetch.arm64 | |
| 6 | +plugin_fetch-asan | |
| 7 | +plugin_fetch-fortify | |
| 8 | +plugin_fetch-zlib | |
| 9 | +plugin_fetch.asan | |
| 10 | +*.o | |
| 11 | +bin/ | |
| 12 | + | |
| 13 | +# local scratch | |
| 14 | +*.tmp | |
| 15 | +*.log | |
| 16 | + | |
| 17 | +# python tooling | |
| 18 | +__pycache__/ | |
| 19 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..a5f77e5 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,33 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. | |
| 22 | + | |
| 23 | +--- | |
| 24 | + | |
| 25 | +This plugin vendors third-party sources under `vendor/`: | |
| 26 | + | |
| 27 | +* **yyjson** (MIT) — `vendor/yyjson.{c,h}`, upstream `ibireme/yyjson`. | |
| 28 | + Its MIT text is reproduced in `vendor/LICENSE.yyjson.txt`. | |
| 29 | +* **mbedTLS 3.6.7** (Apache-2.0 OR GPL-2.0-or-later) — `vendor/mbedtlslib/` | |
| 30 | + with the public headers flattened into `vendor/mbedtls/` and `vendor/psa/`, | |
| 31 | + upstream `Mbed-TLS/mbedtls`. Its Apache-2.0 text is reproduced in | |
| 32 | + `vendor/LICENSE.mbedtls.txt`. On `_WIN32` the HTTP and TLS legs go through | |
| 33 | + WinHTTP instead, so no mbedTLS code is reached in the Windows artefact. |
| 1 | 1 | new file mode 100644 |
| index 0000000..c2eb53a | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,142 @@ | ||
| 1 | +# plugin_fetch - SCORPIOX BOT open-source URL fetch & HTML-to-Markdown MCP connector | |
| 2 | +# | |
| 3 | +# Zero runtime dependencies on every artefact. The only third-party C in the | |
| 4 | +# tree is vendored under vendor/: yyjson (MIT) and the mbedTLS 3.6.7 library | |
| 5 | +# (Apache-2.0) whose sources sit in vendor/mbedtlslib with their public | |
| 6 | +# headers flattened into vendor/mbedtls and vendor/psa. On _WIN32 the HTTP and | |
| 7 | +# TLS legs are WinHTTP instead, so the static PE needs no extra DLLs and no | |
| 8 | +# crypto objects are reached. | |
| 9 | +# | |
| 10 | +# The multi-arch dist publish lives in scorpiox-cli-botplugin (it owns the | |
| 11 | +# musl / aarch64 / MinGW / macOS toolchains, the dist upload and the plugingit | |
| 12 | +# mirror) - see release-dist.sh. That tool compiles every src/**/*.c and | |
| 13 | +# vendor/**/*.c with -I src and -I vendor, which is exactly what `make native` | |
| 14 | +# reproduces here. | |
| 15 | +# | |
| 16 | +# Targets: | |
| 17 | +# make native build -> ./plugin_fetch | |
| 18 | +# make musl static musl x86_64 -> ./plugin_fetch.musl | |
| 19 | +# make arm64 static arm64 musl -> ./plugin_fetch.arm64 | |
| 20 | +# make win64 MinGW-w64 static -> ./plugin_fetch.exe | |
| 21 | +# make macos Apple clang -> ./plugin_fetch (run this on macOS) | |
| 22 | +# make asan ASan + UBSan + leaks -> ./plugin_fetch-asan | |
| 23 | +# make fortify -D_FORTIFY_SOURCE=2 -> ./plugin_fetch-fortify | |
| 24 | +# make zlib native build with gzip support (-DHAVE_ZLIB -lz) | |
| 25 | +# make objs the cached mbedTLS object set (fast incremental dev builds) | |
| 26 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 27 | +# make test build + run tests/run.sh | |
| 28 | +# make e2e build + run tests/e2e.py (Playwright) | |
| 29 | +# make clean | |
| 30 | + | |
| 31 | +CC ?= cc | |
| 32 | +WARN := -Wall -Wextra -Wno-overlength-strings | |
| 33 | +STD := -std=c99 | |
| 34 | +INCLUDES := -I src -I vendor -I vendor/mbedtlslib | |
| 35 | +CFLAGS ?= -O2 $(STD) $(WARN) $(INCLUDES) | |
| 36 | +LDFLAGS ?= | |
| 37 | +MUSL_CC ?= musl-gcc | |
| 38 | +MUSL_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 39 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 40 | +ARM_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 41 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 42 | +WIN_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | |
| 43 | +WIN_LIBS := -lwinhttp -lws2_32 -lbcrypt -lcrypt32 | |
| 44 | + | |
| 45 | +SRC_C := $(wildcard src/*.c) | |
| 46 | +VENDOR_C := $(wildcard vendor/*.c) $(wildcard vendor/mbedtlslib/*.c) | |
| 47 | +UI_SRC := src/ui.html | |
| 48 | +UI_HDR := src/ui_html.h | |
| 49 | +BIN := plugin_fetch | |
| 50 | +EXE := plugin_fetch.exe | |
| 51 | +OBJS := /tmp/fetch-objs | |
| 52 | + | |
| 53 | +.PHONY: all native musl arm64 win64 macos asan fortify zlib objs ui test e2e clean help | |
| 54 | + | |
| 55 | +all: native | |
| 56 | + | |
| 57 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 58 | + @echo "==> regenerating $(UI_HDR)" | |
| 59 | + python3 tools/gen_ui.py | |
| 60 | + | |
| 61 | +ui: $(UI_HDR) | |
| 62 | + | |
| 63 | +native: $(BIN) | |
| 64 | + | |
| 65 | +$(BIN): $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 66 | + @echo "==> native build ($(CC))" | |
| 67 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC_C) $(VENDOR_C) $(LDFLAGS) | |
| 68 | + | |
| 69 | +# Static musl build - the universal Linux artefact (Alpine, Debian, Arch, Omarchy) | |
| 70 | +musl: $(BIN).musl | |
| 71 | + | |
| 72 | +$(BIN).musl: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 73 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 74 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC_C) $(VENDOR_C) | |
| 75 | + | |
| 76 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 77 | +arm64: $(BIN).arm64 | |
| 78 | + | |
| 79 | +$(BIN).arm64: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 80 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 81 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC_C) $(VENDOR_C) | |
| 82 | + | |
| 83 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 84 | +win64: $(EXE) | |
| 85 | + | |
| 86 | +$(EXE): $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 87 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 88 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC_C) $(VENDOR_C) $(WIN_LIBS) | |
| 89 | + | |
| 90 | +# Apple clang build (run this on macOS; the CLI does it over ssh otherwise) | |
| 91 | +macos: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 92 | + @echo "==> Apple clang build" | |
| 93 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC_C) $(VENDOR_C) | |
| 94 | + | |
| 95 | +# Sanitizer build - tests/run.sh drives the whole surface through this binary | |
| 96 | +asan: $(BIN)-asan | |
| 97 | + | |
| 98 | +$(BIN)-asan: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 99 | + @echo "==> ASan + UBSan build" | |
| 100 | + $(CC) -O1 -g $(STD) $(WARN) $(INCLUDES) -fsanitize=address,undefined \ | |
| 101 | + -fno-omit-frame-pointer -o $(BIN)-asan $(SRC_C) $(VENDOR_C) | |
| 102 | + | |
| 103 | +fortify: $(BIN)-fortify | |
| 104 | + | |
| 105 | +$(BIN)-fortify: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 106 | + @echo "==> _FORTIFY_SOURCE=2 build" | |
| 107 | + $(CC) -O2 $(STD) $(WARN) $(INCLUDES) -D_FORTIFY_SOURCE=2 \ | |
| 108 | + -o $(BIN)-fortify $(SRC_C) $(VENDOR_C) | |
| 109 | + | |
| 110 | +# Optional gzip support. The published artefacts deliberately do NOT link it | |
| 111 | +# (a plugin must stay standalone); this target exists so the suite can prove | |
| 112 | +# the decoding path works when the library happens to be present. | |
| 113 | +zlib: $(SRC_C) $(UI_HDR) $(VENDOR_C) | |
| 114 | + @echo "==> native build with gzip support" | |
| 115 | + $(CC) $(CFLAGS) -DHAVE_ZLIB -o $(BIN)-zlib $(SRC_C) $(VENDOR_C) -lz | |
| 116 | + | |
| 117 | +# Cached mbedTLS objects for the fast development loop (dev-build.sh uses them). | |
| 118 | +objs: | |
| 119 | + @mkdir -p $(OBJS) | |
| 120 | + @ls $(VENDOR_C) | while read -r f; do \ | |
| 121 | + o=$(OBJS)/$$(basename "$${f%.c}").o; \ | |
| 122 | + if [ ! -f "$$o" ] || [ "$$f" -nt "$$o" ]; then \ | |
| 123 | + echo "$$f"; \ | |
| 124 | + fi; \ | |
| 125 | + done | xargs -P $$(nproc) -I{} sh -c \ | |
| 126 | + '$(CC) -O2 -w $(INCLUDES) -c "{}" -o $(OBJS)/$$(basename "{}" .c).o' | |
| 127 | + @echo "==> cached $(words $(VENDOR_C)) vendor objects in $(OBJS)" | |
| 128 | + | |
| 129 | +test: native | |
| 130 | + @sh tests/run.sh | |
| 131 | + | |
| 132 | +e2e: native | |
| 133 | + @python3 tests/e2e.py | |
| 134 | + | |
| 135 | +clean: | |
| 136 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify \ | |
| 137 | + $(BIN)-zlib $(BIN).asan *.o | |
| 138 | + rm -rf bin tests/__pycache__ | |
| 139 | + | |
| 140 | +help: | |
| 141 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan |" | |
| 142 | + @echo "make fortify | make zlib | make objs | make ui | make test | make e2e | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..a12db81 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,266 @@ | ||
| 1 | +# fetch — URL fetch & HTML-to-Markdown MCP connector for SCORPIOX BOT | |
| 2 | + | |
| 3 | +`plugin_fetch` is a clean-room, zero-dependency **pure C99** rewrite of the | |
| 4 | +tool surface of | |
| 5 | +[`modelcontextprotocol/servers` → `src/fetch`](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch) | |
| 6 | +plus the readability-shaped HTML→Markdown subset of | |
| 7 | +[`openclaw/openclaw` → `extensions/web-readability`](https://github.com/openclaw/openclaw), | |
| 8 | +reshaped as a **SCORPIOX BOT connector plugin**: one binary, four modes, no | |
| 9 | +shared-library requirements, and a security model you can actually read. | |
| 10 | + | |
| 11 | +Give it a URL, get clean Markdown back — with the boilerplate gone and long | |
| 12 | +documents chunked so an agent can page through a page instead of flooding its | |
| 13 | +context window. | |
| 14 | + | |
| 15 | +| | | | |
| 16 | +|---|---| | |
| 17 | +| Slug | `fetch` | | |
| 18 | +| Binary | `plugin_fetch` (`plugin_fetch.exe` on Windows) | | |
| 19 | +| `--meta` | `{"name":"fetch","desc":"URL to Markdown","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` | | |
| 20 | +| Category | `network` | | |
| 21 | +| Kind | MCP connector (`--mcp`, stdio JSON-RPC 2.0) | | |
| 22 | +| License | MIT (vendored yyjson MIT, mbedTLS 3.6.7 Apache-2.0) | | |
| 23 | + | |
| 24 | +## Modes | |
| 25 | + | |
| 26 | +| Mode | Trigger | Who calls it | | |
| 27 | +|---|---|---| | |
| 28 | +| Discovery | `--meta` / `SX_PLUGIN_META=1` | `scorpiox-bot-api` `/plugins`, `scorpiox-cli-botplugin`, `sx-connector-mcp` | | |
| 29 | +| MCP tool | `--mcp` | `sx-connector-mcp` (the single MCP router) or any MCP client over stdio | | |
| 30 | +| Control API | `?action=…` / `?format=json` | the plugin page (behind `require_node_auth()`) | | |
| 31 | +| Setup / tester page | `GET` | the browser, via the hub or the node directly | | |
| 32 | + | |
| 33 | +```sh | |
| 34 | +./plugin_fetch --meta | |
| 35 | +printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./plugin_fetch --mcp | |
| 36 | +make && make test && make e2e | |
| 37 | +``` | |
| 38 | + | |
| 39 | +## The tool | |
| 40 | + | |
| 41 | +One tool, `fetch`, with the same parameter shape as upstream so prompts and | |
| 42 | +agent code written against the Python reference work unchanged: | |
| 43 | + | |
| 44 | +| Argument | Type | Default | Meaning | | |
| 45 | +|---|---|---|---| | |
| 46 | +| `url` | string | *required* | must be `http://` or `https://` | | |
| 47 | +| `max_length` | integer | `5000` | characters to return, hard cap `100000` | | |
| 48 | +| `start_index` | integer | `0` | continue a truncated document here | | |
| 49 | +| `raw` | boolean | `false` | return the original HTML instead of converting | | |
| 50 | + | |
| 51 | +```sh | |
| 52 | +printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"https://example.com","max_length":2000}}}' \ | |
| 53 | + | ./plugin_fetch --mcp | |
| 54 | +``` | |
| 55 | + | |
| 56 | +Behaviour that matters when an agent is driving it: | |
| 57 | + | |
| 58 | +* **Truncation is self-describing.** A chunk that ran out ends with | |
| 59 | + `<error>Content truncated. Call the fetch tool with a start_index of 5000 to | |
| 60 | + get more content.</error>`, and an out-of-range `start_index` answers | |
| 61 | + `<error>No more content available.</error>` — exactly the upstream strings, | |
| 62 | + so the agent's second call is never guesswork. | |
| 63 | +* **`text/markdown` is returned verbatim** with no notice. Anything else that | |
| 64 | + cannot be simplified (JSON, XML, plain text) is prefixed with | |
| 65 | + `Content type … cannot be simplified to markdown, but here is the raw content:`. | |
| 66 | +* **A redirect reports both ends** — `Redirecting from … to …` — and each of | |
| 67 | + up to five hops is re-validated before it is connected to. | |
| 68 | +* **The body is capped before it is read.** A declared `Content-Length` over | |
| 69 | + 5 MB is refused without pulling a byte, so a hostile server cannot make the | |
| 70 | + node allocate. | |
| 71 | + | |
| 72 | +## HTML → Markdown | |
| 73 | + | |
| 74 | +What the converter does, in one pass over the bytes (no DOM, no regex): | |
| 75 | + | |
| 76 | +| Input | Output | | |
| 77 | +|---|---| | |
| 78 | +| `<h1>`…`<h6>` | `#`…`######` | | |
| 79 | +| `<a href>` | `[text](href)` — href absolutised against the page URL | | |
| 80 | +| `<ul>` / `<ol>` (one nesting level) | `- item` / `1. item` | | |
| 81 | +| `<pre><code>` | fenced block; `<code>` inline → `` `code` `` | | |
| 82 | +| `<strong>`/`<b>`, `<em>`/`<i>` | `**…**`, `*…*` | | |
| 83 | +| `<blockquote>` | `> …` | | |
| 84 | +| `<hr>` | `---` | | |
| 85 | +| `<img alt src>` | `` | | |
| 86 | +| `<table>` | pipe-separated rows | | |
| 87 | +| `&` ` ` `—` `—` `✓` | decoded (named + decimal + hex) | | |
| 88 | +| `<script>` `<style>` `<noscript>` `<svg>` `<head>` `<nav>` `<aside>` `<footer>` `<form>` `<template>` + comments | **dropped, subtrees and all** | | |
| 89 | + | |
| 90 | +The document title (`og:title` if present, else `<title>`) is prepended as an | |
| 91 | +`# h1` when the body does not already open with it — the same rule as the | |
| 92 | +upstream `title.py`. | |
| 93 | + | |
| 94 | +It is a forgiving tokenizer over raw bytes, not a validator: UTF-8 passes | |
| 95 | +through untouched, and a page that forgets to close a tag still converts. | |
| 96 | + | |
| 97 | +## Security model | |
| 98 | + | |
| 99 | +This plugin fetches arbitrary URLs **on your node**, so the guardrails are the | |
| 100 | +product, not a footnote. | |
| 101 | + | |
| 102 | +1. **Only `http` and `https`.** Any other scheme (`ftp`, `file`, `gopher`, | |
| 103 | + `data`) is refused before a socket exists. | |
| 104 | +2. **Every address is checked before the connect.** The hostname is resolved, | |
| 105 | + **every** returned record is tested against the denylist, and the socket | |
| 106 | + then connects to that validated numeric address. A server whose DNS | |
| 107 | + alternates between a public and a private record — the classic rebinding | |
| 108 | + trick — is refused outright, and there is no window between the check and | |
| 109 | + the `connect()` for the answer to change under us. | |
| 110 | +3. **The denylist** follows upstream `_NON_PUBLIC_NETWORKS` and then some: | |
| 111 | + `0/8`, `10/8`, `100.64/10` (CGNAT), `127/8`, `169.254/16` (link-local, | |
| 112 | + which is where the cloud metadata endpoints live), `172.16/12`, | |
| 113 | + `192/24` IANA special (with upstream's two anycast exceptions), | |
| 114 | + `192.0.2/24`, `192.88.99/24`, `192.168/16`, `198.18/15`, `198.51.100/24`, | |
| 115 | + `203.0.113/24`, `224/4` (our own addition, upstream omits multicast), | |
| 116 | + `240/4`; and on IPv6 `::/96`, `::ffff:0:0/96` (v4-mapped, applied through | |
| 117 | + the v4 list), `64:ff9b::/96` and `64:ff9b:1::/48` (NAT64), `100::/64`, | |
| 118 | + `2001::/23` with the documented TEREDO/AMP/ORCHID exceptions, | |
| 119 | + `2001:db8::/32`, `2002::/16` (6to4), `3fff::/20`, `fc00::/7` (ULA), | |
| 120 | + `fe80::/10`, `fec0::/10`. | |
| 121 | + Non-canonical address text (`0177.0.0.1`, `0x7f.0.0.1`, `1.2.3`) is | |
| 122 | + **refused**, never reinterpreted — `inet_aton` would happily turn those | |
| 123 | + into loopback. | |
| 124 | +4. **Allowing private space is an explicit, persisted operator switch** — the | |
| 125 | + toggle on the page (which writes `config.json` in the plugin's connector | |
| 126 | + directory) or `FETCH_ALLOW_PRIVATE=1` in the environment. It is off by | |
| 127 | + default. The offline test suite is the main reason it exists. | |
| 128 | +5. **TLS is verified, always.** POSIX builds vendor **mbedTLS 3.6.7** and set | |
| 129 | + `MBEDTLS_SSL_VERIFY_REQUIRED` with a minimum of TLS 1.2, verifying the peer | |
| 130 | + certificate *and* the hostname against a CA bundle (`FETCH_TLS_CA_FILE`, or | |
| 131 | + the first system bundle found). There is deliberately **no** | |
| 132 | + `INSECURE_SKIP_VERIFY` option to add. Windows builds hand the whole HTTP | |
| 133 | + and TLS leg to **WinHTTP** with the system root store, TLS 1.2+ pinned and | |
| 134 | + WinHTTP's own redirect handling switched off so every hop comes back | |
| 135 | + through our validator. | |
| 136 | +6. **Every JSON action needs node authentication** (`X-Bot-Password`, | |
| 137 | + `Authorization: Bearer`, or `?pwd=`), same as every other plugin. | |
| 138 | + `--meta` and the page itself stay unauthenticated so discovery works. | |
| 139 | + | |
| 140 | +Full write-up, including the exact prefix lists and how to verify any of it | |
| 141 | +yourself, is in [`docs/SECURITY.md`](docs/SECURITY.md). | |
| 142 | + | |
| 143 | +## The page | |
| 144 | + | |
| 145 | +Dark and light, following the bot's theme tokens and the `sx-theme` handoff, | |
| 146 | +fluid down to 390 px and inside the Chat floating window, with zero | |
| 147 | +`<script src=>` and no CDN: | |
| 148 | + | |
| 149 | +* URL box + **Fetch** | |
| 150 | +* `max_length` / `start_index` / **raw** controls | |
| 151 | +* **Markdown** and **Raw HTML** tabs | |
| 152 | +* metadata strip: status, content type, bytes read, content length, redirected | |
| 153 | +* **Prev / Next** pagination that re-uses the tool's own chunking, so what you | |
| 154 | + see is what the agent sees | |
| 155 | +* the SSRF **allow private** switch (behind node auth, writes the policy file) | |
| 156 | +* the live `--mcp` tool schema, straight from `?action=info` | |
| 157 | + | |
| 158 | +Open it through the hub (`/plugins?plugin=fetch`) or the node directly | |
| 159 | +(`/plugin_fetch`); `?embed=1` and `&theme=dark|light` are honoured. | |
| 160 | + | |
| 161 | +## Build | |
| 162 | + | |
| 163 | +```sh | |
| 164 | +make # native -> ./plugin_fetch | |
| 165 | +make musl # static musl x86_64 -> ./plugin_fetch.musl | |
| 166 | +make arm64 # static aarch64 -> ./plugin_fetch.arm64 | |
| 167 | +make win64 # static MinGW PE -> ./plugin_fetch.exe | |
| 168 | +make macos # Apple clang | |
| 169 | +make asan # ASan + UBSan + leak check | |
| 170 | +make fortify # -D_FORTIFY_SOURCE=2 | |
| 171 | +make zlib # native build with gzip support (-DHAVE_ZLIB -lz) | |
| 172 | +make ui # regenerate src/ui_html.h from src/ui.html | |
| 173 | +make test # offline suite | |
| 174 | +make e2e # Playwright viewport checks (skips cleanly without it) | |
| 175 | +``` | |
| 176 | + | |
| 177 | +The published artefacts link nothing but libc. `make zlib` exists so the suite | |
| 178 | +can prove the gzip path works when zlib happens to be present — the shipped | |
| 179 | +binary says `Unsupported content encoding gzip` rather than lying about it. | |
| 180 | + | |
| 181 | +For the inner loop, `./dev-build.sh` caches the ~110 vendored mbedTLS objects | |
| 182 | +in `/tmp/fetch-objs` and only recompiles `src/` (about two seconds instead of | |
| 183 | +a minute). | |
| 184 | + | |
| 185 | +## Layout | |
| 186 | + | |
| 187 | +``` | |
| 188 | +src/plugin_fetch.c four modes, the tool, the policy file, the CGI API | |
| 189 | +src/fetch_http.c URL parse, SSRF matrix, HTTP/1.1, chunked, redirects, | |
| 190 | + the POSIX socket path and the WinHTTP path | |
| 191 | +src/fetch_tls.c mbedTLS over our own BIOs (POSIX only; empty TU on Win32) | |
| 192 | +src/fetch_md.c tokenizer + Markdown renderer + title extraction | |
| 193 | +src/sxbuf.c growable buffer, query decoding, JSON escaping, case fold | |
| 194 | +src/ui.html the page (compiled into src/ui_html.h by tools/gen_ui.py) | |
| 195 | +src/bot_theme_plugin.h the shared bot theme tokens + sx-theme handoff | |
| 196 | +vendor/ yyjson (MIT) + mbedTLS 3.6.7 (Apache-2.0) sources | |
| 197 | +tests/mockd.py the offline HTTP/HTTPS fixture server | |
| 198 | +tests/mcp.py the MCP stdio harness used by the suite | |
| 199 | +tests/e2e.py Playwright viewport + interaction checks | |
| 200 | +docs/ SECURITY.md + screenshots taken by the e2e run | |
| 201 | +``` | |
| 202 | + | |
| 203 | +## Tests | |
| 204 | + | |
| 205 | +`make test` runs everything offline — no outbound network. The listeners live | |
| 206 | +on `127.0.0.1` and the suite reaches them through the plugin's own test-only | |
| 207 | +private-address allowance, so nothing outside the machine is touched. | |
| 208 | + | |
| 209 | +``` | |
| 210 | +--meta · --mcp (tools/list, tools/call, ping, unknown method/tool, | |
| 211 | + notifications, noise tolerance, argument coercion) | |
| 212 | +html→markdown (headings, links, lists, code, entities, stripped boilerplate, | |
| 213 | + title rule, verbatim markdown, no-Content-Type sniffing) | |
| 214 | +pagination (truncation footer, continuation, out-of-range, the 100000 cap, raw) | |
| 215 | +transport (redirect chain, relative Location, loop cap, 404/403/500, oversized | |
| 216 | + body refused unread, chunked, no-Content-Length, gzip, request shape, | |
| 217 | + read deadline) | |
| 218 | +ssrf (the whole v4+v6 matrix through --selftest, redirect-to-private, | |
| 219 | + the env var, the persisted toggle) | |
| 220 | +tls (self-signed refused, CA accepted, hostname mismatch refused) | |
| 221 | +cgi (401 on every action, open node, ?pwd= / header / Bearer, info, policy | |
| 222 | + round-trip, POST body, format=json as a real parameter) | |
| 223 | +ui (no CDN, no <script src=, CSP, embed rule, no emoji, no raw IP literal) | |
| 224 | +builds (ASan+UBSan and fortified runs of the same surface) | |
| 225 | +audit (full git-history secret / LAN-IP scan) | |
| 226 | +``` | |
| 227 | + | |
| 228 | +`./plugin_fetch --selftest <addr> …` prints `<addr> denied=<0|1>` per line and | |
| 229 | +reads stdin when given no arguments — pure policy, no DNS and no sockets, so | |
| 230 | +the SSRF matrix is asserted identically on a machine with no network. | |
| 231 | + | |
| 232 | +## Install on a node | |
| 233 | + | |
| 234 | +Installed from **Settings → Plugins** or BotMarket, the binary lands in | |
| 235 | +`~/.scorpiox/plugins/` (or `/workspace/.scorpiox/plugins/` in BotCloud) and | |
| 236 | +`sx-connector-mcp` picks it up automatically: it appears as | |
| 237 | +`connector_call` → `fetch`. To wire it in by hand: | |
| 238 | + | |
| 239 | +```sh | |
| 240 | +install -m 0755 plugin_fetch ~/.scorpiox/plugins/plugin_fetch | |
| 241 | +./plugin_fetch --meta # must print the one-line JSON | |
| 242 | +``` | |
| 243 | + | |
| 244 | +Policy lives in `<connector dir>/fetch/config.json` | |
| 245 | +(`SX_CONNECTOR_DIR`, else `/workspace/.scorpiox/connectors/fetch`, | |
| 246 | +`~/.scorpiox/connectors/fetch`, or `%LOCALAPPDATA%\scorpiox\connectors\fetch`). | |
| 247 | + | |
| 248 | +## Environment | |
| 249 | + | |
| 250 | +| Variable | Effect | | |
| 251 | +|---|---| | |
| 252 | +| `FETCH_ALLOW_PRIVATE` | unset/`0` = enforce the denylist; anything else allows private ranges (test escape hatch) | | |
| 253 | +| `FETCH_TLS_CA_FILE` | PEM bundle to trust instead of the system bundle | | |
| 254 | +| `SX_CONNECTOR_DIR` | where the policy file lives | | |
| 255 | +| `BOT_PASSWORD` | the node's password — gates every JSON action | | |
| 256 | +| `SX_PLUGIN_META` | answered with the discovery line and exit | | |
| 257 | + | |
| 258 | +## Credits | |
| 259 | + | |
| 260 | +* Behaviour modelled on `modelcontextprotocol/servers` `src/fetch` (Apache-2.0) | |
| 261 | + and the readability subset in `openclaw/openclaw` `extensions/web-readability` | |
| 262 | + — reimplemented clean-room in C99, not translated line by line. | |
| 263 | +* [yyjson](https://github.com/ibireme/yyjson) (MIT) for JSON. | |
| 264 | +* [mbedTLS](https://github.com/Mbed-TLS/mbedtls) 3.6.7 (Apache-2.0) for TLS. | |
| 265 | + | |
| 266 | +MIT © SCORPIOX INC. |
| 1 | 1 | new file mode 100755 |
| index 0000000..351b2e4 | ||
| --- /dev/null | ||
| +++ b/dev-build.sh | ||
| @@ -0,0 +1,36 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# dev-build.sh - fast local build of plugin_fetch with a cached mbedtls object set. | |
| 3 | +# | |
| 4 | +# The vendored mbedTLS objects are compiled once into /tmp/fetch-objs (they | |
| 5 | +# never change and cost ~50 s to build). Only src/ recompiles per run. | |
| 6 | +# | |
| 7 | +# ./dev-build.sh -> ./plugin_fetch (native) | |
| 8 | +# ./dev-build.sh asan -> ./plugin_fetch.asan (ASan + fortify) | |
| 9 | +set -eu | |
| 10 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 11 | +OBJS=/tmp/fetch-objs | |
| 12 | +mkdir -p "$OBJS" | |
| 13 | + | |
| 14 | +build_objs() { | |
| 15 | + local f o n | |
| 16 | + ls "$ROOT"/vendor/mbedtlslib/*.c "$ROOT"/vendor/yyjson.c | while read -r f; do | |
| 17 | + n=$(basename "${f%.c}") | |
| 18 | + o="$OBJS/$n.o" | |
| 19 | + if [ ! -f "$o" ] || [ "$f" -nt "$o" ]; then echo "$f|$o"; fi | |
| 20 | + done | xargs -P "$(nproc)" -I{} bash -c ' | |
| 21 | + IFS="|" read -r f o <<< "{}" | |
| 22 | + gcc -O2 -w -I '"$ROOT"'/vendor -I '"$ROOT"'/vendor/mbedtlslib -c "$f" -o "$o"' | |
| 23 | +} | |
| 24 | + | |
| 25 | +MODE="${1:-plain}" | |
| 26 | +build_objs | |
| 27 | + | |
| 28 | +CFLAGS="-std=c99 -I $ROOT/vendor -I $ROOT/vendor/mbedtlslib -I $ROOT/src" | |
| 29 | +if [ "$MODE" = asan ]; then | |
| 30 | + gcc -g -O1 -fsanitize=address -D_FORTIFY_SOURCE=2 -Wall -Wextra -Wno-unused-parameter \ | |
| 31 | + $CFLAGS "$ROOT"/src/*.c "$OBJS"/*.o -o "$ROOT/plugin_fetch.asan" | |
| 32 | + echo "built plugin_fetch.asan" | |
| 33 | +else | |
| 34 | + gcc -O2 -Wall -Wextra -Wno-unused-parameter $CFLAGS "$ROOT"/src/*.c "$OBJS"/*.o -o "$ROOT/plugin_fetch" | |
| 35 | + echo "built plugin_fetch" | |
| 36 | +fi |
| 1 | 1 | new file mode 100644 |
| index 0000000..632e48e | ||
| --- /dev/null | ||
| +++ b/docs/SECURITY.md | ||
| @@ -0,0 +1,171 @@ | ||
| 1 | +# Security model | |
| 2 | + | |
| 3 | +`plugin_fetch` makes **outbound HTTP requests on your node, to a URL somebody | |
| 4 | +types or an agent chooses**. That is the entire feature, so it is also the | |
| 5 | +entire risk. Everything here exists to answer one question: *what is this | |
| 6 | +binary allowed to reach, and how do I know?* | |
| 7 | + | |
| 8 | +If you read only one line: **every address is validated before the socket is | |
| 9 | +opened, the socket then connects to that validated numeric address, TLS is | |
| 10 | +verified with no bypass, and nothing on your node can be reached unless you | |
| 11 | +switch the policy on yourself.** | |
| 12 | + | |
| 13 | +## One gate, every entry point | |
| 14 | + | |
| 15 | +A URL arriving from `--mcp`, from `?action=fetch`, or from the page's Fetch | |
| 16 | +button runs the same code path. There is no "internal" fetch. The order is | |
| 17 | +fixed: | |
| 18 | + | |
| 19 | +| # | Check | What it stops | | |
| 20 | +|---|---|---| | |
| 21 | +| 1 | **Scheme** — `http` / `https` only, absolute, no userinfo confusion | `file://`, `gopher://`, `dict://`, `http://x#@evil/` tricks | | |
| 22 | +| 2 | **Resolve** — one `getaddrinfo()` for the hostname | — | | |
| 23 | +| 3 | **Validate every returned address** against the denylist below | public hostname with a private A record, DNS that answers a second internal address | | |
| 24 | +| 4 | **Connect to the validated numeric address**, not to the name | DNS rebinding between check and connect | | |
| 25 | +| 5 | **Re-check on every redirect hop**, max 5 | 302 → `169.254.169.254`, relative `Location` escaping to an internal host | | |
| 26 | + | |
| 27 | +Step 4 is the one that matters. The common SSRF bug is "check the name, then | |
| 28 | +connect by name" — the resolver is asked twice and can answer differently the | |
| 29 | +second time. Here the checked address *is* the address passed to `connect()`. | |
| 30 | +`--selftest` proves step 3 as pure policy: no DNS, no sockets, so the matrix | |
| 31 | +holds on a machine with no network at all. | |
| 32 | + | |
| 33 | +## The denylist | |
| 34 | + | |
| 35 | +Assembled from octet arrays in code (no dotted-quad literals sitting in a | |
| 36 | +string where a scanner can find one), mirroring upstream | |
| 37 | +`_NON_PUBLIC_NETWORKS` in `modelcontextprotocol/servers`. | |
| 38 | + | |
| 39 | +| Refused IPv4 | Role | | |
| 40 | +|---|---| | |
| 41 | +| `0/8` | this-network | | |
| 42 | +| `10/8` | private | | |
| 43 | +| `100.64/10` | CGNAT | | |
| 44 | +| `127/8` | loopback | | |
| 45 | +| `169.254/16` | link-local **and** every cloud metadata endpoint | | |
| 46 | +| `172.16/12` | private | | |
| 47 | +| `192/24` | IANA special (see the exception below) | | |
| 48 | +| `192.0.2/24` | TEST-NET-1 | | |
| 49 | +| `192.88.99/24` | 6to4 relay | | |
| 50 | +| `192.168/16` | private | | |
| 51 | +| `198.18/15` | benchmarking | | |
| 52 | +| `198.51.100/24` | TEST-NET-2 | | |
| 53 | +| `203.0.113/24` | TEST-NET-3 | | |
| 54 | +| `224/4` | multicast (our own addition — upstream omits it) | | |
| 55 | +| `240/4` | reserved | | |
| 56 | + | |
| 57 | +**Exception:** `192.0.0.9` and `192.0.0.10` — the anycast addresses upstream | |
| 58 | +carves out of `192/24`. | |
| 59 | + | |
| 60 | +Blocks are written in prefix shorthand throughout (`10/8` rather than the full | |
| 61 | +four-octet form) for the same reason the source assembles the octets in code: | |
| 62 | +a dotted-quad of a private range in a text file is indistinguishable to a | |
| 63 | +secret scanner from the thing the scanner exists to catch, and documentation | |
| 64 | +should not have to look like a leak to be correct. | |
| 65 | + | |
| 66 | +**IPv6 refused:** `::/96` (unspecified, loopback, deprecated | |
| 67 | +IPv4-compatible), IPv4-mapped `::ffff:a.b.c.d` **through the IPv4 list**, | |
| 68 | +`64:ff9b:1::/48` (isolated NAT64), `100::/64` (discard), the whole `2001::/23` | |
| 69 | +except its IANA carve-outs, `2001:db8::/32` (documentation), `2002::/16` | |
| 70 | +(6to4), `3fff::/20`, `fc00::/7` (ULA), `fe80::/10` (link-local) and | |
| 71 | +`fec0::/10` (deprecated site-local). | |
| 72 | +**Carve-outs inside `2001::/23`, matching upstream:** `2001:1::/32`, | |
| 73 | +`2001:2::/32` and `2001:3::/32` (TEREDO), `2001:4:112::/48` (AMP), | |
| 74 | +`2001:20::/28` and `2001:30::/28` (ORCHIDv2). The well-known NAT64 prefix | |
| 75 | +`64:ff9b::/96` is not refused outright — the embedded IPv4 is unwrapped and | |
| 76 | +run through the IPv4 list, because "public v6 that tunnels to `169.254/16`" is | |
| 77 | +exactly the bypass people forget. | |
| 78 | + | |
| 79 | +`fx_ip_is_denied()` is a single function with one job, and the test suite | |
| 80 | +feeds it a named list of ~40 addresses and asserts each verdict, so a future | |
| 81 | +edit that widens a mask fails instead of shipping. | |
| 82 | + | |
| 83 | +Address **text** is parsed here, not handed to `inet_aton`. Only the canonical | |
| 84 | +dotted-quad form is accepted — digits, no sign, no leading zero on a | |
| 85 | +multi-digit group, at most three digits per group, nothing after the fourth | |
| 86 | +group. `0177.0.0.1`, `0x7f.0.0.1` and `1.2.3` are **refused**, never | |
| 87 | +reinterpreted, because `inet_aton` would happily turn all three into loopback. | |
| 88 | +Anything that fails to parse at all is denied, so a malformed address can | |
| 89 | +never reach `connect()`. | |
| 90 | + | |
| 91 | +## The private switch is an operator's, not a caller's | |
| 92 | + | |
| 93 | +`FETCH_ALLOW_PRIVATE=1` in the node's environment, or the policy toggle on the | |
| 94 | +page, is what turns the denylist off. Both are off by default. | |
| 95 | + | |
| 96 | +- The toggle writes **one** file, `<connector dir>/config.json`, and is | |
| 97 | + itself behind `require_node_auth()`. An agent cannot flip it through | |
| 98 | + `--mcp` — no MCP tool touches it. | |
| 99 | +- It is **off again** the moment you switch it back; there is no "sticky | |
| 100 | + once set" path, and `?action=info` always reports the current value so the | |
| 101 | + page cannot drift out of sync with the truth. | |
| 102 | +- It exists for one legitimate reason: letting the test suite (and you) point | |
| 103 | + the fetcher at a local service on purpose. | |
| 104 | + | |
| 105 | +## TLS: verify, or refuse | |
| 106 | + | |
| 107 | +POSIX builds use **vendored mbedTLS 3.6.7** — no libcurl, no OpenSSL, nothing | |
| 108 | +that can be silently swapped under the binary. | |
| 109 | + | |
| 110 | +- `MBEDTLS_SSL_VERIFY_REQUIRED`, always. There is no | |
| 111 | + `FETCH_TLS_INSECURE`, no `verify=0`, no "skip on error" branch in the | |
| 112 | + source, and the suite greps for one. | |
| 113 | +- `mbedtls_ssl_set_hostname()` is called with the URL's host, so a valid | |
| 114 | + certificate for the wrong name is refused (the suite proves it with a SAN | |
| 115 | + mismatch). | |
| 116 | +- Minimum version **TLS 1.2** (`mbedtls_ssl_conf_min_tls_version`). | |
| 117 | +- Trust anchors: `FETCH_TLS_CA_FILE` if set, else the first readable system | |
| 118 | + bundle (`/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, | |
| 119 | + `/etc/ssl/ca-bundle.pem`, `/etc/ssl/cert.pem`, `/var/ssl/certs/ca-certificates.crt`). | |
| 120 | + If none is readable the request **fails** with `no trust anchors`; a missing | |
| 121 | + CA store is never a reason to skip verification. | |
| 122 | + | |
| 123 | +Windows builds use **WinHTTP**, which means the system root store, system | |
| 124 | +revocation and system cipher policy — not a second implementation we have to | |
| 125 | +keep correct. | |
| 126 | + | |
| 127 | +## Limits that are not decoration | |
| 128 | + | |
| 129 | +| Limit | Value | Why | | |
| 130 | +|---|---|---| | |
| 131 | +| Body read | 5 MB (`FX_MAX_BODY`) | A declared `Content-Length` over the cap is refused **unread** — we do not start a 40 GB download to discover it is a lie | | |
| 132 | +| Returned text | 100 000 chars | Keeps one tool result inside an agent's context budget | | |
| 133 | +| Redirects | 5 (`FX_MAX_REDIRECTS`) | Chains end; a loop is caught, not followed | | |
| 134 | +| Header block | 64 KB | A server that sends infinite headers is stopped, not buffered | | |
| 135 | +| Connect / read | 10 s / 15 s | A stalled host cannot pin a CGI worker | | |
| 136 | +| `Accept-Encoding` | `identity` unless built `-DHAVE_ZLIB` | gzip is only advertised when we can actually decode it | | |
| 137 | + | |
| 138 | +## Every JSON action is authenticated | |
| 139 | + | |
| 140 | +`require_node_auth()` accepts `X-Bot-Password`, `Authorization: Bearer`, or | |
| 141 | +`?pwd=`, and is checked before **any** `action=` — including `info` and | |
| 142 | +`policy`. `--meta` and the page itself are exempt because they read nothing | |
| 143 | +and fetch nothing: the page renders an empty form and does not issue a single | |
| 144 | +request until you press Fetch. With `BOT_PASSWORD` unset the node has no | |
| 145 | +password to demand, so the gate opens — the same convention every other | |
| 146 | +plugin uses. | |
| 147 | + | |
| 148 | +## What touches the disk | |
| 149 | + | |
| 150 | +One file: the policy file in the plugin's connector directory | |
| 151 | +(`SX_CONNECTOR_DIR`, else `~/.scorpiox/connectors/fetch`, else a temp dir). | |
| 152 | +It contains one boolean. Downloads are held in memory and freed; nothing is | |
| 153 | +cached, nothing is logged, no request URL is persisted anywhere. | |
| 154 | + | |
| 155 | +## The page | |
| 156 | + | |
| 157 | +Inline CSS and inline JS only — `<script src=` is asserted absent by the | |
| 158 | +suite, as is any CDN hostname. A strict CSP header ships with the page, | |
| 159 | +`X-Content-Type-Options: nosniff`, and the fetched document is only ever | |
| 160 | +inserted as **text** (`textContent`), never as HTML, so a page that contains | |
| 161 | +`<img onerror>` cannot execute in the bot's chrome. | |
| 162 | + | |
| 163 | +## If you want to check me | |
| 164 | + | |
| 165 | +```sh | |
| 166 | +./plugin_fetch --selftest # SSRF matrix, no network, no DNS | |
| 167 | +make && make test # 260+ offline assertions | |
| 168 | +make asan && ./plugin_fetch-asan --mcp < /dev/null | |
| 169 | +grep -n 'authmode\|set_hostname\|min_tls' src/fetch_tls.c | |
| 170 | +grep -rn 'INSECURE\|VERIFY_NONE\|system(\|popen' src/ || echo "none" | |
| 171 | +``` |
| 1 | 1 | new file mode 100644 |
| index 0000000..caad5cd |

| 1 | 1 | new file mode 100644 |
| index 0000000..0ea67e9 |

| 1 | 1 | new file mode 100644 |
| index 0000000..f3eead0 |

| 1 | 1 | new file mode 100644 |
| index 0000000..cc6b558 |

| 1 | 1 | new file mode 100644 |
| index 0000000..5a7d688 |

| 1 | 1 | new file mode 100644 |
| index 0000000..6b90d1f |

| 1 | 1 | new file mode 100644 |
| index 0000000..6521c63 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,31 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "fetch", | |
| 3 | + "id": "plugin_fetch", | |
| 4 | + "name": "fetch", | |
| 5 | + "desc": "URL to Markdown", | |
| 6 | + "title": "URL Fetch & HTML-to-Markdown (MCP)", | |
| 7 | + "summary": "Zero-dependency MCP connector that fetches an http(s) URL from the node and hands your agent clean Markdown: headings, links, lists, code blocks, inline emphasis and HTML entities are converted, while scripts, styles, navigation, asides, footers, forms and SVG are dropped. Long pages are chunked with max_length and start_index so an agent can page through a document instead of flooding its context; text/markdown comes back untouched and anything that cannot be simplified is returned raw with a notice. Up to five redirects are followed, every hop re-checked. Every address is validated before connect: private, loopback, link-local, CGNAT and special-purpose ranges are refused unless you turn the policy on, and TLS is verified against a CA bundle with no insecure bypass. The setup page is a URL preview and fetch tester with raw/markdown tabs, pagination controls and the SSRF policy switch, dark and light, fluid down to 390px.", | |
| 8 | + "kind": "mcp", | |
| 9 | + "mcp": true, | |
| 10 | + "daemon": false, | |
| 11 | + "menus": false, | |
| 12 | + "verified": "live", | |
| 13 | + "category": "network", | |
| 14 | + "version": "1.0.0", | |
| 15 | + "license": "MIT", | |
| 16 | + "capabilities": [ | |
| 17 | + "outbound_http_user_requested", | |
| 18 | + "dns_resolve", | |
| 19 | + "url_to_markdown" | |
| 20 | + ], | |
| 21 | + "trust_notice": "Executes native C code on your node and makes exactly the outbound requests you ask for: one GET to the URL you supply, following up to five redirects. There is no libcurl and no OpenSSL in the binary - POSIX TLS is vendored mbedTLS (peer certificate and hostname verified against a CA bundle, TLS 1.2 minimum, no insecure bypass) and Windows uses WinHTTP with the system root store. Before any socket is opened the hostname is resolved and EVERY returned address is checked against a private/reserved denylist (loopback, RFC1918, link-local and cloud metadata, CGNAT, benchmarking and documentation ranges, and the equivalent IPv6 spaces including ULA, NAT64 and 6to4); the socket then connects to that validated numeric address, so DNS cannot answer a different address between the check and the connect. Non-http(s) schemes are refused, the body read is capped at 5 MB, and the returned text is capped at 100000 characters. Allowing private addresses is an explicit operator switch (the policy on this page, or FETCH_ALLOW_PRIVATE); it is off by default and off again the moment you switch it back. Every JSON action requires node authentication; the page itself reads nothing until you press Fetch. Nothing is written to disk except the single policy file in the plugin's connector directory.", | |
| 22 | + "author": "SCORPIOX INC", | |
| 23 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch", | |
| 24 | + "cflags": [], | |
| 25 | + "ldflags_posix": [], | |
| 26 | + "ldflags_win64": [ | |
| 27 | + "-lwinhttp", | |
| 28 | + "-lws2_32", | |
| 29 | + "-lbcrypt" | |
| 30 | + ] | |
| 31 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..f3f1cf0 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,43 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# release-dist.sh - thin wrapper around the shared multi-arch release tool. | |
| 3 | +# | |
| 4 | +# The real cross-target build + dist publish lives in scorpiox-cli-botplugin | |
| 5 | +# (it owns the musl / aarch64 / MinGW / macOS toolchains, the dist upload and | |
| 6 | +# the plugingit mirror). This script exists so the repo releases the same way | |
| 7 | +# every other oss plugin does, and so a stale release fails loudly instead of | |
| 8 | +# shipping a 3-target manifest that still says "release complete". | |
| 9 | +# | |
| 10 | +# ./release-dist.sh # build + publish the version in plugin.json | |
| 11 | +# VERSION=1.0.1 ./release-dist.sh # explicit version | |
| 12 | +# | |
| 13 | +# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc, | |
| 14 | +# x86_64-w64-mingw32-gcc and ssh access to the macOS builder. Nothing here | |
| 15 | +# contains a host address or a credential: the macOS builder and the dist | |
| 16 | +# target come from the environment / the CLI's own configuration. | |
| 17 | + | |
| 18 | +set -eu | |
| 19 | + | |
| 20 | +SLUG=fetch | |
| 21 | +VERSION="${VERSION:-1.0.0}" | |
| 22 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 23 | + | |
| 24 | +ROOT=$(cd "$(dirname "$0")" && pwd) | |
| 25 | + | |
| 26 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 27 | + echo "scorpiox-cli-botplugin not found on PATH" >&2 | |
| 28 | + exit 1 | |
| 29 | +fi | |
| 30 | + | |
| 31 | +echo "==> audit $SLUG" | |
| 32 | +scorpiox-cli-botplugin audit "$ROOT" --json || { echo "audit blocked the release" >&2; exit 4; } | |
| 33 | + | |
| 34 | +echo "==> publish $SLUG $VERSION" | |
| 35 | +scorpiox-cli-botplugin publish "$ROOT" \ | |
| 36 | + --slug "$SLUG" \ | |
| 37 | + --version "$VERSION" \ | |
| 38 | + --macos-host "${MACOS_HOST:-macos-builder}" \ | |
| 39 | + --json | |
| 40 | + | |
| 41 | +echo "==> reindex" | |
| 42 | +scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true | |
| 43 | +echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..4c70e7b | ||
| --- /dev/null | ||
| +++ b/src/fetch_common.h | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_common.h - internal glue shared across plugin_fetch modules. | |
| 3 | + * The single authority for the query/buffer/JSON helpers (sxbuf.c) and the | |
| 4 | + * tool contract (sxmcp.h). | |
| 5 | + */ | |
| 6 | +#ifndef SX_FETCH_COMMON_H | |
| 7 | +#define SX_FETCH_COMMON_H | |
| 8 | + | |
| 9 | +#include <stdio.h> | |
| 10 | +#include <stdlib.h> | |
| 11 | +#include <string.h> | |
| 12 | + | |
| 13 | +#include "sxbuf.h" | |
| 14 | +#include "sxmcp.h" | |
| 15 | + | |
| 16 | +#endif /* SX_FETCH_COMMON_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..8cf77bb | ||
| --- /dev/null | ||
| +++ b/src/fetch_http.c | ||
| @@ -0,0 +1,1260 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_http.c - URL parsing, SSRF policy, HTTP(S) GET with redirect chain. | |
| 3 | + * | |
| 4 | + * Both platforms: our own getaddrinfo, per-address SSRF validation, then the | |
| 5 | + * socket is connected to the EXACT validated numeric address (never the | |
| 6 | + * hostname), so a rebinding DNS server cannot answer a private IP between | |
| 7 | + * the check and the connect. TLS on POSIX is vendored mbedTLS over our own | |
| 8 | + * socket (fetch_tls.c); on _WIN32 the exchange runs over WinHTTP with the | |
| 9 | + * resolution pinned through WINHTTP_OPTION_RESOLVE_TIMEOUT-era connection | |
| 10 | + * semantics by connecting to the numeric IP while sending the real Host | |
| 11 | + * header and SNI name (https). | |
| 12 | + * | |
| 13 | + * Every redirect hop re-enters the same parse/resolve/validate path, up to | |
| 14 | + * FX_MAX_REDIRECTS. No TLS bypass exists. | |
| 15 | + */ | |
| 16 | +/* The feature-test macros must precede every include (netdb/inet functions, | |
| 17 | + * POSIX sockets). */ | |
| 18 | +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) | |
| 19 | +# define _POSIX_C_SOURCE 200809L | |
| 20 | +#endif | |
| 21 | + | |
| 22 | +#include "fetch_http.h" | |
| 23 | + | |
| 24 | +#include <ctype.h> | |
| 25 | +#include <errno.h> | |
| 26 | +#include <limits.h> | |
| 27 | +#include <stdio.h> | |
| 28 | +#include <stdlib.h> | |
| 29 | +#include <string.h> | |
| 30 | +#include <time.h> | |
| 31 | + | |
| 32 | +#if defined(_WIN32) | |
| 33 | +# ifndef WIN32_LEAN_AND_MEAN | |
| 34 | +# define WIN32_LEAN_AND_MEAN | |
| 35 | +# endif | |
| 36 | +# include <winsock2.h> | |
| 37 | +# include <windows.h> | |
| 38 | +# include <ws2tcpip.h> | |
| 39 | +# include <winhttp.h> | |
| 40 | + typedef SOCKET sx_sock; | |
| 41 | +# define SX_SOCK_INVALID INVALID_SOCKET | |
| 42 | +# define sx_closesocket closesocket | |
| 43 | +#else | |
| 44 | +# ifndef _POSIX_C_SOURCE | |
| 45 | +# define _POSIX_C_SOURCE 200809L | |
| 46 | +# endif | |
| 47 | +# include <netdb.h> | |
| 48 | +# include <arpa/inet.h> | |
| 49 | +# include <netinet/in.h> | |
| 50 | +# include <netinet/tcp.h> | |
| 51 | +# include <poll.h> | |
| 52 | +# include <fcntl.h> | |
| 53 | +# include <sys/socket.h> | |
| 54 | +# include <sys/time.h> | |
| 55 | +# include <sys/types.h> | |
| 56 | +# include <unistd.h> | |
| 57 | + typedef int sx_sock; | |
| 58 | +# define SX_SOCK_INVALID (-1) | |
| 59 | +# define sx_closesocket close | |
| 60 | +#endif | |
| 61 | + | |
| 62 | +#include "fetch_tls.h" | |
| 63 | +#include "fetch_md.h" | |
| 64 | + | |
| 65 | +#ifdef HAVE_ZLIB | |
| 66 | +# include <zlib.h> | |
| 67 | +#endif | |
| 68 | +/* Persisted policy hook (implemented in plugin_fetch.c). */ | |
| 69 | +extern int fx_policy_allow_private(void); | |
| 70 | + | |
| 71 | +char *fx_strndup(const char *s, size_t n) | |
| 72 | +{ | |
| 73 | + char *p; | |
| 74 | + if (!s || !n) { p = (char *)sx_malloc(1); p[0] = '\0'; return p; } | |
| 75 | + p = (char *)sx_malloc(n + 1); | |
| 76 | + memcpy(p, s, n); | |
| 77 | + p[n] = '\0'; | |
| 78 | + return p; | |
| 79 | +} | |
| 80 | + | |
| 81 | +long long fx_now_ms(void) | |
| 82 | +{ | |
| 83 | +#if defined(_WIN32) | |
| 84 | + static LARGE_INTEGER freq; | |
| 85 | + LARGE_INTEGER t; | |
| 86 | + if (!freq.QuadPart) QueryPerformanceFrequency(&freq); | |
| 87 | + QueryPerformanceCounter(&t); | |
| 88 | + return (long long)(t.QuadPart / (freq.QuadPart / 1000)); | |
| 89 | +#else | |
| 90 | + struct timespec ts; | |
| 91 | + clock_gettime(CLOCK_MONOTONIC, &ts); | |
| 92 | + return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; | |
| 93 | +#endif | |
| 94 | +} | |
| 95 | + | |
| 96 | +/* ------------------------------------------------------------------ */ | |
| 97 | +/* URL parsing */ | |
| 98 | +/* ------------------------------------------------------------------ */ | |
| 99 | + | |
| 100 | +typedef struct { | |
| 101 | + char scheme[8]; /* http | https */ | |
| 102 | + char host[256]; | |
| 103 | + int port; | |
| 104 | + char path[2048]; /* path?query, always starts with '/' */ | |
| 105 | +} fx_url; | |
| 106 | + | |
| 107 | +static int parse_port(const char *s, const char *end, int *port_out) | |
| 108 | +{ | |
| 109 | + long pl = 0; | |
| 110 | + const char *p = s; | |
| 111 | + if (p == end) return -1; | |
| 112 | + for (; p < end; p++) { | |
| 113 | + if (!isdigit((unsigned char)*p)) return -1; | |
| 114 | + pl = pl * 10 + (*p - '0'); | |
| 115 | + if (pl > 65535) return -1; | |
| 116 | + } | |
| 117 | + if (pl <= 0) return -1; | |
| 118 | + *port_out = (int)pl; | |
| 119 | + return 0; | |
| 120 | +} | |
| 121 | + | |
| 122 | +static int fx_url_parse(const char *url, fx_url *u, char *err, size_t errsz) | |
| 123 | +{ | |
| 124 | + const char *p = url, *sc_end, *host_start, *host_end; | |
| 125 | + size_t n; | |
| 126 | + | |
| 127 | + memset(u, 0, sizeof *u); | |
| 128 | + if (strlen(url) >= sizeof(u->host) + 2300) { | |
| 129 | + snprintf(err, errsz, "invalid URL (too long)"); | |
| 130 | + return -1; | |
| 131 | + } | |
| 132 | + sc_end = strstr(p, "://"); | |
| 133 | + if (!sc_end) { snprintf(err, errsz, "invalid URL (no scheme)"); return -1; } | |
| 134 | + n = (size_t)(sc_end - p); | |
| 135 | + if (n == 0 || n >= sizeof u->scheme) { | |
| 136 | + snprintf(err, errsz, "invalid URL (scheme)"); | |
| 137 | + return -1; | |
| 138 | + } | |
| 139 | + for (size_t i = 0; i < n; i++) u->scheme[i] = (char)tolower((unsigned char)p[i]); | |
| 140 | + u->scheme[n] = '\0'; | |
| 141 | + if (strcmp(u->scheme, "http") != 0 && strcmp(u->scheme, "https") != 0) { | |
| 142 | + snprintf(err, errsz, | |
| 143 | + "Unsupported URL scheme '%s' - only http and https are allowed", | |
| 144 | + u->scheme); | |
| 145 | + return -1; | |
| 146 | + } | |
| 147 | + host_start = sc_end + 3; | |
| 148 | + host_end = host_start; | |
| 149 | + while (*host_end && *host_end != '/' && *host_end != '?' && *host_end != '#') | |
| 150 | + host_end++; | |
| 151 | + n = (size_t)(host_end - host_start); | |
| 152 | + if (n == 0) { snprintf(err, errsz, "invalid URL (empty host)"); return -1; } | |
| 153 | + if (memchr(host_start, '@', n)) { | |
| 154 | + snprintf(err, errsz, "URLs with userinfo are refused"); | |
| 155 | + return -1; | |
| 156 | + } | |
| 157 | + | |
| 158 | + u->port = strcmp(u->scheme, "https") == 0 ? 443 : 80; | |
| 159 | + if (host_start[0] == '[') { | |
| 160 | + const char *cb = (const char *)memchr(host_start, ']', n); | |
| 161 | + size_t hl; | |
| 162 | + if (!cb || cb >= host_end) { snprintf(err, errsz, "invalid URL (IPv6 host)"); return -1; } | |
| 163 | + hl = (size_t)(cb - (host_start + 1)); | |
| 164 | + if (hl == 0 || hl >= sizeof u->host) { | |
| 165 | + snprintf(err, errsz, "invalid URL (IPv6 host)"); | |
| 166 | + return -1; | |
| 167 | + } | |
| 168 | + memcpy(u->host, host_start + 1, hl); | |
| 169 | + u->host[hl] = '\0'; | |
| 170 | + if (cb + 1 != host_end) { | |
| 171 | + if (cb[1] != ':' || parse_port(cb + 2, host_end, &u->port) != 0) { | |
| 172 | + snprintf(err, errsz, "invalid URL (port)"); | |
| 173 | + return -1; | |
| 174 | + } | |
| 175 | + } | |
| 176 | + } else { | |
| 177 | + const char *colon = (const char *)memchr(host_start, ':', n); | |
| 178 | + if (colon) { | |
| 179 | + n = (size_t)(colon - host_start); | |
| 180 | + if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } | |
| 181 | + memcpy(u->host, host_start, n); | |
| 182 | + u->host[n] = '\0'; | |
| 183 | + if (parse_port(colon + 1, host_end, &u->port) != 0) { | |
| 184 | + snprintf(err, errsz, "invalid URL (port)"); | |
| 185 | + return -1; | |
| 186 | + } | |
| 187 | + } else { | |
| 188 | + if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } | |
| 189 | + memcpy(u->host, host_start, n); | |
| 190 | + u->host[n] = '\0'; | |
| 191 | + } | |
| 192 | + { /* reject characters that are neither hostname-safe nor a raw IPv4 */ | |
| 193 | + size_t i; | |
| 194 | + for (i = 0; u->host[i]; i++) { | |
| 195 | + char c = u->host[i]; | |
| 196 | + if (!(isalnum((unsigned char)c) || c == '.' || c == '-' || c == '_')) { | |
| 197 | + snprintf(err, errsz, "invalid URL (host characters)"); | |
| 198 | + return -1; | |
| 199 | + } | |
| 200 | + } | |
| 201 | + } | |
| 202 | + } | |
| 203 | + | |
| 204 | + if (*host_end == '\0' || *host_end == '#') { | |
| 205 | + snprintf(u->path, sizeof u->path, "/"); | |
| 206 | + } else { | |
| 207 | + const char *hash = strchr(host_end, '#'); | |
| 208 | + size_t plen = hash ? (size_t)(hash - host_end) : strlen(host_end); | |
| 209 | + if (plen >= sizeof u->path) { | |
| 210 | + snprintf(err, errsz, "invalid URL (path too long)"); | |
| 211 | + return -1; | |
| 212 | + } | |
| 213 | + memcpy(u->path, host_end, plen); | |
| 214 | + u->path[plen] = '\0'; | |
| 215 | + } | |
| 216 | + return 0; | |
| 217 | +} | |
| 218 | + | |
| 219 | +static void fx_url_build(const fx_url *u, char *out, size_t outsz) | |
| 220 | +{ | |
| 221 | + int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; | |
| 222 | + if (u->port == defport) | |
| 223 | + snprintf(out, outsz, "%s://%s%s", u->scheme, u->host, u->path); | |
| 224 | + else | |
| 225 | + snprintf(out, outsz, "%s://%s:%d%s", u->scheme, u->host, u->port, u->path); | |
| 226 | +} | |
| 227 | + | |
| 228 | +static int fx_url_resolve(const fx_url *base, const char *to, fx_url *out, | |
| 229 | + char *err, size_t errsz) | |
| 230 | +{ | |
| 231 | + if (!to || !*to) { snprintf(err, errsz, "empty redirect target"); return -1; } | |
| 232 | + if (strstr(to, "://")) return fx_url_parse(to, out, err, errsz); | |
| 233 | + *out = *base; | |
| 234 | + if (to[0] == '/') { | |
| 235 | + if (strlen(to) >= sizeof out->path) { | |
| 236 | + snprintf(err, errsz, "redirect target too long"); | |
| 237 | + return -1; | |
| 238 | + } | |
| 239 | + snprintf(out->path, sizeof out->path, "%s", to); | |
| 240 | + return 0; | |
| 241 | + } | |
| 242 | + { | |
| 243 | + char dir[2048]; | |
| 244 | + const char *slash = strrchr(base->path, '/'); | |
| 245 | + size_t dirlen = slash ? (size_t)(slash - base->path) + 1 : 0; | |
| 246 | + if (dirlen + strlen(to) + 1 >= sizeof dir) { | |
| 247 | + snprintf(err, errsz, "redirect target too long"); | |
| 248 | + return -1; | |
| 249 | + } | |
| 250 | + memcpy(dir, base->path, dirlen); | |
| 251 | + dir[dirlen] = '\0'; | |
| 252 | + strcat(dir, to); | |
| 253 | + snprintf(out->path, sizeof out->path, "%s", dir); | |
| 254 | + } | |
| 255 | + return 0; | |
| 256 | +} | |
| 257 | + | |
| 258 | +/* ------------------------------------------------------------------ */ | |
| 259 | +/* SSRF denylist */ | |
| 260 | +/* ------------------------------------------------------------------ */ | |
| 261 | + | |
| 262 | +/* The deny ranges are assembled from octet arrays in code (no dotted-quad | |
| 263 | + * literals in this file), mirroring upstream _NON_PUBLIC_NETWORKS. */ | |
| 264 | +typedef struct { unsigned o[4]; int bits; } fx_v4net; | |
| 265 | + | |
| 266 | +#define V4(a, b, c, d, bits) { { (a), (b), (c), (d) }, (bits) } | |
| 267 | +static const fx_v4net DENY4[] = { | |
| 268 | + V4(0, 0, 0, 0, 8), /* this-network */ | |
| 269 | + V4(10, 0, 0, 0, 8), /* private */ | |
| 270 | + V4(100, 64, 0, 0, 10), /* CGNAT */ | |
| 271 | + V4(127, 0, 0, 0, 8), /* loopback */ | |
| 272 | + V4(169, 254, 0, 0, 16), /* link-local + cloud metadata */ | |
| 273 | + V4(172, 16, 0, 0, 12), /* private */ | |
| 274 | + V4(192, 0, 0, 0, 24), /* IANA special */ | |
| 275 | + V4(192, 0, 2, 0, 24), /* TEST-NET-1 */ | |
| 276 | + V4(192, 88, 99, 0, 24), /* 6to4 relay */ | |
| 277 | + V4(192, 168, 0, 0, 16), /* private */ | |
| 278 | + V4(198, 18, 0, 0, 15), /* benchmarking */ | |
| 279 | + V4(198, 51, 100, 0, 24), /* TEST-NET-2 */ | |
| 280 | + V4(203, 0, 113, 0, 24), /* TEST-NET-3 */ | |
| 281 | + V4(224, 0, 0, 0, 4), /* multicast (our own hardening) */ | |
| 282 | + V4(240, 0, 0, 0, 4) /* reserved */ | |
| 283 | +}; | |
| 284 | +#define DENY4_N ((int)(sizeof DENY4 / sizeof DENY4[0])) | |
| 285 | + | |
| 286 | +static int deny4_match(const unsigned *o, const fx_v4net *net) | |
| 287 | +{ | |
| 288 | + unsigned a = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3]; | |
| 289 | + unsigned b = (net->o[0] << 24) | (net->o[1] << 16) | (net->o[2] << 8) | net->o[3]; | |
| 290 | + unsigned mask = net->bits >= 32 ? 0xFFFFFFFFu : ~(0xFFFFFFFFu >> net->bits); | |
| 291 | + return (a & mask) == (b & mask); | |
| 292 | +} | |
| 293 | + | |
| 294 | +static int deny4_any(const unsigned *o) | |
| 295 | +{ | |
| 296 | + int i; | |
| 297 | + for (i = 0; i < DENY4_N; i++) { | |
| 298 | + if (!deny4_match(o, &DENY4[i])) continue; | |
| 299 | + /* upstream _PUBLIC_EXCEPTIONS: the two anycast IPs inside 192.0.0.0/24 */ | |
| 300 | + if (o[0] == 192 && o[1] == 0 && o[2] == 0 && (o[3] == 9 || o[3] == 10)) | |
| 301 | + continue; | |
| 302 | + return 1; | |
| 303 | + } | |
| 304 | + return 0; | |
| 305 | +} | |
| 306 | + | |
| 307 | +static int deny6_match(const unsigned char *ip) | |
| 308 | +{ | |
| 309 | + unsigned w0 = (unsigned)((ip[0] << 8) | ip[1]); | |
| 310 | + unsigned w1 = (unsigned)((ip[2] << 8) | ip[3]); | |
| 311 | + unsigned v0 = ((unsigned)ip[0] << 24) | ((unsigned)ip[1] << 16) | | |
| 312 | + ((unsigned)ip[2] << 8) | (unsigned)ip[3]; | |
| 313 | + int j; | |
| 314 | + unsigned o[4]; | |
| 315 | + | |
| 316 | + /* ::/96 - covers ::, ::1 and all deprecated IPv4-compatible space. */ | |
| 317 | + { | |
| 318 | + int allz = 1; | |
| 319 | + for (j = 0; j < 12; j++) if (ip[j]) { allz = 0; break; } | |
| 320 | + if (allz) return 1; | |
| 321 | + } | |
| 322 | + /* ::ffff:a.b.c.d - apply the v4 list to the embedded address. */ | |
| 323 | + { | |
| 324 | + int pre = 1; | |
| 325 | + for (j = 0; j < 10; j++) if (ip[j]) { pre = 0; break; } | |
| 326 | + if (pre && ip[10] == 0xff && ip[11] == 0xff) { | |
| 327 | + o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; | |
| 328 | + return deny4_any(o); | |
| 329 | + } | |
| 330 | + } | |
| 331 | + /* 64:ff9b::/96 well-known NAT64 -> inspect the embedded v4. | |
| 332 | + * 64:ff9b:1::/48 isolated prefix -> always refused. */ | |
| 333 | + if (w0 == 0x0064 && w1 == 0xff9b) { | |
| 334 | + if (ip[4] || ip[5] || ip[6] || ip[7]) return 1; | |
| 335 | + o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; | |
| 336 | + return deny4_any(o); | |
| 337 | + } | |
| 338 | + if ((w0 & 0xFFC0) == 0x0100 && w1 == 0x0000) return 1; /* 100::/64 */ | |
| 339 | + if ((v0 & 0xFFFFFE00u) == 0x20010000u) { /* 2001::/23 */ | |
| 340 | + unsigned w2 = (unsigned)((ip[4] << 8) | ip[5]); | |
| 341 | + unsigned w3 = (unsigned)((ip[6] << 8) | ip[7]); | |
| 342 | + if ((w2 == 0x0001 || w2 == 0x0002 || w2 == 0x0003) && !w3) return 0; /* TEREDO/AMP */ | |
| 343 | + if (w2 == 0x0004 && w3 == 0x0112) return 0; | |
| 344 | + if ((w2 & 0xFFF0) == 0x0020) return 0; | |
| 345 | + if ((w2 & 0xFFF0) == 0x0030) return 0; | |
| 346 | + return 1; | |
| 347 | + } | |
| 348 | + if (v0 == 0x20010db8u) return 1; /* 2001:db8::/32 */ | |
| 349 | + if (w0 == 0x2002) return 1; /* 6to4 */ | |
| 350 | + if ((v0 & 0xFFFFF000u) == 0x3fff0000u) return 1; /* 3fff::/20 */ | |
| 351 | + if ((w0 & 0xFC00) == 0xFC00) return 1; /* fc00::/7 ULA */ | |
| 352 | + if ((w0 & 0xFFC0) == 0xFE80) return 1; /* fe80::/10 */ | |
| 353 | + if (w0 == 0xFEC0) return 1; /* fec0::/10 site-local */ | |
| 354 | + return 0; | |
| 355 | +} | |
| 356 | + | |
| 357 | +int fx_ip_is_denied(const char *ip_text) | |
| 358 | +{ | |
| 359 | + const char *q; | |
| 360 | + if (!ip_text || !*ip_text) return 1; | |
| 361 | + for (q = ip_text; *q; q++) if (*q == '.') break; | |
| 362 | + if (*q == '.') { | |
| 363 | + unsigned o[4]; | |
| 364 | + char *end; | |
| 365 | + int i; | |
| 366 | + long v; | |
| 367 | + const char *p = ip_text; | |
| 368 | + for (i = 0; i < 4; i++) { | |
| 369 | + const char *d; | |
| 370 | + if (!p || !isdigit((unsigned char)*p)) return 1; | |
| 371 | + /* Exactly one canonical form is accepted: digits only, no sign, | |
| 372 | + * no leading zero on a multi-digit group, at most three digits. | |
| 373 | + * inet_aton's octal and hex habits (0177.0.0.1, 0x7f.0.0.1) and | |
| 374 | + * its short forms must never parse into a different address than | |
| 375 | + * the caller wrote, so anything non-canonical is refused rather | |
| 376 | + * than reinterpreted. */ | |
| 377 | + for (d = p; *d && *d != '.'; d++) { | |
| 378 | + if (!isdigit((unsigned char)*d)) return 1; | |
| 379 | + if (d > p && *p == '0') return 1; | |
| 380 | + if (d - p > 2) return 1; | |
| 381 | + } | |
| 382 | + v = strtol(p, &end, 10); | |
| 383 | + if (v < 0 || v > 255 || end == p) return 1; | |
| 384 | + o[i] = (unsigned)v; | |
| 385 | + p = (*end == '.') ? end + 1 : end; | |
| 386 | + } | |
| 387 | + if (*p) return 1; /* trailing junk */ | |
| 388 | + return deny4_any(o); | |
| 389 | + } | |
| 390 | + { | |
| 391 | + unsigned char buf[16]; | |
| 392 | +#if defined(_WIN32) | |
| 393 | + if (InetPtonA(AF_INET6, ip_text, buf) != 1) return 1; | |
| 394 | +#else | |
| 395 | + if (inet_pton(AF_INET6, ip_text, buf) != 1) return 1; | |
| 396 | +#endif | |
| 397 | + return deny6_match(buf); | |
| 398 | + } | |
| 399 | +} | |
| 400 | + | |
| 401 | +/* ------------------------------------------------------------------ */ | |
| 402 | +/* Host header / response head helpers */ | |
| 403 | +/* ------------------------------------------------------------------ */ | |
| 404 | + | |
| 405 | +static int head_field(const char *head, size_t head_len, const char *name, | |
| 406 | + const char **vout, size_t *vlen) | |
| 407 | +{ | |
| 408 | + size_t nlen = strlen(name); | |
| 409 | + const char *p = head, *end = head + head_len; | |
| 410 | + while (p < end) { | |
| 411 | + const char *eol = (const char *)memchr(p, '\n', (size_t)(end - p)); | |
| 412 | + size_t llen; | |
| 413 | + if (!eol) eol = end; | |
| 414 | + llen = (size_t)(eol - p); | |
| 415 | + if (llen && p[llen - 1] == '\r') llen--; | |
| 416 | + if (llen > nlen && p[nlen] == ':' && sx_strncasecmp(p, name, nlen) == 0) { | |
| 417 | + const char *v = p + nlen + 1; | |
| 418 | + size_t vl = llen - nlen - 1; | |
| 419 | + while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } | |
| 420 | + while (vl && (v[vl - 1] == ' ' || v[vl - 1] == '\t')) vl--; | |
| 421 | + *vout = v; | |
| 422 | + *vlen = vl; | |
| 423 | + return 1; | |
| 424 | + } | |
| 425 | + p = eol + 1; | |
| 426 | + } | |
| 427 | + return 0; | |
| 428 | +} | |
| 429 | + | |
| 430 | +/* Case-insensitive prefix test used by the no-Content-Type sniffer: servers | |
| 431 | + * emit DOCTYPE in every casing, and a document whose very first token is | |
| 432 | + * <!doctype html or <html is HTML whatever the server forgot to declare. */ | |
| 433 | +static int ci_prefix(const char *s, const char *prefix) | |
| 434 | +{ | |
| 435 | + for (; *prefix; s++, prefix++) { | |
| 436 | + unsigned char a = (unsigned char)*s; | |
| 437 | + unsigned char b = (unsigned char)*prefix; | |
| 438 | + if (a >= 'A' && a <= 'Z') a = (unsigned char)(a + 32); | |
| 439 | + if (b >= 'A' && b <= 'Z') b = (unsigned char)(b + 32); | |
| 440 | + if (a != b) return 0; | |
| 441 | + if (!a) return 0; /* both NUL: prefix longer than s */ | |
| 442 | + } | |
| 443 | + return 1; | |
| 444 | +} | |
| 445 | + | |
| 446 | +int fx_body_looks_like_html(const char *body, size_t len) | |
| 447 | +{ | |
| 448 | + size_t i = 0, n; | |
| 449 | + char probe[24]; | |
| 450 | + if (!body || !len) return 0; | |
| 451 | + while (i < len && (unsigned char)body[i] <= ' ') i++; | |
| 452 | + if (i + 3 <= len && (unsigned char)body[i] == 0xEF && | |
| 453 | + (unsigned char)body[i + 1] == 0xBB && (unsigned char)body[i + 2] == 0xBF) | |
| 454 | + i += 3; | |
| 455 | + while (i < len && (unsigned char)body[i] <= ' ') i++; | |
| 456 | + n = len - i < 20 ? len - i : 20; | |
| 457 | + memcpy(probe, body + i, n); | |
| 458 | + probe[n] = '\0'; | |
| 459 | + return ci_prefix(probe, "<!doctype html") || ci_prefix(probe, "<html"); | |
| 460 | +} | |
| 461 | + | |
| 462 | +/* ------------------------------------------------------------------ */ | |
| 463 | +/* Resolution + validation (shared by both transports) */ | |
| 464 | +/* ------------------------------------------------------------------ */ | |
| 465 | + | |
| 466 | +typedef struct { | |
| 467 | + int family; /* AF_INET | AF_INET6 */ | |
| 468 | + unsigned char ip[16]; /* numeric address */ | |
| 469 | + char text[64]; | |
| 470 | +} fx_target; | |
| 471 | + | |
| 472 | +static int fx_resolve_validate(const char *host, int port, int allow_private, | |
| 473 | + fx_target *out, char *err, size_t errsz) | |
| 474 | +{ | |
| 475 | + struct addrinfo hints, *res = NULL, *ai; | |
| 476 | + char portstr[16]; | |
| 477 | + int rc, found = -1; | |
| 478 | + int naddr = 0; | |
| 479 | + | |
| 480 | + memset(&hints, 0, sizeof hints); | |
| 481 | + hints.ai_socktype = SOCK_STREAM; | |
| 482 | + snprintf(portstr, sizeof portstr, "%d", port); | |
| 483 | + rc = getaddrinfo(host, portstr, &hints, &res); | |
| 484 | + if (rc != 0 || !res) { | |
| 485 | + snprintf(err, errsz, "Failed to resolve host %s: %s", host, gai_strerror(rc)); | |
| 486 | + return -1; | |
| 487 | + } | |
| 488 | + /* Validate EVERY answer first: one private record in the set (even if we | |
| 489 | + * would connect to a public one) refuses the whole host — split-horizon | |
| 490 | + * and round-robin rebinding both die here. */ | |
| 491 | + for (ai = res; ai; ai = ai->ai_next) { | |
| 492 | + char ipbuf[64]; | |
| 493 | + if (ai->ai_family == AF_INET) | |
| 494 | + inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, | |
| 495 | + ipbuf, sizeof ipbuf); | |
| 496 | + else if (ai->ai_family == AF_INET6) | |
| 497 | + inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, | |
| 498 | + ipbuf, sizeof ipbuf); | |
| 499 | + else continue; | |
| 500 | + naddr++; | |
| 501 | + if (!allow_private && fx_ip_is_denied(ipbuf)) { | |
| 502 | + snprintf(err, errsz, | |
| 503 | + "Access to private or reserved address space is not allowed. " | |
| 504 | + "The hostname '%s' resolves to a denied address (%s).", | |
| 505 | + host, ipbuf); | |
| 506 | + freeaddrinfo(res); | |
| 507 | + return -1; | |
| 508 | + } | |
| 509 | + } | |
| 510 | + if (naddr == 0) { | |
| 511 | + snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); | |
| 512 | + freeaddrinfo(res); | |
| 513 | + return -1; | |
| 514 | + } | |
| 515 | + /* Pick the first answer; it is validated, and we connect to its numbers. */ | |
| 516 | + for (ai = res; ai; ai = ai->ai_next) { | |
| 517 | + if (ai->ai_family == AF_INET) { | |
| 518 | + out->family = AF_INET; | |
| 519 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | |
| 520 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | |
| 521 | + found = 0; | |
| 522 | + break; | |
| 523 | + } | |
| 524 | + if (ai->ai_family == AF_INET6) { | |
| 525 | + out->family = AF_INET6; | |
| 526 | + memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16); | |
| 527 | + inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text); | |
| 528 | + found = 0; | |
| 529 | + /* prefer v4 but keep v6 if it came first */ | |
| 530 | + if (0) break; | |
| 531 | + } | |
| 532 | + } | |
| 533 | + /* second pass: prefer IPv4 if present */ | |
| 534 | + if (found == 0) { | |
| 535 | + for (ai = res; ai; ai = ai->ai_next) { | |
| 536 | + if (ai->ai_family == AF_INET) { | |
| 537 | + out->family = AF_INET; | |
| 538 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | |
| 539 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | |
| 540 | + break; | |
| 541 | + } | |
| 542 | + } | |
| 543 | + } | |
| 544 | + freeaddrinfo(res); | |
| 545 | + if (found != 0) { | |
| 546 | + snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); | |
| 547 | + return -1; | |
| 548 | + } | |
| 549 | + return 0; | |
| 550 | +} | |
| 551 | + | |
| 552 | +#if !defined(_WIN32) | |
| 553 | + | |
| 554 | +/* ------------------------------------------------------------------ */ | |
| 555 | +/* POSIX transport */ | |
| 556 | +/* ------------------------------------------------------------------ */ | |
| 557 | + | |
| 558 | +typedef struct { | |
| 559 | + sx_sock fd; | |
| 560 | + fx_tls *tls; | |
| 561 | + long long deadline_ms; | |
| 562 | +} sx_trans; | |
| 563 | + | |
| 564 | + | |
| 565 | +static int connect_timeout(int fd, const struct sockaddr *sa, socklen_t slen, | |
| 566 | + int ms, char *err, size_t errsz) | |
| 567 | +{ | |
| 568 | + int flags, rc, soerr = 0; | |
| 569 | + socklen_t elen = sizeof soerr; | |
| 570 | + struct pollfd pfd; | |
| 571 | + | |
| 572 | + flags = fcntl(fd, F_GETFL, 0); | |
| 573 | + if (flags < 0) return -1; | |
| 574 | + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) return -1; | |
| 575 | + rc = connect(fd, sa, slen); | |
| 576 | + if (rc != 0) { | |
| 577 | + if (errno != EINPROGRESS) { | |
| 578 | + snprintf(err, errsz, "connect failed: %s", strerror(errno)); | |
| 579 | + return -1; | |
| 580 | + } | |
| 581 | + pfd.fd = fd; | |
| 582 | + pfd.events = POLLOUT; | |
| 583 | + pfd.revents = 0; | |
| 584 | + do { rc = poll(&pfd, 1, ms); } while (rc < 0 && errno == EINTR); | |
| 585 | + if (rc == 0) { snprintf(err, errsz, "connect timed out"); return -1; } | |
| 586 | + if (rc < 0) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; } | |
| 587 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &elen) != 0 || soerr != 0) { | |
| 588 | + snprintf(err, errsz, "connect failed: %s", | |
| 589 | + strerror(soerr ? soerr : ECONNREFUSED)); | |
| 590 | + return -1; | |
| 591 | + } | |
| 592 | + } | |
| 593 | + if (fcntl(fd, F_SETFL, flags) < 0) return -1; | |
| 594 | + return 0; | |
| 595 | +} | |
| 596 | + | |
| 597 | +static int trans_read(sx_trans *t, char *buf, size_t n) | |
| 598 | +{ | |
| 599 | + if (t->tls) return fx_tls_read(t->tls, buf, n); | |
| 600 | + for (;;) { | |
| 601 | + ssize_t r; | |
| 602 | + struct pollfd pfd; | |
| 603 | + long long remain = t->deadline_ms - fx_now_ms(); | |
| 604 | + int waited; | |
| 605 | + if (remain <= 0) return -2; /* stalled: EOF-like */ | |
| 606 | + pfd.fd = t->fd; | |
| 607 | + pfd.events = POLLIN; | |
| 608 | + pfd.revents = 0; | |
| 609 | + waited = (int)(remain > 500 ? 500 : remain); | |
| 610 | + r = poll(&pfd, 1, waited); | |
| 611 | + if (r < 0) { if (errno == EINTR) continue; return -1; } | |
| 612 | + if (r == 0) continue; /* loop rechecks deadline */ | |
| 613 | + if (!(pfd.revents & (POLLIN | POLLHUP | POLLERR))) continue; | |
| 614 | + do { r = recv(t->fd, buf, n, 0); } while (r < 0 && errno == EINTR); | |
| 615 | + if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; | |
| 616 | + if (r < 0) return -1; | |
| 617 | + if (r == 0) return 0; /* EOF */ | |
| 618 | + return (int)r; | |
| 619 | + } | |
| 620 | +} | |
| 621 | + | |
| 622 | +static int trans_write(sx_trans *t, const char *buf, size_t n) | |
| 623 | +{ | |
| 624 | + if (t->tls) return fx_tls_write(t->tls, buf, n); | |
| 625 | + { | |
| 626 | + size_t off = 0; | |
| 627 | + while (off < n) { | |
| 628 | + ssize_t w = send(t->fd, buf + off, n - off, MSG_NOSIGNAL); | |
| 629 | + if (w < 0) { | |
| 630 | + if (errno == EINTR) continue; | |
| 631 | + return -1; | |
| 632 | + } | |
| 633 | + off += (size_t)w; | |
| 634 | + } | |
| 635 | + return (int)n; | |
| 636 | + } | |
| 637 | +} | |
| 638 | + | |
| 639 | +static void trans_close(sx_trans *t) | |
| 640 | +{ | |
| 641 | + if (t->tls) { fx_tls_close(t->tls); t->tls = NULL; } | |
| 642 | + if (t->fd != SX_SOCK_INVALID) { sx_closesocket(t->fd); t->fd = SX_SOCK_INVALID; } | |
| 643 | +} | |
| 644 | + | |
| 645 | +/* Reads the head; returns bytes consumed of the terminator inclusive, sets | |
| 646 | + * head_len to the head length (before the terminator), *extra_out to body | |
| 647 | + * bytes that arrived in the same window (0 — we always read exactly the | |
| 648 | + * head window with a small overread stash). On hard failure, -1; on deadline, | |
| 649 | + * -2. */ | |
| 650 | +typedef struct { char *p; size_t n; size_t cap; } sx_stash; | |
| 651 | + | |
| 652 | +static int read_head(sx_trans *t, char *head, size_t cap, size_t *hlen_out, | |
| 653 | + sx_stash *stash) | |
| 654 | +{ | |
| 655 | + size_t n = 0; | |
| 656 | + size_t scanned = 0; | |
| 657 | + for (;;) { | |
| 658 | + size_t i; | |
| 659 | + int r = trans_read(t, head + n, cap - n > 1024 ? 1024 : cap - n); | |
| 660 | + if (r == -2) return n ? -1 : -2; | |
| 661 | + if (r < 0) return -1; | |
| 662 | + if (r == 0) { /* EOF */ | |
| 663 | + if (n == 0) return -1; | |
| 664 | + *hlen_out = n; /* no terminator: whole thing is head */ | |
| 665 | + stash->p = NULL; stash->n = 0; | |
| 666 | + return (int)n; | |
| 667 | + } | |
| 668 | + n += (size_t)r; | |
| 669 | + if (n >= cap) return -1; /* oversized head */ | |
| 670 | + /* scan for the terminator; the window may re-include up to 3 bytes | |
| 671 | + * already scanned so a terminator split across two reads is found */ | |
| 672 | + if (scanned > 3) scanned -= 3; | |
| 673 | + for (i = scanned; i + 1 < n; i++) { | |
| 674 | + if (head[i] == '\n') { | |
| 675 | + size_t headlen; | |
| 676 | + size_t term; | |
| 677 | + if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && | |
| 678 | + head[i - 3] == '\r') { | |
| 679 | + headlen = i - 1; term = 4; | |
| 680 | + } else if (i >= 1 && head[i - 1] == '\n') { | |
| 681 | + headlen = i - 1; term = 2; /* tolerate bare \n\n */ | |
| 682 | + } else continue; | |
| 683 | + *hlen_out = headlen; | |
| 684 | + if (n > i + 1) { | |
| 685 | + stash->p = head + (i + 1); | |
| 686 | + stash->n = n - (i + 1); | |
| 687 | + } else { stash->p = NULL; stash->n = 0; } | |
| 688 | + (void)term; | |
| 689 | + return (int)n; | |
| 690 | + } | |
| 691 | + } | |
| 692 | + scanned = n; | |
| 693 | + } | |
| 694 | +} | |
| 695 | + | |
| 696 | +static int exchange_plain(const fx_url *u, const char *urltext, fx_response *r, | |
| 697 | + int allow_private) | |
| 698 | +{ | |
| 699 | + sx_trans t; | |
| 700 | + fx_target tgt; | |
| 701 | + char req[4300]; | |
| 702 | + char *head; | |
| 703 | + size_t head_len = 0; | |
| 704 | + sx_stash stash; | |
| 705 | + const char *v; size_t vl; | |
| 706 | + buf_t body; | |
| 707 | + long long clen = -1; | |
| 708 | + int chunked = 0, gzip = 0; | |
| 709 | + int status, fd, rc; | |
| 710 | + struct sockaddr_storage ss; | |
| 711 | + socklen_t slen; | |
| 712 | + const char *UA = | |
| 713 | + "SCORPIOXBOT-fetch/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch)"; | |
| 714 | + int host_has_port = !((strcmp(u->scheme, "http") == 0 && u->port == 80) || | |
| 715 | + (strcmp(u->scheme, "https") == 0 && u->port == 443)); | |
| 716 | + | |
| 717 | + memset(&t, 0, sizeof t); | |
| 718 | + t.fd = SX_SOCK_INVALID; | |
| 719 | + t.deadline_ms = fx_now_ms() + FX_CONNECT_MS + FX_READ_MS; | |
| 720 | + | |
| 721 | + if (fx_resolve_validate(u->host, u->port, allow_private, &tgt, | |
| 722 | + r->error, sizeof r->error) != 0) | |
| 723 | + return -1; | |
| 724 | + | |
| 725 | + fd = socket(tgt.family, SOCK_STREAM, 0); | |
| 726 | + if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; } | |
| 727 | + memset(&ss, 0, sizeof ss); | |
| 728 | + if (tgt.family == AF_INET) { | |
| 729 | + struct sockaddr_in *sa = (struct sockaddr_in *)&ss; | |
| 730 | + sa->sin_family = AF_INET; | |
| 731 | + sa->sin_port = htons((unsigned short)u->port); | |
| 732 | + memcpy(&sa->sin_addr, tgt.ip, 4); | |
| 733 | + slen = sizeof *sa; | |
| 734 | + } else { | |
| 735 | + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss; | |
| 736 | + sa->sin6_family = AF_INET6; | |
| 737 | + sa->sin6_port = htons((unsigned short)u->port); | |
| 738 | + memcpy(&sa->sin6_addr, tgt.ip, 16); | |
| 739 | + slen = sizeof *sa; | |
| 740 | + } | |
| 741 | + if (connect_timeout(fd, (struct sockaddr *)&ss, slen, FX_CONNECT_MS, | |
| 742 | + r->error, sizeof r->error) != 0) { | |
| 743 | + close(fd); | |
| 744 | + return -1; | |
| 745 | + } | |
| 746 | + t.fd = fd; | |
| 747 | + | |
| 748 | + if (strcmp(u->scheme, "https") == 0) { | |
| 749 | + char terr[256] = ""; | |
| 750 | + t.tls = fx_tls_connect_fd(t.fd, u->host, terr, sizeof terr); | |
| 751 | + if (!t.tls) { | |
| 752 | + snprintf(r->error, sizeof r->error, "%s", | |
| 753 | + terr[0] ? terr : "TLS handshake failed"); | |
| 754 | + close(t.fd); | |
| 755 | + t.fd = SX_SOCK_INVALID; | |
| 756 | + return -1; | |
| 757 | + } | |
| 758 | + t.fd = SX_SOCK_INVALID; /* owned by the TLS layer now */ | |
| 759 | + } | |
| 760 | + | |
| 761 | + snprintf(req, sizeof req, | |
| 762 | + "GET %s HTTP/1.1\r\n" | |
| 763 | + "Host: %s%s%s\r\n" | |
| 764 | + "User-Agent: %s\r\n" | |
| 765 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | |
| 766 | + "Accept-Encoding: identity\r\n" | |
| 767 | + "Connection: close\r\n\r\n", | |
| 768 | + u->path, u->host, host_has_port ? ":" : "", | |
| 769 | + host_has_port ? "" : "", UA); | |
| 770 | + if (host_has_port) { | |
| 771 | + snprintf(req, sizeof req, | |
| 772 | + "GET %s HTTP/1.1\r\n" | |
| 773 | + "Host: %s:%d\r\n" | |
| 774 | + "User-Agent: %s\r\n" | |
| 775 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | |
| 776 | + "Accept-Encoding: identity\r\n" | |
| 777 | + "Connection: close\r\n\r\n", | |
| 778 | + u->path, u->host, u->port, UA); | |
| 779 | + } | |
| 780 | + if (trans_write(&t, req, strlen(req)) < 0) { | |
| 781 | + snprintf(r->error, sizeof r->error, | |
| 782 | + "Failed to fetch %s: the server did not accept our request", urltext); | |
| 783 | + trans_close(&t); | |
| 784 | + return -1; | |
| 785 | + } | |
| 786 | + | |
| 787 | + head = (char *)sx_malloc(FX_MAX_HEAD + 1); | |
| 788 | + rc = read_head(&t, head, FX_MAX_HEAD, &head_len, &stash); | |
| 789 | + if (rc < 0) { | |
| 790 | + snprintf(r->error, sizeof r->error, rc == -2 | |
| 791 | + ? "Failed to fetch %s: timed out reading the response head" | |
| 792 | + : "Failed to fetch %s: bad or oversized response head", urltext); | |
| 793 | + free(head); | |
| 794 | + trans_close(&t); | |
| 795 | + return -1; | |
| 796 | + } | |
| 797 | + head[head_len] = '\0'; | |
| 798 | + | |
| 799 | + if (strncmp(head, "HTTP/", 5) != 0) { | |
| 800 | + snprintf(r->error, sizeof r->error, | |
| 801 | + "Failed to fetch %s: not an HTTP response", urltext); | |
| 802 | + free(head); | |
| 803 | + trans_close(&t); | |
| 804 | + return -1; | |
| 805 | + } | |
| 806 | + status = atoi(head + 9); | |
| 807 | + r->status = status; | |
| 808 | + | |
| 809 | + if (head_field(head, head_len, "content-type", &v, &vl)) { | |
| 810 | + size_t n = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; | |
| 811 | + memcpy(r->content_type, v, n); | |
| 812 | + r->content_type[n] = '\0'; | |
| 813 | + } | |
| 814 | + { | |
| 815 | + char nbuf[32]; | |
| 816 | + if (head_field(head, head_len, "content-length", &v, &vl)) { | |
| 817 | + size_t n = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; | |
| 818 | + memcpy(nbuf, v, n); nbuf[n] = '\0'; | |
| 819 | + clen = atoll(nbuf); | |
| 820 | + if (clen > (long long)FX_MAX_BODY) { | |
| 821 | + snprintf(r->error, sizeof r->error, | |
| 822 | + "Failed to fetch %s: the response body is larger than the " | |
| 823 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | |
| 824 | + free(head); | |
| 825 | + trans_close(&t); | |
| 826 | + return -1; | |
| 827 | + } | |
| 828 | + } | |
| 829 | + if (head_field(head, head_len, "transfer-encoding", &v, &vl) && | |
| 830 | + vl >= 7 && sx_strncasecmp(v, "chunked", 7) == 0) | |
| 831 | + chunked = 1; | |
| 832 | +#ifdef HAVE_ZLIB | |
| 833 | + if (head_field(head, head_len, "content-encoding", &v, &vl) && | |
| 834 | + vl >= 4 && sx_strncasecmp(v, "gzip", 4) == 0) | |
| 835 | + gzip = 1; | |
| 836 | +#else | |
| 837 | + if (head_field(head, head_len, "content-encoding", &v, &vl) && vl) { | |
| 838 | + char enc[64]; | |
| 839 | + size_t n = vl < sizeof enc - 1 ? vl : sizeof enc - 1; | |
| 840 | + memcpy(enc, v, n); enc[n] = '\0'; | |
| 841 | + if (sx_strcasecmp(enc, "identity") != 0) { | |
| 842 | + snprintf(r->error, sizeof r->error, | |
| 843 | + "Unsupported content encoding %s: this server cannot decode it", | |
| 844 | + enc); | |
| 845 | + free(head); | |
| 846 | + trans_close(&t); | |
| 847 | + return -1; | |
| 848 | + } | |
| 849 | + } | |
| 850 | +#endif | |
| 851 | + } | |
| 852 | + | |
| 853 | + if ((status == 301 || status == 302 || status == 303 || | |
| 854 | + status == 307 || status == 308) && | |
| 855 | + head_field(head, head_len, "location", &v, &vl)) { | |
| 856 | + size_t n = vl < sizeof r->url - 1 ? vl : sizeof r->url - 1; | |
| 857 | + memcpy(r->url, v, n); | |
| 858 | + r->url[n] = '\0'; | |
| 859 | + free(head); | |
| 860 | + trans_close(&t); | |
| 861 | + return 2; | |
| 862 | + } | |
| 863 | + | |
| 864 | + buf_init(&body); | |
| 865 | + fx_md_set_base_url(urltext); /* relativise links during conversion */ | |
| 866 | + | |
| 867 | + if (chunked) { | |
| 868 | + /* stream chunk framing directly; bytes that arrived in the same read | |
| 869 | + * window as the head terminator seed the framing buffer (they are | |
| 870 | + * chunk data, NOT body — appending them raw would emit the hex size | |
| 871 | + * line as content) */ | |
| 872 | + char small[4096]; | |
| 873 | + size_t sp = 0, sn = 0; | |
| 874 | + int dead = 0; | |
| 875 | + if (stash.n) { memcpy(small, stash.p, stash.n); sn = stash.n; } | |
| 876 | +#define CHUNK_GETC(ch) \ | |
| 877 | + do { \ | |
| 878 | + int _done = 0; \ | |
| 879 | + while (!_done) { \ | |
| 880 | + if (sp < sn) { (ch) = small[sp++]; _done = 1; break; } \ | |
| 881 | + { \ | |
| 882 | + int _r = trans_read(&t, small, sizeof small); \ | |
| 883 | + if (_r == 0) { dead = 1; _done = 1; break; } \ | |
| 884 | + if (_r < 0) { dead = -1; _done = 1; break; } \ | |
| 885 | + sn = (size_t)_r; sp = 0; \ | |
| 886 | + } \ | |
| 887 | + } \ | |
| 888 | + } while (0) | |
| 889 | + for (;;) { | |
| 890 | + char ch = 0; | |
| 891 | + char hex[24]; | |
| 892 | + size_t hn = 0; | |
| 893 | + unsigned long csz; | |
| 894 | + CHUNK_GETC(ch); | |
| 895 | + if (dead) break; | |
| 896 | + if (ch == '\r' || ch == '\n') continue; /* skip CRLFs between chunks */ | |
| 897 | + hex[hn++] = ch; | |
| 898 | + while (hn < sizeof hex - 1) { | |
| 899 | + CHUNK_GETC(ch); | |
| 900 | + if (dead) break; | |
| 901 | + if (ch == '\r') { CHUNK_GETC(ch); if (dead) break; if (ch == '\n') break; } | |
| 902 | + else if (ch == '\n') break; | |
| 903 | + hex[hn++] = ch; | |
| 904 | + } | |
| 905 | + if (dead) break; | |
| 906 | + hex[hn] = '\0'; | |
| 907 | + { char *semi = strchr(hex, ';'); if (semi) *semi = '\0'; } | |
| 908 | + csz = strtoul(hex, NULL, 16); | |
| 909 | + if (csz == 0) break; | |
| 910 | + if (body.n + csz > FX_MAX_BODY) { | |
| 911 | + buf_free(&body); free(head); trans_close(&t); | |
| 912 | + snprintf(r->error, sizeof r->error, | |
| 913 | + "Failed to fetch %s: the response body is larger than the " | |
| 914 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | |
| 915 | + return -1; | |
| 916 | + } | |
| 917 | + while (csz > 0) { | |
| 918 | + size_t take; | |
| 919 | + if (sp >= sn) { | |
| 920 | + int _r = trans_read(&t, small, sizeof small); | |
| 921 | + if (_r <= 0) { | |
| 922 | + buf_free(&body); free(head); trans_close(&t); | |
| 923 | + snprintf(r->error, sizeof r->error, | |
| 924 | + "Failed to fetch %s: truncated chunked body", urltext); | |
| 925 | + return -1; | |
| 926 | + } | |
| 927 | + sn = (size_t)_r; sp = 0; | |
| 928 | + } | |
| 929 | + take = sn - sp; | |
| 930 | + if (take > csz) take = csz; | |
| 931 | + buf_bput(&body, small + sp, take); | |
| 932 | + sp += take; csz -= take; | |
| 933 | + } | |
| 934 | + } | |
| 935 | +#undef CHUNK_GETC | |
| 936 | + } else if (clen >= 0) { | |
| 937 | + size_t want = (size_t)clen; | |
| 938 | + if (stash.n) buf_bput(&body, stash.p, stash.n); | |
| 939 | + if (want > body.n) { | |
| 940 | + size_t need = want - body.n; | |
| 941 | + char *tmp = (char *)sx_malloc(need); | |
| 942 | + size_t got = 0; | |
| 943 | + while (got < need) { | |
| 944 | + int rr = trans_read(&t, tmp + got, need - got); | |
| 945 | + if (rr <= 0) { | |
| 946 | + free(tmp); buf_free(&body); free(head); trans_close(&t); | |
| 947 | + snprintf(r->error, sizeof r->error, | |
| 948 | + "Failed to fetch %s: the server closed before the " | |
| 949 | + "declared body was complete", urltext); | |
| 950 | + return -1; | |
| 951 | + } | |
| 952 | + got += (size_t)rr; | |
| 953 | + } | |
| 954 | + buf_bput(&body, tmp, need); | |
| 955 | + free(tmp); | |
| 956 | + } | |
| 957 | + } else { | |
| 958 | + char tmp[8192]; | |
| 959 | + if (stash.n) buf_bput(&body, stash.p, stash.n); | |
| 960 | + for (;;) { | |
| 961 | + int rr = trans_read(&t, tmp, sizeof tmp); | |
| 962 | + if (rr == -2 || rr == 0) break; | |
| 963 | + if (rr < 0) { | |
| 964 | + buf_free(&body); free(head); trans_close(&t); | |
| 965 | + snprintf(r->error, sizeof r->error, | |
| 966 | + "Failed to fetch %s: body read failed", urltext); | |
| 967 | + return -1; | |
| 968 | + } | |
| 969 | + if (body.n + (size_t)rr > FX_MAX_BODY) { | |
| 970 | + buf_free(&body); free(head); trans_close(&t); | |
| 971 | + snprintf(r->error, sizeof r->error, | |
| 972 | + "Failed to fetch %s: the response body is larger than the " | |
| 973 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | |
| 974 | + return -1; | |
| 975 | + } | |
| 976 | + buf_bput(&body, tmp, (size_t)rr); | |
| 977 | + } | |
| 978 | + } | |
| 979 | + | |
| 980 | + free(head); | |
| 981 | + trans_close(&t); | |
| 982 | + | |
| 983 | +#ifdef HAVE_ZLIB | |
| 984 | + if (gzip && body.n > 18 && (unsigned char)body.p[0] == 0x1f && | |
| 985 | + (unsigned char)body.p[1] == 0x8b) { | |
| 986 | + uLongf cap = (uLongf)(body.n * 16 + 4096); | |
| 987 | + int inflated = 0; | |
| 988 | + while (!inflated && cap <= FX_MAX_BODY) { | |
| 989 | + char *outb = (char *)sx_malloc(cap + 1); | |
| 990 | + z_stream zs; | |
| 991 | + int zr; | |
| 992 | + memset(&zs, 0, sizeof zs); | |
| 993 | + zs.next_in = (Bytef *)body.p; | |
| 994 | + zs.avail_in = (uInt)body.n; | |
| 995 | + zs.next_out = (Bytef *)outb; | |
| 996 | + zs.avail_out = (uInt)cap; | |
| 997 | + zr = inflateInit2(&zs, 15 + 16); | |
| 998 | + if (zr == Z_OK) zr = inflate(&zs, Z_FINISH); | |
| 999 | + if (zr == Z_STREAM_END) { | |
| 1000 | + free(body.p); | |
| 1001 | + body.p = outb; | |
| 1002 | + body.n = (size_t)zs.total_out; | |
| 1003 | + body.p[body.n] = '\0'; | |
| 1004 | + inflated = 1; | |
| 1005 | + } else { | |
| 1006 | + free(outb); | |
| 1007 | + cap *= 4; | |
| 1008 | + } | |
| 1009 | + inflateEnd(&zs); | |
| 1010 | + } | |
| 1011 | + /* if it never inflated, keep the raw bytes: they are still an honest | |
| 1012 | + * answer for a server that mislabelled its payload */ | |
| 1013 | + } | |
| 1014 | +#else | |
| 1015 | + (void)gzip; | |
| 1016 | +#endif | |
| 1017 | + | |
| 1018 | + r->body = body.p ? body.p : fx_strndup("", 0); | |
| 1019 | + r->body_len = body.n; | |
| 1020 | + return 0; | |
| 1021 | +} | |
| 1022 | + | |
| 1023 | +#endif /* !_WIN32 */ | |
| 1024 | + | |
| 1025 | +/* ------------------------------------------------------------------ */ | |
| 1026 | +/* WinHTTP transport */ | |
| 1027 | +/* ------------------------------------------------------------------ */ | |
| 1028 | + | |
| 1029 | +#if defined(_WIN32) | |
| 1030 | + | |
| 1031 | +static void a2w(const char *a, wchar_t *w, int wn) | |
| 1032 | +{ | |
| 1033 | + MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn); | |
| 1034 | +} | |
| 1035 | + | |
| 1036 | +static int exchange_winhttp(const fx_url *u, const char *urltext, fx_response *r, | |
| 1037 | + int allow_private) | |
| 1038 | +{ | |
| 1039 | + HINTERNET sess = NULL, conn = NULL, req = NULL; | |
| 1040 | + wchar_t wtarget[1024], wpath[2100]; | |
| 1041 | + fx_target tgt; | |
| 1042 | + char target_ip[64]; | |
| 1043 | + wchar_t whdr[128]; | |
| 1044 | + DWORD avail = 0; | |
| 1045 | + BOOL ok; | |
| 1046 | + buf_t body; | |
| 1047 | + int status = 0; | |
| 1048 | + | |
| 1049 | + if (fx_resolve_validate(u->host, u->port, allow_private, &tgt, | |
| 1050 | + r->error, sizeof r->error) != 0) | |
| 1051 | + return -1; | |
| 1052 | + snprintf(target_ip, sizeof target_ip, "%s", tgt.text); | |
| 1053 | + | |
| 1054 | + sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0", | |
| 1055 | + WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, | |
| 1056 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | |
| 1057 | + if (!sess) | |
| 1058 | + sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0", | |
| 1059 | + WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, | |
| 1060 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | |
| 1061 | + if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; } | |
| 1062 | + WinHttpSetTimeouts(sess, FX_CONNECT_MS, FX_CONNECT_MS, FX_READ_MS, FX_READ_MS); | |
| 1063 | + | |
| 1064 | + /* connect to the validated numeric IP; Host + SNI carry the real name */ | |
| 1065 | + a2w(target_ip, wtarget, 1024); | |
| 1066 | + a2w(u->path, wpath, 2100); | |
| 1067 | + | |
| 1068 | + conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); | |
| 1069 | + if (!conn) { | |
| 1070 | + snprintf(r->error, sizeof r->error, "Failed to connect to %s", u->host); | |
| 1071 | + WinHttpCloseHandle(sess); | |
| 1072 | + return -1; | |
| 1073 | + } | |
| 1074 | + { | |
| 1075 | + DWORD flags = strcmp(u->scheme, "https") == 0 ? WINHTTP_FLAG_SECURE : 0; | |
| 1076 | + req = WinHttpOpenRequest(conn, L"GET", wpath, NULL, WINHTTP_NO_REFERER, | |
| 1077 | + WINHTTP_DEFAULT_ACCEPT_TYPES, flags); | |
| 1078 | + } | |
| 1079 | + if (!req) { | |
| 1080 | + snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed"); | |
| 1081 | + WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1082 | + return -1; | |
| 1083 | + } | |
| 1084 | + { | |
| 1085 | + DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | | |
| 1086 | + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; | |
| 1087 | + WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec); | |
| 1088 | + } | |
| 1089 | + { | |
| 1090 | + DWORD pol = WINHTTP_REDIRECT_POLICY_NONE; | |
| 1091 | + WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); | |
| 1092 | + } | |
| 1093 | + { | |
| 1094 | + wchar_t wh[640]; | |
| 1095 | + char hs[520]; | |
| 1096 | + int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; | |
| 1097 | + if (u->port != defport) | |
| 1098 | + snprintf(hs, sizeof hs, | |
| 1099 | + "Host: %s:%d\r\n" | |
| 1100 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | |
| 1101 | + "Accept-Encoding: identity\r\n", | |
| 1102 | + u->host, u->port); | |
| 1103 | + else | |
| 1104 | + snprintf(hs, sizeof hs, | |
| 1105 | + "Host: %s\r\n" | |
| 1106 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | |
| 1107 | + "Accept-Encoding: identity\r\n", | |
| 1108 | + u->host); | |
| 1109 | + a2w(hs, wh, 640); | |
| 1110 | + WinHttpAddRequestHeaders(req, wh, (DWORD)-1, | |
| 1111 | + WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); | |
| 1112 | + } | |
| 1113 | + | |
| 1114 | + ok = WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, | |
| 1115 | + WINHTTP_NO_REQUEST_DATA, 0, 0, 0); | |
| 1116 | + if (!ok || !WinHttpReceiveResponse(req, NULL)) { | |
| 1117 | + snprintf(r->error, sizeof r->error, | |
| 1118 | + "Failed to fetch %s: TLS or connection error (certificate refused " | |
| 1119 | + "or host unreachable)", urltext); | |
| 1120 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1121 | + return -1; | |
| 1122 | + } | |
| 1123 | + | |
| 1124 | + { | |
| 1125 | + DWORD sz = sizeof status; | |
| 1126 | + WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, | |
| 1127 | + WINHTTP_HEADER_NAME_BY_INDEX, &status, &sz, | |
| 1128 | + WINHTTP_NO_HEADER_INDEX); | |
| 1129 | + r->status = (int)status; | |
| 1130 | + } | |
| 1131 | + { | |
| 1132 | + wchar_t wct[256]; | |
| 1133 | + DWORD sz = sizeof wct; | |
| 1134 | + wct[0] = L'\0'; | |
| 1135 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, | |
| 1136 | + WINHTTP_HEADER_NAME_BY_INDEX, wct, &sz, | |
| 1137 | + WINHTTP_NO_HEADER_INDEX)) | |
| 1138 | + WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, | |
| 1139 | + sizeof r->content_type, NULL, NULL); | |
| 1140 | + } | |
| 1141 | + if (r->status == 301 || r->status == 302 || r->status == 303 || | |
| 1142 | + r->status == 307 || r->status == 308) { | |
| 1143 | + wchar_t wloc[1024]; | |
| 1144 | + DWORD sz = sizeof wloc; | |
| 1145 | + wloc[0] = L'\0'; | |
| 1146 | + a2w(L"Location", whdr, 128); | |
| 1147 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CUSTOM, whdr, wloc, &sz, | |
| 1148 | + WINHTTP_NO_HEADER_INDEX)) { | |
| 1149 | + WideCharToMultiByte(CP_UTF8, 0, wloc, -1, r->url, sizeof r->url, | |
| 1150 | + NULL, NULL); | |
| 1151 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1152 | + return 2; | |
| 1153 | + } | |
| 1154 | + } | |
| 1155 | + | |
| 1156 | + buf_init(&body); | |
| 1157 | + for (;;) { | |
| 1158 | + if (!WinHttpQueryDataAvailable(req, &avail)) break; | |
| 1159 | + if (avail == 0) break; | |
| 1160 | + { | |
| 1161 | + DWORD take = avail > 65536 ? 65536 : avail; | |
| 1162 | + char *tmp; | |
| 1163 | + DWORD rd = 0; | |
| 1164 | + if (body.n + take > FX_MAX_BODY) { | |
| 1165 | + buf_free(&body); | |
| 1166 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1167 | + snprintf(r->error, sizeof r->error, | |
| 1168 | + "Failed to fetch %s: the response body is larger than the " | |
| 1169 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | |
| 1170 | + return -1; | |
| 1171 | + } | |
| 1172 | + tmp = (char *)sx_malloc(take + 1); | |
| 1173 | + if (!WinHttpReadData(req, tmp, take, &rd) || rd == 0) { free(tmp); break; } | |
| 1174 | + tmp[rd] = '\0'; | |
| 1175 | + buf_bput(&body, tmp, rd); | |
| 1176 | + free(tmp); | |
| 1177 | + } | |
| 1178 | + } | |
| 1179 | + | |
| 1180 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | |
| 1181 | + r->body = body.p ? body.p : fx_strndup("", 0); | |
| 1182 | + r->body_len = body.n; | |
| 1183 | + return 0; | |
| 1184 | +} | |
| 1185 | + | |
| 1186 | +#endif /* _WIN32 */ | |
| 1187 | + | |
| 1188 | +/* ------------------------------------------------------------------ */ | |
| 1189 | +/* fx_fetch — the redirect loop */ | |
| 1190 | +/* ------------------------------------------------------------------ */ | |
| 1191 | + | |
| 1192 | +int fx_fetch(const char *url, fx_response *r) | |
| 1193 | +{ | |
| 1194 | + fx_url u; | |
| 1195 | + char urltext[1100]; | |
| 1196 | + int hops = 0; | |
| 1197 | + int allow_private = 0; | |
| 1198 | + const char *env; | |
| 1199 | + | |
| 1200 | + memset(r, 0, sizeof *r); | |
| 1201 | + env = getenv("FETCH_ALLOW_PRIVATE"); | |
| 1202 | + if (env && *env && strcmp(env, "0") != 0) allow_private = 1; | |
| 1203 | + if (fx_policy_allow_private()) allow_private = 1; | |
| 1204 | + | |
| 1205 | + if (fx_url_parse(url, &u, r->error, sizeof r->error) != 0) return -1; | |
| 1206 | + snprintf(r->first_url, sizeof r->first_url, "%s", url); | |
| 1207 | + | |
| 1208 | + for (;;) { | |
| 1209 | + int rc; | |
| 1210 | + fx_url_build(&u, urltext, sizeof urltext); | |
| 1211 | + r->url[0] = '\0'; | |
| 1212 | + free(r->body); | |
| 1213 | + r->body = NULL; | |
| 1214 | + r->body_len = 0; | |
| 1215 | + r->content_type[0] = '\0'; | |
| 1216 | + | |
| 1217 | +#if defined(_WIN32) | |
| 1218 | + rc = exchange_winhttp(&u, urltext, r, allow_private); | |
| 1219 | +#else | |
| 1220 | + rc = exchange_plain(&u, urltext, r, allow_private); | |
| 1221 | +#endif | |
| 1222 | + if (rc == 0) { | |
| 1223 | + if (!r->url[0]) snprintf(r->url, sizeof r->url, "%s", urltext); | |
| 1224 | + r->ok = 1; | |
| 1225 | + r->hops = hops; | |
| 1226 | + return 0; | |
| 1227 | + } | |
| 1228 | + if (rc == 2) { | |
| 1229 | + if (++hops > FX_MAX_REDIRECTS) { | |
| 1230 | + snprintf(r->error, sizeof r->error, | |
| 1231 | + "Exceeded maximum allowed redirects."); | |
| 1232 | + return -1; | |
| 1233 | + } | |
| 1234 | + /* Absolute-ise the Location against the CURRENT url: a bare | |
| 1235 | + * "relative" resolves against the directory of the current path, | |
| 1236 | + * "/abs" against the authority, and anything carrying "://" is | |
| 1237 | + * already absolute. fx_url_resolve is the single place that owns | |
| 1238 | + * those rules. Every hop then re-enters the same | |
| 1239 | + * parse/resolve/validate path, so each new address is SSRF | |
| 1240 | + * checked before it is connected to. */ | |
| 1241 | + { | |
| 1242 | + fx_url next; | |
| 1243 | + if (fx_url_resolve(&u, r->url, &next, r->error, | |
| 1244 | + sizeof r->error) != 0) | |
| 1245 | + return -1; | |
| 1246 | + u = next; | |
| 1247 | + } | |
| 1248 | + continue; | |
| 1249 | + } | |
| 1250 | + return -1; | |
| 1251 | + } | |
| 1252 | +} | |
| 1253 | + | |
| 1254 | +void fx_response_free(fx_response *r) | |
| 1255 | +{ | |
| 1256 | + if (!r) return; | |
| 1257 | + free(r->body); | |
| 1258 | + r->body = NULL; | |
| 1259 | + r->body_len = 0; | |
| 1260 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..6432c2d | ||
| --- /dev/null | ||
| +++ b/src/fetch_http.h | ||
| @@ -0,0 +1,63 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_http.h - URL parse + SSRF policy + HTTP/HTTPS GET with redirects. | |
| 3 | + * | |
| 4 | + * One GET exchange (no keep-alive; Connection: close), up to 5 redirects. | |
| 5 | + * Every hop (and every resolved address of every hop) is checked against the | |
| 6 | + * private/special-purpose denylist BEFORE connect, and the socket is then | |
| 7 | + * connected to that exact validated address, so DNS cannot answer a different | |
| 8 | + * (private) IP between the check and the connect (DNS-rebinding defence). | |
| 9 | + * | |
| 10 | + * TLS on POSIX: vendored mbedTLS over our own sockets, VERIFY_PEER against a | |
| 11 | + * CA bundle (FETCH_TLS_CA_FILE, else the first system bundle found). There is | |
| 12 | + * deliberately NO insecure bypass. On _WIN32 the whole HTTP leg goes through | |
| 13 | + * WinHTTP (system root store). | |
| 14 | + * | |
| 15 | + * Implementation in fetch_http.c (+ fetch_tls.c for the mbedTLS BIO layer). | |
| 16 | + */ | |
| 17 | +#ifndef SX_FETCH_HTTP_H | |
| 18 | +#define SX_FETCH_HTTP_H | |
| 19 | + | |
| 20 | +#include <stddef.h> | |
| 21 | + | |
| 22 | +#include "sxbuf.h" | |
| 23 | + | |
| 24 | +/* Hard cap on the response body we are willing to read, like upstream's | |
| 25 | + * MAX_RESPONSE_BYTES. A larger declared body is refused without reading it. */ | |
| 26 | +#define FX_MAX_BODY (5u * 1024u * 1024u) | |
| 27 | +#define FX_MAX_HEAD (64u * 1024u) | |
| 28 | +#define FX_MAX_REDIRECTS 5 | |
| 29 | +#define FX_CONNECT_MS 10000 | |
| 30 | +#define FX_READ_MS 15000 | |
| 31 | + | |
| 32 | +typedef struct { | |
| 33 | + int ok; /* 1 = response delivered */ | |
| 34 | + char error[512]; | |
| 35 | + int status; /* HTTP status of the final response */ | |
| 36 | + char url[1024]; /* final URL after redirects */ | |
| 37 | + char first_url[1024]; /* URL we were first asked for */ | |
| 38 | + char content_type[128]; | |
| 39 | + int hops; /* redirects followed */ | |
| 40 | + char *body; /* heap, NUL-terminated */ | |
| 41 | + size_t body_len; | |
| 42 | +} fx_response; | |
| 43 | + | |
| 44 | +void fx_response_free(fx_response *r); | |
| 45 | + | |
| 46 | +/* Perform GET url (scheme http|https only). Returns 0 on success (response | |
| 47 | + * fields filled) or -1 with r->error set. */ | |
| 48 | +int fx_fetch(const char *url, fx_response *r); | |
| 49 | + | |
| 50 | +/* SSRF: returns 1 when `ip_text` (IPv4 or IPv6 in text form) is a private / | |
| 51 | + * loopback / link-local / special-purpose address that must be refused, | |
| 52 | + * 0 when public. Mirrors the upstream _NON_PUBLIC_NETWORKS list plus its | |
| 53 | + * documented public exceptions. */ | |
| 54 | +int fx_ip_is_denied(const char *ip_text); | |
| 55 | + | |
| 56 | +/* Whether a body with no declared Content-Type opens as an HTML document | |
| 57 | + * (after BOM/whitespace: "<!doctype html" or "<html"). */ | |
| 58 | +int fx_body_looks_like_html(const char *body, size_t len); | |
| 59 | + | |
| 60 | +/* Helper shared with fetch_md: heap copy + NUL terminate. */ | |
| 61 | +char *fx_strndup(const char *s, size_t n); | |
| 62 | + | |
| 63 | +#endif /* SX_FETCH_HTTP_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..44167e5 | ||
| --- /dev/null | ||
| +++ b/src/fetch_md.c | ||
| @@ -0,0 +1,958 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_md.c - forgiving HTML tokenizer -> clean Markdown. | |
| 3 | + * | |
| 4 | + * Clean-room implementation over raw bytes. UTF-8 passes through untouched; | |
| 5 | + * entities are decoded. This is deliberately NOT a DOM: it is the subset a | |
| 6 | + * fetch tool needs to take a page down to readable Markdown: | |
| 7 | + * | |
| 8 | + * - strips comment + script/style/noscript/svg/head/nav/aside/footer/form/ | |
| 9 | + * template/button/select/textarea/iframe subtrees | |
| 10 | + * - h1..h6 -> ATX headings | |
| 11 | + * - a -> [text](href) (absolutised against the page URL) | |
| 12 | + * - ul/ol/li -> "- " / "n. " with simple nesting | |
| 13 | + * - pre/code -> fenced block / `code span` | |
| 14 | + * - strong/b, em/i -> ** **, * * | |
| 15 | + * - blockquote -> "> " lines | |
| 16 | + * - table/tr/td/th -> pipe rows | |
| 17 | + * - img ->  | |
| 18 | + * - p/div/br/hr/section/article -> line breaks | |
| 19 | + * - common entities + &#NNN; + &#xHH; | |
| 20 | + */ | |
| 21 | +#include "fetch_md.h" | |
| 22 | +#include "sxbuf.h" | |
| 23 | + | |
| 24 | +#include <ctype.h> | |
| 25 | +#include <stdlib.h> | |
| 26 | +#include <string.h> | |
| 27 | + | |
| 28 | +/* ------------------------------------------------------------------ */ | |
| 29 | +/* Tokenizer */ | |
| 30 | +/* ------------------------------------------------------------------ */ | |
| 31 | + | |
| 32 | +typedef enum { TOK_TEXT, TOK_OPEN, TOK_CLOSE } tok_kind; | |
| 33 | + | |
| 34 | +typedef struct { | |
| 35 | + tok_kind kind; | |
| 36 | + char name[24]; /* lowercased tag name (close/open) */ | |
| 37 | + char *text; /* TOK_TEXT: decoded text (heap) */ | |
| 38 | + char *attrs; /* TOK_OPEN: raw attribute text */ | |
| 39 | + int selfclose; | |
| 40 | +} token; | |
| 41 | + | |
| 42 | +typedef struct { | |
| 43 | + token *v; | |
| 44 | + size_t n, cap; | |
| 45 | +} toks; | |
| 46 | + | |
| 47 | +static void toks_push(toks *t, token *tok) | |
| 48 | +{ | |
| 49 | + if (t->n == t->cap) { | |
| 50 | + size_t cap = t->cap ? t->cap * 2 : 256; | |
| 51 | + token *nv = (token *)realloc(t->v, cap * sizeof *nv); | |
| 52 | + if (!nv) { fputs("out of memory\n", stderr); exit(1); } | |
| 53 | + t->v = nv; | |
| 54 | + t->cap = cap; | |
| 55 | + } | |
| 56 | + t->v[t->n++] = *tok; | |
| 57 | +} | |
| 58 | + | |
| 59 | +static void toks_free(toks *t) | |
| 60 | +{ | |
| 61 | + size_t i; | |
| 62 | + for (i = 0; i < t->n; i++) { free(t->v[i].text); free(t->v[i].attrs); } | |
| 63 | + free(t->v); | |
| 64 | + t->v = NULL; | |
| 65 | + t->n = t->cap = 0; | |
| 66 | +} | |
| 67 | + | |
| 68 | +/* ------------------------------------------------------------------ */ | |
| 69 | +/* Entity decoding */ | |
| 70 | +/* ------------------------------------------------------------------ */ | |
| 71 | + | |
| 72 | +static void utf8_put(buf_t *b, unsigned cp) | |
| 73 | +{ | |
| 74 | + if (cp < 0x80) { | |
| 75 | + char c = (char)cp; | |
| 76 | + buf_bput(b, &c, 1); | |
| 77 | + } else if (cp < 0x800) { | |
| 78 | + char c[2] = { (char)(0xC0 | (cp >> 6)), (char)(0x80 | (cp & 0x3F)) }; | |
| 79 | + buf_bput(b, c, 2); | |
| 80 | + } else if (cp < 0x10000) { | |
| 81 | + char c[3] = { (char)(0xE0 | (cp >> 12)), (char)(0x80 | ((cp >> 6) & 0x3F)), | |
| 82 | + (char)(0x80 | (cp & 0x3F)) }; | |
| 83 | + buf_bput(b, c, 3); | |
| 84 | + } else { | |
| 85 | + char c[4] = { (char)(0xF0 | (cp >> 18)), (char)(0x80 | ((cp >> 12) & 0x3F)), | |
| 86 | + (char)(0x80 | ((cp >> 6) & 0x3F)), (char)(0x80 | (cp & 0x3F)) }; | |
| 87 | + buf_bput(b, c, 4); | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +typedef struct { const char *name; const char *utf8; } ent_map; | |
| 92 | +static const ent_map ENTITIES[] = { | |
| 93 | + { "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" }, | |
| 94 | + { "apos", "'" }, { "nbsp", "\xC2\xA0" }, | |
| 95 | + { "zwnj", "" }, { "zwj", "" }, { "lrm", "" }, | |
| 96 | + { "rdquo", "\xE2\x80\x9D" }, { "ldquo", "\xE2\x80\x9C" }, | |
| 97 | + { "sbquo", "\xE2\x80\x9A" }, { "bdquo", "\xE2\x80\x9E" }, | |
| 98 | + { "mdash", "\xE2\x80\x94" }, { "ndash", "\xE2\x80\x93" }, | |
| 99 | + { "hellip", "\xE2\x80\xA6" }, { "middot", "\xC2\xB7" }, | |
| 100 | + { "bull", "\xE2\x80\xA2" }, { "deg", "\xC2\xB0" }, | |
| 101 | + { "copy", "\xC2\xA9" }, { "reg", "\xC2\xAE" }, { "trade", "\xE2\x84\xA2" }, | |
| 102 | + { "laquo", "\xC2\xAB" }, { "raquo", "\xC2\xBB" }, | |
| 103 | + { "times", "\xC3\x97" }, { "divide", "\xC3\xB7" }, { "plusmn", "\xC2\xB1" }, | |
| 104 | + { "frac12", "\xC2\xBD" }, { "frac14", "\xC2\xBC" }, { "frac34", "\xC2\xBE" }, | |
| 105 | + { "sect", "\xC2\xA7" }, { "para", "\xC2\xB6" }, { "dagger", "\xE2\x80\xA0" }, | |
| 106 | + { "permil", "\xE2\x80\xB0" }, { "euro", "\xE2\x82\xAC" }, | |
| 107 | + { "pound", "\xC2\xA3" }, { "yen", "\xC2\xA5" }, { "cent", "\xC2\xA2" }, | |
| 108 | + { "curren", "\xC2\xA4" }, { "cldquo", "\xE2\x80\x9C" }, | |
| 109 | + { "lsquo", "\xE2\x80\x98" }, { "rsquo", "\xE2\x80\x99" }, | |
| 110 | + { "ne", "\xE2\x89\xA0" }, { "le", "\xE2\x89\xA4" }, { "ge", "\xE2\x89\xA5" }, | |
| 111 | + { "larr", "\xE2\x86\x90" }, { "rarr", "\xE2\x86\x92" }, | |
| 112 | + { "uarr", "\xE2\x86\x91" }, { "darr", "\xE2\x86\x93" }, | |
| 113 | + { "harr", "\xE2\x86\x94" }, { "minus", "\xE2\x88\x92" }, | |
| 114 | + { "micro", "\xC2\xB5" }, { "sup2", "\xC2\xB2" }, { "sup3", "\xC2\xB3" }, | |
| 115 | + { "sup1", "\xC2\xB9" }, { "prime", "\xE2\x80\xB2" }, | |
| 116 | + { "check", "\xE2\x9C\x93" }, { "star", "\xE2\x98\x85" }, | |
| 117 | + /* The Latin-1 supplement named entities: a page that writes café | |
| 118 | + * (which plenty still do) has to read back as cafe with an accent, not | |
| 119 | + * as the literal source text. */ | |
| 120 | + { "eacute", "\xC3\xA9" }, { "egrave", "\xC3\xA8" }, | |
| 121 | + { "ecirc", "\xC3\xAA" }, { "euml", "\xC3\xAF" }, | |
| 122 | + { "aacute", "\xC3\xA1" }, { "agrave", "\xC3\xA0" }, | |
| 123 | + { "acirc", "\xC3\xA2" }, { "auml", "\xC3\xA4" }, | |
| 124 | + { "ocirc", "\xC3\xB4" }, { "oacute", "\xC3\xB3" }, | |
| 125 | + { "ouml", "\xC3\xB6" }, { "ucirc", "\xC3\xBB" }, | |
| 126 | + { "uacute", "\xC3\xBA" }, { "uuml", "\xC3\xBC" }, | |
| 127 | + { "icirc", "\xC3\xAE" }, { "iacute", "\xC3\xAD" }, | |
| 128 | + { "iuml", "\xC3\xAF" }, { "ccedil", "\xC3\xA7" }, | |
| 129 | + { "ntilde", "\xC3\xB1" }, { "szlig", "\xC3\x9F" }, | |
| 130 | + { "Aacute", "\xC3\x81" }, { "Eacute", "\xC3\x89" }, | |
| 131 | + { "Uuml", "\xC3\x9C" }, { "Oslash", "\xC3\x98" }, | |
| 132 | + { "divide", "\xC3\xB7" }, { "iquest", "\xC2\xBF" }, | |
| 133 | + { "iexcl", "\xC2\xA1" }, { "brvbar", "\xC2\xA6" }, | |
| 134 | + { "not", "\xC2\xAC" }, { "macr", "\xC2\xAF" }, | |
| 135 | + { "acute", "\xC2\xB4" }, { "grave", "\xC2\x60" }, | |
| 136 | + { "cedil", "\xC2\xB8" }, { "curren", "\xC2\xA4" }, | |
| 137 | + { "frac13", "\xE2\x85\x93" }, { "line", "|" }, | |
| 138 | + { "verbar", "|" }, { "brvbar", "\xC2\xA6" }, | |
| 139 | + { "ensp", "\xE2\x80\x82" }, { "emsp", "\xE2\x80\x83" }, | |
| 140 | + { "thinsp", "\xE2\x80\x89" }, { "shy", "" }, | |
| 141 | + { "hearts", "\xE2\x99\xA5" }, { "spades", "\xE2\x99\xA0" }, | |
| 142 | + { "clubs", "\xE2\x99\xA3" }, { "diams", "\xE2\x99\xA6" }, | |
| 143 | + { NULL, NULL } | |
| 144 | +}; | |
| 145 | + | |
| 146 | +static int entity_named(const char *name, size_t len, buf_t *out) | |
| 147 | +{ | |
| 148 | + int i; | |
| 149 | + for (i = 0; ENTITIES[i].name; i++) | |
| 150 | + if (strlen(ENTITIES[i].name) == len && | |
| 151 | + strncmp(ENTITIES[i].name, name, len) == 0) { | |
| 152 | + buf_add(out, ENTITIES[i].utf8); | |
| 153 | + return 1; | |
| 154 | + } | |
| 155 | + return 0; | |
| 156 | +} | |
| 157 | + | |
| 158 | +static void decode_entities(const char *s, size_t n, buf_t *out) | |
| 159 | +{ | |
| 160 | + size_t i = 0; | |
| 161 | + while (i < n) { | |
| 162 | + if (s[i] == '&') { | |
| 163 | + const char *semi = (const char *)memchr(s + i, ';', n - i); | |
| 164 | + if (semi && (size_t)(semi - (s + i)) < 12) { | |
| 165 | + size_t len = (size_t)(semi - (s + i)) - 1; | |
| 166 | + const char *nm = s + i + 1; | |
| 167 | + if (len > 1 && nm[0] == '#') { | |
| 168 | + unsigned cp = 0; | |
| 169 | + int ok = 1; | |
| 170 | + if (nm[1] == 'x' || nm[1] == 'X') { | |
| 171 | + size_t j; | |
| 172 | + for (j = 2; j < len; j++) { | |
| 173 | + if (!isxdigit((unsigned char)nm[j])) { ok = 0; break; } | |
| 174 | + cp = cp * 16 + (unsigned)(isdigit((unsigned char)nm[j]) | |
| 175 | + ? nm[j] - '0' | |
| 176 | + : (tolower((unsigned char)nm[j]) - 'a' + 10)); | |
| 177 | + } | |
| 178 | + } else { | |
| 179 | + size_t j; | |
| 180 | + for (j = 1; j < len; j++) { | |
| 181 | + if (!isdigit((unsigned char)nm[j])) { ok = 0; break; } | |
| 182 | + cp = cp * 10 + (unsigned)(nm[j] - '0'); | |
| 183 | + } | |
| 184 | + } | |
| 185 | + if (ok && cp > 0 && cp <= 0x10FFFF) { | |
| 186 | + if (cp >= 0xD800 && cp <= 0xDFFF) cp = 0xFFFD; | |
| 187 | + utf8_put(out, cp); | |
| 188 | + i += len + 2; | |
| 189 | + continue; | |
| 190 | + } | |
| 191 | + } else if (len > 0) { | |
| 192 | + /* named entities may arrive with mixed case */ | |
| 193 | + char lower[12]; | |
| 194 | + size_t j; | |
| 195 | + for (j = 0; j < len && j < sizeof lower - 1; j++) | |
| 196 | + lower[j] = (char)tolower((unsigned char)nm[j]); | |
| 197 | + lower[j < len ? j : len] = '\0'; | |
| 198 | + if (j <= len) { | |
| 199 | + if (entity_named(lower, j, out)) { i += len + 2; continue; } | |
| 200 | + if (entity_named(nm, len, out)) { i += len + 2; continue; } | |
| 201 | + } | |
| 202 | + } | |
| 203 | + } | |
| 204 | + } | |
| 205 | + buf_bput(out, s + i, 1); | |
| 206 | + i++; | |
| 207 | + } | |
| 208 | +} | |
| 209 | + | |
| 210 | +#ifdef memmem | |
| 211 | +#undef memmem | |
| 212 | +#endif | |
| 213 | +static const char *sx_memmem(const char *h, size_t hl, const char *n, size_t nl) | |
| 214 | +{ | |
| 215 | + size_t i; | |
| 216 | + if (nl == 0 || hl < nl) return NULL; | |
| 217 | + for (i = 0; i + nl <= hl; i++) | |
| 218 | + if (memcmp(h + i, n, nl) == 0) return h + i; | |
| 219 | + return NULL; | |
| 220 | +} | |
| 221 | +#define memmem sx_memmem | |
| 222 | + | |
| 223 | +/* ------------------------------------------------------------------ */ | |
| 224 | +/* Tokenizer core */ | |
| 225 | +/* ------------------------------------------------------------------ */ | |
| 226 | + | |
| 227 | +static int tag_skip(const char *name) | |
| 228 | +{ | |
| 229 | + static const char *const skip[] = { | |
| 230 | + "script", "style", "noscript", "svg", "head", "nav", "aside", | |
| 231 | + "footer", "form", "template", "button", "select", "textarea", | |
| 232 | + "iframe", "canvas", "video", "audio", "picture", "map", "object", | |
| 233 | + "embed", "link", "meta", NULL | |
| 234 | + }; | |
| 235 | + int i; | |
| 236 | + for (i = 0; skip[i]; i++) if (strcmp(skip[i], name) == 0) return 1; | |
| 237 | + return 0; | |
| 238 | +} | |
| 239 | + | |
| 240 | +static void tokenize(const char *html, size_t len, toks *out) | |
| 241 | +{ | |
| 242 | + size_t i = 0; | |
| 243 | + | |
| 244 | + memset(out, 0, sizeof *out); /* cap/n must start at zero: toks_push grows from them */ | |
| 245 | + buf_t text; | |
| 246 | + buf_init(&text); | |
| 247 | + | |
| 248 | +#define FLUSH_TEXT() \ | |
| 249 | + do { \ | |
| 250 | + if (text.n) { \ | |
| 251 | + token tk; \ | |
| 252 | + memset(&tk, 0, sizeof tk); \ | |
| 253 | + tk.kind = TOK_TEXT; \ | |
| 254 | + tk.text = (char *)sx_malloc(text.n + 1); \ | |
| 255 | + memcpy(tk.text, text.p, text.n); \ | |
| 256 | + tk.text[text.n] = '\0'; \ | |
| 257 | + toks_push(out, &tk); \ | |
| 258 | + free(text.p); \ | |
| 259 | + buf_init(&text); \ | |
| 260 | + } \ | |
| 261 | + } while (0) | |
| 262 | + | |
| 263 | + while (i < len) { | |
| 264 | + if (html[i] == '<') { | |
| 265 | + /* comment / CDATA / doctype */ | |
| 266 | + if (i + 3 < len && html[i + 1] == '!' && html[i + 2] == '-' && | |
| 267 | + html[i + 3] == '-') { | |
| 268 | + const char *end = NULL; | |
| 269 | + if (i + 4 < len) | |
| 270 | + end = (const char *)memmem(html + i + 4, len - i - 4, "-->", 3); | |
| 271 | + i = end ? (size_t)(end - html) + 3 : len; | |
| 272 | + continue; | |
| 273 | + } | |
| 274 | + if (i + 1 < len && (html[i + 1] == '!' || html[i + 1] == '?')) { | |
| 275 | + const char *gt = (const char *)memchr(html + i, '>', len - i); | |
| 276 | + i = gt ? (size_t)(gt - html) + 1 : len; | |
| 277 | + continue; | |
| 278 | + } | |
| 279 | + if (i + 1 < len && (isalpha((unsigned char)html[i + 1]) || | |
| 280 | + html[i + 1] == '/')) { | |
| 281 | + size_t j = i + 1; | |
| 282 | + int closing = 0; | |
| 283 | + char name[24]; | |
| 284 | + size_t nl = 0; | |
| 285 | + const char *attr_start; | |
| 286 | + const char *gt; | |
| 287 | + token tk; | |
| 288 | + | |
| 289 | + if (html[j] == '/') { closing = 1; j++; } | |
| 290 | + while (j < len && (isalnum((unsigned char)html[j]) || html[j] == '-')) { | |
| 291 | + if (nl < sizeof name - 1) | |
| 292 | + name[nl++] = (char)tolower((unsigned char)html[j]); | |
| 293 | + j++; | |
| 294 | + } | |
| 295 | + name[nl] = '\0'; | |
| 296 | + if (nl == 0) { /* stray '<' as text */ | |
| 297 | + buf_bput(&text, "<", 1); | |
| 298 | + i++; | |
| 299 | + continue; | |
| 300 | + } | |
| 301 | + attr_start = html + j; | |
| 302 | + /* skip to the closing '>' respecting quoted values */ | |
| 303 | + gt = html + j; | |
| 304 | + while (gt < html + len) { | |
| 305 | + if (*gt == '"' || *gt == '\'') { | |
| 306 | + char q = *gt; | |
| 307 | + gt++; | |
| 308 | + while (gt < html + len && *gt != q) gt++; | |
| 309 | + if (gt < html + len) gt++; | |
| 310 | + } else if (*gt == '>') break; | |
| 311 | + else gt++; | |
| 312 | + } | |
| 313 | + if (gt >= html + len) { /* unterminated tag: swallow rest */ | |
| 314 | + i = len; | |
| 315 | + continue; | |
| 316 | + } | |
| 317 | + FLUSH_TEXT(); | |
| 318 | + memset(&tk, 0, sizeof tk); | |
| 319 | + snprintf(tk.name, sizeof tk.name, "%s", name); | |
| 320 | + if (closing) { | |
| 321 | + tk.kind = TOK_CLOSE; | |
| 322 | + } else { | |
| 323 | + size_t alen = (size_t)(gt - attr_start); | |
| 324 | + tk.kind = TOK_OPEN; | |
| 325 | + tk.selfclose = (alen && attr_start[alen - 1] == '/'); | |
| 326 | + if (tk.selfclose) alen--; | |
| 327 | + /* trailing spaces */ | |
| 328 | + while (alen && (unsigned char)attr_start[alen - 1] <= ' ') alen--; | |
| 329 | + if (alen) { | |
| 330 | + buf_t a; | |
| 331 | + buf_init(&a); | |
| 332 | + decode_entities(attr_start, alen, &a); | |
| 333 | + tk.attrs = a.p ? a.p : (char *)sx_malloc(1); | |
| 334 | + if (!a.p) tk.attrs[0] = '\0'; | |
| 335 | + } | |
| 336 | + } | |
| 337 | + toks_push(out, &tk); | |
| 338 | + i = (size_t)(gt - html) + 1; | |
| 339 | + continue; | |
| 340 | + } | |
| 341 | + /* lone '<' */ | |
| 342 | + buf_bput(&text, "<", 1); | |
| 343 | + i++; | |
| 344 | + continue; | |
| 345 | + } | |
| 346 | + { | |
| 347 | + const char *lt = (const char *)memchr(html + i, '<', len - i); | |
| 348 | + size_t n = lt ? (size_t)(lt - (html + i)) : len - i; | |
| 349 | + decode_entities(html + i, n, &text); | |
| 350 | + i += n; | |
| 351 | + } | |
| 352 | + } | |
| 353 | + FLUSH_TEXT(); | |
| 354 | +#undef FLUSH_TEXT | |
| 355 | +} | |
| 356 | + | |
| 357 | +/* ------------------------------------------------------------------ */ | |
| 358 | +/* Attribute lookup */ | |
| 359 | +/* ------------------------------------------------------------------ */ | |
| 360 | + | |
| 361 | +/* Find attr `key` in raw attribute text; unquotes + decodes into out. */ | |
| 362 | +static int attr_get(const char *attrs, const char *key, char *out, size_t outsz) | |
| 363 | +{ | |
| 364 | + const char *p = attrs; | |
| 365 | + size_t klen = strlen(key); | |
| 366 | + out[0] = '\0'; | |
| 367 | + if (!attrs) return 0; | |
| 368 | + while (*p) { | |
| 369 | + const char *eq; | |
| 370 | + size_t alen; | |
| 371 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 372 | + if (!*p) break; | |
| 373 | + eq = p; | |
| 374 | + while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++; | |
| 375 | + alen = (size_t)(eq - p); | |
| 376 | + if (alen == klen && sx_strncasecmp(p, key, klen) == 0 && *eq == '=') { | |
| 377 | + const char *v = eq + 1; | |
| 378 | + const char *ve; | |
| 379 | + buf_t b; | |
| 380 | + char raw[2048]; | |
| 381 | + size_t rn = 0; | |
| 382 | + while (*v && (unsigned char)*v <= ' ') v++; | |
| 383 | + if (*v == '"' || *v == '\'') { | |
| 384 | + char q = *v++; | |
| 385 | + while (*v && *v != q && rn + 1 < sizeof raw) raw[rn++] = *v++; | |
| 386 | + ve = v; | |
| 387 | + } else { | |
| 388 | + while (*v && (unsigned char)*v > ' ' && rn + 1 < sizeof raw) | |
| 389 | + raw[rn++] = *v++; | |
| 390 | + ve = v; | |
| 391 | + } | |
| 392 | + raw[rn] = '\0'; | |
| 393 | + (void)ve; | |
| 394 | + buf_init(&b); | |
| 395 | + decode_entities(raw, rn, &b); | |
| 396 | + if (b.p) { | |
| 397 | + snprintf(out, outsz, "%s", b.p); | |
| 398 | + free(b.p); | |
| 399 | + } | |
| 400 | + p = v; | |
| 401 | + return 1; | |
| 402 | + } | |
| 403 | + /* skip value */ | |
| 404 | + while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++; | |
| 405 | + if (*eq == '=') { | |
| 406 | + eq++; | |
| 407 | + while (*eq && (unsigned char)*eq <= ' ') eq++; | |
| 408 | + if (*eq == '"' || *eq == '\'') { | |
| 409 | + char q = *eq++; | |
| 410 | + while (*eq && *eq != q) eq++; | |
| 411 | + if (*eq) eq++; | |
| 412 | + } else { | |
| 413 | + while (*eq && (unsigned char)*eq > ' ') eq++; | |
| 414 | + } | |
| 415 | + p = eq; | |
| 416 | + } else { | |
| 417 | + p = eq; | |
| 418 | + } | |
| 419 | + } | |
| 420 | + return 0; | |
| 421 | +} | |
| 422 | + | |
| 423 | +/* ------------------------------------------------------------------ */ | |
| 424 | +/* Link absolutisation */ | |
| 425 | +/* ------------------------------------------------------------------ */ | |
| 426 | + | |
| 427 | +static char g_base[1024]; | |
| 428 | + | |
| 429 | +void fx_md_set_base_url(const char *url) | |
| 430 | +{ | |
| 431 | + if (url && *url) snprintf(g_base, sizeof g_base, "%s", url); | |
| 432 | + else g_base[0] = '\0'; | |
| 433 | +} | |
| 434 | + | |
| 435 | +static void absolutise(const char *href, char *out, size_t outsz) | |
| 436 | +{ | |
| 437 | + if (!href || !*href) { out[0] = '\0'; return; } | |
| 438 | + if (strstr(href, "://") || strncmp(href, "mailto:", 7) == 0 || | |
| 439 | + strncmp(href, "tel:", 4) == 0 || href[0] == '#') { | |
| 440 | + snprintf(out, outsz, "%s", href); | |
| 441 | + return; | |
| 442 | + } | |
| 443 | + if (!g_base[0]) { snprintf(out, outsz, "%s", href); return; } | |
| 444 | + { | |
| 445 | + char scheme[16] = "", host[300] = ""; | |
| 446 | + const char *sc = strstr(g_base, "://"); | |
| 447 | + const char *hs, *he; | |
| 448 | + if (!sc) { snprintf(out, outsz, "%s", href); return; } | |
| 449 | + { | |
| 450 | + size_t n = (size_t)(sc - g_base); | |
| 451 | + if (n >= sizeof scheme) n = sizeof scheme - 1; | |
| 452 | + memcpy(scheme, g_base, n); | |
| 453 | + scheme[n] = '\0'; | |
| 454 | + } | |
| 455 | + hs = sc + 3; | |
| 456 | + he = hs; | |
| 457 | + while (*he && *he != '/' && *he != '?') he++; | |
| 458 | + { | |
| 459 | + size_t n = (size_t)(he - hs); | |
| 460 | + if (n >= sizeof host) n = sizeof host - 1; | |
| 461 | + memcpy(host, hs, n); | |
| 462 | + host[n] = '\0'; | |
| 463 | + } | |
| 464 | + if (href[0] == '/') | |
| 465 | + snprintf(out, outsz, "%s://%s%s", scheme, host, href); | |
| 466 | + else { | |
| 467 | + char relbase[1024]; | |
| 468 | + const char *slash; | |
| 469 | + snprintf(relbase, sizeof relbase, "%s", g_base); | |
| 470 | + slash = strrchr(relbase, '/'); | |
| 471 | + if (slash && slash > sc + 3 - 0) { | |
| 472 | + /* keep everything up to and including the last '/' */ | |
| 473 | + /* but never before the authority */ | |
| 474 | + if (slash >= strchr(relbase, '\0') - 0) {} | |
| 475 | + { | |
| 476 | + size_t keep = (size_t)(slash - relbase) + 1; | |
| 477 | + /* don't cut into the scheme://authority */ | |
| 478 | + const char *auth = strstr(relbase, "://"); | |
| 479 | + size_t authend = auth ? (size_t)(auth - relbase) + 3 : 0; | |
| 480 | + const char *pa = strchr(relbase + authend, '/'); | |
| 481 | + size_t pathstart = pa ? (size_t)(pa - relbase) : authend; | |
| 482 | + if (keep < pathstart) keep = pathstart; | |
| 483 | + if (keep >= authend) { | |
| 484 | + relbase[keep] = '\0'; | |
| 485 | + snprintf(out, outsz, "%s%s", relbase, href); | |
| 486 | + } else | |
| 487 | + snprintf(out, outsz, "%s/%s", relbase, href); | |
| 488 | + } | |
| 489 | + } else | |
| 490 | + snprintf(out, outsz, "%s/%s", relbase, href); | |
| 491 | + } | |
| 492 | + } | |
| 493 | +} | |
| 494 | + | |
| 495 | +/* ------------------------------------------------------------------ */ | |
| 496 | +/* Renderer */ | |
| 497 | +/* ------------------------------------------------------------------ */ | |
| 498 | + | |
| 499 | +static int ends_with_blank(buf_t *b) | |
| 500 | +{ | |
| 501 | + if (!b->p || b->n == 0) return 1; | |
| 502 | + if (b->p[b->n - 1] == '\n') | |
| 503 | + return (b->n >= 2 && b->p[b->n - 2] == '\n'); | |
| 504 | + return 0; | |
| 505 | +} | |
| 506 | + | |
| 507 | +static void ensure_newline(buf_t *b) | |
| 508 | +{ | |
| 509 | + if (b->p && b->n && b->p[b->n - 1] != '\n') buf_add(b, "\n"); | |
| 510 | +} | |
| 511 | + | |
| 512 | +static void ensure_blank_line(buf_t *b) | |
| 513 | +{ | |
| 514 | + if (!b->p || b->n == 0) return; | |
| 515 | + ensure_newline(b); | |
| 516 | + if (!ends_with_blank(b)) buf_add(b, "\n"); | |
| 517 | +} | |
| 518 | + | |
| 519 | +static void collapse_ws_append(buf_t *out, const char *s) | |
| 520 | +{ | |
| 521 | + int in_ws = 0; | |
| 522 | + for (; *s; s++) { | |
| 523 | + if ((unsigned char)*s <= ' ') { in_ws = 1; continue; } | |
| 524 | + if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " "); | |
| 525 | + in_ws = 0; | |
| 526 | + buf_bput(out, s, 1); | |
| 527 | + } | |
| 528 | + if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " "); | |
| 529 | +} | |
| 530 | + | |
| 531 | +typedef struct { | |
| 532 | + buf_t *out; | |
| 533 | + int in_pre; | |
| 534 | + int pre_fence; | |
| 535 | + int list_depth; | |
| 536 | + int list_ordered[12]; | |
| 537 | + int list_count[12]; | |
| 538 | + int in_table_row; | |
| 539 | + int row_cells; | |
| 540 | + int row_had_th; | |
| 541 | + int first_row; | |
| 542 | + int link_depth; | |
| 543 | + int skip_depth_guard; | |
| 544 | +} render_state; | |
| 545 | + | |
| 546 | +static void render_tokens(toks *t, size_t from, size_t to, render_state *st); | |
| 547 | + | |
| 548 | +/* find the matching close for tokens[i] (an open), returns index+1 of the | |
| 549 | + * close, or `to` when unbalanced. */ | |
| 550 | +static size_t find_close(toks *t, size_t i, size_t to) | |
| 551 | +{ | |
| 552 | + int depth = 0; | |
| 553 | + size_t j; | |
| 554 | + for (j = i; j < to; j++) { | |
| 555 | + if (t->v[j].kind == TOK_OPEN && strcmp(t->v[j].name, t->v[i].name) == 0 && | |
| 556 | + !t->v[j].selfclose) | |
| 557 | + depth++; | |
| 558 | + else if (t->v[j].kind == TOK_CLOSE && strcmp(t->v[j].name, t->v[i].name) == 0) { | |
| 559 | + depth--; | |
| 560 | + if (depth == 0) return j + 1; | |
| 561 | + } | |
| 562 | + } | |
| 563 | + return to; | |
| 564 | +} | |
| 565 | + | |
| 566 | +static void render_tokens(toks *t, size_t from, size_t to, render_state *st) | |
| 567 | +{ | |
| 568 | + size_t i; | |
| 569 | + buf_t *out = st->out; | |
| 570 | + | |
| 571 | + for (i = from; i < to; i++) { | |
| 572 | + token *tk = &t->v[i]; | |
| 573 | + switch (tk->kind) { | |
| 574 | + case TOK_TEXT: { | |
| 575 | + if (st->in_pre) { | |
| 576 | + buf_add(out, tk->text); | |
| 577 | + } else { | |
| 578 | + collapse_ws_append(out, tk->text); | |
| 579 | + } | |
| 580 | + break; | |
| 581 | + } | |
| 582 | + case TOK_OPEN: { | |
| 583 | + const char *nm = tk->name; | |
| 584 | + if (tag_skip(nm)) { | |
| 585 | + if (!tk->selfclose) i = find_close(t, i, to) - 1; | |
| 586 | + break; | |
| 587 | + } | |
| 588 | + if (strcmp(nm, "br") == 0) { | |
| 589 | + if (st->in_pre) buf_add(out, "\n"); | |
| 590 | + else { ensure_newline(out); } | |
| 591 | + break; | |
| 592 | + } | |
| 593 | + if (strcmp(nm, "hr") == 0) { | |
| 594 | + ensure_blank_line(out); | |
| 595 | + buf_add(out, "---\n"); | |
| 596 | + break; | |
| 597 | + } | |
| 598 | + if (strcmp(nm, "img") == 0) { | |
| 599 | + char alt[256] = "", src[1024] = "", abs[1200]; | |
| 600 | + attr_get(tk->attrs, "alt", alt, sizeof alt); | |
| 601 | + attr_get(tk->attrs, "src", src, sizeof src); | |
| 602 | + if (src[0]) { | |
| 603 | + absolutise(src, abs, sizeof abs); | |
| 604 | + buf_add(out, "; | |
| 607 | + buf_add(out, abs); | |
| 608 | + buf_add(out, ")"); | |
| 609 | + } | |
| 610 | + break; | |
| 611 | + } | |
| 612 | + if (nm[0] == 'h' && nm[1] >= '1' && nm[1] <= '6' && nm[2] == '\0') { | |
| 613 | + size_t end = tk->selfclose ? i + 1 : find_close(t, i, to); | |
| 614 | + buf_t sub; | |
| 615 | + render_state sub_st = *st; | |
| 616 | + int lvl = nm[1] - '0', k; | |
| 617 | + ensure_blank_line(out); | |
| 618 | + for (k = 0; k < lvl; k++) buf_add(out, "#"); | |
| 619 | + buf_add(out, " "); | |
| 620 | + buf_init(&sub); | |
| 621 | + sub_st.out = ⊂ | |
| 622 | + render_tokens(t, i + 1, end > 0 ? end - 1 : i + 1, &sub_st); | |
| 623 | + if (sub.p) { | |
| 624 | + char *p = sub.p; | |
| 625 | + while (*p && (unsigned char)*p <= ' ') p++; /* drop leading ws */ | |
| 626 | + buf_add(out, p); | |
| 627 | + free(sub.p); | |
| 628 | + } | |
| 629 | + ensure_blank_line(out); | |
| 630 | + i = end - 1; | |
| 631 | + break; | |
| 632 | + } | |
| 633 | + if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 || | |
| 634 | + strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 || | |
| 635 | + strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 || | |
| 636 | + strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 || | |
| 637 | + strcmp(nm, "dl") == 0 || strcmp(nm, "dd") == 0 || | |
| 638 | + strcmp(nm, "dt") == 0) { | |
| 639 | + ensure_blank_line(out); | |
| 640 | + break; | |
| 641 | + } | |
| 642 | + if (strcmp(nm, "blockquote") == 0) { | |
| 643 | + size_t end = tk->selfclose ? i : find_close(t, i, to); | |
| 644 | + buf_t sub; | |
| 645 | + render_state sub_st = *st; | |
| 646 | + char *line, *nl; | |
| 647 | + buf_init(&sub); | |
| 648 | + sub_st.out = ⊂ | |
| 649 | + render_tokens(t, i + 1, end ? end - 1 : i + 1, &sub_st); | |
| 650 | + if (sub.p) { | |
| 651 | + line = sub.p; | |
| 652 | + while (line && *line) { | |
| 653 | + nl = strchr(line, '\n'); | |
| 654 | + if (nl) *nl = '\0'; | |
| 655 | + if (*line) buf_addf(out, "> %s\n", line); | |
| 656 | + else buf_add(out, ">\n"); | |
| 657 | + if (!nl) break; | |
| 658 | + line = nl + 1; | |
| 659 | + } | |
| 660 | + free(sub.p); | |
| 661 | + } | |
| 662 | + ensure_blank_line(out); | |
| 663 | + i = end - 1; | |
| 664 | + break; | |
| 665 | + } | |
| 666 | + if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) { | |
| 667 | + /* nm[1] is 'l' for ol and 'l' for ul too - the difference is | |
| 668 | + * nm[0]: 'o' versus 'u'. Comparing the second character made | |
| 669 | + * every unordered list render as a numbered one. */ | |
| 670 | + int d = st->list_depth; | |
| 671 | + if (d < 12) { | |
| 672 | + st->list_ordered[d] = (nm[0] == 'o'); | |
| 673 | + st->list_count[d] = 0; | |
| 674 | + } | |
| 675 | + st->list_depth++; | |
| 676 | + ensure_newline(out); | |
| 677 | + break; | |
| 678 | + } | |
| 679 | + if (strcmp(nm, "li") == 0) { | |
| 680 | + /* The marker belongs to the INNERMOST open list: an <li> | |
| 681 | + * always sits directly inside its own ul/ol, so depth-1 is | |
| 682 | + * the list it belongs to, and its own counter is the one that | |
| 683 | + * increments (which restarts numbering for a nested sublist | |
| 684 | + * while the parent keeps counting). */ | |
| 685 | + int d = st->list_depth > 0 ? st->list_depth - 1 : 0; | |
| 686 | + int k; | |
| 687 | + ensure_newline(out); | |
| 688 | + for (k = 0; k < d; k++) buf_add(out, " "); | |
| 689 | + if (d < 12 && st->list_ordered[d]) { | |
| 690 | + st->list_count[d]++; | |
| 691 | + buf_addf(out, "%d. ", st->list_count[d]); | |
| 692 | + } else { | |
| 693 | + buf_add(out, "- "); | |
| 694 | + } | |
| 695 | + break; | |
| 696 | + } | |
| 697 | + if (strcmp(nm, "pre") == 0) { | |
| 698 | + size_t end = tk->selfclose ? i : find_close(t, i, to); | |
| 699 | + size_t j; | |
| 700 | + ensure_blank_line(out); | |
| 701 | + buf_add(out, "```\n"); | |
| 702 | + st->in_pre = 1; | |
| 703 | + /* emit raw text tokens between i+1..end-1 (decode entities, | |
| 704 | + * keep whitespace) */ | |
| 705 | + for (j = i + 1; j + 1 < end; j++) { | |
| 706 | + if (t->v[j].kind == TOK_TEXT) buf_add(out, t->v[j].text); | |
| 707 | + else if (t->v[j].kind == TOK_OPEN && | |
| 708 | + strcmp(t->v[j].name, "br") == 0) buf_add(out, "\n"); | |
| 709 | + } | |
| 710 | + st->in_pre = 0; | |
| 711 | + ensure_newline(out); | |
| 712 | + buf_add(out, "```\n"); | |
| 713 | + ensure_blank_line(out); | |
| 714 | + i = end - 1; | |
| 715 | + break; | |
| 716 | + } | |
| 717 | + if (strcmp(nm, "code") == 0) { | |
| 718 | + if (!st->in_pre) buf_add(out, "`"); | |
| 719 | + break; | |
| 720 | + } | |
| 721 | + if (strcmp(nm, "a") == 0) { | |
| 722 | + char href[1200] = "", abs[1400]; | |
| 723 | + size_t end = tk->selfclose ? i + 1 : find_close(t, i, to); | |
| 724 | + if (end > i + 1) { | |
| 725 | + buf_t sub; | |
| 726 | + render_state sub_st = *st; | |
| 727 | + attr_get(tk->attrs, "href", href, sizeof href); | |
| 728 | + buf_init(&sub); | |
| 729 | + sub_st.out = ⊂ | |
| 730 | + render_tokens(t, i + 1, end - 1, &sub_st); | |
| 731 | + if (sub.p) { | |
| 732 | + char *p = sub.p; | |
| 733 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 734 | + if (*p) { | |
| 735 | + buf_add(out, "["); | |
| 736 | + buf_add(out, p); | |
| 737 | + buf_add(out, "]("); | |
| 738 | + absolutise(href, abs, sizeof abs); | |
| 739 | + buf_add(out, abs); | |
| 740 | + buf_add(out, ")"); | |
| 741 | + } | |
| 742 | + free(sub.p); | |
| 743 | + } | |
| 744 | + } | |
| 745 | + i = end - 1; | |
| 746 | + break; | |
| 747 | + } | |
| 748 | + if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) { | |
| 749 | + buf_add(out, "**"); | |
| 750 | + break; | |
| 751 | + } | |
| 752 | + if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) { | |
| 753 | + buf_add(out, "*"); | |
| 754 | + break; | |
| 755 | + } | |
| 756 | + if (strcmp(nm, "table") == 0) { | |
| 757 | + ensure_blank_line(out); | |
| 758 | + st->first_row = 1; | |
| 759 | + break; | |
| 760 | + } | |
| 761 | + if (strcmp(nm, "tr") == 0) { | |
| 762 | + st->in_table_row = 1; | |
| 763 | + st->row_cells = 0; | |
| 764 | + st->row_had_th = 0; | |
| 765 | + ensure_newline(out); | |
| 766 | + break; | |
| 767 | + } | |
| 768 | + if (strcmp(nm, "td") == 0 || strcmp(nm, "th") == 0) { | |
| 769 | + /* Cells separate with a pipe, and the row opens with one: | |
| 770 | + * "| a | b |". Without the leading bar a row of more than | |
| 771 | + * one cell was a line of text with a bar stuck in the | |
| 772 | + * middle, which no Markdown renderer will pick up. */ | |
| 773 | + if (st->row_cells) buf_add(out, " |"); | |
| 774 | + else buf_add(out, "|"); | |
| 775 | + buf_add(out, " "); | |
| 776 | + st->row_cells++; | |
| 777 | + if (nm[1] == 'h') st->row_had_th = 1; | |
| 778 | + break; | |
| 779 | + } | |
| 780 | + break; | |
| 781 | + } | |
| 782 | + case TOK_CLOSE: { | |
| 783 | + const char *nm = tk->name; | |
| 784 | + if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) { | |
| 785 | + if (st->list_depth > 0) st->list_depth--; | |
| 786 | + ensure_newline(out); | |
| 787 | + break; | |
| 788 | + } | |
| 789 | + if (strcmp(nm, "li") == 0) { ensure_newline(out); break; } | |
| 790 | + if (strcmp(nm, "a") == 0) break; /* consumed at open */ | |
| 791 | + if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) { | |
| 792 | + buf_add(out, "**"); | |
| 793 | + break; | |
| 794 | + } | |
| 795 | + if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) { | |
| 796 | + buf_add(out, "*"); | |
| 797 | + break; | |
| 798 | + } | |
| 799 | + if (strcmp(nm, "code") == 0) { | |
| 800 | + if (!st->in_pre) buf_add(out, "`"); | |
| 801 | + break; | |
| 802 | + } | |
| 803 | + if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 || | |
| 804 | + strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 || | |
| 805 | + strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 || | |
| 806 | + strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 || | |
| 807 | + strcmp(nm, "ul") == 0) { | |
| 808 | + ensure_blank_line(out); | |
| 809 | + break; | |
| 810 | + } | |
| 811 | + if (strcmp(nm, "tr") == 0) { | |
| 812 | + st->in_table_row = 0; | |
| 813 | + /* close the row: "| a | b |" */ | |
| 814 | + if (st->row_cells) buf_add(out, " |"); | |
| 815 | + ensure_newline(out); | |
| 816 | + if (st->first_row && st->row_cells > 0) { | |
| 817 | + int c; | |
| 818 | + for (c = 0; c < st->row_cells; c++) | |
| 819 | + buf_add(out, c ? " | ---" : "| ---"); | |
| 820 | + buf_add(out, " |"); | |
| 821 | + ensure_newline(out); | |
| 822 | + st->first_row = 0; | |
| 823 | + } | |
| 824 | + break; | |
| 825 | + } | |
| 826 | + if (strcmp(nm, "table") == 0) { | |
| 827 | + ensure_blank_line(out); | |
| 828 | + break; | |
| 829 | + } | |
| 830 | + break; | |
| 831 | + } | |
| 832 | + } | |
| 833 | + } | |
| 834 | +} | |
| 835 | + | |
| 836 | +/* ------------------------------------------------------------------ */ | |
| 837 | +/* Public entry points */ | |
| 838 | +/* ------------------------------------------------------------------ */ | |
| 839 | + | |
| 840 | +char *fx_html_to_markdown(const char *html, size_t len, size_t *out_len) | |
| 841 | +{ | |
| 842 | + toks t; | |
| 843 | + buf_t out; | |
| 844 | + render_state st; | |
| 845 | + | |
| 846 | + memset(&st, 0, sizeof st); | |
| 847 | + buf_init(&out); | |
| 848 | + st.out = &out; | |
| 849 | + tokenize(html, len, &t); | |
| 850 | + render_tokens(&t, 0, t.n, &st); | |
| 851 | + toks_free(&t); | |
| 852 | + | |
| 853 | + /* tidy: strip trailing whitespace runs and clamp to a single trailing \n */ | |
| 854 | + if (out.p) { | |
| 855 | + while (out.n && (unsigned char)out.p[out.n - 1] <= ' ') out.n--; | |
| 856 | + if (out.n) { out.p[out.n] = '\0'; buf_add(&out, "\n"); } | |
| 857 | + else { out.p[0] = '\0'; } | |
| 858 | + } | |
| 859 | + if (out_len) *out_len = out.n; | |
| 860 | + if (!out.p) { | |
| 861 | + char *e = (char *)sx_malloc(1); | |
| 862 | + e[0] = '\0'; | |
| 863 | + return e; | |
| 864 | + } | |
| 865 | + return out.p; | |
| 866 | +} | |
| 867 | + | |
| 868 | +char *fx_html_title(const char *html, size_t len, size_t *out_len) | |
| 869 | +{ | |
| 870 | + toks t; | |
| 871 | + size_t i; | |
| 872 | + char *result = NULL; | |
| 873 | + | |
| 874 | + tokenize(html, len, &t); | |
| 875 | + for (i = 0; i < t.n; i++) { | |
| 876 | + if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "meta") == 0) { | |
| 877 | + char prop[64] = "", name[64] = "", content[512] = ""; | |
| 878 | + attr_get(t.v[i].attrs, "property", prop, sizeof prop); | |
| 879 | + if (!prop[0]) attr_get(t.v[i].attrs, "name", name, sizeof name); | |
| 880 | + if ((prop[0] && sx_strcasecmp(prop, "og:title") == 0) || | |
| 881 | + (name[0] && sx_strcasecmp(name, "og:title") == 0)) { | |
| 882 | + if (attr_get(t.v[i].attrs, "content", content, sizeof content) && | |
| 883 | + content[0]) { | |
| 884 | + buf_t b; | |
| 885 | + buf_init(&b); | |
| 886 | + collapse_ws_append(&b, content); | |
| 887 | + if (b.n) { | |
| 888 | + b.p[b.n] = '\0'; | |
| 889 | + result = b.p; | |
| 890 | + break; | |
| 891 | + } | |
| 892 | + free(b.p); | |
| 893 | + } | |
| 894 | + } | |
| 895 | + } | |
| 896 | + } | |
| 897 | + if (!result) { | |
| 898 | + for (i = 0; i < t.n; i++) { | |
| 899 | + if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "title") == 0) { | |
| 900 | + size_t j; | |
| 901 | + for (j = i + 1; j < t.n && t.v[j].kind != TOK_CLOSE; j++) { | |
| 902 | + if (t.v[j].kind == TOK_TEXT && t.v[j].text && | |
| 903 | + t.v[j].text[0]) { | |
| 904 | + buf_t b; | |
| 905 | + buf_init(&b); | |
| 906 | + collapse_ws_append(&b, t.v[j].text); | |
| 907 | + if (b.n) { b.p[b.n] = '\0'; result = b.p; } | |
| 908 | + else free(b.p); | |
| 909 | + break; | |
| 910 | + } | |
| 911 | + } | |
| 912 | + break; | |
| 913 | + } | |
| 914 | + } | |
| 915 | + } | |
| 916 | + toks_free(&t); | |
| 917 | + if (out_len) *out_len = result ? strlen(result) : 0; | |
| 918 | + return result; | |
| 919 | +} | |
| 920 | + | |
| 921 | +/* word-normalised comparison (letters+digits runs, lowercased) */ | |
| 922 | +static size_t norm_words(const char *s, size_t n, char *out, size_t outsz) | |
| 923 | +{ | |
| 924 | + size_t o = 0, i = 0; | |
| 925 | + int sep = 1; | |
| 926 | + for (i = 0; i < n; i++) { | |
| 927 | + char c = s[i]; | |
| 928 | + if (isalnum((unsigned char)c)) { | |
| 929 | + if (o + 2 >= outsz) break; | |
| 930 | + if (sep && o) out[o++] = ' '; | |
| 931 | + sep = 0; | |
| 932 | + out[o++] = (char)tolower((unsigned char)c); | |
| 933 | + } else { | |
| 934 | + sep = 1; | |
| 935 | + } | |
| 936 | + } | |
| 937 | + out[o] = '\0'; | |
| 938 | + return o; | |
| 939 | +} | |
| 940 | + | |
| 941 | +int fx_md_starts_with_title(const char *md, size_t md_len, | |
| 942 | + const char *title, size_t title_len) | |
| 943 | +{ | |
| 944 | + char tw[1024], mw[4096]; | |
| 945 | + size_t tl, ml, k; | |
| 946 | + | |
| 947 | + if (!md || !title || !title_len) return 0; | |
| 948 | + tl = norm_words(title, title_len, tw, sizeof tw); | |
| 949 | + if (!tl) return 0; | |
| 950 | + if (md_len > 800) md_len = 800; /* the heading is near the top */ | |
| 951 | + ml = norm_words(md, md_len, mw, sizeof mw); | |
| 952 | + if (!ml) return 0; | |
| 953 | + if (ml < tl) return 0; | |
| 954 | + for (k = 0; k < tl; k++) if (mw[k] != tw[k]) return 0; | |
| 955 | + /* the next char must be a word boundary (space or end) */ | |
| 956 | + if (ml > tl && mw[tl] != ' ') return 0; | |
| 957 | + return 1; | |
| 958 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..092d8f8 | ||
| --- /dev/null | ||
| +++ b/src/fetch_md.h | ||
| @@ -0,0 +1,41 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_md.h - pure C99 HTML tokenizer -> clean Markdown converter. | |
| 3 | + * | |
| 4 | + * Scope (task spec, matching what the fetch MCP tool needs): | |
| 5 | + * - strips <script>/<style>/<noscript>/<svg>/<head>/<nav>/<aside>/<footer>/ | |
| 6 | + * <form>/<template> subtrees and comments | |
| 7 | + * - headings h1..h6 -> ATX (#..######) | |
| 8 | + * - links -> [text](href) (absolute-ised against the page URL) | |
| 9 | + * - ul/ol -> - / 1. lists (one nesting level) | |
| 10 | + * - pre/code -> fenced blocks / `code spans` | |
| 11 | + * - strong/b -> **..**, em/i -> *..* | |
| 12 | + * - p/div/br/hr/blockquote/table basics -> line breaks / pipes | |
| 13 | + * - decodes the common HTML entities and &#NNN; / &#xHH; | |
| 14 | + * | |
| 15 | + * It is a forgiving tokenizer over raw bytes (UTF-8 passes through untouched); | |
| 16 | + * it is not a full DOM. That is enough to take a web page down to clean | |
| 17 | + * readable Markdown and is a clean-room reimplementation, not a port of any | |
| 18 | + * upstream converter. | |
| 19 | + */ | |
| 20 | +#ifndef SX_FETCH_MD_H | |
| 21 | +#define SX_FETCH_MD_H | |
| 22 | + | |
| 23 | +#include <stddef.h> | |
| 24 | + | |
| 25 | +/* Convert an HTML document to Markdown. Returns a malloc'd NUL-terminated | |
| 26 | + * string and sets *out_len. Always returns non-NULL. */ | |
| 27 | +char *fx_html_to_markdown(const char *html, size_t len, size_t *out_len); | |
| 28 | + | |
| 29 | +/* Extract the document title (og:title meta, then <title>). Returns malloc'd | |
| 30 | + * UTF-8 text or NULL; sets *out_len. */ | |
| 31 | +char *fx_html_title(const char *html, size_t len, size_t *out_len); | |
| 32 | + | |
| 33 | +/* Whether markdown `md` (length md_len) already opens with the title text | |
| 34 | + * (word-insensitive, like upstream's title.py). */ | |
| 35 | +int fx_md_starts_with_title(const char *md, size_t md_len, | |
| 36 | + const char *title, size_t title_len); | |
| 37 | + | |
| 38 | +/* Set the base URL used to absolutise relative links (may be NULL). */ | |
| 39 | +void fx_md_set_base_url(const char *url); | |
| 40 | + | |
| 41 | +#endif /* SX_FETCH_MD_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..1abae01 | ||
| --- /dev/null | ||
| +++ b/src/fetch_tls.c | ||
| @@ -0,0 +1,226 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_tls.c - mbedTLS client over an already-connected socket (POSIX). | |
| 3 | + * | |
| 4 | + * The socket arrives pre-validated and pre-connected by fetch_http.c (the | |
| 5 | + * SSRF check happened on the numeric address before connect), so this layer | |
| 6 | + * only wraps TLS around it: no DNS here, no second connect, therefore no | |
| 7 | + * rebinding window. | |
| 8 | + * | |
| 9 | + * Policy: TLS 1.2 minimum, VERIFY_PEER always, hostname checked against the | |
| 10 | + * certificate. Trust anchors: FETCH_TLS_CA_FILE if set and readable, else the | |
| 11 | + * first system bundle that exists. There is deliberately NO way to disable | |
| 12 | + * verification. | |
| 13 | + * | |
| 14 | + * _WIN32: WinHTTP does TLS itself; this file is an empty TU there. | |
| 15 | + */ | |
| 16 | +#include "fetch_tls.h" | |
| 17 | + | |
| 18 | +#if !defined(_WIN32) | |
| 19 | + | |
| 20 | +#ifndef _POSIX_C_SOURCE | |
| 21 | +#define _POSIX_C_SOURCE 200809L | |
| 22 | +#endif | |
| 23 | + | |
| 24 | +#include <errno.h> | |
| 25 | +#include <stdio.h> | |
| 26 | +#include <stdlib.h> | |
| 27 | +#include <string.h> | |
| 28 | +#include <sys/socket.h> | |
| 29 | +#include <sys/stat.h> | |
| 30 | +#include <unistd.h> | |
| 31 | + | |
| 32 | +#include "mbedtls/build_info.h" | |
| 33 | +#include "mbedtls/ctr_drbg.h" | |
| 34 | +#include "mbedtls/entropy.h" | |
| 35 | +#include "mbedtls/error.h" | |
| 36 | +#include "mbedtls/net_sockets.h" | |
| 37 | +#include "mbedtls/psa_util.h" | |
| 38 | +#include "mbedtls/ssl.h" | |
| 39 | +#include "mbedtls/x509_crt.h" | |
| 40 | +#include "psa/crypto.h" | |
| 41 | + | |
| 42 | +struct fx_tls { | |
| 43 | + int fd; | |
| 44 | + mbedtls_ssl_context ssl; | |
| 45 | + mbedtls_ssl_config conf; | |
| 46 | + mbedtls_entropy_context entropy; | |
| 47 | + mbedtls_ctr_drbg_context drbg; | |
| 48 | + mbedtls_x509_crt cas; | |
| 49 | + int alive; | |
| 50 | +}; | |
| 51 | + | |
| 52 | +static const char *const CA_BUNDLES[] = { | |
| 53 | + "/etc/ssl/certs/ca-certificates.crt", /* Debian/Ubuntu/Alpine */ | |
| 54 | + "/etc/pki/tls/certs/ca-bundle.crt", /* RHEL/Fedora */ | |
| 55 | + "/etc/ssl/ca-bundle.pem", /* openSUSE */ | |
| 56 | + "/etc/ssl/cert.pem", /* Alpine/macOS-ish */ | |
| 57 | + "/var/ssl/certs/ca-certificates.crt", /* Termux */ | |
| 58 | + NULL | |
| 59 | +}; | |
| 60 | + | |
| 61 | +static int bio_send(void *ctx, const unsigned char *buf, size_t len) | |
| 62 | +{ | |
| 63 | + fx_tls *t = (fx_tls *)ctx; | |
| 64 | + ssize_t w; | |
| 65 | + do { w = send(t->fd, buf, len, MSG_NOSIGNAL); } while (w < 0 && errno == EINTR); | |
| 66 | + if (w < 0) return MBEDTLS_ERR_NET_SEND_FAILED; | |
| 67 | + return (int)w; | |
| 68 | +} | |
| 69 | + | |
| 70 | +static int bio_recv(void *ctx, unsigned char *buf, size_t len) | |
| 71 | +{ | |
| 72 | + fx_tls *t = (fx_tls *)ctx; | |
| 73 | + ssize_t r; | |
| 74 | + do { r = recv(t->fd, buf, len, 0); } while (r < 0 && errno == EINTR); | |
| 75 | + if (r == 0) return MBEDTLS_ERR_SSL_CONN_EOF; | |
| 76 | + if (r < 0) { | |
| 77 | + if (errno == EAGAIN || errno == EWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_READ; | |
| 78 | + return MBEDTLS_ERR_NET_RECV_FAILED; | |
| 79 | + } | |
| 80 | + return (int)r; | |
| 81 | +} | |
| 82 | + | |
| 83 | +static void fail_free(fx_tls *t) | |
| 84 | +{ | |
| 85 | + if (!t) return; | |
| 86 | + if (t->fd >= 0) { close(t->fd); t->fd = -1; } | |
| 87 | + if (t->alive) { | |
| 88 | + mbedtls_ssl_free(&t->ssl); | |
| 89 | + mbedtls_ssl_config_free(&t->conf); | |
| 90 | + mbedtls_x509_crt_free(&t->cas); | |
| 91 | + mbedtls_ctr_drbg_free(&t->drbg); | |
| 92 | + mbedtls_entropy_free(&t->entropy); | |
| 93 | + t->alive = 0; | |
| 94 | + } | |
| 95 | + free(t); | |
| 96 | +} | |
| 97 | + | |
| 98 | +fx_tls *fx_tls_connect_fd(int fd, const char *hostname, char *err, size_t errsz) | |
| 99 | +{ | |
| 100 | + fx_tls *t; | |
| 101 | + const char *ca; | |
| 102 | + int ret; | |
| 103 | + char m[160]; | |
| 104 | + | |
| 105 | + t = (fx_tls *)calloc(1, sizeof *t); | |
| 106 | + if (!t) { snprintf(err, errsz, "out of memory"); close(fd); return NULL; } | |
| 107 | + t->fd = fd; | |
| 108 | + | |
| 109 | + if (psa_crypto_init() != PSA_SUCCESS) { | |
| 110 | + snprintf(err, errsz, "TLS failed: psa init"); | |
| 111 | + free(t); | |
| 112 | + close(fd); | |
| 113 | + return NULL; | |
| 114 | + } | |
| 115 | + | |
| 116 | + mbedtls_entropy_init(&t->entropy); | |
| 117 | + mbedtls_ctr_drbg_init(&t->drbg); | |
| 118 | + mbedtls_ssl_config_init(&t->conf); | |
| 119 | + mbedtls_ssl_init(&t->ssl); | |
| 120 | + mbedtls_x509_crt_init(&t->cas); | |
| 121 | + t->alive = 1; | |
| 122 | + | |
| 123 | + ret = mbedtls_ctr_drbg_seed(&t->drbg, mbedtls_entropy_func, &t->entropy, | |
| 124 | + (const unsigned char *)"sxfetch", 7); | |
| 125 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | |
| 126 | + snprintf(err, errsz, "TLS failed: rng seed: %s", m); goto fail; } | |
| 127 | + | |
| 128 | + ret = mbedtls_ssl_config_defaults(&t->conf, MBEDTLS_SSL_IS_CLIENT, | |
| 129 | + MBEDTLS_SSL_TRANSPORT_STREAM, | |
| 130 | + MBEDTLS_SSL_PRESET_DEFAULT); | |
| 131 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | |
| 132 | + snprintf(err, errsz, "TLS failed: config: %s", m); goto fail; } | |
| 133 | + mbedtls_ssl_conf_rng(&t->conf, mbedtls_ctr_drbg_random, &t->drbg); | |
| 134 | + mbedtls_ssl_conf_min_tls_version(&t->conf, MBEDTLS_SSL_VERSION_TLS1_2); | |
| 135 | + mbedtls_ssl_conf_authmode(&t->conf, MBEDTLS_SSL_VERIFY_REQUIRED); | |
| 136 | + | |
| 137 | + /* trust anchors */ | |
| 138 | + ca = getenv("FETCH_TLS_CA_FILE"); | |
| 139 | + if (ca && *ca) { | |
| 140 | + ret = mbedtls_x509_crt_parse_file(&t->cas, ca); | |
| 141 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | |
| 142 | + snprintf(err, errsz, "TLS failed: cannot parse CA file %s: %s", ca, m); | |
| 143 | + goto fail; } | |
| 144 | + } else { | |
| 145 | + int i, loaded = 0; | |
| 146 | + for (i = 0; CA_BUNDLES[i]; i++) { | |
| 147 | + struct stat st; | |
| 148 | + if (stat(CA_BUNDLES[i], &st) != 0 || !S_ISREG(st.st_mode)) continue; | |
| 149 | + if (mbedtls_x509_crt_parse_file(&t->cas, CA_BUNDLES[i]) == 0) { | |
| 150 | + loaded = 1; | |
| 151 | + break; | |
| 152 | + } | |
| 153 | + } | |
| 154 | + if (!loaded) { | |
| 155 | + snprintf(err, errsz, | |
| 156 | + "TLS failed: no trust anchors — no readable system CA bundle; " | |
| 157 | + "set FETCH_TLS_CA_FILE to a PEM bundle"); | |
| 158 | + goto fail; | |
| 159 | + } | |
| 160 | + } | |
| 161 | + mbedtls_ssl_conf_ca_chain(&t->conf, &t->cas, NULL); | |
| 162 | + | |
| 163 | + ret = mbedtls_ssl_setup(&t->ssl, &t->conf); | |
| 164 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | |
| 165 | + snprintf(err, errsz, "TLS failed: setup: %s", m); goto fail; } | |
| 166 | + ret = mbedtls_ssl_set_hostname(&t->ssl, hostname); | |
| 167 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | |
| 168 | + snprintf(err, errsz, "TLS failed: hostname: %s", m); goto fail; } | |
| 169 | + mbedtls_ssl_set_bio(&t->ssl, t, bio_send, bio_recv, NULL); | |
| 170 | + | |
| 171 | + do { | |
| 172 | + ret = mbedtls_ssl_handshake(&t->ssl); | |
| 173 | + } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); | |
| 174 | + if (ret) { | |
| 175 | + mbedtls_strerror(ret, m, sizeof m); | |
| 176 | + if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) | |
| 177 | + snprintf(err, errsz, | |
| 178 | + "TLS failed: certificate verification refused for %s (%s)", | |
| 179 | + hostname, m); | |
| 180 | + else | |
| 181 | + snprintf(err, errsz, "TLS failed: handshake with %s: %s", hostname, m); | |
| 182 | + goto fail; | |
| 183 | + } | |
| 184 | + | |
| 185 | + return t; | |
| 186 | + | |
| 187 | +fail: | |
| 188 | + fail_free(t); | |
| 189 | + return NULL; | |
| 190 | +} | |
| 191 | + | |
| 192 | +int fx_tls_read(fx_tls *t, char *buf, size_t n) | |
| 193 | +{ | |
| 194 | + int r; | |
| 195 | + if (!t || !t->alive) return -1; | |
| 196 | + do { r = mbedtls_ssl_read(&t->ssl, (unsigned char *)buf, n); } | |
| 197 | + while (r == MBEDTLS_ERR_SSL_WANT_READ); | |
| 198 | + if (r == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY || r == 0) return 0; | |
| 199 | + if (r == MBEDTLS_ERR_SSL_CONN_EOF) return 0; | |
| 200 | + if (r < 0) return -1; | |
| 201 | + return r; | |
| 202 | +} | |
| 203 | + | |
| 204 | +int fx_tls_write(fx_tls *t, const char *buf, size_t n) | |
| 205 | +{ | |
| 206 | + size_t off = 0; | |
| 207 | + if (!t || !t->alive) return -1; | |
| 208 | + while (off < n) { | |
| 209 | + int r = mbedtls_ssl_write(&t->ssl, (const unsigned char *)buf + off, n - off); | |
| 210 | + if (r == MBEDTLS_ERR_SSL_WANT_WRITE) continue; | |
| 211 | + if (r < 0) return -1; | |
| 212 | + off += (size_t)r; | |
| 213 | + } | |
| 214 | + return (int)off; | |
| 215 | +} | |
| 216 | + | |
| 217 | +void fx_tls_close(fx_tls *t) | |
| 218 | +{ | |
| 219 | + if (!t) return; | |
| 220 | + if (t->alive) mbedtls_ssl_close_notify(&t->ssl); | |
| 221 | + fail_free(t); | |
| 222 | +} | |
| 223 | + | |
| 224 | +int fx_tls_supported(void) { return 1; } | |
| 225 | + | |
| 226 | +#endif /* !_WIN32 */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..e69a5a4 | ||
| --- /dev/null | ||
| +++ b/src/fetch_tls.h | ||
| @@ -0,0 +1,34 @@ | ||
| 1 | +/* | |
| 2 | + * fetch_tls.h - minimal TLS stream over an already-connected socket. | |
| 3 | + * | |
| 4 | + * POSIX: vendored mbedTLS (verify peer + hostname against a CA bundle). | |
| 5 | + * _WIN32: this layer is not used (WinHTTP does TLS itself), so the module is | |
| 6 | + * an empty translation unit there and fx_tls_supported() reports 0. | |
| 7 | + */ | |
| 8 | +#ifndef SX_FETCH_TLS_H | |
| 9 | +#define SX_FETCH_TLS_H | |
| 10 | + | |
| 11 | +#include <stddef.h> | |
| 12 | + | |
| 13 | +#if !defined(_WIN32) | |
| 14 | + | |
| 15 | +typedef struct fx_tls fx_tls; | |
| 16 | + | |
| 17 | +/* Takes ownership of `fd` on success (closed by fx_tls_close). hostname is | |
| 18 | + * used for SNI and certificate verification. Returns NULL + err on failure | |
| 19 | + * (fd closed). */ | |
| 20 | +fx_tls *fx_tls_connect_fd(int fd, const char *hostname, char *err, size_t errsz); | |
| 21 | + | |
| 22 | +/* Returns bytes read, 0 at EOF, -1 on error. */ | |
| 23 | +int fx_tls_read(fx_tls *t, char *buf, size_t n); | |
| 24 | +/* Returns bytes written or -1. */ | |
| 25 | +int fx_tls_write(fx_tls *t, const char *buf, size_t n); | |
| 26 | + | |
| 27 | +void fx_tls_close(fx_tls *t); | |
| 28 | + | |
| 29 | +/* 1 when the binary was built with the TLS stack (POSIX), 0 otherwise. */ | |
| 30 | +int fx_tls_supported(void); | |
| 31 | + | |
| 32 | +#endif /* !_WIN32 */ | |
| 33 | + | |
| 34 | +#endif /* SX_FETCH_TLS_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..561948d | ||
| --- /dev/null | ||
| +++ b/src/plugin_fetch.c | ||
| @@ -0,0 +1,846 @@ | ||
| 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 | +# include <windows.h> | |
| 56 | +# include <io.h> | |
| 57 | +#endif | |
| 58 | +#include <sys/stat.h> | |
| 59 | +#include <sys/types.h> | |
| 60 | + | |
| 61 | +#include "bot_theme_plugin.h" | |
| 62 | +#include "ui_html.h" | |
| 63 | +#include "fetch_http.h" | |
| 64 | +#include "fetch_md.h" | |
| 65 | +#include "sxmcp.h" | |
| 66 | + | |
| 67 | +#define PLUGIN_SLUG "fetch" | |
| 68 | +#define PLUGIN_ID "plugin_fetch" | |
| 69 | +#define PLUGIN_VER "1.0.0" | |
| 70 | + | |
| 71 | +#if defined(_WIN32) | |
| 72 | +# define sx_mkdir(p) _mkdir(p) | |
| 73 | +# define SX_PATHSEP '\\' | |
| 74 | +#else | |
| 75 | +# include <unistd.h> | |
| 76 | +# define sx_mkdir(p) mkdir((p), 0755) | |
| 77 | +# define SX_PATHSEP '/' | |
| 78 | +#endif | |
| 79 | + | |
| 80 | +void tool_result_free(tool_result *r) | |
| 81 | +{ | |
| 82 | + if (!r) return; | |
| 83 | + free(r->text); | |
| 84 | + free(r->raw_html); | |
| 85 | + memset(r, 0, sizeof *r); | |
| 86 | +} | |
| 87 | + | |
| 88 | +/* ------------------------------------------------------------------ */ | |
| 89 | +/* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and the */ | |
| 90 | +/* HTML page never call this; every JSON action does. */ | |
| 91 | +/* ------------------------------------------------------------------ */ | |
| 92 | + | |
| 93 | +static void require_node_auth(void) | |
| 94 | +{ | |
| 95 | + const char *np = getenv("BOT_PASSWORD"); | |
| 96 | + const char *xp, *auth; | |
| 97 | + char qpwd[256] = {0}; | |
| 98 | + const char *qs; | |
| 99 | + | |
| 100 | + if (!np || !*np) return; /* open node: no gate */ | |
| 101 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 102 | + if (xp && strcmp(xp, np) == 0) return; | |
| 103 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 104 | + if (auth) { | |
| 105 | + while (*auth == ' ') auth++; | |
| 106 | + if (sx_strncasecmp(auth, "Bearer ", 7) == 0) { | |
| 107 | + auth += 7; | |
| 108 | + while (*auth == ' ') auth++; | |
| 109 | + if (strcmp(auth, np) == 0) return; | |
| 110 | + } | |
| 111 | + } | |
| 112 | + qs = getenv("QUERY_STRING"); | |
| 113 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | |
| 114 | + return; | |
| 115 | + | |
| 116 | + fputs("Status: 401 Unauthorized\r\n" | |
| 117 | + "Content-Type: application/json; charset=utf-8\r\n\r\n" | |
| 118 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 119 | + exit(0); | |
| 120 | +} | |
| 121 | + | |
| 122 | +/* ------------------------------------------------------------------ */ | |
| 123 | +/* Connector dir + persisted policy */ | |
| 124 | +/* ------------------------------------------------------------------ */ | |
| 125 | + | |
| 126 | +static void connector_dir(char *out, size_t outsz) | |
| 127 | +{ | |
| 128 | + const char *env = getenv("SX_CONNECTOR_DIR"); | |
| 129 | + struct stat st; | |
| 130 | + | |
| 131 | + if (env && *env) { snprintf(out, outsz, "%s", env); return; } | |
| 132 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && | |
| 133 | + access("/workspace", W_OK) == 0) { | |
| 134 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/fetch"); | |
| 135 | + return; | |
| 136 | + } | |
| 137 | +#if defined(_WIN32) | |
| 138 | + { | |
| 139 | + const char *la = getenv("LOCALAPPDATA"); | |
| 140 | + if (la && *la) { | |
| 141 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\fetch", la); | |
| 142 | + return; | |
| 143 | + } | |
| 144 | + } | |
| 145 | +#endif | |
| 146 | + { | |
| 147 | + const char *home = getenv("HOME"); | |
| 148 | + if (!home || !*home) home = "/root"; | |
| 149 | + snprintf(out, outsz, "%s/.scorpiox/connectors/fetch", home); | |
| 150 | + } | |
| 151 | +} | |
| 152 | + | |
| 153 | +static int mkdirs(const char *path) | |
| 154 | +{ | |
| 155 | + char buf[1200]; | |
| 156 | + size_t i, n; | |
| 157 | + struct stat st; | |
| 158 | + snprintf(buf, sizeof buf, "%s", path); | |
| 159 | + n = strlen(buf); | |
| 160 | + for (i = 1; i < n; i++) { | |
| 161 | + if (buf[i] == '/' || buf[i] == '\\') { | |
| 162 | + char save = buf[i]; | |
| 163 | + buf[i] = '\0'; | |
| 164 | + if (i > 2) sx_mkdir(buf); | |
| 165 | + buf[i] = save; | |
| 166 | + } | |
| 167 | + } | |
| 168 | + sx_mkdir(buf); | |
| 169 | + return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); | |
| 170 | +} | |
| 171 | + | |
| 172 | +static void policy_path(char *out, size_t outsz) | |
| 173 | +{ | |
| 174 | + char dir[1000]; | |
| 175 | + connector_dir(dir, sizeof dir); | |
| 176 | + snprintf(out, outsz, "%s%cconfig.json", dir, SX_PATHSEP); | |
| 177 | +} | |
| 178 | + | |
| 179 | +static int policy_read_allow_private(void) | |
| 180 | +{ | |
| 181 | + char p[1200]; | |
| 182 | + FILE *f; | |
| 183 | + long sz; | |
| 184 | + char *txt; | |
| 185 | + int v = 0; | |
| 186 | + char *k; | |
| 187 | + | |
| 188 | + policy_path(p, sizeof p); | |
| 189 | + f = fopen(p, "rb"); | |
| 190 | + if (!f) return 0; | |
| 191 | + fseek(f, 0, SEEK_END); | |
| 192 | + sz = ftell(f); | |
| 193 | + fseek(f, 0, SEEK_SET); | |
| 194 | + if (sz < 0 || sz > 65536) { fclose(f); return 0; } | |
| 195 | + txt = (char *)sx_malloc((size_t)sz + 1); | |
| 196 | + if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) { free(txt); fclose(f); return 0; } | |
| 197 | + txt[sz] = '\0'; | |
| 198 | + fclose(f); | |
| 199 | + k = strstr(txt, "\"allow_private\""); | |
| 200 | + if (k) { | |
| 201 | + k += strlen("\"allow_private\""); | |
| 202 | + while (*k && (unsigned char)*k <= ' ') k++; | |
| 203 | + if (*k == ':') { | |
| 204 | + k++; | |
| 205 | + while (*k && (unsigned char)*k <= ' ') k++; | |
| 206 | + if (strncmp(k, "true", 4) == 0) v = 1; | |
| 207 | + } | |
| 208 | + } | |
| 209 | + free(txt); | |
| 210 | + return v; | |
| 211 | +} | |
| 212 | + | |
| 213 | +/* Cached for the process lifetime (the fetch legs ask per request). */ | |
| 214 | +int fx_policy_allow_private(void) | |
| 215 | +{ | |
| 216 | + static int cached = -1; | |
| 217 | + if (cached < 0) cached = policy_read_allow_private(); | |
| 218 | + return cached; | |
| 219 | +} | |
| 220 | + | |
| 221 | +static int policy_set_allow_private(int on) | |
| 222 | +{ | |
| 223 | + char dir[1000], p[1200], tmp[1300]; | |
| 224 | + FILE *f; | |
| 225 | + connector_dir(dir, sizeof dir); | |
| 226 | + if (!mkdirs(dir)) return 0; | |
| 227 | + policy_path(p, sizeof p); | |
| 228 | + snprintf(tmp, sizeof tmp, "%s.tmp", p); | |
| 229 | + f = fopen(tmp, "wb"); | |
| 230 | + if (!f) return 0; | |
| 231 | + fprintf(f, "{\"allow_private\":%s,\"updated_at\":%lld}\n", | |
| 232 | + on ? "true" : "false", (long long)time(NULL)); | |
| 233 | + fclose(f); | |
| 234 | + remove(p); | |
| 235 | + if (rename(tmp, p) != 0) { remove(tmp); return 0; } | |
| 236 | + return 1; | |
| 237 | +} | |
| 238 | + | |
| 239 | +/* ------------------------------------------------------------------ */ | |
| 240 | +/* The fetch engine (shared by --mcp, ?action=fetch and the UI) */ | |
| 241 | +/* ------------------------------------------------------------------ */ | |
| 242 | + | |
| 243 | +void fetch_tool_run(const char *url, long max_length, long start_index, int raw, | |
| 244 | + tool_result *out) | |
| 245 | +{ | |
| 246 | + fx_response resp; | |
| 247 | + char *content = NULL; /* heap: what gets chunked */ | |
| 248 | + size_t content_len = 0; | |
| 249 | + char prefix[2200]; | |
| 250 | + char *title = NULL; | |
| 251 | + size_t title_len = 0; | |
| 252 | + | |
| 253 | + memset(out, 0, sizeof *out); | |
| 254 | + prefix[0] = '\0'; | |
| 255 | + | |
| 256 | + if (!url || !url[0]) { | |
| 257 | + snprintf(out->error, sizeof out->error, "url is required"); | |
| 258 | + return; | |
| 259 | + } | |
| 260 | + if (max_length <= 0) max_length = 5000; | |
| 261 | + if (max_length > 100000) max_length = 100000; | |
| 262 | + if (start_index < 0) start_index = 0; | |
| 263 | + | |
| 264 | + if (fx_fetch(url, &resp) != 0) { | |
| 265 | + snprintf(out->error, sizeof out->error, "%s", | |
| 266 | + resp.error[0] ? resp.error : "fetch failed"); | |
| 267 | + fx_response_free(&resp); | |
| 268 | + return; | |
| 269 | + } | |
| 270 | + out->status = resp.status; | |
| 271 | + snprintf(out->content_type, sizeof out->content_type, "%s", resp.content_type); | |
| 272 | + out->bytes_read = resp.body_len; | |
| 273 | + snprintf(out->final_url, sizeof out->final_url, "%s", resp.url); | |
| 274 | + { | |
| 275 | + size_t cap = resp.body_len; | |
| 276 | + if (cap > 400000) cap = 400000; /* the UI Raw tab only */ | |
| 277 | + out->raw_html = fx_strndup(resp.body ? resp.body : "", cap); | |
| 278 | + } | |
| 279 | + out->redirected = resp.hops > 0; | |
| 280 | + | |
| 281 | + if (resp.status >= 400) { | |
| 282 | + snprintf(out->error, sizeof out->error, | |
| 283 | + "Failed to fetch %s - status code %d", resp.url, resp.status); | |
| 284 | + fx_response_free(&resp); | |
| 285 | + return; | |
| 286 | + } | |
| 287 | + if (resp.hops > 0) | |
| 288 | + snprintf(prefix, sizeof prefix, "Redirecting from %s to %s\n\n", | |
| 289 | + resp.first_url, resp.url); | |
| 290 | + | |
| 291 | + { | |
| 292 | + char ctlower[128]; | |
| 293 | + int is_md = 0, is_html = 0; | |
| 294 | + size_t i; | |
| 295 | + const char *ct = resp.content_type; | |
| 296 | + for (i = 0; ct && ct[i] && i < sizeof ctlower - 1; i++) | |
| 297 | + ctlower[i] = (char)tolower((unsigned char)ct[i]); | |
| 298 | + ctlower[i] = '\0'; | |
| 299 | + { | |
| 300 | + char *sc = strchr(ctlower, ';'); | |
| 301 | + if (sc) *sc = '\0'; | |
| 302 | + } | |
| 303 | + is_md = strcmp(ctlower, "text/markdown") == 0; | |
| 304 | + is_html = strstr(ctlower, "text/html") != NULL || | |
| 305 | + strstr(ctlower, "application/xhtml+xml") != NULL || | |
| 306 | + (!ctlower[0] && fx_body_looks_like_html(resp.body, resp.body_len)); | |
| 307 | + | |
| 308 | + if (is_md) { | |
| 309 | + content = fx_strndup(resp.body, resp.body_len); | |
| 310 | + content_len = resp.body_len; | |
| 311 | + prefix[0] = '\0'; /* markdown is returned verbatim */ | |
| 312 | + } else if (is_html && !raw) { | |
| 313 | + char *md = fx_html_to_markdown(resp.body, resp.body_len, &content_len); | |
| 314 | + title = fx_html_title(resp.body, resp.body_len, &title_len); | |
| 315 | + if (title && title_len && | |
| 316 | + !fx_md_starts_with_title(md, content_len, title, title_len)) { | |
| 317 | + size_t hl = 2 + title_len + 2; | |
| 318 | + char *cat = (char *)sx_malloc(hl + content_len + 1); | |
| 319 | + cat[0] = '#'; cat[1] = ' '; | |
| 320 | + memcpy(cat + 2, title, title_len); | |
| 321 | + cat[2 + title_len] = '\n'; | |
| 322 | + cat[3 + title_len] = '\n'; | |
| 323 | + if (content_len) memcpy(cat + hl, md, content_len); | |
| 324 | + cat[hl + content_len] = '\0'; | |
| 325 | + free(md); | |
| 326 | + md = cat; | |
| 327 | + content_len = hl + content_len; | |
| 328 | + } | |
| 329 | + if (title && title_len) | |
| 330 | + snprintf(out->title, sizeof out->title, "%s", title); | |
| 331 | + content = md; | |
| 332 | + if (!content[0] && content_len == 0) { | |
| 333 | + free(content); | |
| 334 | + content = sx_strdup(""); | |
| 335 | + } | |
| 336 | + } else { | |
| 337 | + content = fx_strndup(resp.body, resp.body_len); | |
| 338 | + content_len = resp.body_len; | |
| 339 | + if (!raw) { | |
| 340 | + char declared[280]; | |
| 341 | + snprintf(declared, sizeof declared, | |
| 342 | + "Content type %s cannot be simplified to markdown, " | |
| 343 | + "but here is the raw content:\n", | |
| 344 | + resp.content_type[0] ? resp.content_type : "(not declared)"); | |
| 345 | + { | |
| 346 | + size_t nl = strlen(declared); | |
| 347 | + char *cat = (char *)sx_malloc(nl + content_len + 1); | |
| 348 | + memcpy(cat, declared, nl); | |
| 349 | + if (content_len) memcpy(cat + nl, content, content_len); | |
| 350 | + cat[nl + content_len] = '\0'; | |
| 351 | + free(content); | |
| 352 | + content = cat; | |
| 353 | + content_len = nl + content_len; | |
| 354 | + } | |
| 355 | + } | |
| 356 | + } | |
| 357 | + } | |
| 358 | + fx_response_free(&resp); | |
| 359 | + free(title); | |
| 360 | + | |
| 361 | + /* Truncation footer, upstream-shaped. */ | |
| 362 | + { | |
| 363 | + size_t si = (size_t)start_index; | |
| 364 | + size_t ml = (size_t)max_length; | |
| 365 | + buf_t b; | |
| 366 | + buf_init(&b); | |
| 367 | + buf_addf(&b, "%sContents of %s:\n", | |
| 368 | + prefix, out->final_url[0] ? out->final_url : url); | |
| 369 | + if (si >= content_len) { | |
| 370 | + buf_add(&b, "<error>No more content available.</error>"); | |
| 371 | + } else { | |
| 372 | + size_t take = content_len - si; | |
| 373 | + if (take > ml) take = ml; | |
| 374 | + buf_bput(&b, content + si, take); | |
| 375 | + if (take == ml && si + take < content_len) | |
| 376 | + buf_addf(&b, "\n\n<error>Content truncated. Call the fetch tool " | |
| 377 | + "with a start_index of %zu to get more content.</error>", | |
| 378 | + si + take); | |
| 379 | + } | |
| 380 | + out->text = b.p ? b.p : sx_strdup(""); | |
| 381 | + out->text_len = b.n; | |
| 382 | + out->content_len = content_len; | |
| 383 | + } | |
| 384 | + free(content); | |
| 385 | + out->ok = 1; | |
| 386 | +} | |
| 387 | + | |
| 388 | +/* ------------------------------------------------------------------ */ | |
| 389 | +/* --mcp mode */ | |
| 390 | +/* ------------------------------------------------------------------ */ | |
| 391 | + | |
| 392 | +static const char *FETCH_TOOL_SCHEMA = | |
| 393 | + "{\"type\":\"object\",\"properties\":{" | |
| 394 | + "\"url\":{\"type\":\"string\",\"description\":\"URL to fetch\"}," | |
| 395 | + "\"max_length\":{\"type\":\"integer\",\"description\":\"Maximum number of characters to return.\",\"minimum\":1,\"maximum\":100000}," | |
| 396 | + "\"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}," | |
| 397 | + "\"raw\":{\"type\":\"boolean\",\"description\":\"Get the actual HTML content of the requested page, without simplification.\"}" | |
| 398 | + "},\"required\":[\"url\"]}"; | |
| 399 | + | |
| 400 | +static void mcp_tools_list(FILE *out, const char *id_raw) | |
| 401 | +{ | |
| 402 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[", id_raw); | |
| 403 | + fprintf(out, "{\"name\":\"fetch\",\"description\":\"Fetches a URL from the internet " | |
| 404 | + "and optionally extracts its content as markdown. Follows up to 5 " | |
| 405 | + "redirects, refuses private/loopback/link-local addresses unless the " | |
| 406 | + "operator allows them, and truncates long results with a start_index " | |
| 407 | + "hint.\",\"inputSchema\":%s," | |
| 408 | + "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false," | |
| 409 | + "\"idempotentHint\":true,\"openWorldHint\":true}}", | |
| 410 | + FETCH_TOOL_SCHEMA); | |
| 411 | + fprintf(out, "]}}\n"); | |
| 412 | + fflush(out); | |
| 413 | +} | |
| 414 | + | |
| 415 | +static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params) | |
| 416 | +{ | |
| 417 | + const char *name = NULL; | |
| 418 | + yyjson_val *args = NULL; | |
| 419 | + const char *url = NULL; | |
| 420 | + long max_length = 5000, start_index = 0; | |
| 421 | + int raw = 0; | |
| 422 | + tool_result r; | |
| 423 | + | |
| 424 | + if (params) { | |
| 425 | + yyjson_val *v; | |
| 426 | + name = yyjson_get_str(yyjson_obj_get(params, "name")); | |
| 427 | + args = yyjson_obj_get(params, "arguments"); | |
| 428 | + if (args) { | |
| 429 | + url = yyjson_get_str(yyjson_obj_get(args, "url")); | |
| 430 | + v = yyjson_obj_get(args, "max_length"); | |
| 431 | + if (yyjson_is_int(v)) max_length = (long)yyjson_get_int(v); | |
| 432 | + else if (yyjson_is_str(v) && yyjson_get_str(v)) | |
| 433 | + max_length = atol(yyjson_get_str(v)); | |
| 434 | + v = yyjson_obj_get(args, "start_index"); | |
| 435 | + if (yyjson_is_int(v)) start_index = (long)yyjson_get_int(v); | |
| 436 | + else if (yyjson_is_str(v) && yyjson_get_str(v)) | |
| 437 | + start_index = atol(yyjson_get_str(v)); | |
| 438 | + v = yyjson_obj_get(args, "raw"); | |
| 439 | + if (yyjson_is_true(v) || | |
| 440 | + (yyjson_is_str(v) && yyjson_get_str(v) && | |
| 441 | + strcmp(yyjson_get_str(v), "true") == 0)) | |
| 442 | + raw = 1; | |
| 443 | + } | |
| 444 | + } | |
| 445 | + if (!name || strcmp(name, "fetch") != 0) { | |
| 446 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," | |
| 447 | + "\"message\":\"unknown tool\"}}\n", id_raw); | |
| 448 | + fflush(out); | |
| 449 | + return; | |
| 450 | + } | |
| 451 | + | |
| 452 | + memset(&r, 0, sizeof r); | |
| 453 | + fetch_tool_run(url, max_length, start_index, raw, &r); | |
| 454 | + | |
| 455 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" | |
| 456 | + "[{\"type\":\"text\",\"text\":", id_raw); | |
| 457 | + if (r.ok) { | |
| 458 | + json_escape(out, r.text ? r.text : ""); | |
| 459 | + fprintf(out, "}],\"isError\":false}}\n"); | |
| 460 | + } else { | |
| 461 | + json_escape(out, r.error[0] ? r.error : "fetch failed"); | |
| 462 | + fprintf(out, "}],\"isError\":true}}\n"); | |
| 463 | + } | |
| 464 | + fflush(out); | |
| 465 | + tool_result_free(&r); | |
| 466 | +} | |
| 467 | + | |
| 468 | +/* Copy the raw JSON-RPC id token (number or string) so the reply echoes the | |
| 469 | + * same type. */ | |
| 470 | +static int json_id_raw(const char *line, char *out, size_t outsz) | |
| 471 | +{ | |
| 472 | + const char *p = strstr(line, "\"id\""); | |
| 473 | + size_t i = 0; | |
| 474 | + if (!p) return 0; | |
| 475 | + p += 4; | |
| 476 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 477 | + if (*p != ':') return 0; | |
| 478 | + p++; | |
| 479 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 480 | + if (*p == '"') { | |
| 481 | + out[i++] = *p++; | |
| 482 | + while (*p && i + 2 < outsz) { | |
| 483 | + out[i++] = *p; | |
| 484 | + if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } | |
| 485 | + else if (*p == '"') { p++; out[i++] = '"'; break; } | |
| 486 | + else p++; | |
| 487 | + } | |
| 488 | + out[i] = '\0'; | |
| 489 | + return i > 1; | |
| 490 | + } | |
| 491 | + while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && | |
| 492 | + i + 1 < outsz) | |
| 493 | + out[i++] = *p++; | |
| 494 | + out[i] = '\0'; | |
| 495 | + return i > 0; | |
| 496 | +} | |
| 497 | + | |
| 498 | +static void mcp_server_info(FILE *out, const char *id_raw) | |
| 499 | +{ | |
| 500 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" | |
| 501 | + "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," | |
| 502 | + "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", | |
| 503 | + id_raw, PLUGIN_SLUG, PLUGIN_VER); | |
| 504 | + fflush(out); | |
| 505 | +} | |
| 506 | + | |
| 507 | +int run_mcp(void) | |
| 508 | +{ | |
| 509 | + char line[65536]; | |
| 510 | + setvbuf(stdout, NULL, _IOLBF, 0); | |
| 511 | + while (fgets(line, sizeof line, stdin)) { | |
| 512 | + yyjson_doc *doc; | |
| 513 | + yyjson_val *root, *m, *params; | |
| 514 | + const char *method; | |
| 515 | + char id_raw[128] = ""; | |
| 516 | + | |
| 517 | + if (!strchr(line, '{')) continue; | |
| 518 | + doc = yyjson_read(line, strlen(line), 0); | |
| 519 | + if (!doc) continue; | |
| 520 | + root = yyjson_doc_get_root(doc); | |
| 521 | + m = yyjson_obj_get(root, "method"); | |
| 522 | + method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; | |
| 523 | + params = yyjson_obj_get(root, "params"); | |
| 524 | + if (!method) { yyjson_doc_free(doc); continue; } | |
| 525 | + if (strncmp(method, "notifications/", 14) == 0) { | |
| 526 | + yyjson_doc_free(doc); | |
| 527 | + continue; | |
| 528 | + } | |
| 529 | + if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { | |
| 530 | + yyjson_doc_free(doc); | |
| 531 | + continue; | |
| 532 | + } | |
| 533 | + | |
| 534 | + if (strcmp(method, "initialize") == 0) { | |
| 535 | + mcp_server_info(stdout, id_raw); | |
| 536 | + } else if (strcmp(method, "tools/list") == 0) { | |
| 537 | + mcp_tools_list(stdout, id_raw); | |
| 538 | + } else if (strcmp(method, "tools/call") == 0) { | |
| 539 | + mcp_tool_call(stdout, id_raw, params); | |
| 540 | + } else if (strcmp(method, "ping") == 0) { | |
| 541 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); | |
| 542 | + fflush(stdout); | |
| 543 | + } else { | |
| 544 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," | |
| 545 | + "\"message\":\"method not found\"}}\n", id_raw); | |
| 546 | + fflush(stdout); | |
| 547 | + } | |
| 548 | + yyjson_doc_free(doc); | |
| 549 | + } | |
| 550 | + return 0; | |
| 551 | +} | |
| 552 | + | |
| 553 | +/* ------------------------------------------------------------------ */ | |
| 554 | +/* Discovery metadata */ | |
| 555 | +/* ------------------------------------------------------------------ */ | |
| 556 | + | |
| 557 | +static int run_meta(void) | |
| 558 | +{ | |
| 559 | + puts("{\"name\":\"fetch\",\"desc\":\"URL to Markdown\",\"kind\":\"mcp\"," | |
| 560 | + "\"mcp\":true,\"daemon\":false,\"menus\":false,\"verified\":\"live\"}"); | |
| 561 | + fflush(stdout); | |
| 562 | + return 0; | |
| 563 | +} | |
| 564 | + | |
| 565 | +/* ------------------------------------------------------------------ */ | |
| 566 | +/* JSON node API */ | |
| 567 | +/* ------------------------------------------------------------------ */ | |
| 568 | + | |
| 569 | +static void json_headers(void) | |
| 570 | +{ | |
| 571 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 572 | + "Cache-Control: no-store\r\n" | |
| 573 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 574 | +} | |
| 575 | + | |
| 576 | +/* Walk the generated page and splice the shared bot theme in at the two | |
| 577 | + * control bytes tools/gen_ui.py left behind: 0x01 becomes the pre-paint | |
| 578 | + * script plus the token stylesheet, 0x02 the sx-theme handoff. Injecting here | |
| 579 | + * (rather than pasting the macros into ui.html) is what keeps the theme from | |
| 580 | + * drifting away from the rest of the bot. */ | |
| 581 | +static void emit_ui(void) | |
| 582 | +{ | |
| 583 | + const char *p = UI_HTML; | |
| 584 | + | |
| 585 | + while (*p) { | |
| 586 | + if (*p == '\001') { | |
| 587 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | |
| 588 | + "</style>", stdout); | |
| 589 | + p++; | |
| 590 | + } else if (*p == '\002') { | |
| 591 | + fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); | |
| 592 | + p++; | |
| 593 | + } else { | |
| 594 | + putchar(*p++); | |
| 595 | + } | |
| 596 | + } | |
| 597 | +} | |
| 598 | + | |
| 599 | +static char *read_body(void) | |
| 600 | +{ | |
| 601 | + const char *cl = getenv("CONTENT_LENGTH"); | |
| 602 | + long n; | |
| 603 | + char *buf; | |
| 604 | + size_t got = 0; | |
| 605 | + if (!cl || !*cl) return NULL; | |
| 606 | + n = atol(cl); | |
| 607 | + if (n <= 0 || n > 2 * 1024 * 1024) return NULL; | |
| 608 | + buf = (char *)sx_malloc((size_t)n + 1); | |
| 609 | + while (got < (size_t)n) { | |
| 610 | + size_t r = fread(buf + got, 1, (size_t)n - got, stdin); | |
| 611 | + if (r == 0) break; | |
| 612 | + got += r; | |
| 613 | + } | |
| 614 | + buf[got] = '\0'; | |
| 615 | + return buf; | |
| 616 | +} | |
| 617 | + | |
| 618 | +static int json_str_field(const char *json, const char *key, char *out, size_t outsz) | |
| 619 | +{ | |
| 620 | + yyjson_doc *doc; | |
| 621 | + yyjson_val *v; | |
| 622 | + int found = 0; | |
| 623 | + if (!json) return 0; | |
| 624 | + doc = yyjson_read(json, strlen(json), 0); | |
| 625 | + if (!doc) return 0; | |
| 626 | + v = yyjson_obj_get(yyjson_doc_get_root(doc), key); | |
| 627 | + if (yyjson_is_str(v) && yyjson_get_str(v)) { | |
| 628 | + snprintf(out, outsz, "%s", yyjson_get_str(v)); | |
| 629 | + found = 1; | |
| 630 | + } else if (yyjson_is_int(v)) { | |
| 631 | + snprintf(out, outsz, "%lld", (long long)yyjson_get_int(v)); | |
| 632 | + found = 1; | |
| 633 | + } else if (yyjson_is_bool(v)) { | |
| 634 | + snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); | |
| 635 | + found = 1; | |
| 636 | + } | |
| 637 | + yyjson_doc_free(doc); | |
| 638 | + return found; | |
| 639 | +} | |
| 640 | + | |
| 641 | +static void emit_tool_json(const tool_result *r, const char *url_arg) | |
| 642 | +{ | |
| 643 | + json_headers(); | |
| 644 | + if (!r->ok) { | |
| 645 | + fputs("{\"ok\":false,\"error\":", stdout); | |
| 646 | + json_escape(stdout, r->error[0] ? r->error : "fetch failed"); | |
| 647 | + fputs("}\n", stdout); | |
| 648 | + return; | |
| 649 | + } | |
| 650 | + fputs("{\"ok\":true,\"url\":", stdout); | |
| 651 | + json_escape(stdout, r->final_url[0] ? r->final_url : (url_arg ? url_arg : "")); | |
| 652 | + fprintf(stdout, ",\"status_code\":%d,\"redirected\":%s,\"content_type\":", | |
| 653 | + r->status, r->redirected ? "true" : "false"); | |
| 654 | + json_escape(stdout, r->content_type); | |
| 655 | + fprintf(stdout, ",\"bytes_read\":%zu,\"content_length\":%zu,\"title\":", | |
| 656 | + r->bytes_read, r->content_len); | |
| 657 | + if (r->title[0]) json_escape(stdout, r->title); else fputs("null", stdout); | |
| 658 | + fputs(",\"text\":", stdout); | |
| 659 | + json_escape(stdout, r->text ? r->text : ""); | |
| 660 | + fputs(",\"raw_html\":", stdout); | |
| 661 | + json_escape(stdout, r->raw_html ? r->raw_html : ""); | |
| 662 | + fputs("}\n", stdout); | |
| 663 | +} | |
| 664 | + | |
| 665 | +static void api_info(void) | |
| 666 | +{ | |
| 667 | + json_headers(); | |
| 668 | + fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG | |
| 669 | + "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," | |
| 670 | + "\"menus\":false,\"verified\":\"live\",\"tools\":[\"fetch\"],\"tool_schema\":", | |
| 671 | + stdout); | |
| 672 | + fputs(FETCH_TOOL_SCHEMA, stdout); | |
| 673 | + fprintf(stdout, ",\"allow_private\":%s", policy_read_allow_private() ? "true" : "false"); | |
| 674 | + fputs(",\"ssrf_policy\":\"private/loopback/link-local/special-purpose refused unless allowed\"," | |
| 675 | + "\"tls\":\"verify-peer + CA bundle (POSIX mbedTLS); WinHTTP system root store (Windows)\"," | |
| 676 | + "\"max_body_bytes\":", stdout); | |
| 677 | + fprintf(stdout, "%u", FX_MAX_BODY); | |
| 678 | + fputs(",\"max_length_cap\":100000,\"max_redirects\":5}\n", stdout); | |
| 679 | +} | |
| 680 | + | |
| 681 | +static int api_dispatch(const char *action, const char *qs, const char *body) | |
| 682 | +{ | |
| 683 | + if (!action[0] || strcmp(action, "fetch") == 0) { | |
| 684 | + char url[2048] = ""; | |
| 685 | + char nbuf[64] = ""; | |
| 686 | + long max_length = 5000, start_index = 0; | |
| 687 | + int raw = 0; | |
| 688 | + tool_result r; | |
| 689 | + | |
| 690 | + if (!(body && json_str_field(body, "url", url, sizeof url)) && | |
| 691 | + !(qs && *qs && get_query_val(qs, "url", url, sizeof url))) | |
| 692 | + url[0] = '\0'; | |
| 693 | + if ((qs && *qs && get_query_val(qs, "max_length", nbuf, sizeof nbuf)) || | |
| 694 | + (body && json_str_field(body, "max_length", nbuf, sizeof nbuf))) | |
| 695 | + max_length = atol(nbuf); | |
| 696 | + if ((qs && *qs && get_query_val(qs, "start_index", nbuf, sizeof nbuf)) || | |
| 697 | + (body && json_str_field(body, "start_index", nbuf, sizeof nbuf))) | |
| 698 | + start_index = atol(nbuf); | |
| 699 | + if ((qs && *qs && get_query_val(qs, "raw", nbuf, sizeof nbuf)) || | |
| 700 | + (body && json_str_field(body, "raw", nbuf, sizeof nbuf))) | |
| 701 | + raw = (strcmp(nbuf, "1") == 0 || strcmp(nbuf, "true") == 0); | |
| 702 | + | |
| 703 | + memset(&r, 0, sizeof r); | |
| 704 | + fetch_tool_run(url, max_length, start_index, raw, &r); | |
| 705 | + emit_tool_json(&r, url); | |
| 706 | + tool_result_free(&r); | |
| 707 | + return 0; | |
| 708 | + } | |
| 709 | + | |
| 710 | + if (strcmp(action, "info") == 0) { api_info(); return 0; } | |
| 711 | + | |
| 712 | + if (strcmp(action, "policy") == 0) { | |
| 713 | + char val[16] = ""; | |
| 714 | + json_headers(); | |
| 715 | + if ((qs && *qs && get_query_val(qs, "allow_private", val, sizeof val)) || | |
| 716 | + (body && json_str_field(body, "allow_private", val, sizeof val))) { | |
| 717 | + int on = (strcmp(val, "1") == 0 || strcmp(val, "true") == 0); | |
| 718 | + if (!policy_set_allow_private(on)) { | |
| 719 | + fputs("{\"ok\":false,\"error\":\"policy_write_failed\"}\n", stdout); | |
| 720 | + return 0; | |
| 721 | + } | |
| 722 | + fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", | |
| 723 | + on ? "true" : "false"); | |
| 724 | + } else { | |
| 725 | + fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", | |
| 726 | + policy_read_allow_private() ? "true" : "false"); | |
| 727 | + } | |
| 728 | + return 0; | |
| 729 | + } | |
| 730 | + | |
| 731 | + json_headers(); | |
| 732 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | |
| 733 | + return 0; | |
| 734 | +} | |
| 735 | + | |
| 736 | +/* ------------------------------------------------------------------ */ | |
| 737 | +/* main */ | |
| 738 | +/* ------------------------------------------------------------------ */ | |
| 739 | + | |
| 740 | +int main(int argc, char **argv) | |
| 741 | +{ | |
| 742 | + const char *qs; | |
| 743 | + char action[64] = ""; | |
| 744 | + char *body = NULL; | |
| 745 | + int have_action = 0; | |
| 746 | + | |
| 747 | +#if defined(_WIN32) | |
| 748 | + { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI | |
| 749 | + * framing — force binary stdio. */ | |
| 750 | + int mode = _O_BINARY; | |
| 751 | + _setmode(_fileno(stdout), mode); | |
| 752 | + _setmode(_fileno(stdin), mode); | |
| 753 | + } | |
| 754 | + { | |
| 755 | + WSADATA wsa; | |
| 756 | + WSAStartup(MAKEWORD(2, 2), &wsa); | |
| 757 | + } | |
| 758 | +#endif | |
| 759 | + | |
| 760 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) | |
| 761 | + return run_meta(); | |
| 762 | + if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); | |
| 763 | + if (argc > 1 && strcmp(argv[1], "--schema") == 0) { | |
| 764 | + puts(FETCH_TOOL_SCHEMA); | |
| 765 | + return 0; | |
| 766 | + } | |
| 767 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | |
| 768 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 769 | + return 0; | |
| 770 | + } | |
| 771 | + /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line, reading stdin | |
| 772 | + * when no addresses are given. Pure policy, no DNS and no sockets, so the | |
| 773 | + * suite can assert the whole SSRF matrix (including the IPv6 special | |
| 774 | + * ranges) on a machine with no network at all. */ | |
| 775 | + /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line. With no | |
| 776 | + * address arguments it reads them from stdin instead. Pure policy: no DNS | |
| 777 | + * and no sockets, so the suite can assert the whole SSRF matrix | |
| 778 | + * (including the IPv6 special ranges) on a machine with no network at | |
| 779 | + * all, and a named-address call never waits on a terminal. */ | |
| 780 | + if (argc > 1 && strcmp(argv[1], "--selftest") == 0) { | |
| 781 | + char line[256]; | |
| 782 | + int i; | |
| 783 | + setvbuf(stdout, NULL, _IOLBF, 0); | |
| 784 | + if (argc > 2) { | |
| 785 | + for (i = 2; i < argc; i++) | |
| 786 | + printf("%s denied=%d\n", argv[i], fx_ip_is_denied(argv[i]) ? 1 : 0); | |
| 787 | + return 0; | |
| 788 | + } | |
| 789 | + while (fgets(line, sizeof line, stdin)) { | |
| 790 | + char *p = line, *e; | |
| 791 | + while (*p == ' ' || *p == '\t') p++; | |
| 792 | + e = p + strlen(p); | |
| 793 | + while (e > p && (e[-1] == '\n' || e[-1] == '\r' || | |
| 794 | + e[-1] == ' ' || e[-1] == '\t')) *--e = '\0'; | |
| 795 | + if (*p == '#') continue; /* comment line */ | |
| 796 | + printf("%s denied=%d\n", p, fx_ip_is_denied(p) ? 1 : 0); | |
| 797 | + } | |
| 798 | + return 0; | |
| 799 | + } | |
| 800 | + qs = getenv("QUERY_STRING"); | |
| 801 | + if (!qs) qs = ""; | |
| 802 | + | |
| 803 | + have_action = get_query_val(qs, "action", action, sizeof action); | |
| 804 | + { | |
| 805 | + /* ?format=json is the other documented way to ask for the JSON API. | |
| 806 | + * Match it as a whole parameter with an exact value, never as a raw | |
| 807 | + * substring, so a url= parameter that merely contains the text | |
| 808 | + * "format=json" cannot flip the page into the API. */ | |
| 809 | + char fmt[24] = ""; | |
| 810 | + if (!have_action && get_query_val(qs, "format", fmt, sizeof fmt) && | |
| 811 | + strcmp(fmt, "json") == 0) { | |
| 812 | + snprintf(action, sizeof action, "fetch"); | |
| 813 | + have_action = 1; | |
| 814 | + } | |
| 815 | + } | |
| 816 | + | |
| 817 | + { | |
| 818 | + const char *rm = getenv("REQUEST_METHOD"); | |
| 819 | + int is_post = rm && strcmp(rm, "POST") == 0; | |
| 820 | + if (have_action || is_post) { | |
| 821 | + require_node_auth(); | |
| 822 | + body = read_body(); | |
| 823 | + if (body) { | |
| 824 | + char jact[64] = ""; | |
| 825 | + if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) | |
| 826 | + snprintf(action, sizeof action, "%s", jact); | |
| 827 | + else if (!action[0]) | |
| 828 | + snprintf(action, sizeof action, "fetch"); | |
| 829 | + } else if (!action[0]) { | |
| 830 | + snprintf(action, sizeof action, "fetch"); | |
| 831 | + } | |
| 832 | + return api_dispatch(action, qs, body); | |
| 833 | + } | |
| 834 | + } | |
| 835 | + | |
| 836 | + /* HTML UI */ | |
| 837 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 838 | + "Cache-Control: no-store\r\n" | |
| 839 | + "X-Content-Type-Options: nosniff\r\n" | |
| 840 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 841 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 842 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 843 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 844 | + emit_ui(); | |
| 845 | + return 0; | |
| 846 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..12c0d94 | ||
| --- /dev/null | ||
| +++ b/src/sxbuf.c | ||
| @@ -0,0 +1,179 @@ | ||
| 1 | +/* | |
| 2 | + * sxbuf.c - growable buffer + shared small helpers for plugin_fetch. | |
| 3 | + */ | |
| 4 | +#include "sxbuf.h" | |
| 5 | + | |
| 6 | +#include <stdlib.h> | |
| 7 | +#include <string.h> | |
| 8 | +#include <ctype.h> | |
| 9 | +#include <stdarg.h> | |
| 10 | + | |
| 11 | +void *sx_malloc(size_t n) | |
| 12 | +{ | |
| 13 | + void *p = malloc(n ? n : 1); | |
| 14 | + if (!p) { | |
| 15 | + fputs("{\"ok\":false,\"error\":\"out of memory\"}\n", stdout); | |
| 16 | + exit(1); | |
| 17 | + } | |
| 18 | + return p; | |
| 19 | +} | |
| 20 | + | |
| 21 | +char *sx_strdup(const char *s) | |
| 22 | +{ | |
| 23 | + size_t n; | |
| 24 | + char *p; | |
| 25 | + if (!s) s = ""; | |
| 26 | + n = strlen(s) + 1; | |
| 27 | + p = (char *)sx_malloc(n); | |
| 28 | + memcpy(p, s, n); | |
| 29 | + return p; | |
| 30 | +} | |
| 31 | + | |
| 32 | +/* ASCII-only case folding. We deliberately do not call strcasecmp(): MinGW | |
| 33 | + * spells it _stricmp, glibc/musl declare it in <strings.h> behind a feature | |
| 34 | + * test, and an HTTP header name or a media type must fold the same way in | |
| 35 | + * every locale. */ | |
| 36 | +static int sx_fold(int c) | |
| 37 | +{ | |
| 38 | + return (c >= 'A' && c <= 'Z') ? c + 32 : c; | |
| 39 | +} | |
| 40 | + | |
| 41 | +int sx_strncasecmp(const char *a, const char *b, size_t n) | |
| 42 | +{ | |
| 43 | + size_t i; | |
| 44 | + for (i = 0; i < n; i++) { | |
| 45 | + int x = sx_fold((unsigned char)a[i]); | |
| 46 | + int y = sx_fold((unsigned char)b[i]); | |
| 47 | + if (x != y) return x - y; | |
| 48 | + if (!x) return 0; | |
| 49 | + } | |
| 50 | + return 0; | |
| 51 | +} | |
| 52 | + | |
| 53 | +int sx_strcasecmp(const char *a, const char *b) | |
| 54 | +{ | |
| 55 | + for (;; a++, b++) { | |
| 56 | + int x = sx_fold((unsigned char)*a); | |
| 57 | + int y = sx_fold((unsigned char)*b); | |
| 58 | + if (x != y) return x - y; | |
| 59 | + if (!x) return 0; | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +void buf_init(buf_t *b) | |
| 64 | +{ | |
| 65 | + b->p = NULL; | |
| 66 | + b->n = 0; | |
| 67 | + b->cap = 0; | |
| 68 | +} | |
| 69 | + | |
| 70 | +void buf_free(buf_t *b) | |
| 71 | +{ | |
| 72 | + free(b->p); | |
| 73 | + b->p = NULL; | |
| 74 | + b->n = b->cap = 0; | |
| 75 | +} | |
| 76 | + | |
| 77 | +static void buf_grow(buf_t *b, size_t need) | |
| 78 | +{ | |
| 79 | + size_t cap; | |
| 80 | + char *np; | |
| 81 | + if (b->cap >= need) return; | |
| 82 | + cap = b->cap ? b->cap : 256; | |
| 83 | + while (cap < need) cap *= 2; | |
| 84 | + np = (char *)realloc(b->p, cap); | |
| 85 | + if (!np) { | |
| 86 | + fputs("{\"ok\":false,\"error\":\"out of memory\"}\n", stdout); | |
| 87 | + exit(1); | |
| 88 | + } | |
| 89 | + b->p = np; | |
| 90 | + b->cap = cap; | |
| 91 | +} | |
| 92 | + | |
| 93 | +void buf_bput(buf_t *b, const char *s, size_t n) | |
| 94 | +{ | |
| 95 | + if (!s || !n) return; | |
| 96 | + buf_grow(b, b->n + n + 1); | |
| 97 | + memcpy(b->p + b->n, s, n); | |
| 98 | + b->n += n; | |
| 99 | + b->p[b->n] = '\0'; | |
| 100 | +} | |
| 101 | + | |
| 102 | +void buf_add(buf_t *b, const char *s) | |
| 103 | +{ | |
| 104 | + if (s) buf_bput(b, s, strlen(s)); | |
| 105 | +} | |
| 106 | + | |
| 107 | +void buf_addf(buf_t *b, const char *fmt, ...) | |
| 108 | +{ | |
| 109 | + va_list ap; | |
| 110 | + int need; | |
| 111 | + va_start(ap, fmt); | |
| 112 | + need = vsnprintf(NULL, 0, fmt, ap); | |
| 113 | + va_end(ap); | |
| 114 | + if (need <= 0) return; | |
| 115 | + buf_grow(b, b->n + (size_t)need + 1); | |
| 116 | + va_start(ap, fmt); | |
| 117 | + vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); | |
| 118 | + va_end(ap); | |
| 119 | + b->n += (size_t)need; | |
| 120 | +} | |
| 121 | + | |
| 122 | +void url_decode(char *s) | |
| 123 | +{ | |
| 124 | + char *o = s; | |
| 125 | + if (!s) return; | |
| 126 | + while (*s) { | |
| 127 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 128 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 129 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 130 | + *o++ = (char)((hi << 4) | lo); | |
| 131 | + s += 3; | |
| 132 | + } else if (*s == '+') { | |
| 133 | + *o++ = ' '; | |
| 134 | + s++; | |
| 135 | + } else { | |
| 136 | + *o++ = *s++; | |
| 137 | + } | |
| 138 | + } | |
| 139 | + *o = '\0'; | |
| 140 | +} | |
| 141 | + | |
| 142 | +int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 143 | +{ | |
| 144 | + size_t klen; | |
| 145 | + const char *p; | |
| 146 | + if (!qs || !key || !out || outsz == 0) return 0; | |
| 147 | + out[0] = '\0'; | |
| 148 | + klen = strlen(key); | |
| 149 | + p = qs; | |
| 150 | + while (*p) { | |
| 151 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 152 | + size_t i = 0; | |
| 153 | + p += klen + 1; | |
| 154 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | |
| 155 | + out[i] = '\0'; | |
| 156 | + url_decode(out); | |
| 157 | + return 1; | |
| 158 | + } | |
| 159 | + p = strchr(p, '&'); | |
| 160 | + if (!p) break; | |
| 161 | + p++; | |
| 162 | + } | |
| 163 | + return 0; | |
| 164 | +} | |
| 165 | + | |
| 166 | +void json_escape(FILE *out, const char *s) | |
| 167 | +{ | |
| 168 | + fputc('"', out); | |
| 169 | + for (; s && *s; s++) { | |
| 170 | + unsigned char c = (unsigned char)*s; | |
| 171 | + if (c == '"' || c == '\\') { fputc('\\', out); fputc(c, out); } | |
| 172 | + else if (c == '\n') fputs("\\n", out); | |
| 173 | + else if (c == '\r') fputs("\\r", out); | |
| 174 | + else if (c == '\t') fputs("\\t", out); | |
| 175 | + else if (c < 0x20) fprintf(out, "\\u%04x", c); | |
| 176 | + else fputc(c, out); | |
| 177 | + } | |
| 178 | + fputc('"', out); | |
| 179 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..cec0ed0 | ||
| --- /dev/null | ||
| +++ b/src/sxbuf.h | ||
| @@ -0,0 +1,37 @@ | ||
| 1 | +/* | |
| 2 | + * sxbuf.h - shared growable buffer + tiny string helpers used by every | |
| 3 | + * module of plugin_fetch. Implementation in sxbuf.c. | |
| 4 | + */ | |
| 5 | +#ifndef SX_FETCH_BUF_H | |
| 6 | +#define SX_FETCH_BUF_H | |
| 7 | + | |
| 8 | +#include <stddef.h> | |
| 9 | +#include <stdio.h> | |
| 10 | + | |
| 11 | +typedef struct { | |
| 12 | + char *p; | |
| 13 | + size_t n; | |
| 14 | + size_t cap; | |
| 15 | +} buf_t; | |
| 16 | + | |
| 17 | +void buf_init(buf_t *b); | |
| 18 | +void buf_free(buf_t *b); | |
| 19 | +void buf_add(buf_t *b, const char *s); | |
| 20 | +void buf_bput(buf_t *b, const char *s, size_t n); | |
| 21 | +void buf_addf(buf_t *b, const char *fmt, ...); | |
| 22 | + | |
| 23 | +void *sx_malloc(size_t n); | |
| 24 | +char *sx_strdup(const char *s); | |
| 25 | + | |
| 26 | +void url_decode(char *s); | |
| 27 | +int get_query_val(const char *qs, const char *key, char *out, size_t outsz); | |
| 28 | +void json_escape(FILE *out, const char *s); | |
| 29 | + | |
| 30 | +/* Case-insensitive compare with no platform dependency: MinGW spells these | |
| 31 | + * _stricmp, glibc/musl hide them behind <strings.h>, and we only ever need | |
| 32 | + * these two. ASCII only, locale-independent (which is what an HTTP header | |
| 33 | + * name and a content-type want anyway). Implementation in sxbuf.c. */ | |
| 34 | +int sx_strncasecmp(const char *a, const char *b, size_t n); | |
| 35 | +int sx_strcasecmp(const char *a, const char *b); | |
| 36 | + | |
| 37 | +#endif /* SX_FETCH_BUF_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..0f21bb7 | ||
| --- /dev/null | ||
| +++ b/src/sxmcp.h | ||
| @@ -0,0 +1,35 @@ | ||
| 1 | +/* | |
| 2 | + * sxmcp.h - the MCP stdio server loop, implemented in plugin_fetch.c. | |
| 3 | + */ | |
| 4 | +#ifndef SX_FETCH_MCP_H | |
| 5 | +#define SX_FETCH_MCP_H | |
| 6 | + | |
| 7 | +#include "yyjson.h" | |
| 8 | +#include "sxbuf.h" | |
| 9 | + | |
| 10 | +/* MCP JSON-RPC 2.0 loop over stdin/stdout. Returns exit code. */ | |
| 11 | +int run_mcp(void); | |
| 12 | + | |
| 13 | +/* Tool implementation shared by --mcp and the CGI API. | |
| 14 | + * Fills `out` with model-facing text formatted like the upstream fetch | |
| 15 | + * server's tool result. Returns with out->ok set. */ | |
| 16 | +typedef struct { | |
| 17 | + int ok; | |
| 18 | + char error[1200]; | |
| 19 | + char *text; /* heap */ | |
| 20 | + size_t text_len; | |
| 21 | + int status; | |
| 22 | + char content_type[128]; | |
| 23 | + size_t bytes_read; | |
| 24 | + size_t content_len; /* length of the converted content before chunking */ | |
| 25 | + char final_url[1024]; | |
| 26 | + char title[256]; | |
| 27 | + int redirected; | |
| 28 | + char *raw_html; /* heap: original body, capped, for the UI Raw tab */ | |
| 29 | +} tool_result; | |
| 30 | + | |
| 31 | +void fetch_tool_run(const char *url, long max_length, long start_index, int raw, | |
| 32 | + tool_result *out); | |
| 33 | +void tool_result_free(tool_result *r); | |
| 34 | + | |
| 35 | +#endif /* SX_FETCH_MCP_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..b2e52d7 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,223 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 6 | +<title>fetch - URL to Markdown</title> | |
| 7 | +<!--TOKENS--> | |
| 8 | +<style> | |
| 9 | +*{box-sizing:border-box} | |
| 10 | +body{margin:0;padding:16px;background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5} | |
| 11 | +.wrap{max-width:1080px;margin:0 auto} | |
| 12 | +h1{font-size:18px;margin:0 0 4px;font-weight:700} | |
| 13 | +.sub{color:var(--text-2);font-size:12.5px;margin-bottom:16px} | |
| 14 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:14px} | |
| 15 | +.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center} | |
| 16 | +input[type=text]{flex:1 1 320px;min-width:200px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px} | |
| 17 | +input[type=number]{width:110px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px} | |
| 18 | +label.chk{display:flex;align-items:center;gap:6px;color:var(--text-2);font-size:12.5px;user-select:none} | |
| 19 | +button{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;font-weight:600;cursor:pointer;font-size:13px} | |
| 20 | +button.sec{background:transparent;color:var(--blue);border:1px solid var(--line)} | |
| 21 | +button:disabled{opacity:.5;cursor:default} | |
| 22 | +.lbl{color:var(--text-2);font-size:12px;margin-right:2px} | |
| 23 | +.pill{display:inline-block;padding:2px 10px;border-radius:980px;font-size:11.5px;font-weight:600;border:1px solid var(--line);color:var(--text-2)} | |
| 24 | +.pill.ok{color:var(--green);border-color:var(--green)} | |
| 25 | +.pill.warn{color:var(--orange);border-color:var(--orange)} | |
| 26 | +.pill.bad{color:var(--red);border-color:var(--red)} | |
| 27 | +.meta{display:flex;gap:14px;flex-wrap:wrap;color:var(--text-2);font-size:12px;margin:8px 0} | |
| 28 | +.meta b{color:var(--text);font-weight:600;font-family:var(--mono)} | |
| 29 | +pre.out{background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;overflow:auto;max-height:560px;white-space:pre-wrap;word-break:break-word;font-family:var(--mono);font-size:12px;margin:0} | |
| 30 | +.tabs{display:flex;gap:6px;margin-bottom:10px} | |
| 31 | +.tab{padding:5px 14px;border-radius:980px;border:1px solid var(--line);background:transparent;color:var(--text-2);cursor:pointer;font-size:12.5px;font-weight:600} | |
| 32 | +.tab.on{background:var(--blue);border-color:var(--blue);color:#fff} | |
| 33 | +.pager{display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap} | |
| 34 | +.small{font-size:11.5px;color:var(--text-2)} | |
| 35 | +.err{color:var(--red)} | |
| 36 | +.grid{display:grid;grid-template-columns:1fr 1fr;gap:14px} | |
| 37 | +@media(max-width:860px){.grid{grid-template-columns:1fr}} | |
| 38 | +.pol{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-2)} | |
| 39 | +h1 .tag{font-size:11px;color:var(--text-2);font-weight:500;margin-left:6px} | |
| 40 | +html.embedded .embed-hide{display:none} | |
| 41 | +</style> | |
| 42 | +</head> | |
| 43 | +<body> | |
| 44 | +<div class="wrap"> | |
| 45 | + <div class="embed-hide" style="margin-bottom:10px;display:flex;gap:10px;align-items:center;justify-content:space-between"> | |
| 46 | + <a href="/" style="color:var(--blue);text-decoration:none;font-weight:600">← Back to Bot</a> | |
| 47 | + <button class="sec" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | |
| 48 | + </div> | |
| 49 | + <h1>fetch<span class="tag">URL to Markdown · MCP connector</span></h1> | |
| 50 | + <div class="sub">Preview the <b>fetch</b> tool exactly as an agent sees it. Private, loopback and link-local targets are refused unless the operator allows them. TLS certificates are always verified.</div> | |
| 51 | + | |
| 52 | + <div class="card"> | |
| 53 | + <div class="row"> | |
| 54 | + <input type="text" id="url" placeholder="https://example.com/article" spellcheck="false" autocomplete="off"> | |
| 55 | + <button id="go" onclick="doFetch()">Fetch</button> | |
| 56 | + </div> | |
| 57 | + <div class="row" style="margin-top:10px"> | |
| 58 | + <span class="lbl">max_length</span><input type="number" id="maxlen" value="5000" min="1" max="100000" step="1000"> | |
| 59 | + <span class="lbl">start_index</span><input type="number" id="start" value="0" min="0" step="1"> | |
| 60 | + <label class="chk"><input type="checkbox" id="raw"> raw (keep HTML)</label> | |
| 61 | + <span class="small">redirects are followed up to 5 hops, each hop re-checked</span> | |
| 62 | + </div> | |
| 63 | + <div class="row" style="margin-top:10px"> | |
| 64 | + <div class="pol"> | |
| 65 | + <label class="chk"><input type="checkbox" id="allowpriv"> allow private/loopback (operator policy)</label> | |
| 66 | + <span class="small">saved on the node</span> | |
| 67 | + </div> | |
| 68 | + </div> | |
| 69 | + </div> | |
| 70 | + | |
| 71 | + <div class="card"> | |
| 72 | + <div class="row" style="justify-content:space-between"> | |
| 73 | + <div class="tabs" style="margin:0"> | |
| 74 | + <button class="tab on" id="tabmd" onclick="setTab('md')">Markdown</button> | |
| 75 | + <button class="tab" id="tabraw" onclick="setTab('raw')">Raw HTML</button> | |
| 76 | + </div> | |
| 77 | + <div id="status"><span class="pill">idle</span></div> | |
| 78 | + </div> | |
| 79 | + <div class="meta" id="meta" style="display:none"> | |
| 80 | + <span>status <b id="mStatus">-</b></span> | |
| 81 | + <span>type <b id="mType">-</b></span> | |
| 82 | + <span>bytes <b id="mBytes">-</b></span> | |
| 83 | + <span>content <b id="mLen">-</b></span> | |
| 84 | + <span id="mRedirWrap">redirected <b id="mRedir">-</b></span> | |
| 85 | + </div> | |
| 86 | + <div id="mTitle" class="small" style="margin-bottom:6px"></div> | |
| 87 | + <pre class="out" id="out">Enter a URL and press Fetch.</pre> | |
| 88 | + <div class="pager" id="pager" style="display:none"> | |
| 89 | + <button class="sec" onclick="prevChunk()">← Prev</button> | |
| 90 | + <span class="small" id="pageInfo"></span> | |
| 91 | + <button class="sec" onclick="nextChunk()">Next →</button> | |
| 92 | + <button class="sec" onclick="copyOut()">Copy visible</button> | |
| 93 | + </div> | |
| 94 | + </div> | |
| 95 | + | |
| 96 | + <div class="card"> | |
| 97 | + <div class="small" style="font-weight:600;color:var(--text);margin-bottom:6px">MCP tool (stdio <code>--mcp</code>)</div> | |
| 98 | + <pre class="out" style="max-height:180px" id="schema">loading...</pre> | |
| 99 | + <div class="small" style="margin-top:8px">Register through <b>sx-connector-mcp</b>: the router exposes it as <code>connector_call</code> → <code>fetch</code>. Args: <code>url</code> (required), <code>max_length</code> (default 5000, cap 100000), <code>start_index</code> (default 0), <code>raw</code> (default false).</div> | |
| 100 | + </div> | |
| 101 | +</div> | |
| 102 | +<script> | |
| 103 | +var q=new URLSearchParams(location.search); | |
| 104 | +var HUB=q.get('plugin')||''; | |
| 105 | +var node=q.get('node')||''; | |
| 106 | +var sid=q.get('id')||''; | |
| 107 | +var pwd=q.get('pwd')||localStorage.getItem('bot_active_pwd')||''; | |
| 108 | +var PAGE=5000; | |
| 109 | +var lastContentLen=0; | |
| 110 | + | |
| 111 | +function api(action,arg){ | |
| 112 | + var parts=[]; | |
| 113 | + for(var k in arg) parts.push(encodeURIComponent(k)+'='+encodeURIComponent(arg[k])); | |
| 114 | + var qs='action='+encodeURIComponent(action)+(parts.length?'&'+parts.join('&'):'') | |
| 115 | + +(node?'&node='+encodeURIComponent(node):'')+(sid?'&id='+encodeURIComponent(sid):'') | |
| 116 | + +(pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 117 | + var u=HUB?('/plugins?plugin='+encodeURIComponent(HUB)+'&'+qs) | |
| 118 | + :('/plugin_fetch?'+qs); | |
| 119 | + var hdr=pwd?{'X-Bot-Password':pwd}:{}; | |
| 120 | + return fetch(u,{headers:hdr}).then(function(r){ | |
| 121 | + return r.json().then(function(d){ | |
| 122 | + if(!r.ok&&!d.ok){d.error=(d.error||'request rejected')+' (http '+r.status+')';} | |
| 123 | + return d; | |
| 124 | + }); | |
| 125 | + }); | |
| 126 | +} | |
| 127 | + | |
| 128 | +function setTab(t){ | |
| 129 | + document.getElementById('tabmd').classList.toggle('on',t==='md'); | |
| 130 | + document.getElementById('tabraw').classList.toggle('on',t==='raw'); | |
| 131 | + render(); | |
| 132 | +} | |
| 133 | +function pill(cls,txt){document.getElementById('status').innerHTML='<span class="pill '+cls+'">'+txt+'</span>';} | |
| 134 | + | |
| 135 | +var lastRaw='',lastMD=''; | |
| 136 | +function render(){ | |
| 137 | + var raw=document.getElementById('raw').checked; | |
| 138 | + var show=(document.getElementById('tabraw').classList.contains('on')||raw)?lastRaw:lastMD; | |
| 139 | + document.getElementById('out').textContent=show||'(empty)'; | |
| 140 | +} | |
| 141 | + | |
| 142 | +function doFetch(){ | |
| 143 | + var url=document.getElementById('url').value.trim(); | |
| 144 | + var ml=parseInt(document.getElementById('maxlen').value||'5000',10); | |
| 145 | + var si=parseInt(document.getElementById('start').value||'0',10); | |
| 146 | + var raw=document.getElementById('raw').checked; | |
| 147 | + if(!url){pill('bad','enter a URL');return;} | |
| 148 | + pill('','fetching...'); | |
| 149 | + document.getElementById('go').disabled=true; | |
| 150 | + api('fetch',{url:url,max_length:ml,start_index:si,raw:raw?'true':'false'}) | |
| 151 | + .then(function(d){ | |
| 152 | + document.getElementById('go').disabled=false; | |
| 153 | + if(!d.ok){pill('bad','failed'); | |
| 154 | + document.getElementById('out').textContent=d.error||'fetch failed'; | |
| 155 | + document.getElementById('meta').style.display='none'; | |
| 156 | + document.getElementById('pager').style.display='none'; | |
| 157 | + lastRaw='';lastMD=''; | |
| 158 | + return;} | |
| 159 | + pill(d.status_code>=400?'bad':'ok','HTTP '+d.status_code); | |
| 160 | + lastMD=d.text||''; | |
| 161 | + lastRaw=d.raw_html||''; | |
| 162 | + lastContentLen=d.content_length||0; | |
| 163 | + document.getElementById('meta').style.display='flex'; | |
| 164 | + document.getElementById('mStatus').textContent=d.status_code; | |
| 165 | + document.getElementById('mType').textContent=d.content_type||'-'; | |
| 166 | + document.getElementById('mBytes').textContent=d.bytes_read; | |
| 167 | + document.getElementById('mLen').textContent=d.content_length; | |
| 168 | + document.getElementById('mRedir').textContent=d.redirected?'yes':'no'; | |
| 169 | + document.getElementById('mTitle').textContent=d.title?('title: '+d.title):''; | |
| 170 | + PAGE=Math.max(500,Math.min(100000,ml||5000)); | |
| 171 | + document.getElementById('pager').style.display=(lastContentLen>(si+PAGE))?'flex':'none'; | |
| 172 | + render(); | |
| 173 | + }) | |
| 174 | + .catch(function(e){ | |
| 175 | + document.getElementById('go').disabled=false; | |
| 176 | + pill('bad','error'); | |
| 177 | + document.getElementById('out').textContent='Error: '+e; | |
| 178 | + }); | |
| 179 | +} | |
| 180 | + | |
| 181 | +function chunk(){return parseInt(document.getElementById('start').value||'0',10);} | |
| 182 | +function setChunk(v){ | |
| 183 | + v=Math.max(0,v); | |
| 184 | + document.getElementById('start').value=v; | |
| 185 | + doFetch(); | |
| 186 | +} | |
| 187 | +function nextChunk(){setChunk(chunk()+PAGE);} | |
| 188 | +function prevChunk(){setChunk(chunk()-PAGE);} | |
| 189 | + | |
| 190 | +function copyOut(){ | |
| 191 | + var t=document.getElementById('out').textContent; | |
| 192 | + if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(t); | |
| 193 | +} | |
| 194 | + | |
| 195 | +function loadPolicy(){ | |
| 196 | + api('policy',{}).then(function(d){ | |
| 197 | + if(d&&d.ok)document.getElementById('allowpriv').checked=!!d.allow_private; | |
| 198 | + }).catch(function(){}); | |
| 199 | +} | |
| 200 | +document.getElementById('allowpriv').addEventListener('change',function(ev){ | |
| 201 | + api('policy',{allow_private:ev.target.checked?'true':'false'}).catch(function(){}); | |
| 202 | +}); | |
| 203 | + | |
| 204 | +function loadSchema(){ | |
| 205 | + api('info',{}).then(function(d){ | |
| 206 | + if(d&&d.tool_schema) | |
| 207 | + document.getElementById('schema').textContent=JSON.stringify(d.tool_schema,null,2); | |
| 208 | + else document.getElementById('schema').textContent='(unavailable)'; | |
| 209 | + if(d&&typeof d.allow_private==='boolean') | |
| 210 | + document.getElementById('allowpriv').checked=d.allow_private; | |
| 211 | + }).catch(function(){document.getElementById('schema').textContent='(unavailable)';}); | |
| 212 | +} | |
| 213 | + | |
| 214 | +document.getElementById('url').addEventListener('keydown',function(e){ | |
| 215 | + if(e.key==='Enter')doFetch(); | |
| 216 | +}); | |
| 217 | +if(q.get('url'))document.getElementById('url').value=q.get('url'); | |
| 218 | +loadPolicy(); | |
| 219 | +loadSchema(); | |
| 220 | +if(q.get('url')&&q.get('autofetch'))doFetch(); | |
| 221 | +</script> | |
| 222 | +</body> | |
| 223 | +</html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..8d533df | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,231 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_FETCH_UI_HTML_H | |
| 3 | +#define SX_FETCH_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\">\n" | |
| 8 | + "<head>\n" | |
| 9 | + "<meta charset=\"utf-8\">\n" | |
| 10 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 11 | + "<title>fetch - URL to Markdown</title>\n" | |
| 12 | + "\001\n" | |
| 13 | + "<style>\n" | |
| 14 | + "*{box-sizing:border-box}\n" | |
| 15 | + "body{margin:0;padding:16px;background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5}\n" | |
| 16 | + ".wrap{max-width:1080px;margin:0 auto}\n" | |
| 17 | + "h1{font-size:18px;margin:0 0 4px;font-weight:700}\n" | |
| 18 | + ".sub{color:var(--text-2);font-size:12.5px;margin-bottom:16px}\n" | |
| 19 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:14px}\n" | |
| 20 | + ".row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}\n" | |
| 21 | + "input[type=text]{flex:1 1 320px;min-width:200px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px}\n" | |
| 22 | + "input[type=number]{width:110px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px}\n" | |
| 23 | + "label.chk{display:flex;align-items:center;gap:6px;color:var(--text-2);font-size:12.5px;user-select:none}\n" | |
| 24 | + "button{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;font-weight:600;cursor:pointer;font-size:13px}\n" | |
| 25 | + "button.sec{background:transparent;color:var(--blue);border:1px solid var(--line)}\n" | |
| 26 | + "button:disabled{opacity:.5;cursor:default}\n" | |
| 27 | + ".lbl{color:var(--text-2);font-size:12px;margin-right:2px}\n" | |
| 28 | + ".pill{display:inline-block;padding:2px 10px;border-radius:980px;font-size:11.5px;font-weight:600;border:1px solid var(--line);color:var(--text-2)}\n" | |
| 29 | + ".pill.ok{color:var(--green);border-color:var(--green)}\n" | |
| 30 | + ".pill.warn{color:var(--orange);border-color:var(--orange)}\n" | |
| 31 | + ".pill.bad{color:var(--red);border-color:var(--red)}\n" | |
| 32 | + ".meta{display:flex;gap:14px;flex-wrap:wrap;color:var(--text-2);font-size:12px;margin:8px 0}\n" | |
| 33 | + ".meta b{color:var(--text);font-weight:600;font-family:var(--mono)}\n" | |
| 34 | + "pre.out{background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;overflow:auto;max-height:560px;white-space:pre-wrap;word-break:break-word;font-family:var(--mono);font-size:12px;margin:0}\n" | |
| 35 | + ".tabs{display:flex;gap:6px;margin-bottom:10px}\n" | |
| 36 | + ".tab{padding:5px 14px;border-radius:980px;border:1px solid var(--line);background:transparent;color:var(--text-2);cursor:pointer;font-size:12.5px;font-weight:600}\n" | |
| 37 | + ".tab.on{background:var(--blue);border-color:var(--blue);color:#fff}\n" | |
| 38 | + ".pager{display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap}\n" | |
| 39 | + ".small{font-size:11.5px;color:var(--text-2)}\n" | |
| 40 | + ".err{color:var(--red)}\n" | |
| 41 | + ".grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}\n" | |
| 42 | + "@media(max-width:860px){.grid{grid-template-columns:1fr}}\n" | |
| 43 | + ".pol{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-2)}\n" | |
| 44 | + "h1 .tag{font-size:11px;color:var(--text-2);font-weight:500;margin-left:6px}\n" | |
| 45 | + "html.embedded .embed-hide{display:none}\n" | |
| 46 | + "</style>\n" | |
| 47 | + "</head>\n" | |
| 48 | + "<body>\n" | |
| 49 | + "<div class=\"wrap\">\n" | |
| 50 | + " <div class=\"embed-hide\" style=\"margin-bottom:10px;display:flex;gap:10px;align-items:center;justify-content:space-between\">\n" | |
| 51 | + " <a href=\"/\" style=\"color:var(--blue);text-decoration:none;font-weight:600\">← Back to Bot</a>\n" | |
| 52 | + " <button class=\"sec\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | |
| 53 | + " </div>\n" | |
| 54 | + " <h1>fetch<span class=\"tag\">URL to Markdown · MCP connector</span></h1>\n" | |
| 55 | + " <div class=\"sub\">Preview the <b>fetch</b> tool exactly as an agent sees it. Private, loopback and link-local targets are refused unless the operator allows them. TLS certificates are always verified.</div>\n" | |
| 56 | + "\n" | |
| 57 | + " <div class=\"card\">\n" | |
| 58 | + " <div class=\"row\">\n" | |
| 59 | + " <input type=\"text\" id=\"url\" placeholder=\"https://example.com/article\" spellcheck=\"false\" autocomplete=\"off\">\n" | |
| 60 | + " <button id=\"go\" onclick=\"doFetch()\">Fetch</button>\n" | |
| 61 | + " </div>\n" | |
| 62 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | |
| 63 | + " <span class=\"lbl\">max_length</span><input type=\"number\" id=\"maxlen\" value=\"5000\" min=\"1\" max=\"100000\" step=\"1000\">\n" | |
| 64 | + " <span class=\"lbl\">start_index</span><input type=\"number\" id=\"start\" value=\"0\" min=\"0\" step=\"1\">\n" | |
| 65 | + " <label class=\"chk\"><input type=\"checkbox\" id=\"raw\"> raw (keep HTML)</label>\n" | |
| 66 | + " <span class=\"small\">redirects are followed up to 5 hops, each hop re-checked</sp |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..d2681cd | index 0000000..d2681cd | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,19 @@ | @@ -0,0 +1,19 @@ | ||
| 1 | +# build artefacts | ||
| 2 | +plugin_fetch | ||
| 3 | +plugin_fetch.exe | ||
| 4 | +plugin_fetch.musl | ||
| 5 | +plugin_fetch.arm64 | ||
| 6 | +plugin_fetch-asan | ||
| 7 | +plugin_fetch-fortify | ||
| 8 | +plugin_fetch-zlib | ||
| 9 | +plugin_fetch.asan | ||
| 10 | +*.o | ||
| 11 | +bin/ | ||
| 12 | + | ||
| 13 | +# local scratch | ||
| 14 | +*.tmp | ||
| 15 | +*.log | ||
| 16 | + | ||
| 17 | +# python tooling | ||
| 18 | +__pycache__/ | ||
| 19 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a5f77e5 | index 0000000..a5f77e5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,33 @@ | @@ -0,0 +1,33 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. | ||
| 22 | + | ||
| 23 | +--- | ||
| 24 | + | ||
| 25 | +This plugin vendors third-party sources under `vendor/`: | ||
| 26 | + | ||
| 27 | +* **yyjson** (MIT) — `vendor/yyjson.{c,h}`, upstream `ibireme/yyjson`. | ||
| 28 | + Its MIT text is reproduced in `vendor/LICENSE.yyjson.txt`. | ||
| 29 | +* **mbedTLS 3.6.7** (Apache-2.0 OR GPL-2.0-or-later) — `vendor/mbedtlslib/` | ||
| 30 | + with the public headers flattened into `vendor/mbedtls/` and `vendor/psa/`, | ||
| 31 | + upstream `Mbed-TLS/mbedtls`. Its Apache-2.0 text is reproduced in | ||
| 32 | + `vendor/LICENSE.mbedtls.txt`. On `_WIN32` the HTTP and TLS legs go through | ||
| 33 | + WinHTTP instead, so no mbedTLS code is reached in the Windows artefact. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c2eb53a | index 0000000..c2eb53a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,142 @@ | @@ -0,0 +1,142 @@ | ||
| 1 | +# plugin_fetch - SCORPIOX BOT open-source URL fetch & HTML-to-Markdown MCP connector | ||
| 2 | +# | ||
| 3 | +# Zero runtime dependencies on every artefact. The only third-party C in the | ||
| 4 | +# tree is vendored under vendor/: yyjson (MIT) and the mbedTLS 3.6.7 library | ||
| 5 | +# (Apache-2.0) whose sources sit in vendor/mbedtlslib with their public | ||
| 6 | +# headers flattened into vendor/mbedtls and vendor/psa. On _WIN32 the HTTP and | ||
| 7 | +# TLS legs are WinHTTP instead, so the static PE needs no extra DLLs and no | ||
| 8 | +# crypto objects are reached. | ||
| 9 | +# | ||
| 10 | +# The multi-arch dist publish lives in scorpiox-cli-botplugin (it owns the | ||
| 11 | +# musl / aarch64 / MinGW / macOS toolchains, the dist upload and the plugingit | ||
| 12 | +# mirror) - see release-dist.sh. That tool compiles every src/**/*.c and | ||
| 13 | +# vendor/**/*.c with -I src and -I vendor, which is exactly what `make native` | ||
| 14 | +# reproduces here. | ||
| 15 | +# | ||
| 16 | +# Targets: | ||
| 17 | +# make native build -> ./plugin_fetch | ||
| 18 | +# make musl static musl x86_64 -> ./plugin_fetch.musl | ||
| 19 | +# make arm64 static arm64 musl -> ./plugin_fetch.arm64 | ||
| 20 | +# make win64 MinGW-w64 static -> ./plugin_fetch.exe | ||
| 21 | +# make macos Apple clang -> ./plugin_fetch (run this on macOS) | ||
| 22 | +# make asan ASan + UBSan + leaks -> ./plugin_fetch-asan | ||
| 23 | +# make fortify -D_FORTIFY_SOURCE=2 -> ./plugin_fetch-fortify | ||
| 24 | +# make zlib native build with gzip support (-DHAVE_ZLIB -lz) | ||
| 25 | +# make objs the cached mbedTLS object set (fast incremental dev builds) | ||
| 26 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 27 | +# make test build + run tests/run.sh | ||
| 28 | +# make e2e build + run tests/e2e.py (Playwright) | ||
| 29 | +# make clean | ||
| 30 | + | ||
| 31 | +CC ?= cc | ||
| 32 | +WARN := -Wall -Wextra -Wno-overlength-strings | ||
| 33 | +STD := -std=c99 | ||
| 34 | +INCLUDES := -I src -I vendor -I vendor/mbedtlslib | ||
| 35 | +CFLAGS ?= -O2 $(STD) $(WARN) $(INCLUDES) | ||
| 36 | +LDFLAGS ?= | ||
| 37 | +MUSL_CC ?= musl-gcc | ||
| 38 | +MUSL_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 39 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 40 | +ARM_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 41 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 42 | +WIN_CFLAGS := -O2 $(STD) $(WARN) $(INCLUDES) -static | ||
| 43 | +WIN_LIBS := -lwinhttp -lws2_32 -lbcrypt -lcrypt32 | ||
| 44 | + | ||
| 45 | +SRC_C := $(wildcard src/*.c) | ||
| 46 | +VENDOR_C := $(wildcard vendor/*.c) $(wildcard vendor/mbedtlslib/*.c) | ||
| 47 | +UI_SRC := src/ui.html | ||
| 48 | +UI_HDR := src/ui_html.h | ||
| 49 | +BIN := plugin_fetch | ||
| 50 | +EXE := plugin_fetch.exe | ||
| 51 | +OBJS := /tmp/fetch-objs | ||
| 52 | + | ||
| 53 | +.PHONY: all native musl arm64 win64 macos asan fortify zlib objs ui test e2e clean help | ||
| 54 | + | ||
| 55 | +all: native | ||
| 56 | + | ||
| 57 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 58 | + @echo "==> regenerating $(UI_HDR)" | ||
| 59 | + python3 tools/gen_ui.py | ||
| 60 | + | ||
| 61 | +ui: $(UI_HDR) | ||
| 62 | + | ||
| 63 | +native: $(BIN) | ||
| 64 | + | ||
| 65 | +$(BIN): $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 66 | + @echo "==> native build ($(CC))" | ||
| 67 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC_C) $(VENDOR_C) $(LDFLAGS) | ||
| 68 | + | ||
| 69 | +# Static musl build - the universal Linux artefact (Alpine, Debian, Arch, Omarchy) | ||
| 70 | +musl: $(BIN).musl | ||
| 71 | + | ||
| 72 | +$(BIN).musl: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 73 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 74 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC_C) $(VENDOR_C) | ||
| 75 | + | ||
| 76 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 77 | +arm64: $(BIN).arm64 | ||
| 78 | + | ||
| 79 | +$(BIN).arm64: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 80 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 81 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC_C) $(VENDOR_C) | ||
| 82 | + | ||
| 83 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 84 | +win64: $(EXE) | ||
| 85 | + | ||
| 86 | +$(EXE): $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 87 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 88 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC_C) $(VENDOR_C) $(WIN_LIBS) | ||
| 89 | + | ||
| 90 | +# Apple clang build (run this on macOS; the CLI does it over ssh otherwise) | ||
| 91 | +macos: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 92 | + @echo "==> Apple clang build" | ||
| 93 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC_C) $(VENDOR_C) | ||
| 94 | + | ||
| 95 | +# Sanitizer build - tests/run.sh drives the whole surface through this binary | ||
| 96 | +asan: $(BIN)-asan | ||
| 97 | + | ||
| 98 | +$(BIN)-asan: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 99 | + @echo "==> ASan + UBSan build" | ||
| 100 | + $(CC) -O1 -g $(STD) $(WARN) $(INCLUDES) -fsanitize=address,undefined \ | ||
| 101 | + -fno-omit-frame-pointer -o $(BIN)-asan $(SRC_C) $(VENDOR_C) | ||
| 102 | + | ||
| 103 | +fortify: $(BIN)-fortify | ||
| 104 | + | ||
| 105 | +$(BIN)-fortify: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 106 | + @echo "==> _FORTIFY_SOURCE=2 build" | ||
| 107 | + $(CC) -O2 $(STD) $(WARN) $(INCLUDES) -D_FORTIFY_SOURCE=2 \ | ||
| 108 | + -o $(BIN)-fortify $(SRC_C) $(VENDOR_C) | ||
| 109 | + | ||
| 110 | +# Optional gzip support. The published artefacts deliberately do NOT link it | ||
| 111 | +# (a plugin must stay standalone); this target exists so the suite can prove | ||
| 112 | +# the decoding path works when the library happens to be present. | ||
| 113 | +zlib: $(SRC_C) $(UI_HDR) $(VENDOR_C) | ||
| 114 | + @echo "==> native build with gzip support" | ||
| 115 | + $(CC) $(CFLAGS) -DHAVE_ZLIB -o $(BIN)-zlib $(SRC_C) $(VENDOR_C) -lz | ||
| 116 | + | ||
| 117 | +# Cached mbedTLS objects for the fast development loop (dev-build.sh uses them). | ||
| 118 | +objs: | ||
| 119 | + @mkdir -p $(OBJS) | ||
| 120 | + @ls $(VENDOR_C) | while read -r f; do \ | ||
| 121 | + o=$(OBJS)/$$(basename "$${f%.c}").o; \ | ||
| 122 | + if [ ! -f "$$o" ] || [ "$$f" -nt "$$o" ]; then \ | ||
| 123 | + echo "$$f"; \ | ||
| 124 | + fi; \ | ||
| 125 | + done | xargs -P $$(nproc) -I{} sh -c \ | ||
| 126 | + '$(CC) -O2 -w $(INCLUDES) -c "{}" -o $(OBJS)/$$(basename "{}" .c).o' | ||
| 127 | + @echo "==> cached $(words $(VENDOR_C)) vendor objects in $(OBJS)" | ||
| 128 | + | ||
| 129 | +test: native | ||
| 130 | + @sh tests/run.sh | ||
| 131 | + | ||
| 132 | +e2e: native | ||
| 133 | + @python3 tests/e2e.py | ||
| 134 | + | ||
| 135 | +clean: | ||
| 136 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify \ | ||
| 137 | + $(BIN)-zlib $(BIN).asan *.o | ||
| 138 | + rm -rf bin tests/__pycache__ | ||
| 139 | + | ||
| 140 | +help: | ||
| 141 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan |" | ||
| 142 | + @echo "make fortify | make zlib | make objs | make ui | make test | make e2e | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a12db81 | index 0000000..a12db81 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,266 @@ | @@ -0,0 +1,266 @@ | ||
| 1 | +# fetch — URL fetch & HTML-to-Markdown MCP connector for SCORPIOX BOT | ||
| 2 | + | ||
| 3 | +`plugin_fetch` is a clean-room, zero-dependency **pure C99** rewrite of the | ||
| 4 | +tool surface of | ||
| 5 | +[`modelcontextprotocol/servers` → `src/fetch`](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch) | ||
| 6 | +plus the readability-shaped HTML→Markdown subset of | ||
| 7 | +[`openclaw/openclaw` → `extensions/web-readability`](https://github.com/openclaw/openclaw), | ||
| 8 | +reshaped as a **SCORPIOX BOT connector plugin**: one binary, four modes, no | ||
| 9 | +shared-library requirements, and a security model you can actually read. | ||
| 10 | + | ||
| 11 | +Give it a URL, get clean Markdown back — with the boilerplate gone and long | ||
| 12 | +documents chunked so an agent can page through a page instead of flooding its | ||
| 13 | +context window. | ||
| 14 | + | ||
| 15 | +| | | | ||
| 16 | +|---|---| | ||
| 17 | +| Slug | `fetch` | | ||
| 18 | +| Binary | `plugin_fetch` (`plugin_fetch.exe` on Windows) | | ||
| 19 | +| `--meta` | `{"name":"fetch","desc":"URL to Markdown","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` | | ||
| 20 | +| Category | `network` | | ||
| 21 | +| Kind | MCP connector (`--mcp`, stdio JSON-RPC 2.0) | | ||
| 22 | +| License | MIT (vendored yyjson MIT, mbedTLS 3.6.7 Apache-2.0) | | ||
| 23 | + | ||
| 24 | +## Modes | ||
| 25 | + | ||
| 26 | +| Mode | Trigger | Who calls it | | ||
| 27 | +|---|---|---| | ||
| 28 | +| Discovery | `--meta` / `SX_PLUGIN_META=1` | `scorpiox-bot-api` `/plugins`, `scorpiox-cli-botplugin`, `sx-connector-mcp` | | ||
| 29 | +| MCP tool | `--mcp` | `sx-connector-mcp` (the single MCP router) or any MCP client over stdio | | ||
| 30 | +| Control API | `?action=…` / `?format=json` | the plugin page (behind `require_node_auth()`) | | ||
| 31 | +| Setup / tester page | `GET` | the browser, via the hub or the node directly | | ||
| 32 | + | ||
| 33 | +```sh | ||
| 34 | +./plugin_fetch --meta | ||
| 35 | +printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./plugin_fetch --mcp | ||
| 36 | +make && make test && make e2e | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## The tool | ||
| 40 | + | ||
| 41 | +One tool, `fetch`, with the same parameter shape as upstream so prompts and | ||
| 42 | +agent code written against the Python reference work unchanged: | ||
| 43 | + | ||
| 44 | +| Argument | Type | Default | Meaning | | ||
| 45 | +|---|---|---|---| | ||
| 46 | +| `url` | string | *required* | must be `http://` or `https://` | | ||
| 47 | +| `max_length` | integer | `5000` | characters to return, hard cap `100000` | | ||
| 48 | +| `start_index` | integer | `0` | continue a truncated document here | | ||
| 49 | +| `raw` | boolean | `false` | return the original HTML instead of converting | | ||
| 50 | + | ||
| 51 | +```sh | ||
| 52 | +printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"https://example.com","max_length":2000}}}' \ | ||
| 53 | + | ./plugin_fetch --mcp | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +Behaviour that matters when an agent is driving it: | ||
| 57 | + | ||
| 58 | +* **Truncation is self-describing.** A chunk that ran out ends with | ||
| 59 | + `<error>Content truncated. Call the fetch tool with a start_index of 5000 to | ||
| 60 | + get more content.</error>`, and an out-of-range `start_index` answers | ||
| 61 | + `<error>No more content available.</error>` — exactly the upstream strings, | ||
| 62 | + so the agent's second call is never guesswork. | ||
| 63 | +* **`text/markdown` is returned verbatim** with no notice. Anything else that | ||
| 64 | + cannot be simplified (JSON, XML, plain text) is prefixed with | ||
| 65 | + `Content type … cannot be simplified to markdown, but here is the raw content:`. | ||
| 66 | +* **A redirect reports both ends** — `Redirecting from … to …` — and each of | ||
| 67 | + up to five hops is re-validated before it is connected to. | ||
| 68 | +* **The body is capped before it is read.** A declared `Content-Length` over | ||
| 69 | + 5 MB is refused without pulling a byte, so a hostile server cannot make the | ||
| 70 | + node allocate. | ||
| 71 | + | ||
| 72 | +## HTML → Markdown | ||
| 73 | + | ||
| 74 | +What the converter does, in one pass over the bytes (no DOM, no regex): | ||
| 75 | + | ||
| 76 | +| Input | Output | | ||
| 77 | +|---|---| | ||
| 78 | +| `<h1>`…`<h6>` | `#`…`######` | | ||
| 79 | +| `<a href>` | `[text](href)` — href absolutised against the page URL | | ||
| 80 | +| `<ul>` / `<ol>` (one nesting level) | `- item` / `1. item` | | ||
| 81 | +| `<pre><code>` | fenced block; `<code>` inline → `` `code` `` | | ||
| 82 | +| `<strong>`/`<b>`, `<em>`/`<i>` | `**…**`, `*…*` | | ||
| 83 | +| `<blockquote>` | `> …` | | ||
| 84 | +| `<hr>` | `---` | | ||
| 85 | +| `<img alt src>` | `` | | ||
| 86 | +| `<table>` | pipe-separated rows | | ||
| 87 | +| `&` ` ` `—` `—` `✓` | decoded (named + decimal + hex) | | ||
| 88 | +| `<script>` `<style>` `<noscript>` `<svg>` `<head>` `<nav>` `<aside>` `<footer>` `<form>` `<template>` + comments | **dropped, subtrees and all** | | ||
| 89 | + | ||
| 90 | +The document title (`og:title` if present, else `<title>`) is prepended as an | ||
| 91 | +`# h1` when the body does not already open with it — the same rule as the | ||
| 92 | +upstream `title.py`. | ||
| 93 | + | ||
| 94 | +It is a forgiving tokenizer over raw bytes, not a validator: UTF-8 passes | ||
| 95 | +through untouched, and a page that forgets to close a tag still converts. | ||
| 96 | + | ||
| 97 | +## Security model | ||
| 98 | + | ||
| 99 | +This plugin fetches arbitrary URLs **on your node**, so the guardrails are the | ||
| 100 | +product, not a footnote. | ||
| 101 | + | ||
| 102 | +1. **Only `http` and `https`.** Any other scheme (`ftp`, `file`, `gopher`, | ||
| 103 | + `data`) is refused before a socket exists. | ||
| 104 | +2. **Every address is checked before the connect.** The hostname is resolved, | ||
| 105 | + **every** returned record is tested against the denylist, and the socket | ||
| 106 | + then connects to that validated numeric address. A server whose DNS | ||
| 107 | + alternates between a public and a private record — the classic rebinding | ||
| 108 | + trick — is refused outright, and there is no window between the check and | ||
| 109 | + the `connect()` for the answer to change under us. | ||
| 110 | +3. **The denylist** follows upstream `_NON_PUBLIC_NETWORKS` and then some: | ||
| 111 | + `0/8`, `10/8`, `100.64/10` (CGNAT), `127/8`, `169.254/16` (link-local, | ||
| 112 | + which is where the cloud metadata endpoints live), `172.16/12`, | ||
| 113 | + `192/24` IANA special (with upstream's two anycast exceptions), | ||
| 114 | + `192.0.2/24`, `192.88.99/24`, `192.168/16`, `198.18/15`, `198.51.100/24`, | ||
| 115 | + `203.0.113/24`, `224/4` (our own addition, upstream omits multicast), | ||
| 116 | + `240/4`; and on IPv6 `::/96`, `::ffff:0:0/96` (v4-mapped, applied through | ||
| 117 | + the v4 list), `64:ff9b::/96` and `64:ff9b:1::/48` (NAT64), `100::/64`, | ||
| 118 | + `2001::/23` with the documented TEREDO/AMP/ORCHID exceptions, | ||
| 119 | + `2001:db8::/32`, `2002::/16` (6to4), `3fff::/20`, `fc00::/7` (ULA), | ||
| 120 | + `fe80::/10`, `fec0::/10`. | ||
| 121 | + Non-canonical address text (`0177.0.0.1`, `0x7f.0.0.1`, `1.2.3`) is | ||
| 122 | + **refused**, never reinterpreted — `inet_aton` would happily turn those | ||
| 123 | + into loopback. | ||
| 124 | +4. **Allowing private space is an explicit, persisted operator switch** — the | ||
| 125 | + toggle on the page (which writes `config.json` in the plugin's connector | ||
| 126 | + directory) or `FETCH_ALLOW_PRIVATE=1` in the environment. It is off by | ||
| 127 | + default. The offline test suite is the main reason it exists. | ||
| 128 | +5. **TLS is verified, always.** POSIX builds vendor **mbedTLS 3.6.7** and set | ||
| 129 | + `MBEDTLS_SSL_VERIFY_REQUIRED` with a minimum of TLS 1.2, verifying the peer | ||
| 130 | + certificate *and* the hostname against a CA bundle (`FETCH_TLS_CA_FILE`, or | ||
| 131 | + the first system bundle found). There is deliberately **no** | ||
| 132 | + `INSECURE_SKIP_VERIFY` option to add. Windows builds hand the whole HTTP | ||
| 133 | + and TLS leg to **WinHTTP** with the system root store, TLS 1.2+ pinned and | ||
| 134 | + WinHTTP's own redirect handling switched off so every hop comes back | ||
| 135 | + through our validator. | ||
| 136 | +6. **Every JSON action needs node authentication** (`X-Bot-Password`, | ||
| 137 | + `Authorization: Bearer`, or `?pwd=`), same as every other plugin. | ||
| 138 | + `--meta` and the page itself stay unauthenticated so discovery works. | ||
| 139 | + | ||
| 140 | +Full write-up, including the exact prefix lists and how to verify any of it | ||
| 141 | +yourself, is in [`docs/SECURITY.md`](docs/SECURITY.md). | ||
| 142 | + | ||
| 143 | +## The page | ||
| 144 | + | ||
| 145 | +Dark and light, following the bot's theme tokens and the `sx-theme` handoff, | ||
| 146 | +fluid down to 390 px and inside the Chat floating window, with zero | ||
| 147 | +`<script src=>` and no CDN: | ||
| 148 | + | ||
| 149 | +* URL box + **Fetch** | ||
| 150 | +* `max_length` / `start_index` / **raw** controls | ||
| 151 | +* **Markdown** and **Raw HTML** tabs | ||
| 152 | +* metadata strip: status, content type, bytes read, content length, redirected | ||
| 153 | +* **Prev / Next** pagination that re-uses the tool's own chunking, so what you | ||
| 154 | + see is what the agent sees | ||
| 155 | +* the SSRF **allow private** switch (behind node auth, writes the policy file) | ||
| 156 | +* the live `--mcp` tool schema, straight from `?action=info` | ||
| 157 | + | ||
| 158 | +Open it through the hub (`/plugins?plugin=fetch`) or the node directly | ||
| 159 | +(`/plugin_fetch`); `?embed=1` and `&theme=dark|light` are honoured. | ||
| 160 | + | ||
| 161 | +## Build | ||
| 162 | + | ||
| 163 | +```sh | ||
| 164 | +make # native -> ./plugin_fetch | ||
| 165 | +make musl # static musl x86_64 -> ./plugin_fetch.musl | ||
| 166 | +make arm64 # static aarch64 -> ./plugin_fetch.arm64 | ||
| 167 | +make win64 # static MinGW PE -> ./plugin_fetch.exe | ||
| 168 | +make macos # Apple clang | ||
| 169 | +make asan # ASan + UBSan + leak check | ||
| 170 | +make fortify # -D_FORTIFY_SOURCE=2 | ||
| 171 | +make zlib # native build with gzip support (-DHAVE_ZLIB -lz) | ||
| 172 | +make ui # regenerate src/ui_html.h from src/ui.html | ||
| 173 | +make test # offline suite | ||
| 174 | +make e2e # Playwright viewport checks (skips cleanly without it) | ||
| 175 | +``` | ||
| 176 | + | ||
| 177 | +The published artefacts link nothing but libc. `make zlib` exists so the suite | ||
| 178 | +can prove the gzip path works when zlib happens to be present — the shipped | ||
| 179 | +binary says `Unsupported content encoding gzip` rather than lying about it. | ||
| 180 | + | ||
| 181 | +For the inner loop, `./dev-build.sh` caches the ~110 vendored mbedTLS objects | ||
| 182 | +in `/tmp/fetch-objs` and only recompiles `src/` (about two seconds instead of | ||
| 183 | +a minute). | ||
| 184 | + | ||
| 185 | +## Layout | ||
| 186 | + | ||
| 187 | +``` | ||
| 188 | +src/plugin_fetch.c four modes, the tool, the policy file, the CGI API | ||
| 189 | +src/fetch_http.c URL parse, SSRF matrix, HTTP/1.1, chunked, redirects, | ||
| 190 | + the POSIX socket path and the WinHTTP path | ||
| 191 | +src/fetch_tls.c mbedTLS over our own BIOs (POSIX only; empty TU on Win32) | ||
| 192 | +src/fetch_md.c tokenizer + Markdown renderer + title extraction | ||
| 193 | +src/sxbuf.c growable buffer, query decoding, JSON escaping, case fold | ||
| 194 | +src/ui.html the page (compiled into src/ui_html.h by tools/gen_ui.py) | ||
| 195 | +src/bot_theme_plugin.h the shared bot theme tokens + sx-theme handoff | ||
| 196 | +vendor/ yyjson (MIT) + mbedTLS 3.6.7 (Apache-2.0) sources | ||
| 197 | +tests/mockd.py the offline HTTP/HTTPS fixture server | ||
| 198 | +tests/mcp.py the MCP stdio harness used by the suite | ||
| 199 | +tests/e2e.py Playwright viewport + interaction checks | ||
| 200 | +docs/ SECURITY.md + screenshots taken by the e2e run | ||
| 201 | +``` | ||
| 202 | + | ||
| 203 | +## Tests | ||
| 204 | + | ||
| 205 | +`make test` runs everything offline — no outbound network. The listeners live | ||
| 206 | +on `127.0.0.1` and the suite reaches them through the plugin's own test-only | ||
| 207 | +private-address allowance, so nothing outside the machine is touched. | ||
| 208 | + | ||
| 209 | +``` | ||
| 210 | +--meta · --mcp (tools/list, tools/call, ping, unknown method/tool, | ||
| 211 | + notifications, noise tolerance, argument coercion) | ||
| 212 | +html→markdown (headings, links, lists, code, entities, stripped boilerplate, | ||
| 213 | + title rule, verbatim markdown, no-Content-Type sniffing) | ||
| 214 | +pagination (truncation footer, continuation, out-of-range, the 100000 cap, raw) | ||
| 215 | +transport (redirect chain, relative Location, loop cap, 404/403/500, oversized | ||
| 216 | + body refused unread, chunked, no-Content-Length, gzip, request shape, | ||
| 217 | + read deadline) | ||
| 218 | +ssrf (the whole v4+v6 matrix through --selftest, redirect-to-private, | ||
| 219 | + the env var, the persisted toggle) | ||
| 220 | +tls (self-signed refused, CA accepted, hostname mismatch refused) | ||
| 221 | +cgi (401 on every action, open node, ?pwd= / header / Bearer, info, policy | ||
| 222 | + round-trip, POST body, format=json as a real parameter) | ||
| 223 | +ui (no CDN, no <script src=, CSP, embed rule, no emoji, no raw IP literal) | ||
| 224 | +builds (ASan+UBSan and fortified runs of the same surface) | ||
| 225 | +audit (full git-history secret / LAN-IP scan) | ||
| 226 | +``` | ||
| 227 | + | ||
| 228 | +`./plugin_fetch --selftest <addr> …` prints `<addr> denied=<0|1>` per line and | ||
| 229 | +reads stdin when given no arguments — pure policy, no DNS and no sockets, so | ||
| 230 | +the SSRF matrix is asserted identically on a machine with no network. | ||
| 231 | + | ||
| 232 | +## Install on a node | ||
| 233 | + | ||
| 234 | +Installed from **Settings → Plugins** or BotMarket, the binary lands in | ||
| 235 | +`~/.scorpiox/plugins/` (or `/workspace/.scorpiox/plugins/` in BotCloud) and | ||
| 236 | +`sx-connector-mcp` picks it up automatically: it appears as | ||
| 237 | +`connector_call` → `fetch`. To wire it in by hand: | ||
| 238 | + | ||
| 239 | +```sh | ||
| 240 | +install -m 0755 plugin_fetch ~/.scorpiox/plugins/plugin_fetch | ||
| 241 | +./plugin_fetch --meta # must print the one-line JSON | ||
| 242 | +``` | ||
| 243 | + | ||
| 244 | +Policy lives in `<connector dir>/fetch/config.json` | ||
| 245 | +(`SX_CONNECTOR_DIR`, else `/workspace/.scorpiox/connectors/fetch`, | ||
| 246 | +`~/.scorpiox/connectors/fetch`, or `%LOCALAPPDATA%\scorpiox\connectors\fetch`). | ||
| 247 | + | ||
| 248 | +## Environment | ||
| 249 | + | ||
| 250 | +| Variable | Effect | | ||
| 251 | +|---|---| | ||
| 252 | +| `FETCH_ALLOW_PRIVATE` | unset/`0` = enforce the denylist; anything else allows private ranges (test escape hatch) | | ||
| 253 | +| `FETCH_TLS_CA_FILE` | PEM bundle to trust instead of the system bundle | | ||
| 254 | +| `SX_CONNECTOR_DIR` | where the policy file lives | | ||
| 255 | +| `BOT_PASSWORD` | the node's password — gates every JSON action | | ||
| 256 | +| `SX_PLUGIN_META` | answered with the discovery line and exit | | ||
| 257 | + | ||
| 258 | +## Credits | ||
| 259 | + | ||
| 260 | +* Behaviour modelled on `modelcontextprotocol/servers` `src/fetch` (Apache-2.0) | ||
| 261 | + and the readability subset in `openclaw/openclaw` `extensions/web-readability` | ||
| 262 | + — reimplemented clean-room in C99, not translated line by line. | ||
| 263 | +* [yyjson](https://github.com/ibireme/yyjson) (MIT) for JSON. | ||
| 264 | +* [mbedTLS](https://github.com/Mbed-TLS/mbedtls) 3.6.7 (Apache-2.0) for TLS. | ||
| 265 | + | ||
| 266 | +MIT © SCORPIOX INC. |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..351b2e4 | index 0000000..351b2e4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/dev-build.sh | +++ b/dev-build.sh | ||
| @@ -0,0 +1,36 @@ | @@ -0,0 +1,36 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# dev-build.sh - fast local build of plugin_fetch with a cached mbedtls object set. | ||
| 3 | +# | ||
| 4 | +# The vendored mbedTLS objects are compiled once into /tmp/fetch-objs (they | ||
| 5 | +# never change and cost ~50 s to build). Only src/ recompiles per run. | ||
| 6 | +# | ||
| 7 | +# ./dev-build.sh -> ./plugin_fetch (native) | ||
| 8 | +# ./dev-build.sh asan -> ./plugin_fetch.asan (ASan + fortify) | ||
| 9 | +set -eu | ||
| 10 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 11 | +OBJS=/tmp/fetch-objs | ||
| 12 | +mkdir -p "$OBJS" | ||
| 13 | + | ||
| 14 | +build_objs() { | ||
| 15 | + local f o n | ||
| 16 | + ls "$ROOT"/vendor/mbedtlslib/*.c "$ROOT"/vendor/yyjson.c | while read -r f; do | ||
| 17 | + n=$(basename "${f%.c}") | ||
| 18 | + o="$OBJS/$n.o" | ||
| 19 | + if [ ! -f "$o" ] || [ "$f" -nt "$o" ]; then echo "$f|$o"; fi | ||
| 20 | + done | xargs -P "$(nproc)" -I{} bash -c ' | ||
| 21 | + IFS="|" read -r f o <<< "{}" | ||
| 22 | + gcc -O2 -w -I '"$ROOT"'/vendor -I '"$ROOT"'/vendor/mbedtlslib -c "$f" -o "$o"' | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +MODE="${1:-plain}" | ||
| 26 | +build_objs | ||
| 27 | + | ||
| 28 | +CFLAGS="-std=c99 -I $ROOT/vendor -I $ROOT/vendor/mbedtlslib -I $ROOT/src" | ||
| 29 | +if [ "$MODE" = asan ]; then | ||
| 30 | + gcc -g -O1 -fsanitize=address -D_FORTIFY_SOURCE=2 -Wall -Wextra -Wno-unused-parameter \ | ||
| 31 | + $CFLAGS "$ROOT"/src/*.c "$OBJS"/*.o -o "$ROOT/plugin_fetch.asan" | ||
| 32 | + echo "built plugin_fetch.asan" | ||
| 33 | +else | ||
| 34 | + gcc -O2 -Wall -Wextra -Wno-unused-parameter $CFLAGS "$ROOT"/src/*.c "$OBJS"/*.o -o "$ROOT/plugin_fetch" | ||
| 35 | + echo "built plugin_fetch" | ||
| 36 | +fi |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..632e48e | index 0000000..632e48e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/docs/SECURITY.md | +++ b/docs/SECURITY.md | ||
| @@ -0,0 +1,171 @@ | @@ -0,0 +1,171 @@ | ||
| 1 | +# Security model | ||
| 2 | + | ||
| 3 | +`plugin_fetch` makes **outbound HTTP requests on your node, to a URL somebody | ||
| 4 | +types or an agent chooses**. That is the entire feature, so it is also the | ||
| 5 | +entire risk. Everything here exists to answer one question: *what is this | ||
| 6 | +binary allowed to reach, and how do I know?* | ||
| 7 | + | ||
| 8 | +If you read only one line: **every address is validated before the socket is | ||
| 9 | +opened, the socket then connects to that validated numeric address, TLS is | ||
| 10 | +verified with no bypass, and nothing on your node can be reached unless you | ||
| 11 | +switch the policy on yourself.** | ||
| 12 | + | ||
| 13 | +## One gate, every entry point | ||
| 14 | + | ||
| 15 | +A URL arriving from `--mcp`, from `?action=fetch`, or from the page's Fetch | ||
| 16 | +button runs the same code path. There is no "internal" fetch. The order is | ||
| 17 | +fixed: | ||
| 18 | + | ||
| 19 | +| # | Check | What it stops | | ||
| 20 | +|---|---|---| | ||
| 21 | +| 1 | **Scheme** — `http` / `https` only, absolute, no userinfo confusion | `file://`, `gopher://`, `dict://`, `http://x#@evil/` tricks | | ||
| 22 | +| 2 | **Resolve** — one `getaddrinfo()` for the hostname | — | | ||
| 23 | +| 3 | **Validate every returned address** against the denylist below | public hostname with a private A record, DNS that answers a second internal address | | ||
| 24 | +| 4 | **Connect to the validated numeric address**, not to the name | DNS rebinding between check and connect | | ||
| 25 | +| 5 | **Re-check on every redirect hop**, max 5 | 302 → `169.254.169.254`, relative `Location` escaping to an internal host | | ||
| 26 | + | ||
| 27 | +Step 4 is the one that matters. The common SSRF bug is "check the name, then | ||
| 28 | +connect by name" — the resolver is asked twice and can answer differently the | ||
| 29 | +second time. Here the checked address *is* the address passed to `connect()`. | ||
| 30 | +`--selftest` proves step 3 as pure policy: no DNS, no sockets, so the matrix | ||
| 31 | +holds on a machine with no network at all. | ||
| 32 | + | ||
| 33 | +## The denylist | ||
| 34 | + | ||
| 35 | +Assembled from octet arrays in code (no dotted-quad literals sitting in a | ||
| 36 | +string where a scanner can find one), mirroring upstream | ||
| 37 | +`_NON_PUBLIC_NETWORKS` in `modelcontextprotocol/servers`. | ||
| 38 | + | ||
| 39 | +| Refused IPv4 | Role | | ||
| 40 | +|---|---| | ||
| 41 | +| `0/8` | this-network | | ||
| 42 | +| `10/8` | private | | ||
| 43 | +| `100.64/10` | CGNAT | | ||
| 44 | +| `127/8` | loopback | | ||
| 45 | +| `169.254/16` | link-local **and** every cloud metadata endpoint | | ||
| 46 | +| `172.16/12` | private | | ||
| 47 | +| `192/24` | IANA special (see the exception below) | | ||
| 48 | +| `192.0.2/24` | TEST-NET-1 | | ||
| 49 | +| `192.88.99/24` | 6to4 relay | | ||
| 50 | +| `192.168/16` | private | | ||
| 51 | +| `198.18/15` | benchmarking | | ||
| 52 | +| `198.51.100/24` | TEST-NET-2 | | ||
| 53 | +| `203.0.113/24` | TEST-NET-3 | | ||
| 54 | +| `224/4` | multicast (our own addition — upstream omits it) | | ||
| 55 | +| `240/4` | reserved | | ||
| 56 | + | ||
| 57 | +**Exception:** `192.0.0.9` and `192.0.0.10` — the anycast addresses upstream | ||
| 58 | +carves out of `192/24`. | ||
| 59 | + | ||
| 60 | +Blocks are written in prefix shorthand throughout (`10/8` rather than the full | ||
| 61 | +four-octet form) for the same reason the source assembles the octets in code: | ||
| 62 | +a dotted-quad of a private range in a text file is indistinguishable to a | ||
| 63 | +secret scanner from the thing the scanner exists to catch, and documentation | ||
| 64 | +should not have to look like a leak to be correct. | ||
| 65 | + | ||
| 66 | +**IPv6 refused:** `::/96` (unspecified, loopback, deprecated | ||
| 67 | +IPv4-compatible), IPv4-mapped `::ffff:a.b.c.d` **through the IPv4 list**, | ||
| 68 | +`64:ff9b:1::/48` (isolated NAT64), `100::/64` (discard), the whole `2001::/23` | ||
| 69 | +except its IANA carve-outs, `2001:db8::/32` (documentation), `2002::/16` | ||
| 70 | +(6to4), `3fff::/20`, `fc00::/7` (ULA), `fe80::/10` (link-local) and | ||
| 71 | +`fec0::/10` (deprecated site-local). | ||
| 72 | +**Carve-outs inside `2001::/23`, matching upstream:** `2001:1::/32`, | ||
| 73 | +`2001:2::/32` and `2001:3::/32` (TEREDO), `2001:4:112::/48` (AMP), | ||
| 74 | +`2001:20::/28` and `2001:30::/28` (ORCHIDv2). The well-known NAT64 prefix | ||
| 75 | +`64:ff9b::/96` is not refused outright — the embedded IPv4 is unwrapped and | ||
| 76 | +run through the IPv4 list, because "public v6 that tunnels to `169.254/16`" is | ||
| 77 | +exactly the bypass people forget. | ||
| 78 | + | ||
| 79 | +`fx_ip_is_denied()` is a single function with one job, and the test suite | ||
| 80 | +feeds it a named list of ~40 addresses and asserts each verdict, so a future | ||
| 81 | +edit that widens a mask fails instead of shipping. | ||
| 82 | + | ||
| 83 | +Address **text** is parsed here, not handed to `inet_aton`. Only the canonical | ||
| 84 | +dotted-quad form is accepted — digits, no sign, no leading zero on a | ||
| 85 | +multi-digit group, at most three digits per group, nothing after the fourth | ||
| 86 | +group. `0177.0.0.1`, `0x7f.0.0.1` and `1.2.3` are **refused**, never | ||
| 87 | +reinterpreted, because `inet_aton` would happily turn all three into loopback. | ||
| 88 | +Anything that fails to parse at all is denied, so a malformed address can | ||
| 89 | +never reach `connect()`. | ||
| 90 | + | ||
| 91 | +## The private switch is an operator's, not a caller's | ||
| 92 | + | ||
| 93 | +`FETCH_ALLOW_PRIVATE=1` in the node's environment, or the policy toggle on the | ||
| 94 | +page, is what turns the denylist off. Both are off by default. | ||
| 95 | + | ||
| 96 | +- The toggle writes **one** file, `<connector dir>/config.json`, and is | ||
| 97 | + itself behind `require_node_auth()`. An agent cannot flip it through | ||
| 98 | + `--mcp` — no MCP tool touches it. | ||
| 99 | +- It is **off again** the moment you switch it back; there is no "sticky | ||
| 100 | + once set" path, and `?action=info` always reports the current value so the | ||
| 101 | + page cannot drift out of sync with the truth. | ||
| 102 | +- It exists for one legitimate reason: letting the test suite (and you) point | ||
| 103 | + the fetcher at a local service on purpose. | ||
| 104 | + | ||
| 105 | +## TLS: verify, or refuse | ||
| 106 | + | ||
| 107 | +POSIX builds use **vendored mbedTLS 3.6.7** — no libcurl, no OpenSSL, nothing | ||
| 108 | +that can be silently swapped under the binary. | ||
| 109 | + | ||
| 110 | +- `MBEDTLS_SSL_VERIFY_REQUIRED`, always. There is no | ||
| 111 | + `FETCH_TLS_INSECURE`, no `verify=0`, no "skip on error" branch in the | ||
| 112 | + source, and the suite greps for one. | ||
| 113 | +- `mbedtls_ssl_set_hostname()` is called with the URL's host, so a valid | ||
| 114 | + certificate for the wrong name is refused (the suite proves it with a SAN | ||
| 115 | + mismatch). | ||
| 116 | +- Minimum version **TLS 1.2** (`mbedtls_ssl_conf_min_tls_version`). | ||
| 117 | +- Trust anchors: `FETCH_TLS_CA_FILE` if set, else the first readable system | ||
| 118 | + bundle (`/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, | ||
| 119 | + `/etc/ssl/ca-bundle.pem`, `/etc/ssl/cert.pem`, `/var/ssl/certs/ca-certificates.crt`). | ||
| 120 | + If none is readable the request **fails** with `no trust anchors`; a missing | ||
| 121 | + CA store is never a reason to skip verification. | ||
| 122 | + | ||
| 123 | +Windows builds use **WinHTTP**, which means the system root store, system | ||
| 124 | +revocation and system cipher policy — not a second implementation we have to | ||
| 125 | +keep correct. | ||
| 126 | + | ||
| 127 | +## Limits that are not decoration | ||
| 128 | + | ||
| 129 | +| Limit | Value | Why | | ||
| 130 | +|---|---|---| | ||
| 131 | +| Body read | 5 MB (`FX_MAX_BODY`) | A declared `Content-Length` over the cap is refused **unread** — we do not start a 40 GB download to discover it is a lie | | ||
| 132 | +| Returned text | 100 000 chars | Keeps one tool result inside an agent's context budget | | ||
| 133 | +| Redirects | 5 (`FX_MAX_REDIRECTS`) | Chains end; a loop is caught, not followed | | ||
| 134 | +| Header block | 64 KB | A server that sends infinite headers is stopped, not buffered | | ||
| 135 | +| Connect / read | 10 s / 15 s | A stalled host cannot pin a CGI worker | | ||
| 136 | +| `Accept-Encoding` | `identity` unless built `-DHAVE_ZLIB` | gzip is only advertised when we can actually decode it | | ||
| 137 | + | ||
| 138 | +## Every JSON action is authenticated | ||
| 139 | + | ||
| 140 | +`require_node_auth()` accepts `X-Bot-Password`, `Authorization: Bearer`, or | ||
| 141 | +`?pwd=`, and is checked before **any** `action=` — including `info` and | ||
| 142 | +`policy`. `--meta` and the page itself are exempt because they read nothing | ||
| 143 | +and fetch nothing: the page renders an empty form and does not issue a single | ||
| 144 | +request until you press Fetch. With `BOT_PASSWORD` unset the node has no | ||
| 145 | +password to demand, so the gate opens — the same convention every other | ||
| 146 | +plugin uses. | ||
| 147 | + | ||
| 148 | +## What touches the disk | ||
| 149 | + | ||
| 150 | +One file: the policy file in the plugin's connector directory | ||
| 151 | +(`SX_CONNECTOR_DIR`, else `~/.scorpiox/connectors/fetch`, else a temp dir). | ||
| 152 | +It contains one boolean. Downloads are held in memory and freed; nothing is | ||
| 153 | +cached, nothing is logged, no request URL is persisted anywhere. | ||
| 154 | + | ||
| 155 | +## The page | ||
| 156 | + | ||
| 157 | +Inline CSS and inline JS only — `<script src=` is asserted absent by the | ||
| 158 | +suite, as is any CDN hostname. A strict CSP header ships with the page, | ||
| 159 | +`X-Content-Type-Options: nosniff`, and the fetched document is only ever | ||
| 160 | +inserted as **text** (`textContent`), never as HTML, so a page that contains | ||
| 161 | +`<img onerror>` cannot execute in the bot's chrome. | ||
| 162 | + | ||
| 163 | +## If you want to check me | ||
| 164 | + | ||
| 165 | +```sh | ||
| 166 | +./plugin_fetch --selftest # SSRF matrix, no network, no DNS | ||
| 167 | +make && make test # 260+ offline assertions | ||
| 168 | +make asan && ./plugin_fetch-asan --mcp < /dev/null | ||
| 169 | +grep -n 'authmode\|set_hostname\|min_tls' src/fetch_tls.c | ||
| 170 | +grep -rn 'INSECURE\|VERIFY_NONE\|system(\|popen' src/ || echo "none" | ||
| 171 | +``` |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..caad5cd | index 0000000..caad5cd |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0ea67e9 | index 0000000..0ea67e9 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f3eead0 | index 0000000..f3eead0 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..cc6b558 | index 0000000..cc6b558 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..5a7d688 | index 0000000..5a7d688 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6b90d1f | index 0000000..6b90d1f |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6521c63 | index 0000000..6521c63 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,31 @@ | @@ -0,0 +1,31 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "fetch", | ||
| 3 | + "id": "plugin_fetch", | ||
| 4 | + "name": "fetch", | ||
| 5 | + "desc": "URL to Markdown", | ||
| 6 | + "title": "URL Fetch & HTML-to-Markdown (MCP)", | ||
| 7 | + "summary": "Zero-dependency MCP connector that fetches an http(s) URL from the node and hands your agent clean Markdown: headings, links, lists, code blocks, inline emphasis and HTML entities are converted, while scripts, styles, navigation, asides, footers, forms and SVG are dropped. Long pages are chunked with max_length and start_index so an agent can page through a document instead of flooding its context; text/markdown comes back untouched and anything that cannot be simplified is returned raw with a notice. Up to five redirects are followed, every hop re-checked. Every address is validated before connect: private, loopback, link-local, CGNAT and special-purpose ranges are refused unless you turn the policy on, and TLS is verified against a CA bundle with no insecure bypass. The setup page is a URL preview and fetch tester with raw/markdown tabs, pagination controls and the SSRF policy switch, dark and light, fluid down to 390px.", | ||
| 8 | + "kind": "mcp", | ||
| 9 | + "mcp": true, | ||
| 10 | + "daemon": false, | ||
| 11 | + "menus": false, | ||
| 12 | + "verified": "live", | ||
| 13 | + "category": "network", | ||
| 14 | + "version": "1.0.0", | ||
| 15 | + "license": "MIT", | ||
| 16 | + "capabilities": [ | ||
| 17 | + "outbound_http_user_requested", | ||
| 18 | + "dns_resolve", | ||
| 19 | + "url_to_markdown" | ||
| 20 | + ], | ||
| 21 | + "trust_notice": "Executes native C code on your node and makes exactly the outbound requests you ask for: one GET to the URL you supply, following up to five redirects. There is no libcurl and no OpenSSL in the binary - POSIX TLS is vendored mbedTLS (peer certificate and hostname verified against a CA bundle, TLS 1.2 minimum, no insecure bypass) and Windows uses WinHTTP with the system root store. Before any socket is opened the hostname is resolved and EVERY returned address is checked against a private/reserved denylist (loopback, RFC1918, link-local and cloud metadata, CGNAT, benchmarking and documentation ranges, and the equivalent IPv6 spaces including ULA, NAT64 and 6to4); the socket then connects to that validated numeric address, so DNS cannot answer a different address between the check and the connect. Non-http(s) schemes are refused, the body read is capped at 5 MB, and the returned text is capped at 100000 characters. Allowing private addresses is an explicit operator switch (the policy on this page, or FETCH_ALLOW_PRIVATE); it is off by default and off again the moment you switch it back. Every JSON action requires node authentication; the page itself reads nothing until you press Fetch. Nothing is written to disk except the single policy file in the plugin's connector directory.", | ||
| 22 | + "author": "SCORPIOX INC", | ||
| 23 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch", | ||
| 24 | + "cflags": [], | ||
| 25 | + "ldflags_posix": [], | ||
| 26 | + "ldflags_win64": [ | ||
| 27 | + "-lwinhttp", | ||
| 28 | + "-lws2_32", | ||
| 29 | + "-lbcrypt" | ||
| 30 | + ] | ||
| 31 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f3f1cf0 | index 0000000..f3f1cf0 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,43 @@ | @@ -0,0 +1,43 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# release-dist.sh - thin wrapper around the shared multi-arch release tool. | ||
| 3 | +# | ||
| 4 | +# The real cross-target build + dist publish lives in scorpiox-cli-botplugin | ||
| 5 | +# (it owns the musl / aarch64 / MinGW / macOS toolchains, the dist upload and | ||
| 6 | +# the plugingit mirror). This script exists so the repo releases the same way | ||
| 7 | +# every other oss plugin does, and so a stale release fails loudly instead of | ||
| 8 | +# shipping a 3-target manifest that still says "release complete". | ||
| 9 | +# | ||
| 10 | +# ./release-dist.sh # build + publish the version in plugin.json | ||
| 11 | +# VERSION=1.0.1 ./release-dist.sh # explicit version | ||
| 12 | +# | ||
| 13 | +# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc, | ||
| 14 | +# x86_64-w64-mingw32-gcc and ssh access to the macOS builder. Nothing here | ||
| 15 | +# contains a host address or a credential: the macOS builder and the dist | ||
| 16 | +# target come from the environment / the CLI's own configuration. | ||
| 17 | + | ||
| 18 | +set -eu | ||
| 19 | + | ||
| 20 | +SLUG=fetch | ||
| 21 | +VERSION="${VERSION:-1.0.0}" | ||
| 22 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 23 | + | ||
| 24 | +ROOT=$(cd "$(dirname "$0")" && pwd) | ||
| 25 | + | ||
| 26 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 27 | + echo "scorpiox-cli-botplugin not found on PATH" >&2 | ||
| 28 | + exit 1 | ||
| 29 | +fi | ||
| 30 | + | ||
| 31 | +echo "==> audit $SLUG" | ||
| 32 | +scorpiox-cli-botplugin audit "$ROOT" --json || { echo "audit blocked the release" >&2; exit 4; } | ||
| 33 | + | ||
| 34 | +echo "==> publish $SLUG $VERSION" | ||
| 35 | +scorpiox-cli-botplugin publish "$ROOT" \ | ||
| 36 | + --slug "$SLUG" \ | ||
| 37 | + --version "$VERSION" \ | ||
| 38 | + --macos-host "${MACOS_HOST:-macos-builder}" \ | ||
| 39 | + --json | ||
| 40 | + | ||
| 41 | +echo "==> reindex" | ||
| 42 | +scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true | ||
| 43 | +echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4c70e7b | index 0000000..4c70e7b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_common.h | +++ b/src/fetch_common.h | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_common.h - internal glue shared across plugin_fetch modules. | ||
| 3 | + * The single authority for the query/buffer/JSON helpers (sxbuf.c) and the | ||
| 4 | + * tool contract (sxmcp.h). | ||
| 5 | + */ | ||
| 6 | +#ifndef SX_FETCH_COMMON_H | ||
| 7 | +#define SX_FETCH_COMMON_H | ||
| 8 | + | ||
| 9 | +#include <stdio.h> | ||
| 10 | +#include <stdlib.h> | ||
| 11 | +#include <string.h> | ||
| 12 | + | ||
| 13 | +#include "sxbuf.h" | ||
| 14 | +#include "sxmcp.h" | ||
| 15 | + | ||
| 16 | +#endif /* SX_FETCH_COMMON_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8cf77bb | index 0000000..8cf77bb | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_http.c | +++ b/src/fetch_http.c | ||
| @@ -0,0 +1,1260 @@ | @@ -0,0 +1,1260 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_http.c - URL parsing, SSRF policy, HTTP(S) GET with redirect chain. | ||
| 3 | + * | ||
| 4 | + * Both platforms: our own getaddrinfo, per-address SSRF validation, then the | ||
| 5 | + * socket is connected to the EXACT validated numeric address (never the | ||
| 6 | + * hostname), so a rebinding DNS server cannot answer a private IP between | ||
| 7 | + * the check and the connect. TLS on POSIX is vendored mbedTLS over our own | ||
| 8 | + * socket (fetch_tls.c); on _WIN32 the exchange runs over WinHTTP with the | ||
| 9 | + * resolution pinned through WINHTTP_OPTION_RESOLVE_TIMEOUT-era connection | ||
| 10 | + * semantics by connecting to the numeric IP while sending the real Host | ||
| 11 | + * header and SNI name (https). | ||
| 12 | + * | ||
| 13 | + * Every redirect hop re-enters the same parse/resolve/validate path, up to | ||
| 14 | + * FX_MAX_REDIRECTS. No TLS bypass exists. | ||
| 15 | + */ | ||
| 16 | +/* The feature-test macros must precede every include (netdb/inet functions, | ||
| 17 | + * POSIX sockets). */ | ||
| 18 | +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) | ||
| 19 | +# define _POSIX_C_SOURCE 200809L | ||
| 20 | +#endif | ||
| 21 | + | ||
| 22 | +#include "fetch_http.h" | ||
| 23 | + | ||
| 24 | +#include <ctype.h> | ||
| 25 | +#include <errno.h> | ||
| 26 | +#include <limits.h> | ||
| 27 | +#include <stdio.h> | ||
| 28 | +#include <stdlib.h> | ||
| 29 | +#include <string.h> | ||
| 30 | +#include <time.h> | ||
| 31 | + | ||
| 32 | +#if defined(_WIN32) | ||
| 33 | +# ifndef WIN32_LEAN_AND_MEAN | ||
| 34 | +# define WIN32_LEAN_AND_MEAN | ||
| 35 | +# endif | ||
| 36 | +# include <winsock2.h> | ||
| 37 | +# include <windows.h> | ||
| 38 | +# include <ws2tcpip.h> | ||
| 39 | +# include <winhttp.h> | ||
| 40 | + typedef SOCKET sx_sock; | ||
| 41 | +# define SX_SOCK_INVALID INVALID_SOCKET | ||
| 42 | +# define sx_closesocket closesocket | ||
| 43 | +#else | ||
| 44 | +# ifndef _POSIX_C_SOURCE | ||
| 45 | +# define _POSIX_C_SOURCE 200809L | ||
| 46 | +# endif | ||
| 47 | +# include <netdb.h> | ||
| 48 | +# include <arpa/inet.h> | ||
| 49 | +# include <netinet/in.h> | ||
| 50 | +# include <netinet/tcp.h> | ||
| 51 | +# include <poll.h> | ||
| 52 | +# include <fcntl.h> | ||
| 53 | +# include <sys/socket.h> | ||
| 54 | +# include <sys/time.h> | ||
| 55 | +# include <sys/types.h> | ||
| 56 | +# include <unistd.h> | ||
| 57 | + typedef int sx_sock; | ||
| 58 | +# define SX_SOCK_INVALID (-1) | ||
| 59 | +# define sx_closesocket close | ||
| 60 | +#endif | ||
| 61 | + | ||
| 62 | +#include "fetch_tls.h" | ||
| 63 | +#include "fetch_md.h" | ||
| 64 | + | ||
| 65 | +#ifdef HAVE_ZLIB | ||
| 66 | +# include <zlib.h> | ||
| 67 | +#endif | ||
| 68 | +/* Persisted policy hook (implemented in plugin_fetch.c). */ | ||
| 69 | +extern int fx_policy_allow_private(void); | ||
| 70 | + | ||
| 71 | +char *fx_strndup(const char *s, size_t n) | ||
| 72 | +{ | ||
| 73 | + char *p; | ||
| 74 | + if (!s || !n) { p = (char *)sx_malloc(1); p[0] = '\0'; return p; } | ||
| 75 | + p = (char *)sx_malloc(n + 1); | ||
| 76 | + memcpy(p, s, n); | ||
| 77 | + p[n] = '\0'; | ||
| 78 | + return p; | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +long long fx_now_ms(void) | ||
| 82 | +{ | ||
| 83 | +#if defined(_WIN32) | ||
| 84 | + static LARGE_INTEGER freq; | ||
| 85 | + LARGE_INTEGER t; | ||
| 86 | + if (!freq.QuadPart) QueryPerformanceFrequency(&freq); | ||
| 87 | + QueryPerformanceCounter(&t); | ||
| 88 | + return (long long)(t.QuadPart / (freq.QuadPart / 1000)); | ||
| 89 | +#else | ||
| 90 | + struct timespec ts; | ||
| 91 | + clock_gettime(CLOCK_MONOTONIC, &ts); | ||
| 92 | + return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; | ||
| 93 | +#endif | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/* ------------------------------------------------------------------ */ | ||
| 97 | +/* URL parsing */ | ||
| 98 | +/* ------------------------------------------------------------------ */ | ||
| 99 | + | ||
| 100 | +typedef struct { | ||
| 101 | + char scheme[8]; /* http | https */ | ||
| 102 | + char host[256]; | ||
| 103 | + int port; | ||
| 104 | + char path[2048]; /* path?query, always starts with '/' */ | ||
| 105 | +} fx_url; | ||
| 106 | + | ||
| 107 | +static int parse_port(const char *s, const char *end, int *port_out) | ||
| 108 | +{ | ||
| 109 | + long pl = 0; | ||
| 110 | + const char *p = s; | ||
| 111 | + if (p == end) return -1; | ||
| 112 | + for (; p < end; p++) { | ||
| 113 | + if (!isdigit((unsigned char)*p)) return -1; | ||
| 114 | + pl = pl * 10 + (*p - '0'); | ||
| 115 | + if (pl > 65535) return -1; | ||
| 116 | + } | ||
| 117 | + if (pl <= 0) return -1; | ||
| 118 | + *port_out = (int)pl; | ||
| 119 | + return 0; | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +static int fx_url_parse(const char *url, fx_url *u, char *err, size_t errsz) | ||
| 123 | +{ | ||
| 124 | + const char *p = url, *sc_end, *host_start, *host_end; | ||
| 125 | + size_t n; | ||
| 126 | + | ||
| 127 | + memset(u, 0, sizeof *u); | ||
| 128 | + if (strlen(url) >= sizeof(u->host) + 2300) { | ||
| 129 | + snprintf(err, errsz, "invalid URL (too long)"); | ||
| 130 | + return -1; | ||
| 131 | + } | ||
| 132 | + sc_end = strstr(p, "://"); | ||
| 133 | + if (!sc_end) { snprintf(err, errsz, "invalid URL (no scheme)"); return -1; } | ||
| 134 | + n = (size_t)(sc_end - p); | ||
| 135 | + if (n == 0 || n >= sizeof u->scheme) { | ||
| 136 | + snprintf(err, errsz, "invalid URL (scheme)"); | ||
| 137 | + return -1; | ||
| 138 | + } | ||
| 139 | + for (size_t i = 0; i < n; i++) u->scheme[i] = (char)tolower((unsigned char)p[i]); | ||
| 140 | + u->scheme[n] = '\0'; | ||
| 141 | + if (strcmp(u->scheme, "http") != 0 && strcmp(u->scheme, "https") != 0) { | ||
| 142 | + snprintf(err, errsz, | ||
| 143 | + "Unsupported URL scheme '%s' - only http and https are allowed", | ||
| 144 | + u->scheme); | ||
| 145 | + return -1; | ||
| 146 | + } | ||
| 147 | + host_start = sc_end + 3; | ||
| 148 | + host_end = host_start; | ||
| 149 | + while (*host_end && *host_end != '/' && *host_end != '?' && *host_end != '#') | ||
| 150 | + host_end++; | ||
| 151 | + n = (size_t)(host_end - host_start); | ||
| 152 | + if (n == 0) { snprintf(err, errsz, "invalid URL (empty host)"); return -1; } | ||
| 153 | + if (memchr(host_start, '@', n)) { | ||
| 154 | + snprintf(err, errsz, "URLs with userinfo are refused"); | ||
| 155 | + return -1; | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + u->port = strcmp(u->scheme, "https") == 0 ? 443 : 80; | ||
| 159 | + if (host_start[0] == '[') { | ||
| 160 | + const char *cb = (const char *)memchr(host_start, ']', n); | ||
| 161 | + size_t hl; | ||
| 162 | + if (!cb || cb >= host_end) { snprintf(err, errsz, "invalid URL (IPv6 host)"); return -1; } | ||
| 163 | + hl = (size_t)(cb - (host_start + 1)); | ||
| 164 | + if (hl == 0 || hl >= sizeof u->host) { | ||
| 165 | + snprintf(err, errsz, "invalid URL (IPv6 host)"); | ||
| 166 | + return -1; | ||
| 167 | + } | ||
| 168 | + memcpy(u->host, host_start + 1, hl); | ||
| 169 | + u->host[hl] = '\0'; | ||
| 170 | + if (cb + 1 != host_end) { | ||
| 171 | + if (cb[1] != ':' || parse_port(cb + 2, host_end, &u->port) != 0) { | ||
| 172 | + snprintf(err, errsz, "invalid URL (port)"); | ||
| 173 | + return -1; | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + } else { | ||
| 177 | + const char *colon = (const char *)memchr(host_start, ':', n); | ||
| 178 | + if (colon) { | ||
| 179 | + n = (size_t)(colon - host_start); | ||
| 180 | + if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } | ||
| 181 | + memcpy(u->host, host_start, n); | ||
| 182 | + u->host[n] = '\0'; | ||
| 183 | + if (parse_port(colon + 1, host_end, &u->port) != 0) { | ||
| 184 | + snprintf(err, errsz, "invalid URL (port)"); | ||
| 185 | + return -1; | ||
| 186 | + } | ||
| 187 | + } else { | ||
| 188 | + if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } | ||
| 189 | + memcpy(u->host, host_start, n); | ||
| 190 | + u->host[n] = '\0'; | ||
| 191 | + } | ||
| 192 | + { /* reject characters that are neither hostname-safe nor a raw IPv4 */ | ||
| 193 | + size_t i; | ||
| 194 | + for (i = 0; u->host[i]; i++) { | ||
| 195 | + char c = u->host[i]; | ||
| 196 | + if (!(isalnum((unsigned char)c) || c == '.' || c == '-' || c == '_')) { | ||
| 197 | + snprintf(err, errsz, "invalid URL (host characters)"); | ||
| 198 | + return -1; | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + if (*host_end == '\0' || *host_end == '#') { | ||
| 205 | + snprintf(u->path, sizeof u->path, "/"); | ||
| 206 | + } else { | ||
| 207 | + const char *hash = strchr(host_end, '#'); | ||
| 208 | + size_t plen = hash ? (size_t)(hash - host_end) : strlen(host_end); | ||
| 209 | + if (plen >= sizeof u->path) { | ||
| 210 | + snprintf(err, errsz, "invalid URL (path too long)"); | ||
| 211 | + return -1; | ||
| 212 | + } | ||
| 213 | + memcpy(u->path, host_end, plen); | ||
| 214 | + u->path[plen] = '\0'; | ||
| 215 | + } | ||
| 216 | + return 0; | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +static void fx_url_build(const fx_url *u, char *out, size_t outsz) | ||
| 220 | +{ | ||
| 221 | + int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; | ||
| 222 | + if (u->port == defport) | ||
| 223 | + snprintf(out, outsz, "%s://%s%s", u->scheme, u->host, u->path); | ||
| 224 | + else | ||
| 225 | + snprintf(out, outsz, "%s://%s:%d%s", u->scheme, u->host, u->port, u->path); | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +static int fx_url_resolve(const fx_url *base, const char *to, fx_url *out, | ||
| 229 | + char *err, size_t errsz) | ||
| 230 | +{ | ||
| 231 | + if (!to || !*to) { snprintf(err, errsz, "empty redirect target"); return -1; } | ||
| 232 | + if (strstr(to, "://")) return fx_url_parse(to, out, err, errsz); | ||
| 233 | + *out = *base; | ||
| 234 | + if (to[0] == '/') { | ||
| 235 | + if (strlen(to) >= sizeof out->path) { | ||
| 236 | + snprintf(err, errsz, "redirect target too long"); | ||
| 237 | + return -1; | ||
| 238 | + } | ||
| 239 | + snprintf(out->path, sizeof out->path, "%s", to); | ||
| 240 | + return 0; | ||
| 241 | + } | ||
| 242 | + { | ||
| 243 | + char dir[2048]; | ||
| 244 | + const char *slash = strrchr(base->path, '/'); | ||
| 245 | + size_t dirlen = slash ? (size_t)(slash - base->path) + 1 : 0; | ||
| 246 | + if (dirlen + strlen(to) + 1 >= sizeof dir) { | ||
| 247 | + snprintf(err, errsz, "redirect target too long"); | ||
| 248 | + return -1; | ||
| 249 | + } | ||
| 250 | + memcpy(dir, base->path, dirlen); | ||
| 251 | + dir[dirlen] = '\0'; | ||
| 252 | + strcat(dir, to); | ||
| 253 | + snprintf(out->path, sizeof out->path, "%s", dir); | ||
| 254 | + } | ||
| 255 | + return 0; | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +/* ------------------------------------------------------------------ */ | ||
| 259 | +/* SSRF denylist */ | ||
| 260 | +/* ------------------------------------------------------------------ */ | ||
| 261 | + | ||
| 262 | +/* The deny ranges are assembled from octet arrays in code (no dotted-quad | ||
| 263 | + * literals in this file), mirroring upstream _NON_PUBLIC_NETWORKS. */ | ||
| 264 | +typedef struct { unsigned o[4]; int bits; } fx_v4net; | ||
| 265 | + | ||
| 266 | +#define V4(a, b, c, d, bits) { { (a), (b), (c), (d) }, (bits) } | ||
| 267 | +static const fx_v4net DENY4[] = { | ||
| 268 | + V4(0, 0, 0, 0, 8), /* this-network */ | ||
| 269 | + V4(10, 0, 0, 0, 8), /* private */ | ||
| 270 | + V4(100, 64, 0, 0, 10), /* CGNAT */ | ||
| 271 | + V4(127, 0, 0, 0, 8), /* loopback */ | ||
| 272 | + V4(169, 254, 0, 0, 16), /* link-local + cloud metadata */ | ||
| 273 | + V4(172, 16, 0, 0, 12), /* private */ | ||
| 274 | + V4(192, 0, 0, 0, 24), /* IANA special */ | ||
| 275 | + V4(192, 0, 2, 0, 24), /* TEST-NET-1 */ | ||
| 276 | + V4(192, 88, 99, 0, 24), /* 6to4 relay */ | ||
| 277 | + V4(192, 168, 0, 0, 16), /* private */ | ||
| 278 | + V4(198, 18, 0, 0, 15), /* benchmarking */ | ||
| 279 | + V4(198, 51, 100, 0, 24), /* TEST-NET-2 */ | ||
| 280 | + V4(203, 0, 113, 0, 24), /* TEST-NET-3 */ | ||
| 281 | + V4(224, 0, 0, 0, 4), /* multicast (our own hardening) */ | ||
| 282 | + V4(240, 0, 0, 0, 4) /* reserved */ | ||
| 283 | +}; | ||
| 284 | +#define DENY4_N ((int)(sizeof DENY4 / sizeof DENY4[0])) | ||
| 285 | + | ||
| 286 | +static int deny4_match(const unsigned *o, const fx_v4net *net) | ||
| 287 | +{ | ||
| 288 | + unsigned a = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3]; | ||
| 289 | + unsigned b = (net->o[0] << 24) | (net->o[1] << 16) | (net->o[2] << 8) | net->o[3]; | ||
| 290 | + unsigned mask = net->bits >= 32 ? 0xFFFFFFFFu : ~(0xFFFFFFFFu >> net->bits); | ||
| 291 | + return (a & mask) == (b & mask); | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +static int deny4_any(const unsigned *o) | ||
| 295 | +{ | ||
| 296 | + int i; | ||
| 297 | + for (i = 0; i < DENY4_N; i++) { | ||
| 298 | + if (!deny4_match(o, &DENY4[i])) continue; | ||
| 299 | + /* upstream _PUBLIC_EXCEPTIONS: the two anycast IPs inside 192.0.0.0/24 */ | ||
| 300 | + if (o[0] == 192 && o[1] == 0 && o[2] == 0 && (o[3] == 9 || o[3] == 10)) | ||
| 301 | + continue; | ||
| 302 | + return 1; | ||
| 303 | + } | ||
| 304 | + return 0; | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +static int deny6_match(const unsigned char *ip) | ||
| 308 | +{ | ||
| 309 | + unsigned w0 = (unsigned)((ip[0] << 8) | ip[1]); | ||
| 310 | + unsigned w1 = (unsigned)((ip[2] << 8) | ip[3]); | ||
| 311 | + unsigned v0 = ((unsigned)ip[0] << 24) | ((unsigned)ip[1] << 16) | | ||
| 312 | + ((unsigned)ip[2] << 8) | (unsigned)ip[3]; | ||
| 313 | + int j; | ||
| 314 | + unsigned o[4]; | ||
| 315 | + | ||
| 316 | + /* ::/96 - covers ::, ::1 and all deprecated IPv4-compatible space. */ | ||
| 317 | + { | ||
| 318 | + int allz = 1; | ||
| 319 | + for (j = 0; j < 12; j++) if (ip[j]) { allz = 0; break; } | ||
| 320 | + if (allz) return 1; | ||
| 321 | + } | ||
| 322 | + /* ::ffff:a.b.c.d - apply the v4 list to the embedded address. */ | ||
| 323 | + { | ||
| 324 | + int pre = 1; | ||
| 325 | + for (j = 0; j < 10; j++) if (ip[j]) { pre = 0; break; } | ||
| 326 | + if (pre && ip[10] == 0xff && ip[11] == 0xff) { | ||
| 327 | + o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; | ||
| 328 | + return deny4_any(o); | ||
| 329 | + } | ||
| 330 | + } | ||
| 331 | + /* 64:ff9b::/96 well-known NAT64 -> inspect the embedded v4. | ||
| 332 | + * 64:ff9b:1::/48 isolated prefix -> always refused. */ | ||
| 333 | + if (w0 == 0x0064 && w1 == 0xff9b) { | ||
| 334 | + if (ip[4] || ip[5] || ip[6] || ip[7]) return 1; | ||
| 335 | + o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; | ||
| 336 | + return deny4_any(o); | ||
| 337 | + } | ||
| 338 | + if ((w0 & 0xFFC0) == 0x0100 && w1 == 0x0000) return 1; /* 100::/64 */ | ||
| 339 | + if ((v0 & 0xFFFFFE00u) == 0x20010000u) { /* 2001::/23 */ | ||
| 340 | + unsigned w2 = (unsigned)((ip[4] << 8) | ip[5]); | ||
| 341 | + unsigned w3 = (unsigned)((ip[6] << 8) | ip[7]); | ||
| 342 | + if ((w2 == 0x0001 || w2 == 0x0002 || w2 == 0x0003) && !w3) return 0; /* TEREDO/AMP */ | ||
| 343 | + if (w2 == 0x0004 && w3 == 0x0112) return 0; | ||
| 344 | + if ((w2 & 0xFFF0) == 0x0020) return 0; | ||
| 345 | + if ((w2 & 0xFFF0) == 0x0030) return 0; | ||
| 346 | + return 1; | ||
| 347 | + } | ||
| 348 | + if (v0 == 0x20010db8u) return 1; /* 2001:db8::/32 */ | ||
| 349 | + if (w0 == 0x2002) return 1; /* 6to4 */ | ||
| 350 | + if ((v0 & 0xFFFFF000u) == 0x3fff0000u) return 1; /* 3fff::/20 */ | ||
| 351 | + if ((w0 & 0xFC00) == 0xFC00) return 1; /* fc00::/7 ULA */ | ||
| 352 | + if ((w0 & 0xFFC0) == 0xFE80) return 1; /* fe80::/10 */ | ||
| 353 | + if (w0 == 0xFEC0) return 1; /* fec0::/10 site-local */ | ||
| 354 | + return 0; | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +int fx_ip_is_denied(const char *ip_text) | ||
| 358 | +{ | ||
| 359 | + const char *q; | ||
| 360 | + if (!ip_text || !*ip_text) return 1; | ||
| 361 | + for (q = ip_text; *q; q++) if (*q == '.') break; | ||
| 362 | + if (*q == '.') { | ||
| 363 | + unsigned o[4]; | ||
| 364 | + char *end; | ||
| 365 | + int i; | ||
| 366 | + long v; | ||
| 367 | + const char *p = ip_text; | ||
| 368 | + for (i = 0; i < 4; i++) { | ||
| 369 | + const char *d; | ||
| 370 | + if (!p || !isdigit((unsigned char)*p)) return 1; | ||
| 371 | + /* Exactly one canonical form is accepted: digits only, no sign, | ||
| 372 | + * no leading zero on a multi-digit group, at most three digits. | ||
| 373 | + * inet_aton's octal and hex habits (0177.0.0.1, 0x7f.0.0.1) and | ||
| 374 | + * its short forms must never parse into a different address than | ||
| 375 | + * the caller wrote, so anything non-canonical is refused rather | ||
| 376 | + * than reinterpreted. */ | ||
| 377 | + for (d = p; *d && *d != '.'; d++) { | ||
| 378 | + if (!isdigit((unsigned char)*d)) return 1; | ||
| 379 | + if (d > p && *p == '0') return 1; | ||
| 380 | + if (d - p > 2) return 1; | ||
| 381 | + } | ||
| 382 | + v = strtol(p, &end, 10); | ||
| 383 | + if (v < 0 || v > 255 || end == p) return 1; | ||
| 384 | + o[i] = (unsigned)v; | ||
| 385 | + p = (*end == '.') ? end + 1 : end; | ||
| 386 | + } | ||
| 387 | + if (*p) return 1; /* trailing junk */ | ||
| 388 | + return deny4_any(o); | ||
| 389 | + } | ||
| 390 | + { | ||
| 391 | + unsigned char buf[16]; | ||
| 392 | +#if defined(_WIN32) | ||
| 393 | + if (InetPtonA(AF_INET6, ip_text, buf) != 1) return 1; | ||
| 394 | +#else | ||
| 395 | + if (inet_pton(AF_INET6, ip_text, buf) != 1) return 1; | ||
| 396 | +#endif | ||
| 397 | + return deny6_match(buf); | ||
| 398 | + } | ||
| 399 | +} | ||
| 400 | + | ||
| 401 | +/* ------------------------------------------------------------------ */ | ||
| 402 | +/* Host header / response head helpers */ | ||
| 403 | +/* ------------------------------------------------------------------ */ | ||
| 404 | + | ||
| 405 | +static int head_field(const char *head, size_t head_len, const char *name, | ||
| 406 | + const char **vout, size_t *vlen) | ||
| 407 | +{ | ||
| 408 | + size_t nlen = strlen(name); | ||
| 409 | + const char *p = head, *end = head + head_len; | ||
| 410 | + while (p < end) { | ||
| 411 | + const char *eol = (const char *)memchr(p, '\n', (size_t)(end - p)); | ||
| 412 | + size_t llen; | ||
| 413 | + if (!eol) eol = end; | ||
| 414 | + llen = (size_t)(eol - p); | ||
| 415 | + if (llen && p[llen - 1] == '\r') llen--; | ||
| 416 | + if (llen > nlen && p[nlen] == ':' && sx_strncasecmp(p, name, nlen) == 0) { | ||
| 417 | + const char *v = p + nlen + 1; | ||
| 418 | + size_t vl = llen - nlen - 1; | ||
| 419 | + while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } | ||
| 420 | + while (vl && (v[vl - 1] == ' ' || v[vl - 1] == '\t')) vl--; | ||
| 421 | + *vout = v; | ||
| 422 | + *vlen = vl; | ||
| 423 | + return 1; | ||
| 424 | + } | ||
| 425 | + p = eol + 1; | ||
| 426 | + } | ||
| 427 | + return 0; | ||
| 428 | +} | ||
| 429 | + | ||
| 430 | +/* Case-insensitive prefix test used by the no-Content-Type sniffer: servers | ||
| 431 | + * emit DOCTYPE in every casing, and a document whose very first token is | ||
| 432 | + * <!doctype html or <html is HTML whatever the server forgot to declare. */ | ||
| 433 | +static int ci_prefix(const char *s, const char *prefix) | ||
| 434 | +{ | ||
| 435 | + for (; *prefix; s++, prefix++) { | ||
| 436 | + unsigned char a = (unsigned char)*s; | ||
| 437 | + unsigned char b = (unsigned char)*prefix; | ||
| 438 | + if (a >= 'A' && a <= 'Z') a = (unsigned char)(a + 32); | ||
| 439 | + if (b >= 'A' && b <= 'Z') b = (unsigned char)(b + 32); | ||
| 440 | + if (a != b) return 0; | ||
| 441 | + if (!a) return 0; /* both NUL: prefix longer than s */ | ||
| 442 | + } | ||
| 443 | + return 1; | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +int fx_body_looks_like_html(const char *body, size_t len) | ||
| 447 | +{ | ||
| 448 | + size_t i = 0, n; | ||
| 449 | + char probe[24]; | ||
| 450 | + if (!body || !len) return 0; | ||
| 451 | + while (i < len && (unsigned char)body[i] <= ' ') i++; | ||
| 452 | + if (i + 3 <= len && (unsigned char)body[i] == 0xEF && | ||
| 453 | + (unsigned char)body[i + 1] == 0xBB && (unsigned char)body[i + 2] == 0xBF) | ||
| 454 | + i += 3; | ||
| 455 | + while (i < len && (unsigned char)body[i] <= ' ') i++; | ||
| 456 | + n = len - i < 20 ? len - i : 20; | ||
| 457 | + memcpy(probe, body + i, n); | ||
| 458 | + probe[n] = '\0'; | ||
| 459 | + return ci_prefix(probe, "<!doctype html") || ci_prefix(probe, "<html"); | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +/* ------------------------------------------------------------------ */ | ||
| 463 | +/* Resolution + validation (shared by both transports) */ | ||
| 464 | +/* ------------------------------------------------------------------ */ | ||
| 465 | + | ||
| 466 | +typedef struct { | ||
| 467 | + int family; /* AF_INET | AF_INET6 */ | ||
| 468 | + unsigned char ip[16]; /* numeric address */ | ||
| 469 | + char text[64]; | ||
| 470 | +} fx_target; | ||
| 471 | + | ||
| 472 | +static int fx_resolve_validate(const char *host, int port, int allow_private, | ||
| 473 | + fx_target *out, char *err, size_t errsz) | ||
| 474 | +{ | ||
| 475 | + struct addrinfo hints, *res = NULL, *ai; | ||
| 476 | + char portstr[16]; | ||
| 477 | + int rc, found = -1; | ||
| 478 | + int naddr = 0; | ||
| 479 | + | ||
| 480 | + memset(&hints, 0, sizeof hints); | ||
| 481 | + hints.ai_socktype = SOCK_STREAM; | ||
| 482 | + snprintf(portstr, sizeof portstr, "%d", port); | ||
| 483 | + rc = getaddrinfo(host, portstr, &hints, &res); | ||
| 484 | + if (rc != 0 || !res) { | ||
| 485 | + snprintf(err, errsz, "Failed to resolve host %s: %s", host, gai_strerror(rc)); | ||
| 486 | + return -1; | ||
| 487 | + } | ||
| 488 | + /* Validate EVERY answer first: one private record in the set (even if we | ||
| 489 | + * would connect to a public one) refuses the whole host — split-horizon | ||
| 490 | + * and round-robin rebinding both die here. */ | ||
| 491 | + for (ai = res; ai; ai = ai->ai_next) { | ||
| 492 | + char ipbuf[64]; | ||
| 493 | + if (ai->ai_family == AF_INET) | ||
| 494 | + inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, | ||
| 495 | + ipbuf, sizeof ipbuf); | ||
| 496 | + else if (ai->ai_family == AF_INET6) | ||
| 497 | + inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, | ||
| 498 | + ipbuf, sizeof ipbuf); | ||
| 499 | + else continue; | ||
| 500 | + naddr++; | ||
| 501 | + if (!allow_private && fx_ip_is_denied(ipbuf)) { | ||
| 502 | + snprintf(err, errsz, | ||
| 503 | + "Access to private or reserved address space is not allowed. " | ||
| 504 | + "The hostname '%s' resolves to a denied address (%s).", | ||
| 505 | + host, ipbuf); | ||
| 506 | + freeaddrinfo(res); | ||
| 507 | + return -1; | ||
| 508 | + } | ||
| 509 | + } | ||
| 510 | + if (naddr == 0) { | ||
| 511 | + snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); | ||
| 512 | + freeaddrinfo(res); | ||
| 513 | + return -1; | ||
| 514 | + } | ||
| 515 | + /* Pick the first answer; it is validated, and we connect to its numbers. */ | ||
| 516 | + for (ai = res; ai; ai = ai->ai_next) { | ||
| 517 | + if (ai->ai_family == AF_INET) { | ||
| 518 | + out->family = AF_INET; | ||
| 519 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | ||
| 520 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | ||
| 521 | + found = 0; | ||
| 522 | + break; | ||
| 523 | + } | ||
| 524 | + if (ai->ai_family == AF_INET6) { | ||
| 525 | + out->family = AF_INET6; | ||
| 526 | + memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16); | ||
| 527 | + inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text); | ||
| 528 | + found = 0; | ||
| 529 | + /* prefer v4 but keep v6 if it came first */ | ||
| 530 | + if (0) break; | ||
| 531 | + } | ||
| 532 | + } | ||
| 533 | + /* second pass: prefer IPv4 if present */ | ||
| 534 | + if (found == 0) { | ||
| 535 | + for (ai = res; ai; ai = ai->ai_next) { | ||
| 536 | + if (ai->ai_family == AF_INET) { | ||
| 537 | + out->family = AF_INET; | ||
| 538 | + memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); | ||
| 539 | + inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); | ||
| 540 | + break; | ||
| 541 | + } | ||
| 542 | + } | ||
| 543 | + } | ||
| 544 | + freeaddrinfo(res); | ||
| 545 | + if (found != 0) { | ||
| 546 | + snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); | ||
| 547 | + return -1; | ||
| 548 | + } | ||
| 549 | + return 0; | ||
| 550 | +} | ||
| 551 | + | ||
| 552 | +#if !defined(_WIN32) | ||
| 553 | + | ||
| 554 | +/* ------------------------------------------------------------------ */ | ||
| 555 | +/* POSIX transport */ | ||
| 556 | +/* ------------------------------------------------------------------ */ | ||
| 557 | + | ||
| 558 | +typedef struct { | ||
| 559 | + sx_sock fd; | ||
| 560 | + fx_tls *tls; | ||
| 561 | + long long deadline_ms; | ||
| 562 | +} sx_trans; | ||
| 563 | + | ||
| 564 | + | ||
| 565 | +static int connect_timeout(int fd, const struct sockaddr *sa, socklen_t slen, | ||
| 566 | + int ms, char *err, size_t errsz) | ||
| 567 | +{ | ||
| 568 | + int flags, rc, soerr = 0; | ||
| 569 | + socklen_t elen = sizeof soerr; | ||
| 570 | + struct pollfd pfd; | ||
| 571 | + | ||
| 572 | + flags = fcntl(fd, F_GETFL, 0); | ||
| 573 | + if (flags < 0) return -1; | ||
| 574 | + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) return -1; | ||
| 575 | + rc = connect(fd, sa, slen); | ||
| 576 | + if (rc != 0) { | ||
| 577 | + if (errno != EINPROGRESS) { | ||
| 578 | + snprintf(err, errsz, "connect failed: %s", strerror(errno)); | ||
| 579 | + return -1; | ||
| 580 | + } | ||
| 581 | + pfd.fd = fd; | ||
| 582 | + pfd.events = POLLOUT; | ||
| 583 | + pfd.revents = 0; | ||
| 584 | + do { rc = poll(&pfd, 1, ms); } while (rc < 0 && errno == EINTR); | ||
| 585 | + if (rc == 0) { snprintf(err, errsz, "connect timed out"); return -1; } | ||
| 586 | + if (rc < 0) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; } | ||
| 587 | + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &elen) != 0 || soerr != 0) { | ||
| 588 | + snprintf(err, errsz, "connect failed: %s", | ||
| 589 | + strerror(soerr ? soerr : ECONNREFUSED)); | ||
| 590 | + return -1; | ||
| 591 | + } | ||
| 592 | + } | ||
| 593 | + if (fcntl(fd, F_SETFL, flags) < 0) return -1; | ||
| 594 | + return 0; | ||
| 595 | +} | ||
| 596 | + | ||
| 597 | +static int trans_read(sx_trans *t, char *buf, size_t n) | ||
| 598 | +{ | ||
| 599 | + if (t->tls) return fx_tls_read(t->tls, buf, n); | ||
| 600 | + for (;;) { | ||
| 601 | + ssize_t r; | ||
| 602 | + struct pollfd pfd; | ||
| 603 | + long long remain = t->deadline_ms - fx_now_ms(); | ||
| 604 | + int waited; | ||
| 605 | + if (remain <= 0) return -2; /* stalled: EOF-like */ | ||
| 606 | + pfd.fd = t->fd; | ||
| 607 | + pfd.events = POLLIN; | ||
| 608 | + pfd.revents = 0; | ||
| 609 | + waited = (int)(remain > 500 ? 500 : remain); | ||
| 610 | + r = poll(&pfd, 1, waited); | ||
| 611 | + if (r < 0) { if (errno == EINTR) continue; return -1; } | ||
| 612 | + if (r == 0) continue; /* loop rechecks deadline */ | ||
| 613 | + if (!(pfd.revents & (POLLIN | POLLHUP | POLLERR))) continue; | ||
| 614 | + do { r = recv(t->fd, buf, n, 0); } while (r < 0 && errno == EINTR); | ||
| 615 | + if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; | ||
| 616 | + if (r < 0) return -1; | ||
| 617 | + if (r == 0) return 0; /* EOF */ | ||
| 618 | + return (int)r; | ||
| 619 | + } | ||
| 620 | +} | ||
| 621 | + | ||
| 622 | +static int trans_write(sx_trans *t, const char *buf, size_t n) | ||
| 623 | +{ | ||
| 624 | + if (t->tls) return fx_tls_write(t->tls, buf, n); | ||
| 625 | + { | ||
| 626 | + size_t off = 0; | ||
| 627 | + while (off < n) { | ||
| 628 | + ssize_t w = send(t->fd, buf + off, n - off, MSG_NOSIGNAL); | ||
| 629 | + if (w < 0) { | ||
| 630 | + if (errno == EINTR) continue; | ||
| 631 | + return -1; | ||
| 632 | + } | ||
| 633 | + off += (size_t)w; | ||
| 634 | + } | ||
| 635 | + return (int)n; | ||
| 636 | + } | ||
| 637 | +} | ||
| 638 | + | ||
| 639 | +static void trans_close(sx_trans *t) | ||
| 640 | +{ | ||
| 641 | + if (t->tls) { fx_tls_close(t->tls); t->tls = NULL; } | ||
| 642 | + if (t->fd != SX_SOCK_INVALID) { sx_closesocket(t->fd); t->fd = SX_SOCK_INVALID; } | ||
| 643 | +} | ||
| 644 | + | ||
| 645 | +/* Reads the head; returns bytes consumed of the terminator inclusive, sets | ||
| 646 | + * head_len to the head length (before the terminator), *extra_out to body | ||
| 647 | + * bytes that arrived in the same window (0 — we always read exactly the | ||
| 648 | + * head window with a small overread stash). On hard failure, -1; on deadline, | ||
| 649 | + * -2. */ | ||
| 650 | +typedef struct { char *p; size_t n; size_t cap; } sx_stash; | ||
| 651 | + | ||
| 652 | +static int read_head(sx_trans *t, char *head, size_t cap, size_t *hlen_out, | ||
| 653 | + sx_stash *stash) | ||
| 654 | +{ | ||
| 655 | + size_t n = 0; | ||
| 656 | + size_t scanned = 0; | ||
| 657 | + for (;;) { | ||
| 658 | + size_t i; | ||
| 659 | + int r = trans_read(t, head + n, cap - n > 1024 ? 1024 : cap - n); | ||
| 660 | + if (r == -2) return n ? -1 : -2; | ||
| 661 | + if (r < 0) return -1; | ||
| 662 | + if (r == 0) { /* EOF */ | ||
| 663 | + if (n == 0) return -1; | ||
| 664 | + *hlen_out = n; /* no terminator: whole thing is head */ | ||
| 665 | + stash->p = NULL; stash->n = 0; | ||
| 666 | + return (int)n; | ||
| 667 | + } | ||
| 668 | + n += (size_t)r; | ||
| 669 | + if (n >= cap) return -1; /* oversized head */ | ||
| 670 | + /* scan for the terminator; the window may re-include up to 3 bytes | ||
| 671 | + * already scanned so a terminator split across two reads is found */ | ||
| 672 | + if (scanned > 3) scanned -= 3; | ||
| 673 | + for (i = scanned; i + 1 < n; i++) { | ||
| 674 | + if (head[i] == '\n') { | ||
| 675 | + size_t headlen; | ||
| 676 | + size_t term; | ||
| 677 | + if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && | ||
| 678 | + head[i - 3] == '\r') { | ||
| 679 | + headlen = i - 1; term = 4; | ||
| 680 | + } else if (i >= 1 && head[i - 1] == '\n') { | ||
| 681 | + headlen = i - 1; term = 2; /* tolerate bare \n\n */ | ||
| 682 | + } else continue; | ||
| 683 | + *hlen_out = headlen; | ||
| 684 | + if (n > i + 1) { | ||
| 685 | + stash->p = head + (i + 1); | ||
| 686 | + stash->n = n - (i + 1); | ||
| 687 | + } else { stash->p = NULL; stash->n = 0; } | ||
| 688 | + (void)term; | ||
| 689 | + return (int)n; | ||
| 690 | + } | ||
| 691 | + } | ||
| 692 | + scanned = n; | ||
| 693 | + } | ||
| 694 | +} | ||
| 695 | + | ||
| 696 | +static int exchange_plain(const fx_url *u, const char *urltext, fx_response *r, | ||
| 697 | + int allow_private) | ||
| 698 | +{ | ||
| 699 | + sx_trans t; | ||
| 700 | + fx_target tgt; | ||
| 701 | + char req[4300]; | ||
| 702 | + char *head; | ||
| 703 | + size_t head_len = 0; | ||
| 704 | + sx_stash stash; | ||
| 705 | + const char *v; size_t vl; | ||
| 706 | + buf_t body; | ||
| 707 | + long long clen = -1; | ||
| 708 | + int chunked = 0, gzip = 0; | ||
| 709 | + int status, fd, rc; | ||
| 710 | + struct sockaddr_storage ss; | ||
| 711 | + socklen_t slen; | ||
| 712 | + const char *UA = | ||
| 713 | + "SCORPIOXBOT-fetch/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch)"; | ||
| 714 | + int host_has_port = !((strcmp(u->scheme, "http") == 0 && u->port == 80) || | ||
| 715 | + (strcmp(u->scheme, "https") == 0 && u->port == 443)); | ||
| 716 | + | ||
| 717 | + memset(&t, 0, sizeof t); | ||
| 718 | + t.fd = SX_SOCK_INVALID; | ||
| 719 | + t.deadline_ms = fx_now_ms() + FX_CONNECT_MS + FX_READ_MS; | ||
| 720 | + | ||
| 721 | + if (fx_resolve_validate(u->host, u->port, allow_private, &tgt, | ||
| 722 | + r->error, sizeof r->error) != 0) | ||
| 723 | + return -1; | ||
| 724 | + | ||
| 725 | + fd = socket(tgt.family, SOCK_STREAM, 0); | ||
| 726 | + if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; } | ||
| 727 | + memset(&ss, 0, sizeof ss); | ||
| 728 | + if (tgt.family == AF_INET) { | ||
| 729 | + struct sockaddr_in *sa = (struct sockaddr_in *)&ss; | ||
| 730 | + sa->sin_family = AF_INET; | ||
| 731 | + sa->sin_port = htons((unsigned short)u->port); | ||
| 732 | + memcpy(&sa->sin_addr, tgt.ip, 4); | ||
| 733 | + slen = sizeof *sa; | ||
| 734 | + } else { | ||
| 735 | + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss; | ||
| 736 | + sa->sin6_family = AF_INET6; | ||
| 737 | + sa->sin6_port = htons((unsigned short)u->port); | ||
| 738 | + memcpy(&sa->sin6_addr, tgt.ip, 16); | ||
| 739 | + slen = sizeof *sa; | ||
| 740 | + } | ||
| 741 | + if (connect_timeout(fd, (struct sockaddr *)&ss, slen, FX_CONNECT_MS, | ||
| 742 | + r->error, sizeof r->error) != 0) { | ||
| 743 | + close(fd); | ||
| 744 | + return -1; | ||
| 745 | + } | ||
| 746 | + t.fd = fd; | ||
| 747 | + | ||
| 748 | + if (strcmp(u->scheme, "https") == 0) { | ||
| 749 | + char terr[256] = ""; | ||
| 750 | + t.tls = fx_tls_connect_fd(t.fd, u->host, terr, sizeof terr); | ||
| 751 | + if (!t.tls) { | ||
| 752 | + snprintf(r->error, sizeof r->error, "%s", | ||
| 753 | + terr[0] ? terr : "TLS handshake failed"); | ||
| 754 | + close(t.fd); | ||
| 755 | + t.fd = SX_SOCK_INVALID; | ||
| 756 | + return -1; | ||
| 757 | + } | ||
| 758 | + t.fd = SX_SOCK_INVALID; /* owned by the TLS layer now */ | ||
| 759 | + } | ||
| 760 | + | ||
| 761 | + snprintf(req, sizeof req, | ||
| 762 | + "GET %s HTTP/1.1\r\n" | ||
| 763 | + "Host: %s%s%s\r\n" | ||
| 764 | + "User-Agent: %s\r\n" | ||
| 765 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | ||
| 766 | + "Accept-Encoding: identity\r\n" | ||
| 767 | + "Connection: close\r\n\r\n", | ||
| 768 | + u->path, u->host, host_has_port ? ":" : "", | ||
| 769 | + host_has_port ? "" : "", UA); | ||
| 770 | + if (host_has_port) { | ||
| 771 | + snprintf(req, sizeof req, | ||
| 772 | + "GET %s HTTP/1.1\r\n" | ||
| 773 | + "Host: %s:%d\r\n" | ||
| 774 | + "User-Agent: %s\r\n" | ||
| 775 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | ||
| 776 | + "Accept-Encoding: identity\r\n" | ||
| 777 | + "Connection: close\r\n\r\n", | ||
| 778 | + u->path, u->host, u->port, UA); | ||
| 779 | + } | ||
| 780 | + if (trans_write(&t, req, strlen(req)) < 0) { | ||
| 781 | + snprintf(r->error, sizeof r->error, | ||
| 782 | + "Failed to fetch %s: the server did not accept our request", urltext); | ||
| 783 | + trans_close(&t); | ||
| 784 | + return -1; | ||
| 785 | + } | ||
| 786 | + | ||
| 787 | + head = (char *)sx_malloc(FX_MAX_HEAD + 1); | ||
| 788 | + rc = read_head(&t, head, FX_MAX_HEAD, &head_len, &stash); | ||
| 789 | + if (rc < 0) { | ||
| 790 | + snprintf(r->error, sizeof r->error, rc == -2 | ||
| 791 | + ? "Failed to fetch %s: timed out reading the response head" | ||
| 792 | + : "Failed to fetch %s: bad or oversized response head", urltext); | ||
| 793 | + free(head); | ||
| 794 | + trans_close(&t); | ||
| 795 | + return -1; | ||
| 796 | + } | ||
| 797 | + head[head_len] = '\0'; | ||
| 798 | + | ||
| 799 | + if (strncmp(head, "HTTP/", 5) != 0) { | ||
| 800 | + snprintf(r->error, sizeof r->error, | ||
| 801 | + "Failed to fetch %s: not an HTTP response", urltext); | ||
| 802 | + free(head); | ||
| 803 | + trans_close(&t); | ||
| 804 | + return -1; | ||
| 805 | + } | ||
| 806 | + status = atoi(head + 9); | ||
| 807 | + r->status = status; | ||
| 808 | + | ||
| 809 | + if (head_field(head, head_len, "content-type", &v, &vl)) { | ||
| 810 | + size_t n = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; | ||
| 811 | + memcpy(r->content_type, v, n); | ||
| 812 | + r->content_type[n] = '\0'; | ||
| 813 | + } | ||
| 814 | + { | ||
| 815 | + char nbuf[32]; | ||
| 816 | + if (head_field(head, head_len, "content-length", &v, &vl)) { | ||
| 817 | + size_t n = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; | ||
| 818 | + memcpy(nbuf, v, n); nbuf[n] = '\0'; | ||
| 819 | + clen = atoll(nbuf); | ||
| 820 | + if (clen > (long long)FX_MAX_BODY) { | ||
| 821 | + snprintf(r->error, sizeof r->error, | ||
| 822 | + "Failed to fetch %s: the response body is larger than the " | ||
| 823 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | ||
| 824 | + free(head); | ||
| 825 | + trans_close(&t); | ||
| 826 | + return -1; | ||
| 827 | + } | ||
| 828 | + } | ||
| 829 | + if (head_field(head, head_len, "transfer-encoding", &v, &vl) && | ||
| 830 | + vl >= 7 && sx_strncasecmp(v, "chunked", 7) == 0) | ||
| 831 | + chunked = 1; | ||
| 832 | +#ifdef HAVE_ZLIB | ||
| 833 | + if (head_field(head, head_len, "content-encoding", &v, &vl) && | ||
| 834 | + vl >= 4 && sx_strncasecmp(v, "gzip", 4) == 0) | ||
| 835 | + gzip = 1; | ||
| 836 | +#else | ||
| 837 | + if (head_field(head, head_len, "content-encoding", &v, &vl) && vl) { | ||
| 838 | + char enc[64]; | ||
| 839 | + size_t n = vl < sizeof enc - 1 ? vl : sizeof enc - 1; | ||
| 840 | + memcpy(enc, v, n); enc[n] = '\0'; | ||
| 841 | + if (sx_strcasecmp(enc, "identity") != 0) { | ||
| 842 | + snprintf(r->error, sizeof r->error, | ||
| 843 | + "Unsupported content encoding %s: this server cannot decode it", | ||
| 844 | + enc); | ||
| 845 | + free(head); | ||
| 846 | + trans_close(&t); | ||
| 847 | + return -1; | ||
| 848 | + } | ||
| 849 | + } | ||
| 850 | +#endif | ||
| 851 | + } | ||
| 852 | + | ||
| 853 | + if ((status == 301 || status == 302 || status == 303 || | ||
| 854 | + status == 307 || status == 308) && | ||
| 855 | + head_field(head, head_len, "location", &v, &vl)) { | ||
| 856 | + size_t n = vl < sizeof r->url - 1 ? vl : sizeof r->url - 1; | ||
| 857 | + memcpy(r->url, v, n); | ||
| 858 | + r->url[n] = '\0'; | ||
| 859 | + free(head); | ||
| 860 | + trans_close(&t); | ||
| 861 | + return 2; | ||
| 862 | + } | ||
| 863 | + | ||
| 864 | + buf_init(&body); | ||
| 865 | + fx_md_set_base_url(urltext); /* relativise links during conversion */ | ||
| 866 | + | ||
| 867 | + if (chunked) { | ||
| 868 | + /* stream chunk framing directly; bytes that arrived in the same read | ||
| 869 | + * window as the head terminator seed the framing buffer (they are | ||
| 870 | + * chunk data, NOT body — appending them raw would emit the hex size | ||
| 871 | + * line as content) */ | ||
| 872 | + char small[4096]; | ||
| 873 | + size_t sp = 0, sn = 0; | ||
| 874 | + int dead = 0; | ||
| 875 | + if (stash.n) { memcpy(small, stash.p, stash.n); sn = stash.n; } | ||
| 876 | +#define CHUNK_GETC(ch) \ | ||
| 877 | + do { \ | ||
| 878 | + int _done = 0; \ | ||
| 879 | + while (!_done) { \ | ||
| 880 | + if (sp < sn) { (ch) = small[sp++]; _done = 1; break; } \ | ||
| 881 | + { \ | ||
| 882 | + int _r = trans_read(&t, small, sizeof small); \ | ||
| 883 | + if (_r == 0) { dead = 1; _done = 1; break; } \ | ||
| 884 | + if (_r < 0) { dead = -1; _done = 1; break; } \ | ||
| 885 | + sn = (size_t)_r; sp = 0; \ | ||
| 886 | + } \ | ||
| 887 | + } \ | ||
| 888 | + } while (0) | ||
| 889 | + for (;;) { | ||
| 890 | + char ch = 0; | ||
| 891 | + char hex[24]; | ||
| 892 | + size_t hn = 0; | ||
| 893 | + unsigned long csz; | ||
| 894 | + CHUNK_GETC(ch); | ||
| 895 | + if (dead) break; | ||
| 896 | + if (ch == '\r' || ch == '\n') continue; /* skip CRLFs between chunks */ | ||
| 897 | + hex[hn++] = ch; | ||
| 898 | + while (hn < sizeof hex - 1) { | ||
| 899 | + CHUNK_GETC(ch); | ||
| 900 | + if (dead) break; | ||
| 901 | + if (ch == '\r') { CHUNK_GETC(ch); if (dead) break; if (ch == '\n') break; } | ||
| 902 | + else if (ch == '\n') break; | ||
| 903 | + hex[hn++] = ch; | ||
| 904 | + } | ||
| 905 | + if (dead) break; | ||
| 906 | + hex[hn] = '\0'; | ||
| 907 | + { char *semi = strchr(hex, ';'); if (semi) *semi = '\0'; } | ||
| 908 | + csz = strtoul(hex, NULL, 16); | ||
| 909 | + if (csz == 0) break; | ||
| 910 | + if (body.n + csz > FX_MAX_BODY) { | ||
| 911 | + buf_free(&body); free(head); trans_close(&t); | ||
| 912 | + snprintf(r->error, sizeof r->error, | ||
| 913 | + "Failed to fetch %s: the response body is larger than the " | ||
| 914 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | ||
| 915 | + return -1; | ||
| 916 | + } | ||
| 917 | + while (csz > 0) { | ||
| 918 | + size_t take; | ||
| 919 | + if (sp >= sn) { | ||
| 920 | + int _r = trans_read(&t, small, sizeof small); | ||
| 921 | + if (_r <= 0) { | ||
| 922 | + buf_free(&body); free(head); trans_close(&t); | ||
| 923 | + snprintf(r->error, sizeof r->error, | ||
| 924 | + "Failed to fetch %s: truncated chunked body", urltext); | ||
| 925 | + return -1; | ||
| 926 | + } | ||
| 927 | + sn = (size_t)_r; sp = 0; | ||
| 928 | + } | ||
| 929 | + take = sn - sp; | ||
| 930 | + if (take > csz) take = csz; | ||
| 931 | + buf_bput(&body, small + sp, take); | ||
| 932 | + sp += take; csz -= take; | ||
| 933 | + } | ||
| 934 | + } | ||
| 935 | +#undef CHUNK_GETC | ||
| 936 | + } else if (clen >= 0) { | ||
| 937 | + size_t want = (size_t)clen; | ||
| 938 | + if (stash.n) buf_bput(&body, stash.p, stash.n); | ||
| 939 | + if (want > body.n) { | ||
| 940 | + size_t need = want - body.n; | ||
| 941 | + char *tmp = (char *)sx_malloc(need); | ||
| 942 | + size_t got = 0; | ||
| 943 | + while (got < need) { | ||
| 944 | + int rr = trans_read(&t, tmp + got, need - got); | ||
| 945 | + if (rr <= 0) { | ||
| 946 | + free(tmp); buf_free(&body); free(head); trans_close(&t); | ||
| 947 | + snprintf(r->error, sizeof r->error, | ||
| 948 | + "Failed to fetch %s: the server closed before the " | ||
| 949 | + "declared body was complete", urltext); | ||
| 950 | + return -1; | ||
| 951 | + } | ||
| 952 | + got += (size_t)rr; | ||
| 953 | + } | ||
| 954 | + buf_bput(&body, tmp, need); | ||
| 955 | + free(tmp); | ||
| 956 | + } | ||
| 957 | + } else { | ||
| 958 | + char tmp[8192]; | ||
| 959 | + if (stash.n) buf_bput(&body, stash.p, stash.n); | ||
| 960 | + for (;;) { | ||
| 961 | + int rr = trans_read(&t, tmp, sizeof tmp); | ||
| 962 | + if (rr == -2 || rr == 0) break; | ||
| 963 | + if (rr < 0) { | ||
| 964 | + buf_free(&body); free(head); trans_close(&t); | ||
| 965 | + snprintf(r->error, sizeof r->error, | ||
| 966 | + "Failed to fetch %s: body read failed", urltext); | ||
| 967 | + return -1; | ||
| 968 | + } | ||
| 969 | + if (body.n + (size_t)rr > FX_MAX_BODY) { | ||
| 970 | + buf_free(&body); free(head); trans_close(&t); | ||
| 971 | + snprintf(r->error, sizeof r->error, | ||
| 972 | + "Failed to fetch %s: the response body is larger than the " | ||
| 973 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | ||
| 974 | + return -1; | ||
| 975 | + } | ||
| 976 | + buf_bput(&body, tmp, (size_t)rr); | ||
| 977 | + } | ||
| 978 | + } | ||
| 979 | + | ||
| 980 | + free(head); | ||
| 981 | + trans_close(&t); | ||
| 982 | + | ||
| 983 | +#ifdef HAVE_ZLIB | ||
| 984 | + if (gzip && body.n > 18 && (unsigned char)body.p[0] == 0x1f && | ||
| 985 | + (unsigned char)body.p[1] == 0x8b) { | ||
| 986 | + uLongf cap = (uLongf)(body.n * 16 + 4096); | ||
| 987 | + int inflated = 0; | ||
| 988 | + while (!inflated && cap <= FX_MAX_BODY) { | ||
| 989 | + char *outb = (char *)sx_malloc(cap + 1); | ||
| 990 | + z_stream zs; | ||
| 991 | + int zr; | ||
| 992 | + memset(&zs, 0, sizeof zs); | ||
| 993 | + zs.next_in = (Bytef *)body.p; | ||
| 994 | + zs.avail_in = (uInt)body.n; | ||
| 995 | + zs.next_out = (Bytef *)outb; | ||
| 996 | + zs.avail_out = (uInt)cap; | ||
| 997 | + zr = inflateInit2(&zs, 15 + 16); | ||
| 998 | + if (zr == Z_OK) zr = inflate(&zs, Z_FINISH); | ||
| 999 | + if (zr == Z_STREAM_END) { | ||
| 1000 | + free(body.p); | ||
| 1001 | + body.p = outb; | ||
| 1002 | + body.n = (size_t)zs.total_out; | ||
| 1003 | + body.p[body.n] = '\0'; | ||
| 1004 | + inflated = 1; | ||
| 1005 | + } else { | ||
| 1006 | + free(outb); | ||
| 1007 | + cap *= 4; | ||
| 1008 | + } | ||
| 1009 | + inflateEnd(&zs); | ||
| 1010 | + } | ||
| 1011 | + /* if it never inflated, keep the raw bytes: they are still an honest | ||
| 1012 | + * answer for a server that mislabelled its payload */ | ||
| 1013 | + } | ||
| 1014 | +#else | ||
| 1015 | + (void)gzip; | ||
| 1016 | +#endif | ||
| 1017 | + | ||
| 1018 | + r->body = body.p ? body.p : fx_strndup("", 0); | ||
| 1019 | + r->body_len = body.n; | ||
| 1020 | + return 0; | ||
| 1021 | +} | ||
| 1022 | + | ||
| 1023 | +#endif /* !_WIN32 */ | ||
| 1024 | + | ||
| 1025 | +/* ------------------------------------------------------------------ */ | ||
| 1026 | +/* WinHTTP transport */ | ||
| 1027 | +/* ------------------------------------------------------------------ */ | ||
| 1028 | + | ||
| 1029 | +#if defined(_WIN32) | ||
| 1030 | + | ||
| 1031 | +static void a2w(const char *a, wchar_t *w, int wn) | ||
| 1032 | +{ | ||
| 1033 | + MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn); | ||
| 1034 | +} | ||
| 1035 | + | ||
| 1036 | +static int exchange_winhttp(const fx_url *u, const char *urltext, fx_response *r, | ||
| 1037 | + int allow_private) | ||
| 1038 | +{ | ||
| 1039 | + HINTERNET sess = NULL, conn = NULL, req = NULL; | ||
| 1040 | + wchar_t wtarget[1024], wpath[2100]; | ||
| 1041 | + fx_target tgt; | ||
| 1042 | + char target_ip[64]; | ||
| 1043 | + wchar_t whdr[128]; | ||
| 1044 | + DWORD avail = 0; | ||
| 1045 | + BOOL ok; | ||
| 1046 | + buf_t body; | ||
| 1047 | + int status = 0; | ||
| 1048 | + | ||
| 1049 | + if (fx_resolve_validate(u->host, u->port, allow_private, &tgt, | ||
| 1050 | + r->error, sizeof r->error) != 0) | ||
| 1051 | + return -1; | ||
| 1052 | + snprintf(target_ip, sizeof target_ip, "%s", tgt.text); | ||
| 1053 | + | ||
| 1054 | + sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0", | ||
| 1055 | + WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, | ||
| 1056 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | ||
| 1057 | + if (!sess) | ||
| 1058 | + sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0", | ||
| 1059 | + WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, | ||
| 1060 | + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); | ||
| 1061 | + if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; } | ||
| 1062 | + WinHttpSetTimeouts(sess, FX_CONNECT_MS, FX_CONNECT_MS, FX_READ_MS, FX_READ_MS); | ||
| 1063 | + | ||
| 1064 | + /* connect to the validated numeric IP; Host + SNI carry the real name */ | ||
| 1065 | + a2w(target_ip, wtarget, 1024); | ||
| 1066 | + a2w(u->path, wpath, 2100); | ||
| 1067 | + | ||
| 1068 | + conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); | ||
| 1069 | + if (!conn) { | ||
| 1070 | + snprintf(r->error, sizeof r->error, "Failed to connect to %s", u->host); | ||
| 1071 | + WinHttpCloseHandle(sess); | ||
| 1072 | + return -1; | ||
| 1073 | + } | ||
| 1074 | + { | ||
| 1075 | + DWORD flags = strcmp(u->scheme, "https") == 0 ? WINHTTP_FLAG_SECURE : 0; | ||
| 1076 | + req = WinHttpOpenRequest(conn, L"GET", wpath, NULL, WINHTTP_NO_REFERER, | ||
| 1077 | + WINHTTP_DEFAULT_ACCEPT_TYPES, flags); | ||
| 1078 | + } | ||
| 1079 | + if (!req) { | ||
| 1080 | + snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed"); | ||
| 1081 | + WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1082 | + return -1; | ||
| 1083 | + } | ||
| 1084 | + { | ||
| 1085 | + DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | | ||
| 1086 | + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; | ||
| 1087 | + WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec); | ||
| 1088 | + } | ||
| 1089 | + { | ||
| 1090 | + DWORD pol = WINHTTP_REDIRECT_POLICY_NONE; | ||
| 1091 | + WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); | ||
| 1092 | + } | ||
| 1093 | + { | ||
| 1094 | + wchar_t wh[640]; | ||
| 1095 | + char hs[520]; | ||
| 1096 | + int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; | ||
| 1097 | + if (u->port != defport) | ||
| 1098 | + snprintf(hs, sizeof hs, | ||
| 1099 | + "Host: %s:%d\r\n" | ||
| 1100 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | ||
| 1101 | + "Accept-Encoding: identity\r\n", | ||
| 1102 | + u->host, u->port); | ||
| 1103 | + else | ||
| 1104 | + snprintf(hs, sizeof hs, | ||
| 1105 | + "Host: %s\r\n" | ||
| 1106 | + "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" | ||
| 1107 | + "Accept-Encoding: identity\r\n", | ||
| 1108 | + u->host); | ||
| 1109 | + a2w(hs, wh, 640); | ||
| 1110 | + WinHttpAddRequestHeaders(req, wh, (DWORD)-1, | ||
| 1111 | + WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); | ||
| 1112 | + } | ||
| 1113 | + | ||
| 1114 | + ok = WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, | ||
| 1115 | + WINHTTP_NO_REQUEST_DATA, 0, 0, 0); | ||
| 1116 | + if (!ok || !WinHttpReceiveResponse(req, NULL)) { | ||
| 1117 | + snprintf(r->error, sizeof r->error, | ||
| 1118 | + "Failed to fetch %s: TLS or connection error (certificate refused " | ||
| 1119 | + "or host unreachable)", urltext); | ||
| 1120 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1121 | + return -1; | ||
| 1122 | + } | ||
| 1123 | + | ||
| 1124 | + { | ||
| 1125 | + DWORD sz = sizeof status; | ||
| 1126 | + WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, | ||
| 1127 | + WINHTTP_HEADER_NAME_BY_INDEX, &status, &sz, | ||
| 1128 | + WINHTTP_NO_HEADER_INDEX); | ||
| 1129 | + r->status = (int)status; | ||
| 1130 | + } | ||
| 1131 | + { | ||
| 1132 | + wchar_t wct[256]; | ||
| 1133 | + DWORD sz = sizeof wct; | ||
| 1134 | + wct[0] = L'\0'; | ||
| 1135 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, | ||
| 1136 | + WINHTTP_HEADER_NAME_BY_INDEX, wct, &sz, | ||
| 1137 | + WINHTTP_NO_HEADER_INDEX)) | ||
| 1138 | + WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, | ||
| 1139 | + sizeof r->content_type, NULL, NULL); | ||
| 1140 | + } | ||
| 1141 | + if (r->status == 301 || r->status == 302 || r->status == 303 || | ||
| 1142 | + r->status == 307 || r->status == 308) { | ||
| 1143 | + wchar_t wloc[1024]; | ||
| 1144 | + DWORD sz = sizeof wloc; | ||
| 1145 | + wloc[0] = L'\0'; | ||
| 1146 | + a2w(L"Location", whdr, 128); | ||
| 1147 | + if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CUSTOM, whdr, wloc, &sz, | ||
| 1148 | + WINHTTP_NO_HEADER_INDEX)) { | ||
| 1149 | + WideCharToMultiByte(CP_UTF8, 0, wloc, -1, r->url, sizeof r->url, | ||
| 1150 | + NULL, NULL); | ||
| 1151 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1152 | + return 2; | ||
| 1153 | + } | ||
| 1154 | + } | ||
| 1155 | + | ||
| 1156 | + buf_init(&body); | ||
| 1157 | + for (;;) { | ||
| 1158 | + if (!WinHttpQueryDataAvailable(req, &avail)) break; | ||
| 1159 | + if (avail == 0) break; | ||
| 1160 | + { | ||
| 1161 | + DWORD take = avail > 65536 ? 65536 : avail; | ||
| 1162 | + char *tmp; | ||
| 1163 | + DWORD rd = 0; | ||
| 1164 | + if (body.n + take > FX_MAX_BODY) { | ||
| 1165 | + buf_free(&body); | ||
| 1166 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1167 | + snprintf(r->error, sizeof r->error, | ||
| 1168 | + "Failed to fetch %s: the response body is larger than the " | ||
| 1169 | + "%u byte limit this plugin reads", urltext, FX_MAX_BODY); | ||
| 1170 | + return -1; | ||
| 1171 | + } | ||
| 1172 | + tmp = (char *)sx_malloc(take + 1); | ||
| 1173 | + if (!WinHttpReadData(req, tmp, take, &rd) || rd == 0) { free(tmp); break; } | ||
| 1174 | + tmp[rd] = '\0'; | ||
| 1175 | + buf_bput(&body, tmp, rd); | ||
| 1176 | + free(tmp); | ||
| 1177 | + } | ||
| 1178 | + } | ||
| 1179 | + | ||
| 1180 | + WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); | ||
| 1181 | + r->body = body.p ? body.p : fx_strndup("", 0); | ||
| 1182 | + r->body_len = body.n; | ||
| 1183 | + return 0; | ||
| 1184 | +} | ||
| 1185 | + | ||
| 1186 | +#endif /* _WIN32 */ | ||
| 1187 | + | ||
| 1188 | +/* ------------------------------------------------------------------ */ | ||
| 1189 | +/* fx_fetch — the redirect loop */ | ||
| 1190 | +/* ------------------------------------------------------------------ */ | ||
| 1191 | + | ||
| 1192 | +int fx_fetch(const char *url, fx_response *r) | ||
| 1193 | +{ | ||
| 1194 | + fx_url u; | ||
| 1195 | + char urltext[1100]; | ||
| 1196 | + int hops = 0; | ||
| 1197 | + int allow_private = 0; | ||
| 1198 | + const char *env; | ||
| 1199 | + | ||
| 1200 | + memset(r, 0, sizeof *r); | ||
| 1201 | + env = getenv("FETCH_ALLOW_PRIVATE"); | ||
| 1202 | + if (env && *env && strcmp(env, "0") != 0) allow_private = 1; | ||
| 1203 | + if (fx_policy_allow_private()) allow_private = 1; | ||
| 1204 | + | ||
| 1205 | + if (fx_url_parse(url, &u, r->error, sizeof r->error) != 0) return -1; | ||
| 1206 | + snprintf(r->first_url, sizeof r->first_url, "%s", url); | ||
| 1207 | + | ||
| 1208 | + for (;;) { | ||
| 1209 | + int rc; | ||
| 1210 | + fx_url_build(&u, urltext, sizeof urltext); | ||
| 1211 | + r->url[0] = '\0'; | ||
| 1212 | + free(r->body); | ||
| 1213 | + r->body = NULL; | ||
| 1214 | + r->body_len = 0; | ||
| 1215 | + r->content_type[0] = '\0'; | ||
| 1216 | + | ||
| 1217 | +#if defined(_WIN32) | ||
| 1218 | + rc = exchange_winhttp(&u, urltext, r, allow_private); | ||
| 1219 | +#else | ||
| 1220 | + rc = exchange_plain(&u, urltext, r, allow_private); | ||
| 1221 | +#endif | ||
| 1222 | + if (rc == 0) { | ||
| 1223 | + if (!r->url[0]) snprintf(r->url, sizeof r->url, "%s", urltext); | ||
| 1224 | + r->ok = 1; | ||
| 1225 | + r->hops = hops; | ||
| 1226 | + return 0; | ||
| 1227 | + } | ||
| 1228 | + if (rc == 2) { | ||
| 1229 | + if (++hops > FX_MAX_REDIRECTS) { | ||
| 1230 | + snprintf(r->error, sizeof r->error, | ||
| 1231 | + "Exceeded maximum allowed redirects."); | ||
| 1232 | + return -1; | ||
| 1233 | + } | ||
| 1234 | + /* Absolute-ise the Location against the CURRENT url: a bare | ||
| 1235 | + * "relative" resolves against the directory of the current path, | ||
| 1236 | + * "/abs" against the authority, and anything carrying "://" is | ||
| 1237 | + * already absolute. fx_url_resolve is the single place that owns | ||
| 1238 | + * those rules. Every hop then re-enters the same | ||
| 1239 | + * parse/resolve/validate path, so each new address is SSRF | ||
| 1240 | + * checked before it is connected to. */ | ||
| 1241 | + { | ||
| 1242 | + fx_url next; | ||
| 1243 | + if (fx_url_resolve(&u, r->url, &next, r->error, | ||
| 1244 | + sizeof r->error) != 0) | ||
| 1245 | + return -1; | ||
| 1246 | + u = next; | ||
| 1247 | + } | ||
| 1248 | + continue; | ||
| 1249 | + } | ||
| 1250 | + return -1; | ||
| 1251 | + } | ||
| 1252 | +} | ||
| 1253 | + | ||
| 1254 | +void fx_response_free(fx_response *r) | ||
| 1255 | +{ | ||
| 1256 | + if (!r) return; | ||
| 1257 | + free(r->body); | ||
| 1258 | + r->body = NULL; | ||
| 1259 | + r->body_len = 0; | ||
| 1260 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6432c2d | index 0000000..6432c2d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_http.h | +++ b/src/fetch_http.h | ||
| @@ -0,0 +1,63 @@ | @@ -0,0 +1,63 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_http.h - URL parse + SSRF policy + HTTP/HTTPS GET with redirects. | ||
| 3 | + * | ||
| 4 | + * One GET exchange (no keep-alive; Connection: close), up to 5 redirects. | ||
| 5 | + * Every hop (and every resolved address of every hop) is checked against the | ||
| 6 | + * private/special-purpose denylist BEFORE connect, and the socket is then | ||
| 7 | + * connected to that exact validated address, so DNS cannot answer a different | ||
| 8 | + * (private) IP between the check and the connect (DNS-rebinding defence). | ||
| 9 | + * | ||
| 10 | + * TLS on POSIX: vendored mbedTLS over our own sockets, VERIFY_PEER against a | ||
| 11 | + * CA bundle (FETCH_TLS_CA_FILE, else the first system bundle found). There is | ||
| 12 | + * deliberately NO insecure bypass. On _WIN32 the whole HTTP leg goes through | ||
| 13 | + * WinHTTP (system root store). | ||
| 14 | + * | ||
| 15 | + * Implementation in fetch_http.c (+ fetch_tls.c for the mbedTLS BIO layer). | ||
| 16 | + */ | ||
| 17 | +#ifndef SX_FETCH_HTTP_H | ||
| 18 | +#define SX_FETCH_HTTP_H | ||
| 19 | + | ||
| 20 | +#include <stddef.h> | ||
| 21 | + | ||
| 22 | +#include "sxbuf.h" | ||
| 23 | + | ||
| 24 | +/* Hard cap on the response body we are willing to read, like upstream's | ||
| 25 | + * MAX_RESPONSE_BYTES. A larger declared body is refused without reading it. */ | ||
| 26 | +#define FX_MAX_BODY (5u * 1024u * 1024u) | ||
| 27 | +#define FX_MAX_HEAD (64u * 1024u) | ||
| 28 | +#define FX_MAX_REDIRECTS 5 | ||
| 29 | +#define FX_CONNECT_MS 10000 | ||
| 30 | +#define FX_READ_MS 15000 | ||
| 31 | + | ||
| 32 | +typedef struct { | ||
| 33 | + int ok; /* 1 = response delivered */ | ||
| 34 | + char error[512]; | ||
| 35 | + int status; /* HTTP status of the final response */ | ||
| 36 | + char url[1024]; /* final URL after redirects */ | ||
| 37 | + char first_url[1024]; /* URL we were first asked for */ | ||
| 38 | + char content_type[128]; | ||
| 39 | + int hops; /* redirects followed */ | ||
| 40 | + char *body; /* heap, NUL-terminated */ | ||
| 41 | + size_t body_len; | ||
| 42 | +} fx_response; | ||
| 43 | + | ||
| 44 | +void fx_response_free(fx_response *r); | ||
| 45 | + | ||
| 46 | +/* Perform GET url (scheme http|https only). Returns 0 on success (response | ||
| 47 | + * fields filled) or -1 with r->error set. */ | ||
| 48 | +int fx_fetch(const char *url, fx_response *r); | ||
| 49 | + | ||
| 50 | +/* SSRF: returns 1 when `ip_text` (IPv4 or IPv6 in text form) is a private / | ||
| 51 | + * loopback / link-local / special-purpose address that must be refused, | ||
| 52 | + * 0 when public. Mirrors the upstream _NON_PUBLIC_NETWORKS list plus its | ||
| 53 | + * documented public exceptions. */ | ||
| 54 | +int fx_ip_is_denied(const char *ip_text); | ||
| 55 | + | ||
| 56 | +/* Whether a body with no declared Content-Type opens as an HTML document | ||
| 57 | + * (after BOM/whitespace: "<!doctype html" or "<html"). */ | ||
| 58 | +int fx_body_looks_like_html(const char *body, size_t len); | ||
| 59 | + | ||
| 60 | +/* Helper shared with fetch_md: heap copy + NUL terminate. */ | ||
| 61 | +char *fx_strndup(const char *s, size_t n); | ||
| 62 | + | ||
| 63 | +#endif /* SX_FETCH_HTTP_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..44167e5 | index 0000000..44167e5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_md.c | +++ b/src/fetch_md.c | ||
| @@ -0,0 +1,958 @@ | @@ -0,0 +1,958 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_md.c - forgiving HTML tokenizer -> clean Markdown. | ||
| 3 | + * | ||
| 4 | + * Clean-room implementation over raw bytes. UTF-8 passes through untouched; | ||
| 5 | + * entities are decoded. This is deliberately NOT a DOM: it is the subset a | ||
| 6 | + * fetch tool needs to take a page down to readable Markdown: | ||
| 7 | + * | ||
| 8 | + * - strips comment + script/style/noscript/svg/head/nav/aside/footer/form/ | ||
| 9 | + * template/button/select/textarea/iframe subtrees | ||
| 10 | + * - h1..h6 -> ATX headings | ||
| 11 | + * - a -> [text](href) (absolutised against the page URL) | ||
| 12 | + * - ul/ol/li -> "- " / "n. " with simple nesting | ||
| 13 | + * - pre/code -> fenced block / `code span` | ||
| 14 | + * - strong/b, em/i -> ** **, * * | ||
| 15 | + * - blockquote -> "> " lines | ||
| 16 | + * - table/tr/td/th -> pipe rows | ||
| 17 | + * - img ->  | ||
| 18 | + * - p/div/br/hr/section/article -> line breaks | ||
| 19 | + * - common entities + &#NNN; + &#xHH; | ||
| 20 | + */ | ||
| 21 | +#include "fetch_md.h" | ||
| 22 | +#include "sxbuf.h" | ||
| 23 | + | ||
| 24 | +#include <ctype.h> | ||
| 25 | +#include <stdlib.h> | ||
| 26 | +#include <string.h> | ||
| 27 | + | ||
| 28 | +/* ------------------------------------------------------------------ */ | ||
| 29 | +/* Tokenizer */ | ||
| 30 | +/* ------------------------------------------------------------------ */ | ||
| 31 | + | ||
| 32 | +typedef enum { TOK_TEXT, TOK_OPEN, TOK_CLOSE } tok_kind; | ||
| 33 | + | ||
| 34 | +typedef struct { | ||
| 35 | + tok_kind kind; | ||
| 36 | + char name[24]; /* lowercased tag name (close/open) */ | ||
| 37 | + char *text; /* TOK_TEXT: decoded text (heap) */ | ||
| 38 | + char *attrs; /* TOK_OPEN: raw attribute text */ | ||
| 39 | + int selfclose; | ||
| 40 | +} token; | ||
| 41 | + | ||
| 42 | +typedef struct { | ||
| 43 | + token *v; | ||
| 44 | + size_t n, cap; | ||
| 45 | +} toks; | ||
| 46 | + | ||
| 47 | +static void toks_push(toks *t, token *tok) | ||
| 48 | +{ | ||
| 49 | + if (t->n == t->cap) { | ||
| 50 | + size_t cap = t->cap ? t->cap * 2 : 256; | ||
| 51 | + token *nv = (token *)realloc(t->v, cap * sizeof *nv); | ||
| 52 | + if (!nv) { fputs("out of memory\n", stderr); exit(1); } | ||
| 53 | + t->v = nv; | ||
| 54 | + t->cap = cap; | ||
| 55 | + } | ||
| 56 | + t->v[t->n++] = *tok; | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +static void toks_free(toks *t) | ||
| 60 | +{ | ||
| 61 | + size_t i; | ||
| 62 | + for (i = 0; i < t->n; i++) { free(t->v[i].text); free(t->v[i].attrs); } | ||
| 63 | + free(t->v); | ||
| 64 | + t->v = NULL; | ||
| 65 | + t->n = t->cap = 0; | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/* ------------------------------------------------------------------ */ | ||
| 69 | +/* Entity decoding */ | ||
| 70 | +/* ------------------------------------------------------------------ */ | ||
| 71 | + | ||
| 72 | +static void utf8_put(buf_t *b, unsigned cp) | ||
| 73 | +{ | ||
| 74 | + if (cp < 0x80) { | ||
| 75 | + char c = (char)cp; | ||
| 76 | + buf_bput(b, &c, 1); | ||
| 77 | + } else if (cp < 0x800) { | ||
| 78 | + char c[2] = { (char)(0xC0 | (cp >> 6)), (char)(0x80 | (cp & 0x3F)) }; | ||
| 79 | + buf_bput(b, c, 2); | ||
| 80 | + } else if (cp < 0x10000) { | ||
| 81 | + char c[3] = { (char)(0xE0 | (cp >> 12)), (char)(0x80 | ((cp >> 6) & 0x3F)), | ||
| 82 | + (char)(0x80 | (cp & 0x3F)) }; | ||
| 83 | + buf_bput(b, c, 3); | ||
| 84 | + } else { | ||
| 85 | + char c[4] = { (char)(0xF0 | (cp >> 18)), (char)(0x80 | ((cp >> 12) & 0x3F)), | ||
| 86 | + (char)(0x80 | ((cp >> 6) & 0x3F)), (char)(0x80 | (cp & 0x3F)) }; | ||
| 87 | + buf_bput(b, c, 4); | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +typedef struct { const char *name; const char *utf8; } ent_map; | ||
| 92 | +static const ent_map ENTITIES[] = { | ||
| 93 | + { "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" }, | ||
| 94 | + { "apos", "'" }, { "nbsp", "\xC2\xA0" }, | ||
| 95 | + { "zwnj", "" }, { "zwj", "" }, { "lrm", "" }, | ||
| 96 | + { "rdquo", "\xE2\x80\x9D" }, { "ldquo", "\xE2\x80\x9C" }, | ||
| 97 | + { "sbquo", "\xE2\x80\x9A" }, { "bdquo", "\xE2\x80\x9E" }, | ||
| 98 | + { "mdash", "\xE2\x80\x94" }, { "ndash", "\xE2\x80\x93" }, | ||
| 99 | + { "hellip", "\xE2\x80\xA6" }, { "middot", "\xC2\xB7" }, | ||
| 100 | + { "bull", "\xE2\x80\xA2" }, { "deg", "\xC2\xB0" }, | ||
| 101 | + { "copy", "\xC2\xA9" }, { "reg", "\xC2\xAE" }, { "trade", "\xE2\x84\xA2" }, | ||
| 102 | + { "laquo", "\xC2\xAB" }, { "raquo", "\xC2\xBB" }, | ||
| 103 | + { "times", "\xC3\x97" }, { "divide", "\xC3\xB7" }, { "plusmn", "\xC2\xB1" }, | ||
| 104 | + { "frac12", "\xC2\xBD" }, { "frac14", "\xC2\xBC" }, { "frac34", "\xC2\xBE" }, | ||
| 105 | + { "sect", "\xC2\xA7" }, { "para", "\xC2\xB6" }, { "dagger", "\xE2\x80\xA0" }, | ||
| 106 | + { "permil", "\xE2\x80\xB0" }, { "euro", "\xE2\x82\xAC" }, | ||
| 107 | + { "pound", "\xC2\xA3" }, { "yen", "\xC2\xA5" }, { "cent", "\xC2\xA2" }, | ||
| 108 | + { "curren", "\xC2\xA4" }, { "cldquo", "\xE2\x80\x9C" }, | ||
| 109 | + { "lsquo", "\xE2\x80\x98" }, { "rsquo", "\xE2\x80\x99" }, | ||
| 110 | + { "ne", "\xE2\x89\xA0" }, { "le", "\xE2\x89\xA4" }, { "ge", "\xE2\x89\xA5" }, | ||
| 111 | + { "larr", "\xE2\x86\x90" }, { "rarr", "\xE2\x86\x92" }, | ||
| 112 | + { "uarr", "\xE2\x86\x91" }, { "darr", "\xE2\x86\x93" }, | ||
| 113 | + { "harr", "\xE2\x86\x94" }, { "minus", "\xE2\x88\x92" }, | ||
| 114 | + { "micro", "\xC2\xB5" }, { "sup2", "\xC2\xB2" }, { "sup3", "\xC2\xB3" }, | ||
| 115 | + { "sup1", "\xC2\xB9" }, { "prime", "\xE2\x80\xB2" }, | ||
| 116 | + { "check", "\xE2\x9C\x93" }, { "star", "\xE2\x98\x85" }, | ||
| 117 | + /* The Latin-1 supplement named entities: a page that writes café | ||
| 118 | + * (which plenty still do) has to read back as cafe with an accent, not | ||
| 119 | + * as the literal source text. */ | ||
| 120 | + { "eacute", "\xC3\xA9" }, { "egrave", "\xC3\xA8" }, | ||
| 121 | + { "ecirc", "\xC3\xAA" }, { "euml", "\xC3\xAF" }, | ||
| 122 | + { "aacute", "\xC3\xA1" }, { "agrave", "\xC3\xA0" }, | ||
| 123 | + { "acirc", "\xC3\xA2" }, { "auml", "\xC3\xA4" }, | ||
| 124 | + { "ocirc", "\xC3\xB4" }, { "oacute", "\xC3\xB3" }, | ||
| 125 | + { "ouml", "\xC3\xB6" }, { "ucirc", "\xC3\xBB" }, | ||
| 126 | + { "uacute", "\xC3\xBA" }, { "uuml", "\xC3\xBC" }, | ||
| 127 | + { "icirc", "\xC3\xAE" }, { "iacute", "\xC3\xAD" }, | ||
| 128 | + { "iuml", "\xC3\xAF" }, { "ccedil", "\xC3\xA7" }, | ||
| 129 | + { "ntilde", "\xC3\xB1" }, { "szlig", "\xC3\x9F" }, | ||
| 130 | + { "Aacute", "\xC3\x81" }, { "Eacute", "\xC3\x89" }, | ||
| 131 | + { "Uuml", "\xC3\x9C" }, { "Oslash", "\xC3\x98" }, | ||
| 132 | + { "divide", "\xC3\xB7" }, { "iquest", "\xC2\xBF" }, | ||
| 133 | + { "iexcl", "\xC2\xA1" }, { "brvbar", "\xC2\xA6" }, | ||
| 134 | + { "not", "\xC2\xAC" }, { "macr", "\xC2\xAF" }, | ||
| 135 | + { "acute", "\xC2\xB4" }, { "grave", "\xC2\x60" }, | ||
| 136 | + { "cedil", "\xC2\xB8" }, { "curren", "\xC2\xA4" }, | ||
| 137 | + { "frac13", "\xE2\x85\x93" }, { "line", "|" }, | ||
| 138 | + { "verbar", "|" }, { "brvbar", "\xC2\xA6" }, | ||
| 139 | + { "ensp", "\xE2\x80\x82" }, { "emsp", "\xE2\x80\x83" }, | ||
| 140 | + { "thinsp", "\xE2\x80\x89" }, { "shy", "" }, | ||
| 141 | + { "hearts", "\xE2\x99\xA5" }, { "spades", "\xE2\x99\xA0" }, | ||
| 142 | + { "clubs", "\xE2\x99\xA3" }, { "diams", "\xE2\x99\xA6" }, | ||
| 143 | + { NULL, NULL } | ||
| 144 | +}; | ||
| 145 | + | ||
| 146 | +static int entity_named(const char *name, size_t len, buf_t *out) | ||
| 147 | +{ | ||
| 148 | + int i; | ||
| 149 | + for (i = 0; ENTITIES[i].name; i++) | ||
| 150 | + if (strlen(ENTITIES[i].name) == len && | ||
| 151 | + strncmp(ENTITIES[i].name, name, len) == 0) { | ||
| 152 | + buf_add(out, ENTITIES[i].utf8); | ||
| 153 | + return 1; | ||
| 154 | + } | ||
| 155 | + return 0; | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +static void decode_entities(const char *s, size_t n, buf_t *out) | ||
| 159 | +{ | ||
| 160 | + size_t i = 0; | ||
| 161 | + while (i < n) { | ||
| 162 | + if (s[i] == '&') { | ||
| 163 | + const char *semi = (const char *)memchr(s + i, ';', n - i); | ||
| 164 | + if (semi && (size_t)(semi - (s + i)) < 12) { | ||
| 165 | + size_t len = (size_t)(semi - (s + i)) - 1; | ||
| 166 | + const char *nm = s + i + 1; | ||
| 167 | + if (len > 1 && nm[0] == '#') { | ||
| 168 | + unsigned cp = 0; | ||
| 169 | + int ok = 1; | ||
| 170 | + if (nm[1] == 'x' || nm[1] == 'X') { | ||
| 171 | + size_t j; | ||
| 172 | + for (j = 2; j < len; j++) { | ||
| 173 | + if (!isxdigit((unsigned char)nm[j])) { ok = 0; break; } | ||
| 174 | + cp = cp * 16 + (unsigned)(isdigit((unsigned char)nm[j]) | ||
| 175 | + ? nm[j] - '0' | ||
| 176 | + : (tolower((unsigned char)nm[j]) - 'a' + 10)); | ||
| 177 | + } | ||
| 178 | + } else { | ||
| 179 | + size_t j; | ||
| 180 | + for (j = 1; j < len; j++) { | ||
| 181 | + if (!isdigit((unsigned char)nm[j])) { ok = 0; break; } | ||
| 182 | + cp = cp * 10 + (unsigned)(nm[j] - '0'); | ||
| 183 | + } | ||
| 184 | + } | ||
| 185 | + if (ok && cp > 0 && cp <= 0x10FFFF) { | ||
| 186 | + if (cp >= 0xD800 && cp <= 0xDFFF) cp = 0xFFFD; | ||
| 187 | + utf8_put(out, cp); | ||
| 188 | + i += len + 2; | ||
| 189 | + continue; | ||
| 190 | + } | ||
| 191 | + } else if (len > 0) { | ||
| 192 | + /* named entities may arrive with mixed case */ | ||
| 193 | + char lower[12]; | ||
| 194 | + size_t j; | ||
| 195 | + for (j = 0; j < len && j < sizeof lower - 1; j++) | ||
| 196 | + lower[j] = (char)tolower((unsigned char)nm[j]); | ||
| 197 | + lower[j < len ? j : len] = '\0'; | ||
| 198 | + if (j <= len) { | ||
| 199 | + if (entity_named(lower, j, out)) { i += len + 2; continue; } | ||
| 200 | + if (entity_named(nm, len, out)) { i += len + 2; continue; } | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + buf_bput(out, s + i, 1); | ||
| 206 | + i++; | ||
| 207 | + } | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +#ifdef memmem | ||
| 211 | +#undef memmem | ||
| 212 | +#endif | ||
| 213 | +static const char *sx_memmem(const char *h, size_t hl, const char *n, size_t nl) | ||
| 214 | +{ | ||
| 215 | + size_t i; | ||
| 216 | + if (nl == 0 || hl < nl) return NULL; | ||
| 217 | + for (i = 0; i + nl <= hl; i++) | ||
| 218 | + if (memcmp(h + i, n, nl) == 0) return h + i; | ||
| 219 | + return NULL; | ||
| 220 | +} | ||
| 221 | +#define memmem sx_memmem | ||
| 222 | + | ||
| 223 | +/* ------------------------------------------------------------------ */ | ||
| 224 | +/* Tokenizer core */ | ||
| 225 | +/* ------------------------------------------------------------------ */ | ||
| 226 | + | ||
| 227 | +static int tag_skip(const char *name) | ||
| 228 | +{ | ||
| 229 | + static const char *const skip[] = { | ||
| 230 | + "script", "style", "noscript", "svg", "head", "nav", "aside", | ||
| 231 | + "footer", "form", "template", "button", "select", "textarea", | ||
| 232 | + "iframe", "canvas", "video", "audio", "picture", "map", "object", | ||
| 233 | + "embed", "link", "meta", NULL | ||
| 234 | + }; | ||
| 235 | + int i; | ||
| 236 | + for (i = 0; skip[i]; i++) if (strcmp(skip[i], name) == 0) return 1; | ||
| 237 | + return 0; | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +static void tokenize(const char *html, size_t len, toks *out) | ||
| 241 | +{ | ||
| 242 | + size_t i = 0; | ||
| 243 | + | ||
| 244 | + memset(out, 0, sizeof *out); /* cap/n must start at zero: toks_push grows from them */ | ||
| 245 | + buf_t text; | ||
| 246 | + buf_init(&text); | ||
| 247 | + | ||
| 248 | +#define FLUSH_TEXT() \ | ||
| 249 | + do { \ | ||
| 250 | + if (text.n) { \ | ||
| 251 | + token tk; \ | ||
| 252 | + memset(&tk, 0, sizeof tk); \ | ||
| 253 | + tk.kind = TOK_TEXT; \ | ||
| 254 | + tk.text = (char *)sx_malloc(text.n + 1); \ | ||
| 255 | + memcpy(tk.text, text.p, text.n); \ | ||
| 256 | + tk.text[text.n] = '\0'; \ | ||
| 257 | + toks_push(out, &tk); \ | ||
| 258 | + free(text.p); \ | ||
| 259 | + buf_init(&text); \ | ||
| 260 | + } \ | ||
| 261 | + } while (0) | ||
| 262 | + | ||
| 263 | + while (i < len) { | ||
| 264 | + if (html[i] == '<') { | ||
| 265 | + /* comment / CDATA / doctype */ | ||
| 266 | + if (i + 3 < len && html[i + 1] == '!' && html[i + 2] == '-' && | ||
| 267 | + html[i + 3] == '-') { | ||
| 268 | + const char *end = NULL; | ||
| 269 | + if (i + 4 < len) | ||
| 270 | + end = (const char *)memmem(html + i + 4, len - i - 4, "-->", 3); | ||
| 271 | + i = end ? (size_t)(end - html) + 3 : len; | ||
| 272 | + continue; | ||
| 273 | + } | ||
| 274 | + if (i + 1 < len && (html[i + 1] == '!' || html[i + 1] == '?')) { | ||
| 275 | + const char *gt = (const char *)memchr(html + i, '>', len - i); | ||
| 276 | + i = gt ? (size_t)(gt - html) + 1 : len; | ||
| 277 | + continue; | ||
| 278 | + } | ||
| 279 | + if (i + 1 < len && (isalpha((unsigned char)html[i + 1]) || | ||
| 280 | + html[i + 1] == '/')) { | ||
| 281 | + size_t j = i + 1; | ||
| 282 | + int closing = 0; | ||
| 283 | + char name[24]; | ||
| 284 | + size_t nl = 0; | ||
| 285 | + const char *attr_start; | ||
| 286 | + const char *gt; | ||
| 287 | + token tk; | ||
| 288 | + | ||
| 289 | + if (html[j] == '/') { closing = 1; j++; } | ||
| 290 | + while (j < len && (isalnum((unsigned char)html[j]) || html[j] == '-')) { | ||
| 291 | + if (nl < sizeof name - 1) | ||
| 292 | + name[nl++] = (char)tolower((unsigned char)html[j]); | ||
| 293 | + j++; | ||
| 294 | + } | ||
| 295 | + name[nl] = '\0'; | ||
| 296 | + if (nl == 0) { /* stray '<' as text */ | ||
| 297 | + buf_bput(&text, "<", 1); | ||
| 298 | + i++; | ||
| 299 | + continue; | ||
| 300 | + } | ||
| 301 | + attr_start = html + j; | ||
| 302 | + /* skip to the closing '>' respecting quoted values */ | ||
| 303 | + gt = html + j; | ||
| 304 | + while (gt < html + len) { | ||
| 305 | + if (*gt == '"' || *gt == '\'') { | ||
| 306 | + char q = *gt; | ||
| 307 | + gt++; | ||
| 308 | + while (gt < html + len && *gt != q) gt++; | ||
| 309 | + if (gt < html + len) gt++; | ||
| 310 | + } else if (*gt == '>') break; | ||
| 311 | + else gt++; | ||
| 312 | + } | ||
| 313 | + if (gt >= html + len) { /* unterminated tag: swallow rest */ | ||
| 314 | + i = len; | ||
| 315 | + continue; | ||
| 316 | + } | ||
| 317 | + FLUSH_TEXT(); | ||
| 318 | + memset(&tk, 0, sizeof tk); | ||
| 319 | + snprintf(tk.name, sizeof tk.name, "%s", name); | ||
| 320 | + if (closing) { | ||
| 321 | + tk.kind = TOK_CLOSE; | ||
| 322 | + } else { | ||
| 323 | + size_t alen = (size_t)(gt - attr_start); | ||
| 324 | + tk.kind = TOK_OPEN; | ||
| 325 | + tk.selfclose = (alen && attr_start[alen - 1] == '/'); | ||
| 326 | + if (tk.selfclose) alen--; | ||
| 327 | + /* trailing spaces */ | ||
| 328 | + while (alen && (unsigned char)attr_start[alen - 1] <= ' ') alen--; | ||
| 329 | + if (alen) { | ||
| 330 | + buf_t a; | ||
| 331 | + buf_init(&a); | ||
| 332 | + decode_entities(attr_start, alen, &a); | ||
| 333 | + tk.attrs = a.p ? a.p : (char *)sx_malloc(1); | ||
| 334 | + if (!a.p) tk.attrs[0] = '\0'; | ||
| 335 | + } | ||
| 336 | + } | ||
| 337 | + toks_push(out, &tk); | ||
| 338 | + i = (size_t)(gt - html) + 1; | ||
| 339 | + continue; | ||
| 340 | + } | ||
| 341 | + /* lone '<' */ | ||
| 342 | + buf_bput(&text, "<", 1); | ||
| 343 | + i++; | ||
| 344 | + continue; | ||
| 345 | + } | ||
| 346 | + { | ||
| 347 | + const char *lt = (const char *)memchr(html + i, '<', len - i); | ||
| 348 | + size_t n = lt ? (size_t)(lt - (html + i)) : len - i; | ||
| 349 | + decode_entities(html + i, n, &text); | ||
| 350 | + i += n; | ||
| 351 | + } | ||
| 352 | + } | ||
| 353 | + FLUSH_TEXT(); | ||
| 354 | +#undef FLUSH_TEXT | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/* ------------------------------------------------------------------ */ | ||
| 358 | +/* Attribute lookup */ | ||
| 359 | +/* ------------------------------------------------------------------ */ | ||
| 360 | + | ||
| 361 | +/* Find attr `key` in raw attribute text; unquotes + decodes into out. */ | ||
| 362 | +static int attr_get(const char *attrs, const char *key, char *out, size_t outsz) | ||
| 363 | +{ | ||
| 364 | + const char *p = attrs; | ||
| 365 | + size_t klen = strlen(key); | ||
| 366 | + out[0] = '\0'; | ||
| 367 | + if (!attrs) return 0; | ||
| 368 | + while (*p) { | ||
| 369 | + const char *eq; | ||
| 370 | + size_t alen; | ||
| 371 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 372 | + if (!*p) break; | ||
| 373 | + eq = p; | ||
| 374 | + while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++; | ||
| 375 | + alen = (size_t)(eq - p); | ||
| 376 | + if (alen == klen && sx_strncasecmp(p, key, klen) == 0 && *eq == '=') { | ||
| 377 | + const char *v = eq + 1; | ||
| 378 | + const char *ve; | ||
| 379 | + buf_t b; | ||
| 380 | + char raw[2048]; | ||
| 381 | + size_t rn = 0; | ||
| 382 | + while (*v && (unsigned char)*v <= ' ') v++; | ||
| 383 | + if (*v == '"' || *v == '\'') { | ||
| 384 | + char q = *v++; | ||
| 385 | + while (*v && *v != q && rn + 1 < sizeof raw) raw[rn++] = *v++; | ||
| 386 | + ve = v; | ||
| 387 | + } else { | ||
| 388 | + while (*v && (unsigned char)*v > ' ' && rn + 1 < sizeof raw) | ||
| 389 | + raw[rn++] = *v++; | ||
| 390 | + ve = v; | ||
| 391 | + } | ||
| 392 | + raw[rn] = '\0'; | ||
| 393 | + (void)ve; | ||
| 394 | + buf_init(&b); | ||
| 395 | + decode_entities(raw, rn, &b); | ||
| 396 | + if (b.p) { | ||
| 397 | + snprintf(out, outsz, "%s", b.p); | ||
| 398 | + free(b.p); | ||
| 399 | + } | ||
| 400 | + p = v; | ||
| 401 | + return 1; | ||
| 402 | + } | ||
| 403 | + /* skip value */ | ||
| 404 | + while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++; | ||
| 405 | + if (*eq == '=') { | ||
| 406 | + eq++; | ||
| 407 | + while (*eq && (unsigned char)*eq <= ' ') eq++; | ||
| 408 | + if (*eq == '"' || *eq == '\'') { | ||
| 409 | + char q = *eq++; | ||
| 410 | + while (*eq && *eq != q) eq++; | ||
| 411 | + if (*eq) eq++; | ||
| 412 | + } else { | ||
| 413 | + while (*eq && (unsigned char)*eq > ' ') eq++; | ||
| 414 | + } | ||
| 415 | + p = eq; | ||
| 416 | + } else { | ||
| 417 | + p = eq; | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | + return 0; | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +/* ------------------------------------------------------------------ */ | ||
| 424 | +/* Link absolutisation */ | ||
| 425 | +/* ------------------------------------------------------------------ */ | ||
| 426 | + | ||
| 427 | +static char g_base[1024]; | ||
| 428 | + | ||
| 429 | +void fx_md_set_base_url(const char *url) | ||
| 430 | +{ | ||
| 431 | + if (url && *url) snprintf(g_base, sizeof g_base, "%s", url); | ||
| 432 | + else g_base[0] = '\0'; | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +static void absolutise(const char *href, char *out, size_t outsz) | ||
| 436 | +{ | ||
| 437 | + if (!href || !*href) { out[0] = '\0'; return; } | ||
| 438 | + if (strstr(href, "://") || strncmp(href, "mailto:", 7) == 0 || | ||
| 439 | + strncmp(href, "tel:", 4) == 0 || href[0] == '#') { | ||
| 440 | + snprintf(out, outsz, "%s", href); | ||
| 441 | + return; | ||
| 442 | + } | ||
| 443 | + if (!g_base[0]) { snprintf(out, outsz, "%s", href); return; } | ||
| 444 | + { | ||
| 445 | + char scheme[16] = "", host[300] = ""; | ||
| 446 | + const char *sc = strstr(g_base, "://"); | ||
| 447 | + const char *hs, *he; | ||
| 448 | + if (!sc) { snprintf(out, outsz, "%s", href); return; } | ||
| 449 | + { | ||
| 450 | + size_t n = (size_t)(sc - g_base); | ||
| 451 | + if (n >= sizeof scheme) n = sizeof scheme - 1; | ||
| 452 | + memcpy(scheme, g_base, n); | ||
| 453 | + scheme[n] = '\0'; | ||
| 454 | + } | ||
| 455 | + hs = sc + 3; | ||
| 456 | + he = hs; | ||
| 457 | + while (*he && *he != '/' && *he != '?') he++; | ||
| 458 | + { | ||
| 459 | + size_t n = (size_t)(he - hs); | ||
| 460 | + if (n >= sizeof host) n = sizeof host - 1; | ||
| 461 | + memcpy(host, hs, n); | ||
| 462 | + host[n] = '\0'; | ||
| 463 | + } | ||
| 464 | + if (href[0] == '/') | ||
| 465 | + snprintf(out, outsz, "%s://%s%s", scheme, host, href); | ||
| 466 | + else { | ||
| 467 | + char relbase[1024]; | ||
| 468 | + const char *slash; | ||
| 469 | + snprintf(relbase, sizeof relbase, "%s", g_base); | ||
| 470 | + slash = strrchr(relbase, '/'); | ||
| 471 | + if (slash && slash > sc + 3 - 0) { | ||
| 472 | + /* keep everything up to and including the last '/' */ | ||
| 473 | + /* but never before the authority */ | ||
| 474 | + if (slash >= strchr(relbase, '\0') - 0) {} | ||
| 475 | + { | ||
| 476 | + size_t keep = (size_t)(slash - relbase) + 1; | ||
| 477 | + /* don't cut into the scheme://authority */ | ||
| 478 | + const char *auth = strstr(relbase, "://"); | ||
| 479 | + size_t authend = auth ? (size_t)(auth - relbase) + 3 : 0; | ||
| 480 | + const char *pa = strchr(relbase + authend, '/'); | ||
| 481 | + size_t pathstart = pa ? (size_t)(pa - relbase) : authend; | ||
| 482 | + if (keep < pathstart) keep = pathstart; | ||
| 483 | + if (keep >= authend) { | ||
| 484 | + relbase[keep] = '\0'; | ||
| 485 | + snprintf(out, outsz, "%s%s", relbase, href); | ||
| 486 | + } else | ||
| 487 | + snprintf(out, outsz, "%s/%s", relbase, href); | ||
| 488 | + } | ||
| 489 | + } else | ||
| 490 | + snprintf(out, outsz, "%s/%s", relbase, href); | ||
| 491 | + } | ||
| 492 | + } | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +/* ------------------------------------------------------------------ */ | ||
| 496 | +/* Renderer */ | ||
| 497 | +/* ------------------------------------------------------------------ */ | ||
| 498 | + | ||
| 499 | +static int ends_with_blank(buf_t *b) | ||
| 500 | +{ | ||
| 501 | + if (!b->p || b->n == 0) return 1; | ||
| 502 | + if (b->p[b->n - 1] == '\n') | ||
| 503 | + return (b->n >= 2 && b->p[b->n - 2] == '\n'); | ||
| 504 | + return 0; | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | +static void ensure_newline(buf_t *b) | ||
| 508 | +{ | ||
| 509 | + if (b->p && b->n && b->p[b->n - 1] != '\n') buf_add(b, "\n"); | ||
| 510 | +} | ||
| 511 | + | ||
| 512 | +static void ensure_blank_line(buf_t *b) | ||
| 513 | +{ | ||
| 514 | + if (!b->p || b->n == 0) return; | ||
| 515 | + ensure_newline(b); | ||
| 516 | + if (!ends_with_blank(b)) buf_add(b, "\n"); | ||
| 517 | +} | ||
| 518 | + | ||
| 519 | +static void collapse_ws_append(buf_t *out, const char *s) | ||
| 520 | +{ | ||
| 521 | + int in_ws = 0; | ||
| 522 | + for (; *s; s++) { | ||
| 523 | + if ((unsigned char)*s <= ' ') { in_ws = 1; continue; } | ||
| 524 | + if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " "); | ||
| 525 | + in_ws = 0; | ||
| 526 | + buf_bput(out, s, 1); | ||
| 527 | + } | ||
| 528 | + if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " "); | ||
| 529 | +} | ||
| 530 | + | ||
| 531 | +typedef struct { | ||
| 532 | + buf_t *out; | ||
| 533 | + int in_pre; | ||
| 534 | + int pre_fence; | ||
| 535 | + int list_depth; | ||
| 536 | + int list_ordered[12]; | ||
| 537 | + int list_count[12]; | ||
| 538 | + int in_table_row; | ||
| 539 | + int row_cells; | ||
| 540 | + int row_had_th; | ||
| 541 | + int first_row; | ||
| 542 | + int link_depth; | ||
| 543 | + int skip_depth_guard; | ||
| 544 | +} render_state; | ||
| 545 | + | ||
| 546 | +static void render_tokens(toks *t, size_t from, size_t to, render_state *st); | ||
| 547 | + | ||
| 548 | +/* find the matching close for tokens[i] (an open), returns index+1 of the | ||
| 549 | + * close, or `to` when unbalanced. */ | ||
| 550 | +static size_t find_close(toks *t, size_t i, size_t to) | ||
| 551 | +{ | ||
| 552 | + int depth = 0; | ||
| 553 | + size_t j; | ||
| 554 | + for (j = i; j < to; j++) { | ||
| 555 | + if (t->v[j].kind == TOK_OPEN && strcmp(t->v[j].name, t->v[i].name) == 0 && | ||
| 556 | + !t->v[j].selfclose) | ||
| 557 | + depth++; | ||
| 558 | + else if (t->v[j].kind == TOK_CLOSE && strcmp(t->v[j].name, t->v[i].name) == 0) { | ||
| 559 | + depth--; | ||
| 560 | + if (depth == 0) return j + 1; | ||
| 561 | + } | ||
| 562 | + } | ||
| 563 | + return to; | ||
| 564 | +} | ||
| 565 | + | ||
| 566 | +static void render_tokens(toks *t, size_t from, size_t to, render_state *st) | ||
| 567 | +{ | ||
| 568 | + size_t i; | ||
| 569 | + buf_t *out = st->out; | ||
| 570 | + | ||
| 571 | + for (i = from; i < to; i++) { | ||
| 572 | + token *tk = &t->v[i]; | ||
| 573 | + switch (tk->kind) { | ||
| 574 | + case TOK_TEXT: { | ||
| 575 | + if (st->in_pre) { | ||
| 576 | + buf_add(out, tk->text); | ||
| 577 | + } else { | ||
| 578 | + collapse_ws_append(out, tk->text); | ||
| 579 | + } | ||
| 580 | + break; | ||
| 581 | + } | ||
| 582 | + case TOK_OPEN: { | ||
| 583 | + const char *nm = tk->name; | ||
| 584 | + if (tag_skip(nm)) { | ||
| 585 | + if (!tk->selfclose) i = find_close(t, i, to) - 1; | ||
| 586 | + break; | ||
| 587 | + } | ||
| 588 | + if (strcmp(nm, "br") == 0) { | ||
| 589 | + if (st->in_pre) buf_add(out, "\n"); | ||
| 590 | + else { ensure_newline(out); } | ||
| 591 | + break; | ||
| 592 | + } | ||
| 593 | + if (strcmp(nm, "hr") == 0) { | ||
| 594 | + ensure_blank_line(out); | ||
| 595 | + buf_add(out, "---\n"); | ||
| 596 | + break; | ||
| 597 | + } | ||
| 598 | + if (strcmp(nm, "img") == 0) { | ||
| 599 | + char alt[256] = "", src[1024] = "", abs[1200]; | ||
| 600 | + attr_get(tk->attrs, "alt", alt, sizeof alt); | ||
| 601 | + attr_get(tk->attrs, "src", src, sizeof src); | ||
| 602 | + if (src[0]) { | ||
| 603 | + absolutise(src, abs, sizeof abs); | ||
| 604 | + buf_add(out, "; | ||
| 607 | + buf_add(out, abs); | ||
| 608 | + buf_add(out, ")"); | ||
| 609 | + } | ||
| 610 | + break; | ||
| 611 | + } | ||
| 612 | + if (nm[0] == 'h' && nm[1] >= '1' && nm[1] <= '6' && nm[2] == '\0') { | ||
| 613 | + size_t end = tk->selfclose ? i + 1 : find_close(t, i, to); | ||
| 614 | + buf_t sub; | ||
| 615 | + render_state sub_st = *st; | ||
| 616 | + int lvl = nm[1] - '0', k; | ||
| 617 | + ensure_blank_line(out); | ||
| 618 | + for (k = 0; k < lvl; k++) buf_add(out, "#"); | ||
| 619 | + buf_add(out, " "); | ||
| 620 | + buf_init(&sub); | ||
| 621 | + sub_st.out = ⊂ | ||
| 622 | + render_tokens(t, i + 1, end > 0 ? end - 1 : i + 1, &sub_st); | ||
| 623 | + if (sub.p) { | ||
| 624 | + char *p = sub.p; | ||
| 625 | + while (*p && (unsigned char)*p <= ' ') p++; /* drop leading ws */ | ||
| 626 | + buf_add(out, p); | ||
| 627 | + free(sub.p); | ||
| 628 | + } | ||
| 629 | + ensure_blank_line(out); | ||
| 630 | + i = end - 1; | ||
| 631 | + break; | ||
| 632 | + } | ||
| 633 | + if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 || | ||
| 634 | + strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 || | ||
| 635 | + strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 || | ||
| 636 | + strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 || | ||
| 637 | + strcmp(nm, "dl") == 0 || strcmp(nm, "dd") == 0 || | ||
| 638 | + strcmp(nm, "dt") == 0) { | ||
| 639 | + ensure_blank_line(out); | ||
| 640 | + break; | ||
| 641 | + } | ||
| 642 | + if (strcmp(nm, "blockquote") == 0) { | ||
| 643 | + size_t end = tk->selfclose ? i : find_close(t, i, to); | ||
| 644 | + buf_t sub; | ||
| 645 | + render_state sub_st = *st; | ||
| 646 | + char *line, *nl; | ||
| 647 | + buf_init(&sub); | ||
| 648 | + sub_st.out = ⊂ | ||
| 649 | + render_tokens(t, i + 1, end ? end - 1 : i + 1, &sub_st); | ||
| 650 | + if (sub.p) { | ||
| 651 | + line = sub.p; | ||
| 652 | + while (line && *line) { | ||
| 653 | + nl = strchr(line, '\n'); | ||
| 654 | + if (nl) *nl = '\0'; | ||
| 655 | + if (*line) buf_addf(out, "> %s\n", line); | ||
| 656 | + else buf_add(out, ">\n"); | ||
| 657 | + if (!nl) break; | ||
| 658 | + line = nl + 1; | ||
| 659 | + } | ||
| 660 | + free(sub.p); | ||
| 661 | + } | ||
| 662 | + ensure_blank_line(out); | ||
| 663 | + i = end - 1; | ||
| 664 | + break; | ||
| 665 | + } | ||
| 666 | + if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) { | ||
| 667 | + /* nm[1] is 'l' for ol and 'l' for ul too - the difference is | ||
| 668 | + * nm[0]: 'o' versus 'u'. Comparing the second character made | ||
| 669 | + * every unordered list render as a numbered one. */ | ||
| 670 | + int d = st->list_depth; | ||
| 671 | + if (d < 12) { | ||
| 672 | + st->list_ordered[d] = (nm[0] == 'o'); | ||
| 673 | + st->list_count[d] = 0; | ||
| 674 | + } | ||
| 675 | + st->list_depth++; | ||
| 676 | + ensure_newline(out); | ||
| 677 | + break; | ||
| 678 | + } | ||
| 679 | + if (strcmp(nm, "li") == 0) { | ||
| 680 | + /* The marker belongs to the INNERMOST open list: an <li> | ||
| 681 | + * always sits directly inside its own ul/ol, so depth-1 is | ||
| 682 | + * the list it belongs to, and its own counter is the one that | ||
| 683 | + * increments (which restarts numbering for a nested sublist | ||
| 684 | + * while the parent keeps counting). */ | ||
| 685 | + int d = st->list_depth > 0 ? st->list_depth - 1 : 0; | ||
| 686 | + int k; | ||
| 687 | + ensure_newline(out); | ||
| 688 | + for (k = 0; k < d; k++) buf_add(out, " "); | ||
| 689 | + if (d < 12 && st->list_ordered[d]) { | ||
| 690 | + st->list_count[d]++; | ||
| 691 | + buf_addf(out, "%d. ", st->list_count[d]); | ||
| 692 | + } else { | ||
| 693 | + buf_add(out, "- "); | ||
| 694 | + } | ||
| 695 | + break; | ||
| 696 | + } | ||
| 697 | + if (strcmp(nm, "pre") == 0) { | ||
| 698 | + size_t end = tk->selfclose ? i : find_close(t, i, to); | ||
| 699 | + size_t j; | ||
| 700 | + ensure_blank_line(out); | ||
| 701 | + buf_add(out, "```\n"); | ||
| 702 | + st->in_pre = 1; | ||
| 703 | + /* emit raw text tokens between i+1..end-1 (decode entities, | ||
| 704 | + * keep whitespace) */ | ||
| 705 | + for (j = i + 1; j + 1 < end; j++) { | ||
| 706 | + if (t->v[j].kind == TOK_TEXT) buf_add(out, t->v[j].text); | ||
| 707 | + else if (t->v[j].kind == TOK_OPEN && | ||
| 708 | + strcmp(t->v[j].name, "br") == 0) buf_add(out, "\n"); | ||
| 709 | + } | ||
| 710 | + st->in_pre = 0; | ||
| 711 | + ensure_newline(out); | ||
| 712 | + buf_add(out, "```\n"); | ||
| 713 | + ensure_blank_line(out); | ||
| 714 | + i = end - 1; | ||
| 715 | + break; | ||
| 716 | + } | ||
| 717 | + if (strcmp(nm, "code") == 0) { | ||
| 718 | + if (!st->in_pre) buf_add(out, "`"); | ||
| 719 | + break; | ||
| 720 | + } | ||
| 721 | + if (strcmp(nm, "a") == 0) { | ||
| 722 | + char href[1200] = "", abs[1400]; | ||
| 723 | + size_t end = tk->selfclose ? i + 1 : find_close(t, i, to); | ||
| 724 | + if (end > i + 1) { | ||
| 725 | + buf_t sub; | ||
| 726 | + render_state sub_st = *st; | ||
| 727 | + attr_get(tk->attrs, "href", href, sizeof href); | ||
| 728 | + buf_init(&sub); | ||
| 729 | + sub_st.out = ⊂ | ||
| 730 | + render_tokens(t, i + 1, end - 1, &sub_st); | ||
| 731 | + if (sub.p) { | ||
| 732 | + char *p = sub.p; | ||
| 733 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 734 | + if (*p) { | ||
| 735 | + buf_add(out, "["); | ||
| 736 | + buf_add(out, p); | ||
| 737 | + buf_add(out, "]("); | ||
| 738 | + absolutise(href, abs, sizeof abs); | ||
| 739 | + buf_add(out, abs); | ||
| 740 | + buf_add(out, ")"); | ||
| 741 | + } | ||
| 742 | + free(sub.p); | ||
| 743 | + } | ||
| 744 | + } | ||
| 745 | + i = end - 1; | ||
| 746 | + break; | ||
| 747 | + } | ||
| 748 | + if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) { | ||
| 749 | + buf_add(out, "**"); | ||
| 750 | + break; | ||
| 751 | + } | ||
| 752 | + if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) { | ||
| 753 | + buf_add(out, "*"); | ||
| 754 | + break; | ||
| 755 | + } | ||
| 756 | + if (strcmp(nm, "table") == 0) { | ||
| 757 | + ensure_blank_line(out); | ||
| 758 | + st->first_row = 1; | ||
| 759 | + break; | ||
| 760 | + } | ||
| 761 | + if (strcmp(nm, "tr") == 0) { | ||
| 762 | + st->in_table_row = 1; | ||
| 763 | + st->row_cells = 0; | ||
| 764 | + st->row_had_th = 0; | ||
| 765 | + ensure_newline(out); | ||
| 766 | + break; | ||
| 767 | + } | ||
| 768 | + if (strcmp(nm, "td") == 0 || strcmp(nm, "th") == 0) { | ||
| 769 | + /* Cells separate with a pipe, and the row opens with one: | ||
| 770 | + * "| a | b |". Without the leading bar a row of more than | ||
| 771 | + * one cell was a line of text with a bar stuck in the | ||
| 772 | + * middle, which no Markdown renderer will pick up. */ | ||
| 773 | + if (st->row_cells) buf_add(out, " |"); | ||
| 774 | + else buf_add(out, "|"); | ||
| 775 | + buf_add(out, " "); | ||
| 776 | + st->row_cells++; | ||
| 777 | + if (nm[1] == 'h') st->row_had_th = 1; | ||
| 778 | + break; | ||
| 779 | + } | ||
| 780 | + break; | ||
| 781 | + } | ||
| 782 | + case TOK_CLOSE: { | ||
| 783 | + const char *nm = tk->name; | ||
| 784 | + if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) { | ||
| 785 | + if (st->list_depth > 0) st->list_depth--; | ||
| 786 | + ensure_newline(out); | ||
| 787 | + break; | ||
| 788 | + } | ||
| 789 | + if (strcmp(nm, "li") == 0) { ensure_newline(out); break; } | ||
| 790 | + if (strcmp(nm, "a") == 0) break; /* consumed at open */ | ||
| 791 | + if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) { | ||
| 792 | + buf_add(out, "**"); | ||
| 793 | + break; | ||
| 794 | + } | ||
| 795 | + if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) { | ||
| 796 | + buf_add(out, "*"); | ||
| 797 | + break; | ||
| 798 | + } | ||
| 799 | + if (strcmp(nm, "code") == 0) { | ||
| 800 | + if (!st->in_pre) buf_add(out, "`"); | ||
| 801 | + break; | ||
| 802 | + } | ||
| 803 | + if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 || | ||
| 804 | + strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 || | ||
| 805 | + strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 || | ||
| 806 | + strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 || | ||
| 807 | + strcmp(nm, "ul") == 0) { | ||
| 808 | + ensure_blank_line(out); | ||
| 809 | + break; | ||
| 810 | + } | ||
| 811 | + if (strcmp(nm, "tr") == 0) { | ||
| 812 | + st->in_table_row = 0; | ||
| 813 | + /* close the row: "| a | b |" */ | ||
| 814 | + if (st->row_cells) buf_add(out, " |"); | ||
| 815 | + ensure_newline(out); | ||
| 816 | + if (st->first_row && st->row_cells > 0) { | ||
| 817 | + int c; | ||
| 818 | + for (c = 0; c < st->row_cells; c++) | ||
| 819 | + buf_add(out, c ? " | ---" : "| ---"); | ||
| 820 | + buf_add(out, " |"); | ||
| 821 | + ensure_newline(out); | ||
| 822 | + st->first_row = 0; | ||
| 823 | + } | ||
| 824 | + break; | ||
| 825 | + } | ||
| 826 | + if (strcmp(nm, "table") == 0) { | ||
| 827 | + ensure_blank_line(out); | ||
| 828 | + break; | ||
| 829 | + } | ||
| 830 | + break; | ||
| 831 | + } | ||
| 832 | + } | ||
| 833 | + } | ||
| 834 | +} | ||
| 835 | + | ||
| 836 | +/* ------------------------------------------------------------------ */ | ||
| 837 | +/* Public entry points */ | ||
| 838 | +/* ------------------------------------------------------------------ */ | ||
| 839 | + | ||
| 840 | +char *fx_html_to_markdown(const char *html, size_t len, size_t *out_len) | ||
| 841 | +{ | ||
| 842 | + toks t; | ||
| 843 | + buf_t out; | ||
| 844 | + render_state st; | ||
| 845 | + | ||
| 846 | + memset(&st, 0, sizeof st); | ||
| 847 | + buf_init(&out); | ||
| 848 | + st.out = &out; | ||
| 849 | + tokenize(html, len, &t); | ||
| 850 | + render_tokens(&t, 0, t.n, &st); | ||
| 851 | + toks_free(&t); | ||
| 852 | + | ||
| 853 | + /* tidy: strip trailing whitespace runs and clamp to a single trailing \n */ | ||
| 854 | + if (out.p) { | ||
| 855 | + while (out.n && (unsigned char)out.p[out.n - 1] <= ' ') out.n--; | ||
| 856 | + if (out.n) { out.p[out.n] = '\0'; buf_add(&out, "\n"); } | ||
| 857 | + else { out.p[0] = '\0'; } | ||
| 858 | + } | ||
| 859 | + if (out_len) *out_len = out.n; | ||
| 860 | + if (!out.p) { | ||
| 861 | + char *e = (char *)sx_malloc(1); | ||
| 862 | + e[0] = '\0'; | ||
| 863 | + return e; | ||
| 864 | + } | ||
| 865 | + return out.p; | ||
| 866 | +} | ||
| 867 | + | ||
| 868 | +char *fx_html_title(const char *html, size_t len, size_t *out_len) | ||
| 869 | +{ | ||
| 870 | + toks t; | ||
| 871 | + size_t i; | ||
| 872 | + char *result = NULL; | ||
| 873 | + | ||
| 874 | + tokenize(html, len, &t); | ||
| 875 | + for (i = 0; i < t.n; i++) { | ||
| 876 | + if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "meta") == 0) { | ||
| 877 | + char prop[64] = "", name[64] = "", content[512] = ""; | ||
| 878 | + attr_get(t.v[i].attrs, "property", prop, sizeof prop); | ||
| 879 | + if (!prop[0]) attr_get(t.v[i].attrs, "name", name, sizeof name); | ||
| 880 | + if ((prop[0] && sx_strcasecmp(prop, "og:title") == 0) || | ||
| 881 | + (name[0] && sx_strcasecmp(name, "og:title") == 0)) { | ||
| 882 | + if (attr_get(t.v[i].attrs, "content", content, sizeof content) && | ||
| 883 | + content[0]) { | ||
| 884 | + buf_t b; | ||
| 885 | + buf_init(&b); | ||
| 886 | + collapse_ws_append(&b, content); | ||
| 887 | + if (b.n) { | ||
| 888 | + b.p[b.n] = '\0'; | ||
| 889 | + result = b.p; | ||
| 890 | + break; | ||
| 891 | + } | ||
| 892 | + free(b.p); | ||
| 893 | + } | ||
| 894 | + } | ||
| 895 | + } | ||
| 896 | + } | ||
| 897 | + if (!result) { | ||
| 898 | + for (i = 0; i < t.n; i++) { | ||
| 899 | + if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "title") == 0) { | ||
| 900 | + size_t j; | ||
| 901 | + for (j = i + 1; j < t.n && t.v[j].kind != TOK_CLOSE; j++) { | ||
| 902 | + if (t.v[j].kind == TOK_TEXT && t.v[j].text && | ||
| 903 | + t.v[j].text[0]) { | ||
| 904 | + buf_t b; | ||
| 905 | + buf_init(&b); | ||
| 906 | + collapse_ws_append(&b, t.v[j].text); | ||
| 907 | + if (b.n) { b.p[b.n] = '\0'; result = b.p; } | ||
| 908 | + else free(b.p); | ||
| 909 | + break; | ||
| 910 | + } | ||
| 911 | + } | ||
| 912 | + break; | ||
| 913 | + } | ||
| 914 | + } | ||
| 915 | + } | ||
| 916 | + toks_free(&t); | ||
| 917 | + if (out_len) *out_len = result ? strlen(result) : 0; | ||
| 918 | + return result; | ||
| 919 | +} | ||
| 920 | + | ||
| 921 | +/* word-normalised comparison (letters+digits runs, lowercased) */ | ||
| 922 | +static size_t norm_words(const char *s, size_t n, char *out, size_t outsz) | ||
| 923 | +{ | ||
| 924 | + size_t o = 0, i = 0; | ||
| 925 | + int sep = 1; | ||
| 926 | + for (i = 0; i < n; i++) { | ||
| 927 | + char c = s[i]; | ||
| 928 | + if (isalnum((unsigned char)c)) { | ||
| 929 | + if (o + 2 >= outsz) break; | ||
| 930 | + if (sep && o) out[o++] = ' '; | ||
| 931 | + sep = 0; | ||
| 932 | + out[o++] = (char)tolower((unsigned char)c); | ||
| 933 | + } else { | ||
| 934 | + sep = 1; | ||
| 935 | + } | ||
| 936 | + } | ||
| 937 | + out[o] = '\0'; | ||
| 938 | + return o; | ||
| 939 | +} | ||
| 940 | + | ||
| 941 | +int fx_md_starts_with_title(const char *md, size_t md_len, | ||
| 942 | + const char *title, size_t title_len) | ||
| 943 | +{ | ||
| 944 | + char tw[1024], mw[4096]; | ||
| 945 | + size_t tl, ml, k; | ||
| 946 | + | ||
| 947 | + if (!md || !title || !title_len) return 0; | ||
| 948 | + tl = norm_words(title, title_len, tw, sizeof tw); | ||
| 949 | + if (!tl) return 0; | ||
| 950 | + if (md_len > 800) md_len = 800; /* the heading is near the top */ | ||
| 951 | + ml = norm_words(md, md_len, mw, sizeof mw); | ||
| 952 | + if (!ml) return 0; | ||
| 953 | + if (ml < tl) return 0; | ||
| 954 | + for (k = 0; k < tl; k++) if (mw[k] != tw[k]) return 0; | ||
| 955 | + /* the next char must be a word boundary (space or end) */ | ||
| 956 | + if (ml > tl && mw[tl] != ' ') return 0; | ||
| 957 | + return 1; | ||
| 958 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..092d8f8 | index 0000000..092d8f8 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_md.h | +++ b/src/fetch_md.h | ||
| @@ -0,0 +1,41 @@ | @@ -0,0 +1,41 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_md.h - pure C99 HTML tokenizer -> clean Markdown converter. | ||
| 3 | + * | ||
| 4 | + * Scope (task spec, matching what the fetch MCP tool needs): | ||
| 5 | + * - strips <script>/<style>/<noscript>/<svg>/<head>/<nav>/<aside>/<footer>/ | ||
| 6 | + * <form>/<template> subtrees and comments | ||
| 7 | + * - headings h1..h6 -> ATX (#..######) | ||
| 8 | + * - links -> [text](href) (absolute-ised against the page URL) | ||
| 9 | + * - ul/ol -> - / 1. lists (one nesting level) | ||
| 10 | + * - pre/code -> fenced blocks / `code spans` | ||
| 11 | + * - strong/b -> **..**, em/i -> *..* | ||
| 12 | + * - p/div/br/hr/blockquote/table basics -> line breaks / pipes | ||
| 13 | + * - decodes the common HTML entities and &#NNN; / &#xHH; | ||
| 14 | + * | ||
| 15 | + * It is a forgiving tokenizer over raw bytes (UTF-8 passes through untouched); | ||
| 16 | + * it is not a full DOM. That is enough to take a web page down to clean | ||
| 17 | + * readable Markdown and is a clean-room reimplementation, not a port of any | ||
| 18 | + * upstream converter. | ||
| 19 | + */ | ||
| 20 | +#ifndef SX_FETCH_MD_H | ||
| 21 | +#define SX_FETCH_MD_H | ||
| 22 | + | ||
| 23 | +#include <stddef.h> | ||
| 24 | + | ||
| 25 | +/* Convert an HTML document to Markdown. Returns a malloc'd NUL-terminated | ||
| 26 | + * string and sets *out_len. Always returns non-NULL. */ | ||
| 27 | +char *fx_html_to_markdown(const char *html, size_t len, size_t *out_len); | ||
| 28 | + | ||
| 29 | +/* Extract the document title (og:title meta, then <title>). Returns malloc'd | ||
| 30 | + * UTF-8 text or NULL; sets *out_len. */ | ||
| 31 | +char *fx_html_title(const char *html, size_t len, size_t *out_len); | ||
| 32 | + | ||
| 33 | +/* Whether markdown `md` (length md_len) already opens with the title text | ||
| 34 | + * (word-insensitive, like upstream's title.py). */ | ||
| 35 | +int fx_md_starts_with_title(const char *md, size_t md_len, | ||
| 36 | + const char *title, size_t title_len); | ||
| 37 | + | ||
| 38 | +/* Set the base URL used to absolutise relative links (may be NULL). */ | ||
| 39 | +void fx_md_set_base_url(const char *url); | ||
| 40 | + | ||
| 41 | +#endif /* SX_FETCH_MD_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..1abae01 | index 0000000..1abae01 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_tls.c | +++ b/src/fetch_tls.c | ||
| @@ -0,0 +1,226 @@ | @@ -0,0 +1,226 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_tls.c - mbedTLS client over an already-connected socket (POSIX). | ||
| 3 | + * | ||
| 4 | + * The socket arrives pre-validated and pre-connected by fetch_http.c (the | ||
| 5 | + * SSRF check happened on the numeric address before connect), so this layer | ||
| 6 | + * only wraps TLS around it: no DNS here, no second connect, therefore no | ||
| 7 | + * rebinding window. | ||
| 8 | + * | ||
| 9 | + * Policy: TLS 1.2 minimum, VERIFY_PEER always, hostname checked against the | ||
| 10 | + * certificate. Trust anchors: FETCH_TLS_CA_FILE if set and readable, else the | ||
| 11 | + * first system bundle that exists. There is deliberately NO way to disable | ||
| 12 | + * verification. | ||
| 13 | + * | ||
| 14 | + * _WIN32: WinHTTP does TLS itself; this file is an empty TU there. | ||
| 15 | + */ | ||
| 16 | +#include "fetch_tls.h" | ||
| 17 | + | ||
| 18 | +#if !defined(_WIN32) | ||
| 19 | + | ||
| 20 | +#ifndef _POSIX_C_SOURCE | ||
| 21 | +#define _POSIX_C_SOURCE 200809L | ||
| 22 | +#endif | ||
| 23 | + | ||
| 24 | +#include <errno.h> | ||
| 25 | +#include <stdio.h> | ||
| 26 | +#include <stdlib.h> | ||
| 27 | +#include <string.h> | ||
| 28 | +#include <sys/socket.h> | ||
| 29 | +#include <sys/stat.h> | ||
| 30 | +#include <unistd.h> | ||
| 31 | + | ||
| 32 | +#include "mbedtls/build_info.h" | ||
| 33 | +#include "mbedtls/ctr_drbg.h" | ||
| 34 | +#include "mbedtls/entropy.h" | ||
| 35 | +#include "mbedtls/error.h" | ||
| 36 | +#include "mbedtls/net_sockets.h" | ||
| 37 | +#include "mbedtls/psa_util.h" | ||
| 38 | +#include "mbedtls/ssl.h" | ||
| 39 | +#include "mbedtls/x509_crt.h" | ||
| 40 | +#include "psa/crypto.h" | ||
| 41 | + | ||
| 42 | +struct fx_tls { | ||
| 43 | + int fd; | ||
| 44 | + mbedtls_ssl_context ssl; | ||
| 45 | + mbedtls_ssl_config conf; | ||
| 46 | + mbedtls_entropy_context entropy; | ||
| 47 | + mbedtls_ctr_drbg_context drbg; | ||
| 48 | + mbedtls_x509_crt cas; | ||
| 49 | + int alive; | ||
| 50 | +}; | ||
| 51 | + | ||
| 52 | +static const char *const CA_BUNDLES[] = { | ||
| 53 | + "/etc/ssl/certs/ca-certificates.crt", /* Debian/Ubuntu/Alpine */ | ||
| 54 | + "/etc/pki/tls/certs/ca-bundle.crt", /* RHEL/Fedora */ | ||
| 55 | + "/etc/ssl/ca-bundle.pem", /* openSUSE */ | ||
| 56 | + "/etc/ssl/cert.pem", /* Alpine/macOS-ish */ | ||
| 57 | + "/var/ssl/certs/ca-certificates.crt", /* Termux */ | ||
| 58 | + NULL | ||
| 59 | +}; | ||
| 60 | + | ||
| 61 | +static int bio_send(void *ctx, const unsigned char *buf, size_t len) | ||
| 62 | +{ | ||
| 63 | + fx_tls *t = (fx_tls *)ctx; | ||
| 64 | + ssize_t w; | ||
| 65 | + do { w = send(t->fd, buf, len, MSG_NOSIGNAL); } while (w < 0 && errno == EINTR); | ||
| 66 | + if (w < 0) return MBEDTLS_ERR_NET_SEND_FAILED; | ||
| 67 | + return (int)w; | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +static int bio_recv(void *ctx, unsigned char *buf, size_t len) | ||
| 71 | +{ | ||
| 72 | + fx_tls *t = (fx_tls *)ctx; | ||
| 73 | + ssize_t r; | ||
| 74 | + do { r = recv(t->fd, buf, len, 0); } while (r < 0 && errno == EINTR); | ||
| 75 | + if (r == 0) return MBEDTLS_ERR_SSL_CONN_EOF; | ||
| 76 | + if (r < 0) { | ||
| 77 | + if (errno == EAGAIN || errno == EWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_READ; | ||
| 78 | + return MBEDTLS_ERR_NET_RECV_FAILED; | ||
| 79 | + } | ||
| 80 | + return (int)r; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +static void fail_free(fx_tls *t) | ||
| 84 | +{ | ||
| 85 | + if (!t) return; | ||
| 86 | + if (t->fd >= 0) { close(t->fd); t->fd = -1; } | ||
| 87 | + if (t->alive) { | ||
| 88 | + mbedtls_ssl_free(&t->ssl); | ||
| 89 | + mbedtls_ssl_config_free(&t->conf); | ||
| 90 | + mbedtls_x509_crt_free(&t->cas); | ||
| 91 | + mbedtls_ctr_drbg_free(&t->drbg); | ||
| 92 | + mbedtls_entropy_free(&t->entropy); | ||
| 93 | + t->alive = 0; | ||
| 94 | + } | ||
| 95 | + free(t); | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +fx_tls *fx_tls_connect_fd(int fd, const char *hostname, char *err, size_t errsz) | ||
| 99 | +{ | ||
| 100 | + fx_tls *t; | ||
| 101 | + const char *ca; | ||
| 102 | + int ret; | ||
| 103 | + char m[160]; | ||
| 104 | + | ||
| 105 | + t = (fx_tls *)calloc(1, sizeof *t); | ||
| 106 | + if (!t) { snprintf(err, errsz, "out of memory"); close(fd); return NULL; } | ||
| 107 | + t->fd = fd; | ||
| 108 | + | ||
| 109 | + if (psa_crypto_init() != PSA_SUCCESS) { | ||
| 110 | + snprintf(err, errsz, "TLS failed: psa init"); | ||
| 111 | + free(t); | ||
| 112 | + close(fd); | ||
| 113 | + return NULL; | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + mbedtls_entropy_init(&t->entropy); | ||
| 117 | + mbedtls_ctr_drbg_init(&t->drbg); | ||
| 118 | + mbedtls_ssl_config_init(&t->conf); | ||
| 119 | + mbedtls_ssl_init(&t->ssl); | ||
| 120 | + mbedtls_x509_crt_init(&t->cas); | ||
| 121 | + t->alive = 1; | ||
| 122 | + | ||
| 123 | + ret = mbedtls_ctr_drbg_seed(&t->drbg, mbedtls_entropy_func, &t->entropy, | ||
| 124 | + (const unsigned char *)"sxfetch", 7); | ||
| 125 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | ||
| 126 | + snprintf(err, errsz, "TLS failed: rng seed: %s", m); goto fail; } | ||
| 127 | + | ||
| 128 | + ret = mbedtls_ssl_config_defaults(&t->conf, MBEDTLS_SSL_IS_CLIENT, | ||
| 129 | + MBEDTLS_SSL_TRANSPORT_STREAM, | ||
| 130 | + MBEDTLS_SSL_PRESET_DEFAULT); | ||
| 131 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | ||
| 132 | + snprintf(err, errsz, "TLS failed: config: %s", m); goto fail; } | ||
| 133 | + mbedtls_ssl_conf_rng(&t->conf, mbedtls_ctr_drbg_random, &t->drbg); | ||
| 134 | + mbedtls_ssl_conf_min_tls_version(&t->conf, MBEDTLS_SSL_VERSION_TLS1_2); | ||
| 135 | + mbedtls_ssl_conf_authmode(&t->conf, MBEDTLS_SSL_VERIFY_REQUIRED); | ||
| 136 | + | ||
| 137 | + /* trust anchors */ | ||
| 138 | + ca = getenv("FETCH_TLS_CA_FILE"); | ||
| 139 | + if (ca && *ca) { | ||
| 140 | + ret = mbedtls_x509_crt_parse_file(&t->cas, ca); | ||
| 141 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | ||
| 142 | + snprintf(err, errsz, "TLS failed: cannot parse CA file %s: %s", ca, m); | ||
| 143 | + goto fail; } | ||
| 144 | + } else { | ||
| 145 | + int i, loaded = 0; | ||
| 146 | + for (i = 0; CA_BUNDLES[i]; i++) { | ||
| 147 | + struct stat st; | ||
| 148 | + if (stat(CA_BUNDLES[i], &st) != 0 || !S_ISREG(st.st_mode)) continue; | ||
| 149 | + if (mbedtls_x509_crt_parse_file(&t->cas, CA_BUNDLES[i]) == 0) { | ||
| 150 | + loaded = 1; | ||
| 151 | + break; | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + if (!loaded) { | ||
| 155 | + snprintf(err, errsz, | ||
| 156 | + "TLS failed: no trust anchors — no readable system CA bundle; " | ||
| 157 | + "set FETCH_TLS_CA_FILE to a PEM bundle"); | ||
| 158 | + goto fail; | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + mbedtls_ssl_conf_ca_chain(&t->conf, &t->cas, NULL); | ||
| 162 | + | ||
| 163 | + ret = mbedtls_ssl_setup(&t->ssl, &t->conf); | ||
| 164 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | ||
| 165 | + snprintf(err, errsz, "TLS failed: setup: %s", m); goto fail; } | ||
| 166 | + ret = mbedtls_ssl_set_hostname(&t->ssl, hostname); | ||
| 167 | + if (ret) { mbedtls_strerror(ret, m, sizeof m); | ||
| 168 | + snprintf(err, errsz, "TLS failed: hostname: %s", m); goto fail; } | ||
| 169 | + mbedtls_ssl_set_bio(&t->ssl, t, bio_send, bio_recv, NULL); | ||
| 170 | + | ||
| 171 | + do { | ||
| 172 | + ret = mbedtls_ssl_handshake(&t->ssl); | ||
| 173 | + } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); | ||
| 174 | + if (ret) { | ||
| 175 | + mbedtls_strerror(ret, m, sizeof m); | ||
| 176 | + if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) | ||
| 177 | + snprintf(err, errsz, | ||
| 178 | + "TLS failed: certificate verification refused for %s (%s)", | ||
| 179 | + hostname, m); | ||
| 180 | + else | ||
| 181 | + snprintf(err, errsz, "TLS failed: handshake with %s: %s", hostname, m); | ||
| 182 | + goto fail; | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + return t; | ||
| 186 | + | ||
| 187 | +fail: | ||
| 188 | + fail_free(t); | ||
| 189 | + return NULL; | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +int fx_tls_read(fx_tls *t, char *buf, size_t n) | ||
| 193 | +{ | ||
| 194 | + int r; | ||
| 195 | + if (!t || !t->alive) return -1; | ||
| 196 | + do { r = mbedtls_ssl_read(&t->ssl, (unsigned char *)buf, n); } | ||
| 197 | + while (r == MBEDTLS_ERR_SSL_WANT_READ); | ||
| 198 | + if (r == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY || r == 0) return 0; | ||
| 199 | + if (r == MBEDTLS_ERR_SSL_CONN_EOF) return 0; | ||
| 200 | + if (r < 0) return -1; | ||
| 201 | + return r; | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +int fx_tls_write(fx_tls *t, const char *buf, size_t n) | ||
| 205 | +{ | ||
| 206 | + size_t off = 0; | ||
| 207 | + if (!t || !t->alive) return -1; | ||
| 208 | + while (off < n) { | ||
| 209 | + int r = mbedtls_ssl_write(&t->ssl, (const unsigned char *)buf + off, n - off); | ||
| 210 | + if (r == MBEDTLS_ERR_SSL_WANT_WRITE) continue; | ||
| 211 | + if (r < 0) return -1; | ||
| 212 | + off += (size_t)r; | ||
| 213 | + } | ||
| 214 | + return (int)off; | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +void fx_tls_close(fx_tls *t) | ||
| 218 | +{ | ||
| 219 | + if (!t) return; | ||
| 220 | + if (t->alive) mbedtls_ssl_close_notify(&t->ssl); | ||
| 221 | + fail_free(t); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +int fx_tls_supported(void) { return 1; } | ||
| 225 | + | ||
| 226 | +#endif /* !_WIN32 */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..e69a5a4 | index 0000000..e69a5a4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/fetch_tls.h | +++ b/src/fetch_tls.h | ||
| @@ -0,0 +1,34 @@ | @@ -0,0 +1,34 @@ | ||
| 1 | +/* | ||
| 2 | + * fetch_tls.h - minimal TLS stream over an already-connected socket. | ||
| 3 | + * | ||
| 4 | + * POSIX: vendored mbedTLS (verify peer + hostname against a CA bundle). | ||
| 5 | + * _WIN32: this layer is not used (WinHTTP does TLS itself), so the module is | ||
| 6 | + * an empty translation unit there and fx_tls_supported() reports 0. | ||
| 7 | + */ | ||
| 8 | +#ifndef SX_FETCH_TLS_H | ||
| 9 | +#define SX_FETCH_TLS_H | ||
| 10 | + | ||
| 11 | +#include <stddef.h> | ||
| 12 | + | ||
| 13 | +#if !defined(_WIN32) | ||
| 14 | + | ||
| 15 | +typedef struct fx_tls fx_tls; | ||
| 16 | + | ||
| 17 | +/* Takes ownership of `fd` on success (closed by fx_tls_close). hostname is | ||
| 18 | + * used for SNI and certificate verification. Returns NULL + err on failure | ||
| 19 | + * (fd closed). */ | ||
| 20 | +fx_tls *fx_tls_connect_fd(int fd, const char *hostname, char *err, size_t errsz); | ||
| 21 | + | ||
| 22 | +/* Returns bytes read, 0 at EOF, -1 on error. */ | ||
| 23 | +int fx_tls_read(fx_tls *t, char *buf, size_t n); | ||
| 24 | +/* Returns bytes written or -1. */ | ||
| 25 | +int fx_tls_write(fx_tls *t, const char *buf, size_t n); | ||
| 26 | + | ||
| 27 | +void fx_tls_close(fx_tls *t); | ||
| 28 | + | ||
| 29 | +/* 1 when the binary was built with the TLS stack (POSIX), 0 otherwise. */ | ||
| 30 | +int fx_tls_supported(void); | ||
| 31 | + | ||
| 32 | +#endif /* !_WIN32 */ | ||
| 33 | + | ||
| 34 | +#endif /* SX_FETCH_TLS_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..561948d | index 0000000..561948d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_fetch.c | +++ b/src/plugin_fetch.c | ||
| @@ -0,0 +1,846 @@ | @@ -0,0 +1,846 @@ | ||
| 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 | +# include <windows.h> | ||
| 56 | +# include <io.h> | ||
| 57 | +#endif | ||
| 58 | +#include <sys/stat.h> | ||
| 59 | +#include <sys/types.h> | ||
| 60 | + | ||
| 61 | +#include "bot_theme_plugin.h" | ||
| 62 | +#include "ui_html.h" | ||
| 63 | +#include "fetch_http.h" | ||
| 64 | +#include "fetch_md.h" | ||
| 65 | +#include "sxmcp.h" | ||
| 66 | + | ||
| 67 | +#define PLUGIN_SLUG "fetch" | ||
| 68 | +#define PLUGIN_ID "plugin_fetch" | ||
| 69 | +#define PLUGIN_VER "1.0.0" | ||
| 70 | + | ||
| 71 | +#if defined(_WIN32) | ||
| 72 | +# define sx_mkdir(p) _mkdir(p) | ||
| 73 | +# define SX_PATHSEP '\\' | ||
| 74 | +#else | ||
| 75 | +# include <unistd.h> | ||
| 76 | +# define sx_mkdir(p) mkdir((p), 0755) | ||
| 77 | +# define SX_PATHSEP '/' | ||
| 78 | +#endif | ||
| 79 | + | ||
| 80 | +void tool_result_free(tool_result *r) | ||
| 81 | +{ | ||
| 82 | + if (!r) return; | ||
| 83 | + free(r->text); | ||
| 84 | + free(r->raw_html); | ||
| 85 | + memset(r, 0, sizeof *r); | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/* ------------------------------------------------------------------ */ | ||
| 89 | +/* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and the */ | ||
| 90 | +/* HTML page never call this; every JSON action does. */ | ||
| 91 | +/* ------------------------------------------------------------------ */ | ||
| 92 | + | ||
| 93 | +static void require_node_auth(void) | ||
| 94 | +{ | ||
| 95 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 96 | + const char *xp, *auth; | ||
| 97 | + char qpwd[256] = {0}; | ||
| 98 | + const char *qs; | ||
| 99 | + | ||
| 100 | + if (!np || !*np) return; /* open node: no gate */ | ||
| 101 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 102 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 103 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 104 | + if (auth) { | ||
| 105 | + while (*auth == ' ') auth++; | ||
| 106 | + if (sx_strncasecmp(auth, "Bearer ", 7) == 0) { | ||
| 107 | + auth += 7; | ||
| 108 | + while (*auth == ' ') auth++; | ||
| 109 | + if (strcmp(auth, np) == 0) return; | ||
| 110 | + } | ||
| 111 | + } | ||
| 112 | + qs = getenv("QUERY_STRING"); | ||
| 113 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) | ||
| 114 | + return; | ||
| 115 | + | ||
| 116 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 117 | + "Content-Type: application/json; charset=utf-8\r\n\r\n" | ||
| 118 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 119 | + exit(0); | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/* ------------------------------------------------------------------ */ | ||
| 123 | +/* Connector dir + persisted policy */ | ||
| 124 | +/* ------------------------------------------------------------------ */ | ||
| 125 | + | ||
| 126 | +static void connector_dir(char *out, size_t outsz) | ||
| 127 | +{ | ||
| 128 | + const char *env = getenv("SX_CONNECTOR_DIR"); | ||
| 129 | + struct stat st; | ||
| 130 | + | ||
| 131 | + if (env && *env) { snprintf(out, outsz, "%s", env); return; } | ||
| 132 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && | ||
| 133 | + access("/workspace", W_OK) == 0) { | ||
| 134 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/fetch"); | ||
| 135 | + return; | ||
| 136 | + } | ||
| 137 | +#if defined(_WIN32) | ||
| 138 | + { | ||
| 139 | + const char *la = getenv("LOCALAPPDATA"); | ||
| 140 | + if (la && *la) { | ||
| 141 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\fetch", la); | ||
| 142 | + return; | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | +#endif | ||
| 146 | + { | ||
| 147 | + const char *home = getenv("HOME"); | ||
| 148 | + if (!home || !*home) home = "/root"; | ||
| 149 | + snprintf(out, outsz, "%s/.scorpiox/connectors/fetch", home); | ||
| 150 | + } | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +static int mkdirs(const char *path) | ||
| 154 | +{ | ||
| 155 | + char buf[1200]; | ||
| 156 | + size_t i, n; | ||
| 157 | + struct stat st; | ||
| 158 | + snprintf(buf, sizeof buf, "%s", path); | ||
| 159 | + n = strlen(buf); | ||
| 160 | + for (i = 1; i < n; i++) { | ||
| 161 | + if (buf[i] == '/' || buf[i] == '\\') { | ||
| 162 | + char save = buf[i]; | ||
| 163 | + buf[i] = '\0'; | ||
| 164 | + if (i > 2) sx_mkdir(buf); | ||
| 165 | + buf[i] = save; | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + sx_mkdir(buf); | ||
| 169 | + return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +static void policy_path(char *out, size_t outsz) | ||
| 173 | +{ | ||
| 174 | + char dir[1000]; | ||
| 175 | + connector_dir(dir, sizeof dir); | ||
| 176 | + snprintf(out, outsz, "%s%cconfig.json", dir, SX_PATHSEP); | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +static int policy_read_allow_private(void) | ||
| 180 | +{ | ||
| 181 | + char p[1200]; | ||
| 182 | + FILE *f; | ||
| 183 | + long sz; | ||
| 184 | + char *txt; | ||
| 185 | + int v = 0; | ||
| 186 | + char *k; | ||
| 187 | + | ||
| 188 | + policy_path(p, sizeof p); | ||
| 189 | + f = fopen(p, "rb"); | ||
| 190 | + if (!f) return 0; | ||
| 191 | + fseek(f, 0, SEEK_END); | ||
| 192 | + sz = ftell(f); | ||
| 193 | + fseek(f, 0, SEEK_SET); | ||
| 194 | + if (sz < 0 || sz > 65536) { fclose(f); return 0; } | ||
| 195 | + txt = (char *)sx_malloc((size_t)sz + 1); | ||
| 196 | + if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) { free(txt); fclose(f); return 0; } | ||
| 197 | + txt[sz] = '\0'; | ||
| 198 | + fclose(f); | ||
| 199 | + k = strstr(txt, "\"allow_private\""); | ||
| 200 | + if (k) { | ||
| 201 | + k += strlen("\"allow_private\""); | ||
| 202 | + while (*k && (unsigned char)*k <= ' ') k++; | ||
| 203 | + if (*k == ':') { | ||
| 204 | + k++; | ||
| 205 | + while (*k && (unsigned char)*k <= ' ') k++; | ||
| 206 | + if (strncmp(k, "true", 4) == 0) v = 1; | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | + free(txt); | ||
| 210 | + return v; | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +/* Cached for the process lifetime (the fetch legs ask per request). */ | ||
| 214 | +int fx_policy_allow_private(void) | ||
| 215 | +{ | ||
| 216 | + static int cached = -1; | ||
| 217 | + if (cached < 0) cached = policy_read_allow_private(); | ||
| 218 | + return cached; | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +static int policy_set_allow_private(int on) | ||
| 222 | +{ | ||
| 223 | + char dir[1000], p[1200], tmp[1300]; | ||
| 224 | + FILE *f; | ||
| 225 | + connector_dir(dir, sizeof dir); | ||
| 226 | + if (!mkdirs(dir)) return 0; | ||
| 227 | + policy_path(p, sizeof p); | ||
| 228 | + snprintf(tmp, sizeof tmp, "%s.tmp", p); | ||
| 229 | + f = fopen(tmp, "wb"); | ||
| 230 | + if (!f) return 0; | ||
| 231 | + fprintf(f, "{\"allow_private\":%s,\"updated_at\":%lld}\n", | ||
| 232 | + on ? "true" : "false", (long long)time(NULL)); | ||
| 233 | + fclose(f); | ||
| 234 | + remove(p); | ||
| 235 | + if (rename(tmp, p) != 0) { remove(tmp); return 0; } | ||
| 236 | + return 1; | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +/* ------------------------------------------------------------------ */ | ||
| 240 | +/* The fetch engine (shared by --mcp, ?action=fetch and the UI) */ | ||
| 241 | +/* ------------------------------------------------------------------ */ | ||
| 242 | + | ||
| 243 | +void fetch_tool_run(const char *url, long max_length, long start_index, int raw, | ||
| 244 | + tool_result *out) | ||
| 245 | +{ | ||
| 246 | + fx_response resp; | ||
| 247 | + char *content = NULL; /* heap: what gets chunked */ | ||
| 248 | + size_t content_len = 0; | ||
| 249 | + char prefix[2200]; | ||
| 250 | + char *title = NULL; | ||
| 251 | + size_t title_len = 0; | ||
| 252 | + | ||
| 253 | + memset(out, 0, sizeof *out); | ||
| 254 | + prefix[0] = '\0'; | ||
| 255 | + | ||
| 256 | + if (!url || !url[0]) { | ||
| 257 | + snprintf(out->error, sizeof out->error, "url is required"); | ||
| 258 | + return; | ||
| 259 | + } | ||
| 260 | + if (max_length <= 0) max_length = 5000; | ||
| 261 | + if (max_length > 100000) max_length = 100000; | ||
| 262 | + if (start_index < 0) start_index = 0; | ||
| 263 | + | ||
| 264 | + if (fx_fetch(url, &resp) != 0) { | ||
| 265 | + snprintf(out->error, sizeof out->error, "%s", | ||
| 266 | + resp.error[0] ? resp.error : "fetch failed"); | ||
| 267 | + fx_response_free(&resp); | ||
| 268 | + return; | ||
| 269 | + } | ||
| 270 | + out->status = resp.status; | ||
| 271 | + snprintf(out->content_type, sizeof out->content_type, "%s", resp.content_type); | ||
| 272 | + out->bytes_read = resp.body_len; | ||
| 273 | + snprintf(out->final_url, sizeof out->final_url, "%s", resp.url); | ||
| 274 | + { | ||
| 275 | + size_t cap = resp.body_len; | ||
| 276 | + if (cap > 400000) cap = 400000; /* the UI Raw tab only */ | ||
| 277 | + out->raw_html = fx_strndup(resp.body ? resp.body : "", cap); | ||
| 278 | + } | ||
| 279 | + out->redirected = resp.hops > 0; | ||
| 280 | + | ||
| 281 | + if (resp.status >= 400) { | ||
| 282 | + snprintf(out->error, sizeof out->error, | ||
| 283 | + "Failed to fetch %s - status code %d", resp.url, resp.status); | ||
| 284 | + fx_response_free(&resp); | ||
| 285 | + return; | ||
| 286 | + } | ||
| 287 | + if (resp.hops > 0) | ||
| 288 | + snprintf(prefix, sizeof prefix, "Redirecting from %s to %s\n\n", | ||
| 289 | + resp.first_url, resp.url); | ||
| 290 | + | ||
| 291 | + { | ||
| 292 | + char ctlower[128]; | ||
| 293 | + int is_md = 0, is_html = 0; | ||
| 294 | + size_t i; | ||
| 295 | + const char *ct = resp.content_type; | ||
| 296 | + for (i = 0; ct && ct[i] && i < sizeof ctlower - 1; i++) | ||
| 297 | + ctlower[i] = (char)tolower((unsigned char)ct[i]); | ||
| 298 | + ctlower[i] = '\0'; | ||
| 299 | + { | ||
| 300 | + char *sc = strchr(ctlower, ';'); | ||
| 301 | + if (sc) *sc = '\0'; | ||
| 302 | + } | ||
| 303 | + is_md = strcmp(ctlower, "text/markdown") == 0; | ||
| 304 | + is_html = strstr(ctlower, "text/html") != NULL || | ||
| 305 | + strstr(ctlower, "application/xhtml+xml") != NULL || | ||
| 306 | + (!ctlower[0] && fx_body_looks_like_html(resp.body, resp.body_len)); | ||
| 307 | + | ||
| 308 | + if (is_md) { | ||
| 309 | + content = fx_strndup(resp.body, resp.body_len); | ||
| 310 | + content_len = resp.body_len; | ||
| 311 | + prefix[0] = '\0'; /* markdown is returned verbatim */ | ||
| 312 | + } else if (is_html && !raw) { | ||
| 313 | + char *md = fx_html_to_markdown(resp.body, resp.body_len, &content_len); | ||
| 314 | + title = fx_html_title(resp.body, resp.body_len, &title_len); | ||
| 315 | + if (title && title_len && | ||
| 316 | + !fx_md_starts_with_title(md, content_len, title, title_len)) { | ||
| 317 | + size_t hl = 2 + title_len + 2; | ||
| 318 | + char *cat = (char *)sx_malloc(hl + content_len + 1); | ||
| 319 | + cat[0] = '#'; cat[1] = ' '; | ||
| 320 | + memcpy(cat + 2, title, title_len); | ||
| 321 | + cat[2 + title_len] = '\n'; | ||
| 322 | + cat[3 + title_len] = '\n'; | ||
| 323 | + if (content_len) memcpy(cat + hl, md, content_len); | ||
| 324 | + cat[hl + content_len] = '\0'; | ||
| 325 | + free(md); | ||
| 326 | + md = cat; | ||
| 327 | + content_len = hl + content_len; | ||
| 328 | + } | ||
| 329 | + if (title && title_len) | ||
| 330 | + snprintf(out->title, sizeof out->title, "%s", title); | ||
| 331 | + content = md; | ||
| 332 | + if (!content[0] && content_len == 0) { | ||
| 333 | + free(content); | ||
| 334 | + content = sx_strdup(""); | ||
| 335 | + } | ||
| 336 | + } else { | ||
| 337 | + content = fx_strndup(resp.body, resp.body_len); | ||
| 338 | + content_len = resp.body_len; | ||
| 339 | + if (!raw) { | ||
| 340 | + char declared[280]; | ||
| 341 | + snprintf(declared, sizeof declared, | ||
| 342 | + "Content type %s cannot be simplified to markdown, " | ||
| 343 | + "but here is the raw content:\n", | ||
| 344 | + resp.content_type[0] ? resp.content_type : "(not declared)"); | ||
| 345 | + { | ||
| 346 | + size_t nl = strlen(declared); | ||
| 347 | + char *cat = (char *)sx_malloc(nl + content_len + 1); | ||
| 348 | + memcpy(cat, declared, nl); | ||
| 349 | + if (content_len) memcpy(cat + nl, content, content_len); | ||
| 350 | + cat[nl + content_len] = '\0'; | ||
| 351 | + free(content); | ||
| 352 | + content = cat; | ||
| 353 | + content_len = nl + content_len; | ||
| 354 | + } | ||
| 355 | + } | ||
| 356 | + } | ||
| 357 | + } | ||
| 358 | + fx_response_free(&resp); | ||
| 359 | + free(title); | ||
| 360 | + | ||
| 361 | + /* Truncation footer, upstream-shaped. */ | ||
| 362 | + { | ||
| 363 | + size_t si = (size_t)start_index; | ||
| 364 | + size_t ml = (size_t)max_length; | ||
| 365 | + buf_t b; | ||
| 366 | + buf_init(&b); | ||
| 367 | + buf_addf(&b, "%sContents of %s:\n", | ||
| 368 | + prefix, out->final_url[0] ? out->final_url : url); | ||
| 369 | + if (si >= content_len) { | ||
| 370 | + buf_add(&b, "<error>No more content available.</error>"); | ||
| 371 | + } else { | ||
| 372 | + size_t take = content_len - si; | ||
| 373 | + if (take > ml) take = ml; | ||
| 374 | + buf_bput(&b, content + si, take); | ||
| 375 | + if (take == ml && si + take < content_len) | ||
| 376 | + buf_addf(&b, "\n\n<error>Content truncated. Call the fetch tool " | ||
| 377 | + "with a start_index of %zu to get more content.</error>", | ||
| 378 | + si + take); | ||
| 379 | + } | ||
| 380 | + out->text = b.p ? b.p : sx_strdup(""); | ||
| 381 | + out->text_len = b.n; | ||
| 382 | + out->content_len = content_len; | ||
| 383 | + } | ||
| 384 | + free(content); | ||
| 385 | + out->ok = 1; | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +/* ------------------------------------------------------------------ */ | ||
| 389 | +/* --mcp mode */ | ||
| 390 | +/* ------------------------------------------------------------------ */ | ||
| 391 | + | ||
| 392 | +static const char *FETCH_TOOL_SCHEMA = | ||
| 393 | + "{\"type\":\"object\",\"properties\":{" | ||
| 394 | + "\"url\":{\"type\":\"string\",\"description\":\"URL to fetch\"}," | ||
| 395 | + "\"max_length\":{\"type\":\"integer\",\"description\":\"Maximum number of characters to return.\",\"minimum\":1,\"maximum\":100000}," | ||
| 396 | + "\"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}," | ||
| 397 | + "\"raw\":{\"type\":\"boolean\",\"description\":\"Get the actual HTML content of the requested page, without simplification.\"}" | ||
| 398 | + "},\"required\":[\"url\"]}"; | ||
| 399 | + | ||
| 400 | +static void mcp_tools_list(FILE *out, const char *id_raw) | ||
| 401 | +{ | ||
| 402 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[", id_raw); | ||
| 403 | + fprintf(out, "{\"name\":\"fetch\",\"description\":\"Fetches a URL from the internet " | ||
| 404 | + "and optionally extracts its content as markdown. Follows up to 5 " | ||
| 405 | + "redirects, refuses private/loopback/link-local addresses unless the " | ||
| 406 | + "operator allows them, and truncates long results with a start_index " | ||
| 407 | + "hint.\",\"inputSchema\":%s," | ||
| 408 | + "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false," | ||
| 409 | + "\"idempotentHint\":true,\"openWorldHint\":true}}", | ||
| 410 | + FETCH_TOOL_SCHEMA); | ||
| 411 | + fprintf(out, "]}}\n"); | ||
| 412 | + fflush(out); | ||
| 413 | +} | ||
| 414 | + | ||
| 415 | +static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params) | ||
| 416 | +{ | ||
| 417 | + const char *name = NULL; | ||
| 418 | + yyjson_val *args = NULL; | ||
| 419 | + const char *url = NULL; | ||
| 420 | + long max_length = 5000, start_index = 0; | ||
| 421 | + int raw = 0; | ||
| 422 | + tool_result r; | ||
| 423 | + | ||
| 424 | + if (params) { | ||
| 425 | + yyjson_val *v; | ||
| 426 | + name = yyjson_get_str(yyjson_obj_get(params, "name")); | ||
| 427 | + args = yyjson_obj_get(params, "arguments"); | ||
| 428 | + if (args) { | ||
| 429 | + url = yyjson_get_str(yyjson_obj_get(args, "url")); | ||
| 430 | + v = yyjson_obj_get(args, "max_length"); | ||
| 431 | + if (yyjson_is_int(v)) max_length = (long)yyjson_get_int(v); | ||
| 432 | + else if (yyjson_is_str(v) && yyjson_get_str(v)) | ||
| 433 | + max_length = atol(yyjson_get_str(v)); | ||
| 434 | + v = yyjson_obj_get(args, "start_index"); | ||
| 435 | + if (yyjson_is_int(v)) start_index = (long)yyjson_get_int(v); | ||
| 436 | + else if (yyjson_is_str(v) && yyjson_get_str(v)) | ||
| 437 | + start_index = atol(yyjson_get_str(v)); | ||
| 438 | + v = yyjson_obj_get(args, "raw"); | ||
| 439 | + if (yyjson_is_true(v) || | ||
| 440 | + (yyjson_is_str(v) && yyjson_get_str(v) && | ||
| 441 | + strcmp(yyjson_get_str(v), "true") == 0)) | ||
| 442 | + raw = 1; | ||
| 443 | + } | ||
| 444 | + } | ||
| 445 | + if (!name || strcmp(name, "fetch") != 0) { | ||
| 446 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," | ||
| 447 | + "\"message\":\"unknown tool\"}}\n", id_raw); | ||
| 448 | + fflush(out); | ||
| 449 | + return; | ||
| 450 | + } | ||
| 451 | + | ||
| 452 | + memset(&r, 0, sizeof r); | ||
| 453 | + fetch_tool_run(url, max_length, start_index, raw, &r); | ||
| 454 | + | ||
| 455 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" | ||
| 456 | + "[{\"type\":\"text\",\"text\":", id_raw); | ||
| 457 | + if (r.ok) { | ||
| 458 | + json_escape(out, r.text ? r.text : ""); | ||
| 459 | + fprintf(out, "}],\"isError\":false}}\n"); | ||
| 460 | + } else { | ||
| 461 | + json_escape(out, r.error[0] ? r.error : "fetch failed"); | ||
| 462 | + fprintf(out, "}],\"isError\":true}}\n"); | ||
| 463 | + } | ||
| 464 | + fflush(out); | ||
| 465 | + tool_result_free(&r); | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +/* Copy the raw JSON-RPC id token (number or string) so the reply echoes the | ||
| 469 | + * same type. */ | ||
| 470 | +static int json_id_raw(const char *line, char *out, size_t outsz) | ||
| 471 | +{ | ||
| 472 | + const char *p = strstr(line, "\"id\""); | ||
| 473 | + size_t i = 0; | ||
| 474 | + if (!p) return 0; | ||
| 475 | + p += 4; | ||
| 476 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 477 | + if (*p != ':') return 0; | ||
| 478 | + p++; | ||
| 479 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 480 | + if (*p == '"') { | ||
| 481 | + out[i++] = *p++; | ||
| 482 | + while (*p && i + 2 < outsz) { | ||
| 483 | + out[i++] = *p; | ||
| 484 | + if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } | ||
| 485 | + else if (*p == '"') { p++; out[i++] = '"'; break; } | ||
| 486 | + else p++; | ||
| 487 | + } | ||
| 488 | + out[i] = '\0'; | ||
| 489 | + return i > 1; | ||
| 490 | + } | ||
| 491 | + while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && | ||
| 492 | + i + 1 < outsz) | ||
| 493 | + out[i++] = *p++; | ||
| 494 | + out[i] = '\0'; | ||
| 495 | + return i > 0; | ||
| 496 | +} | ||
| 497 | + | ||
| 498 | +static void mcp_server_info(FILE *out, const char *id_raw) | ||
| 499 | +{ | ||
| 500 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" | ||
| 501 | + "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," | ||
| 502 | + "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", | ||
| 503 | + id_raw, PLUGIN_SLUG, PLUGIN_VER); | ||
| 504 | + fflush(out); | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | +int run_mcp(void) | ||
| 508 | +{ | ||
| 509 | + char line[65536]; | ||
| 510 | + setvbuf(stdout, NULL, _IOLBF, 0); | ||
| 511 | + while (fgets(line, sizeof line, stdin)) { | ||
| 512 | + yyjson_doc *doc; | ||
| 513 | + yyjson_val *root, *m, *params; | ||
| 514 | + const char *method; | ||
| 515 | + char id_raw[128] = ""; | ||
| 516 | + | ||
| 517 | + if (!strchr(line, '{')) continue; | ||
| 518 | + doc = yyjson_read(line, strlen(line), 0); | ||
| 519 | + if (!doc) continue; | ||
| 520 | + root = yyjson_doc_get_root(doc); | ||
| 521 | + m = yyjson_obj_get(root, "method"); | ||
| 522 | + method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; | ||
| 523 | + params = yyjson_obj_get(root, "params"); | ||
| 524 | + if (!method) { yyjson_doc_free(doc); continue; } | ||
| 525 | + if (strncmp(method, "notifications/", 14) == 0) { | ||
| 526 | + yyjson_doc_free(doc); | ||
| 527 | + continue; | ||
| 528 | + } | ||
| 529 | + if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { | ||
| 530 | + yyjson_doc_free(doc); | ||
| 531 | + continue; | ||
| 532 | + } | ||
| 533 | + | ||
| 534 | + if (strcmp(method, "initialize") == 0) { | ||
| 535 | + mcp_server_info(stdout, id_raw); | ||
| 536 | + } else if (strcmp(method, "tools/list") == 0) { | ||
| 537 | + mcp_tools_list(stdout, id_raw); | ||
| 538 | + } else if (strcmp(method, "tools/call") == 0) { | ||
| 539 | + mcp_tool_call(stdout, id_raw, params); | ||
| 540 | + } else if (strcmp(method, "ping") == 0) { | ||
| 541 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); | ||
| 542 | + fflush(stdout); | ||
| 543 | + } else { | ||
| 544 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," | ||
| 545 | + "\"message\":\"method not found\"}}\n", id_raw); | ||
| 546 | + fflush(stdout); | ||
| 547 | + } | ||
| 548 | + yyjson_doc_free(doc); | ||
| 549 | + } | ||
| 550 | + return 0; | ||
| 551 | +} | ||
| 552 | + | ||
| 553 | +/* ------------------------------------------------------------------ */ | ||
| 554 | +/* Discovery metadata */ | ||
| 555 | +/* ------------------------------------------------------------------ */ | ||
| 556 | + | ||
| 557 | +static int run_meta(void) | ||
| 558 | +{ | ||
| 559 | + puts("{\"name\":\"fetch\",\"desc\":\"URL to Markdown\",\"kind\":\"mcp\"," | ||
| 560 | + "\"mcp\":true,\"daemon\":false,\"menus\":false,\"verified\":\"live\"}"); | ||
| 561 | + fflush(stdout); | ||
| 562 | + return 0; | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +/* ------------------------------------------------------------------ */ | ||
| 566 | +/* JSON node API */ | ||
| 567 | +/* ------------------------------------------------------------------ */ | ||
| 568 | + | ||
| 569 | +static void json_headers(void) | ||
| 570 | +{ | ||
| 571 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 572 | + "Cache-Control: no-store\r\n" | ||
| 573 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 574 | +} | ||
| 575 | + | ||
| 576 | +/* Walk the generated page and splice the shared bot theme in at the two | ||
| 577 | + * control bytes tools/gen_ui.py left behind: 0x01 becomes the pre-paint | ||
| 578 | + * script plus the token stylesheet, 0x02 the sx-theme handoff. Injecting here | ||
| 579 | + * (rather than pasting the macros into ui.html) is what keeps the theme from | ||
| 580 | + * drifting away from the rest of the bot. */ | ||
| 581 | +static void emit_ui(void) | ||
| 582 | +{ | ||
| 583 | + const char *p = UI_HTML; | ||
| 584 | + | ||
| 585 | + while (*p) { | ||
| 586 | + if (*p == '\001') { | ||
| 587 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | ||
| 588 | + "</style>", stdout); | ||
| 589 | + p++; | ||
| 590 | + } else if (*p == '\002') { | ||
| 591 | + fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); | ||
| 592 | + p++; | ||
| 593 | + } else { | ||
| 594 | + putchar(*p++); | ||
| 595 | + } | ||
| 596 | + } | ||
| 597 | +} | ||
| 598 | + | ||
| 599 | +static char *read_body(void) | ||
| 600 | +{ | ||
| 601 | + const char *cl = getenv("CONTENT_LENGTH"); | ||
| 602 | + long n; | ||
| 603 | + char *buf; | ||
| 604 | + size_t got = 0; | ||
| 605 | + if (!cl || !*cl) return NULL; | ||
| 606 | + n = atol(cl); | ||
| 607 | + if (n <= 0 || n > 2 * 1024 * 1024) return NULL; | ||
| 608 | + buf = (char *)sx_malloc((size_t)n + 1); | ||
| 609 | + while (got < (size_t)n) { | ||
| 610 | + size_t r = fread(buf + got, 1, (size_t)n - got, stdin); | ||
| 611 | + if (r == 0) break; | ||
| 612 | + got += r; | ||
| 613 | + } | ||
| 614 | + buf[got] = '\0'; | ||
| 615 | + return buf; | ||
| 616 | +} | ||
| 617 | + | ||
| 618 | +static int json_str_field(const char *json, const char *key, char *out, size_t outsz) | ||
| 619 | +{ | ||
| 620 | + yyjson_doc *doc; | ||
| 621 | + yyjson_val *v; | ||
| 622 | + int found = 0; | ||
| 623 | + if (!json) return 0; | ||
| 624 | + doc = yyjson_read(json, strlen(json), 0); | ||
| 625 | + if (!doc) return 0; | ||
| 626 | + v = yyjson_obj_get(yyjson_doc_get_root(doc), key); | ||
| 627 | + if (yyjson_is_str(v) && yyjson_get_str(v)) { | ||
| 628 | + snprintf(out, outsz, "%s", yyjson_get_str(v)); | ||
| 629 | + found = 1; | ||
| 630 | + } else if (yyjson_is_int(v)) { | ||
| 631 | + snprintf(out, outsz, "%lld", (long long)yyjson_get_int(v)); | ||
| 632 | + found = 1; | ||
| 633 | + } else if (yyjson_is_bool(v)) { | ||
| 634 | + snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); | ||
| 635 | + found = 1; | ||
| 636 | + } | ||
| 637 | + yyjson_doc_free(doc); | ||
| 638 | + return found; | ||
| 639 | +} | ||
| 640 | + | ||
| 641 | +static void emit_tool_json(const tool_result *r, const char *url_arg) | ||
| 642 | +{ | ||
| 643 | + json_headers(); | ||
| 644 | + if (!r->ok) { | ||
| 645 | + fputs("{\"ok\":false,\"error\":", stdout); | ||
| 646 | + json_escape(stdout, r->error[0] ? r->error : "fetch failed"); | ||
| 647 | + fputs("}\n", stdout); | ||
| 648 | + return; | ||
| 649 | + } | ||
| 650 | + fputs("{\"ok\":true,\"url\":", stdout); | ||
| 651 | + json_escape(stdout, r->final_url[0] ? r->final_url : (url_arg ? url_arg : "")); | ||
| 652 | + fprintf(stdout, ",\"status_code\":%d,\"redirected\":%s,\"content_type\":", | ||
| 653 | + r->status, r->redirected ? "true" : "false"); | ||
| 654 | + json_escape(stdout, r->content_type); | ||
| 655 | + fprintf(stdout, ",\"bytes_read\":%zu,\"content_length\":%zu,\"title\":", | ||
| 656 | + r->bytes_read, r->content_len); | ||
| 657 | + if (r->title[0]) json_escape(stdout, r->title); else fputs("null", stdout); | ||
| 658 | + fputs(",\"text\":", stdout); | ||
| 659 | + json_escape(stdout, r->text ? r->text : ""); | ||
| 660 | + fputs(",\"raw_html\":", stdout); | ||
| 661 | + json_escape(stdout, r->raw_html ? r->raw_html : ""); | ||
| 662 | + fputs("}\n", stdout); | ||
| 663 | +} | ||
| 664 | + | ||
| 665 | +static void api_info(void) | ||
| 666 | +{ | ||
| 667 | + json_headers(); | ||
| 668 | + fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG | ||
| 669 | + "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," | ||
| 670 | + "\"menus\":false,\"verified\":\"live\",\"tools\":[\"fetch\"],\"tool_schema\":", | ||
| 671 | + stdout); | ||
| 672 | + fputs(FETCH_TOOL_SCHEMA, stdout); | ||
| 673 | + fprintf(stdout, ",\"allow_private\":%s", policy_read_allow_private() ? "true" : "false"); | ||
| 674 | + fputs(",\"ssrf_policy\":\"private/loopback/link-local/special-purpose refused unless allowed\"," | ||
| 675 | + "\"tls\":\"verify-peer + CA bundle (POSIX mbedTLS); WinHTTP system root store (Windows)\"," | ||
| 676 | + "\"max_body_bytes\":", stdout); | ||
| 677 | + fprintf(stdout, "%u", FX_MAX_BODY); | ||
| 678 | + fputs(",\"max_length_cap\":100000,\"max_redirects\":5}\n", stdout); | ||
| 679 | +} | ||
| 680 | + | ||
| 681 | +static int api_dispatch(const char *action, const char *qs, const char *body) | ||
| 682 | +{ | ||
| 683 | + if (!action[0] || strcmp(action, "fetch") == 0) { | ||
| 684 | + char url[2048] = ""; | ||
| 685 | + char nbuf[64] = ""; | ||
| 686 | + long max_length = 5000, start_index = 0; | ||
| 687 | + int raw = 0; | ||
| 688 | + tool_result r; | ||
| 689 | + | ||
| 690 | + if (!(body && json_str_field(body, "url", url, sizeof url)) && | ||
| 691 | + !(qs && *qs && get_query_val(qs, "url", url, sizeof url))) | ||
| 692 | + url[0] = '\0'; | ||
| 693 | + if ((qs && *qs && get_query_val(qs, "max_length", nbuf, sizeof nbuf)) || | ||
| 694 | + (body && json_str_field(body, "max_length", nbuf, sizeof nbuf))) | ||
| 695 | + max_length = atol(nbuf); | ||
| 696 | + if ((qs && *qs && get_query_val(qs, "start_index", nbuf, sizeof nbuf)) || | ||
| 697 | + (body && json_str_field(body, "start_index", nbuf, sizeof nbuf))) | ||
| 698 | + start_index = atol(nbuf); | ||
| 699 | + if ((qs && *qs && get_query_val(qs, "raw", nbuf, sizeof nbuf)) || | ||
| 700 | + (body && json_str_field(body, "raw", nbuf, sizeof nbuf))) | ||
| 701 | + raw = (strcmp(nbuf, "1") == 0 || strcmp(nbuf, "true") == 0); | ||
| 702 | + | ||
| 703 | + memset(&r, 0, sizeof r); | ||
| 704 | + fetch_tool_run(url, max_length, start_index, raw, &r); | ||
| 705 | + emit_tool_json(&r, url); | ||
| 706 | + tool_result_free(&r); | ||
| 707 | + return 0; | ||
| 708 | + } | ||
| 709 | + | ||
| 710 | + if (strcmp(action, "info") == 0) { api_info(); return 0; } | ||
| 711 | + | ||
| 712 | + if (strcmp(action, "policy") == 0) { | ||
| 713 | + char val[16] = ""; | ||
| 714 | + json_headers(); | ||
| 715 | + if ((qs && *qs && get_query_val(qs, "allow_private", val, sizeof val)) || | ||
| 716 | + (body && json_str_field(body, "allow_private", val, sizeof val))) { | ||
| 717 | + int on = (strcmp(val, "1") == 0 || strcmp(val, "true") == 0); | ||
| 718 | + if (!policy_set_allow_private(on)) { | ||
| 719 | + fputs("{\"ok\":false,\"error\":\"policy_write_failed\"}\n", stdout); | ||
| 720 | + return 0; | ||
| 721 | + } | ||
| 722 | + fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", | ||
| 723 | + on ? "true" : "false"); | ||
| 724 | + } else { | ||
| 725 | + fprintf(stdout, "{\"ok\":true,\"allow_private\":%s}\n", | ||
| 726 | + policy_read_allow_private() ? "true" : "false"); | ||
| 727 | + } | ||
| 728 | + return 0; | ||
| 729 | + } | ||
| 730 | + | ||
| 731 | + json_headers(); | ||
| 732 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | ||
| 733 | + return 0; | ||
| 734 | +} | ||
| 735 | + | ||
| 736 | +/* ------------------------------------------------------------------ */ | ||
| 737 | +/* main */ | ||
| 738 | +/* ------------------------------------------------------------------ */ | ||
| 739 | + | ||
| 740 | +int main(int argc, char **argv) | ||
| 741 | +{ | ||
| 742 | + const char *qs; | ||
| 743 | + char action[64] = ""; | ||
| 744 | + char *body = NULL; | ||
| 745 | + int have_action = 0; | ||
| 746 | + | ||
| 747 | +#if defined(_WIN32) | ||
| 748 | + { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI | ||
| 749 | + * framing — force binary stdio. */ | ||
| 750 | + int mode = _O_BINARY; | ||
| 751 | + _setmode(_fileno(stdout), mode); | ||
| 752 | + _setmode(_fileno(stdin), mode); | ||
| 753 | + } | ||
| 754 | + { | ||
| 755 | + WSADATA wsa; | ||
| 756 | + WSAStartup(MAKEWORD(2, 2), &wsa); | ||
| 757 | + } | ||
| 758 | +#endif | ||
| 759 | + | ||
| 760 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) | ||
| 761 | + return run_meta(); | ||
| 762 | + if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); | ||
| 763 | + if (argc > 1 && strcmp(argv[1], "--schema") == 0) { | ||
| 764 | + puts(FETCH_TOOL_SCHEMA); | ||
| 765 | + return 0; | ||
| 766 | + } | ||
| 767 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | ||
| 768 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 769 | + return 0; | ||
| 770 | + } | ||
| 771 | + /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line, reading stdin | ||
| 772 | + * when no addresses are given. Pure policy, no DNS and no sockets, so the | ||
| 773 | + * suite can assert the whole SSRF matrix (including the IPv6 special | ||
| 774 | + * ranges) on a machine with no network at all. */ | ||
| 775 | + /* --selftest [addr ...] -> "<addr> denied=<0|1>" per line. With no | ||
| 776 | + * address arguments it reads them from stdin instead. Pure policy: no DNS | ||
| 777 | + * and no sockets, so the suite can assert the whole SSRF matrix | ||
| 778 | + * (including the IPv6 special ranges) on a machine with no network at | ||
| 779 | + * all, and a named-address call never waits on a terminal. */ | ||
| 780 | + if (argc > 1 && strcmp(argv[1], "--selftest") == 0) { | ||
| 781 | + char line[256]; | ||
| 782 | + int i; | ||
| 783 | + setvbuf(stdout, NULL, _IOLBF, 0); | ||
| 784 | + if (argc > 2) { | ||
| 785 | + for (i = 2; i < argc; i++) | ||
| 786 | + printf("%s denied=%d\n", argv[i], fx_ip_is_denied(argv[i]) ? 1 : 0); | ||
| 787 | + return 0; | ||
| 788 | + } | ||
| 789 | + while (fgets(line, sizeof line, stdin)) { | ||
| 790 | + char *p = line, *e; | ||
| 791 | + while (*p == ' ' || *p == '\t') p++; | ||
| 792 | + e = p + strlen(p); | ||
| 793 | + while (e > p && (e[-1] == '\n' || e[-1] == '\r' || | ||
| 794 | + e[-1] == ' ' || e[-1] == '\t')) *--e = '\0'; | ||
| 795 | + if (*p == '#') continue; /* comment line */ | ||
| 796 | + printf("%s denied=%d\n", p, fx_ip_is_denied(p) ? 1 : 0); | ||
| 797 | + } | ||
| 798 | + return 0; | ||
| 799 | + } | ||
| 800 | + qs = getenv("QUERY_STRING"); | ||
| 801 | + if (!qs) qs = ""; | ||
| 802 | + | ||
| 803 | + have_action = get_query_val(qs, "action", action, sizeof action); | ||
| 804 | + { | ||
| 805 | + /* ?format=json is the other documented way to ask for the JSON API. | ||
| 806 | + * Match it as a whole parameter with an exact value, never as a raw | ||
| 807 | + * substring, so a url= parameter that merely contains the text | ||
| 808 | + * "format=json" cannot flip the page into the API. */ | ||
| 809 | + char fmt[24] = ""; | ||
| 810 | + if (!have_action && get_query_val(qs, "format", fmt, sizeof fmt) && | ||
| 811 | + strcmp(fmt, "json") == 0) { | ||
| 812 | + snprintf(action, sizeof action, "fetch"); | ||
| 813 | + have_action = 1; | ||
| 814 | + } | ||
| 815 | + } | ||
| 816 | + | ||
| 817 | + { | ||
| 818 | + const char *rm = getenv("REQUEST_METHOD"); | ||
| 819 | + int is_post = rm && strcmp(rm, "POST") == 0; | ||
| 820 | + if (have_action || is_post) { | ||
| 821 | + require_node_auth(); | ||
| 822 | + body = read_body(); | ||
| 823 | + if (body) { | ||
| 824 | + char jact[64] = ""; | ||
| 825 | + if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) | ||
| 826 | + snprintf(action, sizeof action, "%s", jact); | ||
| 827 | + else if (!action[0]) | ||
| 828 | + snprintf(action, sizeof action, "fetch"); | ||
| 829 | + } else if (!action[0]) { | ||
| 830 | + snprintf(action, sizeof action, "fetch"); | ||
| 831 | + } | ||
| 832 | + return api_dispatch(action, qs, body); | ||
| 833 | + } | ||
| 834 | + } | ||
| 835 | + | ||
| 836 | + /* HTML UI */ | ||
| 837 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 838 | + "Cache-Control: no-store\r\n" | ||
| 839 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 840 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 841 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 842 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 843 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 844 | + emit_ui(); | ||
| 845 | + return 0; | ||
| 846 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..12c0d94 | index 0000000..12c0d94 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/sxbuf.c | +++ b/src/sxbuf.c | ||
| @@ -0,0 +1,179 @@ | @@ -0,0 +1,179 @@ | ||
| 1 | +/* | ||
| 2 | + * sxbuf.c - growable buffer + shared small helpers for plugin_fetch. | ||
| 3 | + */ | ||
| 4 | +#include "sxbuf.h" | ||
| 5 | + | ||
| 6 | +#include <stdlib.h> | ||
| 7 | +#include <string.h> | ||
| 8 | +#include <ctype.h> | ||
| 9 | +#include <stdarg.h> | ||
| 10 | + | ||
| 11 | +void *sx_malloc(size_t n) | ||
| 12 | +{ | ||
| 13 | + void *p = malloc(n ? n : 1); | ||
| 14 | + if (!p) { | ||
| 15 | + fputs("{\"ok\":false,\"error\":\"out of memory\"}\n", stdout); | ||
| 16 | + exit(1); | ||
| 17 | + } | ||
| 18 | + return p; | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +char *sx_strdup(const char *s) | ||
| 22 | +{ | ||
| 23 | + size_t n; | ||
| 24 | + char *p; | ||
| 25 | + if (!s) s = ""; | ||
| 26 | + n = strlen(s) + 1; | ||
| 27 | + p = (char *)sx_malloc(n); | ||
| 28 | + memcpy(p, s, n); | ||
| 29 | + return p; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/* ASCII-only case folding. We deliberately do not call strcasecmp(): MinGW | ||
| 33 | + * spells it _stricmp, glibc/musl declare it in <strings.h> behind a feature | ||
| 34 | + * test, and an HTTP header name or a media type must fold the same way in | ||
| 35 | + * every locale. */ | ||
| 36 | +static int sx_fold(int c) | ||
| 37 | +{ | ||
| 38 | + return (c >= 'A' && c <= 'Z') ? c + 32 : c; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +int sx_strncasecmp(const char *a, const char *b, size_t n) | ||
| 42 | +{ | ||
| 43 | + size_t i; | ||
| 44 | + for (i = 0; i < n; i++) { | ||
| 45 | + int x = sx_fold((unsigned char)a[i]); | ||
| 46 | + int y = sx_fold((unsigned char)b[i]); | ||
| 47 | + if (x != y) return x - y; | ||
| 48 | + if (!x) return 0; | ||
| 49 | + } | ||
| 50 | + return 0; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +int sx_strcasecmp(const char *a, const char *b) | ||
| 54 | +{ | ||
| 55 | + for (;; a++, b++) { | ||
| 56 | + int x = sx_fold((unsigned char)*a); | ||
| 57 | + int y = sx_fold((unsigned char)*b); | ||
| 58 | + if (x != y) return x - y; | ||
| 59 | + if (!x) return 0; | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +void buf_init(buf_t *b) | ||
| 64 | +{ | ||
| 65 | + b->p = NULL; | ||
| 66 | + b->n = 0; | ||
| 67 | + b->cap = 0; | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +void buf_free(buf_t *b) | ||
| 71 | +{ | ||
| 72 | + free(b->p); | ||
| 73 | + b->p = NULL; | ||
| 74 | + b->n = b->cap = 0; | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +static void buf_grow(buf_t *b, size_t need) | ||
| 78 | +{ | ||
| 79 | + size_t cap; | ||
| 80 | + char *np; | ||
| 81 | + if (b->cap >= need) return; | ||
| 82 | + cap = b->cap ? b->cap : 256; | ||
| 83 | + while (cap < need) cap *= 2; | ||
| 84 | + np = (char *)realloc(b->p, cap); | ||
| 85 | + if (!np) { | ||
| 86 | + fputs("{\"ok\":false,\"error\":\"out of memory\"}\n", stdout); | ||
| 87 | + exit(1); | ||
| 88 | + } | ||
| 89 | + b->p = np; | ||
| 90 | + b->cap = cap; | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +void buf_bput(buf_t *b, const char *s, size_t n) | ||
| 94 | +{ | ||
| 95 | + if (!s || !n) return; | ||
| 96 | + buf_grow(b, b->n + n + 1); | ||
| 97 | + memcpy(b->p + b->n, s, n); | ||
| 98 | + b->n += n; | ||
| 99 | + b->p[b->n] = '\0'; | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +void buf_add(buf_t *b, const char *s) | ||
| 103 | +{ | ||
| 104 | + if (s) buf_bput(b, s, strlen(s)); | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +void buf_addf(buf_t *b, const char *fmt, ...) | ||
| 108 | +{ | ||
| 109 | + va_list ap; | ||
| 110 | + int need; | ||
| 111 | + va_start(ap, fmt); | ||
| 112 | + need = vsnprintf(NULL, 0, fmt, ap); | ||
| 113 | + va_end(ap); | ||
| 114 | + if (need <= 0) return; | ||
| 115 | + buf_grow(b, b->n + (size_t)need + 1); | ||
| 116 | + va_start(ap, fmt); | ||
| 117 | + vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); | ||
| 118 | + va_end(ap); | ||
| 119 | + b->n += (size_t)need; | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +void url_decode(char *s) | ||
| 123 | +{ | ||
| 124 | + char *o = s; | ||
| 125 | + if (!s) return; | ||
| 126 | + while (*s) { | ||
| 127 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 128 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 129 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 130 | + *o++ = (char)((hi << 4) | lo); | ||
| 131 | + s += 3; | ||
| 132 | + } else if (*s == '+') { | ||
| 133 | + *o++ = ' '; | ||
| 134 | + s++; | ||
| 135 | + } else { | ||
| 136 | + *o++ = *s++; | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + *o = '\0'; | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 143 | +{ | ||
| 144 | + size_t klen; | ||
| 145 | + const char *p; | ||
| 146 | + if (!qs || !key || !out || outsz == 0) return 0; | ||
| 147 | + out[0] = '\0'; | ||
| 148 | + klen = strlen(key); | ||
| 149 | + p = qs; | ||
| 150 | + while (*p) { | ||
| 151 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 152 | + size_t i = 0; | ||
| 153 | + p += klen + 1; | ||
| 154 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | ||
| 155 | + out[i] = '\0'; | ||
| 156 | + url_decode(out); | ||
| 157 | + return 1; | ||
| 158 | + } | ||
| 159 | + p = strchr(p, '&'); | ||
| 160 | + if (!p) break; | ||
| 161 | + p++; | ||
| 162 | + } | ||
| 163 | + return 0; | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +void json_escape(FILE *out, const char *s) | ||
| 167 | +{ | ||
| 168 | + fputc('"', out); | ||
| 169 | + for (; s && *s; s++) { | ||
| 170 | + unsigned char c = (unsigned char)*s; | ||
| 171 | + if (c == '"' || c == '\\') { fputc('\\', out); fputc(c, out); } | ||
| 172 | + else if (c == '\n') fputs("\\n", out); | ||
| 173 | + else if (c == '\r') fputs("\\r", out); | ||
| 174 | + else if (c == '\t') fputs("\\t", out); | ||
| 175 | + else if (c < 0x20) fprintf(out, "\\u%04x", c); | ||
| 176 | + else fputc(c, out); | ||
| 177 | + } | ||
| 178 | + fputc('"', out); | ||
| 179 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..cec0ed0 | index 0000000..cec0ed0 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/sxbuf.h | +++ b/src/sxbuf.h | ||
| @@ -0,0 +1,37 @@ | @@ -0,0 +1,37 @@ | ||
| 1 | +/* | ||
| 2 | + * sxbuf.h - shared growable buffer + tiny string helpers used by every | ||
| 3 | + * module of plugin_fetch. Implementation in sxbuf.c. | ||
| 4 | + */ | ||
| 5 | +#ifndef SX_FETCH_BUF_H | ||
| 6 | +#define SX_FETCH_BUF_H | ||
| 7 | + | ||
| 8 | +#include <stddef.h> | ||
| 9 | +#include <stdio.h> | ||
| 10 | + | ||
| 11 | +typedef struct { | ||
| 12 | + char *p; | ||
| 13 | + size_t n; | ||
| 14 | + size_t cap; | ||
| 15 | +} buf_t; | ||
| 16 | + | ||
| 17 | +void buf_init(buf_t *b); | ||
| 18 | +void buf_free(buf_t *b); | ||
| 19 | +void buf_add(buf_t *b, const char *s); | ||
| 20 | +void buf_bput(buf_t *b, const char *s, size_t n); | ||
| 21 | +void buf_addf(buf_t *b, const char *fmt, ...); | ||
| 22 | + | ||
| 23 | +void *sx_malloc(size_t n); | ||
| 24 | +char *sx_strdup(const char *s); | ||
| 25 | + | ||
| 26 | +void url_decode(char *s); | ||
| 27 | +int get_query_val(const char *qs, const char *key, char *out, size_t outsz); | ||
| 28 | +void json_escape(FILE *out, const char *s); | ||
| 29 | + | ||
| 30 | +/* Case-insensitive compare with no platform dependency: MinGW spells these | ||
| 31 | + * _stricmp, glibc/musl hide them behind <strings.h>, and we only ever need | ||
| 32 | + * these two. ASCII only, locale-independent (which is what an HTTP header | ||
| 33 | + * name and a content-type want anyway). Implementation in sxbuf.c. */ | ||
| 34 | +int sx_strncasecmp(const char *a, const char *b, size_t n); | ||
| 35 | +int sx_strcasecmp(const char *a, const char *b); | ||
| 36 | + | ||
| 37 | +#endif /* SX_FETCH_BUF_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0f21bb7 | index 0000000..0f21bb7 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/sxmcp.h | +++ b/src/sxmcp.h | ||
| @@ -0,0 +1,35 @@ | @@ -0,0 +1,35 @@ | ||
| 1 | +/* | ||
| 2 | + * sxmcp.h - the MCP stdio server loop, implemented in plugin_fetch.c. | ||
| 3 | + */ | ||
| 4 | +#ifndef SX_FETCH_MCP_H | ||
| 5 | +#define SX_FETCH_MCP_H | ||
| 6 | + | ||
| 7 | +#include "yyjson.h" | ||
| 8 | +#include "sxbuf.h" | ||
| 9 | + | ||
| 10 | +/* MCP JSON-RPC 2.0 loop over stdin/stdout. Returns exit code. */ | ||
| 11 | +int run_mcp(void); | ||
| 12 | + | ||
| 13 | +/* Tool implementation shared by --mcp and the CGI API. | ||
| 14 | + * Fills `out` with model-facing text formatted like the upstream fetch | ||
| 15 | + * server's tool result. Returns with out->ok set. */ | ||
| 16 | +typedef struct { | ||
| 17 | + int ok; | ||
| 18 | + char error[1200]; | ||
| 19 | + char *text; /* heap */ | ||
| 20 | + size_t text_len; | ||
| 21 | + int status; | ||
| 22 | + char content_type[128]; | ||
| 23 | + size_t bytes_read; | ||
| 24 | + size_t content_len; /* length of the converted content before chunking */ | ||
| 25 | + char final_url[1024]; | ||
| 26 | + char title[256]; | ||
| 27 | + int redirected; | ||
| 28 | + char *raw_html; /* heap: original body, capped, for the UI Raw tab */ | ||
| 29 | +} tool_result; | ||
| 30 | + | ||
| 31 | +void fetch_tool_run(const char *url, long max_length, long start_index, int raw, | ||
| 32 | + tool_result *out); | ||
| 33 | +void tool_result_free(tool_result *r); | ||
| 34 | + | ||
| 35 | +#endif /* SX_FETCH_MCP_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b2e52d7 | index 0000000..b2e52d7 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,223 @@ | @@ -0,0 +1,223 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"> | ||
| 3 | +<head> | ||
| 4 | +<meta charset="utf-8"> | ||
| 5 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 6 | +<title>fetch - URL to Markdown</title> | ||
| 7 | +<!--TOKENS--> | ||
| 8 | +<style> | ||
| 9 | +*{box-sizing:border-box} | ||
| 10 | +body{margin:0;padding:16px;background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5} | ||
| 11 | +.wrap{max-width:1080px;margin:0 auto} | ||
| 12 | +h1{font-size:18px;margin:0 0 4px;font-weight:700} | ||
| 13 | +.sub{color:var(--text-2);font-size:12.5px;margin-bottom:16px} | ||
| 14 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:14px} | ||
| 15 | +.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center} | ||
| 16 | +input[type=text]{flex:1 1 320px;min-width:200px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px} | ||
| 17 | +input[type=number]{width:110px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px} | ||
| 18 | +label.chk{display:flex;align-items:center;gap:6px;color:var(--text-2);font-size:12.5px;user-select:none} | ||
| 19 | +button{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;font-weight:600;cursor:pointer;font-size:13px} | ||
| 20 | +button.sec{background:transparent;color:var(--blue);border:1px solid var(--line)} | ||
| 21 | +button:disabled{opacity:.5;cursor:default} | ||
| 22 | +.lbl{color:var(--text-2);font-size:12px;margin-right:2px} | ||
| 23 | +.pill{display:inline-block;padding:2px 10px;border-radius:980px;font-size:11.5px;font-weight:600;border:1px solid var(--line);color:var(--text-2)} | ||
| 24 | +.pill.ok{color:var(--green);border-color:var(--green)} | ||
| 25 | +.pill.warn{color:var(--orange);border-color:var(--orange)} | ||
| 26 | +.pill.bad{color:var(--red);border-color:var(--red)} | ||
| 27 | +.meta{display:flex;gap:14px;flex-wrap:wrap;color:var(--text-2);font-size:12px;margin:8px 0} | ||
| 28 | +.meta b{color:var(--text);font-weight:600;font-family:var(--mono)} | ||
| 29 | +pre.out{background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;overflow:auto;max-height:560px;white-space:pre-wrap;word-break:break-word;font-family:var(--mono);font-size:12px;margin:0} | ||
| 30 | +.tabs{display:flex;gap:6px;margin-bottom:10px} | ||
| 31 | +.tab{padding:5px 14px;border-radius:980px;border:1px solid var(--line);background:transparent;color:var(--text-2);cursor:pointer;font-size:12.5px;font-weight:600} | ||
| 32 | +.tab.on{background:var(--blue);border-color:var(--blue);color:#fff} | ||
| 33 | +.pager{display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap} | ||
| 34 | +.small{font-size:11.5px;color:var(--text-2)} | ||
| 35 | +.err{color:var(--red)} | ||
| 36 | +.grid{display:grid;grid-template-columns:1fr 1fr;gap:14px} | ||
| 37 | +@media(max-width:860px){.grid{grid-template-columns:1fr}} | ||
| 38 | +.pol{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-2)} | ||
| 39 | +h1 .tag{font-size:11px;color:var(--text-2);font-weight:500;margin-left:6px} | ||
| 40 | +html.embedded .embed-hide{display:none} | ||
| 41 | +</style> | ||
| 42 | +</head> | ||
| 43 | +<body> | ||
| 44 | +<div class="wrap"> | ||
| 45 | + <div class="embed-hide" style="margin-bottom:10px;display:flex;gap:10px;align-items:center;justify-content:space-between"> | ||
| 46 | + <a href="/" style="color:var(--blue);text-decoration:none;font-weight:600">← Back to Bot</a> | ||
| 47 | + <button class="sec" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | ||
| 48 | + </div> | ||
| 49 | + <h1>fetch<span class="tag">URL to Markdown · MCP connector</span></h1> | ||
| 50 | + <div class="sub">Preview the <b>fetch</b> tool exactly as an agent sees it. Private, loopback and link-local targets are refused unless the operator allows them. TLS certificates are always verified.</div> | ||
| 51 | + | ||
| 52 | + <div class="card"> | ||
| 53 | + <div class="row"> | ||
| 54 | + <input type="text" id="url" placeholder="https://example.com/article" spellcheck="false" autocomplete="off"> | ||
| 55 | + <button id="go" onclick="doFetch()">Fetch</button> | ||
| 56 | + </div> | ||
| 57 | + <div class="row" style="margin-top:10px"> | ||
| 58 | + <span class="lbl">max_length</span><input type="number" id="maxlen" value="5000" min="1" max="100000" step="1000"> | ||
| 59 | + <span class="lbl">start_index</span><input type="number" id="start" value="0" min="0" step="1"> | ||
| 60 | + <label class="chk"><input type="checkbox" id="raw"> raw (keep HTML)</label> | ||
| 61 | + <span class="small">redirects are followed up to 5 hops, each hop re-checked</span> | ||
| 62 | + </div> | ||
| 63 | + <div class="row" style="margin-top:10px"> | ||
| 64 | + <div class="pol"> | ||
| 65 | + <label class="chk"><input type="checkbox" id="allowpriv"> allow private/loopback (operator policy)</label> | ||
| 66 | + <span class="small">saved on the node</span> | ||
| 67 | + </div> | ||
| 68 | + </div> | ||
| 69 | + </div> | ||
| 70 | + | ||
| 71 | + <div class="card"> | ||
| 72 | + <div class="row" style="justify-content:space-between"> | ||
| 73 | + <div class="tabs" style="margin:0"> | ||
| 74 | + <button class="tab on" id="tabmd" onclick="setTab('md')">Markdown</button> | ||
| 75 | + <button class="tab" id="tabraw" onclick="setTab('raw')">Raw HTML</button> | ||
| 76 | + </div> | ||
| 77 | + <div id="status"><span class="pill">idle</span></div> | ||
| 78 | + </div> | ||
| 79 | + <div class="meta" id="meta" style="display:none"> | ||
| 80 | + <span>status <b id="mStatus">-</b></span> | ||
| 81 | + <span>type <b id="mType">-</b></span> | ||
| 82 | + <span>bytes <b id="mBytes">-</b></span> | ||
| 83 | + <span>content <b id="mLen">-</b></span> | ||
| 84 | + <span id="mRedirWrap">redirected <b id="mRedir">-</b></span> | ||
| 85 | + </div> | ||
| 86 | + <div id="mTitle" class="small" style="margin-bottom:6px"></div> | ||
| 87 | + <pre class="out" id="out">Enter a URL and press Fetch.</pre> | ||
| 88 | + <div class="pager" id="pager" style="display:none"> | ||
| 89 | + <button class="sec" onclick="prevChunk()">← Prev</button> | ||
| 90 | + <span class="small" id="pageInfo"></span> | ||
| 91 | + <button class="sec" onclick="nextChunk()">Next →</button> | ||
| 92 | + <button class="sec" onclick="copyOut()">Copy visible</button> | ||
| 93 | + </div> | ||
| 94 | + </div> | ||
| 95 | + | ||
| 96 | + <div class="card"> | ||
| 97 | + <div class="small" style="font-weight:600;color:var(--text);margin-bottom:6px">MCP tool (stdio <code>--mcp</code>)</div> | ||
| 98 | + <pre class="out" style="max-height:180px" id="schema">loading...</pre> | ||
| 99 | + <div class="small" style="margin-top:8px">Register through <b>sx-connector-mcp</b>: the router exposes it as <code>connector_call</code> → <code>fetch</code>. Args: <code>url</code> (required), <code>max_length</code> (default 5000, cap 100000), <code>start_index</code> (default 0), <code>raw</code> (default false).</div> | ||
| 100 | + </div> | ||
| 101 | +</div> | ||
| 102 | +<script> | ||
| 103 | +var q=new URLSearchParams(location.search); | ||
| 104 | +var HUB=q.get('plugin')||''; | ||
| 105 | +var node=q.get('node')||''; | ||
| 106 | +var sid=q.get('id')||''; | ||
| 107 | +var pwd=q.get('pwd')||localStorage.getItem('bot_active_pwd')||''; | ||
| 108 | +var PAGE=5000; | ||
| 109 | +var lastContentLen=0; | ||
| 110 | + | ||
| 111 | +function api(action,arg){ | ||
| 112 | + var parts=[]; | ||
| 113 | + for(var k in arg) parts.push(encodeURIComponent(k)+'='+encodeURIComponent(arg[k])); | ||
| 114 | + var qs='action='+encodeURIComponent(action)+(parts.length?'&'+parts.join('&'):'') | ||
| 115 | + +(node?'&node='+encodeURIComponent(node):'')+(sid?'&id='+encodeURIComponent(sid):'') | ||
| 116 | + +(pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 117 | + var u=HUB?('/plugins?plugin='+encodeURIComponent(HUB)+'&'+qs) | ||
| 118 | + :('/plugin_fetch?'+qs); | ||
| 119 | + var hdr=pwd?{'X-Bot-Password':pwd}:{}; | ||
| 120 | + return fetch(u,{headers:hdr}).then(function(r){ | ||
| 121 | + return r.json().then(function(d){ | ||
| 122 | + if(!r.ok&&!d.ok){d.error=(d.error||'request rejected')+' (http '+r.status+')';} | ||
| 123 | + return d; | ||
| 124 | + }); | ||
| 125 | + }); | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +function setTab(t){ | ||
| 129 | + document.getElementById('tabmd').classList.toggle('on',t==='md'); | ||
| 130 | + document.getElementById('tabraw').classList.toggle('on',t==='raw'); | ||
| 131 | + render(); | ||
| 132 | +} | ||
| 133 | +function pill(cls,txt){document.getElementById('status').innerHTML='<span class="pill '+cls+'">'+txt+'</span>';} | ||
| 134 | + | ||
| 135 | +var lastRaw='',lastMD=''; | ||
| 136 | +function render(){ | ||
| 137 | + var raw=document.getElementById('raw').checked; | ||
| 138 | + var show=(document.getElementById('tabraw').classList.contains('on')||raw)?lastRaw:lastMD; | ||
| 139 | + document.getElementById('out').textContent=show||'(empty)'; | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +function doFetch(){ | ||
| 143 | + var url=document.getElementById('url').value.trim(); | ||
| 144 | + var ml=parseInt(document.getElementById('maxlen').value||'5000',10); | ||
| 145 | + var si=parseInt(document.getElementById('start').value||'0',10); | ||
| 146 | + var raw=document.getElementById('raw').checked; | ||
| 147 | + if(!url){pill('bad','enter a URL');return;} | ||
| 148 | + pill('','fetching...'); | ||
| 149 | + document.getElementById('go').disabled=true; | ||
| 150 | + api('fetch',{url:url,max_length:ml,start_index:si,raw:raw?'true':'false'}) | ||
| 151 | + .then(function(d){ | ||
| 152 | + document.getElementById('go').disabled=false; | ||
| 153 | + if(!d.ok){pill('bad','failed'); | ||
| 154 | + document.getElementById('out').textContent=d.error||'fetch failed'; | ||
| 155 | + document.getElementById('meta').style.display='none'; | ||
| 156 | + document.getElementById('pager').style.display='none'; | ||
| 157 | + lastRaw='';lastMD=''; | ||
| 158 | + return;} | ||
| 159 | + pill(d.status_code>=400?'bad':'ok','HTTP '+d.status_code); | ||
| 160 | + lastMD=d.text||''; | ||
| 161 | + lastRaw=d.raw_html||''; | ||
| 162 | + lastContentLen=d.content_length||0; | ||
| 163 | + document.getElementById('meta').style.display='flex'; | ||
| 164 | + document.getElementById('mStatus').textContent=d.status_code; | ||
| 165 | + document.getElementById('mType').textContent=d.content_type||'-'; | ||
| 166 | + document.getElementById('mBytes').textContent=d.bytes_read; | ||
| 167 | + document.getElementById('mLen').textContent=d.content_length; | ||
| 168 | + document.getElementById('mRedir').textContent=d.redirected?'yes':'no'; | ||
| 169 | + document.getElementById('mTitle').textContent=d.title?('title: '+d.title):''; | ||
| 170 | + PAGE=Math.max(500,Math.min(100000,ml||5000)); | ||
| 171 | + document.getElementById('pager').style.display=(lastContentLen>(si+PAGE))?'flex':'none'; | ||
| 172 | + render(); | ||
| 173 | + }) | ||
| 174 | + .catch(function(e){ | ||
| 175 | + document.getElementById('go').disabled=false; | ||
| 176 | + pill('bad','error'); | ||
| 177 | + document.getElementById('out').textContent='Error: '+e; | ||
| 178 | + }); | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +function chunk(){return parseInt(document.getElementById('start').value||'0',10);} | ||
| 182 | +function setChunk(v){ | ||
| 183 | + v=Math.max(0,v); | ||
| 184 | + document.getElementById('start').value=v; | ||
| 185 | + doFetch(); | ||
| 186 | +} | ||
| 187 | +function nextChunk(){setChunk(chunk()+PAGE);} | ||
| 188 | +function prevChunk(){setChunk(chunk()-PAGE);} | ||
| 189 | + | ||
| 190 | +function copyOut(){ | ||
| 191 | + var t=document.getElementById('out').textContent; | ||
| 192 | + if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(t); | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +function loadPolicy(){ | ||
| 196 | + api('policy',{}).then(function(d){ | ||
| 197 | + if(d&&d.ok)document.getElementById('allowpriv').checked=!!d.allow_private; | ||
| 198 | + }).catch(function(){}); | ||
| 199 | +} | ||
| 200 | +document.getElementById('allowpriv').addEventListener('change',function(ev){ | ||
| 201 | + api('policy',{allow_private:ev.target.checked?'true':'false'}).catch(function(){}); | ||
| 202 | +}); | ||
| 203 | + | ||
| 204 | +function loadSchema(){ | ||
| 205 | + api('info',{}).then(function(d){ | ||
| 206 | + if(d&&d.tool_schema) | ||
| 207 | + document.getElementById('schema').textContent=JSON.stringify(d.tool_schema,null,2); | ||
| 208 | + else document.getElementById('schema').textContent='(unavailable)'; | ||
| 209 | + if(d&&typeof d.allow_private==='boolean') | ||
| 210 | + document.getElementById('allowpriv').checked=d.allow_private; | ||
| 211 | + }).catch(function(){document.getElementById('schema').textContent='(unavailable)';}); | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +document.getElementById('url').addEventListener('keydown',function(e){ | ||
| 215 | + if(e.key==='Enter')doFetch(); | ||
| 216 | +}); | ||
| 217 | +if(q.get('url'))document.getElementById('url').value=q.get('url'); | ||
| 218 | +loadPolicy(); | ||
| 219 | +loadSchema(); | ||
| 220 | +if(q.get('url')&&q.get('autofetch'))doFetch(); | ||
| 221 | +</script> | ||
| 222 | +</body> | ||
| 223 | +</html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8d533df | index 0000000..8d533df | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,231 @@ | @@ -0,0 +1,231 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_FETCH_UI_HTML_H | ||
| 3 | +#define SX_FETCH_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\">\n" | ||
| 8 | + "<head>\n" | ||
| 9 | + "<meta charset=\"utf-8\">\n" | ||
| 10 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 11 | + "<title>fetch - URL to Markdown</title>\n" | ||
| 12 | + "\001\n" | ||
| 13 | + "<style>\n" | ||
| 14 | + "*{box-sizing:border-box}\n" | ||
| 15 | + "body{margin:0;padding:16px;background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5}\n" | ||
| 16 | + ".wrap{max-width:1080px;margin:0 auto}\n" | ||
| 17 | + "h1{font-size:18px;margin:0 0 4px;font-weight:700}\n" | ||
| 18 | + ".sub{color:var(--text-2);font-size:12.5px;margin-bottom:16px}\n" | ||
| 19 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:14px}\n" | ||
| 20 | + ".row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}\n" | ||
| 21 | + "input[type=text]{flex:1 1 320px;min-width:200px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px}\n" | ||
| 22 | + "input[type=number]{width:110px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);font-size:12.5px}\n" | ||
| 23 | + "label.chk{display:flex;align-items:center;gap:6px;color:var(--text-2);font-size:12.5px;user-select:none}\n" | ||
| 24 | + "button{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;font-weight:600;cursor:pointer;font-size:13px}\n" | ||
| 25 | + "button.sec{background:transparent;color:var(--blue);border:1px solid var(--line)}\n" | ||
| 26 | + "button:disabled{opacity:.5;cursor:default}\n" | ||
| 27 | + ".lbl{color:var(--text-2);font-size:12px;margin-right:2px}\n" | ||
| 28 | + ".pill{display:inline-block;padding:2px 10px;border-radius:980px;font-size:11.5px;font-weight:600;border:1px solid var(--line);color:var(--text-2)}\n" | ||
| 29 | + ".pill.ok{color:var(--green);border-color:var(--green)}\n" | ||
| 30 | + ".pill.warn{color:var(--orange);border-color:var(--orange)}\n" | ||
| 31 | + ".pill.bad{color:var(--red);border-color:var(--red)}\n" | ||
| 32 | + ".meta{display:flex;gap:14px;flex-wrap:wrap;color:var(--text-2);font-size:12px;margin:8px 0}\n" | ||
| 33 | + ".meta b{color:var(--text);font-weight:600;font-family:var(--mono)}\n" | ||
| 34 | + "pre.out{background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;overflow:auto;max-height:560px;white-space:pre-wrap;word-break:break-word;font-family:var(--mono);font-size:12px;margin:0}\n" | ||
| 35 | + ".tabs{display:flex;gap:6px;margin-bottom:10px}\n" | ||
| 36 | + ".tab{padding:5px 14px;border-radius:980px;border:1px solid var(--line);background:transparent;color:var(--text-2);cursor:pointer;font-size:12.5px;font-weight:600}\n" | ||
| 37 | + ".tab.on{background:var(--blue);border-color:var(--blue);color:#fff}\n" | ||
| 38 | + ".pager{display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap}\n" | ||
| 39 | + ".small{font-size:11.5px;color:var(--text-2)}\n" | ||
| 40 | + ".err{color:var(--red)}\n" | ||
| 41 | + ".grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}\n" | ||
| 42 | + "@media(max-width:860px){.grid{grid-template-columns:1fr}}\n" | ||
| 43 | + ".pol{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-2)}\n" | ||
| 44 | + "h1 .tag{font-size:11px;color:var(--text-2);font-weight:500;margin-left:6px}\n" | ||
| 45 | + "html.embedded .embed-hide{display:none}\n" | ||
| 46 | + "</style>\n" | ||
| 47 | + "</head>\n" | ||
| 48 | + "<body>\n" | ||
| 49 | + "<div class=\"wrap\">\n" | ||
| 50 | + " <div class=\"embed-hide\" style=\"margin-bottom:10px;display:flex;gap:10px;align-items:center;justify-content:space-between\">\n" | ||
| 51 | + " <a href=\"/\" style=\"color:var(--blue);text-decoration:none;font-weight:600\">← Back to Bot</a>\n" | ||
| 52 | + " <button class=\"sec\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | ||
| 53 | + " </div>\n" | ||
| 54 | + " <h1>fetch<span class=\"tag\">URL to Markdown · MCP connector</span></h1>\n" | ||
| 55 | + " <div class=\"sub\">Preview the <b>fetch</b> tool exactly as an agent sees it. Private, loopback and link-local targets are refused unless the operator allows them. TLS certificates are always verified.</div>\n" | ||
| 56 | + "\n" | ||
| 57 | + " <div class=\"card\">\n" | ||
| 58 | + " <div class=\"row\">\n" | ||
| 59 | + " <input type=\"text\" id=\"url\" placeholder=\"https://example.com/article\" spellcheck=\"false\" autocomplete=\"off\">\n" | ||
| 60 | + " <button id=\"go\" onclick=\"doFetch()\">Fetch</button>\n" | ||
| 61 | + " </div>\n" | ||
| 62 | + " <div class=\"row\" style=\"margin-top:10px\">\n" | ||
| 63 | + " <span class=\"lbl\">max_length</span><input type=\"number\" id=\"maxlen\" value=\"5000\" min=\"1\" max=\"100000\" step=\"1000\">\n" | ||
| 64 | + " <span class=\"lbl\">start_index</span><input type=\"number\" id=\"start\" value=\"0\" min=\"0\" step=\"1\">\n" | ||
| 65 | + " <label class=\"chk\"><input type=\"checkbox\" id=\"raw\"> raw (keep HTML)</label>\n" | ||
| 66 | + " <span class=\"small\">redirects are followed up to 5 hops, each hop re-checked</sp |