/* * plugin_sqlite - SCORPIOX BOT open-source read-only SQLite explorer plugin * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery * 2. ?action=dbs | ?action=schema&db=... | ?action=query&db=...&sql=... * | ?action=info | ?format=json * -> JSON node API (read-only database access) * 3. GET (default) -> responsive HTML explorer UI * * READ-ONLY BY CONSTRUCTION * - Every database is opened with SQLITE_OPEN_READONLY. * - sqlite3_set_authorizer() permits only SQLITE_SELECT, SQLITE_READ, * SQLITE_RECURSIVE, SQLITE_FUNCTION and a small whitelist of read-only * PRAGMAs. INSERT / UPDATE / DELETE / CREATE / DROP / ALTER / ATTACH / * DETACH / TRANSACTION / REINDEX / VACUUM are all refused by the engine * before they can reach the file. * - Only .db / .sqlite / .sqlite3 regular files under /workspace, * /codebases, $HOME (or $SQLITE_ALLOWED_ROOT) are browsable. Paths are * resolved and verified - '..' traversal, SQLite URI filenames and system * paths such as /etc/passwd are rejected. * - Result rows are capped at 500 and each statement is bounded by a * sqlite3_progress_handler ceiling (~2 s). * * Vendors the public-domain SQLite amalgamation (vendor/sqlite3.{c,h}) and * compiles it with -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_THREADSAFE=0, so the * Linux (glibc + musl static), macOS and Windows binaries need no sqlite3 CLI, * no libsqlite3.so and no sqlite3.dll. * * Zero dependencies beyond libc. MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 #elif !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include /* MinGW/MSVC CRT starts stdout in TEXT mode, which rewrites every \n we emit * into \r\n. A CGI header block must end with exactly CRLF CRLF; text mode * turns "\r\n\r\n" into "\r\r\n\r\r\n", scorpiox-server cannot find the * header/body separator, and the whole reply (headers included) is served as a * body with Content-Type: text/html. Force binary stdio before main() runs — * the same constructor scorpiox-bot-api handlers use (sx_shell.h). */ __attribute__((constructor)) static void sx_plugin_binary_stdio(void) { _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); } # include # define SX_STAT struct _stat64 # define sx_stat(p,s) _stat64((p),(s)) # define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG) # define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) #else # include # include # include # include # define SX_STAT struct stat # define sx_stat(p,s) stat((p),(s)) # define SX_ISREG(m) S_ISREG(m) # define SX_ISDIR(m) S_ISDIR(m) #endif /* Relative include so the tree also builds without -I flags (the marketplace * release CLI compiles every src and vendor C file in one command). */ #include "../vendor/sqlite3.h" #include "bot_theme_plugin.h" #define PLUGIN_SLUG "sqlite" #define PLUGIN_ID "plugin_sqlite" #define PLUGIN_VER "1.0.3" #define MAX_NAME 256 /* glibc's fortified realpath() demands a PATH_MAX-sized buffer. */ #define MAX_PATHQ 4096 #define MAX_DBS 200 #define MAX_TABLES 200 #define MAX_COLS 128 #define MAX_SQL 16384 #define MAX_ROWS 500 #define MAX_SCAN_ENTRIES 60000 #define MAX_SCAN_DEPTH 4 #define STMT_BUDGET_MS 2000 /* * Per-root entry allowance for the discovery walk. $SQLITE_SCAN_BUDGET lowers * it so tests can prove the truncation path on a tiny fixture; a value that is * not a positive integer is ignored rather than trusted. */ static int scan_budget(void) { static int cached = -1; if (cached < 0) { const char *e = getenv("SQLITE_SCAN_BUDGET"); long v = (e && *e) ? strtol(e, NULL, 10) : 0; cached = (v > 0 && v <= MAX_SCAN_ENTRIES) ? (int)v : MAX_SCAN_ENTRIES; } return cached; } /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } /* Read one parameter (decoded) out of a query or form string. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } /* JSON string literal; drops control characters rather than escaping them. */ static void json_str(const char *s) { fputc('"', stdout); if (s) { for (; *s; s++) { unsigned char c = (unsigned char)*s; if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((int)c, stdout); } else if (c == '\n') fputs("\\n", stdout); else if (c == '\r') fputs("\\r", stdout); else if (c == '\t') fputs("\\t", stdout); else if (c >= 0x20) fputc((int)c, stdout); } } fputc('"', stdout); } static void copy_str(char *dst, size_t dstsz, const char *src) { size_t n; if (!dst || dstsz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= dstsz) n = dstsz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static void utc_now(char *buf, size_t sz) { time_t t = time(NULL); struct tm tmv; #if defined(_WIN32) struct tm *p = gmtime(&t); if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv); #else gmtime_r(&t, &tmv); #endif strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } static long long now_ms(void) { #if defined(_WIN32) return (long long)GetTickCount64(); #else struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL; #endif } static long node_pid(void) { #if defined(_WIN32) return (long)GetCurrentProcessId(); #else return (long)getpid(); #endif } static const char *platform_name(void) { #if defined(_WIN32) return "windows"; #elif defined(__APPLE__) return "macos"; #else return "linux"; #endif } /* Case-insensitive prefix compare, portable across glibc / macOS / MinGW. */ static int ci_prefix(const char *s, const char *pre) { while (*pre) { if (!*s) return 0; if (tolower((unsigned char)*s) != tolower((unsigned char)*pre)) return 0; s++; pre++; } return 1; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ /* * Everything except --meta discovery must prove it knows the node password. * Accepted exactly like the rest of the node API: X-Bot-Password (what * bot-web proxies with), Authorization: Bearer, and ?pwd= (what the plugin * iframe appends). With BOT_PASSWORD unset the plugin is a deliberate no-op * so it can be exercised from a shell during development. */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256]; const char *qs; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (ci_prefix(auth, "Bearer ")) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Path discipline */ /* ------------------------------------------------------------------ */ typedef struct { char path[MAX_PATHQ]; char label[32]; int exists; } sx_root_t; /* * The allowlist. $SQLITE_ALLOWED_ROOT is honoured first so a node owner can * point the plugin at a specific directory, and the three conventional roots * follow. Nothing outside these is ever opened, no matter what the query says. */ static int collect_roots(sx_root_t *out, int max) { int n = 0; const char *extra = getenv("SQLITE_ALLOWED_ROOT"); const char *home = getenv("HOME"); #if defined(_WIN32) if (!home || !*home) home = getenv("USERPROFILE"); #endif SX_STAT st; memset(out, 0, (size_t)max * sizeof(out[0])); if (extra && *extra && n < max) { copy_str(out[n].path, sizeof(out[n].path), extra); copy_str(out[n].label, sizeof(out[n].label), "allowed"); out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode)); n++; } #if !defined(_WIN32) if (n < max) { copy_str(out[n].path, sizeof(out[n].path), "/workspace"); copy_str(out[n].label, sizeof(out[n].label), "workspace"); out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode)); n++; } if (n < max) { copy_str(out[n].path, sizeof(out[n].path), "/codebases"); copy_str(out[n].label, sizeof(out[n].label), "codebases"); out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode)); n++; } #endif if (home && *home && n < max) { copy_str(out[n].path, sizeof(out[n].path), home); copy_str(out[n].label, sizeof(out[n].label), "home"); out[n].exists = (sx_stat(out[n].path, &st) == 0 && SX_ISDIR(st.st_mode)); n++; } return n; } static int has_dotdot(const char *p) { const char *s = p; while (s && *s) { if (s[0] == '.' && s[1] == '.' && (s == p || s[-1] == '/' || s[-1] == '\\') && (s[2] == '\0' || s[2] == '/' || s[2] == '\\')) return 1; s = strchr(s, '/'); if (!s) break; s++; } return 0; } /* Suffix gate: .db / .sqlite / .sqlite3 / .db3 (case-insensitive). */ static int has_db_suffix(const char *p) { size_t n = strlen(p); const char *s; if (n < 4) return 0; for (s = p + n; s > p && s[-1] != '/' && s[-1] != '\\'; s--) { if (*s == '.') { if (ci_prefix(s, ".db") || ci_prefix(s, ".db3") || ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3")) return 1; return 0; } } return 0; } /* * Resolve and validate a database path. * 1 allowed, canonical path written to out * 0 not allowed (outside the roots / traversal / not a db file) * -1 allowed location but the file is absent */ static int resolve_db_path(const char *req, char *out, size_t outsz) { sx_root_t roots[8]; int nroots, i; char canon[MAX_PATHQ]; SX_STAT st; size_t i2; if (!req || !*req) return 0; if (strlen(req) >= MAX_PATHQ) return 0; /* SQLite URI filenames can smuggle a different file past a naive check. */ if (ci_prefix(req, "file:")) return 0; if (strstr(req, "://")) return 0; if (strstr(req, "?") || strstr(req, "#")) return 0; if (has_dotdot(req)) return 0; if (!has_db_suffix(req)) return 0; /* An absolute request must resolve to itself; relative ones are joined to * $HOME so a bare "app.db" still works from the UI. */ if (req[0] == '/' || (isalpha((unsigned char)req[0]) && req[1] == ':')) { copy_str(canon, sizeof(canon), req); } else { const char *home = getenv("HOME"); #if defined(_WIN32) if (!home || !*home) home = getenv("USERPROFILE"); #endif if (!home || !*home) return 0; snprintf(canon, sizeof(canon), "%s/%s", home, req); } /* Normalise to an absolute, symlink-free path when the platform can. A * the leaf does not exist we resolve its parent instead and remember. */ { #if defined(_WIN32) char tmp[MAX_PATHQ]; if (_fullpath(tmp, canon, sizeof(tmp)) != NULL) copy_str(canon, sizeof(canon), tmp); else return 0; #else char tmp[MAX_PATHQ]; if (realpath(canon, tmp) != NULL) { copy_str(canon, sizeof(canon), tmp); } else if (errno == ENOENT) { char dir[MAX_PATHQ], parent[MAX_PATHQ], rp[MAX_PATHQ]; char *slash; copy_str(dir, sizeof dir, canon); slash = strrchr(dir, '/'); if (!slash) return 0; *slash = '\0'; copy_str(parent, sizeof parent, slash + 1); if (realpath(dir, rp) != NULL) { /* Bounded manual join: snprintf's "%s/%s" over two * PATH_MAX-sized buffers trips -Wformat-truncation. */ size_t rl = strlen(rp); canon[0] = '\0'; if (rl + strlen(parent) + 2 < sizeof canon) { memcpy(canon, rp, rl); canon[rl] = '/'; copy_str(canon + rl + 1, sizeof(canon) - rl - 1, parent); } else { return 0; } } } else { return 0; } #endif } nroots = collect_roots(roots, 8); for (i = 0; i < nroots; i++) { size_t rl; if (!roots[i].exists) continue; rl = strlen(roots[i].path); while (rl > 1 && roots[i].path[rl - 1] == '/') rl--; if (strncmp(canon, roots[i].path, rl) != 0) continue; if (canon[rl] != '/' && canon[rl] != '\0') continue; if (sx_stat(canon, &st) != 0) return -1; if (!SX_ISREG(st.st_mode)) return 0; copy_str(out, outsz, canon); return 1; } /* Not under any root. Collapse any doubled separators first so the check * above cannot be defeated by "//workspace//..//". */ for (i2 = 0; canon[i2]; i2++) if (canon[i2] == '\\') canon[i2] = '/'; return 0; } /* ------------------------------------------------------------------ */ /* SQLite: read-only open, authorizer, bounded execution */ /* ------------------------------------------------------------------ */ typedef struct { long long deadline_ms; int aborted; } sx_budget_t; static int progress_cb(void *p) { sx_budget_t *b = (sx_budget_t *)p; if (!b) return 0; if (now_ms() > b->deadline_ms) { b->aborted = 1; return 1; } return 0; } /* Read-only schema pragmas we are willing to run, and only these. */ static int pragma_allowed(const char *name) { static const char *ok[] = { /* Pure readers only. Settable pragmas (journal_mode, encoding, * auto_vacuum, user_version, application_id, schema_version) are * deliberately absent: on a read-only handle they cannot write anyway, * but refusing them keeps the contract honest and the error explicit. */ "table_info", "table_xinfo", "index_list", "index_info", "index_xinfo", "foreign_key_list", "database_list", "collation_list", "page_count", "page_size", "freelist_count", "compile_options", "quick_check", "integrity_check", "table_list", NULL }; int i; if (!name) return 0; for (i = 0; ok[i]; i++) if (ci_prefix(name, ok[i]) && (name[strlen(ok[i])] == '\0')) return 1; return 0; } /* * SQLITE_DENY on everything not explicitly allowed. Note that this fires for * the *compiled* statement, so a statement that tries to write is refused * before execution even on a writable file - defence in depth on top of * SQLITE_OPEN_READONLY. */ static int authorizer_cb(void *ud, int action, const char *a1, const char *a2, const char *dbname, const char *trigger) { (void)ud; (void)a2; (void)dbname; (void)trigger; switch (action) { case SQLITE_SELECT: case SQLITE_READ: case SQLITE_RECURSIVE: return SQLITE_OK; case SQLITE_FUNCTION: /* Extension loading is off by default and we never enable it, but a * binary built without -DSQLITE_OMIT_LOAD_EXTENSION could still reach * the function entry point. Name it and refuse it. */ if (a2 && ci_prefix(a2, "load_extension") && !a2[14]) return SQLITE_DENY; return SQLITE_OK; case SQLITE_PRAGMA: return pragma_allowed(a1) ? SQLITE_OK : SQLITE_DENY; default: return SQLITE_DENY; } } static sqlite3 *open_ro(const char *path, int *errout) { sqlite3 *db = NULL; int rc; if (errout) *errout = 0; /* READONLY plus no URI handling: the path has already been canonicalised * by resolve_db_path(), and URI filenames would re-introduce a second * filename parser under our feet. */ rc = sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL); if (rc != SQLITE_OK) { if (db) sqlite3_close(db); if (errout) *errout = rc; return NULL; } sqlite3_extended_result_codes(db, 1); sqlite3_limit(db, SQLITE_LIMIT_ATTACHED, 0); sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000); sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, MAX_SQL); sqlite3_busy_timeout(db, 500); return db; } /* Confirm the file really is a SQLite database before we report anything. */ static int is_database(sqlite3 *db) { sqlite3_stmt *st = NULL; int rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM sqlite_master", -1, &st, NULL); if (rc != SQLITE_OK) { if (st) sqlite3_finalize(st); return 0; } rc = sqlite3_step(st); sqlite3_finalize(st); return rc == SQLITE_ROW || rc == SQLITE_DONE; } /* ------------------------------------------------------------------ */ /* JSON output helpers */ /* ------------------------------------------------------------------ */ static void json_header(void) { /* Deliberately no Content-Length - the server owns framing. */ fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void json_error(const char *code, const char *detail) { json_header(); fputs("{\"ok\":false,\"error\":", stdout); json_str(code); if (detail && *detail) { fputs(",\"detail\":", stdout); json_str(detail); } fputs("}\n", stdout); } /* Emit one typed result value. BLOBs become a bounded hex preview. */ static void emit_value(sqlite3_stmt *st, int col) { switch (sqlite3_column_type(st, col)) { case SQLITE_INTEGER: printf("%lld", (long long)sqlite3_column_int64(st, col)); break; case SQLITE_FLOAT: { double d = sqlite3_column_double(st, col); if (d != d || d > 1.7976931348623157e308 || d < -1.7976931348623157e308) { /* NaN / Inf are not JSON numbers - describe them instead. */ char buf[32]; if (d != d) copy_str(buf, sizeof buf, "NaN"); else if (d > 0) copy_str(buf, sizeof buf, "Infinity"); else copy_str(buf, sizeof buf, "-Infinity"); json_str(buf); } else { printf("%.15g", d); } break; } case SQLITE_TEXT: { const unsigned char *t = sqlite3_column_text(st, col); json_str(t ? (const char *)t : ""); break; } case SQLITE_BLOB: { const unsigned char *b = (const unsigned char *)sqlite3_column_blob(st, col); int n = sqlite3_column_bytes(st, col), i, lim = n > 48 ? 48 : n; printf("{\"blob_bytes\":%d,\"hex\":\"", n); for (i = 0; i < lim; i++) printf("%02x", b[i]); fputs(n > lim ? "...\"}" : "\"}", stdout); break; } default: fputs("null", stdout); break; } } static const char *value_type_name(sqlite3_stmt *st, int col) { switch (sqlite3_column_type(st, col)) { case SQLITE_INTEGER: return "int"; case SQLITE_FLOAT: return "float"; case SQLITE_TEXT: return "text"; case SQLITE_BLOB: return "blob"; default: return "null"; } } /* Quote an identifier for interpolation into SQL (never for user values). */ static void quote_ident(const char *in, char *out, size_t outsz) { size_t o = 0; if (outsz < 3) { if (outsz) out[0] = '\0'; return; } out[o++] = '"'; for (; in && *in && o + 3 < outsz; in++) { if (*in == '"') out[o++] = '"'; out[o++] = *in; } out[o++] = '"'; out[o] = '\0'; } /* ------------------------------------------------------------------ */ /* Database discovery */ /* ------------------------------------------------------------------ */ typedef struct { char path[MAX_PATHQ]; char root[32]; long long size; long long mtime; } sx_db_t; static int db_suffix_ok(const char *name) { size_t n = strlen(name); const char *s = name + n; while (s > name && *s != '.') s--; if (*s != '.') return 0; return ci_prefix(s, ".db") || ci_prefix(s, ".db3") || ci_prefix(s, ".sqlite") || ci_prefix(s, ".sqlite3"); } static int skip_name(const char *n) { if (!n || !*n) return 1; if (n[0] == '.' && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0'))) return 1; /* Skip the obvious noise directories; they are never databases anyway. */ if (strcmp(n, ".git") == 0 || strcmp(n, "node_modules") == 0 || strcmp(n, "__pycache__") == 0 || strcmp(n, "venv") == 0 || strcmp(n, ".venv") == 0 || strcmp(n, "bin") == 0 || strcmp(n, "obj") == 0 || strcmp(n, "target") == 0) return 1; return 0; } static int walk_dbs(const char *dir, const char *rootlabel, int depth, sx_db_t *out, int max, int *count, int *visited) { if (depth > MAX_SCAN_DEPTH || *count >= max || *visited > scan_budget()) return 0; #if defined(_WIN32) { WIN32_FIND_DATAA fd; HANDLE h; char pat[MAX_PATHQ]; snprintf(pat, sizeof(pat), "%s\\*", dir); h = FindFirstFileA(pat, &fd); if (h == INVALID_HANDLE_VALUE) return 0; do { char full[MAX_PATHQ]; SX_STAT st; if (skip_name(fd.cFileName)) continue; (*visited)++; if (*visited > scan_budget() || *count >= max) break; snprintf(full, sizeof(full), "%s\\%s", dir, fd.cFileName); if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { walk_dbs(full, rootlabel, depth + 1, out, max, count, visited); } else if (db_suffix_ok(fd.cFileName) && sx_stat(full, &st) == 0 && SX_ISREG(st.st_mode)) { copy_str(out[*count].path, sizeof(out[*count].path), full); copy_str(out[*count].root, sizeof(out[*count].root), rootlabel); out[*count].size = (long long)st.st_size; out[*count].mtime = (long long)st.st_mtime; (*count)++; } } while (FindNextFileA(h, &fd)); FindClose(h); } #else { DIR *d = opendir(dir); struct dirent *e; if (!d) return 0; while ((e = readdir(d)) != NULL) { char full[MAX_PATHQ]; SX_STAT st; if (skip_name(e->d_name)) continue; (*visited)++; if (*visited > scan_budget() || *count >= max) break; snprintf(full, sizeof(full), "%s/%s", dir, e->d_name); if (lstat(full, &st) != 0) continue; if (S_ISDIR(st.st_mode)) { /* Never follow a symlinked directory: that is how a walk * escapes the allowlisted root. */ if (S_ISLNK(st.st_mode)) continue; walk_dbs(full, rootlabel, depth + 1, out, max, count, visited); } else if (S_ISREG(st.st_mode) && db_suffix_ok(e->d_name)) { copy_str(out[*count].path, sizeof(out[*count].path), full); copy_str(out[*count].root, sizeof(out[*count].root), rootlabel); out[*count].size = (long long)st.st_size; out[*count].mtime = (long long)st.st_mtime; (*count)++; } } closedir(d); } #endif return 0; } /* ------------------------------------------------------------------ */ /* Actions */ /* ------------------------------------------------------------------ */ static void action_dbs(void) { sx_root_t roots[8]; sx_db_t dbs[MAX_DBS]; int nroots, i, count = 0; int total_visited = 0; int root_visited[8]; int root_count[8]; int root_truncated[8]; nroots = collect_roots(roots, 8); memset(dbs, 0, sizeof(dbs)); memset(root_visited, 0, sizeof(root_visited)); memset(root_count, 0, sizeof(root_count)); memset(root_truncated, 0, sizeof(root_truncated)); /* Each root gets its own entry budget. A single global counter lets one big * tree (/codebases, a monorepo) exhaust the allowance before the walk ever * reaches $HOME, so databases sitting in the user's home directory were * undiscoverable - the UI reported "1 database" on a node that had three. * The per-root counts also let the UI name the root that was truncated * instead of silently showing a short list. */ for (i = 0; i < nroots && count < MAX_DBS; i++) { int before = count; int visited = 0; if (!roots[i].exists) continue; walk_dbs(roots[i].path, roots[i].label, 0, dbs, MAX_DBS, &count, &visited); root_visited[i] = visited; root_count[i] = count - before; root_truncated[i] = (visited > scan_budget() || count >= MAX_DBS); total_visited += visited; } json_header(); fputs("{\"ok\":true,\"action\":\"dbs\",\"plugin\":\"" PLUGIN_ID "\"", stdout); fputs(",\"roots\":[", stdout); for (i = 0; i < nroots; i++) { if (i) fputc(',', stdout); fputs("{\"label\":", stdout); json_str(roots[i].label); fputs(",\"path\":", stdout); json_str(roots[i].path); printf(",\"exists\":%s,\"dbs\":%d,\"scanned_entries\":%d,\"truncated\":%s}", roots[i].exists ? "true" : "false", root_count[i], root_visited[i], root_truncated[i] ? "true" : "false"); } fputs("]", stdout); printf(",\"count\":%d,\"scanned_entries\":%d,\"max_depth\":%d,\"max_scan_entries\":%d," "\"dbs\":[", count, total_visited, MAX_SCAN_DEPTH, scan_budget()); for (i = 0; i < count; i++) { char utc[40]; time_t t = (time_t)dbs[i].mtime; struct tm tmv; #if defined(_WIN32) struct tm *p = gmtime(&t); if (p) tmv = *p; else memset(&tmv, 0, sizeof tmv); #else gmtime_r(&t, &tmv); #endif strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv); if (i) fputc(',', stdout); fputs("{\"path\":", stdout); json_str(dbs[i].path); fputs(",\"root\":", stdout); json_str(dbs[i].root); printf(",\"bytes\":%lld,\"mtime\":", dbs[i].size); json_str(utc); fputc('}', stdout); } fputs("],\"readonly\":true}\n", stdout); } /* Count rows in one table, bounded by the statement budget. */ static int table_rows(sqlite3 *db, const char *table, long long *out) { sqlite3_stmt *st = NULL; char sql[MAX_NAME * 2 + 64]; char q[MAX_NAME * 2 + 4]; int rc; quote_ident(table, q, sizeof q); snprintf(sql, sizeof sql, "SELECT count(*) FROM %s", q); rc = sqlite3_prepare_v2(db, sql, -1, &st, NULL); if (rc != SQLITE_OK) { if (st) sqlite3_finalize(st); return rc; } rc = sqlite3_step(st); if (rc == SQLITE_ROW) { *out = (long long)sqlite3_column_int64(st, 0); rc = SQLITE_OK; } else *out = -1; sqlite3_finalize(st); return rc; } static void action_schema(const char *dbreq) { char path[MAX_PATHQ]; char errbuf[512]; sqlite3 *db; sqlite3_stmt *st = NULL; sx_budget_t budget; int r, rc, tcount = 0; memset(path, 0, sizeof path); r = resolve_db_path(dbreq, path, sizeof path); if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; } if (r < 0) { json_error("not_found", "database file does not exist"); return; } db = open_ro(path, &rc); if (!db) { snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc)); json_error("open_failed", errbuf); return; } if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; } sqlite3_set_authorizer(db, authorizer_cb, NULL); budget.deadline_ms = now_ms() + STMT_BUDGET_MS; budget.aborted = 0; sqlite3_progress_handler(db, 20000, progress_cb, &budget); json_header(); fputs("{\"ok\":true,\"action\":\"schema\",\"readonly\":true,\"db\":", stdout); json_str(path); fputs(",\"tables\":[", stdout); rc = sqlite3_prepare_v2(db, "SELECT name, type FROM sqlite_master " "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name", -1, &st, NULL); if (rc != SQLITE_OK) { sqlite3_close(db); /* Header already emitted, so finish the document with an error field. */ fputs("],\"error\":\"schema_query_failed\"}\n", stdout); return; } while (sqlite3_step(st) == SQLITE_ROW && tcount < MAX_TABLES) { const char *name = (const char *)sqlite3_column_text(st, 0); const char *kind = (const char *)sqlite3_column_text(st, 1); long long rows = -1; sqlite3_stmt *cs = NULL; char q[MAX_NAME * 2 + 4]; int ci = 0; char sql[MAX_NAME * 2 + 96]; if (!name) continue; if (tcount) fputc(',', stdout); fputs("{\"name\":", stdout); json_str(name); fputs(",\"type\":", stdout); json_str(kind ? kind : "table"); if (table_rows(db, name, &rows) == SQLITE_OK) printf(",\"rows\":%lld", rows); else fputs(",\"rows\":null", stdout); quote_ident(name, q, sizeof q); fputs(",\"columns\":[", stdout); snprintf(sql, sizeof sql, "PRAGMA table_info(%s)", q); if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) { while (sqlite3_step(cs) == SQLITE_ROW) { const char *cn = (const char *)sqlite3_column_text(cs, 1); const char *ct = (const char *)sqlite3_column_text(cs, 2); int nn = sqlite3_column_int(cs, 3); int pk = sqlite3_column_int(cs, 5); if (ci++) fputc(',', stdout); fputs("{\"name\":", stdout); json_str(cn ? cn : ""); fputs(",\"type\":", stdout); json_str(ct ? ct : ""); printf(",\"notnull\":%s,\"pk\":%d}", nn ? "true" : "false", pk); } } sqlite3_finalize(cs); fputs("]", stdout); ci = 0; fputs(",\"indexes\":[", stdout); snprintf(sql, sizeof sql, "PRAGMA index_list(%s)", q); if (sqlite3_prepare_v2(db, sql, -1, &cs, NULL) == SQLITE_OK) { while (sqlite3_step(cs) == SQLITE_ROW) { const char *in = (const char *)sqlite3_column_text(cs, 1); int uniq = sqlite3_column_int(cs, 2); if (ci++) fputc(',', stdout); fputs("{\"name\":", stdout); json_str(in ? in : ""); printf(",\"unique\":%s}", uniq ? "true" : "false"); } } sqlite3_finalize(cs); fputs("]}", stdout); tcount++; } sqlite3_finalize(st); printf("],\"table_count\":%d,\"truncated\":%s,\"budget_ms\":%d}\n", tcount, tcount >= MAX_TABLES ? "true" : "false", STMT_BUDGET_MS); sqlite3_close(db); } /* * First keyword of the statement. The authorizer is the real gate; this check * only produces a friendlier error than "not authorized". */ static const char *first_keyword(const char *sql, char *out, size_t outsz) { size_t i = 0; while (*sql && isspace((unsigned char)*sql)) sql++; while (*sql && (isalnum((unsigned char)*sql) || *sql == '_') && i + 1 < outsz) out[i++] = (char)tolower((unsigned char)*sql++); out[i] = '\0'; return out; } static int statement_allowed_shape(const char *kw) { return strcmp(kw, "select") == 0 || strcmp(kw, "with") == 0 || strcmp(kw, "pragma") == 0 || strcmp(kw, "explain") == 0 || strcmp(kw, "values") == 0; } static void action_query(const char *dbreq, const char *sql) { char path[MAX_PATHQ]; char errbuf[512]; char kw[32]; sqlite3 *db; sqlite3_stmt *st = NULL; sx_budget_t budget; int r, rc, ncols, nrows = 0, truncated = 0, i; char types[MAX_COLS][8]; const char *tail = NULL; long long t0, t1; if (!sql || !*sql) { json_error("missing_sql", "pass ?sql=SELECT ... or POST sql=..."); return; } if (strlen(sql) >= MAX_SQL) { json_error("sql_too_long", "statement exceeds the SQL length limit"); return; } r = resolve_db_path(dbreq, path, sizeof path); if (r == 0) { json_error("forbidden_path", "path outside the allowlisted roots or not a database file"); return; } if (r < 0) { json_error("not_found", "database file does not exist"); return; } first_keyword(sql, kw, sizeof kw); if (!statement_allowed_shape(kw)) { json_error("read_only", "only SELECT / WITH / PRAGMA / EXPLAIN statements are accepted"); return; } db = open_ro(path, &rc); if (!db) { snprintf(errbuf, sizeof errbuf, "cannot open database (%s)", sqlite3_errstr(rc)); json_error("open_failed", errbuf); return; } if (!is_database(db)) { sqlite3_close(db); json_error("not_a_database", "file is not a SQLite database"); return; } sqlite3_set_authorizer(db, authorizer_cb, NULL); budget.deadline_ms = now_ms() + STMT_BUDGET_MS; budget.aborted = 0; sqlite3_progress_handler(db, 20000, progress_cb, &budget); t0 = now_ms(); rc = sqlite3_prepare_v2(db, sql, -1, &st, &tail); if (rc != SQLITE_OK) { snprintf(errbuf, sizeof errbuf, "%s", sqlite3_errmsg(db)); sqlite3_close(db); json_error("sql_error", errbuf); return; } /* Reject stacked statements: prepare() stops after the first one and the * tail would otherwise be silently dropped. */ while (tail && *tail && isspace((unsigned char)*tail)) tail++; if (tail && *tail) { sqlite3_finalize(st); sqlite3_close(db); json_error("multiple_statements", "submit one statement at a time"); return; } ncols = sqlite3_column_count(st); json_header(); fputs("{\"ok\":true,\"action\":\"query\",\"readonly\":true,\"db\":", stdout); json_str(path); printf(",\"columns\":["); for (i = 0; i < ncols; i++) { const char *cn = sqlite3_column_name(st, i); const char *dl = sqlite3_column_decltype(st, i); if (i) fputc(',', stdout); fputs("{\"name\":", stdout); json_str(cn ? cn : ""); fputs(",\"decl\":", stdout); json_str(dl ? dl : ""); fputc('}', stdout); } fputs("],\"rows\":[", stdout); memset(types, 0, sizeof types); while ((rc = sqlite3_step(st)) == SQLITE_ROW) { if (nrows >= MAX_ROWS) { truncated = 1; break; } if (nrows) fputc(',', stdout); fputc('[', stdout); for (i = 0; i < ncols; i++) { if (i) fputc(',', stdout); emit_value(st, i); /* Column type is only meaningful while a row is positioned, so * remember the first row's types for the summary block. */ if (nrows == 0 && i < MAX_COLS) copy_str(types[i], sizeof types[i], value_type_name(st, i)); } fputc(']', stdout); nrows++; } if (rc == SQLITE_INTERRUPT || budget.aborted) { /* Budget hit mid-scan: keep what we streamed and say so. */ truncated = 1; } else if (rc != SQLITE_ROW && rc != SQLITE_DONE) { const char *m = sqlite3_errmsg(db); fputs("],\"error\":", stdout); json_str(m ? m : "statement failed"); printf(",\"aborted\":%s}\n", budget.aborted ? "true" : "false"); sqlite3_finalize(st); sqlite3_close(db); return; } t1 = now_ms(); printf("],\"row_count\":%d,\"truncated\":%s,\"limit\":%d,\"ms\":%lld," "\"aborted\":%s,\"types\":[", nrows, truncated ? "true" : "false", MAX_ROWS, t1 - t0, budget.aborted ? "true" : "false"); for (i = 0; i < ncols && nrows > 0 && i < MAX_COLS; i++) { if (i) fputc(',', stdout); json_str(types[i]); } fputs("]}\n", stdout); sqlite3_finalize(st); sqlite3_close(db); } static void action_info(void) { char utc[40]; utc_now(utc, sizeof utc); json_header(); fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); json_str(platform_name()); fputs(",\"sqlite\":", stdout); json_str(sqlite3_libversion()); printf(",\"pid\":%ld,\"utc\":", node_pid()); json_str(utc); fputs(",\"node_auth\":", stdout); { const char *np = getenv("BOT_PASSWORD"); fputs((np && *np) ? "true" : "false", stdout); } fputs(",\"readonly\":true,\"zero_network\":true,\"threadsafe\":0," "\"load_extension\":false," "\"max_rows\":", stdout); printf("%d", MAX_ROWS); fputs(",\"budget_ms\":", stdout); printf("%d", STMT_BUDGET_MS); fputs(",\"allowed_roots\":[\"allowed\",\"workspace\",\"codebases\",\"home\"]," "\"actions\":[\"dbs\",\"schema\",\"query\",\"info\"]}\n", stdout); } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ static int mode_html(int embed) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); fputs("\n" "" "sqlite", stdout); fputs(SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "", stdout); fputs("
", stdout); if (!embed) { fputs("", stdout); } fputs("

sqlite

" "read-only" "—" "" "" "
", stdout); fputs("

Database

" "
" "
" "
" "
Only .db / .sqlite / .sqlite3 files under the " "allowlisted roots are listed.
" "
", stdout); fputs("

Tables

" "
Select a database.
", stdout); fputs("

SQL

" "" "
" "" "" "" "" "Ctrl+Enter to run" "
", stdout); fputs("

Results

" "
" "
" "
No results yet.
", stdout); fputs("
", stdout); /* ---------------- client ---------------- */ fputs("\n", stdout); return 0; } /* ------------------------------------------------------------------ */ /* Main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64], db[512], sqlbuf[MAX_SQL], format[16]; int want_json = 0, embed = 0; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { puts("{\"name\":\"sqlite\",\"desc\":\"SQLite viewer\"}"); return 0; } if (argc > 1 && strcmp(argv[1], "--version") == 0) { printf("%s %s (sqlite %s)\n", PLUGIN_ID, PLUGIN_VER, sqlite3_libversion()); return 0; } if (argc > 1 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) { fputs("usage: " PLUGIN_ID " [--meta|--version|--help]\n" "\n" "Run as a CGI-style executable. Modes:\n" " --meta / SX_PLUGIN_META=1 discovery JSON\n" " ?action=dbs list databases under the allowed roots\n" " ?action=schema&db= tables, columns, indexes, row counts\n" " ?action=query&db=&sql=