/* * plugin_gitstat - SCORPIOX BOT open-source local git repository status board * * One clean-room C99 binary, three modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=repos|repo|fetch / ?format=json / POST -> JSON node API * 3. GET (default) -> responsive HTML board * * It walks a fixed set of allowlisted roots (never beyond them), finds every * working tree that has a .git directory or a .git worktree file, and asks git * about each one through argv-only child processes (no shell, ever): * * git -C status --porcelain=v2 --branch --untracked-files=normal * git -C log -1 --format=%H%x09%ct%x09%s * git -C stash list --format=%gd * * From that it derives branch, dirty file count, ahead/behind upstream, stash * count, detached / no-upstream / unborn states and the last commit. Fetching * from a remote is the ONLY write-ish operation and it stays off until the node * operator sets GITSTAT_ALLOW_FETCH=1; even then it is `git fetch --prune` with * a 30 s timeout, and GIT_TERMINAL_PROMPT=0 plus an empty GIT_ASKPASS so a * credential prompt can never hang the node. * * Remote URLs are stripped of any userinfo before they are printed, so a repo * whose origin is https://user:token@host/x.git never leaks the token into the * dashboard, the JSON API or the bot's logs. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must be the very first thing on Windows: CreateProcessA/GetFileAttributesA * and the pipe helpers are gated on _WIN32_WINNT, and MinGW defaults to 0x502. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include #else # include # include # include # include # include # include # include # include #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "gitstat" #define PLUGIN_ID "plugin_gitstat" #define PLUGIN_VER "1.0.0" #define PLUGIN_NAME "git" #define PLUGIN_DESC "Repo status" #define MAX_REPOS 1200 #define MAX_ROOT_ENTRIES 20000 #define MAX_DEPTH 4 #define MAX_ROOTS 8 #define MAX_CHANGED 500 #define MAX_COMMITS 20 #define OUT_CAP (512 * 1024) #define FETCH_TIMEOUT_S 30 #define GIT_TIMEOUT_S 20 /* ------------------------------------------------------------------ */ /* Buffers */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t len; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->cap = 4096; b->len = 0; b->p = (char *)malloc(b->cap); if (b->p) b->p[0] = '\0'; } static void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->len = b->cap = 0; } static void buf_add(buf_t *b, const char *s, size_t n) { if (!b->p) return; if (b->len + n + 1 > b->cap) { size_t nc = b->cap; char *np; while (nc < b->len + n + 1) nc *= 2; np = (char *)realloc(b->p, nc); if (!np) return; b->p = np; b->cap = nc; } memcpy(b->p + b->len, s, n); b->len += n; b->p[b->len] = '\0'; } static void buf_puts(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } static void buf_printf(buf_t *b, const char *fmt, ...) { char tmp[2048]; va_list ap; int n; va_start(ap, fmt); n = vsnprintf(tmp, sizeof(tmp), fmt, ap); va_end(ap); if (n < 0) return; if ((size_t)n < sizeof(tmp)) { buf_add(b, tmp, (size_t)n); } else { char *big = (char *)malloc((size_t)n + 1); if (!big) return; va_start(ap, fmt); vsnprintf(big, (size_t)n + 1, fmt, ap); va_end(ap); buf_add(b, big, (size_t)n); free(big); } } static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } /* JSON string escaper. Also the last line of defence against a remote URL * carrying something that would break the document. */ static void json_str(buf_t *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); buf_add(b, "\"", 1); while (*p) { switch (*p) { case '"': buf_add(b, "\\\"", 2); break; case '\\': buf_add(b, "\\\\", 2); break; case '\n': buf_add(b, "\\n", 2); break; case '\r': buf_add(b, "\\r", 2); break; case '\t': buf_add(b, "\\t", 2); break; default: if (*p < 0x20) { char esc[8]; snprintf(esc, sizeof(esc), "\\u%04x", *p); buf_add(b, esc, strlen(esc)); } else { buf_add(b, (const char *)p, 1); } } p++; } buf_add(b, "\"", 1); } /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void str_copy(char *dst, size_t sz, const char *src) { size_t n; if (!dst || sz == 0) return; if (!src) src = ""; n = strlen(src); if (n > sz - 1) n = sz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static void str_trim(char *s) { size_t n; char *p = s; if (!s) return; while (*p && (unsigned char)*p <= ' ') p++; if (p != s) memmove(s, p, strlen(p) + 1); n = strlen(s); while (n > 0 && (unsigned char)s[n - 1] <= ' ') s[--n] = '\0'; } 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'; } /* Returns 1 when the key was present (value may be empty). */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { const char *p; size_t klen; if (!qs || !key || !out || outsz == 0) return 0; out[0] = '\0'; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static int is_post_request(void) { const char *m = getenv("REQUEST_METHOD"); return m && strcmp(m, "POST") == 0; } static void utc_stamp(time_t t, char *buf, size_t sz) { struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &t); #else gmtime_r(&t, &tmv); #endif strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } /* Strip any userinfo from a URL-ish string so an origin like * https://user:token@host/x.git is printed as https://host/x.git. */ static void redact_url(const char *in, char *out, size_t sz) { const char *scheme; const char *at; if (!in || !*in) { str_copy(out, sz, ""); return; } scheme = strstr(in, "://"); if (!scheme) { str_copy(out, sz, in); return; } at = strchr(scheme + 3, '@'); if (!at) { str_copy(out, sz, in); return; } /* Anything with an '@' before the first '/' carries userinfo. */ { const char *slash = strchr(scheme + 3, '/'); if (slash && slash < at) { str_copy(out, sz, in); return; } } /* scheme:// + rest-after-@ */ { size_t head = (size_t)(scheme + 3 - in); if (head >= sz) head = sz - 1; memcpy(out, in, head); out[head] = '\0'; strncat(out, at + 1, sz - strlen(out) - 1); } } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; const char *qs; char qpwd[256]; 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 (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "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); } /* ------------------------------------------------------------------ */ /* Running git: argv only, never a shell */ /* ------------------------------------------------------------------ */ /* Captures stdout into out (NUL terminated, truncated at outsz-1) and returns * the child's exit status, or -1 when it could not be started or timed out. * Every argv passed here is built from a constant plus one validated path. */ #if defined(_WIN32) static void win_quote(const char *in, char *out, size_t sz) { size_t o = 0; o += (size_t)snprintf(out, sz, "\""); while (*in && o + 3 < sz) { if (*in == '"' || *in == '\\') { out[o++] = '\\'; } out[o++] = *in++; } if (o + 2 < sz) out[o++] = '"'; out[o] = '\0'; } static int run_argv(char *const argv[], buf_t *out, int timeout_s) { SECURITY_ATTRIBUTES sa; HANDLE rd = NULL, wr = NULL; STARTUPINFOA si; PROCESS_INFORMATION pi; char cmdline[4096]; size_t used = 0; DWORD waited; DWORD ticks = 0; int rc = -1; memset(&sa, 0, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; if (!CreatePipe(&rd, &wr, &sa, 0)) return -1; SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0); cmdline[0] = '\0'; { int i; for (i = 0; argv[i]; i++) { char q[1200]; size_t need; win_quote(argv[i], q, sizeof(q)); need = strlen(q) + 2; if (used + need + 1 >= sizeof(cmdline)) break; if (used) cmdline[used++] = ' '; memcpy(cmdline + used, q, strlen(q)); used += strlen(q); cmdline[used] = '\0'; } } memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = wr; si.hStdError = wr; si.hStdInput = NULL; memset(&pi, 0, sizeof(pi)); if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { CloseHandle(rd); CloseHandle(wr); return -1; } CloseHandle(wr); for (;;) { DWORD avail = 0; char tmp[4096]; DWORD got = 0; if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break; if (avail == 0) { waited = WaitForSingleObject(pi.hProcess, 20); if (waited == WAIT_OBJECT_0) { /* one last drain */ if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break; if (avail == 0) break; } else if (timeout_s > 0 && waited == WAIT_TIMEOUT) { if (++ticks > (DWORD)timeout_s * 50) { TerminateProcess(pi.hProcess, 1); break; } } continue; } if (avail > sizeof(tmp)) avail = sizeof(tmp); if (!ReadFile(rd, tmp, avail, &got, NULL) || got == 0) break; if (out) buf_add(out, tmp, got); } if (WaitForSingleObject(pi.hProcess, (DWORD)(timeout_s > 0 ? timeout_s : 20) * 1000u) != WAIT_OBJECT_0) { TerminateProcess(pi.hProcess, 1); WaitForSingleObject(pi.hProcess, 2000); } { DWORD code = 1; GetExitCodeProcess(pi.hProcess, &code); rc = (int)code; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(rd); return rc; } #else /* POSIX */ static int run_argv(char *const argv[], buf_t *out, int timeout_s) { int fds[2]; pid_t pid; int status = 0; int timed_out = 0; time_t started; char *child_env_ok; if (pipe(fds) != 0) return -1; pid = fork(); if (pid < 0) { close(fds[0]); close(fds[1]); return -1; } if (pid == 0) { /* Child: stdout+stderr into the pipe, stdin from /dev/null so nothing * can ever block waiting for a password prompt. */ int devnull = open("/dev/null", O_RDONLY); if (devnull >= 0) { dup2(devnull, STDIN_FILENO); if (devnull != STDIN_FILENO) close(devnull); } dup2(fds[1], STDOUT_FILENO); dup2(fds[1], STDERR_FILENO); close(fds[0]); close(fds[1]); execvp(argv[0], argv); _exit(127); } close(fds[1]); child_env_ok = (char *)""; /* keep the compiler quiet about unused locals */ (void)child_env_ok; started = time(NULL); for (;;) { struct pollfd pfd; char tmp[4096]; ssize_t n; int pr; pfd.fd = fds[0]; pfd.events = POLLIN; pfd.revents = 0; pr = poll(&pfd, 1, 100); if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) { n = read(fds[0], tmp, sizeof(tmp)); if (n > 0) { if (out) buf_add(out, tmp, (size_t)n); continue; } if (n == 0) break; } if (timeout_s > 0 && (time(NULL) - started) > timeout_s) { timed_out = 1; kill(pid, SIGKILL); break; } } close(fds[0]); while (waitpid(pid, &status, 0) < 0) { if (errno != EINTR) break; } if (timed_out) return -1; if (WIFEXITED(status)) return WEXITSTATUS(status); return -1; } #endif /* git -C ... */ static int run_git(const char *repo, char *const extra[], buf_t *out, int timeout_s) { char *argv[16]; int i = 0; int rc; argv[i++] = (char *)"git"; argv[i++] = (char *)"-C"; argv[i++] = (char *)repo; while (*extra && i < 14) argv[i++] = *extra++; argv[i] = NULL; rc = run_argv(argv, out, timeout_s); return rc; } /* ------------------------------------------------------------------ */ /* Repository model */ /* ------------------------------------------------------------------ */ typedef struct { char path[1024]; char name[256]; char root[768]; char branch[256]; char upstream[512]; /* redacted */ char remote[512]; /* origin URL, userinfo stripped */ int ahead; int behind; int dirty; /* changed entries (tracked + untracked) */ int untracked; int staged; int conflicted; int stash; int detached; int no_upstream; int unborn; int detached_ok; long long last_ct; char last_hash[48]; char last_subject[300]; } repo_t; static repo_t g_repos[MAX_REPOS]; static int g_repo_count; typedef struct { char root[768]; /* as configured, for display */ char canon[768]; /* realpath() form, for the prefix check */ int exists; int count; int truncated; } rootstat_t; static rootstat_t g_roots[MAX_ROOTS]; static int g_root_count; /* ------------------------------------------------------------------ */ /* Discovery */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) # define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) # define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG) #else # define SX_ISDIR(m) S_ISDIR(m) # define SX_ISREG(m) S_ISREG(m) #endif static int path_exists(const char *p) { #if defined(_WIN32) return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; #else struct stat st; return stat(p, &st) == 0; #endif } /* A repo is a directory that has a .git entry which is either a directory * (normal clone) or a regular file (worktree / submodule pointer). */ static int is_repo_dir(const char *dir) { char gp[1200]; #if defined(_WIN32) DWORD attr; #else struct stat st; #endif snprintf(gp, sizeof(gp), "%s/.git", dir); #if defined(_WIN32) attr = GetFileAttributesA(gp); if (attr == INVALID_FILE_ATTRIBUTES) return 0; return (attr & FILE_ATTRIBUTE_DIRECTORY) || !(attr & FILE_ATTRIBUTE_DIRECTORY); #else if (lstat(gp, &st) != 0) { if (stat(gp, &st) != 0) return 0; } return SX_ISDIR(st.st_mode) || SX_ISREG(st.st_mode); #endif } static const char *base_name(const char *p) { const char *s = strrchr(p, '/'); #if defined(_WIN32) const char *b = strrchr(p, '\\'); if (b && (!s || b > s)) s = b; #endif return s ? s + 1 : p; } static void repo_add(const char *dir, const char *root) { repo_t *r; if (g_repo_count >= MAX_REPOS) return; r = &g_repos[g_repo_count++]; memset(r, 0, sizeof(*r)); str_copy(r->path, sizeof(r->path), dir); str_copy(r->name, sizeof(r->name), base_name(dir)); str_copy(r->root, sizeof(r->root), root); } /* Depth-limited walk. A repository is a leaf: once found we do not descend into * it, because a node's repos are the unit you want to see, not every vendored * checkout inside them. Entry budget is per root (lesson: a shared budget hides * the second root entirely). */ static void walk_dir(const char *dir, const char *root, int depth, int *entries, int *truncated) { if (depth > MAX_DEPTH) return; if (*truncated) return; if (is_repo_dir(dir)) { repo_add(dir, root); return; } if (depth == MAX_DEPTH) return; { #if defined(_WIN32) WIN32_FIND_DATAA fd; HANDLE h; char pat[1400]; snprintf(pat, sizeof(pat), "%s\\*", dir); h = FindFirstFileA(pat, &fd); if (h == INVALID_HANDLE_VALUE) return; do { char child[1400]; if (fd.cFileName[0] == '.') continue; if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; if (strcmp(fd.cFileName, "node_modules") == 0) continue; if (strcmp(fd.cFileName, "__pycache__") == 0) continue; if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; } snprintf(child, sizeof(child), "%s\\%s", dir, fd.cFileName); walk_dir(child, root, depth + 1, entries, truncated); } while (FindNextFileA(h, &fd)); FindClose(h); #else DIR *d = opendir(dir); struct dirent *e; if (!d) return; while ((e = readdir(d)) != NULL) { char child[1400]; struct stat st; if (e->d_name[0] == '.') continue; if (strcmp(e->d_name, "node_modules") == 0) continue; if (strcmp(e->d_name, "__pycache__") == 0) continue; snprintf(child, sizeof(child), "%s/%s", dir, e->d_name); if (lstat(child, &st) != 0) continue; if (!SX_ISDIR(st.st_mode)) continue; /* never follow symlinks */ if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; } walk_dir(child, root, depth + 1, entries, truncated); } closedir(d); #endif } } static void canon_path(const char *in, char *out, size_t sz); static int path_exists(const char *p); static void root_add(const char *root, const char *sep_list_used) { (void)sep_list_used; if (!root || !*root) return; if (g_root_count >= MAX_ROOTS) return; { int i; for (i = 0; i < g_root_count; i++) if (strcmp(g_roots[i].root, root) == 0) return; } str_copy(g_roots[g_root_count].root, sizeof(g_roots[g_root_count].root), root); canon_path(root, g_roots[g_root_count].canon, sizeof(g_roots[g_root_count].canon)); g_roots[g_root_count].exists = 0; g_roots[g_root_count].count = 0; g_roots[g_root_count].truncated = 0; g_root_count++; } static void roots_from_env(const char *name, int posix_sep) { const char *v = getenv(name); char buf[2048]; char sep; char *p; char *start; if (!v || !*v) return; snprintf(buf, sizeof(buf), "%s", v); #if defined(_WIN32) sep = posix_sep ? ';' : ';'; if (posix_sep) { char *q = buf; while ((q = strchr(q, ':')) != NULL) { /* a drive-letter colon is followed by a separator, not a path */ if (q[1] == '\\' || q[1] == '/') { q++; continue; } *q = ';'; q++; } } #else sep = ':'; (void)posix_sep; #endif start = buf; for (p = buf; ; p++) { if (*p == sep || *p == '\0') { char saved = *p; *p = '\0'; str_trim(start); root_add(start, sep == ';' ? ";" : ":"); if (saved == '\0') break; start = p + 1; } } } static void collect_roots(void) { const char *home = getenv("HOME"); const char *only = getenv("GITSTAT_ONLY_ROOTS"); g_root_count = 0; /* GITSTAT_ONLY_ROOTS=1 makes GITSTAT_ROOTS the complete list. It exists for * two callers: a node that wants an explicit allowlist, and the test suite, * which must see a fixture tree and nothing else. The default behaviour is * still the documented one: the platform roots plus GITSTAT_ROOTS. */ if (only && *only && strcmp(only, "0") != 0) { roots_from_env("GITSTAT_ROOTS", 1); return; } #if defined(_WIN32) home = getenv("USERPROFILE"); if (!home || !*home) home = getenv("HOMEDRIVE"); root_add(home, ";"); if (path_exists("D:\\codebases")) root_add("D:\\codebases", ";"); if (path_exists("C:\\codebases")) root_add("C:\\codebases", ";"); roots_from_env("GITSTAT_ROOTS", 1); #else root_add("/workspace", ":"); root_add("/codebases", ":"); root_add(home, ":"); roots_from_env("GITSTAT_ROOTS", 1); #endif } /* ------------------------------------------------------------------ */ /* git queries per repo */ /* ------------------------------------------------------------------ */ /* status --porcelain=v2 --branch. Header lines carry branch state; the rest are * one changed entry each. Lines look like: * # branch.oid (all zeros when unborn) * # branch.head |(detached) * # branch.upstream (absent when no upstream) * # branch.ab +N -M (absent when no upstream) * 1 XY sub mH mI mW hH hI path * 2 XY ... path * u XY ... path * ? path * ! path */ static void parse_status(const char *text, repo_t *r) { const char *p = text; char line[1200]; while (*p) { size_t n = 0; while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++; line[n] = '\0'; if (*p == '\n') p++; str_trim(line); if (!line[0]) continue; if (line[0] == '#') { const char *v = line + 1; while (*v == ' ') v++; if (strncmp(v, "branch.head ", 12) == 0) { const char *b = v + 12; if (strcmp(b, "(detached)") == 0) { r->detached = 1; str_copy(r->branch, sizeof(r->branch), "detached"); } else { str_copy(r->branch, sizeof(r->branch), b); } } else if (strncmp(v, "branch.upstream ", 16) == 0) { char clean[512]; redact_url(v + 16, clean, sizeof(clean)); str_copy(r->upstream, sizeof(r->upstream), clean); } else if (strncmp(v, "branch.ab ", 10) == 0) { const char *ab = v + 10; int ahead = 0, behind = 0; if (sscanf(ab, "+%d -%d", &ahead, &behind) == 2) { r->ahead = ahead; r->behind = behind; } else if (sscanf(ab, "+%d -%d", &ahead, &behind) == 1) { r->ahead = ahead; } } else if (strncmp(v, "branch.oid ", 11) == 0) { const char *oid = v + 11; if (strcmp(oid, "(initial)") == 0) r->unborn = 1; } continue; } if (line[0] == '?') { r->dirty++; r->untracked++; } else if (line[0] == '!') { /* ignored: not a change */ } else if (line[0] == '1' || line[0] == '2') { r->dirty++; if (line[0] == '1') { char xy[8] = { 0, 0, 0 }; if (sscanf(line, "1 %2s", xy) == 1) { if (xy[0] != '.' && xy[0] != '\0') r->staged++; } } else { r->staged++; } } else if (line[0] == 'u') { r->dirty++; r->conflicted++; } } if (!r->unborn && r->branch[0] && strcmp(r->branch, "detached") != 0 && !r->upstream[0]) r->no_upstream = 1; if (r->unborn) r->no_upstream = 1; } /* "1 XY ..." -> XY codes for the detail drawer. */ static void status_code(const char *line, char *out, size_t sz) { if (line[0] == '?') { str_copy(out, sz, "\?\?"); return; } if (line[0] == '!') { str_copy(out, sz, "!!"); return; } if (line[0] == 'u') { str_copy(out, sz, "UU"); return; } if ((line[0] == '1' || line[0] == '2') && line[1] == ' ') str_copy(out, sz, line + 2); else str_copy(out, sz, "--"); } /* Path of a v2 status line: everything after the fixed fields. */ static void status_path(const char *line, char *out, size_t sz) { const char *p = line; int fields; out[0] = '\0'; if (line[0] == '?') { str_copy(out, sz, line + 2); return; } if (line[0] == '!') { str_copy(out, sz, line + 2); return; } if (line[0] == 'u') fields = 10; else if (line[0] == '2') fields = 9; else if (line[0] == '1') fields = 8; else { str_copy(out, sz, line); return; } for (; fields > 0 && *p; fields--) { while (*p && *p != ' ') p++; while (*p == ' ') p++; } str_copy(out, sz, p); if (line[0] == '2') { /* rename records carry "old\tnew" */ char *tab = strchr(out, '\t'); if (tab) memmove(out, tab + 1, strlen(tab + 1) + 1); } } /* Three child processes per repository, not four: the origin URL is only read * for the repository you actually open, not for every row of the board. On a Mac * with fifty checkouts that is most of a second saved per row. (--show-stash * would fold the stash count into the status header too, but only in the human * output - porcelain v2 never carries it, so `stash list` stays.) */ static void query_repo(repo_t *r, int with_remote) { buf_t out; char *status_args[] = { (char *)"status", (char *)"--porcelain=v2", (char *)"--branch", (char *)"--untracked-files=normal", NULL }; char *stash_args[] = { (char *)"stash", (char *)"list", (char *)"--format=%gd", NULL }; char *log_args[] = { (char *)"log", (char *)"-1", (char *)"--format=%H%x09%ct%x09%s", NULL }; buf_init(&out); if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) parse_status(buf_str(&out), r); buf_free(&out); buf_init(&out); if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) { char *p = out.p; char *t1 = strchr(p, '\t'); if (t1) { *t1 = '\0'; str_copy(r->last_hash, sizeof(r->last_hash), p); { char *t2 = strchr(t1 + 1, '\t'); if (t2) { *t2 = '\0'; r->last_ct = atoll(t1 + 1); str_copy(r->last_subject, sizeof(r->last_subject), t2 + 1); } else { r->last_ct = atoll(t1 + 1); } } str_trim(r->last_subject); } } buf_free(&out); buf_init(&out); if (run_git(r->path, stash_args, &out, GIT_TIMEOUT_S) >= 0) { const char *p = out.p; while (p && *p) { const char *nl = strchr(p, '\n'); if (!nl) break; if (nl > p) r->stash++; p = nl + 1; } } buf_free(&out); if (with_remote) { buf_init(&out); { char *cfg_args[] = { (char *)"config", (char *)"--get", (char *)"remote.origin.url", NULL }; if (run_git(r->path, cfg_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) { char raw[512]; char clean[512]; str_copy(raw, sizeof(raw), out.p); str_trim(raw); redact_url(raw, clean, sizeof(clean)); str_copy(r->remote, sizeof(r->remote), clean); } } buf_free(&out); } } static int repo_cmp(const void *a, const void *b) { const repo_t *x = (const repo_t *)a; const repo_t *y = (const repo_t *)b; /* Dirty first (uncommitted work is the thing you came to see), then most * recently touched, then path. */ if ((x->dirty > 0) != (y->dirty > 0)) return x->dirty > 0 ? -1 : 1; if (x->dirty != y->dirty) return y->dirty - x->dirty; if (x->last_ct != y->last_ct) return (x->last_ct > y->last_ct) ? -1 : 1; return strcmp(x->path, y->path); } static void collect_repos(void) { int i; collect_roots(); g_repo_count = 0; for (i = 0; i < g_root_count; i++) { int entries = 0; int truncated = 0; int before = g_repo_count; g_roots[i].exists = path_exists(g_roots[i].root) ? 1 : 0; if (g_roots[i].exists) walk_dir(g_roots[i].root, g_roots[i].root, 0, &entries, &truncated); g_roots[i].truncated = truncated; g_roots[i].count = g_repo_count - before; } for (i = 0; i < g_repo_count; i++) query_repo(&g_repos[i], 0); if (g_repo_count > 1) qsort(g_repos, (size_t)g_repo_count, sizeof(repo_t), repo_cmp); } /* ------------------------------------------------------------------ */ /* Path allowlisting */ /* ------------------------------------------------------------------ */ /* realpath() cannot be handed a caller-sized buffer: glibc's fortified * wrapper aborts when the buffer is smaller than PATH_MAX, and the paths here * are keep-to-1024 bytes in a 1400-byte array. Ask realpath to allocate, then * copy into our own fixed array. */ static void canon_path(const char *in, char *out, size_t sz) { #if defined(_WIN32) if (!GetFullPathNameA(in, (DWORD)sz, out, NULL)) str_copy(out, sz, in); #else char *rp = realpath(in, NULL); if (rp) { str_copy(out, sz, rp); free(rp); } else { str_copy(out, sz, in); } #endif } static int under_root(const char *path) { int i; for (i = 0; i < g_root_count; i++) { /* Compare against the canonical root, not the configured string: on * macOS /tmp and /var are symlinks, so realpath("/tmp/x") is * "/private/tmp/x" and a raw prefix test would refuse every path. */ const char *r = g_roots[i].canon[0] ? g_roots[i].canon : g_roots[i].root; size_t n = strlen(r); if (n == 0) continue; if (strncmp(path, r, n) != 0) continue; if (path[n] == '\0' || path[n] == '/' || path[n] == '\\') return 1; } return 0; } /* A repo path is acceptable only when it canonicalises to somewhere under an * allowlisted root AND that directory carries a .git entry. This is the whole * authorisation model for the API: nothing outside the roots is ever read, and * no argument can walk upwards with "..". */ static int path_allowed(const char *requested, char *canon, size_t sz) { char tmp[1400]; if (!requested || !*requested) return 0; if (strstr(requested, "..")) return 0; collect_roots(); canon_path(requested, tmp, sizeof(tmp)); if (!under_root(tmp)) return 0; if (!is_repo_dir(tmp)) return 0; str_copy(canon, sz, tmp); return 1; } /* ------------------------------------------------------------------ */ /* JSON emitters */ /* ------------------------------------------------------------------ */ static void json_header(int status) { if (status == 403) fputs("Status: 403 Forbidden\r\n", stdout); else if (status == 400) fputs("Status: 400 Bad Request\r\n", stdout); 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 emit_repo(buf_t *b, const repo_t *r, int detail) { char at[40]; char up[512]; redact_url(r->upstream, up, sizeof(up)); utc_stamp((time_t)r->last_ct, at, sizeof(at)); buf_add(b, "{", 1); buf_puts(b, "\"path\":"); json_str(b, r->path); buf_puts(b, ",\"name\":"); json_str(b, r->name); buf_puts(b, ",\"root\":"); json_str(b, r->root); buf_puts(b, ",\"branch\":"); json_str(b, r->branch); buf_puts(b, ",\"upstream\":"); json_str(b, up); buf_puts(b, ",\"remote\":"); json_str(b, r->remote); buf_printf(b, ",\"ahead\":%d,\"behind\":%d,\"dirty\":%d,\"untracked\":%d," "\"staged\":%d,\"conflicted\":%d,\"stash\":%d", r->ahead, r->behind, r->dirty, r->untracked, r->staged, r->conflicted, r->stash); buf_printf(b, ",\"detached\":%s,\"no_upstream\":%s,\"unborn\":%s", r->detached ? "true" : "false", r->no_upstream ? "true" : "false", r->unborn ? "true" : "false"); buf_puts(b, ",\"last_commit\":{"); buf_puts(b, "\"hash\":"); json_str(b, r->last_hash); buf_puts(b, ",\"short\":"); { char sh[12]; str_copy(sh, sizeof(sh), r->last_hash); json_str(b, sh); } buf_printf(b, ",\"ct\":%lld", r->last_ct); buf_puts(b, ",\"at\":"); json_str(b, at); buf_puts(b, ",\"subject\":"); json_str(b, r->last_subject); buf_puts(b, "}"); (void)detail; buf_add(b, "}", 1); } static void print_repos(void) { buf_t b; int i; char now[40]; int dirty = 0, ahead = 0, behind = 0, stashed = 0, detached = 0; for (i = 0; i < g_repo_count; i++) { if (g_repos[i].dirty > 0) dirty++; if (g_repos[i].ahead > 0) ahead++; if (g_repos[i].behind > 0) behind++; if (g_repos[i].stash > 0) stashed += g_repos[i].stash; if (g_repos[i].detached) detached++; } utc_stamp(time(NULL), now, sizeof(now)); buf_init(&b); buf_printf(&b, "{\"ok\":true,\"action\":\"repos\",\"count\":%d", g_repo_count); buf_printf(&b, ",\"table_capped\":%s", g_repo_count >= MAX_REPOS ? "true" : "false"); buf_printf(&b, ",\"summary\":{\"dirty\":%d,\"ahead\":%d,\"behind\":%d," "\"stashes\":%d,\"detached\":%d}", dirty, ahead, behind, stashed, detached); buf_puts(&b, ",\"checked_at\":"); json_str(&b, now); buf_puts(&b, ",\"roots\":["); for (i = 0; i < g_root_count; i++) { if (i) buf_add(&b, ",", 1); buf_add(&b, "{", 1); buf_puts(&b, "\"root\":"); json_str(&b, g_roots[i].root); buf_printf(&b, ",\"exists\":%s,\"count\":%d,\"truncated\":%s", g_roots[i].exists ? "true" : "false", g_roots[i].count, g_roots[i].truncated ? "true" : "false"); buf_add(&b, "}", 1); } buf_puts(&b, "],\"repos\":["); for (i = 0; i < g_repo_count; i++) { if (i) buf_add(&b, ",", 1); emit_repo(&b, &g_repos[i], 0); } buf_puts(&b, "]}\n"); fputs(buf_str(&b), stdout); buf_free(&b); } static int print_repo_detail(const char *path) { char canon[1400]; repo_t *r = NULL; buf_t b; buf_t out; int i; char at[40]; if (!path_allowed(path, canon, sizeof(canon))) { json_header(403); fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout); return 0; } /* Prefer the record we already measured; fall back to measuring it now when * the path was not part of the (budgeted) discovery walk. */ for (i = 0; i < g_repo_count; i++) { if (strcmp(g_repos[i].path, canon) == 0) { r = &g_repos[i]; break; } } if (r) query_repo(r, 1); if (!r) { if (g_repo_count >= MAX_REPOS) { json_header(400); fputs("{\"ok\":false,\"error\":\"repository table full\"}\n", stdout); return 0; } r = &g_repos[g_repo_count]; memset(r, 0, sizeof(*r)); str_copy(r->path, sizeof(r->path), canon); str_copy(r->name, sizeof(r->name), base_name(canon)); { /* Keep the row shaped like a discovered one: attribute it to the * root it actually sits under rather than reporting an empty root. */ int k; for (k = 0; k < g_root_count; k++) { const char *rp = g_roots[k].canon[0] ? g_roots[k].canon : g_roots[k].root; size_t n = strlen(rp); if (n && strncmp(canon, rp, n) == 0 && (canon[n] == '\0' || canon[n] == '/' || canon[n] == '\\')) { str_copy(r->root, sizeof(r->root), g_roots[k].root); break; } } } query_repo(r, 1); g_repo_count++; } buf_init(&b); buf_printf(&b, "{\"ok\":true,\"action\":\"repo\",\"repo\":"); emit_repo(&b, r, 1); /* changed files, max MAX_CHANGED */ { char *status_args[] = { (char *)"status", (char *)"--porcelain=v2", (char *)"--untracked-files=normal", NULL }; int shown = 0, total = 0; int trunc = 0; buf_init(&out); buf_puts(&b, ",\"changed\":["); if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) { const char *p = out.p; char line[1200]; while (p && *p) { size_t n = 0; while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++; line[n] = '\0'; if (*p == '\n') p++; str_trim(line); if (!line[0] || line[0] == '#') continue; total++; if (shown >= MAX_CHANGED) { trunc = 1; continue; } { char code[8], fp[900]; status_code(line, code, sizeof(code)); status_path(line, fp, sizeof(fp)); if (shown) buf_add(&b, ",", 1); buf_add(&b, "{", 1); buf_puts(&b, "\"code\":"); json_str(&b, code); buf_puts(&b, ",\"path\":"); json_str(&b, fp); buf_add(&b, "}", 1); shown++; } } } buf_free(&out); buf_printf(&b, "],\"changed_count\":%d,\"changed_truncated\":%s", total, trunc ? "true" : "false"); } /* recent commits */ { char *log_args[] = { (char *)"log", (char *)"-20", (char *)"--format=%H%x09%ct%x09%an%x09%s", NULL }; int n = 0; buf_init(&out); buf_puts(&b, ",\"commits\":["); if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0) { const char *p = out.p; while (p && *p && n < MAX_COMMITS) { const char *nl = strchr(p, '\n'); size_t len = nl ? (size_t)(nl - p) : strlen(p); char line[1500]; if (len >= sizeof(line)) len = sizeof(line) - 1; memcpy(line, p, len); line[len] = '\0'; p = nl ? nl + 1 : p + len; if (!line[0]) continue; { char *t1 = strchr(line, '\t'); char *t2; char *t3; if (!t1) continue; *t1 = '\0'; t2 = strchr(t1 + 1, '\t'); if (!t2) continue; *t2 = '\0'; t3 = strchr(t2 + 1, '\t'); if (t3) *t3 = '\0'; utc_stamp((time_t)atoll(t1 + 1), at, sizeof(at)); if (n) buf_add(&b, ",", 1); buf_add(&b, "{", 1); buf_puts(&b, "\"hash\":"); json_str(&b, line); buf_printf(&b, ",\"ct\":%lld", (long long)atoll(t1 + 1)); buf_puts(&b, ",\"author\":"); json_str(&b, t2 + 1); buf_puts(&b, ",\"subject\":"); json_str(&b, t3 ? t3 + 1 : ""); buf_add(&b, "}", 1); n++; } } } buf_free(&out); buf_add(&b, "]", 1); } buf_puts(&b, "}\n"); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } static int do_fetch(const char *path, int *status_out) { char canon[1400]; buf_t b; buf_t out; int rc; repo_t tmp; if (!path_allowed(path, canon, sizeof(canon))) { json_header(403); fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout); return 0; } json_header(0); if (!getenv("GITSTAT_ALLOW_FETCH") || strcmp(getenv("GITSTAT_ALLOW_FETCH"), "1") != 0) { buf_init(&b); buf_puts(&b, "{\"ok\":false,\"error\":\"fetch is disabled on this node\"," "\"hint\":\"set GITSTAT_ALLOW_FETCH=1 to enable git fetch --prune\"}\n"); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } { char *fetch_args[] = { (char *)"fetch", (char *)"--prune", NULL }; buf_init(&out); rc = run_git(canon, fetch_args, &out, FETCH_TIMEOUT_S); memset(&tmp, 0, sizeof(tmp)); str_copy(tmp.path, sizeof(tmp.path), canon); query_repo(&tmp, 1); buf_init(&b); buf_printf(&b, "{\"ok\":%s,\"action\":\"fetch\",\"exit\":%d", rc == 0 ? "true" : "false", rc); buf_puts(&b, ",\"path\":"); json_str(&b, canon); buf_puts(&b, ",\"output\":"); json_str(&b, buf_str(&out)); buf_printf(&b, ",\"ahead\":%d,\"behind\":%d,\"branch\":", tmp.ahead, tmp.behind); json_str(&b, tmp.branch); buf_puts(&b, "}\n"); fputs(buf_str(&b), stdout); buf_free(&b); buf_free(&out); } (void)status_out; return 0; } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ /* Split UI_HTML on the two control-byte placeholders and expand them into the * theme macros, so the page and the bot palette can never drift apart. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static int mode_html(void) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); return 0; } /* ------------------------------------------------------------------ */ /* Modes */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}\n", stdout); return 0; } static int mode_json(const char *qs) { char action[64]; char path[1024]; action[0] = '\0'; get_query_val(qs, "action", action, sizeof(action)); if (strcmp(action, "repo") == 0) { collect_roots(); get_query_val(qs, "path", path, sizeof(path)); json_header(0); return print_repo_detail(path); } if (strcmp(action, "fetch") == 0) { int st = 0; collect_roots(); get_query_val(qs, "path", path, sizeof(path)); if (!is_post_request()) { json_header(400); fputs("{\"ok\":false,\"error\":\"fetch is POST only\"}\n", stdout); return 0; } return do_fetch(path, &st); } if (strcmp(action, "repos") == 0 || !action[0] || strcmp(action, "all") == 0) { collect_repos(); json_header(0); print_repos(); return 0; } json_header(0); fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); return 0; } int main(int argc, char **argv) { const char *qs; int embed; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) return mode_meta(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (is_post_request() && strstr(qs, "action=fetch")) { char path[1024]; collect_roots(); get_query_val(qs, "path", path, sizeof(path)); return do_fetch(path, NULL); } if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) return mode_json(qs); embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); (void)embed; return mode_html(); }