scorpiox-bot-plugin-filesystem
←plugin_filesystem.cc
3524 lines · 120 KBHEADBlameDownload
1/*
2 * plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP
3 * connector for your node
4 *
5 * A clean-room rewrite (pure C99, zero dependencies) of the tool surface of
6 * modelcontextprotocol/servers `src/filesystem`, reshaped as a SCORPIOX BOT
7 * connector plugin: ONE binary, FOUR modes.
8 *
9 * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata (unauthenticated)
10 * 2. --mcp -> MCP JSON-RPC 2.0 over stdio
11 * (initialize / tools/list / tools/call)
12 * 3. ?action=... / ?format=json -> JSON control API (require_node_auth)
13 * 4. GET (default) -> Allowed Roots & Permissions page
14 *
15 * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git
16 *
17 * SANDBOX BY CONSTRUCTION. There is no popen, no system, no socket anywhere
18 * in this file: the plugin touches the filesystem and nothing else. Every
19 * path that arrives in a tool call or an HTTP request is canonicalised on the
20 * real filesystem (realpath() on POSIX, GetFullPathNameA +
21 * GetFinalPathNameByHandleA on Windows) and prefix-checked against the
22 * allowlisted roots AFTER symlink resolution. `..`, embedded NUL bytes and
23 * symlinks that point outside the roots are refused with an explicit error.
24 * /proc, /sys and /dev are refused even when they sit under an allowed root.
25 *
26 * Two forms of every root are kept (the configured path AND its realpath),
27 * which is what lets a user configure /tmp on macOS and still reach the
28 * files that realpath resolves under /private/tmp.
29 *
30 * Roots come from
31 * ~/.scorpiox/connectors/plugin_filesystem/roots.json (or the node's
32 * /workspace/.scorpiox/connectors/... equivalent), overridable with the
33 * FS_ALLOWED_ROOTS environment variable for tests, and defaulting to
34 * /workspace or $HOME when nothing is configured.
35 *
36 * MIT License. Copyright (c) 2026 SCORPIOX INC.
37 */
38
39/* Must come before every include on Windows: MinGW defaults to 0x502
40 * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */
41#if defined(_WIN32) && !defined(_WIN32_WINNT)
42# define _WIN32_WINNT 0x0601
43#endif
44
45#if !defined(_WIN32)
46# define _POSIX_C_SOURCE 200809L
47# define _DEFAULT_SOURCE 1
48# if defined(__APPLE__)
49# define _DARWIN_C_SOURCE 1
50# endif
51#endif
52
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <stdarg.h>
57#include <ctype.h>
58#include <errno.h>
59#include <time.h>
60
61#if defined(_WIN32)
62# define WIN32_LEAN_AND_MEAN
63# include <windows.h>
64# include <direct.h>
65# include <io.h>
66# include <fcntl.h>
67 /* WIN32_LEAN_AND_MEAN trims the transitive <sys/stat.h> that mingw's
68 * <io.h> used to drag in, so include it by name - the stat/lstat
69 * helpers below are shared by both platforms. */
70# include <sys/stat.h>
71# include <sys/types.h>
72# define SEP '\\'
73# define PATH_SPLITCH '\\'
74#else
75# include <unistd.h>
76# include <sys/stat.h>
77# include <sys/types.h>
78# include <dirent.h>
79# define SEP '/'
80# define PATH_SPLITCH '/'
81#endif
82
83#include "yyjson.h"
84
85#include "bot_theme_plugin.h"
86#include "ui_html.h"
87
88#define PLUGIN_SLUG "filesystem"
89#define PLUGIN_ID "plugin_filesystem"
90#define PLUGIN_VER "1.0.1"
91#define PLUGIN_NAME "filesystem"
92#define PLUGIN_DESC "Allowlist FS"
93#define MCP_PROTO "2024-11-05"
94
95#define PATH_SZ 4096
96#define NAME_SZ 512
97#define MAX_ROOTS 16
98#define MAX_ENTRIES 5000 /* entries listed per directory */
99#define WALK_BUDGET 20000 /* entries visited per tree/search */
100#define MAX_RESULTS 1000 /* search_files matches */
101#define MAX_DEPTH 24 /* recursive walk guard */
102#define READ_CAP ((size_t)10 * 1024 * 1024) /* 10 MiB per file */
103#define WRITE_CAP ((size_t)8 * 1024 * 1024) /* 8 MiB body per write */
104#define BIN_PROBE 8192
105#define IO_CHUNK 65536
106#define MCP_LINE_CAP ((size_t)64 * 1024 * 1024) /* one request line */
107#define TOOLS_N 11
108
109/* ------------------------------------------------------------------ */
110/* Growable byte buffer */
111/* ------------------------------------------------------------------ */
112
113typedef struct {
114 char *p;
115 size_t n;
116 size_t cap;
117} buf_t;
118
119static void buf_init(buf_t *b)
120{
121 b->p = NULL;
122 b->n = 0;
123 b->cap = 0;
124}
125
126static int buf_need(buf_t *b, size_t extra)
127{
128 size_t want = b->n + extra + 1;
129 char *np;
130 if (want <= b->cap) return 1;
131 if (b->cap == 0) b->cap = 1024;
132 while (b->cap < want) {
133 if (b->cap > (size_t)256 * 1024 * 1024) return 0;
134 b->cap *= 2;
135 }
136 np = (char *)realloc(b->p, b->cap);
137 if (!np) return 0;
138 b->p = np;
139 return 1;
140}
141
142static void buf_add(buf_t *b, const char *s, size_t n)
143{
144 if (n == 0) return;
145 if (!buf_need(b, n)) return;
146 memcpy(b->p + b->n, s, n);
147 b->n += n;
148 b->p[b->n] = '\0';
149}
150
151static void buf_puts(buf_t *b, const char *s)
152{
153 if (s) buf_add(b, s, strlen(s));
154}
155
156static void buf_putc(buf_t *b, char c)
157{
158 if (!buf_need(b, 1)) return;
159 b->p[b->n++] = c;
160 b->p[b->n] = '\0';
161}
162
163static const char *buf_str(buf_t *b)
164{
165 return b->p ? b->p : "";
166}
167
168static void buf_printf(buf_t *b, const char *fmt, ...)
169{
170 char tmp[1024];
171 va_list ap;
172 int n;
173 va_start(ap, fmt);
174 n = vsnprintf(tmp, sizeof tmp, fmt, ap);
175 va_end(ap);
176 if (n < 0) return;
177 if ((size_t)n < sizeof tmp) {
178 buf_add(b, tmp, (size_t)n);
179 return;
180 }
181 {
182 char *big = (char *)malloc((size_t)n + 1);
183 if (!big) return;
184 va_start(ap, fmt);
185 vsnprintf(big, (size_t)n + 1, fmt, ap);
186 va_end(ap);
187 buf_add(b, big, (size_t)n);
188 free(big);
189 }
190}
191
192static void buf_free(buf_t *b)
193{
194 free(b->p);
195 b->p = NULL;
196 b->n = 0;
197 b->cap = 0;
198}
199
200/* ------------------------------------------------------------------ */
201/* Small utilities */
202/* ------------------------------------------------------------------ */
203
204static void str_copy(char *dst, size_t sz, const char *src)
205{
206 size_t n;
207 if (!dst || sz == 0) return;
208 if (!src) { dst[0] = '\0'; return; }
209 n = strlen(src);
210 if (n >= sz) n = sz - 1;
211 memcpy(dst, src, n);
212 dst[n] = '\0';
213}
214
215static int str_ieq(const char *a, const char *b)
216{
217 for (; *a && *b; a++, b++) {
218 if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
219 }
220 return *a == *b;
221}
222
223#if defined(_WIN32)
224static void rstrip_sep(char *s)
225{
226 size_t n = strlen(s);
227 while (n > 3 && (s[n - 1] == '\\' || s[n - 1] == '/')) s[--n] = '\0';
228}
229#endif
230
231static void path_join(char *out, size_t sz, const char *a, const char *b)
232{
233 size_t n;
234 if (!out || sz == 0) return;
235 out[0] = '\0';
236 if (!a) a = "";
237 if (!b) b = "";
238 str_copy(out, sz, a);
239 n = strlen(out);
240 if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) {
241 out[n++] = SEP;
242 out[n] = '\0';
243 }
244 if (n + strlen(b) < sz) str_copy(out + n, sz - n, b);
245}
246
247static void url_decode(char *s)
248{
249 char *o = s;
250 if (!s) return;
251 while (*s) {
252 if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
253 int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
254 int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
255 *o++ = (char)((hi << 4) | lo);
256 s += 3;
257 } else if (*s == '+') {
258 *o++ = ' ';
259 s++;
260 } else {
261 *o++ = *s++;
262 }
263 }
264 *o = '\0';
265}
266
267static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
268{
269 size_t klen;
270 const char *p;
271
272 if (!out || outsz == 0) return 0;
273 out[0] = '\0';
274 if (!qs || !key) return 0;
275 klen = strlen(key);
276
277 for (p = qs; *p; ) {
278 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
279 const char *v = p + klen + 1;
280 size_t i = 0;
281 while (*v && *v != '&' && i + 1 < outsz)
282 out[i++] = *v++;
283 out[i] = '\0';
284 url_decode(out);
285 return 1;
286 }
287 p = strchr(p, '&');
288 if (!p) break;
289 p++;
290 }
291 return 0;
292}
293
294/* JSON-escape s into b (quotes included). Bytes are passed through so
295 * UTF-8 file content survives; control characters are escaped. */
296static void json_str(buf_t *b, const char *s)
297{
298 buf_putc(b, '"');
299 for (; s && *s; s++) {
300 unsigned char c = (unsigned char)*s;
301 switch (c) {
302 case '"': buf_puts(b, "\\\""); break;
303 case '\\': buf_puts(b, "\\\\"); break;
304 case '\n': buf_puts(b, "\\n"); break;
305 case '\r': buf_puts(b, "\\r"); break;
306 case '\t': buf_puts(b, "\\t"); break;
307 default:
308 if (c < 0x20) {
309 char tmp[8];
310 sprintf(tmp, "\\u%04x", c);
311 buf_puts(b, tmp);
312 } else {
313 buf_putc(b, (char)c);
314 }
315 }
316 }
317 buf_putc(b, '"');
318}
319
320static void fmt_iso(long long t, char *out, size_t sz)
321{
322 time_t tt = (time_t)t;
323 struct tm tmv;
324#if defined(_WIN32)
325 gmtime_s(&tmv, &tt);
326#else
327 gmtime_r(&tt, &tmv);
328#endif
329 strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
330}
331
332
333/* ------------------------------------------------------------------ */
334/* yyjson helpers */
335/* */
336/* yyjson (vendored, MIT, upstream yyjson/yyjson) is the only thing */
337/* that touches JSON structure. Requests are read with yyjson_read() */
338/* (no insitu, so the request buffer is never mutated and never needs */
339/* a terminator), and every response is written through the buf_t */
340/* helpers below so a 10 MiB file body is escaped exactly once. */
341/* ------------------------------------------------------------------ */
342
343/* JSON strings may carry \u0000. yyjson keeps the whole length but the C
344 * pointer truncates at the NUL, so "a.txt\0secret" would silently become
345 * "a.txt" - a path the caller never asked for. Any string we treat as a path,
346 * pattern or text must therefore be NUL-free; ju_cstr is the gate. */
347static const char *ju_cstr(yyjson_val *v)
348{
349 const char *s;
350 if (!v || !yyjson_is_str(v)) return NULL;
351 s = yyjson_get_str(v);
352 if (!s) return NULL;
353 if (strlen(s) != yyjson_get_len(v)) return NULL; /* embedded NUL */
354 return s;
355}
356
357static const char *ju_str(yyjson_val *o, const char *key)
358{
359 if (!o) return NULL;
360 return ju_cstr(yyjson_obj_get(o, key));
361}
362
363static long long ju_int(yyjson_val *o, const char *key, long long dflt, int *present)
364{
365 yyjson_val *v;
366 if (present) *present = 0;
367 if (!o) return dflt;
368 v = yyjson_obj_get(o, key);
369 if (!v) return dflt;
370 if (yyjson_is_num(v)) {
371 if (present) *present = 1;
372 return (long long)yyjson_get_num(v);
373 }
374 if (yyjson_is_str(v)) { /* {"head":"20"} is what a
375 * chatty model often sends */
376 char *endp = NULL;
377 long long n = strtoll(yyjson_get_str(v), &endp, 10);
378 if (endp && *endp == '\0' && endp != yyjson_get_str(v)) {
379 if (present) *present = 1;
380 return n;
381 }
382 }
383 return dflt;
384}
385
386static int ju_bool(yyjson_val *o, const char *key, int dflt)
387{
388 yyjson_val *v;
389 if (!o) return dflt;
390 v = yyjson_obj_get(o, key);
391 if (!v) return dflt;
392 if (yyjson_is_bool(v)) return yyjson_get_bool(v) ? 1 : 0;
393 if (yyjson_is_str(v)) return str_ieq(yyjson_get_str(v), "true");
394 if (yyjson_is_int(v)) return yyjson_get_sint(v) != 0;
395 return dflt;
396}
397
398/* Coerce a string field that may arrive as a number (an agent that sends
399 * {"head":20}) instead of "20". Returns 1 when the key exists at all. */
400static int ju_field_str(yyjson_val *o, const char *key, char *out, size_t outsz)
401{
402 yyjson_val *v;
403 if (!o) return 0;
404 v = yyjson_obj_get(o, key);
405 if (!v) return 0;
406 if (yyjson_is_str(v)) {
407 const char *s = ju_cstr(v);
408 if (!s) return 0; /* embedded NUL: refuse, never truncate */
409 str_copy(out, outsz, s);
410 return 1;
411 }
412 if (yyjson_is_int(v)) {
413 snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v));
414 return 1;
415 }
416 if (yyjson_is_uint(v)) {
417 snprintf(out, outsz, "%llu", (unsigned long long)yyjson_get_uint(v));
418 return 1;
419 }
420 if (yyjson_is_real(v)) {
421 snprintf(out, outsz, "%g", yyjson_get_real(v));
422 return 1;
423 }
424 if (yyjson_is_bool(v)) {
425 str_copy(out, outsz, yyjson_get_bool(v) ? "true" : "false");
426 return 1;
427 }
428 return 0;
429}
430
431/* ------------------------------------------------------------------ */
432/* Node auth (CGI modes only; --meta and --mcp are exempt) */
433/* ------------------------------------------------------------------ */
434
435static void require_node_auth(void)
436{
437 const char *np = getenv("BOT_PASSWORD");
438 const char *xp;
439 const char *auth;
440 const char *qs;
441 char qpwd[256];
442
443 if (!np || !*np) return;
444
445 xp = getenv("HTTP_X_BOT_PASSWORD");
446 if (xp && strcmp(xp, np) == 0) return;
447
448 auth = getenv("HTTP_AUTHORIZATION");
449 if (auth) {
450 while (*auth == ' ') auth++;
451 if (strncmp(auth, "Bearer ", 7) == 0) {
452 auth += 7;
453 while (*auth == ' ') auth++;
454 if (strcmp(auth, np) == 0) return;
455 }
456 }
457
458 qs = getenv("QUERY_STRING");
459 if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
460 return;
461
462 fputs("Status: 401 Unauthorized\r\n"
463 "Content-Type: application/json; charset=utf-8\r\n"
464 "Cache-Control: no-store\r\n"
465 "X-Content-Type-Options: nosniff\r\n\r\n"
466 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
467 exit(0);
468}
469
470/* ------------------------------------------------------------------ */
471/* Allowed roots */
472/* */
473/* Each root is stored TWICE where the two forms differ: the path the */
474/* operator configured and its canonical realpath. That is what makes */
475/* a configured /tmp work on macOS, where realpath answers /private/ */
476/* tmp, and it is also what lets the UI show an operator whose root */
477/* has drifted (a symlinked home, a mounted volume) before they file */
478/* a bug about a tool that "cannot see my files". */
479/* ------------------------------------------------------------------ */
480
481typedef struct {
482 char configured[PATH_SZ];
483 char canonical[PATH_SZ];
484 int exists;
485 int is_dir;
486} root_t;
487
488static root_t g_roots[MAX_ROOTS];
489static int g_root_count;
490static int g_tool_off[TOOLS_N]; /* permissions: 1 = disabled */
491static char g_roots_file[PATH_SZ];
492
493static int deny_count;
494static char g_deny[MAX_ROOTS][PATH_SZ];
495
496/* Tool names in registration order - the same order tools/list reports. */
497static const char *TOOL_NAMES[TOOLS_N] = {
498 "read_text_file", "read_multiple_files", "write_file", "edit_file",
499 "create_directory", "list_directory", "directory_tree", "move_file",
500 "search_files", "get_file_info", "list_allowed_directories"
501};
502
503static int tool_index(const char *name)
504{
505 int i;
506 if (!name) return -1;
507 for (i = 0; i < TOOLS_N; i++)
508 if (strcmp(TOOL_NAMES[i], name) == 0) return i;
509 return -1;
510}
511
512/* ------------------------------------------------------------------ */
513/* Path canonicalisation */
514/* ------------------------------------------------------------------ */
515
516#if defined(_WIN32)
517
518static void win_norm(char *s)
519{
520 for (; *s; s++) {
521 if (*s == '/') *s = '\\';
522 *s = (char)tolower((unsigned char)*s);
523 }
524}
525
526static int path_under_p(const char *p, const char *root)
527{
528 char a[PATH_SZ], b[PATH_SZ];
529 size_t n;
530 str_copy(a, sizeof a, p);
531 str_copy(b, sizeof b, root);
532 win_norm(a);
533 win_norm(b);
534 n = strlen(b);
535 while (n > 3 && b[n - 1] == '\\') b[--n] = '\0';
536 if (strcmp(a, b) == 0) return 1;
537 if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1;
538 return 0;
539}
540
541#else /* POSIX */
542
543static int path_under_p(const char *p, const char *root)
544{
545 size_t n;
546 if (!p || !root) return 0;
547 n = strlen(root);
548 if (strcmp(p, root) == 0) return 1;
549 if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0;
550 if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1;
551 return 0;
552}
553
554#endif /* platform prefix check */
555
556/* Lexical normalisation only: no filesystem access, so it works for a path
557 * that does not exist yet (write_file, create_directory). Because
558 * path_shape_ok() has already rejected every ".." segment, collapsing
559 * separators here cannot be used to walk out of anything. */
560static int lexical_abs(const char *raw, char *out, size_t outsz)
561{
562 size_t i, o = 0;
563 int last_sep = 1; /* the head counts as a sep */
564
565 if (!raw || !*raw) return 0;
566#if defined(_WIN32)
567 {
568 char full[PATH_SZ];
569 DWORD n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL);
570 if (n == 0 || n >= (DWORD)sizeof full) return 0;
571 str_copy(out, outsz, full);
572 rstrip_sep(out);
573 return out[0] ? 1 : 0;
574 }
575#else
576 if (raw[0] != '/') return 0;
577 if (outsz < 2) return 0;
578 out[o++] = '/'; /* absolute, always */
579 for (i = 1; raw[i]; i++) {
580 char c = raw[i];
581 if (c == '\\') c = '/';
582 if (c == '/') {
583 if (last_sep) continue;
584 if (o + 1 >= outsz) return 0;
585 out[o++] = '/';
586 last_sep = 1;
587 /* collapse a "." segment: /a/./b behaves as /a/b */
588 if (raw[i + 1] == '.' &&
589 (raw[i + 2] == '/' || raw[i + 2] == '\\' || raw[i + 2] == '\0'))
590 i++;
591 continue;
592 }
593 if (o + 1 >= outsz) return 0;
594 out[o++] = c;
595 last_sep = 0;
596 }
597 if (o == 0) { out[0] = '/'; out[1] = '\0'; return 1; }
598 while (o > 1 && out[o - 1] == '/') o--;
599 out[o] = '\0';
600 return 1;
601#endif
602}
603
604/* Lexical form, used when the target does not exist yet. */
605static int norm_lex(const char *raw, char *out, size_t outsz)
606{
607 return lexical_abs(raw, out, outsz);
608}
609
610/* Full canonicalisation: resolves every symlink that exists on disk. */
611static int canon_path(const char *raw, char *out, size_t outsz)
612{
613#if defined(_WIN32)
614 char full[PATH_SZ];
615 HANDLE h;
616 char final[PATH_SZ];
617
618 if (!lexical_abs(raw, full, sizeof full)) return 0;
619 if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) return 0;
620 h = CreateFileA(full, 0,
621 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
622 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
623 if (h != INVALID_HANDLE_VALUE) {
624 DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0);
625 CloseHandle(h);
626 if (fn > 0 && fn < (DWORD)sizeof final) {
627 char *src = final;
628 if (strncmp(src, "\\\\?\\", 4) == 0) src += 4;
629 str_copy(out, outsz, src);
630 return 1;
631 }
632 }
633 str_copy(out, outsz, full);
634 return 1;
635#else
636 char *r;
637 char lex[PATH_SZ];
638 struct stat lst;
639 if (!lexical_abs(raw, lex, sizeof lex)) return 0;
640 if (lstat(lex, &lst) != 0) return 0; /* nothing there to canonicalise */
641 r = realpath(lex, NULL);
642 if (!r) return 0;
643 str_copy(out, outsz, r);
644 free(r);
645 return 1;
646#endif
647}
648
649/* Absolute-path shape check. Rejects NUL smuggling attempts, `..` anywhere,
650 * and on POSIX anything not rooted at '/'. */
651static int path_shape_ok(const char *raw)
652{
653 size_t i;
654 if (!raw || !*raw) return 0;
655 if (strlen(raw) >= PATH_SZ) return 0;
656#if !defined(_WIN32)
657 if (raw[0] != '/') return 0;
658#else
659 if (!(isalpha((unsigned char)raw[0]) && raw[1] == ':' &&
660 (raw[2] == '\\' || raw[2] == '/'))) {
661 if (raw[0] != '/' && raw[0] != '\\') return 0; /* UNC-ish: allowed */
662 }
663#endif
664 for (i = 0; raw[i]; i++) {
665 if ((unsigned char)raw[i] < 0x20) return 0; /* control bytes */
666 }
667 /* `..` is never a legitimate segment: a caller that means the parent
668 * sends the parent's absolute path. Rejecting it outright also kills
669 * %2e%2e and every other encoded variant after url_decode(). */
670 for (i = 0; raw[i]; i++) {
671 if (raw[i] != '.') continue;
672 if (i > 0 && raw[i - 1] != '/' && raw[i - 1] != '\\') continue;
673 if (raw[i + 1] == '.' && (raw[i + 2] == '/' || raw[i + 2] == '\\' ||
674 raw[i + 2] == '\0')) return 0;
675 }
676 return 1;
677}
678
679static int denied_path(const char *p)
680{
681 int i;
682 for (i = 0; i < deny_count; i++)
683 if (path_under_p(p, g_deny[i])) return 1;
684#if !defined(_WIN32)
685 {
686 static const char *deny[] = { "/proc", "/sys", "/dev" };
687 size_t k;
688 for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
689 if (path_under_p(p, deny[k])) return 1;
690 }
691#else
692 {
693 /* Windows equivalents of "never go here": the registry hives and the
694 * system volume shadow copies live under C:\Windows and C:\System
695 * Volume Information, and a node's own plugin directory is where the
696 * binaries the bot executes sit. */
697 static const char *deny[] = {
698 "C:\\Windows\\System32\\config",
699 "C:\\System Volume Information"
700 };
701 size_t k;
702 for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
703 if (path_under_p(p, deny[k])) return 1;
704 }
705#endif
706 return 0;
707}
708
709static int root_contains(const char *canon)
710{
711 int i;
712 for (i = 0; i < g_root_count; i++) {
713 if (path_under_p(canon, g_roots[i].canonical)) return i;
714 if (g_roots[i].configured[0] &&
715 path_under_p(canon, g_roots[i].configured)) return i;
716 }
717 return -1;
718}
719
720static void parent_of(const char *canon, char *out, size_t outsz)
721{
722 size_t n;
723 str_copy(out, outsz, canon);
724 n = strlen(out);
725 while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0';
726#if defined(_WIN32)
727 while (n > 3 && out[n - 1] != '\\' && out[n - 1] != '/') out[--n] = '\0';
728 if (n > 3) out[--n] = '\0';
729 else str_copy(out, outsz, canon);
730#else
731 while (n > 1 && out[n - 1] != '/') out[--n] = '\0';
732 if (n > 1) out[--n] = '\0';
733 if (!out[0]) str_copy(out, outsz, "/");
734#endif
735}
736
737/* Authorise one path for one mode.
738 * mode 'r' - the entry must exist and be inside a root.
739 * mode 'w' - the ENTRY may not exist yet, so its PARENT is the thing that
740 * must exist and stay inside a root; a symlinked leaf that
741 * points out of the sandbox is refused by re-checking the
742 * canonical form of what is already on disk.
743 * On failure returns 0 with a one-line reason in err (never a stack trace:
744 * these strings are what the model reads to decide what to do next). */
745static int resolve_allowed(const char *raw, char *out, size_t outsz,
746 char mode, const char **err)
747{
748 char canon[PATH_SZ], parent[PATH_SZ];
749
750 if (!raw || !*raw) { *err = "path is empty"; return 0; }
751 if (!path_shape_ok(raw)) {
752 *err = "path must be absolute and must not contain '..'";
753 return 0;
754 }
755 if (!canon_path(raw, canon, sizeof canon)) {
756 if (mode == 'r') { *err = "path does not exist"; return 0; }
757 /* The entry does not exist yet (write_file, create_directory): the
758 * lexical form is what we can check, and the parent is what has to
759 * really exist and stay inside a root. */
760 if (!norm_lex(raw, canon, sizeof canon)) {
761 *err = "path could not be normalised";
762 return 0;
763 }
764 }
765 if (denied_path(canon)) { *err = "path is on the deny list"; return 0; }
766 if (root_contains(canon) < 0) {
767 *err = "path is outside the allowed directories";
768 return 0;
769 }
770 if (mode == 'w') {
771 parent_of(canon, parent, sizeof parent);
772 if (strcmp(parent, canon) != 0) {
773 char pc[PATH_SZ];
774 if (canon_path(parent, pc, sizeof pc)) {
775 if (denied_path(pc)) { *err = "parent directory is denied"; return 0; }
776 if (root_contains(pc) < 0) {
777 *err = "parent directory is outside the allowed directories";
778 return 0;
779 }
780 }
781 }
782 }
783 str_copy(out, outsz, canon);
784 return 1;
785}
786
787/* ------------------------------------------------------------------ */
788/* Config directory + roots.json */
789/* ------------------------------------------------------------------ */
790
791/* State lives OUTSIDE the plugin binary path (connector spec §C.1) so it
792 * survives reinstall and container restarts:
793 * $FS_CONNECTORS_DIR/<id>/ (tests)
794 * /workspace/.scorpiox/connectors/<id>/ (BotCloud containers)
795 * ~/.scorpiox/connectors/<id>/ (POSIX)
796 * %LOCALAPPDATA%\\scorpiox\\connectors\\<id>/ (Windows) */
797#if defined(_WIN32)
798static int is_dir_path(const char *p)
799{
800 DWORD att;
801 if (!p || !*p) return 0;
802 att = GetFileAttributesA(p);
803 return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_DIRECTORY);
804}
805#else
806static int is_dir_path(const char *p)
807{
808 struct stat st;
809 if (!p || !*p) return 0;
810 return (stat(p, &st) == 0) && S_ISDIR(st.st_mode);
811}
812#endif
813
814static void connectors_dir(char *out, size_t outsz)
815{
816 const char *env = getenv("FS_CONNECTORS_DIR");
817 const char *home;
818
819 if (env && *env) {
820 snprintf(out, outsz, "%s/%s", env, PLUGIN_ID);
821 return;
822 }
823#if defined(_WIN32)
824 home = getenv("LOCALAPPDATA");
825 if (!home || !*home) home = getenv("USERPROFILE");
826 if (home && *home) {
827 snprintf(out, outsz, "%s\\scorpiox\\connectors\\%s", home, PLUGIN_ID);
828 return;
829 }
830 snprintf(out, outsz, ".\\scorpiox-connectors\\%s", PLUGIN_ID);
831#else
832 if (is_dir_path("/workspace/.scorpiox")) {
833 snprintf(out, outsz, "/workspace/.scorpiox/connectors/%s", PLUGIN_ID);
834 return;
835 }
836 home = getenv("HOME");
837 if (home && *home) {
838 snprintf(out, outsz, "%s/.scorpiox/connectors/%s", home, PLUGIN_ID);
839 return;
840 }
841 snprintf(out, outsz, "./.scorpiox-connectors/%s", PLUGIN_ID);
842#endif
843}
844
845/* mkdir -p, portable, mode 0700 (this directory holds operator config). */
846static int mkpath(const char *path)
847{
848 char tmp[PATH_SZ];
849 char *p;
850 size_t n;
851
852 str_copy(tmp, sizeof tmp, path);
853 n = strlen(tmp);
854 while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
855 for (p = tmp + 1; *p; p++) {
856 if (*p != '/' && *p != '\\') continue;
857 *p = '\0';
858#if defined(_WIN32)
859 _mkdir(tmp);
860#else
861 mkdir(tmp, 0700);
862#endif
863 *p = SEP;
864 }
865#if defined(_WIN32)
866 if (_mkdir(tmp) == 0 || errno == EEXIST) return 0;
867 return -1;
868#else
869 if (mkdir(tmp, 0700) == 0 || errno == EEXIST) return 0;
870 return -1;
871#endif
872}
873
874static void add_root_raw(const char *configured)
875{
876 char canon[PATH_SZ];
877 struct stat st;
878 int i;
879
880 if (g_root_count >= MAX_ROOTS) return;
881 if (!configured || !*configured) return;
882
883 /* Trim surrounding whitespace and any leftover shell quotes: an operator
884 * who pastes "/data/reports " or '/data/reports' into roots.json means
885 * the directory, not a name with a trailing space. */
886 {
887 char clean[PATH_SZ];
888 size_t a = 0, b2 = strlen(configured);
889 while (a < b2 && isspace((unsigned char)configured[a])) a++;
890 while (b2 > a && isspace((unsigned char)configured[b2 - 1])) b2--;
891 if (b2 - a >= 2 && ((configured[a] == '"' && configured[b2 - 1] == '"') ||
892 (configured[a] == '\'' && configured[b2 - 1] == '\''))) {
893 a++; b2--;
894 }
895 if (b2 <= a) return;
896 if (b2 - a >= PATH_SZ) return;
897 memcpy(clean, configured + a, b2 - a);
898 clean[b2 - a] = '\0';
899 if (!path_shape_ok(clean)) return;
900 if (!canon_path(clean, canon, sizeof canon)) return;
901 if (denied_path(canon)) return;
902 }
903 for (i = 0; i < g_root_count; i++)
904 if (strcmp(g_roots[i].canonical, canon) == 0) return;
905
906 str_copy(g_roots[g_root_count].configured, PATH_SZ, configured);
907 str_copy(g_roots[g_root_count].canonical, PATH_SZ, canon);
908#if defined(_WIN32)
909 {
910 DWORD att = GetFileAttributesA(canon);
911 g_roots[g_root_count].exists = (att != INVALID_FILE_ATTRIBUTES);
912 g_roots[g_root_count].is_dir = (att != INVALID_FILE_ATTRIBUTES) &&
913 (att & FILE_ATTRIBUTE_DIRECTORY);
914 }
915#else
916 st.st_mode = 0;
917 g_roots[g_root_count].exists = (stat(canon, &st) == 0);
918 g_roots[g_root_count].is_dir = S_ISDIR(st.st_mode);
919#endif
920 g_root_count++;
921}
922
923static void add_deny(const char *p)
924{
925 char canon[PATH_SZ];
926 int i;
927 if (deny_count >= MAX_ROOTS) return;
928 if (!p || !*p) return;
929 if (!path_shape_ok(p)) return;
930 if (!canon_path(p, canon, sizeof canon)) str_copy(canon, sizeof canon, p);
931 for (i = 0; i < deny_count; i++)
932 if (strcmp(g_deny[i], canon) == 0) return;
933 str_copy(g_deny[deny_count++], PATH_SZ, canon);
934}
935
936/* roots.json: {"roots":["/data","/srv"],"denied":["/data/secret"],
937 * "permissions":{"write_file":false,...}}
938 * A missing or unreadable file is not an error - the defaults below apply. */
939static int load_roots_file(void)
940{
941 FILE *f;
942 long sz;
943 char *txt;
944 yyjson_doc *doc;
945 yyjson_val *root, *arr, *perm, *it;
946 size_t i, max;
947 int loaded = 0;
948
949 if (!g_roots_file[0]) {
950 char dir[PATH_SZ];
951 connectors_dir(dir, sizeof dir);
952 snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
953 if (g_roots_file[0]) {
954 size_t dl = strlen(g_roots_file);
955 if (dl + 12 < sizeof g_roots_file) {
956 g_roots_file[dl] = SEP;
957 g_roots_file[dl + 1] = '\0';
958 str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
959 }
960 }
961 }
962
963 f = fopen(g_roots_file, "rb");
964 if (!f) return 0;
965 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; }
966 sz = ftell(f);
967 if (sz < 0 || (size_t)sz > 256 * 1024) { fclose(f); return 0; }
968 rewind(f);
969 txt = (char *)malloc((size_t)sz + 1);
970 if (!txt) { fclose(f); return 0; }
971 if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) {
972 free(txt);
973 fclose(f);
974 return 0;
975 }
976 txt[sz] = '\0';
977 fclose(f);
978
979 doc = yyjson_read(txt, (size_t)sz, 0);
980 free(txt);
981 if (!doc) return 0;
982 root = yyjson_doc_get_root(doc);
983 if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; }
984
985 arr = yyjson_obj_get(root, "roots");
986 if (yyjson_is_arr(arr)) {
987 max = yyjson_arr_size(arr);
988 for (i = 0; i < max; i++) {
989 it = yyjson_arr_get(arr, i);
990 if (yyjson_is_str(it)) { add_root_raw(yyjson_get_str(it)); loaded = 1; }
991 }
992 }
993 arr = yyjson_obj_get(root, "denied");
994 if (yyjson_is_arr(arr)) {
995 max = yyjson_arr_size(arr);
996 for (i = 0; i < max; i++) {
997 it = yyjson_arr_get(arr, i);
998 if (yyjson_is_str(it)) add_deny(yyjson_get_str(it));
999 }
1000 }
1001 perm = yyjson_obj_get(root, "permissions");
1002 if (yyjson_is_obj(perm)) {
1003 for (i = 0; i < (size_t)TOOLS_N; i++) {
1004 yyjson_val *v = yyjson_obj_get(perm, TOOL_NAMES[i]);
1005 if (v && yyjson_is_bool(v) && !yyjson_get_bool(v)) g_tool_off[i] = 1;
1006 }
1007 loaded = 1;
1008 }
1009 yyjson_doc_free(doc);
1010 return loaded;
1011}
1012
1013static void init_roots(void)
1014{
1015 const char *extra;
1016 const char *home;
1017
1018 if (g_root_count) return;
1019
1020 /* 1. $FS_ALLOWED_ROOTS always wins - tests and one-shot operator overrides
1021 * must not need a file, and a connector that cannot be pointed at a
1022 * fixture tree cannot be tested at all. */
1023 extra = getenv("FS_ALLOWED_ROOTS");
1024 if (extra && *extra) {
1025 char copy[PATH_SZ];
1026 char *tok;
1027 char delim;
1028#if defined(_WIN32)
1029 delim = ';'; /* ':' is drive syntax on NT */
1030#else
1031 delim = ':';
1032#endif
1033 str_copy(copy, sizeof copy, extra);
1034 tok = copy;
1035 while (tok && *tok) {
1036 char *nx = strchr(tok, delim);
1037 if (nx) *nx++ = '\0';
1038 add_root_raw(tok);
1039 tok = nx;
1040 }
1041 if (g_root_count) return;
1042 }
1043
1044 /* 2. operator config */
1045 if (load_roots_file() && g_root_count) return;
1046
1047 /* 3. defaults: the two places a node actually keeps user files. */
1048#if defined(_WIN32)
1049 home = getenv("USERPROFILE");
1050 if (home && *home) add_root_raw(home);
1051 {
1052 const char *d = getenv("DRIVE");
1053 char buf[PATH_SZ];
1054 if (d && *d) { snprintf(buf, sizeof buf, "%s:\\codebases", d); add_root_raw(buf); }
1055 add_root_raw("D:\\codebases");
1056 }
1057#else
1058 if (is_dir_path("/workspace")) add_root_raw("/workspace");
1059 home = getenv("HOME");
1060 if (home && *home) add_root_raw(home);
1061 if (g_root_count == 0) add_root_raw("/tmp"); /* last resort, still scoped */
1062#endif
1063}
1064
1065/* ------------------------------------------------------------------ */
1066/* Filesystem primitives */
1067/* ------------------------------------------------------------------ */
1068
1069static int is_regular(const char *p)
1070{
1071#if defined(_WIN32)
1072 DWORD att = GetFileAttributesA(p);
1073 if (att == INVALID_FILE_ATTRIBUTES) return 0;
1074 return !(att & FILE_ATTRIBUTE_DIRECTORY);
1075#else
1076 struct stat st;
1077 if (lstat(p, &st) != 0) return 0;
1078 return S_ISREG(st.st_mode);
1079#endif
1080}
1081
1082static int is_link_path(const char *p)
1083{
1084#if defined(_WIN32)
1085 DWORD att = GetFileAttributesA(p);
1086 return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_REPARSE_POINT);
1087#else
1088 struct stat st;
1089 return (lstat(p, &st) == 0) && S_ISLNK(st.st_mode);
1090#endif
1091}
1092
1093static long long file_size(const char *p)
1094{
1095#if defined(_WIN32)
1096 WIN32_FILE_ATTRIBUTE_DATA d;
1097 LARGE_INTEGER li;
1098 if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return -1;
1099 li.HighPart = d.nFileSizeHigh;
1100 li.LowPart = d.nFileSizeLow;
1101 return (long long)li.QuadPart;
1102#else
1103 struct stat st;
1104 if (stat(p, &st) != 0) return -1;
1105 return (long long)st.st_size;
1106#endif
1107}
1108
1109static long long file_mtime(const char *p)
1110{
1111#if defined(_WIN32)
1112 WIN32_FILE_ATTRIBUTE_DATA d;
1113 FILETIME ft;
1114 ULARGE_INTEGER u;
1115 if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
1116 ft = d.ftLastWriteTime;
1117 u.LowPart = ft.dwLowDateTime;
1118 u.HighPart = ft.dwHighDateTime;
1119 return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1120#else
1121 struct stat st;
1122 if (stat(p, &st) != 0) return 0;
1123 return (long long)st.st_mtime;
1124#endif
1125}
1126
1127static unsigned file_mode(const char *p)
1128{
1129#if defined(_WIN32)
1130 DWORD att = GetFileAttributesA(p);
1131 unsigned m = 0;
1132 if (att == INVALID_FILE_ATTRIBUTES) return 0;
1133 m |= 0700;
1134 if (!(att & FILE_ATTRIBUTE_READONLY)) m |= 0222;
1135 if (att & FILE_ATTRIBUTE_DIRECTORY) m |= 0111;
1136 return m;
1137#else
1138 struct stat st;
1139 if (stat(p, &st) != 0) return 0;
1140 return (unsigned)(st.st_mode & 07777);
1141#endif
1142}
1143
1144/* Read the whole file (capped) into b. Sets *binary when a NUL shows up in
1145 * the first BIN_PROBE bytes - the same probe the read-only browser uses, so
1146 * both plugins agree on what "binary" means on this node. */
1147static int read_whole(const char *path, buf_t *b, size_t cap, int *binary,
1148 const char **err)
1149{
1150 FILE *f;
1151 long long sz;
1152 char chunk[IO_CHUNK];
1153 size_t total = 0;
1154 int probed = 0;
1155
1156 if (binary) *binary = 0;
1157 sz = file_size(path);
1158 if (sz < 0) { *err = "cannot stat file"; return 0; }
1159 if ((size_t)sz > cap) { *err = "file is larger than the read limit"; return 0; }
1160
1161 f = fopen(path, "rb");
1162 if (!f) {
1163 *err = (errno == EACCES) ? "permission denied" : "cannot open file";
1164 return 0;
1165 }
1166 for (;;) {
1167 size_t n = fread(chunk, 1, sizeof chunk, f);
1168 if (n == 0) break;
1169 if (!binary) {
1170 /* fall through */
1171 } else if (!probed) {
1172 size_t i, stop = n < BIN_PROBE ? n : BIN_PROBE;
1173 for (i = 0; i < stop; i++)
1174 if (chunk[i] == '\0') { *binary = 1; break; }
1175 if (total + n >= BIN_PROBE) probed = 1;
1176 }
1177 buf_add(b, chunk, n);
1178 total += n;
1179 if (total > cap) {
1180 fclose(f);
1181 *err = "file is larger than the read limit";
1182 return 0;
1183 }
1184 }
1185 fclose(f);
1186 if (binary && !probed) {
1187 /* small file: probe what we have */
1188 size_t i, stop = b->n < BIN_PROBE ? b->n : BIN_PROBE;
1189 for (i = 0; i < stop; i++)
1190 if (b->p && b->p[i] == '\0') { *binary = 1; break; }
1191 }
1192 *err = NULL;
1193 return 1;
1194}
1195
1196/* First n lines, joined with a single \n and with no trailing newline -
1197 * the same shape upstream headFile returns, so a caller that counts
1198 * newlines counts lines and not an extra blank one. */
1199static void text_head(const char *s, size_t len, long n, buf_t *out)
1200{
1201 size_t i = 0;
1202 long lines = 0;
1203 if (n < 0) { buf_add(out, s, len); return; }
1204 if (n == 0) return;
1205 while (i < len && lines < n) {
1206 size_t start = i, e = i;
1207 while (e < len && s[e] != '\n') e++;
1208 if (lines) buf_putc(out, '\n');
1209 if (e > start && s[e - 1] == '\r') e--; /* CRLF normalised */
1210 buf_add(out, s + start, e - start);
1211 lines++;
1212 i = (e < len) ? e + 1 : len;
1213 }
1214}
1215
1216/* Last n lines. A trailing newline ends the last line rather than starting an
1217 * empty one, so "a\nb\n" with tail=1 is "b\n" - the same reading the upstream
1218 * tailFile takes, and the one that stops an off-by-one from appearing as
1219 * "tail 1 gave me a blank line". */
1220static void text_tail(const char *s, size_t len, long n, buf_t *out)
1221{
1222 size_t end = len;
1223 long lines = 0;
1224 size_t i;
1225
1226 if (n < 0) { buf_add(out, s, len); return; }
1227 if (n == 0 || len == 0) return;
1228 while (end > 0 && (s[end - 1] == '\n' || s[end - 1] == '\r')) end--;
1229 if (end == 0) return;
1230 for (i = end; i > 0; ) {
1231 i--;
1232 if (s[i] == '\n') {
1233 lines++;
1234 if (lines >= n) { i++; break; }
1235 }
1236 }
1237 buf_add(out, s + i, end - i);
1238}
1239
1240/* Write content atomically: write to <path>.tmp-<pid>, flush to disk, then
1241 * rename over the target. A crash mid-write therefore leaves either the old
1242 * file or the new one, never a half-written file - which matters because the
1243 * whole point of this connector is that an agent edits files unattended. */
1244static int write_atomic(const char *path, const char *content, size_t len,
1245 const char **err)
1246{
1247 char tmp[PATH_SZ];
1248 FILE *f;
1249 int rc = 0;
1250
1251 snprintf(tmp, sizeof tmp, "%s.tmp-%ld", path, (long)
1252#if defined(_WIN32)
1253 GetCurrentProcessId()
1254#else
1255 (long)getpid()
1256#endif
1257 );
1258 f = fopen(tmp, "wb");
1259 if (!f) { *err = "cannot create temporary file"; return 0; }
1260 if (len && fwrite(content, 1, len, f) != len) {
1261 fclose(f);
1262#if !defined(_WIN32)
1263 remove(tmp);
1264#else
1265 DeleteFileA(tmp);
1266#endif
1267 *err = "write failed (disk full?)";
1268 return 0;
1269 }
1270 if (fflush(f) != 0) { fclose(f); rc = 0; *err = "flush failed"; }
1271 else {
1272#if !defined(_WIN32)
1273 fflush(f);
1274 fsync(fileno(f));
1275#endif
1276 fclose(f);
1277 rc = 1;
1278 }
1279 if (!rc) return 0;
1280
1281#if defined(_WIN32)
1282 /* Windows rename() refuses to replace an existing file. */
1283 {
1284 char bak[PATH_SZ];
1285 snprintf(bak, sizeof bak, "%s.bak-%ld", path, (long)GetCurrentProcessId());
1286 MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
1287 if (GetFileAttributesA(tmp) != INVALID_FILE_ATTRIBUTES) {
1288 /* fallback: copy over then delete the temp */
1289 CopyFileA(tmp, path, FALSE);
1290 DeleteFileA(tmp);
1291 (void)bak;
1292 }
1293 if (GetFileAttributesA(path) == INVALID_FILE_ATTRIBUTES) {
1294 *err = "rename failed";
1295 return 0;
1296 }
1297 }
1298#else
1299 if (rename(tmp, path) != 0) {
1300 remove(tmp);
1301 *err = "rename failed";
1302 return 0;
1303 }
1304#endif
1305 *err = NULL;
1306 return 1;
1307}
1308
1309static int ensure_parent(const char *path)
1310{
1311 char parent[PATH_SZ];
1312 parent_of(path, parent, sizeof parent);
1313 if (strcmp(parent, path) == 0) return 0;
1314 return mkpath(parent);
1315}
1316
1317static int mkdir_p(const char *path)
1318{
1319 return mkpath(path);
1320}
1321
1322static int copy_file(const char *src, const char *dst, const char **err)
1323{
1324 FILE *in, *out;
1325 char chunk[IO_CHUNK];
1326 size_t n;
1327
1328 in = fopen(src, "rb");
1329 if (!in) { *err = "cannot open source"; return 0; }
1330 if (ensure_parent(dst) != 0) { fclose(in); *err = "cannot create destination directory"; return 0; }
1331 out = fopen(dst, "wb");
1332 if (!out) { fclose(in); *err = "cannot create destination"; return 0; }
1333 while ((n = fread(chunk, 1, sizeof chunk, in)) > 0) {
1334 if (fwrite(chunk, 1, n, out) != n) {
1335 fclose(in);
1336 fclose(out);
1337 *err = "copy failed (disk full?)";
1338 return 0;
1339 }
1340 }
1341 if (ferror(in)) { fclose(in); fclose(out); *err = "read error"; return 0; }
1342 fclose(in);
1343 if (fflush(out) != 0) { fclose(out); *err = "flush failed"; return 0; }
1344 fclose(out);
1345 *err = NULL;
1346 return 1;
1347}
1348
1349/* ------------------------------------------------------------------ */
1350/* Glob matching */
1351/* */
1352/* search_files and excludePatterns need minimatch's useful subset with */
1353/* no dependency: '*' and '?' within one path segment, '**' across */
1354/* segments, and brace-free patterns. A pattern with no separator is */
1355/* matched against the file NAME as well as the relative path, which is */
1356/* what makes "*.log" behave like a person expects. */
1357/* ------------------------------------------------------------------ */
1358
1359static int glob_here(const char *pat, const char *s, int slash_means_end)
1360{
1361 while (*pat) {
1362 if (pat[0] == '*' && pat[1] == '*') {
1363 const char *p2 = pat + 2;
1364 if (*p2 == '/') p2++;
1365 if (!*p2) return 1; /* ** matches rest */
1366 for (;;) {
1367 if (glob_here(p2, s, 0)) return 1;
1368 while (*s && *s != '/') s++;
1369 if (*s == '/') s++;
1370 else break;
1371 }
1372 return 0;
1373 }
1374 if (*pat == '*') {
1375 const char *p2 = pat + 1;
1376 if (slash_means_end) {
1377 for (;;) {
1378 if (glob_here(p2, s, slash_means_end)) return 1;
1379 if (*s == '/' || *s == '\\') return 0;
1380 if (!*s) return 0;
1381 s++;
1382 }
1383 }
1384 for (;;) {
1385 if (glob_here(p2, s, slash_means_end)) return 1;
1386 if (!*s) return 0;
1387 s++;
1388 }
1389 }
1390 if (*pat == '?') {
1391 if (!*s || *s == '/') return 0;
1392 pat++;
1393 s++;
1394 continue;
1395 }
1396 if (*pat != *s) return 0;
1397 pat++;
1398 s++;
1399 }
1400 return *s == '\0';
1401}
1402
1403static int glob_match(const char *pat, const char *s)
1404{
1405 if (!pat || !s) return 0;
1406 return glob_here(pat, s, 1);
1407}
1408
1409/* Excludes follow upstream isExcludedPath: a pattern with a star is matched
1410 * on the relative path (and a trailing double-star-slash also matches the
1411 * directory itself); a plain name matches at any depth. */
1412static int is_excluded(const char *relpath, int is_dir, yyjson_val *excludes)
1413{
1414 size_t i, max;
1415 if (!excludes || !yyjson_is_arr(excludes)) return 0;
1416 max = yyjson_arr_size(excludes);
1417 for (i = 0; i < max; i++) {
1418 yyjson_val *v = yyjson_arr_get(excludes, i);
1419 const char *pat;
1420 char buf[NAME_SZ * 4];
1421 if (!yyjson_is_str(v)) continue;
1422 pat = yyjson_get_str(v);
1423 if (!pat || !*pat) continue;
1424 if (strchr(pat, '*')) {
1425 if (glob_match(pat, relpath)) return 1;
1426 {
1427 size_t pl = strlen(pat);
1428 if (pl > 3 && !strcmp(pat + pl - 3, "/**")) {
1429 char cut[NAME_SZ * 4];
1430 str_copy(cut, sizeof cut, pat);
1431 cut[pl - 3] = '\0';
1432 if (is_dir && glob_match(cut, relpath)) return 1;
1433 }
1434 }
1435 continue;
1436 }
1437 if (glob_match(pat, relpath)) return 1;
1438 snprintf(buf, sizeof buf, "**/%s", pat);
1439 if (glob_match(buf, relpath)) return 1;
1440 if (is_dir) {
1441 snprintf(buf, sizeof buf, "**/%s/**", pat);
1442 if (glob_match(buf, relpath)) return 1;
1443 }
1444 }
1445 return 0;
1446}
1447
1448/* ------------------------------------------------------------------ */
1449/* Unified diff (enough of it to read like git's) */
1450/* ------------------------------------------------------------------ */
1451
1452typedef struct {
1453 char **line;
1454 size_t n;
1455} lines_t;
1456
1457static void lines_split(const char *s, size_t len, lines_t *out)
1458{
1459 size_t cap = 64, n = 0, start = 0, i;
1460 char **v = (char **)malloc(cap * sizeof *v);
1461 out->line = NULL;
1462 out->n = 0;
1463 if (!v) return;
1464 for (i = 0; i <= len; i++) {
1465 if (i == len || s[i] == '\n') {
1466 size_t sl = i - start;
1467 char *ln;
1468 if (sl && s[start + sl - 1] == '\r') sl--; /* compare LF-only */
1469 ln = (char *)malloc(sl + 1);
1470 if (!ln) break;
1471 memcpy(ln, s + start, sl);
1472 ln[sl] = '\0';
1473 if (n == cap) {
1474 char **nv;
1475 cap *= 2;
1476 nv = (char **)realloc(v, cap * sizeof *v);
1477 if (!nv) { free(ln); break; }
1478 v = nv;
1479 }
1480 v[n++] = ln;
1481 start = i + 1;
1482 if (i == len) break;
1483 }
1484 }
1485 out->line = v;
1486 out->n = n;
1487}
1488
1489static void lines_free(lines_t *l)
1490{
1491 size_t i;
1492 for (i = 0; i < l->n; i++) free(l->line[i]);
1493 free(l->line);
1494 l->line = NULL;
1495 l->n = 0;
1496}
1497
1498/* Append one @@ hunk with its context. */
1499static void diff_hunk(buf_t *out, lines_t *a, lines_t *b,
1500 size_t a0, size_t a1, size_t b0, size_t b1)
1501{
1502 size_t i;
1503 if (a1 > a0 || b1 > b0) {
1504 buf_printf(out, "@@ -%u,%u +%u,%u @@\n",
1505 (unsigned)(a0 + 1), (unsigned)(a1 - a0),
1506 (unsigned)(b0 + 1), (unsigned)(b1 - b0));
1507 for (i = a0; i < a1; i++) { buf_putc(out, '-'); buf_puts(out, a->line[i]); buf_putc(out, '\n'); }
1508 for (i = b0; i < b1; i++) { buf_putc(out, '+'); buf_puts(out, b->line[i]); buf_putc(out, '\n'); }
1509 }
1510}
1511
1512/* A deliberately simple LCS-free diff: match the common prefix and suffix,
1513 * then report the middle as one remove/add pair. Real git diffs of agent
1514 * edits are almost always local, and a wrong-but-labelled diff is worse than
1515 * a coarse honest one, so nothing here pretends to be Myers. */
1516static void make_diff(buf_t *out, const char *an, size_t alen,
1517 const char *bn, size_t blen, const char *name)
1518{
1519 lines_t a, b;
1520 size_t pre = 0, suf = 0;
1521
1522 lines_split(an, alen, &a);
1523 lines_split(bn, blen, &b);
1524 while (pre < a.n && pre < b.n && !strcmp(a.line[pre], b.line[pre])) pre++;
1525 while (suf + pre < a.n && suf + pre < b.n &&
1526 !strcmp(a.line[a.n - 1 - suf], b.line[b.n - 1 - suf])) suf++;
1527
1528 buf_printf(out, "--- %s\n+++ %s\n", name, name);
1529 if (a.n == b.n && pre == a.n) {
1530 buf_puts(out, "(no changes)\n");
1531 } else {
1532 diff_hunk(out, &a, &b, pre, a.n - suf, pre, b.n - suf);
1533 }
1534 lines_free(&a);
1535 lines_free(&b);
1536}
1537
1538/* ------------------------------------------------------------------ */
1539/* Directory helpers */
1540/* ------------------------------------------------------------------ */
1541
1542typedef struct {
1543 char name[NAME_SZ];
1544 int is_dir;
1545 int is_link;
1546 long long size;
1547 long long mtime;
1548} dent_t;
1549
1550static int cmp_dent(const void *x, const void *y)
1551{
1552 const dent_t *a = (const dent_t *)x, *b = (const dent_t *)y;
1553 if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; /* dirs first */
1554 return strcmp(a->name, b->name);
1555}
1556
1557/* Read one directory, sorted, capped. Returns count or -1. */
1558static long list_dir(const char *path, dent_t **out, const char **err)
1559{
1560 dent_t *v = NULL;
1561 long n = 0, cap = 0;
1562#if !defined(_WIN32)
1563 DIR *d;
1564 struct dirent *de;
1565 d = opendir(path);
1566 if (!d) {
1567 *err = (errno == EACCES) ? "permission denied" :
1568 (errno == ENOENT) ? "path does not exist" : "cannot read directory";
1569 return -1;
1570 }
1571 while ((de = readdir(d)) != NULL) {
1572 char full[PATH_SZ];
1573 dent_t e;
1574 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
1575 if (n == cap) {
1576 dent_t *nv;
1577 cap = cap ? cap * 2 : 128;
1578 if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1579 nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1580 if (!nv) break;
1581 v = nv;
1582 }
1583 if (n >= MAX_ENTRIES) break;
1584 memset(&e, 0, sizeof e);
1585 str_copy(e.name, sizeof e.name, de->d_name);
1586 path_join(full, sizeof full, path, de->d_name);
1587 e.is_link = is_link_path(full);
1588 e.is_dir = is_dir_path(full);
1589 e.size = e.is_dir ? 0 : file_size(full);
1590 e.mtime = file_mtime(full);
1591 v[n++] = e;
1592 }
1593 closedir(d);
1594#else
1595 WIN32_FIND_DATAA fd;
1596 HANDLE h;
1597 char pat[PATH_SZ];
1598 snprintf(pat, sizeof pat, "%s\\*", path);
1599 h = FindFirstFileA(pat, &fd);
1600 if (h == INVALID_HANDLE_VALUE) {
1601 *err = "cannot read directory";
1602 return -1;
1603 }
1604 do {
1605 char full[PATH_SZ];
1606 dent_t e;
1607 if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
1608 if (n == cap) {
1609 dent_t *nv;
1610 cap = cap ? cap * 2 : 128;
1611 if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1612 nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1613 if (!nv) break;
1614 v = nv;
1615 }
1616 if (n >= MAX_ENTRIES) break;
1617 memset(&e, 0, sizeof e);
1618 str_copy(e.name, sizeof e.name, fd.cFileName);
1619 path_join(full, sizeof full, path, fd.cFileName);
1620 e.is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
1621 e.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
1622 {
1623 ULARGE_INTEGER u;
1624 u.LowPart = fd.nFileSizeLow;
1625 u.HighPart = fd.nFileSizeHigh;
1626 e.size = e.is_dir ? 0 : (long long)u.QuadPart;
1627 }
1628 {
1629 ULARGE_INTEGER u;
1630 u.LowPart = fd.ftLastWriteTime.dwLowDateTime;
1631 u.HighPart = fd.ftLastWriteTime.dwHighDateTime;
1632 e.mtime = (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1633 }
1634 v[n++] = e;
1635 } while (FindNextFileA(h, &fd));
1636 FindClose(h);
1637#endif
1638 if (n > 1) qsort(v, (size_t)n, sizeof *v, cmp_dent);
1639 *out = v;
1640 *err = NULL;
1641 return n;
1642}
1643
1644/* ------------------------------------------------------------------ */
1645/* MCP tools */
1646/* */
1647/* Each handler appends either the result text or a one-line reason to */
1648/* *text and returns 0 (result) or 1 (isError). The dispatcher wraps */
1649/* the text into {"content":[{"type":"text","text":...}],"isError":b}, */
1650/* which is exactly what scorpiox-connector-mcp relays upstream. */
1651/* */
1652/* Error text is written for the MODEL, not for a log: it names the */
1653/* path, says which rule refused it, and (where there is one) what to */
1654/* do instead. "permission denied" alone sends an agent in circles. */
1655/* ------------------------------------------------------------------ */
1656
1657typedef int (*tool_fn)(yyjson_val *args, buf_t *text);
1658
1659/* Refuse the "binary" case in a way that tells the caller what to use. */
1660#define BINARY_HINT "file contains binary bytes; read_text_file returns text only - use get_file_info for metadata, or the files plugin to view it"
1661
1662static int tool_read_text_file(yyjson_val *args, buf_t *text)
1663{
1664 char raw[PATH_SZ], canon[PATH_SZ];
1665 const char *err = NULL;
1666 buf_t b;
1667 int have_head = 0, have_tail = 0;
1668 long head = -1, tail = -1;
1669 int binary = 0;
1670
1671 if (!ju_field_str(args, "path", raw, sizeof raw))
1672 return (buf_puts(text, "missing required parameter \"path\""), 1);
1673 if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
1674 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1675 if (!is_regular(canon))
1676 return (buf_printf(text, "%s: not a regular file", raw), 1);
1677
1678 head = ju_int(args, "head", -1, &have_head);
1679 tail = ju_int(args, "tail", -1, &have_tail);
1680 if (head < -1 || tail < -1)
1681 return (buf_puts(text, "head and tail must be non-negative integers"), 1);
1682
1683 buf_init(&b);
1684 if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1685 buf_printf(text, "%s: %s", raw, err ? err : "read failed");
1686 buf_free(&b);
1687 return 1;
1688 }
1689 if (binary) {
1690 buf_printf(text, "%s: " BINARY_HINT, raw);
1691 buf_free(&b);
1692 return 1;
1693 }
1694 if (have_head && have_tail) {
1695 buf_puts(text, "head and tail are mutually exclusive - send one or the other");
1696 buf_free(&b);
1697 return 1;
1698 }
1699 if (have_head) text_head(b.p ? b.p : "", b.n, head, text);
1700 else if (have_tail) text_tail(b.p ? b.p : "", b.n, tail, text);
1701 else buf_add(text, b.p ? b.p : "", b.n);
1702 buf_free(&b);
1703 return 0;
1704}
1705
1706/* One element of read_multiple_files. Kept as a function so the loop that
1707 * drives it stays readable. */
1708static void read_one_path(const char *path, buf_t *out, int *first)
1709{
1710 char canon[PATH_SZ];
1711 const char *err = NULL;
1712 buf_t b;
1713 int binary = 0;
1714
1715 /* each item below terminates with its own newline, so the separator is
1716 * "---
1717" and not "
1718---
1719" - that is what makes the output byte-split
1720 * on a line of three dashes, exactly like upstream */
1721 if (!*first) buf_puts(out, "---\n");
1722 *first = 0;
1723
1724 if (!resolve_allowed(path, canon, sizeof canon, 'r', &err)) {
1725 buf_printf(out, "%s: Error - %s\n", path, err ? err : "refused");
1726 return;
1727 }
1728 if (!is_regular(canon)) {
1729 buf_printf(out, "%s: Error - not a regular file\n", path);
1730 return;
1731 }
1732 buf_init(&b);
1733 if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1734 buf_printf(out, "%s: Error - %s\n", path, err ? err : "read failed");
1735 buf_free(&b);
1736 return;
1737 }
1738 if (binary) {
1739 buf_printf(out, "%s: Error - binary file\n", path);
1740 buf_free(&b);
1741 return;
1742 }
1743 buf_printf(out, "%s:\n", path);
1744 buf_add(out, b.p ? b.p : "", b.n);
1745 buf_putc(out, '\n');
1746 buf_free(&b);
1747}
1748
1749static int tool_read_multiple_files(yyjson_val *args, buf_t *text)
1750{
1751 yyjson_val *arr = args ? yyjson_obj_get(args, "paths") : NULL;
1752 size_t i, max;
1753 int first = 1;
1754
1755 if (!arr || !yyjson_is_arr(arr) || yyjson_arr_size(arr) == 0)
1756 return (buf_puts(text, "missing required parameter \"paths\" (a non-empty array of strings)"), 1);
1757 max = yyjson_arr_size(arr);
1758 if (max > 200) max = 200; /* one call must not swallow a node */
1759 for (i = 0; i < max; i++) {
1760 yyjson_val *v = yyjson_arr_get(arr, i);
1761 const char *pv = ju_cstr(v); /* NUL-safe: never a truncated path */
1762 if (pv && pv[0]) read_one_path(pv, text, &first);
1763 }
1764 return 0;
1765}
1766
1767static int tool_write_file(yyjson_val *args, buf_t *text)
1768{
1769 char raw[PATH_SZ], canon[PATH_SZ];
1770 const char *err = NULL;
1771 const char *content;
1772 size_t clen;
1773
1774 if (!ju_field_str(args, "path", raw, sizeof raw))
1775 return (buf_puts(text, "missing required parameter \"path\""), 1);
1776 if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
1777 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1778 if (is_dir_path(canon))
1779 return (buf_printf(text, "%s: that is a directory", raw), 1);
1780 if (is_link_path(canon))
1781 return (buf_printf(text, "%s: refusing to write through a symlink", raw), 1);
1782
1783 {
1784 yyjson_val *cv = args ? yyjson_obj_get(args, "content") : NULL;
1785 if (!cv) return (buf_puts(text, "missing required parameter \"content\""), 1);
1786 if (!yyjson_is_str(cv))
1787 return (buf_puts(text, "\"content\" must be a string"), 1);
1788 content = yyjson_get_str(cv);
1789 clen = yyjson_get_len(cv);
1790 }
1791 if (clen > WRITE_CAP)
1792 return (buf_printf(text, "content is %llu bytes (limit %llu)",
1793 (unsigned long long)clen, (unsigned long long)WRITE_CAP), 1);
1794
1795 if (ensure_parent(canon) != 0)
1796 return (buf_printf(text, "%s: cannot create the parent directory", raw), 1);
1797 if (!write_atomic(canon, content, clen, &err))
1798 return (buf_printf(text, "%s: %s", raw, err ? err : "write failed"), 1);
1799
1800 buf_printf(text, "Successfully wrote %llu bytes to %s",
1801 (unsigned long long)clen, raw);
1802 return 0;
1803}
1804
1805/* ------------------------------------------------------------------ */
1806/* edit_file */
1807/* */
1808/* Upstream semantics, kept: edits apply in order, each to the result */
1809/* of the ones before it; each replaces the FIRST match of oldText; */
1810/* an exact match wins, and when there is none a run of whole lines */
1811/* matches if each line is equal once leading and trailing whitespace */
1812/* is ignored (newText then takes the file's indentation is NOT */
1813/* re-derived - we keep the caller's text and say so in the diff); if */
1814/* ANY edit has no match NOTHING is written and the error shows where */
1815/* the file diverges; dryRun computes and returns the diff without */
1816/* touching the disk. The file's own line ending is detected and */
1817/* restored. */
1818/* ------------------------------------------------------------------ */
1819
1820/* Find `needle` in `hay` (exact). Returns offset or (size_t)-1. */
1821static size_t find_sub(const char *hay, size_t hlen, const char *needle, size_t nlen)
1822{
1823 size_t i;
1824 if (nlen == 0 || nlen > hlen) return (size_t)-1;
1825 for (i = 0; i + nlen <= hlen; i++)
1826 if (!memcmp(hay + i, needle, nlen)) return i;
1827 return (size_t)-1;
1828}
1829
1830/* Whitespace-insensitive whole-line match. Returns start offset of the
1831 * matching region and sets *endlen, or (size_t)-1. The match must start at
1832 * a line boundary and the compared run must be followed by a newline when
1833 * oldText ends with one. */
1834static size_t find_lines(const char *hay, size_t hlen, const char *needle,
1835 size_t nlen, size_t *matchlen)
1836{
1837 /* Split needle into lines (LF-only, trailing \n dropped). */
1838 char *ndup;
1839 char *nl[64];
1840 size_t nlines = 0, i, start = 0;
1841 char *hl[4096];
1842 size_t hlines = 0, pos[4097];
1843 size_t cand;
1844
1845 *matchlen = 0;
1846 if (nlen == 0) return (size_t)-1;
1847 ndup = (char *)malloc(nlen + 1);
1848 if (!ndup) return (size_t)-1;
1849 memcpy(ndup, needle, nlen);
1850 ndup[nlen] = '\0';
1851 if (nlen && ndup[nlen - 1] == '\n') ndup[nlen - 1] = '\0';
1852 for (i = 0; ndup[i]; i++) {
1853 if (ndup[i] == '\r') ndup[i] = '\0';
1854 if (ndup[i] == '\n') {
1855 ndup[i] = '\0';
1856 if (nlines < 64) nl[nlines++] = ndup + start;
1857 start = i + 1;
1858 }
1859 }
1860 if (nlines < 64) nl[nlines++] = ndup + start;
1861 /* oldText ended with a newline: that trailing "" is not a line to match,
1862 * and the boundary is enforced separately below. */
1863 if (nlen && needle[nlen - 1] == '\n' && nlines > 1 &&
1864 nl[nlines - 1][0] == '\0') nlines--;
1865 if (nlines == 0 || nlines > 64) { free(ndup); return (size_t)-1; }
1866
1867 /* Split haystack into lines, remembering offsets. */
1868 start = 0;
1869 for (i = 0; i <= hlen; i++) {
1870 if (i == hlen || hay[i] == '\n') {
1871 if (hlines < 4096) {
1872 size_t lstart = start, lend = i;
1873 /* strip a trailing \r for comparison, keep the byte in place */
1874 pos[hlines] = lstart;
1875 {
1876 size_t sl = lstart, el = lend;
1877 char *dup;
1878 if (el > sl && hay[el - 1] == '\r') el--;
1879 dup = (char *)malloc(el - sl + 1);
1880 if (!dup) {
1881 size_t k;
1882 for (k = 0; k < hlines; k++) free(hl[k]);
1883 free(ndup);
1884 return (size_t)-1;
1885 }
1886 memcpy(dup, hay + sl, el - sl);
1887 dup[el - sl] = '\0';
1888 hl[hlines] = dup;
1889 }
1890 hlines++;
1891 }
1892 start = i + 1;
1893 if (i == hlen) break;
1894 }
1895 }
1896 if (hlines + 1 > 4096) { hlines = 4096; }
1897
1898 for (cand = 0; cand + nlines <= hlines && cand + nlines <= 4096; cand++) {
1899 size_t j, ok = 1;
1900 for (j = 0; j < nlines; j++) {
1901 const char *a = nl[j], *b = hl[cand + j];
1902 while (*a == ' ' || *a == '\t') a++;
1903 while (*b == ' ' || *b == '\t') b++;
1904 {
1905 size_t la = strlen(a), lb = strlen(b);
1906 while (la && (a[la - 1] == ' ' || a[la - 1] == '\t')) la--;
1907 while (lb && (b[lb - 1] == ' ' || b[lb - 1] == '\t')) lb--;
1908 if (la != lb || memcmp(a, b, la)) { ok = 0; break; }
1909 }
1910 }
1911 if (ok) {
1912 size_t s = pos[cand];
1913 size_t e = pos[cand + nlines - 1];
1914 /* The run must land on line boundaries. The last matched line
1915 * ends at its newline (or at EOF); when oldText itself asked for
1916 * the newline it is part of the match, when it did not the
1917 * file's own newline is left alone - which is what keeps an edit
1918 * from silently deleting the file's trailing newline. */
1919 while (e < hlen && hay[e] != '\n') e++;
1920 if (needle[nlen - 1] == '\n') {
1921 if (e == hlen) { /* no newline to consume */
1922 size_t k;
1923 for (k = 0; k < hlines; k++) free(hl[k]);
1924 free(ndup);
1925 return (size_t)-1;
1926 }
1927 e++;
1928 }
1929 *matchlen = e - s;
1930 {
1931 size_t k;
1932 for (k = 0; k < hlines; k++) free(hl[k]);
1933 }
1934 free(ndup);
1935 return s;
1936 }
1937 }
1938 {
1939 size_t k;
1940 for (k = 0; k < hlines; k++) free(hl[k]);
1941 }
1942 free(ndup);
1943 return (size_t)-1;
1944}
1945
1946/* Report the first diverging non-blank line of `cur` vs `old`, numbered. */
1947static void describe_mismatch(buf_t *text, const char *cur, size_t curlen,
1948 const char *old, size_t oldlen, size_t index)
1949{
1950 char probe[NAME_SZ];
1951 size_t i, o = 0, shown = 0;
1952 size_t plen = 0;
1953
1954 /* first non-empty line of oldText, trimmed */
1955 while (o < oldlen && (old[o] == '\n' || old[o] == '\r' ||
1956 old[o] == ' ' || old[o] == '\t')) o++;
1957 while (o + plen < oldlen && plen < sizeof probe - 1 &&
1958 old[o + plen] != '\n' && old[o + plen] != '\r') {
1959 probe[plen] = old[o + plen];
1960 plen++;
1961 }
1962 probe[plen] = '\0';
1963 /* trim trailing spaces */
1964 while (plen && (probe[plen - 1] == ' ' || probe[plen - 1] == '\t')) probe[--plen] = '\0';
1965
1966 buf_printf(text, "edit #%u did not match. ", (unsigned)(index + 1));
1967 if (plen) {
1968 long long best = -1;
1969 double bestscore = -1;
1970 /* Find the line of the file most similar to probe's first token. */
1971 size_t ls = 0, ln = 1;
1972 for (i = 0; i <= curlen; i++) {
1973 if (i == curlen || cur[i] == '\n') {
1974 size_t s = ls, e = i, m, hits = 0;
1975 while (s < e && (cur[s] == ' ' || cur[s] == '\t')) s++;
1976 while (e > s && (cur[e - 1] == ' ' || cur[e - 1] == '\t' ||
1977 cur[e - 1] == '\r')) e--;
1978 if (e > s && plen) {
1979 for (m = s; m < e; m++) {
1980 size_t k;
1981 for (k = 0; k < plen; k++)
1982 if (cur[m] == probe[k]) { hits++; break; }
1983 }
1984 {
1985 double sc = (double)hits / (double)(e - s);
1986 if (sc > bestscore) { bestscore = sc; best = (long long)ln; }
1987 }
1988 }
1989 ls = i + 1;
1990 ln++;
1991 }
1992 }
1993 if (best > 0) {
1994 buf_printf(text, "The closest line is %lld. ", best);
1995 /* print up to 3 numbered lines around it */
1996 {
1997 size_t ls2 = 0, ln2 = 1;
1998 for (i = 0; i <= curlen; i++) {
1999 if (i == curlen || cur[i] == '\n') {
2000 int phantom = (i == curlen && ls2 == curlen);
2001 if (!phantom && ln2 >= (size_t)best - 1 && shown < 3) {
2002 size_t s = ls2, e = (i < curlen) ? i : curlen;
2003 buf_printf(text, "%lld| ", (long long)ln2);
2004 for (; s < e && s < ls2 + 200; s++)
2005 if (cur[s] != '\r') buf_putc(text, cur[s]);
2006 buf_putc(text, '\n');
2007 shown++;
2008 }
2009 ls2 = i + 1;
2010 ln2++;
2011 }
2012 }
2013 }
2014 } else {
2015 buf_puts(text, "Nothing in the file resembles oldText. ");
2016 }
2017 } else {
2018 buf_puts(text, "oldText was blank. ");
2019 }
2020 buf_puts(text, "Copy oldText from a read_text_file of the current content and retry.");
2021}
2022
2023static int tool_edit_file(yyjson_val *args, buf_t *text)
2024{
2025 char raw[PATH_SZ], canon[PATH_SZ];
2026 const char *err = NULL;
2027 yyjson_val *edits;
2028 buf_t cur, work;
2029 size_t i, max;
2030 int dry_run;
2031 char *orig = NULL;
2032 size_t origlen = 0;
2033 int eol_crlf = 0;
2034
2035 if (!ju_field_str(args, "path", raw, sizeof raw))
2036 return (buf_puts(text, "missing required parameter \"path\""), 1);
2037 if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2038 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2039 if (!is_regular(canon))
2040 return (buf_printf(text, "%s: not a regular file", raw), 1);
2041
2042 edits = args ? yyjson_obj_get(args, "edits") : NULL;
2043 if (!edits || !yyjson_is_arr(edits) || yyjson_arr_size(edits) == 0)
2044 return (buf_puts(text, "missing required parameter \"edits\" (a non-empty array of {oldText,newText})"), 1);
2045 dry_run = ju_bool(args, "dryRun", 0);
2046
2047 buf_init(&cur);
2048 if (!read_whole(canon, &cur, READ_CAP, NULL, &err)) {
2049 buf_printf(text, "%s: %s", raw, err ? err : "read failed");
2050 buf_free(&cur);
2051 return 1;
2052 }
2053 /* detect the file's dominant line ending so the write restores it */
2054 for (i = 0; i + 1 < cur.n; i++)
2055 if (cur.p[i] == '\r' && cur.p[i + 1] == '\n') { eol_crlf = 1; break; }
2056
2057 /* normalise to LF for matching */
2058 {
2059 size_t o = 0;
2060 for (i = 0; i < cur.n; i++)
2061 if (!(cur.p[i] == '\r' && i + 1 < cur.n && cur.p[i + 1] == '\n'))
2062 cur.p[o++] = cur.p[i];
2063 cur.n = o;
2064 if (cur.p) cur.p[o] = '\0';
2065 }
2066 orig = (char *)malloc(cur.n + 1);
2067 if (!orig) { buf_free(&cur); return (buf_puts(text, "out of memory"), 1); }
2068 memcpy(orig, cur.p ? cur.p : "", cur.n);
2069 orig[cur.n] = '\0';
2070 origlen = cur.n;
2071
2072 buf_init(&work);
2073 buf_add(&work, orig, origlen);
2074
2075 max = yyjson_arr_size(edits);
2076 if (max > 100) max = 100;
2077 for (i = 0; i < max; i++) {
2078 yyjson_val *e = yyjson_arr_get(edits, i);
2079 const char *ot, *nt;
2080 size_t otlen, ntlen, at, ml;
2081 buf_t next;
2082
2083 if (!yyjson_is_obj(e)) {
2084 buf_free(&work);
2085 free(orig);
2086 buf_free(&cur);
2087 buf_puts(text, "each edit must be an object with oldText and newText");
2088 return 1;
2089 }
2090 ot = ju_str(e, "oldText");
2091 nt = ju_str(e, "newText");
2092 if (!ot) {
2093 buf_free(&work);
2094 free(orig);
2095 buf_free(&cur);
2096 buf_printf(text, "edit #%u is missing \"oldText\"", (unsigned)(i + 1));
2097 return 1;
2098 }
2099 if (!nt) nt = "";
2100 otlen = strlen(ot);
2101 ntlen = strlen(nt);
2102 if (otlen == 0) {
2103 buf_free(&work);
2104 free(orig);
2105 buf_free(&cur);
2106 buf_printf(text, "edit #%u has empty oldText - that would insert at position 0; send a real anchor",
2107 (unsigned)(i + 1));
2108 return 1;
2109 }
2110
2111 at = find_sub(work.p, work.n, ot, otlen);
2112 ml = otlen;
2113 if (at == (size_t)-1)
2114 at = find_lines(work.p, work.n, ot, otlen, &ml);
2115 if (at == (size_t)-1) {
2116 describe_mismatch(text, work.p, work.n, ot, otlen, i);
2117 buf_puts(text, " Nothing was written.");
2118 buf_free(&work);
2119 free(orig);
2120 buf_free(&cur);
2121 return 1;
2122 }
2123 buf_init(&next);
2124 buf_add(&next, work.p, at);
2125 buf_add(&next, nt, ntlen);
2126 buf_add(&next, work.p + at + ml, work.n - at - ml);
2127 buf_free(&work);
2128 work = next;
2129 }
2130
2131 if (!dry_run) {
2132 buf_t outb;
2133 const char *werr = NULL;
2134 buf_init(&outb);
2135 if (eol_crlf) {
2136 for (i = 0; i < work.n; i++) {
2137 if (work.p[i] == '\n') buf_putc(&outb, '\r');
2138 buf_putc(&outb, work.p[i]);
2139 }
2140 } else {
2141 buf_add(&outb, work.p, work.n);
2142 }
2143 if (!write_atomic(canon, outb.p ? outb.p : "", outb.n, &werr)) {
2144 buf_free(&outb);
2145 buf_free(&work);
2146 free(orig);
2147 buf_free(&cur);
2148 buf_printf(text, "%s: %s", raw, werr ? werr : "write failed");
2149 return 1;
2150 }
2151 buf_free(&outb);
2152 }
2153
2154 make_diff(text, orig, origlen, work.p ? work.p : "", work.n, raw);
2155 if (dry_run) buf_puts(text, "\n(dry run - nothing was written)\n");
2156 buf_free(&work);
2157 free(orig);
2158 buf_free(&cur);
2159 return 0;
2160}
2161
2162/* ------------------------------------------------------------------ */
2163/* The remaining tools */
2164/* ------------------------------------------------------------------ */
2165
2166static int tool_create_directory(yyjson_val *args, buf_t *text)
2167{
2168 char raw[PATH_SZ], canon[PATH_SZ];
2169 const char *err = NULL;
2170
2171 if (!ju_field_str(args, "path", raw, sizeof raw))
2172 return (buf_puts(text, "missing required parameter \"path\""), 1);
2173 if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2174 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2175 if (is_dir_path(canon)) {
2176 buf_printf(text, "Directory already exists: %s", raw);
2177 return 0;
2178 }
2179 if (is_regular(canon))
2180 return (buf_printf(text, "%s: a file already exists at that path", raw), 1);
2181 if (mkdir_p(canon) != 0)
2182 return (buf_printf(text, "%s: cannot create directory (%s)", raw,
2183 strerror(errno)), 1);
2184 buf_printf(text, "Successfully created directory %s", raw);
2185 return 0;
2186}
2187
2188static void emit_listing(buf_t *text, const char *path, const char *raw,
2189 long n, dent_t *v, int with_sizes)
2190{
2191 long i;
2192 long long tot_files = 0, tot_dirs = 0;
2193 for (i = 0; i < n; i++) {
2194 if (v[i].is_dir) tot_dirs++;
2195 else tot_files++;
2196 buf_puts(text, v[i].is_dir ? "[DIR] " : "[FILE] ");
2197 buf_puts(text, v[i].name);
2198 if (with_sizes && !v[i].is_dir)
2199 buf_printf(text, " %lld bytes", v[i].size);
2200 buf_putc(text, '\n');
2201 }
2202 if (n >= MAX_ENTRIES)
2203 buf_printf(text, "(listing truncated at %d entries)\n", MAX_ENTRIES);
2204 if (with_sizes)
2205 buf_printf(text, "\n%d directories, %lld files\n",
2206 (int)tot_dirs, tot_files);
2207 (void)path;
2208 (void)raw;
2209}
2210
2211static int tool_list_directory(yyjson_val *args, buf_t *text)
2212{
2213 char raw[PATH_SZ], canon[PATH_SZ];
2214 const char *err = NULL;
2215 dent_t *v = NULL;
2216 long n;
2217
2218 if (!ju_field_str(args, "path", raw, sizeof raw))
2219 return (buf_puts(text, "missing required parameter \"path\""), 1);
2220 if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2221 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2222 if (!is_dir_path(canon))
2223 return (buf_printf(text, "%s: not a directory", raw), 1);
2224 n = list_dir(canon, &v, &err);
2225 if (n < 0) {
2226 buf_printf(text, "%s: %s", raw, err ? err : "cannot read directory");
2227 return 1;
2228 }
2229 emit_listing(text, canon, raw, n, v, 0);
2230 free(v);
2231 return 0;
2232}
2233
2234/* Upstream says the tree is "formatted with 2-space indentation for
2235 * readability", and an agent pastes this straight into a reply, so the
2236 * indentation is part of the tool's output contract - not decoration. */
2237static void indent(buf_t *b, int depth)
2238{
2239 int i;
2240 for (i = 0; i < depth * 2; i++) buf_putc(b, ' ');
2241}
2242
2243/* Whether the buffer ends with an entry (so a closing bracket needs its own
2244 * line). An empty children array stays on one line: []. */
2245static int body_has_entries(const buf_t *b)
2246{
2247 size_t i;
2248 if (!b->p || b->n == 0) return 0;
2249 i = b->n - 1;
2250 while (i > 0 && (b->p[i] == ' ' || b->p[i] == '\n')) i--;
2251 return b->p[i] != '[';
2252}
2253
2254static int tree_walk(buf_t *b, const char *dir, const char *rel, int depth,
2255 int max_depth, long *budget, yyjson_val *excludes,
2256 int *truncated)
2257{
2258 dent_t *v = NULL;
2259 const char *err = NULL;
2260 long n, i;
2261 int first = 1;
2262
2263 if (*budget <= 0) { *truncated = 1; return 0; }
2264 n = list_dir(dir, &v, &err);
2265 if (n < 0) return -1;
2266 for (i = 0; i < n; i++) {
2267 char child[PATH_SZ], crel[PATH_SZ];
2268 if (*budget <= 0) { *truncated = 1; break; }
2269 if (v[i].name[0] == '.') continue; /* dotfiles stay out of a tree */
2270 (*budget)--;
2271 path_join(child, sizeof child, dir, v[i].name);
2272 if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2273 else str_copy(crel, sizeof crel, v[i].name);
2274 if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2275
2276 if (!first) buf_putc(b, ',');
2277 first = 0;
2278 buf_putc(b, '\n');
2279 indent(b, depth);
2280 buf_puts(b, "{\"name\":");
2281 json_str(b, v[i].name);
2282 buf_puts(b, ", \"type\":");
2283 buf_puts(b, v[i].is_dir ? "\"directory\"" : "\"file\"");
2284 if (v[i].is_dir && depth < max_depth) {
2285 int sub_trunc = 0;
2286 buf_puts(b, ", \"children\":[");
2287 tree_walk(b, child, crel, depth + 1, max_depth, budget, excludes,
2288 &sub_trunc);
2289 if (sub_trunc) *truncated = 1;
2290 if (body_has_entries(b)) {
2291 buf_putc(b, '\n');
2292 indent(b, depth);
2293 }
2294 buf_putc(b, ']');
2295 }
2296 buf_putc(b, '}');
2297 }
2298 free(v);
2299 return 0;
2300}
2301
2302static int tool_directory_tree(yyjson_val *args, buf_t *text)
2303{
2304 char raw[PATH_SZ], canon[PATH_SZ];
2305 const char *err = NULL;
2306 int have = 0;
2307 long long md = ju_int(args, "maxDepth", 4, &have);
2308 long budget = WALK_BUDGET;
2309 int truncated = 0;
2310 yyjson_val *excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2311 buf_t body;
2312
2313 if (!ju_field_str(args, "path", raw, sizeof raw))
2314 return (buf_puts(text, "missing required parameter \"path\""), 1);
2315 if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2316 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2317 if (!is_dir_path(canon))
2318 return (buf_printf(text, "%s: not a directory", raw), 1);
2319 if (md < 0) md = 0;
2320 if (md > MAX_DEPTH) md = MAX_DEPTH;
2321
2322 buf_init(&body);
2323 buf_putc(&body, '[');
2324 tree_walk(&body, canon, "", 1, (int)md, &budget, excludes, &truncated);
2325 if (body_has_entries(&body)) {
2326 buf_putc(&body, '\n');
2327 indent(&body, 0);
2328 }
2329 buf_putc(&body, ']');
2330 buf_add(text, body.p ? body.p : "[]", body.n);
2331 buf_free(&body);
2332 if (truncated)
2333 buf_printf(text, "\n(truncated after %d entries; narrow the path or lower maxDepth)",
2334 WALK_BUDGET);
2335 return 0;
2336}
2337
2338static int tool_move_file(yyjson_val *args, buf_t *text)
2339{
2340 char sraw[PATH_SZ], draw[PATH_SZ], src[PATH_SZ], dst[PATH_SZ];
2341 const char *err = NULL;
2342
2343 if (!ju_field_str(args, "source", sraw, sizeof sraw))
2344 return (buf_puts(text, "missing required parameter \"source\""), 1);
2345 if (!ju_field_str(args, "destination", draw, sizeof draw))
2346 return (buf_puts(text, "missing required parameter \"destination\""), 1);
2347 if (!resolve_allowed(sraw, src, sizeof src, 'r', &err))
2348 return (buf_printf(text, "source %s: %s", sraw, err ? err : "refused"), 1);
2349 if (is_link_path(src))
2350 return (buf_printf(text, "source %s: refusing to move a symlink", sraw), 1);
2351 if (resolve_allowed(draw, dst, sizeof dst, 'r', &err)) {
2352 if (is_dir_path(dst))
2353 return (buf_printf(text, "%s: a directory already exists at the destination", draw), 1);
2354 if (strcmp(src, dst) == 0) {
2355 buf_printf(text, "Source and destination are the same file: %s", sraw);
2356 return 0;
2357 }
2358 /* Upstream refuses to overwrite; so do we, silently-overwriting an
2359 * operator's file is the one thing an agent should never get. */
2360 return (buf_printf(text, "%s already exists - move nothing. Move to a new name instead.", draw), 1);
2361 }
2362 if (!resolve_allowed(draw, dst, sizeof dst, 'w', &err))
2363 return (buf_printf(text, "destination %s: %s", draw, err ? err : "refused"), 1);
2364 if (ensure_parent(dst) != 0)
2365 return (buf_printf(text, "%s: cannot create the destination directory", draw), 1);
2366
2367#if defined(_WIN32)
2368 if (!MoveFileExA(src, dst, MOVEFILE_WRITE_THROUGH)) {
2369 DWORD e = GetLastError();
2370 if (e == ERROR_NOT_SAME_DEVICE) {
2371 if (!copy_file(src, dst, &err)) {
2372 buf_printf(text, "%s: %s", sraw, err ? err : "copy failed");
2373 return 1;
2374 }
2375 DeleteFileA(src);
2376 } else {
2377 buf_printf(text, "%s -> %s: Win32 error %lu", sraw, draw, (unsigned long)e);
2378 return 1;
2379 }
2380 }
2381#else
2382 if (rename(src, dst) != 0) {
2383 if (errno == EXDEV) {
2384 /* Cross-device: copy then remove. Same visible result, one more
2385 * window, so the removal only happens once the copy is on disk. */
2386 if (!copy_file(src, dst, &err)) {
2387 buf_printf(text, "%s -> %s: %s", sraw, draw, err ? err : "copy failed");
2388 return 1;
2389 }
2390 if (remove(src) != 0) {
2391 buf_printf(text, "copied %s to %s but could not remove the source (%s)",
2392 sraw, draw, strerror(errno));
2393 return 1;
2394 }
2395 } else {
2396 buf_printf(text, "%s -> %s: %s", sraw, draw, strerror(errno));
2397 return 1;
2398 }
2399 }
2400#endif
2401 buf_printf(text, "Successfully moved %s to %s", sraw, draw);
2402 return 0;
2403}
2404
2405/* A walk may only descend into paths still inside a root; re-checking each
2406 * child also catches a symlink that a directory scan handed us. */
2407static int is_allowed_for_walk(const char *canon_child)
2408{
2409 char pc[PATH_SZ];
2410 if (denied_path(canon_child)) return 0;
2411 if (root_contains(canon_child) >= 0) return 1;
2412 if (canon_path(canon_child, pc, sizeof pc))
2413 return root_contains(pc) >= 0 && !denied_path(pc);
2414 return 0;
2415}
2416
2417typedef struct {
2418 buf_t *out;
2419 long count;
2420 int truncated;
2421} search_ctx;
2422
2423static void search_walk(const char *dir, const char *rel, const char *pattern,
2424 yyjson_val *excludes, long *budget, search_ctx *sc)
2425{
2426 dent_t *v = NULL;
2427 const char *err = NULL;
2428 long n, i;
2429
2430 if (*budget <= 0) { sc->truncated = 1; return; }
2431 n = list_dir(dir, &v, &err);
2432 if (n < 0) return; /* unreadable subtree: skip */
2433 for (i = 0; i < n; i++) {
2434 char child[PATH_SZ], crel[PATH_SZ];
2435 if (*budget <= 0) { sc->truncated = 1; break; }
2436 (*budget)--;
2437 path_join(child, sizeof child, dir, v[i].name);
2438 if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2439 else str_copy(crel, sizeof crel, v[i].name);
2440
2441 /* excludes are checked before anything else, so an excluded subtree
2442 * is never even opened (upstream #4162) */
2443 if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2444 if (!is_allowed_for_walk(child)) { continue; }
2445
2446 if (sc->count < MAX_RESULTS) {
2447 int hit = glob_match(pattern, crel) || glob_match(pattern, v[i].name);
2448 if (hit) {
2449 if (sc->count) buf_putc(sc->out, '\n');
2450 buf_puts(sc->out, child);
2451 sc->count++;
2452 }
2453 } else {
2454 sc->truncated = 1;
2455 }
2456 if (v[i].is_dir) search_walk(child, crel, pattern, excludes, budget, sc);
2457 }
2458 free(v);
2459}
2460
2461static int tool_search_files(yyjson_val *args, buf_t *text)
2462{
2463 char raw[PATH_SZ], canon[PATH_SZ], rel[PATH_SZ] = "";
2464 const char *err = NULL;
2465 char pattern[NAME_SZ];
2466 yyjson_val *excludes;
2467 search_ctx sc;
2468 long budget = WALK_BUDGET;
2469
2470 if (!ju_field_str(args, "path", raw, sizeof raw))
2471 return (buf_puts(text, "missing required parameter \"path\""), 1);
2472 if (!ju_field_str(args, "pattern", pattern, sizeof pattern))
2473 return (buf_puts(text, "missing required parameter \"pattern\""), 1);
2474 if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2475 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2476 if (!is_dir_path(canon))
2477 return (buf_printf(text, "%s: not a directory (search walks directories)", raw), 1);
2478 excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2479
2480 sc.out = text;
2481 sc.count = 0;
2482 sc.truncated = 0;
2483 search_walk(canon, rel, pattern, excludes, &budget, &sc);
2484 if (sc.count == 0) {
2485 buf_puts(text, "(no matches)");
2486 return 0;
2487 }
2488 if (sc.truncated)
2489 buf_printf(text, "\n(truncated: %d matches shown, walk budget %d entries; narrow the path or add excludePatterns)",
2490 (int)sc.count, WALK_BUDGET);
2491 return 0;
2492}
2493
2494/* One timestamp as a JSON string (or null). */
2495static void json_time(buf_t *b, long long t)
2496{
2497 char iso[40];
2498 if (t <= 0) { buf_puts(b, "null"); return; }
2499 fmt_iso(t, iso, sizeof iso);
2500 json_str(b, iso);
2501}
2502
2503static long long file_atime(const char *p)
2504{
2505#if defined(_WIN32)
2506 WIN32_FILE_ATTRIBUTE_DATA d;
2507 ULARGE_INTEGER u;
2508 if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
2509 u.LowPart = d.ftLastAccessTime.dwLowDateTime;
2510 u.HighPart = d.ftLastAccessTime.dwHighDateTime;
2511 return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
2512#else
2513 struct stat st;
2514 if (stat(p, &st) != 0) return 0;
2515 return (long long)st.st_atime;
2516#endif
2517}
2518
2519static int tool_get_file_info(yyjson_val *args, buf_t *text)
2520{
2521 char raw[PATH_SZ], canon[PATH_SZ];
2522 const char *err = NULL;
2523
2524 if (!ju_field_str(args, "path", raw, sizeof raw))
2525 return (buf_puts(text, "missing required parameter \"path\""), 1);
2526 if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2527 return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2528
2529 buf_puts(text, "{\n \"path\":");
2530 json_str(text, canon);
2531 buf_puts(text, is_dir_path(canon)
2532 ? ",\n \"type\":\"directory\""
2533 : ",\n \"type\":\"file\"");
2534 buf_printf(text, ",\n \"size\":%lld", file_size(canon));
2535 buf_puts(text, ",\n \"created\":");
2536 json_time(text, 0); /* birth time is not portable */
2537 buf_puts(text, ",\n \"modified\":");
2538 json_time(text, file_mtime(canon));
2539 buf_puts(text, ",\n \"accessed\":");
2540 json_time(text, file_atime(canon));
2541 buf_printf(text, ",\n \"isFile\":%s", is_regular(canon) ? "true" : "false");
2542 buf_printf(text, ",\n \"isDirectory\":%s", is_dir_path(canon) ? "true" : "false");
2543 buf_printf(text, ",\n \"isSymlink\":%s", is_link_path(canon) ? "true" : "false");
2544 buf_printf(text, ",\n \"mode\":\"%04o\"\n}\n", file_mode(canon));
2545 return 0;
2546}
2547
2548static int tool_list_allowed_directories(yyjson_val *args, buf_t *text)
2549{
2550 int i;
2551 (void)args;
2552 buf_printf(text, "Allowed directories (%d):\n", g_root_count);
2553 if (g_root_count == 0)
2554 buf_puts(text, "(none configured - the plugin has nothing it may touch)");
2555 for (i = 0; i < g_root_count; i++) {
2556 buf_puts(text, g_roots[i].canonical);
2557 if (strcmp(g_roots[i].configured, g_roots[i].canonical) != 0)
2558 buf_printf(text, " (configured as %s)", g_roots[i].configured);
2559 if (!g_roots[i].exists) buf_puts(text, " [does not exist]");
2560 else if (!g_roots[i].is_dir) buf_puts(text, " [not a directory]");
2561 buf_putc(text, '\n');
2562 }
2563 return 0;
2564}
2565
2566/* ------------------------------------------------------------------ */
2567/* Tool registry */
2568/* */
2569/* Descriptions are written to be read by a model choosing a tool, so */
2570/* they say when to use this one and what the parameters mean, and every */
2571/* one ends with the same reminder: it only works inside the allowed */
2572/* directories. The inputSchema is what the router hands to clang's */
2573/* MAX_TOOLS 512 budget, so it stays compact. */
2574/* ------------------------------------------------------------------ */
2575
2576typedef struct {
2577 const char *name;
2578 const char *title;
2579 const char *desc;
2580 const char *schema;
2581 int read_only;
2582 int destructive;
2583 tool_fn fn;
2584} tool_def;
2585
2586#define S_PROPS(p) "{\"type\":\"object\",\"properties\":{" p "},\"required\""
2587
2588static const tool_def TOOLS[TOOLS_N] = {
2589{"read_text_file", "Read Text File",
2590 "Read the complete contents of a file as text. Use head for the first N lines "
2591 "or tail for the last N (send at most one). Fails on binary files; use "
2592 "get_file_info for metadata. Only works within allowed directories.",
2593 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2594 "\"head\":{\"type\":\"integer\",\"description\":\"Return only the first N lines\"},"
2595 "\"tail\":{\"type\":\"integer\",\"description\":\"Return only the last N lines\"}},"
2596 "\"required\":[\"path\"]}", 1, 0, tool_read_text_file},
2597
2598{"read_multiple_files", "Read Multiple Files",
2599 "Read several files in one call - cheaper than one read per file when "
2600 "comparing or diffing. Each result is prefixed with its path and separated by "
2601 "a line of three dashes; a file that fails reports its error without stopping "
2602 "the rest. Only works within allowed directories.",
2603 "{\"type\":\"object\",\"properties\":{\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2604 "\"description\":\"Absolute file paths (up to 200)\"}},\"required\":[\"paths\"]}", 1, 0,
2605 tool_read_multiple_files},
2606
2607{"write_file", "Write File",
2608 "Create or completely overwrite a file. Content is written to a temporary "
2609 "file and renamed into place, so a crash cannot leave a half-written file. "
2610 "Missing parent directories are created. Only works within allowed directories.",
2611 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2612 "\"content\":{\"type\":\"string\",\"description\":\"Exact bytes to write\"}},\"required\":[\"path\",\"content\"]}",
2613 0, 1, tool_write_file},
2614
2615{"edit_file", "Edit File",
2616 "Apply targeted replacements to a text file. Edits apply in order and each "
2617 "replaces the first match of its oldText; oldText must match exactly, except "
2618 "that LF/CRLF never matters and a run of whole lines matches when each line "
2619 "is equal ignoring leading and trailing whitespace. If any edit fails to "
2620 "match, NOTHING is written and the reply shows the closest numbered lines. "
2621 "Set dryRun to see the diff without touching the disk. Only works within "
2622 "allowed directories.",
2623 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2624 "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"oldText\":{\"type\":\"string\"},"
2625 "\"newText\":{\"type\":\"string\"}},\"required\":[\"oldText\",\"newText\"]}},\"dryRun\":{\"type\":\"boolean\","
2626 "\"description\":\"Compute and return the diff without writing\"}},\"required\":[\"path\",\"edits\"]}",
2627 0, 1, tool_edit_file},
2628
2629{"create_directory", "Create Directory",
2630 "Create a directory and any missing parents. Succeeds if it already exists. "
2631 "Only works within allowed directories.",
2632 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2633 "\"required\":[\"path\"]}", 0, 0, tool_create_directory},
2634
2635{"list_directory", "List Directory",
2636 "List entries directly inside a directory, each marked [DIR] or [FILE], "
2637 "directories first then alphabetical. For a recursive view use directory_tree. "
2638 "Only works within allowed directories.",
2639 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2640 "\"required\":[\"path\"]}", 1, 0, tool_list_directory},
2641
2642{"directory_tree", "Directory Tree",
2643 "Recursive tree of a directory as JSON: name, type (file/directory) and "
2644 "children for directories. maxDepth bounds the depth (default 4); "
2645 "excludePatterns are glob patterns matched against the relative path. Dot "
2646 "entries are omitted. Only works within allowed directories.",
2647 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"},"
2648 "\"maxDepth\":{\"type\":\"integer\",\"description\":\"Levels to descend (0-24, default 4)\"},"
2649 "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2650 "\"description\":\"Globs such as node_modules or *.tmp matched on the relative path\"}},"
2651 "\"required\":[\"path\"]}", 1, 0, tool_directory_tree},
2652
2653{"move_file", "Move File",
2654 "Move or rename a file or directory. Will NOT overwrite an existing "
2655 "destination - move to a new name instead. A cross-device move falls back to "
2656 "copy-then-delete. Only works within allowed directories.",
2657 "{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\",\"description\":\"Absolute current path\"},"
2658 "\"destination\":{\"type\":\"string\",\"description\":\"Absolute new path (must not exist)\"}},"
2659 "\"required\":[\"source\",\"destination\"]}", 0, 1, tool_move_file},
2660
2661{"search_files", "Search Files",
2662 "Recursively find files and directories whose name or relative path matches a "
2663 "glob pattern such as *.c or test_*.py. excludePatterns prunes subtrees "
2664 "(node_modules, .git) before they are ever opened. Returns absolute paths. "
2665 "Only works within allowed directories.",
2666 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory to search\"},"
2667 "\"pattern\":{\"type\":\"string\",\"description\":\"Glob, e.g. *.log or **/README*\"},"
2668 "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2669 "\"description\":\"Globs pruned from the walk\"}},\"required\":[\"path\",\"pattern\"]}", 1, 0,
2670 tool_search_files},
2671
2672{"get_file_info", "Get File Info",
2673 "Size, timestamps, type, symlink-ness and permission bits of one path. Use "
2674 "this before reading anything large. Only works within allowed directories.",
2675 "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute path\"}},"
2676 "\"required\":[\"path\"]}", 1, 0, tool_get_file_info},
2677
2678{"list_allowed_directories", "List Allowed Directories",
2679 "Report the directories this server may read and write, with the canonical "
2680 "path each one really resolves to. Call this first when a path is refused so "
2681 "you can pick a path inside a root.",
2682 "{\"type\":\"object\",\"properties\":{}}", 1, 0, tool_list_allowed_directories}
2683};
2684
2685/* ------------------------------------------------------------------ */
2686/* --mcp : MCP JSON-RPC 2.0 over stdio */
2687/* */
2688/* Contract as the router drives it (scorpiox-connector-mcp): one JSON */
2689/* object per line, responses on stdout terminated by \n, and nothing */
2690/* else ever printed to stdout. Logs therefore go to stderr, a malformed */
2691/* line is answered with -32700 (the router skips unparseable lines, but */
2692/* an id-less parse error is what a client needs to see it is talking to */
2693/* a real server), and a notification gets no reply at all. */
2694/* */
2695/* Content-Length framing is tolerated on input because a few clients */
2696/* speak LSP-style headers; output is always newline-delimited. */
2697/* ------------------------------------------------------------------ */
2698
2699static void log_err(const char *fmt, ...)
2700{
2701 va_list ap;
2702 fputs(PLUGIN_ID ": ", stderr);
2703 va_start(ap, fmt);
2704 vfprintf(stderr, fmt, ap);
2705 va_end(ap);
2706 fputc('\n', stderr);
2707}
2708
2709static void send_msg(const char *json)
2710{
2711 fputs(json, stdout);
2712 fputc('\n', stdout);
2713 fflush(stdout);
2714}
2715
2716static void send_result(const char *id_raw, const char *result_json)
2717{
2718 buf_t b;
2719 if (!id_raw) return; /* notification */
2720 buf_init(&b);
2721 buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}",
2722 id_raw, result_json ? result_json : "{}");
2723 send_msg(b.p ? b.p : "{}");
2724 buf_free(&b);
2725}
2726
2727static void send_error(const char *id_raw, int code, const char *msg)
2728{
2729 buf_t b;
2730 /* A parse error has no id to echo, but JSON-RPC still wants the
2731 * client to see it: answer with id:null. Only a request we know is a
2732 * notification (an id-less, method-bearing line) stays silent. */
2733 buf_init(&b);
2734 buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":%d,\"message\":",
2735 id_raw ? id_raw : "null", code);
2736 json_str(&b, msg ? msg : "error");
2737 buf_puts(&b, "}}");
2738 send_msg(b.p ? b.p : "{}");
2739 buf_free(&b);
2740}
2741
2742/* The id verbatim (number or string) so it round-trips byte-exact. */
2743static char *id_raw_of(yyjson_val *root)
2744{
2745 yyjson_val *id = yyjson_obj_get(root, "id");
2746 char *s;
2747 if (!id) return NULL; /* a notification */
2748 s = yyjson_val_write(id, 0, NULL);
2749 return s ? s : strdup("null");
2750}
2751
2752static void emit_tools_list(const char *id_raw)
2753{
2754 buf_t b;
2755 int i;
2756 buf_init(&b);
2757 buf_puts(&b, "{\"tools\":[");
2758 for (i = 0; i < TOOLS_N; i++) {
2759 if (i) buf_putc(&b, ',');
2760 buf_puts(&b, "{\"name\":");
2761 json_str(&b, TOOLS[i].name);
2762 buf_puts(&b, ",\"title\":");
2763 json_str(&b, TOOLS[i].title);
2764 buf_puts(&b, ",\"description\":");
2765 json_str(&b, TOOLS[i].desc);
2766 buf_puts(&b, ",\"inputSchema\":");
2767 buf_puts(&b, TOOLS[i].schema);
2768 buf_puts(&b, ",\"annotations\":{\"readOnlyHint\":");
2769 buf_puts(&b, TOOLS[i].read_only ? "true" : "false");
2770 buf_puts(&b, ",\"destructiveHint\":");
2771 buf_puts(&b, TOOLS[i].destructive ? "true" : "false");
2772 buf_puts(&b, ",\"idempotentHint\":true,\"openWorldHint\":false}");
2773 buf_putc(&b, '}');
2774 }
2775 buf_puts(&b, "]}");
2776 send_result(id_raw, b.p);
2777 buf_free(&b);
2778}
2779
2780static void handle_tools_call(const char *id_raw, yyjson_val *params)
2781{
2782 const char *name = ju_str(params, "name");
2783 yyjson_val *arguments = params ? yyjson_obj_get(params, "arguments") : NULL;
2784 buf_t text;
2785 int is_err;
2786 int idx;
2787 buf_t out;
2788
2789 if (!name || !*name) {
2790 send_error(id_raw, -32602, "missing tool name");
2791 return;
2792 }
2793 idx = tool_index(name);
2794 if (idx < 0) {
2795 send_error(id_raw, -32602, "unknown tool");
2796 return;
2797 }
2798 if (g_tool_off[idx]) {
2799 buf_t why;
2800 buf_init(&why);
2801 buf_printf(&why, "tool \"%s\" is disabled in this connector's permissions - "
2802 "enable it in the filesystem plugin page (Allowed Roots & Permissions)",
2803 TOOLS[idx].name);
2804 buf_init(&out);
2805 buf_puts(&out, "{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":");
2806 json_str(&out, why.p ? why.p : "");
2807 buf_puts(&out, "}]}");
2808 send_result(id_raw, out.p);
2809 buf_free(&out);
2810 buf_free(&why);
2811 return;
2812 }
2813 if (arguments && !yyjson_is_obj(arguments)) arguments = NULL;
2814
2815 buf_init(&text);
2816 is_err = TOOLS[idx].fn(arguments, &text);
2817
2818 buf_init(&out);
2819 buf_puts(&out, "{\"isError\":");
2820 buf_puts(&out, is_err ? "true" : "false");
2821 buf_puts(&out, ",\"content\":[{\"type\":\"text\",\"text\":");
2822 json_str(&out, text.p ? text.p : "");
2823 buf_puts(&out, "}]}");
2824 send_result(id_raw, out.p);
2825 buf_free(&out);
2826 buf_free(&text);
2827}
2828
2829static void handle_line(const char *line)
2830{
2831 yyjson_doc *doc;
2832 yyjson_val *root, *params;
2833 const char *method;
2834 char *id_raw;
2835
2836 if (!line) return;
2837 while (*line == ' ' || *line == '\t') line++;
2838 if (!*line) return;
2839
2840 doc = yyjson_read(line, strlen(line), 0);
2841 if (!doc) {
2842 send_error(NULL, -32700, "parse error");
2843 return;
2844 }
2845 root = yyjson_doc_get_root(doc);
2846 if (!yyjson_is_obj(root)) {
2847 yyjson_doc_free(doc);
2848 send_error(NULL, -32700, "parse error");
2849 return;
2850 }
2851 method = ju_str(root, "method");
2852 id_raw = id_raw_of(root);
2853 params = yyjson_obj_get(root, "params");
2854
2855 if (!method) {
2856 if (id_raw) send_error(id_raw, -32600, "missing method");
2857 free(id_raw);
2858 yyjson_doc_free(doc);
2859 return;
2860 }
2861
2862 if (!strcmp(method, "initialize")) {
2863 buf_t b;
2864 const char *want = ju_str(params, "protocolVersion");
2865 buf_init(&b);
2866 buf_puts(&b, "{\"protocolVersion\":");
2867 /* Answer the client's version when it is one we speak, else ours:
2868 * 2024-11-05 is what scorpiox-connector-mcp asks for. */
2869 json_str(&b, (want && (!strcmp(want, "2024-11-05") || !strcmp(want, "2025-03-26") ||
2870 !strcmp(want, "2025-06-18"))) ? want : MCP_PROTO);
2871 buf_puts(&b, ",\"capabilities\":{\"tools\":{\"listChanged\":false}},\"serverInfo\":{");
2872 buf_puts(&b, "\"name\":\"");
2873 buf_puts(&b, PLUGIN_ID);
2874 buf_puts(&b, "\",\"version\":\"");
2875 buf_puts(&b, PLUGIN_VER);
2876 buf_puts(&b, "\"},\"instructions\":");
2877 json_str(&b,
2878 "Sandboxed filesystem tools. Every path is canonicalised and "
2879 "must resolve inside the allowed roots; traversal and symlink "
2880 "escapes are refused. Call list_allowed_directories first if "
2881 "a path is refused.");
2882 buf_putc(&b, '}');
2883 send_result(id_raw, b.p);
2884 buf_free(&b);
2885 } else if (!strncmp(method, "notifications/", 14) || !strcmp(method, "ping")) {
2886 if (id_raw && !strcmp(method, "ping")) send_result(id_raw, "{}");
2887 } else if (!strcmp(method, "tools/list")) {
2888 if (id_raw) {
2889 init_roots();
2890 emit_tools_list(id_raw);
2891 }
2892 } else if (!strcmp(method, "tools/call")) {
2893 init_roots();
2894 handle_tools_call(id_raw, params);
2895 } else if (!strcmp(method, "resources/list")) {
2896 if (id_raw) send_result(id_raw, "{\"resources\":[]}");
2897 } else if (!strcmp(method, "resources/templates/list")) {
2898 if (id_raw) send_result(id_raw, "{\"resourceTemplates\":[]}");
2899 } else if (!strcmp(method, "prompts/list")) {
2900 if (id_raw) send_result(id_raw, "{\"prompts\":[]}");
2901 } else if (!strcmp(method, "logging/setLevel")) {
2902 if (id_raw) send_result(id_raw, "{}");
2903 } else {
2904 if (id_raw) send_error(id_raw, -32601, "method not found");
2905 }
2906
2907 free(id_raw);
2908 yyjson_doc_free(doc);
2909}
2910
2911/* Read one request. Newline-delimited, with Content-Length framing accepted
2912 * because a handful of clients emit LSP headers instead of newlines. */
2913static int read_request_line(buf_t *line)
2914{
2915 static char rb[IO_CHUNK];
2916 static size_t rn, rp;
2917 long long want = -1;
2918
2919 line->n = 0;
2920 for (;;) {
2921 if (rp < rn) {
2922 size_t i = rp;
2923 int nl = 0;
2924 while (i < rn && rb[i] != '\n') i++;
2925 if (i < rn) nl = 1;
2926 {
2927 size_t take = i - rp;
2928 char tmp[IO_CHUNK + 1]; /* +1: the terminator below */
2929 if (take > 0) memcpy(tmp, rb + rp, take);
2930 rp = i + (nl ? 1 : 0);
2931 tmp[take] = '\0';
2932 while (take > 0 && (tmp[take - 1] == '\r' || tmp[take - 1] == ' '))
2933 tmp[--take] = '\0';
2934 if (want < 0 && !strncmp(tmp, "Content-Length:", 15)) {
2935 want = strtoll(tmp + 15, NULL, 10);
2936 continue;
2937 }
2938 if (want < 0 && take == 0 && !nl) continue; /* header blank */
2939 buf_add(line, tmp, take);
2940 if (want < 0) {
2941 /* Newline-delimited: a chunk without '\n' is not a line,
2942 * it is the front half of one. Only return when the
2943 * terminator was actually seen (or at EOF below).
2944 * take==0 && nl is the terminator that completes a frame
2945 * written as two separate writes - the router's
2946 * proc_send() writes the body and the '\n' apart, and an
2947 * earlier cut of this function dropped that blank line
2948 * into the header path, hanging every router call. */
2949 if (nl) return 1;
2950 continue;
2951 }
2952 if ((long long)line->n >= want) { /* framed body */
2953 if (line->p && (size_t)want < line->cap) line->p[want] = '\0';
2954 line->n = (size_t)want;
2955 want = -1;
2956 return 1;
2957 }
2958 buf_putc(line, '\n');
2959 continue;
2960 }
2961 }
2962 if (rp >= rn) { rn = 0; rp = 0; }
2963 /* NOT fread: on a pipe fread blocks until the whole 64 KiB buffer
2964 * fills or EOF, so a client that sends "frame" and flushes, then
2965 * sends "\n" later (the router's proc_send writes body and newline
2966 * as separate writes), would hang. read() returns what is there. */
2967 for (;;) {
2968#if defined(_WIN32)
2969 long got = (long)_read(_fileno(stdin), rb, (unsigned)sizeof rb);
2970#else
2971 long got = (long)read(fileno(stdin), rb, sizeof rb);
2972#endif
2973 if (got > 0) { rn = (size_t)got; break; }
2974 if (got == 0) return line->n ? 1 : 0; /* EOF */
2975#if !defined(_WIN32)
2976 if (errno == EINTR) continue; /* signal, retry */
2977#endif
2978 return line->n ? 1 : 0; /* error = close */
2979 }
2980 }
2981}
2982
2983static int mode_mcp(void)
2984{
2985 buf_t line;
2986#if defined(_WIN32)
2987 _setmode(_fileno(stdout), O_BINARY); /* \n stays \n, no CRLF */
2988 _setmode(_fileno(stdin), O_BINARY);
2989#endif
2990 buf_init(&line);
2991 while (read_request_line(&line)) {
2992 if (line.n > MCP_LINE_CAP) {
2993 log_err("request line exceeds %d bytes; dropping", (int)MCP_LINE_CAP);
2994 send_error(NULL, -32600, "request too large");
2995 continue;
2996 }
2997 if (line.n) handle_line(line.p);
2998 }
2999 buf_free(&line);
3000 return 0;
3001}
3002
3003/* ------------------------------------------------------------------ */
3004/* Config persistence (the Setup UI writes what --mcp reads) */
3005/* ------------------------------------------------------------------ */
3006
3007/* Atomic like write_file: same tmp+rename discipline, because a half-written
3008 * roots.json would silently widen or narrow the sandbox. */
3009static int save_roots_file(void)
3010{
3011 char dir[PATH_SZ], tmp[PATH_SZ];
3012 buf_t b;
3013 FILE *f;
3014 int i;
3015
3016 connectors_dir(dir, sizeof dir);
3017 if (mkpath(dir) != 0) return -1;
3018 snprintf(tmp, sizeof tmp, "%s", g_roots_file);
3019 if (strlen(tmp) + 12 >= sizeof tmp) return -1;
3020 str_copy(tmp + strlen(tmp), sizeof tmp - strlen(tmp), ".tmp");
3021
3022 buf_init(&b);
3023 buf_puts(&b, "{\n \"roots\": [");
3024 for (i = 0; i < g_root_count; i++) {
3025 if (i) buf_putc(&b, ',');
3026 buf_puts(&b, "\n ");
3027 json_str(&b, g_roots[i].configured[0] ? g_roots[i].configured
3028 : g_roots[i].canonical);
3029 }
3030 buf_puts(&b, g_root_count ? "\n ],\n" : "],\n");
3031 buf_puts(&b, " \"denied\": [");
3032 for (i = 0; i < deny_count; i++) {
3033 if (i) buf_putc(&b, ',');
3034 buf_puts(&b, "\n ");
3035 json_str(&b, g_deny[i]);
3036 }
3037 buf_puts(&b, deny_count ? "\n ],\n" : "],\n");
3038 buf_puts(&b, " \"permissions\": {\n");
3039 for (i = 0; i < TOOLS_N; i++) {
3040 buf_printf(&b, " \"%s\": %s%s\n", TOOL_NAMES[i],
3041 g_tool_off[i] ? "false" : "true",
3042 i + 1 < TOOLS_N ? "," : "");
3043 }
3044 buf_puts(&b, " }\n}\n");
3045
3046 f = fopen(tmp, "wb");
3047 if (!f) { buf_free(&b); return -1; }
3048 if (b.n && fwrite(b.p, 1, b.n, f) != b.n) {
3049 fclose(f);
3050#if defined(_WIN32)
3051 DeleteFileA(tmp);
3052#else
3053 remove(tmp);
3054#endif
3055 buf_free(&b);
3056 return -1;
3057 }
3058 fclose(f);
3059#if defined(_WIN32)
3060 MoveFileExA(g_roots_file, tmp, 0); /* keep a copy for rollback */
3061 if (!MoveFileExA(tmp, g_roots_file, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
3062 buf_free(&b);
3063 return -1;
3064 }
3065#else
3066 if (rename(tmp, g_roots_file) != 0) {
3067 remove(tmp);
3068 buf_free(&b);
3069 return -1;
3070 }
3071#endif
3072 buf_free(&b);
3073 return 0;
3074}
3075
3076static void ensure_roots_file_path(void)
3077{
3078 if (g_roots_file[0]) return;
3079 init_roots();
3080 if (g_roots_file[0]) return;
3081 {
3082 char dir[PATH_SZ];
3083 connectors_dir(dir, sizeof dir);
3084 snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
3085 {
3086 size_t dl = strlen(g_roots_file);
3087 if (dl + 12 < sizeof g_roots_file) {
3088 g_roots_file[dl] = SEP;
3089 g_roots_file[dl + 1] = '\0';
3090 str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
3091 }
3092 }
3093 }
3094}
3095
3096static void json_header(void)
3097{
3098 fputs("Content-Type: application/json; charset=utf-8\r\n"
3099 "Cache-Control: no-store\r\n"
3100 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
3101}
3102
3103static void json_err(int code, const char *msg)
3104{
3105 if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout);
3106 else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout);
3107 else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout);
3108 else if (code == 409) fputs("Status: 409 Conflict\r\n", stdout);
3109 else fputs("Status: 500 Internal Server Error\r\n", stdout);
3110 json_header();
3111 printf("{\"ok\":false,\"error\":");
3112 {
3113 buf_t b;
3114 buf_init(&b);
3115 json_str(&b, msg ? msg : "error");
3116 fputs(buf_str(&b), stdout);
3117 buf_free(&b);
3118 }
3119 fputs("}\n", stdout);
3120}
3121
3122/* ------------------------------------------------------------------ */
3123/* CGI actions */
3124/* ------------------------------------------------------------------ */
3125
3126static void do_status(void)
3127{
3128 int i;
3129 json_header();
3130 printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"kind\":\"mcp\","
3131 "\"mcp\":true,\"verified\":\"live\",\"protocol\":\"%s\",\"tools\":%d,"
3132 "\"roots_file\":", PLUGIN_ID, PLUGIN_VER, MCP_PROTO, TOOLS_N);
3133 {
3134 buf_t b;
3135 buf_init(&b);
3136 ensure_roots_file_path();
3137 json_str(&b, g_roots_file);
3138 printf("%s", buf_str(&b));
3139 buf_free(&b);
3140 }
3141 printf(",\"config_source\":%s",
3142 getenv("FS_ALLOWED_ROOTS") ? "\"env:FS_ALLOWED_ROOTS\"" :
3143 (g_root_count ? "\"roots.json-or-defaults\"" : "\"none\""));
3144 printf(",\"writable\":%s",
3145 (g_roots_file[0] && access(g_roots_file, 2) == 0) ||
3146 (!g_roots_file[0]) ? "true" : "false");
3147 printf(",\"roots\":[");
3148 for (i = 0; i < g_root_count; i++) {
3149 printf("%s{\"configured\":", i ? "," : "");
3150 {
3151 buf_t b;
3152 buf_init(&b);
3153 json_str(&b, g_roots[i].configured);
3154 printf("%s", buf_str(&b));
3155 buf_free(&b);
3156 }
3157 printf(",\"canonical\":");
3158 {
3159 buf_t b;
3160 buf_init(&b);
3161 json_str(&b, g_roots[i].canonical);
3162 printf("%s", buf_str(&b));
3163 buf_free(&b);
3164 }
3165 printf(",\"exists\":%s,\"is_dir\":%s,\"drift\":%s}",
3166 g_roots[i].exists ? "true" : "false",
3167 g_roots[i].is_dir ? "true" : "false",
3168 strcmp(g_roots[i].configured, g_roots[i].canonical) ? "true" : "false");
3169 }
3170 printf("],\"denied\":[");
3171 for (i = 0; i < deny_count; i++) {
3172 buf_t b;
3173 buf_init(&b);
3174 json_str(&b, g_deny[i]);
3175 printf("%s%s", i ? "," : "", buf_str(&b));
3176 buf_free(&b);
3177 }
3178 printf("],\"permissions\":{");
3179 for (i = 0; i < TOOLS_N; i++)
3180 printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3181 g_tool_off[i] ? "false" : "true");
3182 printf("}}\n");
3183}
3184
3185static void do_roots(void)
3186{
3187 int i;
3188 json_header();
3189 printf("{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count);
3190 for (i = 0; i < g_root_count; i++) {
3191 const char *base = strrchr(g_roots[i].canonical, '/');
3192 char label[NAME_SZ];
3193 buf_t b;
3194 buf_init(&b);
3195 if (i) buf_putc(&b, ','); /* after init - was UB before it */
3196 buf_puts(&b, "\n {\"path\":");
3197 json_str(&b, g_roots[i].canonical);
3198 buf_puts(&b, ",\"canonical\":");
3199 json_str(&b, g_roots[i].canonical);
3200 buf_puts(&b, ",\"configured\":");
3201 json_str(&b, g_roots[i].configured);
3202 buf_puts(&b, ",\"name\":");
3203 if (base && base[1]) str_copy(label, sizeof label, base + 1);
3204 else str_copy(label, sizeof label, g_roots[i].canonical);
3205 json_str(&b, label);
3206 buf_printf(&b, ",\"exists\":%s,\"is_dir\":%s}",
3207 g_roots[i].exists ? "true" : "false",
3208 g_roots[i].is_dir ? "true" : "false");
3209 fputs(buf_str(&b), stdout);
3210 buf_free(&b);
3211 }
3212 printf("\n]}\n");
3213}
3214
3215static void do_roots_add(const char *path)
3216{
3217 int before = g_root_count;
3218 char canon[PATH_SZ];
3219 if (!path || !*path) { json_err(400, "path is required"); return; }
3220 if (!path_shape_ok(path)) {
3221 json_err(400, "path must be absolute and must not contain '..'");
3222 return;
3223 }
3224 if (!canon_path(path, canon, sizeof canon)) {
3225 json_err(404, "that directory does not exist yet");
3226 return;
3227 }
3228 if (denied_path(canon)) { json_err(403, "that path is on the deny list"); return; }
3229 add_root_raw(path);
3230 if (g_root_count == before) { json_err(409, "that directory is already allowed"); return; }
3231 ensure_roots_file_path();
3232 if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3233 json_header();
3234 printf("{\"ok\":true,\"added\":");
3235 {
3236 buf_t b;
3237 buf_init(&b);
3238 json_str(&b, canon);
3239 printf("%s", buf_str(&b));
3240 buf_free(&b);
3241 }
3242 printf(",\"count\":%d}\n", g_root_count);
3243}
3244
3245static void do_roots_remove(const char *path)
3246{
3247 char canon[PATH_SZ];
3248 int i, j, found = 0;
3249
3250 if (!path || !*path) { json_err(400, "path is required"); return; }
3251 if (canon_path(path, canon, sizeof canon)) {
3252 /* matched below */
3253 } else {
3254 str_copy(canon, sizeof canon, path);
3255 }
3256 for (i = 0; i < g_root_count; i++) {
3257 if (!strcmp(g_roots[i].canonical, canon) ||
3258 !strcmp(g_roots[i].configured, path) ||
3259 path_under_p(canon, g_roots[i].canonical)) {
3260 for (j = i; j + 1 < g_root_count; j++) g_roots[j] = g_roots[j + 1];
3261 g_root_count--;
3262 found = 1;
3263 break;
3264 }
3265 }
3266 if (!found) { json_err(404, "that directory is not in the allowlist"); return; }
3267 ensure_roots_file_path();
3268 if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3269 json_header();
3270 printf("{\"ok\":true,\"removed\":true,\"count\":%d}\n", g_root_count);
3271}
3272
3273static void do_permissions(void)
3274{
3275 int i;
3276 json_header();
3277 printf("{\"ok\":true,\"permissions\":{");
3278 for (i = 0; i < TOOLS_N; i++)
3279 printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3280 g_tool_off[i] ? "false" : "true");
3281 printf("}}\n");
3282}
3283
3284static void do_permissions_set(const char *qs)
3285{
3286 char tool[64], val[16];
3287 int idx;
3288
3289 if (!get_query_val(qs, "tool", tool, sizeof tool)) {
3290 json_err(400, "tool is required");
3291 return;
3292 }
3293 idx = tool_index(tool);
3294 if (idx < 0) { json_err(404, "unknown tool"); return; }
3295 if (!get_query_val(qs, "enabled", val, sizeof val)) {
3296 json_err(400, "enabled is required (true/false)");
3297 return;
3298 }
3299 g_tool_off[idx] = (strcmp(val, "true") == 0 || strcmp(val, "1") == 0) ? 0 : 1;
3300 /* list_allowed_directories is the diagnostic an operator needs when a
3301 * path is refused, so it can never be switched off. */
3302 if (idx == TOOLS_N - 1) g_tool_off[idx] = 0;
3303 ensure_roots_file_path();
3304 if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3305 json_header();
3306 printf("{\"ok\":true,\"tool\":");
3307 {
3308 buf_t b;
3309 buf_init(&b);
3310 json_str(&b, TOOL_NAMES[idx]);
3311 printf("%s", buf_str(&b));
3312 buf_free(&b);
3313 }
3314 printf(",\"enabled\":%s}\n", g_tool_off[idx] ? "false" : "true");
3315}
3316
3317/* The sandbox boundary tester: what an operator types in, the tool sees.
3318 * Reports both forms and the exact reason a path is refused. */
3319static void do_sandbox_test(const char *path)
3320{
3321 char canon[PATH_SZ];
3322 const char *err = NULL;
3323 int allowed = 0;
3324
3325 if (!path || !*path) { json_err(400, "path is required"); return; }
3326 allowed = resolve_allowed(path, canon, sizeof canon, 'r', &err);
3327 if (!allowed) {
3328 /* a write-mode answer is more useful for a path that does not exist */
3329 char wc[PATH_SZ];
3330 const char *werr = NULL;
3331 if (resolve_allowed(path, wc, sizeof wc, 'w', &werr)) {
3332 buf_t b;
3333 json_header();
3334 printf("{\"ok\":true,\"path\":");
3335 buf_init(&b);
3336 json_str(&b, path);
3337 printf("%s,\"allowed\":true,\"mode\":\"write\",\"canonical\":", buf_str(&b));
3338 buf_free(&b);
3339 buf_init(&b);
3340 json_str(&b, wc);
3341 printf("%s}\n", buf_str(&b));
3342 buf_free(&b);
3343 return;
3344 }
3345 }
3346 {
3347 buf_t b;
3348 json_header();
3349 buf_init(&b);
3350 json_str(&b, path);
3351 printf("{\"ok\":true,\"path\":%s,\"allowed\":%s,\"canonical\":",
3352 buf_str(&b), allowed ? "true" : "false");
3353 buf_free(&b);
3354 if (allowed) {
3355 buf_init(&b);
3356 json_str(&b, canon);
3357 printf("%s,\"reason\":\"inside an allowed root\"}\n", buf_str(&b));
3358 buf_free(&b);
3359 } else {
3360 buf_init(&b);
3361 json_str(&b, canon);
3362 printf("%s,\"reason\":", buf_str(&b));
3363 buf_free(&b);
3364 buf_init(&b);
3365 json_str(&b, err ? err : "refused");
3366 printf("%s}\n", buf_str(&b));
3367 buf_free(&b);
3368 }
3369 }
3370}
3371
3372static void do_tools(void)
3373{
3374 int i;
3375 json_header();
3376 printf("{\"ok\":true,\"tools\":[");
3377 for (i = 0; i < TOOLS_N; i++) {
3378 buf_t b;
3379 buf_init(&b);
3380 if (i) buf_putc(&b, ',');
3381 buf_puts(&b, "{\"name\":");
3382 json_str(&b, TOOLS[i].name);
3383 buf_puts(&b, ",\"title\":");
3384 json_str(&b, TOOLS[i].title);
3385 buf_puts(&b, ",\"description\":");
3386 json_str(&b, TOOLS[i].desc);
3387 buf_printf(&b, ",\"read_only\":%s,\"destructive\":%s,\"enabled\":%s}",
3388 TOOLS[i].read_only ? "true" : "false",
3389 TOOLS[i].destructive ? "true" : "false",
3390 g_tool_off[i] ? "false" : "true");
3391 fputs(buf_str(&b), stdout);
3392 buf_free(&b);
3393 }
3394 printf("]}\n");
3395}
3396
3397/* ------------------------------------------------------------------ */
3398/* HTML UI */
3399/* ------------------------------------------------------------------ */
3400
3401/* Expand the two control-byte placeholders from src/ui.html into the bot
3402 * theme macros, so the page and the bot palette can never drift. */
3403static void emit_ui(int embed)
3404{
3405 const char *p = UI_HTML;
3406
3407 while (*p) {
3408 if (*p == '\001') {
3409 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
3410 ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
3411 "</style>", stdout);
3412 p++;
3413 } else if (*p == '\002') {
3414 fputs(SX_BOT_THEME_HANDOFF, stdout);
3415 p++;
3416 } else {
3417 putchar(*p++);
3418 }
3419 }
3420 (void)embed;
3421}
3422
3423static void mode_html(int embed)
3424{
3425 fputs("Content-Type: text/html; charset=utf-8\r\n"
3426 "Cache-Control: no-store\r\n"
3427 "X-Content-Type-Options: nosniff\r\n"
3428 "X-Frame-Options: SAMEORIGIN\r\n"
3429 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
3430 "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
3431 "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
3432 emit_ui(embed);
3433}
3434
3435/* ------------------------------------------------------------------ */
3436/* main */
3437/* ------------------------------------------------------------------ */
3438
3439static void print_help(void)
3440{
3441 printf("%s %s - SCORPIOX BOT allowlisted filesystem MCP connector\n\n"
3442 "modes:\n"
3443 " --meta print plugin discovery metadata and exit\n"
3444 " --mcp serve MCP JSON-RPC 2.0 over stdin/stdout\n"
3445 " (no args) CGI: Allowed Roots & Permissions page + ?action= API\n"
3446 " --version print version\n\n"
3447 "config: %s/roots.json (or FS_ALLOWED_ROOTS, colon-separated)\n"
3448 "tools: ", PLUGIN_ID, PLUGIN_VER, " ~/.scorpiox/connectors/" PLUGIN_ID);
3449 {
3450 int i;
3451 for (i = 0; i < TOOLS_N; i++)
3452 printf("%s%s", i ? ", " : "", TOOLS[i].name);
3453 }
3454 printf("\n");
3455}
3456
3457int main(int argc, char **argv)
3458{
3459 const char *qs;
3460 char action[64];
3461 char path[PATH_SZ];
3462 int i;
3463
3464 /* 1. Discovery metadata - unauthenticated: /plugins and the connector
3465 * router probe every installed binary, and a probe that needs the
3466 * node password is a probe that fails. */
3467 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
3468 fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\","
3469 "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false,"
3470 "\"verified\":\"live\",\"version\":\"" PLUGIN_VER "\"}\n", stdout);
3471 return 0;
3472 }
3473 for (i = 1; i < argc; i++) {
3474 if (!strcmp(argv[i], "--version")) {
3475 printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
3476 return 0;
3477 }
3478 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
3479 print_help();
3480 return 0;
3481 }
3482 }
3483
3484 /* 2. MCP stdio server - the connector mode. No CGI headers, no auth:
3485 * the caller is the node's own MCP router, already trusted. */
3486 if (argc > 1 && !strcmp(argv[1], "--mcp")) {
3487 init_roots();
3488 return mode_mcp();
3489 }
3490
3491 /* 3. CGI modes below are all behind node auth. */
3492 require_node_auth();
3493 init_roots();
3494
3495 qs = getenv("QUERY_STRING");
3496 if (!qs) qs = "";
3497
3498 action[0] = '\0';
3499 path[0] = '\0';
3500 get_query_val(qs, "action", action, sizeof action);
3501 get_query_val(qs, "path", path, sizeof path);
3502
3503 if (action[0] || strstr(qs, "format=json")) {
3504 if (!action[0]) str_copy(action, sizeof action, "status");
3505
3506 if (!strcmp(action, "status")) do_status();
3507 else if (!strcmp(action, "roots")) do_roots();
3508 else if (!strcmp(action, "roots_add")) do_roots_add(path);
3509 else if (!strcmp(action, "roots_remove")) do_roots_remove(path);
3510 else if (!strcmp(action, "permissions")) do_permissions();
3511 else if (!strcmp(action, "permissions_set")) do_permissions_set(qs);
3512 else if (!strcmp(action, "sandbox_test")) do_sandbox_test(path);
3513 else if (!strcmp(action, "tools")) do_tools();
3514 else json_err(400, "unknown action");
3515 return 0;
3516 }
3517
3518 /* 4. Everything else is the page. */
3519 {
3520 int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL;
3521 mode_html(embed);
3522 }
3523 return 0;
3524}