| 1 | /* |
| 2 | * plugin_gitstat - SCORPIOX BOT open-source local git repository status board |
| 3 | * |
| 4 | * One clean-room C99 binary, three modes: |
| 5 | * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata |
| 6 | * 2. ?action=repos|repo|fetch / ?format=json / POST -> JSON node API |
| 7 | * 3. GET (default) -> responsive HTML board |
| 8 | * |
| 9 | * It walks a fixed set of allowlisted roots (never beyond them), finds every |
| 10 | * working tree that has a .git directory or a .git worktree file, and asks git |
| 11 | * about each one through argv-only child processes (no shell, ever): |
| 12 | * |
| 13 | * git -C <repo> status --porcelain=v2 --branch --untracked-files=normal |
| 14 | * git -C <repo> log -1 --format=%H%x09%ct%x09%s |
| 15 | * git -C <repo> stash list --format=%gd |
| 16 | * |
| 17 | * From that it derives branch, dirty file count, ahead/behind upstream, stash |
| 18 | * count, detached / no-upstream / unborn states and the last commit. Fetching |
| 19 | * from a remote is the ONLY write-ish operation and it stays off until the node |
| 20 | * operator sets GITSTAT_ALLOW_FETCH=1; even then it is `git fetch --prune` with |
| 21 | * a 30 s timeout, and GIT_TERMINAL_PROMPT=0 plus an empty GIT_ASKPASS so a |
| 22 | * credential prompt can never hang the node. |
| 23 | * |
| 24 | * Remote URLs are stripped of any userinfo before they are printed, so a repo |
| 25 | * whose origin is https://user:token@host/x.git never leaks the token into the |
| 26 | * dashboard, the JSON API or the bot's logs. |
| 27 | * |
| 28 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 29 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 30 | * scorpiox-server on the node. |
| 31 | * |
| 32 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 33 | */ |
| 34 | |
| 35 | /* Must be the very first thing on Windows: CreateProcessA/GetFileAttributesA |
| 36 | * and the pipe helpers are gated on _WIN32_WINNT, and MinGW defaults to 0x502. */ |
| 37 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 38 | # define _WIN32_WINNT 0x0601 |
| 39 | #endif |
| 40 | |
| 41 | #if !defined(_WIN32) |
| 42 | # define _POSIX_C_SOURCE 200809L |
| 43 | # define _DEFAULT_SOURCE 1 |
| 44 | # if defined(__APPLE__) |
| 45 | # define _DARWIN_C_SOURCE 1 |
| 46 | # endif |
| 47 | #endif |
| 48 | |
| 49 | #include <stdio.h> |
| 50 | #include <stdlib.h> |
| 51 | #include <string.h> |
| 52 | #include <stdarg.h> |
| 53 | #include <ctype.h> |
| 54 | #include <errno.h> |
| 55 | #include <time.h> |
| 56 | |
| 57 | #if defined(_WIN32) |
| 58 | # define WIN32_LEAN_AND_MEAN |
| 59 | # include <windows.h> |
| 60 | #else |
| 61 | # include <unistd.h> |
| 62 | # include <dirent.h> |
| 63 | # include <fcntl.h> |
| 64 | # include <sys/types.h> |
| 65 | # include <sys/stat.h> |
| 66 | # include <sys/wait.h> |
| 67 | # include <signal.h> |
| 68 | # include <poll.h> |
| 69 | #endif |
| 70 | |
| 71 | #include "bot_theme_plugin.h" |
| 72 | #include "ui_html.h" |
| 73 | |
| 74 | #define PLUGIN_SLUG "gitstat" |
| 75 | #define PLUGIN_ID "plugin_gitstat" |
| 76 | #define PLUGIN_VER "1.0.0" |
| 77 | |
| 78 | #define PLUGIN_NAME "git" |
| 79 | #define PLUGIN_DESC "Repo status" |
| 80 | |
| 81 | #define MAX_REPOS 1200 |
| 82 | #define MAX_ROOT_ENTRIES 20000 |
| 83 | #define MAX_DEPTH 4 |
| 84 | #define MAX_ROOTS 8 |
| 85 | #define MAX_CHANGED 500 |
| 86 | #define MAX_COMMITS 20 |
| 87 | #define OUT_CAP (512 * 1024) |
| 88 | #define FETCH_TIMEOUT_S 30 |
| 89 | #define GIT_TIMEOUT_S 20 |
| 90 | |
| 91 | /* ------------------------------------------------------------------ */ |
| 92 | /* Buffers */ |
| 93 | /* ------------------------------------------------------------------ */ |
| 94 | |
| 95 | typedef struct { |
| 96 | char *p; |
| 97 | size_t len; |
| 98 | size_t cap; |
| 99 | } buf_t; |
| 100 | |
| 101 | static void buf_init(buf_t *b) |
| 102 | { |
| 103 | b->cap = 4096; |
| 104 | b->len = 0; |
| 105 | b->p = (char *)malloc(b->cap); |
| 106 | if (b->p) b->p[0] = '\0'; |
| 107 | } |
| 108 | |
| 109 | static void buf_free(buf_t *b) |
| 110 | { |
| 111 | free(b->p); |
| 112 | b->p = NULL; |
| 113 | b->len = b->cap = 0; |
| 114 | } |
| 115 | |
| 116 | static void buf_add(buf_t *b, const char *s, size_t n) |
| 117 | { |
| 118 | if (!b->p) return; |
| 119 | if (b->len + n + 1 > b->cap) { |
| 120 | size_t nc = b->cap; |
| 121 | char *np; |
| 122 | while (nc < b->len + n + 1) nc *= 2; |
| 123 | np = (char *)realloc(b->p, nc); |
| 124 | if (!np) return; |
| 125 | b->p = np; |
| 126 | b->cap = nc; |
| 127 | } |
| 128 | memcpy(b->p + b->len, s, n); |
| 129 | b->len += n; |
| 130 | b->p[b->len] = '\0'; |
| 131 | } |
| 132 | |
| 133 | static void buf_puts(buf_t *b, const char *s) |
| 134 | { |
| 135 | if (s) buf_add(b, s, strlen(s)); |
| 136 | } |
| 137 | |
| 138 | static void buf_printf(buf_t *b, const char *fmt, ...) |
| 139 | { |
| 140 | char tmp[2048]; |
| 141 | va_list ap; |
| 142 | int n; |
| 143 | |
| 144 | va_start(ap, fmt); |
| 145 | n = vsnprintf(tmp, sizeof(tmp), fmt, ap); |
| 146 | va_end(ap); |
| 147 | if (n < 0) return; |
| 148 | if ((size_t)n < sizeof(tmp)) { |
| 149 | buf_add(b, tmp, (size_t)n); |
| 150 | } else { |
| 151 | char *big = (char *)malloc((size_t)n + 1); |
| 152 | if (!big) return; |
| 153 | va_start(ap, fmt); |
| 154 | vsnprintf(big, (size_t)n + 1, fmt, ap); |
| 155 | va_end(ap); |
| 156 | buf_add(b, big, (size_t)n); |
| 157 | free(big); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } |
| 162 | |
| 163 | /* JSON string escaper. Also the last line of defence against a remote URL |
| 164 | * carrying something that would break the document. */ |
| 165 | static void json_str(buf_t *b, const char *s) |
| 166 | { |
| 167 | const unsigned char *p = (const unsigned char *)(s ? s : ""); |
| 168 | buf_add(b, "\"", 1); |
| 169 | while (*p) { |
| 170 | switch (*p) { |
| 171 | case '"': buf_add(b, "\\\"", 2); break; |
| 172 | case '\\': buf_add(b, "\\\\", 2); break; |
| 173 | case '\n': buf_add(b, "\\n", 2); break; |
| 174 | case '\r': buf_add(b, "\\r", 2); break; |
| 175 | case '\t': buf_add(b, "\\t", 2); break; |
| 176 | default: |
| 177 | if (*p < 0x20) { |
| 178 | char esc[8]; |
| 179 | snprintf(esc, sizeof(esc), "\\u%04x", *p); |
| 180 | buf_add(b, esc, strlen(esc)); |
| 181 | } else { |
| 182 | buf_add(b, (const char *)p, 1); |
| 183 | } |
| 184 | } |
| 185 | p++; |
| 186 | } |
| 187 | buf_add(b, "\"", 1); |
| 188 | } |
| 189 | |
| 190 | /* ------------------------------------------------------------------ */ |
| 191 | /* Small utilities */ |
| 192 | /* ------------------------------------------------------------------ */ |
| 193 | |
| 194 | static void str_copy(char *dst, size_t sz, const char *src) |
| 195 | { |
| 196 | size_t n; |
| 197 | if (!dst || sz == 0) return; |
| 198 | if (!src) src = ""; |
| 199 | n = strlen(src); |
| 200 | if (n > sz - 1) n = sz - 1; |
| 201 | memcpy(dst, src, n); |
| 202 | dst[n] = '\0'; |
| 203 | } |
| 204 | |
| 205 | static void str_trim(char *s) |
| 206 | { |
| 207 | size_t n; |
| 208 | char *p = s; |
| 209 | if (!s) return; |
| 210 | while (*p && (unsigned char)*p <= ' ') p++; |
| 211 | if (p != s) memmove(s, p, strlen(p) + 1); |
| 212 | n = strlen(s); |
| 213 | while (n > 0 && (unsigned char)s[n - 1] <= ' ') s[--n] = '\0'; |
| 214 | } |
| 215 | |
| 216 | static void url_decode(char *s) |
| 217 | { |
| 218 | char *o = s; |
| 219 | if (!s) return; |
| 220 | while (*s) { |
| 221 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 222 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 223 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 224 | *o++ = (char)((hi << 4) | lo); |
| 225 | s += 3; |
| 226 | } else if (*s == '+') { |
| 227 | *o++ = ' '; |
| 228 | s++; |
| 229 | } else { |
| 230 | *o++ = *s++; |
| 231 | } |
| 232 | } |
| 233 | *o = '\0'; |
| 234 | } |
| 235 | |
| 236 | /* Returns 1 when the key was present (value may be empty). */ |
| 237 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 238 | { |
| 239 | const char *p; |
| 240 | size_t klen; |
| 241 | |
| 242 | if (!qs || !key || !out || outsz == 0) return 0; |
| 243 | out[0] = '\0'; |
| 244 | klen = strlen(key); |
| 245 | p = qs; |
| 246 | while (*p) { |
| 247 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 248 | size_t i = 0; |
| 249 | p += klen + 1; |
| 250 | while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; |
| 251 | out[i] = '\0'; |
| 252 | url_decode(out); |
| 253 | return 1; |
| 254 | } |
| 255 | p = strchr(p, '&'); |
| 256 | if (!p) break; |
| 257 | p++; |
| 258 | } |
| 259 | return 0; |
| 260 | } |
| 261 | |
| 262 | static int is_post_request(void) |
| 263 | { |
| 264 | const char *m = getenv("REQUEST_METHOD"); |
| 265 | return m && strcmp(m, "POST") == 0; |
| 266 | } |
| 267 | |
| 268 | static void utc_stamp(time_t t, char *buf, size_t sz) |
| 269 | { |
| 270 | struct tm tmv; |
| 271 | #if defined(_WIN32) |
| 272 | gmtime_s(&tmv, &t); |
| 273 | #else |
| 274 | gmtime_r(&t, &tmv); |
| 275 | #endif |
| 276 | strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 277 | } |
| 278 | |
| 279 | /* Strip any userinfo from a URL-ish string so an origin like |
| 280 | * https://user:token@host/x.git is printed as https://host/x.git. */ |
| 281 | static void redact_url(const char *in, char *out, size_t sz) |
| 282 | { |
| 283 | const char *scheme; |
| 284 | const char *at; |
| 285 | |
| 286 | if (!in || !*in) { str_copy(out, sz, ""); return; } |
| 287 | |
| 288 | scheme = strstr(in, "://"); |
| 289 | if (!scheme) { str_copy(out, sz, in); return; } |
| 290 | |
| 291 | at = strchr(scheme + 3, '@'); |
| 292 | if (!at) { str_copy(out, sz, in); return; } |
| 293 | |
| 294 | /* Anything with an '@' before the first '/' carries userinfo. */ |
| 295 | { |
| 296 | const char *slash = strchr(scheme + 3, '/'); |
| 297 | if (slash && slash < at) { str_copy(out, sz, in); return; } |
| 298 | } |
| 299 | |
| 300 | /* scheme:// + rest-after-@ */ |
| 301 | { |
| 302 | size_t head = (size_t)(scheme + 3 - in); |
| 303 | if (head >= sz) head = sz - 1; |
| 304 | memcpy(out, in, head); |
| 305 | out[head] = '\0'; |
| 306 | strncat(out, at + 1, sz - strlen(out) - 1); |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | /* ------------------------------------------------------------------ */ |
| 311 | /* Node authentication */ |
| 312 | /* ------------------------------------------------------------------ */ |
| 313 | |
| 314 | static void require_node_auth(void) |
| 315 | { |
| 316 | const char *np = getenv("BOT_PASSWORD"); |
| 317 | const char *xp; |
| 318 | const char *auth; |
| 319 | const char *qs; |
| 320 | char qpwd[256]; |
| 321 | |
| 322 | if (!np || !*np) return; |
| 323 | |
| 324 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 325 | if (xp && strcmp(xp, np) == 0) return; |
| 326 | |
| 327 | auth = getenv("HTTP_AUTHORIZATION"); |
| 328 | if (auth) { |
| 329 | while (*auth == ' ') auth++; |
| 330 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 331 | auth += 7; |
| 332 | while (*auth == ' ') auth++; |
| 333 | if (strcmp(auth, np) == 0) return; |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | qs = getenv("QUERY_STRING"); |
| 338 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 339 | return; |
| 340 | |
| 341 | fputs("Status: 401 Unauthorized\r\n" |
| 342 | "Content-Type: application/json; charset=utf-8\r\n" |
| 343 | "Cache-Control: no-store\r\n" |
| 344 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 345 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 346 | exit(0); |
| 347 | } |
| 348 | |
| 349 | /* ------------------------------------------------------------------ */ |
| 350 | /* Running git: argv only, never a shell */ |
| 351 | /* ------------------------------------------------------------------ */ |
| 352 | |
| 353 | /* Captures stdout into out (NUL terminated, truncated at outsz-1) and returns |
| 354 | * the child's exit status, or -1 when it could not be started or timed out. |
| 355 | * Every argv passed here is built from a constant plus one validated path. */ |
| 356 | #if defined(_WIN32) |
| 357 | |
| 358 | static void win_quote(const char *in, char *out, size_t sz) |
| 359 | { |
| 360 | size_t o = 0; |
| 361 | o += (size_t)snprintf(out, sz, "\""); |
| 362 | while (*in && o + 3 < sz) { |
| 363 | if (*in == '"' || *in == '\\') { out[o++] = '\\'; } |
| 364 | out[o++] = *in++; |
| 365 | } |
| 366 | if (o + 2 < sz) out[o++] = '"'; |
| 367 | out[o] = '\0'; |
| 368 | } |
| 369 | |
| 370 | static int run_argv(char *const argv[], buf_t *out, int timeout_s) |
| 371 | { |
| 372 | SECURITY_ATTRIBUTES sa; |
| 373 | HANDLE rd = NULL, wr = NULL; |
| 374 | STARTUPINFOA si; |
| 375 | PROCESS_INFORMATION pi; |
| 376 | char cmdline[4096]; |
| 377 | size_t used = 0; |
| 378 | DWORD waited; |
| 379 | DWORD ticks = 0; |
| 380 | int rc = -1; |
| 381 | |
| 382 | memset(&sa, 0, sizeof(sa)); |
| 383 | sa.nLength = sizeof(sa); |
| 384 | sa.bInheritHandle = TRUE; |
| 385 | if (!CreatePipe(&rd, &wr, &sa, 0)) return -1; |
| 386 | SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0); |
| 387 | |
| 388 | cmdline[0] = '\0'; |
| 389 | { |
| 390 | int i; |
| 391 | for (i = 0; argv[i]; i++) { |
| 392 | char q[1200]; |
| 393 | size_t need; |
| 394 | win_quote(argv[i], q, sizeof(q)); |
| 395 | need = strlen(q) + 2; |
| 396 | if (used + need + 1 >= sizeof(cmdline)) break; |
| 397 | if (used) cmdline[used++] = ' '; |
| 398 | memcpy(cmdline + used, q, strlen(q)); |
| 399 | used += strlen(q); |
| 400 | cmdline[used] = '\0'; |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | memset(&si, 0, sizeof(si)); |
| 405 | si.cb = sizeof(si); |
| 406 | si.dwFlags = STARTF_USESTDHANDLES; |
| 407 | si.hStdOutput = wr; |
| 408 | si.hStdError = wr; |
| 409 | si.hStdInput = NULL; |
| 410 | memset(&pi, 0, sizeof(pi)); |
| 411 | |
| 412 | if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, |
| 413 | NULL, NULL, &si, &pi)) { |
| 414 | CloseHandle(rd); |
| 415 | CloseHandle(wr); |
| 416 | return -1; |
| 417 | } |
| 418 | CloseHandle(wr); |
| 419 | |
| 420 | for (;;) { |
| 421 | DWORD avail = 0; |
| 422 | char tmp[4096]; |
| 423 | DWORD got = 0; |
| 424 | if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break; |
| 425 | if (avail == 0) { |
| 426 | waited = WaitForSingleObject(pi.hProcess, 20); |
| 427 | if (waited == WAIT_OBJECT_0) { |
| 428 | /* one last drain */ |
| 429 | if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break; |
| 430 | if (avail == 0) break; |
| 431 | } else if (timeout_s > 0 && waited == WAIT_TIMEOUT) { |
| 432 | if (++ticks > (DWORD)timeout_s * 50) { |
| 433 | TerminateProcess(pi.hProcess, 1); |
| 434 | break; |
| 435 | } |
| 436 | } |
| 437 | continue; |
| 438 | } |
| 439 | if (avail > sizeof(tmp)) avail = sizeof(tmp); |
| 440 | if (!ReadFile(rd, tmp, avail, &got, NULL) || got == 0) break; |
| 441 | if (out) buf_add(out, tmp, got); |
| 442 | } |
| 443 | |
| 444 | if (WaitForSingleObject(pi.hProcess, (DWORD)(timeout_s > 0 ? timeout_s : 20) * 1000u) |
| 445 | != WAIT_OBJECT_0) { |
| 446 | TerminateProcess(pi.hProcess, 1); |
| 447 | WaitForSingleObject(pi.hProcess, 2000); |
| 448 | } |
| 449 | { |
| 450 | DWORD code = 1; |
| 451 | GetExitCodeProcess(pi.hProcess, &code); |
| 452 | rc = (int)code; |
| 453 | } |
| 454 | CloseHandle(pi.hProcess); |
| 455 | CloseHandle(pi.hThread); |
| 456 | CloseHandle(rd); |
| 457 | return rc; |
| 458 | } |
| 459 | |
| 460 | #else /* POSIX */ |
| 461 | |
| 462 | static int run_argv(char *const argv[], buf_t *out, int timeout_s) |
| 463 | { |
| 464 | int fds[2]; |
| 465 | pid_t pid; |
| 466 | int status = 0; |
| 467 | int timed_out = 0; |
| 468 | time_t started; |
| 469 | char *child_env_ok; |
| 470 | |
| 471 | if (pipe(fds) != 0) return -1; |
| 472 | |
| 473 | pid = fork(); |
| 474 | if (pid < 0) { |
| 475 | close(fds[0]); |
| 476 | close(fds[1]); |
| 477 | return -1; |
| 478 | } |
| 479 | |
| 480 | if (pid == 0) { |
| 481 | /* Child: stdout+stderr into the pipe, stdin from /dev/null so nothing |
| 482 | * can ever block waiting for a password prompt. */ |
| 483 | int devnull = open("/dev/null", O_RDONLY); |
| 484 | if (devnull >= 0) { |
| 485 | dup2(devnull, STDIN_FILENO); |
| 486 | if (devnull != STDIN_FILENO) close(devnull); |
| 487 | } |
| 488 | dup2(fds[1], STDOUT_FILENO); |
| 489 | dup2(fds[1], STDERR_FILENO); |
| 490 | close(fds[0]); |
| 491 | close(fds[1]); |
| 492 | execvp(argv[0], argv); |
| 493 | _exit(127); |
| 494 | } |
| 495 | |
| 496 | close(fds[1]); |
| 497 | child_env_ok = (char *)""; /* keep the compiler quiet about unused locals */ |
| 498 | (void)child_env_ok; |
| 499 | started = time(NULL); |
| 500 | |
| 501 | for (;;) { |
| 502 | struct pollfd pfd; |
| 503 | char tmp[4096]; |
| 504 | ssize_t n; |
| 505 | int pr; |
| 506 | |
| 507 | pfd.fd = fds[0]; |
| 508 | pfd.events = POLLIN; |
| 509 | pfd.revents = 0; |
| 510 | pr = poll(&pfd, 1, 100); |
| 511 | if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) { |
| 512 | n = read(fds[0], tmp, sizeof(tmp)); |
| 513 | if (n > 0) { |
| 514 | if (out) buf_add(out, tmp, (size_t)n); |
| 515 | continue; |
| 516 | } |
| 517 | if (n == 0) break; |
| 518 | } |
| 519 | if (timeout_s > 0 && (time(NULL) - started) > timeout_s) { |
| 520 | timed_out = 1; |
| 521 | kill(pid, SIGKILL); |
| 522 | break; |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | close(fds[0]); |
| 527 | |
| 528 | while (waitpid(pid, &status, 0) < 0) { |
| 529 | if (errno != EINTR) break; |
| 530 | } |
| 531 | |
| 532 | if (timed_out) return -1; |
| 533 | if (WIFEXITED(status)) return WEXITSTATUS(status); |
| 534 | return -1; |
| 535 | } |
| 536 | |
| 537 | #endif |
| 538 | |
| 539 | /* git -C <repo> ... */ |
| 540 | static int run_git(const char *repo, char *const extra[], buf_t *out, int timeout_s) |
| 541 | { |
| 542 | char *argv[16]; |
| 543 | int i = 0; |
| 544 | int rc; |
| 545 | |
| 546 | argv[i++] = (char *)"git"; |
| 547 | argv[i++] = (char *)"-C"; |
| 548 | argv[i++] = (char *)repo; |
| 549 | while (*extra && i < 14) argv[i++] = *extra++; |
| 550 | argv[i] = NULL; |
| 551 | |
| 552 | rc = run_argv(argv, out, timeout_s); |
| 553 | return rc; |
| 554 | } |
| 555 | |
| 556 | /* ------------------------------------------------------------------ */ |
| 557 | /* Repository model */ |
| 558 | /* ------------------------------------------------------------------ */ |
| 559 | |
| 560 | typedef struct { |
| 561 | char path[1024]; |
| 562 | char name[256]; |
| 563 | char root[768]; |
| 564 | char branch[256]; |
| 565 | char upstream[512]; /* redacted */ |
| 566 | char remote[512]; /* origin URL, userinfo stripped */ |
| 567 | int ahead; |
| 568 | int behind; |
| 569 | int dirty; /* changed entries (tracked + untracked) */ |
| 570 | int untracked; |
| 571 | int staged; |
| 572 | int conflicted; |
| 573 | int stash; |
| 574 | int detached; |
| 575 | int no_upstream; |
| 576 | int unborn; |
| 577 | int detached_ok; |
| 578 | long long last_ct; |
| 579 | char last_hash[48]; |
| 580 | char last_subject[300]; |
| 581 | } repo_t; |
| 582 | |
| 583 | static repo_t g_repos[MAX_REPOS]; |
| 584 | static int g_repo_count; |
| 585 | |
| 586 | typedef struct { |
| 587 | char root[768]; /* as configured, for display */ |
| 588 | char canon[768]; /* realpath() form, for the prefix check */ |
| 589 | int exists; |
| 590 | int count; |
| 591 | int truncated; |
| 592 | } rootstat_t; |
| 593 | |
| 594 | static rootstat_t g_roots[MAX_ROOTS]; |
| 595 | static int g_root_count; |
| 596 | |
| 597 | /* ------------------------------------------------------------------ */ |
| 598 | /* Discovery */ |
| 599 | /* ------------------------------------------------------------------ */ |
| 600 | |
| 601 | #if defined(_WIN32) |
| 602 | # define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) |
| 603 | # define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG) |
| 604 | #else |
| 605 | # define SX_ISDIR(m) S_ISDIR(m) |
| 606 | # define SX_ISREG(m) S_ISREG(m) |
| 607 | #endif |
| 608 | |
| 609 | static int path_exists(const char *p) |
| 610 | { |
| 611 | #if defined(_WIN32) |
| 612 | return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; |
| 613 | #else |
| 614 | struct stat st; |
| 615 | return stat(p, &st) == 0; |
| 616 | #endif |
| 617 | } |
| 618 | |
| 619 | /* A repo is a directory that has a .git entry which is either a directory |
| 620 | * (normal clone) or a regular file (worktree / submodule pointer). */ |
| 621 | static int is_repo_dir(const char *dir) |
| 622 | { |
| 623 | char gp[1200]; |
| 624 | #if defined(_WIN32) |
| 625 | DWORD attr; |
| 626 | #else |
| 627 | struct stat st; |
| 628 | #endif |
| 629 | |
| 630 | snprintf(gp, sizeof(gp), "%s/.git", dir); |
| 631 | #if defined(_WIN32) |
| 632 | attr = GetFileAttributesA(gp); |
| 633 | if (attr == INVALID_FILE_ATTRIBUTES) return 0; |
| 634 | return (attr & FILE_ATTRIBUTE_DIRECTORY) || !(attr & FILE_ATTRIBUTE_DIRECTORY); |
| 635 | #else |
| 636 | if (lstat(gp, &st) != 0) { |
| 637 | if (stat(gp, &st) != 0) return 0; |
| 638 | } |
| 639 | return SX_ISDIR(st.st_mode) || SX_ISREG(st.st_mode); |
| 640 | #endif |
| 641 | } |
| 642 | |
| 643 | static const char *base_name(const char *p) |
| 644 | { |
| 645 | const char *s = strrchr(p, '/'); |
| 646 | #if defined(_WIN32) |
| 647 | const char *b = strrchr(p, '\\'); |
| 648 | if (b && (!s || b > s)) s = b; |
| 649 | #endif |
| 650 | return s ? s + 1 : p; |
| 651 | } |
| 652 | |
| 653 | static void repo_add(const char *dir, const char *root) |
| 654 | { |
| 655 | repo_t *r; |
| 656 | |
| 657 | if (g_repo_count >= MAX_REPOS) return; |
| 658 | r = &g_repos[g_repo_count++]; |
| 659 | memset(r, 0, sizeof(*r)); |
| 660 | str_copy(r->path, sizeof(r->path), dir); |
| 661 | str_copy(r->name, sizeof(r->name), base_name(dir)); |
| 662 | str_copy(r->root, sizeof(r->root), root); |
| 663 | } |
| 664 | |
| 665 | /* Depth-limited walk. A repository is a leaf: once found we do not descend into |
| 666 | * it, because a node's repos are the unit you want to see, not every vendored |
| 667 | * checkout inside them. Entry budget is per root (lesson: a shared budget hides |
| 668 | * the second root entirely). */ |
| 669 | static void walk_dir(const char *dir, const char *root, int depth, |
| 670 | int *entries, int *truncated) |
| 671 | { |
| 672 | if (depth > MAX_DEPTH) return; |
| 673 | if (*truncated) return; |
| 674 | |
| 675 | if (is_repo_dir(dir)) { |
| 676 | repo_add(dir, root); |
| 677 | return; |
| 678 | } |
| 679 | if (depth == MAX_DEPTH) return; |
| 680 | |
| 681 | { |
| 682 | #if defined(_WIN32) |
| 683 | WIN32_FIND_DATAA fd; |
| 684 | HANDLE h; |
| 685 | char pat[1400]; |
| 686 | snprintf(pat, sizeof(pat), "%s\\*", dir); |
| 687 | h = FindFirstFileA(pat, &fd); |
| 688 | if (h == INVALID_HANDLE_VALUE) return; |
| 689 | do { |
| 690 | char child[1400]; |
| 691 | if (fd.cFileName[0] == '.') continue; |
| 692 | if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; |
| 693 | if (strcmp(fd.cFileName, "node_modules") == 0) continue; |
| 694 | if (strcmp(fd.cFileName, "__pycache__") == 0) continue; |
| 695 | if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; } |
| 696 | snprintf(child, sizeof(child), "%s\\%s", dir, fd.cFileName); |
| 697 | walk_dir(child, root, depth + 1, entries, truncated); |
| 698 | } while (FindNextFileA(h, &fd)); |
| 699 | FindClose(h); |
| 700 | #else |
| 701 | DIR *d = opendir(dir); |
| 702 | struct dirent *e; |
| 703 | if (!d) return; |
| 704 | while ((e = readdir(d)) != NULL) { |
| 705 | char child[1400]; |
| 706 | struct stat st; |
| 707 | if (e->d_name[0] == '.') continue; |
| 708 | if (strcmp(e->d_name, "node_modules") == 0) continue; |
| 709 | if (strcmp(e->d_name, "__pycache__") == 0) continue; |
| 710 | snprintf(child, sizeof(child), "%s/%s", dir, e->d_name); |
| 711 | if (lstat(child, &st) != 0) continue; |
| 712 | if (!SX_ISDIR(st.st_mode)) continue; /* never follow symlinks */ |
| 713 | if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; } |
| 714 | walk_dir(child, root, depth + 1, entries, truncated); |
| 715 | } |
| 716 | closedir(d); |
| 717 | #endif |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | static void canon_path(const char *in, char *out, size_t sz); |
| 722 | static int path_exists(const char *p); |
| 723 | |
| 724 | static void root_add(const char *root, const char *sep_list_used) |
| 725 | { |
| 726 | (void)sep_list_used; |
| 727 | if (!root || !*root) return; |
| 728 | if (g_root_count >= MAX_ROOTS) return; |
| 729 | { |
| 730 | int i; |
| 731 | for (i = 0; i < g_root_count; i++) |
| 732 | if (strcmp(g_roots[i].root, root) == 0) return; |
| 733 | } |
| 734 | str_copy(g_roots[g_root_count].root, sizeof(g_roots[g_root_count].root), root); |
| 735 | canon_path(root, g_roots[g_root_count].canon, sizeof(g_roots[g_root_count].canon)); |
| 736 | g_roots[g_root_count].exists = 0; |
| 737 | g_roots[g_root_count].count = 0; |
| 738 | g_roots[g_root_count].truncated = 0; |
| 739 | g_root_count++; |
| 740 | } |
| 741 | |
| 742 | static void roots_from_env(const char *name, int posix_sep) |
| 743 | { |
| 744 | const char *v = getenv(name); |
| 745 | char buf[2048]; |
| 746 | char sep; |
| 747 | char *p; |
| 748 | char *start; |
| 749 | |
| 750 | if (!v || !*v) return; |
| 751 | snprintf(buf, sizeof(buf), "%s", v); |
| 752 | |
| 753 | #if defined(_WIN32) |
| 754 | sep = posix_sep ? ';' : ';'; |
| 755 | if (posix_sep) { |
| 756 | char *q = buf; |
| 757 | while ((q = strchr(q, ':')) != NULL) { |
| 758 | /* a drive-letter colon is followed by a separator, not a path */ |
| 759 | if (q[1] == '\\' || q[1] == '/') { q++; continue; } |
| 760 | *q = ';'; |
| 761 | q++; |
| 762 | } |
| 763 | } |
| 764 | #else |
| 765 | sep = ':'; |
| 766 | (void)posix_sep; |
| 767 | #endif |
| 768 | |
| 769 | start = buf; |
| 770 | for (p = buf; ; p++) { |
| 771 | if (*p == sep || *p == '\0') { |
| 772 | char saved = *p; |
| 773 | *p = '\0'; |
| 774 | str_trim(start); |
| 775 | root_add(start, sep == ';' ? ";" : ":"); |
| 776 | if (saved == '\0') break; |
| 777 | start = p + 1; |
| 778 | } |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | static void collect_roots(void) |
| 783 | { |
| 784 | const char *home = getenv("HOME"); |
| 785 | |
| 786 | const char *only = getenv("GITSTAT_ONLY_ROOTS"); |
| 787 | g_root_count = 0; |
| 788 | |
| 789 | /* GITSTAT_ONLY_ROOTS=1 makes GITSTAT_ROOTS the complete list. It exists for |
| 790 | * two callers: a node that wants an explicit allowlist, and the test suite, |
| 791 | * which must see a fixture tree and nothing else. The default behaviour is |
| 792 | * still the documented one: the platform roots plus GITSTAT_ROOTS. */ |
| 793 | if (only && *only && strcmp(only, "0") != 0) { |
| 794 | roots_from_env("GITSTAT_ROOTS", 1); |
| 795 | return; |
| 796 | } |
| 797 | |
| 798 | #if defined(_WIN32) |
| 799 | home = getenv("USERPROFILE"); |
| 800 | if (!home || !*home) home = getenv("HOMEDRIVE"); |
| 801 | root_add(home, ";"); |
| 802 | if (path_exists("D:\\codebases")) root_add("D:\\codebases", ";"); |
| 803 | if (path_exists("C:\\codebases")) root_add("C:\\codebases", ";"); |
| 804 | roots_from_env("GITSTAT_ROOTS", 1); |
| 805 | #else |
| 806 | root_add("/workspace", ":"); |
| 807 | root_add("/codebases", ":"); |
| 808 | root_add(home, ":"); |
| 809 | roots_from_env("GITSTAT_ROOTS", 1); |
| 810 | #endif |
| 811 | } |
| 812 | |
| 813 | /* ------------------------------------------------------------------ */ |
| 814 | /* git queries per repo */ |
| 815 | /* ------------------------------------------------------------------ */ |
| 816 | |
| 817 | /* status --porcelain=v2 --branch. Header lines carry branch state; the rest are |
| 818 | * one changed entry each. Lines look like: |
| 819 | * # branch.oid <hash> (all zeros when unborn) |
| 820 | * # branch.head <name>|(detached) |
| 821 | * # branch.upstream <ref> (absent when no upstream) |
| 822 | * # branch.ab +N -M (absent when no upstream) |
| 823 | * 1 XY sub mH mI mW hH hI path |
| 824 | * 2 XY ... path |
| 825 | * u XY ... path |
| 826 | * ? path |
| 827 | * ! path |
| 828 | */ |
| 829 | static void parse_status(const char *text, repo_t *r) |
| 830 | { |
| 831 | const char *p = text; |
| 832 | char line[1200]; |
| 833 | |
| 834 | while (*p) { |
| 835 | size_t n = 0; |
| 836 | while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++; |
| 837 | line[n] = '\0'; |
| 838 | if (*p == '\n') p++; |
| 839 | str_trim(line); |
| 840 | if (!line[0]) continue; |
| 841 | |
| 842 | if (line[0] == '#') { |
| 843 | const char *v = line + 1; |
| 844 | while (*v == ' ') v++; |
| 845 | if (strncmp(v, "branch.head ", 12) == 0) { |
| 846 | const char *b = v + 12; |
| 847 | if (strcmp(b, "(detached)") == 0) { |
| 848 | r->detached = 1; |
| 849 | str_copy(r->branch, sizeof(r->branch), "detached"); |
| 850 | } else { |
| 851 | str_copy(r->branch, sizeof(r->branch), b); |
| 852 | } |
| 853 | } else if (strncmp(v, "branch.upstream ", 16) == 0) { |
| 854 | char clean[512]; |
| 855 | redact_url(v + 16, clean, sizeof(clean)); |
| 856 | str_copy(r->upstream, sizeof(r->upstream), clean); |
| 857 | } else if (strncmp(v, "branch.ab ", 10) == 0) { |
| 858 | const char *ab = v + 10; |
| 859 | int ahead = 0, behind = 0; |
| 860 | if (sscanf(ab, "+%d -%d", &ahead, &behind) == 2) { |
| 861 | r->ahead = ahead; |
| 862 | r->behind = behind; |
| 863 | } else if (sscanf(ab, "+%d -%d", &ahead, &behind) == 1) { |
| 864 | r->ahead = ahead; |
| 865 | } |
| 866 | } else if (strncmp(v, "branch.oid ", 11) == 0) { |
| 867 | const char *oid = v + 11; |
| 868 | if (strcmp(oid, "(initial)") == 0) r->unborn = 1; |
| 869 | } |
| 870 | continue; |
| 871 | } |
| 872 | |
| 873 | if (line[0] == '?') { |
| 874 | r->dirty++; |
| 875 | r->untracked++; |
| 876 | } else if (line[0] == '!') { |
| 877 | /* ignored: not a change */ |
| 878 | } else if (line[0] == '1' || line[0] == '2') { |
| 879 | r->dirty++; |
| 880 | if (line[0] == '1') { |
| 881 | char xy[8] = { 0, 0, 0 }; |
| 882 | if (sscanf(line, "1 %2s", xy) == 1) { |
| 883 | if (xy[0] != '.' && xy[0] != '\0') r->staged++; |
| 884 | } |
| 885 | } else { |
| 886 | r->staged++; |
| 887 | } |
| 888 | } else if (line[0] == 'u') { |
| 889 | r->dirty++; |
| 890 | r->conflicted++; |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | if (!r->unborn && r->branch[0] && strcmp(r->branch, "detached") != 0 && !r->upstream[0]) |
| 895 | r->no_upstream = 1; |
| 896 | if (r->unborn) r->no_upstream = 1; |
| 897 | } |
| 898 | |
| 899 | /* "1 XY ..." -> XY codes for the detail drawer. */ |
| 900 | static void status_code(const char *line, char *out, size_t sz) |
| 901 | { |
| 902 | if (line[0] == '?') { str_copy(out, sz, "\?\?"); return; } |
| 903 | if (line[0] == '!') { str_copy(out, sz, "!!"); return; } |
| 904 | if (line[0] == 'u') { str_copy(out, sz, "UU"); return; } |
| 905 | if ((line[0] == '1' || line[0] == '2') && line[1] == ' ') |
| 906 | str_copy(out, sz, line + 2); |
| 907 | else |
| 908 | str_copy(out, sz, "--"); |
| 909 | } |
| 910 | |
| 911 | /* Path of a v2 status line: everything after the fixed fields. */ |
| 912 | static void status_path(const char *line, char *out, size_t sz) |
| 913 | { |
| 914 | const char *p = line; |
| 915 | int fields; |
| 916 | |
| 917 | out[0] = '\0'; |
| 918 | if (line[0] == '?') { str_copy(out, sz, line + 2); return; } |
| 919 | if (line[0] == '!') { str_copy(out, sz, line + 2); return; } |
| 920 | if (line[0] == 'u') fields = 10; |
| 921 | else if (line[0] == '2') fields = 9; |
| 922 | else if (line[0] == '1') fields = 8; |
| 923 | else { str_copy(out, sz, line); return; } |
| 924 | |
| 925 | for (; fields > 0 && *p; fields--) { |
| 926 | while (*p && *p != ' ') p++; |
| 927 | while (*p == ' ') p++; |
| 928 | } |
| 929 | str_copy(out, sz, p); |
| 930 | if (line[0] == '2') { |
| 931 | /* rename records carry "old\tnew" */ |
| 932 | char *tab = strchr(out, '\t'); |
| 933 | if (tab) memmove(out, tab + 1, strlen(tab + 1) + 1); |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | /* Three child processes per repository, not four: the origin URL is only read |
| 938 | * for the repository you actually open, not for every row of the board. On a Mac |
| 939 | * with fifty checkouts that is most of a second saved per row. (--show-stash |
| 940 | * would fold the stash count into the status header too, but only in the human |
| 941 | * output - porcelain v2 never carries it, so `stash list` stays.) */ |
| 942 | static void query_repo(repo_t *r, int with_remote) |
| 943 | { |
| 944 | buf_t out; |
| 945 | char *status_args[] = { (char *)"status", (char *)"--porcelain=v2", |
| 946 | (char *)"--branch", (char *)"--untracked-files=normal", NULL }; |
| 947 | char *stash_args[] = { (char *)"stash", (char *)"list", (char *)"--format=%gd", NULL }; |
| 948 | char *log_args[] = { (char *)"log", (char *)"-1", (char *)"--format=%H%x09%ct%x09%s", NULL }; |
| 949 | |
| 950 | buf_init(&out); |
| 951 | if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) |
| 952 | parse_status(buf_str(&out), r); |
| 953 | buf_free(&out); |
| 954 | |
| 955 | buf_init(&out); |
| 956 | if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) { |
| 957 | char *p = out.p; |
| 958 | char *t1 = strchr(p, '\t'); |
| 959 | if (t1) { |
| 960 | *t1 = '\0'; |
| 961 | str_copy(r->last_hash, sizeof(r->last_hash), p); |
| 962 | { |
| 963 | char *t2 = strchr(t1 + 1, '\t'); |
| 964 | if (t2) { |
| 965 | *t2 = '\0'; |
| 966 | r->last_ct = atoll(t1 + 1); |
| 967 | str_copy(r->last_subject, sizeof(r->last_subject), t2 + 1); |
| 968 | } else { |
| 969 | r->last_ct = atoll(t1 + 1); |
| 970 | } |
| 971 | } |
| 972 | str_trim(r->last_subject); |
| 973 | } |
| 974 | } |
| 975 | buf_free(&out); |
| 976 | |
| 977 | buf_init(&out); |
| 978 | if (run_git(r->path, stash_args, &out, GIT_TIMEOUT_S) >= 0) { |
| 979 | const char *p = out.p; |
| 980 | while (p && *p) { |
| 981 | const char *nl = strchr(p, '\n'); |
| 982 | if (!nl) break; |
| 983 | if (nl > p) r->stash++; |
| 984 | p = nl + 1; |
| 985 | } |
| 986 | } |
| 987 | buf_free(&out); |
| 988 | |
| 989 | if (with_remote) { |
| 990 | buf_init(&out); |
| 991 | { |
| 992 | char *cfg_args[] = { (char *)"config", (char *)"--get", |
| 993 | (char *)"remote.origin.url", NULL }; |
| 994 | if (run_git(r->path, cfg_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) { |
| 995 | char raw[512]; |
| 996 | char clean[512]; |
| 997 | str_copy(raw, sizeof(raw), out.p); |
| 998 | str_trim(raw); |
| 999 | redact_url(raw, clean, sizeof(clean)); |
| 1000 | str_copy(r->remote, sizeof(r->remote), clean); |
| 1001 | } |
| 1002 | } |
| 1003 | buf_free(&out); |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | static int repo_cmp(const void *a, const void *b) |
| 1008 | { |
| 1009 | const repo_t *x = (const repo_t *)a; |
| 1010 | const repo_t *y = (const repo_t *)b; |
| 1011 | |
| 1012 | /* Dirty first (uncommitted work is the thing you came to see), then most |
| 1013 | * recently touched, then path. */ |
| 1014 | if ((x->dirty > 0) != (y->dirty > 0)) return x->dirty > 0 ? -1 : 1; |
| 1015 | if (x->dirty != y->dirty) return y->dirty - x->dirty; |
| 1016 | if (x->last_ct != y->last_ct) return (x->last_ct > y->last_ct) ? -1 : 1; |
| 1017 | return strcmp(x->path, y->path); |
| 1018 | } |
| 1019 | |
| 1020 | static void collect_repos(void) |
| 1021 | { |
| 1022 | int i; |
| 1023 | |
| 1024 | collect_roots(); |
| 1025 | g_repo_count = 0; |
| 1026 | |
| 1027 | for (i = 0; i < g_root_count; i++) { |
| 1028 | int entries = 0; |
| 1029 | int truncated = 0; |
| 1030 | int before = g_repo_count; |
| 1031 | |
| 1032 | g_roots[i].exists = path_exists(g_roots[i].root) ? 1 : 0; |
| 1033 | if (g_roots[i].exists) |
| 1034 | walk_dir(g_roots[i].root, g_roots[i].root, 0, &entries, &truncated); |
| 1035 | g_roots[i].truncated = truncated; |
| 1036 | g_roots[i].count = g_repo_count - before; |
| 1037 | } |
| 1038 | |
| 1039 | for (i = 0; i < g_repo_count; i++) query_repo(&g_repos[i], 0); |
| 1040 | |
| 1041 | if (g_repo_count > 1) |
| 1042 | qsort(g_repos, (size_t)g_repo_count, sizeof(repo_t), repo_cmp); |
| 1043 | } |
| 1044 | |
| 1045 | /* ------------------------------------------------------------------ */ |
| 1046 | /* Path allowlisting */ |
| 1047 | /* ------------------------------------------------------------------ */ |
| 1048 | |
| 1049 | /* realpath() cannot be handed a caller-sized buffer: glibc's fortified |
| 1050 | * wrapper aborts when the buffer is smaller than PATH_MAX, and the paths here |
| 1051 | * are keep-to-1024 bytes in a 1400-byte array. Ask realpath to allocate, then |
| 1052 | * copy into our own fixed array. */ |
| 1053 | static void canon_path(const char *in, char *out, size_t sz) |
| 1054 | { |
| 1055 | #if defined(_WIN32) |
| 1056 | if (!GetFullPathNameA(in, (DWORD)sz, out, NULL)) str_copy(out, sz, in); |
| 1057 | #else |
| 1058 | char *rp = realpath(in, NULL); |
| 1059 | if (rp) { |
| 1060 | str_copy(out, sz, rp); |
| 1061 | free(rp); |
| 1062 | } else { |
| 1063 | str_copy(out, sz, in); |
| 1064 | } |
| 1065 | #endif |
| 1066 | } |
| 1067 | |
| 1068 | static int under_root(const char *path) |
| 1069 | { |
| 1070 | int i; |
| 1071 | for (i = 0; i < g_root_count; i++) { |
| 1072 | /* Compare against the canonical root, not the configured string: on |
| 1073 | * macOS /tmp and /var are symlinks, so realpath("/tmp/x") is |
| 1074 | * "/private/tmp/x" and a raw prefix test would refuse every path. */ |
| 1075 | const char *r = g_roots[i].canon[0] ? g_roots[i].canon : g_roots[i].root; |
| 1076 | size_t n = strlen(r); |
| 1077 | if (n == 0) continue; |
| 1078 | if (strncmp(path, r, n) != 0) continue; |
| 1079 | if (path[n] == '\0' || path[n] == '/' || path[n] == '\\') return 1; |
| 1080 | } |
| 1081 | return 0; |
| 1082 | } |
| 1083 | |
| 1084 | /* A repo path is acceptable only when it canonicalises to somewhere under an |
| 1085 | * allowlisted root AND that directory carries a .git entry. This is the whole |
| 1086 | * authorisation model for the API: nothing outside the roots is ever read, and |
| 1087 | * no argument can walk upwards with "..". */ |
| 1088 | static int path_allowed(const char *requested, char *canon, size_t sz) |
| 1089 | { |
| 1090 | char tmp[1400]; |
| 1091 | |
| 1092 | if (!requested || !*requested) return 0; |
| 1093 | if (strstr(requested, "..")) return 0; |
| 1094 | |
| 1095 | collect_roots(); |
| 1096 | canon_path(requested, tmp, sizeof(tmp)); |
| 1097 | if (!under_root(tmp)) return 0; |
| 1098 | if (!is_repo_dir(tmp)) return 0; |
| 1099 | str_copy(canon, sz, tmp); |
| 1100 | return 1; |
| 1101 | } |
| 1102 | |
| 1103 | /* ------------------------------------------------------------------ */ |
| 1104 | /* JSON emitters */ |
| 1105 | /* ------------------------------------------------------------------ */ |
| 1106 | |
| 1107 | static void json_header(int status) |
| 1108 | { |
| 1109 | if (status == 403) |
| 1110 | fputs("Status: 403 Forbidden\r\n", stdout); |
| 1111 | else if (status == 400) |
| 1112 | fputs("Status: 400 Bad Request\r\n", stdout); |
| 1113 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1114 | "Cache-Control: no-store\r\n" |
| 1115 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1116 | } |
| 1117 | |
| 1118 | static void emit_repo(buf_t *b, const repo_t *r, int detail) |
| 1119 | { |
| 1120 | char at[40]; |
| 1121 | char up[512]; |
| 1122 | |
| 1123 | redact_url(r->upstream, up, sizeof(up)); |
| 1124 | utc_stamp((time_t)r->last_ct, at, sizeof(at)); |
| 1125 | |
| 1126 | buf_add(b, "{", 1); |
| 1127 | buf_puts(b, "\"path\":"); json_str(b, r->path); |
| 1128 | buf_puts(b, ",\"name\":"); json_str(b, r->name); |
| 1129 | buf_puts(b, ",\"root\":"); json_str(b, r->root); |
| 1130 | buf_puts(b, ",\"branch\":"); json_str(b, r->branch); |
| 1131 | buf_puts(b, ",\"upstream\":"); json_str(b, up); |
| 1132 | buf_puts(b, ",\"remote\":"); json_str(b, r->remote); |
| 1133 | buf_printf(b, ",\"ahead\":%d,\"behind\":%d,\"dirty\":%d,\"untracked\":%d," |
| 1134 | "\"staged\":%d,\"conflicted\":%d,\"stash\":%d", |
| 1135 | r->ahead, r->behind, r->dirty, r->untracked, |
| 1136 | r->staged, r->conflicted, r->stash); |
| 1137 | buf_printf(b, ",\"detached\":%s,\"no_upstream\":%s,\"unborn\":%s", |
| 1138 | r->detached ? "true" : "false", |
| 1139 | r->no_upstream ? "true" : "false", |
| 1140 | r->unborn ? "true" : "false"); |
| 1141 | buf_puts(b, ",\"last_commit\":{"); |
| 1142 | buf_puts(b, "\"hash\":"); json_str(b, r->last_hash); |
| 1143 | buf_puts(b, ",\"short\":"); |
| 1144 | { |
| 1145 | char sh[12]; |
| 1146 | str_copy(sh, sizeof(sh), r->last_hash); |
| 1147 | json_str(b, sh); |
| 1148 | } |
| 1149 | buf_printf(b, ",\"ct\":%lld", r->last_ct); |
| 1150 | buf_puts(b, ",\"at\":"); json_str(b, at); |
| 1151 | buf_puts(b, ",\"subject\":"); json_str(b, r->last_subject); |
| 1152 | buf_puts(b, "}"); |
| 1153 | (void)detail; |
| 1154 | buf_add(b, "}", 1); |
| 1155 | } |
| 1156 | |
| 1157 | static void print_repos(void) |
| 1158 | { |
| 1159 | buf_t b; |
| 1160 | int i; |
| 1161 | char now[40]; |
| 1162 | int dirty = 0, ahead = 0, behind = 0, stashed = 0, detached = 0; |
| 1163 | |
| 1164 | for (i = 0; i < g_repo_count; i++) { |
| 1165 | if (g_repos[i].dirty > 0) dirty++; |
| 1166 | if (g_repos[i].ahead > 0) ahead++; |
| 1167 | if (g_repos[i].behind > 0) behind++; |
| 1168 | if (g_repos[i].stash > 0) stashed += g_repos[i].stash; |
| 1169 | if (g_repos[i].detached) detached++; |
| 1170 | } |
| 1171 | utc_stamp(time(NULL), now, sizeof(now)); |
| 1172 | |
| 1173 | buf_init(&b); |
| 1174 | buf_printf(&b, "{\"ok\":true,\"action\":\"repos\",\"count\":%d", g_repo_count); |
| 1175 | buf_printf(&b, ",\"table_capped\":%s", g_repo_count >= MAX_REPOS ? "true" : "false"); |
| 1176 | buf_printf(&b, ",\"summary\":{\"dirty\":%d,\"ahead\":%d,\"behind\":%d," |
| 1177 | "\"stashes\":%d,\"detached\":%d}", |
| 1178 | dirty, ahead, behind, stashed, detached); |
| 1179 | buf_puts(&b, ",\"checked_at\":"); json_str(&b, now); |
| 1180 | buf_puts(&b, ",\"roots\":["); |
| 1181 | for (i = 0; i < g_root_count; i++) { |
| 1182 | if (i) buf_add(&b, ",", 1); |
| 1183 | buf_add(&b, "{", 1); |
| 1184 | buf_puts(&b, "\"root\":"); json_str(&b, g_roots[i].root); |
| 1185 | buf_printf(&b, ",\"exists\":%s,\"count\":%d,\"truncated\":%s", |
| 1186 | g_roots[i].exists ? "true" : "false", g_roots[i].count, |
| 1187 | g_roots[i].truncated ? "true" : "false"); |
| 1188 | buf_add(&b, "}", 1); |
| 1189 | } |
| 1190 | buf_puts(&b, "],\"repos\":["); |
| 1191 | for (i = 0; i < g_repo_count; i++) { |
| 1192 | if (i) buf_add(&b, ",", 1); |
| 1193 | emit_repo(&b, &g_repos[i], 0); |
| 1194 | } |
| 1195 | buf_puts(&b, "]}\n"); |
| 1196 | fputs(buf_str(&b), stdout); |
| 1197 | buf_free(&b); |
| 1198 | } |
| 1199 | |
| 1200 | static int print_repo_detail(const char *path) |
| 1201 | { |
| 1202 | char canon[1400]; |
| 1203 | repo_t *r = NULL; |
| 1204 | buf_t b; |
| 1205 | buf_t out; |
| 1206 | int i; |
| 1207 | char at[40]; |
| 1208 | |
| 1209 | if (!path_allowed(path, canon, sizeof(canon))) { |
| 1210 | json_header(403); |
| 1211 | fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout); |
| 1212 | return 0; |
| 1213 | } |
| 1214 | |
| 1215 | /* Prefer the record we already measured; fall back to measuring it now when |
| 1216 | * the path was not part of the (budgeted) discovery walk. */ |
| 1217 | for (i = 0; i < g_repo_count; i++) { |
| 1218 | if (strcmp(g_repos[i].path, canon) == 0) { r = &g_repos[i]; break; } |
| 1219 | } |
| 1220 | if (r) query_repo(r, 1); |
| 1221 | if (!r) { |
| 1222 | if (g_repo_count >= MAX_REPOS) { |
| 1223 | json_header(400); |
| 1224 | fputs("{\"ok\":false,\"error\":\"repository table full\"}\n", stdout); |
| 1225 | return 0; |
| 1226 | } |
| 1227 | r = &g_repos[g_repo_count]; |
| 1228 | memset(r, 0, sizeof(*r)); |
| 1229 | str_copy(r->path, sizeof(r->path), canon); |
| 1230 | str_copy(r->name, sizeof(r->name), base_name(canon)); |
| 1231 | { |
| 1232 | /* Keep the row shaped like a discovered one: attribute it to the |
| 1233 | * root it actually sits under rather than reporting an empty root. */ |
| 1234 | int k; |
| 1235 | for (k = 0; k < g_root_count; k++) { |
| 1236 | const char *rp = g_roots[k].canon[0] ? g_roots[k].canon : g_roots[k].root; |
| 1237 | size_t n = strlen(rp); |
| 1238 | if (n && strncmp(canon, rp, n) == 0 && |
| 1239 | (canon[n] == '\0' || canon[n] == '/' || canon[n] == '\\')) { |
| 1240 | str_copy(r->root, sizeof(r->root), g_roots[k].root); |
| 1241 | break; |
| 1242 | } |
| 1243 | } |
| 1244 | } |
| 1245 | query_repo(r, 1); |
| 1246 | g_repo_count++; |
| 1247 | } |
| 1248 | |
| 1249 | buf_init(&b); |
| 1250 | buf_printf(&b, "{\"ok\":true,\"action\":\"repo\",\"repo\":"); |
| 1251 | emit_repo(&b, r, 1); |
| 1252 | |
| 1253 | /* changed files, max MAX_CHANGED */ |
| 1254 | { |
| 1255 | char *status_args[] = { (char *)"status", (char *)"--porcelain=v2", |
| 1256 | (char *)"--untracked-files=normal", NULL }; |
| 1257 | int shown = 0, total = 0; |
| 1258 | int trunc = 0; |
| 1259 | |
| 1260 | buf_init(&out); |
| 1261 | buf_puts(&b, ",\"changed\":["); |
| 1262 | if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) { |
| 1263 | const char *p = out.p; |
| 1264 | char line[1200]; |
| 1265 | while (p && *p) { |
| 1266 | size_t n = 0; |
| 1267 | while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++; |
| 1268 | line[n] = '\0'; |
| 1269 | if (*p == '\n') p++; |
| 1270 | str_trim(line); |
| 1271 | if (!line[0] || line[0] == '#') continue; |
| 1272 | total++; |
| 1273 | if (shown >= MAX_CHANGED) { trunc = 1; continue; } |
| 1274 | { |
| 1275 | char code[8], fp[900]; |
| 1276 | status_code(line, code, sizeof(code)); |
| 1277 | status_path(line, fp, sizeof(fp)); |
| 1278 | if (shown) buf_add(&b, ",", 1); |
| 1279 | buf_add(&b, "{", 1); |
| 1280 | buf_puts(&b, "\"code\":"); json_str(&b, code); |
| 1281 | buf_puts(&b, ",\"path\":"); json_str(&b, fp); |
| 1282 | buf_add(&b, "}", 1); |
| 1283 | shown++; |
| 1284 | } |
| 1285 | } |
| 1286 | } |
| 1287 | buf_free(&out); |
| 1288 | buf_printf(&b, "],\"changed_count\":%d,\"changed_truncated\":%s", |
| 1289 | total, trunc ? "true" : "false"); |
| 1290 | } |
| 1291 | |
| 1292 | /* recent commits */ |
| 1293 | { |
| 1294 | char *log_args[] = { (char *)"log", (char *)"-20", |
| 1295 | (char *)"--format=%H%x09%ct%x09%an%x09%s", NULL }; |
| 1296 | int n = 0; |
| 1297 | |
| 1298 | buf_init(&out); |
| 1299 | buf_puts(&b, ",\"commits\":["); |
| 1300 | if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0) { |
| 1301 | const char *p = out.p; |
| 1302 | while (p && *p && n < MAX_COMMITS) { |
| 1303 | const char *nl = strchr(p, '\n'); |
| 1304 | size_t len = nl ? (size_t)(nl - p) : strlen(p); |
| 1305 | char line[1500]; |
| 1306 | if (len >= sizeof(line)) len = sizeof(line) - 1; |
| 1307 | memcpy(line, p, len); |
| 1308 | line[len] = '\0'; |
| 1309 | p = nl ? nl + 1 : p + len; |
| 1310 | if (!line[0]) continue; |
| 1311 | { |
| 1312 | char *t1 = strchr(line, '\t'); |
| 1313 | char *t2; |
| 1314 | char *t3; |
| 1315 | if (!t1) continue; |
| 1316 | *t1 = '\0'; |
| 1317 | t2 = strchr(t1 + 1, '\t'); |
| 1318 | if (!t2) continue; |
| 1319 | *t2 = '\0'; |
| 1320 | t3 = strchr(t2 + 1, '\t'); |
| 1321 | if (t3) *t3 = '\0'; |
| 1322 | utc_stamp((time_t)atoll(t1 + 1), at, sizeof(at)); |
| 1323 | if (n) buf_add(&b, ",", 1); |
| 1324 | buf_add(&b, "{", 1); |
| 1325 | buf_puts(&b, "\"hash\":"); json_str(&b, line); |
| 1326 | buf_printf(&b, ",\"ct\":%lld", (long long)atoll(t1 + 1)); |
| 1327 | buf_puts(&b, ",\"author\":"); json_str(&b, t2 + 1); |
| 1328 | buf_puts(&b, ",\"subject\":"); json_str(&b, t3 ? t3 + 1 : ""); |
| 1329 | buf_add(&b, "}", 1); |
| 1330 | n++; |
| 1331 | } |
| 1332 | } |
| 1333 | } |
| 1334 | buf_free(&out); |
| 1335 | buf_add(&b, "]", 1); |
| 1336 | } |
| 1337 | |
| 1338 | buf_puts(&b, "}\n"); |
| 1339 | fputs(buf_str(&b), stdout); |
| 1340 | buf_free(&b); |
| 1341 | return 0; |
| 1342 | } |
| 1343 | |
| 1344 | static int do_fetch(const char *path, int *status_out) |
| 1345 | { |
| 1346 | char canon[1400]; |
| 1347 | buf_t b; |
| 1348 | buf_t out; |
| 1349 | int rc; |
| 1350 | repo_t tmp; |
| 1351 | |
| 1352 | if (!path_allowed(path, canon, sizeof(canon))) { |
| 1353 | json_header(403); |
| 1354 | fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout); |
| 1355 | return 0; |
| 1356 | } |
| 1357 | |
| 1358 | json_header(0); |
| 1359 | if (!getenv("GITSTAT_ALLOW_FETCH") || strcmp(getenv("GITSTAT_ALLOW_FETCH"), "1") != 0) { |
| 1360 | buf_init(&b); |
| 1361 | buf_puts(&b, "{\"ok\":false,\"error\":\"fetch is disabled on this node\"," |
| 1362 | "\"hint\":\"set GITSTAT_ALLOW_FETCH=1 to enable git fetch --prune\"}\n"); |
| 1363 | fputs(buf_str(&b), stdout); |
| 1364 | buf_free(&b); |
| 1365 | return 0; |
| 1366 | } |
| 1367 | |
| 1368 | { |
| 1369 | char *fetch_args[] = { (char *)"fetch", (char *)"--prune", NULL }; |
| 1370 | buf_init(&out); |
| 1371 | rc = run_git(canon, fetch_args, &out, FETCH_TIMEOUT_S); |
| 1372 | |
| 1373 | memset(&tmp, 0, sizeof(tmp)); |
| 1374 | str_copy(tmp.path, sizeof(tmp.path), canon); |
| 1375 | query_repo(&tmp, 1); |
| 1376 | |
| 1377 | buf_init(&b); |
| 1378 | buf_printf(&b, "{\"ok\":%s,\"action\":\"fetch\",\"exit\":%d", |
| 1379 | rc == 0 ? "true" : "false", rc); |
| 1380 | buf_puts(&b, ",\"path\":"); json_str(&b, canon); |
| 1381 | buf_puts(&b, ",\"output\":"); json_str(&b, buf_str(&out)); |
| 1382 | buf_printf(&b, ",\"ahead\":%d,\"behind\":%d,\"branch\":", tmp.ahead, tmp.behind); |
| 1383 | json_str(&b, tmp.branch); |
| 1384 | buf_puts(&b, "}\n"); |
| 1385 | fputs(buf_str(&b), stdout); |
| 1386 | buf_free(&b); |
| 1387 | buf_free(&out); |
| 1388 | } |
| 1389 | (void)status_out; |
| 1390 | return 0; |
| 1391 | } |
| 1392 | |
| 1393 | /* ------------------------------------------------------------------ */ |
| 1394 | /* HTML UI */ |
| 1395 | /* ------------------------------------------------------------------ */ |
| 1396 | |
| 1397 | /* Split UI_HTML on the two control-byte placeholders and expand them into the |
| 1398 | * theme macros, so the page and the bot palette can never drift apart. */ |
| 1399 | static void emit_ui(void) |
| 1400 | { |
| 1401 | const char *p = UI_HTML; |
| 1402 | |
| 1403 | while (*p) { |
| 1404 | if (*p == '\001') { |
| 1405 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 1406 | ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);" |
| 1407 | "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}" |
| 1408 | "</style>", stdout); |
| 1409 | p++; |
| 1410 | } else if (*p == '\002') { |
| 1411 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1412 | p++; |
| 1413 | } else { |
| 1414 | putchar(*p++); |
| 1415 | } |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | static int mode_html(void) |
| 1420 | { |
| 1421 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1422 | "Cache-Control: no-store\r\n" |
| 1423 | "X-Content-Type-Options: nosniff\r\n" |
| 1424 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 1425 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 1426 | "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); |
| 1427 | emit_ui(); |
| 1428 | return 0; |
| 1429 | } |
| 1430 | |
| 1431 | /* ------------------------------------------------------------------ */ |
| 1432 | /* Modes */ |
| 1433 | /* ------------------------------------------------------------------ */ |
| 1434 | |
| 1435 | static int mode_meta(void) |
| 1436 | { |
| 1437 | fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}\n", stdout); |
| 1438 | return 0; |
| 1439 | } |
| 1440 | |
| 1441 | static int mode_json(const char *qs) |
| 1442 | { |
| 1443 | char action[64]; |
| 1444 | char path[1024]; |
| 1445 | |
| 1446 | action[0] = '\0'; |
| 1447 | get_query_val(qs, "action", action, sizeof(action)); |
| 1448 | |
| 1449 | if (strcmp(action, "repo") == 0) { |
| 1450 | collect_roots(); |
| 1451 | get_query_val(qs, "path", path, sizeof(path)); |
| 1452 | json_header(0); |
| 1453 | return print_repo_detail(path); |
| 1454 | } |
| 1455 | |
| 1456 | if (strcmp(action, "fetch") == 0) { |
| 1457 | int st = 0; |
| 1458 | collect_roots(); |
| 1459 | get_query_val(qs, "path", path, sizeof(path)); |
| 1460 | if (!is_post_request()) { |
| 1461 | json_header(400); |
| 1462 | fputs("{\"ok\":false,\"error\":\"fetch is POST only\"}\n", stdout); |
| 1463 | return 0; |
| 1464 | } |
| 1465 | return do_fetch(path, &st); |
| 1466 | } |
| 1467 | |
| 1468 | if (strcmp(action, "repos") == 0 || !action[0] || strcmp(action, "all") == 0) { |
| 1469 | collect_repos(); |
| 1470 | json_header(0); |
| 1471 | print_repos(); |
| 1472 | return 0; |
| 1473 | } |
| 1474 | |
| 1475 | json_header(0); |
| 1476 | fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); |
| 1477 | return 0; |
| 1478 | } |
| 1479 | |
| 1480 | int main(int argc, char **argv) |
| 1481 | { |
| 1482 | const char *qs; |
| 1483 | int embed; |
| 1484 | |
| 1485 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || |
| 1486 | (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) |
| 1487 | return mode_meta(); |
| 1488 | |
| 1489 | require_node_auth(); |
| 1490 | |
| 1491 | qs = getenv("QUERY_STRING"); |
| 1492 | if (!qs) qs = ""; |
| 1493 | |
| 1494 | if (is_post_request() && strstr(qs, "action=fetch")) { |
| 1495 | char path[1024]; |
| 1496 | collect_roots(); |
| 1497 | get_query_val(qs, "path", path, sizeof(path)); |
| 1498 | return do_fetch(path, NULL); |
| 1499 | } |
| 1500 | |
| 1501 | if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) |
| 1502 | return mode_json(qs); |
| 1503 | |
| 1504 | embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); |
| 1505 | (void)embed; |
| 1506 | return mode_html(); |
| 1507 | } |