scorpiox-bot-plugin-google-quota
←plugin_google_quota.cc
1791 lines · 55 KBHEADBlameDownload
1/*
2 * plugin_google_quota - SCORPIOX BOT open-source Google Antigravity
3 * multi-account quota monitor and active-account switcher for your node.
4 *
5 * A single clean-room C99 binary that serves THREE modes:
6 * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
7 * 2. ?action=... / ?format=json -> JSON node API
8 * 3. GET (default) -> responsive HTML UI
9 *
10 * DESIGN NOTE (why there is no TLS and no OAuth client secret here):
11 * Refreshing Google OAuth tokens and calling cloudcode-pa requires an OAuth
12 * client identity and TLS. A public clean-room repository must never carry an
13 * OAuth client secret, so this plugin does not speak TLS at all. It reads the
14 * local account list and active selection files written by
15 * scorpiox-antigravity-login and invokes the node's scorpiox-google-quota CLI:
16 *
17 * ~/.config/google-accounts/antigravity_accounts.json (emails + presence)
18 * ~/.config/google-accounts/selected_account.txt (active email)
19 *
20 * Every path and the quota CLI can be overridden for testing or relocation:
21 *
22 * GOOGLE_ACCOUNTS_FILE accounts JSON (also accepts ANTIGRAVITY_CREDS_PATH)
23 * GOOGLE_SELECTED_FILE selected account file (default: sibling selected_account.txt)
24 * GOOGLE_QUOTA_BIN quota CLI binary (default: scorpiox-google-quota)
25 *
26 * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. When reading
27 * antigravity_accounts.json, only email and refresh_token presence (boolean)
28 * are recorded; token strings are never copied or emitted.
29 *
30 * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang
31 * and x86_64-w64-mingw32-gcc -static.
32 *
33 * MIT License. Copyright (c) 2026 SCORPIOX INC.
34 */
35
36#if defined(_WIN32) && !defined(_WIN32_WINNT)
37# define _WIN32_WINNT 0x0601
38#endif
39
40#if !defined(_WIN32)
41# define _POSIX_C_SOURCE 200809L
42# define _DEFAULT_SOURCE 1
43# if defined(__APPLE__)
44# define _DARWIN_C_SOURCE 1
45# endif
46#endif
47
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <ctype.h>
52#include <errno.h>
53#include <stdarg.h>
54#include <time.h>
55
56#if defined(_WIN32)
57# define WIN32_LEAN_AND_MEAN
58# include <windows.h>
59# include <direct.h>
60# include <fcntl.h>
61# include <io.h>
62# define popen _popen
63# define pclose _pclose
64# define PATH_SEP '\\'
65#else
66# include <unistd.h>
67# include <fcntl.h>
68# include <poll.h>
69# include <sys/stat.h>
70# include <sys/types.h>
71# include <sys/wait.h>
72# define PATH_SEP '/'
73#endif
74
75#include "bot_theme_plugin.h"
76#include "ui_html.h"
77
78#define PLUGIN_SLUG "google-quota"
79#define PLUGIN_ID "plugin_google_quota"
80#define PLUGIN_VER "1.0.3"
81#define PLUGIN_NAME "google quota"
82#define PLUGIN_DESC "Account quotas"
83#define DEFAULT_QUOTA_BIN "scorpiox-google-quota"
84
85#define PATH_SZ 1024
86#define EMAIL_SZ 256
87#define PROJ_SZ 256
88#define MODEL_SZ 128
89#define RESET_SZ 64
90#define CMD_SZ 4096
91#define FIELD_SZ 512
92#define OUT_MAX (512 * 1024)
93#define MAX_ACCOUNTS 64
94#define MAX_MODELS 128
95#define MAX_WORKERS 8
96
97/* ------------------------------------------------------------------ */
98/* Growable byte buffer */
99/* ------------------------------------------------------------------ */
100
101typedef struct {
102 char *p;
103 size_t n;
104 size_t cap;
105} buf_t;
106
107static void buf_init(buf_t *b)
108{
109 b->p = NULL;
110 b->n = 0;
111 b->cap = 0;
112}
113
114static int buf_need(buf_t *b, size_t extra)
115{
116 size_t want = b->n + extra + 1;
117 char *np;
118
119 if (want <= b->cap) return 1;
120 if (b->cap == 0) b->cap = 1024;
121 while (b->cap < want) {
122 if (b->cap > (size_t)32 * 1024 * 1024) return 0;
123 b->cap *= 2;
124 }
125 np = (char *)realloc(b->p, b->cap);
126 if (!np) return 0;
127 b->p = np;
128 return 1;
129}
130
131static int buf_add(buf_t *b, const char *s, size_t len)
132{
133 if (!s || len == 0) return 1;
134 if (!buf_need(b, len)) return 0;
135 memcpy(b->p + b->n, s, len);
136 b->n += len;
137 b->p[b->n] = '\0';
138 return 1;
139}
140
141static int buf_adds(buf_t *b, const char *s)
142{
143 return s ? buf_add(b, s, strlen(s)) : 1;
144}
145
146static int buf_addc(buf_t *b, char c)
147{
148 return buf_add(b, &c, 1);
149}
150
151static int buf_addf(buf_t *b, const char *fmt, ...)
152{
153 char tmp[2048];
154 int n;
155 va_list ap;
156
157 va_start(ap, fmt);
158 n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
159 va_end(ap);
160 if (n < 0) return 0;
161 if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n);
162
163 {
164 char *big = (char *)malloc((size_t)n + 1);
165 int ok;
166 if (!big) return 0;
167 va_start(ap, fmt);
168 vsnprintf(big, (size_t)n + 1, fmt, ap);
169 va_end(ap);
170 ok = buf_add(b, big, (size_t)n);
171 free(big);
172 return ok;
173 }
174}
175
176static int buf_json(buf_t *b, const char *s)
177{
178 const unsigned char *p = (const unsigned char *)(s ? s : "");
179 if (!buf_addc(b, '"')) return 0;
180 for (; *p; p++) {
181 switch (*p) {
182 case '"': if (!buf_adds(b, "\\\"")) return 0; break;
183 case '\\': if (!buf_adds(b, "\\\\")) return 0; break;
184 case '\n': if (!buf_adds(b, "\\n")) return 0; break;
185 case '\r': if (!buf_adds(b, "\\r")) return 0; break;
186 case '\t': if (!buf_adds(b, "\\t")) return 0; break;
187 default:
188 if (*p < 0x20) {
189 if (!buf_addf(b, "\\u%04x", (unsigned)*p)) return 0;
190 } else {
191 if (!buf_addc(b, (char)*p)) return 0;
192 }
193 }
194 }
195 return buf_addc(b, '"');
196}
197
198static const char *buf_str(const buf_t *b)
199{
200 return b->p ? b->p : "";
201}
202
203static void buf_free(buf_t *b)
204{
205 free(b->p);
206 b->p = NULL;
207 b->n = 0;
208 b->cap = 0;
209}
210
211/* ------------------------------------------------------------------ */
212/* String, query & env helpers */
213/* ------------------------------------------------------------------ */
214
215static int ascii_strncasecmp(const char *a, const char *b, size_t n)
216{
217 size_t i;
218 for (i = 0; i < n; i++) {
219 unsigned char ca = (unsigned char)a[i];
220 unsigned char cb = (unsigned char)b[i];
221 int da = tolower(ca);
222 int db = tolower(cb);
223 if (da != db) return da - db;
224 if (ca == '\0') return 0;
225 }
226 return 0;
227}
228
229static void trim_tail(char *s)
230{
231 size_t n;
232 if (!s) return;
233 n = strlen(s);
234 while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
235 s[n - 1] == '\r' || s[n - 1] == '\n')) {
236 s[--n] = '\0';
237 }
238}
239
240static void url_decode(char *s)
241{
242 char *w = s;
243 char *r = s;
244 if (!s) return;
245 while (*r) {
246 if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) {
247 int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10;
248 int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10;
249 *w++ = (char)((hi << 4) | lo);
250 r += 3;
251 } else if (*r == '+') {
252 *w++ = ' ';
253 r++;
254 } else {
255 *w++ = *r++;
256 }
257 }
258 *w = '\0';
259}
260
261static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
262{
263 size_t klen;
264 const char *p;
265
266 if (!out || outsz == 0) return 0;
267 out[0] = '\0';
268 if (!qs || !key) return 0;
269 klen = strlen(key);
270 p = qs;
271 while (*p) {
272 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
273 size_t i = 0;
274 p += klen + 1;
275 while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
276 out[i] = '\0';
277 url_decode(out);
278 return 1;
279 }
280 p = strchr(p, '&');
281 if (!p) break;
282 p++;
283 }
284 return 0;
285}
286
287static int query_has(const char *qs, const char *key)
288{
289 size_t klen;
290 const char *p;
291
292 if (!qs || !key) return 0;
293 klen = strlen(key);
294 p = qs;
295 while (p && *p) {
296 if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
297 return 1;
298 p = strchr(p, '&');
299 if (!p) break;
300 p++;
301 }
302 return 0;
303}
304
305static void set_env_var(const char *k, const char *v)
306{
307#if defined(_WIN32)
308 _putenv_s(k, v ? v : "");
309#else
310 setenv(k, v ? v : "", 1);
311#endif
312}
313
314static void unset_env_var(const char *k)
315{
316#if defined(_WIN32)
317 _putenv_s(k, "");
318#else
319 unsetenv(k);
320#endif
321}
322
323/* ------------------------------------------------------------------ */
324/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
325/* ------------------------------------------------------------------ */
326
327static void require_node_auth(void)
328{
329 const char *np = getenv("BOT_PASSWORD");
330 const char *xp;
331 const char *auth;
332 char qpwd[256] = {0};
333
334 if (!np || !*np) return;
335
336 xp = getenv("HTTP_X_BOT_PASSWORD");
337 if (xp && strcmp(xp, np) == 0) return;
338
339 auth = getenv("HTTP_AUTHORIZATION");
340 if (auth) {
341 while (*auth == ' ') auth++;
342 if (ascii_strncasecmp(auth, "Bearer ", 7) == 0) {
343 auth += 7;
344 while (*auth == ' ') auth++;
345 if (strcmp(auth, np) == 0) return;
346 }
347 }
348
349 if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
350 strcmp(qpwd, np) == 0) return;
351
352 fputs("Status: 401 Unauthorized\r\n"
353 "Content-Type: application/json; charset=utf-8\r\n"
354 "Cache-Control: no-store\r\n\r\n"
355 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
356 exit(0);
357}
358
359/* ------------------------------------------------------------------ */
360/* Paths & files */
361/* ------------------------------------------------------------------ */
362
363static const char *home_dir(void)
364{
365#ifdef _WIN32
366 static char home[512];
367 DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home));
368 if (n > 0 && n < sizeof(home)) return home;
369 {
370 const char *h = getenv("USERPROFILE");
371 if (h && *h) return h;
372 h = getenv("HOME");
373 return (h && *h) ? h : NULL;
374 }
375#else
376 const char *h = getenv("HOME");
377 return (h && *h) ? h : NULL;
378#endif
379}
380
381static void accounts_path(char *out, size_t n)
382{
383 const char *env = getenv("GOOGLE_ACCOUNTS_FILE");
384 const char *home;
385
386 if (env && *env) { snprintf(out, n, "%s", env); return; }
387 env = getenv("ANTIGRAVITY_CREDS_PATH");
388 if (env && *env) { snprintf(out, n, "%s", env); return; }
389
390 home = home_dir();
391 if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; }
392 snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json",
393 home, PATH_SEP, PATH_SEP, PATH_SEP);
394}
395
396static void selected_path(char *out, size_t n)
397{
398 const char *env = getenv("GOOGLE_SELECTED_FILE");
399 char base[PATH_SZ];
400 char *slash;
401
402 if (env && *env) { snprintf(out, n, "%s", env); return; }
403
404 accounts_path(base, sizeof(base));
405 slash = strrchr(base, PATH_SEP);
406 if (!slash) slash = strrchr(base, '/');
407 if (!slash) { snprintf(out, n, "selected_account.txt"); return; }
408 *(slash + 1) = '\0';
409 snprintf(out, n, "%sselected_account.txt", base);
410}
411
412static const char *quota_bin(void)
413{
414 const char *b = getenv("GOOGLE_QUOTA_BIN");
415 return (b && *b) ? b : DEFAULT_QUOTA_BIN;
416}
417
418#if defined(_WIN32)
419static int file_exists(const char *p)
420{
421 DWORD a = GetFileAttributesA(p);
422 return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
423}
424#endif
425
426static int bin_available(const char *bin)
427{
428 if (!bin || !*bin) return 0;
429#if defined(_WIN32)
430 {
431 char full[MAX_PATH];
432 DWORD n;
433 if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':'))
434 return file_exists(bin);
435 n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL);
436 return n > 0 && n < (DWORD)sizeof(full);
437 }
438#else
439 if (strchr(bin, '/')) {
440 struct stat st;
441 return stat(bin, &st) == 0 && S_ISREG(st.st_mode) && access(bin, X_OK) == 0;
442 }
443 {
444 const char *path_env = getenv("PATH");
445 const char *p;
446 if (!path_env || !*path_env) return 0;
447 p = path_env;
448 while (*p) {
449 const char *colon = strchr(p, ':');
450 size_t dlen = colon ? (size_t)(colon - p) : strlen(p);
451 char cand[PATH_SZ];
452 if (dlen > 0 && dlen + 1 + strlen(bin) + 1 < sizeof(cand)) {
453 struct stat st;
454 memcpy(cand, p, dlen);
455 cand[dlen] = '/';
456 strcpy(cand + dlen + 1, bin);
457 if (stat(cand, &st) == 0 && S_ISREG(st.st_mode) && access(cand, X_OK) == 0)
458 return 1;
459 }
460 if (!colon) break;
461 p = colon + 1;
462 }
463 return 0;
464 }
465#endif
466}
467
468static char *read_file(const char *path)
469{
470 FILE *f;
471 long sz;
472 char *buf;
473
474 if (!path || !*path) return NULL;
475 f = fopen(path, "rb");
476 if (!f) return NULL;
477 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
478 sz = ftell(f);
479 if (sz < 0 || sz > 4 * 1024 * 1024) { fclose(f); return NULL; }
480 rewind(f);
481 buf = (char *)malloc((size_t)sz + 1);
482 if (!buf) { fclose(f); return NULL; }
483 if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
484 free(buf);
485 fclose(f);
486 return NULL;
487 }
488 buf[sz] = '\0';
489 fclose(f);
490 return buf;
491}
492
493/* ------------------------------------------------------------------ */
494/* Minimal JSON scanner (read-only, zero dependencies) */
495/* ------------------------------------------------------------------ */
496
497static const char *json_skip_ws(const char *p, const char *end)
498{
499 while (p && p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
500 return p;
501}
502
503static const char *json_skip_value(const char *p)
504{
505 int depth = 0;
506 int in_str = 0;
507
508 if (!p) return NULL;
509 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++;
510 if (!*p) return NULL;
511
512 if (*p != '{' && *p != '[' && *p != '"') {
513 while (*p && *p != ',' && *p != '}' && *p != ']' &&
514 *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++;
515 return p;
516 }
517
518 for (; *p; p++) {
519 if (in_str) {
520 if (*p == '\\' && p[1]) { p++; continue; }
521 if (*p == '"') {
522 in_str = 0;
523 if (depth == 0) return p + 1;
524 }
525 continue;
526 }
527 if (*p == '"') { in_str = 1; continue; }
528 if (*p == '{' || *p == '[') { depth++; continue; }
529 if (*p == '}' || *p == ']') {
530 depth--;
531 if (depth <= 0) return p + 1;
532 }
533 }
534 return p;
535}
536
537static int json_read_string_at(const char **pp, char *out, size_t outsz)
538{
539 const char *p = *pp;
540 size_t o = 0;
541
542 if (!p || *p != '"') return 0;
543 p++;
544 while (*p && *p != '"') {
545 unsigned char c = (unsigned char)*p++;
546 if (c == '\\' && *p) {
547 char e = *p++;
548 switch (e) {
549 case '"': c = '"'; break;
550 case '\\': c = '\\'; break;
551 case '/': c = '/'; break;
552 case 'n': c = '\n'; break;
553 case 'r': c = '\r'; break;
554 case 't': c = '\t'; break;
555 default: c = (unsigned char)e; break;
556 }
557 }
558 if (o + 1 < outsz) out[o++] = (char)c;
559 }
560 if (*p == '"') p++;
561 out[o] = '\0';
562 *pp = p;
563 return 1;
564}
565
566static const char *json_find_key(const char *obj, const char *end, const char *key)
567{
568 const char *p = obj;
569 size_t klen = strlen(key);
570 int depth = 0;
571
572 p = json_skip_ws(p, end);
573 if (p < end && *p == '{') p++;
574
575 while (p && p < end) {
576 if (*p == '"') {
577 char name[128];
578 json_read_string_at(&p, name, sizeof(name));
579 if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
580 const char *q = json_skip_ws(p, end);
581 if (q < end && *q == ':') {
582 q = json_skip_ws(q + 1, end);
583 return (q < end) ? q : NULL;
584 }
585 }
586 continue;
587 }
588 if (*p == '{' || *p == '[') depth++;
589 else if (*p == '}' || *p == ']') depth--;
590 p++;
591 }
592 return NULL;
593}
594
595static int json_str_field(const char *obj, const char *end, const char *key,
596 char *out, size_t outsz)
597{
598 const char *v;
599
600 if (!out || outsz == 0) return 0;
601 v = json_find_key(obj, end, key);
602 if (!v || *v == 'n') return 0;
603 out[0] = '\0';
604 if (*v == '"') return json_read_string_at(&v, out, outsz);
605 {
606 size_t i = 0;
607 while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++;
608 out[i] = '\0';
609 trim_tail(out);
610 return out[0] ? 1 : 0;
611 }
612}
613
614static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
615{
616 const char *v = json_find_key(obj, end, key);
617 if (!v) return dflt;
618 if (strncmp(v, "true", 4) == 0) return 1;
619 if (strncmp(v, "false", 5) == 0) return 0;
620 if (*v == '1') return 1;
621 return 0;
622}
623
624/* Returns 1 if numeric value parsed into *out, 0 if missing or null. */
625static int json_double_field(const char *obj, const char *end, const char *key, double *out)
626{
627 const char *v = json_find_key(obj, end, key);
628 char *ep = NULL;
629 double val;
630
631 if (!v || *v == 'n') return 0;
632 if (*v != '-' && !isdigit((unsigned char)*v) && *v != '.') return 0;
633 val = strtod(v, &ep);
634 if (ep == v) return 0;
635 *out = val;
636 return 1;
637}
638
639/* ------------------------------------------------------------------ */
640/* Account list loading (never copies refresh_token) */
641/* ------------------------------------------------------------------ */
642
643typedef struct {
644 char email[EMAIL_SZ];
645 int has_refresh;
646 int selected;
647} acct_entry_t;
648
649static int is_safe_email(const char *s)
650{
651 int has_at = 0;
652 const char *p;
653
654 if (!s || !*s || strlen(s) >= EMAIL_SZ) return 0;
655 for (p = s; *p; p++) {
656 unsigned char c = (unsigned char)*p;
657 if (c == '@') { has_at = 1; continue; }
658 if (isalnum(c) || c == '.' || c == '_' || c == '-' || c == '+') continue;
659 return 0;
660 }
661 return has_at;
662}
663
664static int load_accounts(acct_entry_t *list, int max_n, char *selected_out, size_t sel_sz)
665{
666 char apath[PATH_SZ], spath[PATH_SZ];
667 char *raw_sel, *raw_accts;
668 int count = 0;
669
670 selected_out[0] = '\0';
671 selected_path(spath, sizeof(spath));
672 raw_sel = read_file(spath);
673 if (raw_sel) {
674 trim_tail(raw_sel);
675 if (is_safe_email(raw_sel)) snprintf(selected_out, sel_sz, "%s", raw_sel);
676 free(raw_sel);
677 }
678
679 accounts_path(apath, sizeof(apath));
680 raw_accts = read_file(apath);
681 if (!raw_accts) return 0;
682
683 {
684 const char *p = raw_accts;
685 while (p && *p && count < max_n) {
686 const char *open = strchr(p, '{');
687 const char *end;
688 char email[EMAIL_SZ] = {0};
689 char rt_probe[8] = {0};
690 int has_rt = 0;
691 int dup = 0;
692 int i;
693
694 if (!open) break;
695 end = json_skip_value(open);
696 if (!end || end <= open) break;
697
698 json_str_field(open, end, "email", email, sizeof(email));
699 /* Presence check only: never copy or retain the refresh token. */
700 if (json_str_field(open, end, "refresh_token", rt_probe, sizeof(rt_probe)) && rt_probe[0])
701 has_rt = 1;
702
703 if (is_safe_email(email)) {
704 for (i = 0; i < count; i++) {
705 if (strcmp(list[i].email, email) == 0) {
706 if (has_rt) list[i].has_refresh = 1;
707 dup = 1;
708 break;
709 }
710 }
711 if (!dup) {
712 snprintf(list[count].email, sizeof(list[count].email), "%s", email);
713 list[count].has_refresh = has_rt;
714 list[count].selected = (selected_out[0] && strcmp(selected_out, email) == 0) ? 1 : 0;
715 count++;
716 }
717 }
718 p = end;
719 }
720 }
721
722 free(raw_accts);
723 return count;
724}
725
726/* ------------------------------------------------------------------ */
727/* Child process execution */
728/* ------------------------------------------------------------------ */
729
730static void prepare_quota_env(void)
731{
732 char apath[PATH_SZ];
733 accounts_path(apath, sizeof(apath));
734
735 /* Clear profile/token overrides so --account always resolves from the
736 * local accounts file rather than an inherited agent profile. */
737 unset_env_var("ACTIVE_PROFILE");
738 unset_env_var("GOOGLE_ACCESS_TOKEN");
739 unset_env_var("GOOGLE_REMOTE_URL");
740 unset_env_var("GOOGLE_PROJECT_ID");
741 unset_env_var("GOOGLE_ACCOUNT");
742 set_env_var("GOOGLE_TOKEN_SOURCE", "local");
743 set_env_var("GOOGLE_ACCOUNTS_FILE", apath);
744}
745
746#if defined(_WIN32)
747static void shell_quote_into(const char *in, char *out, size_t outsz)
748{
749 size_t o = 0;
750 const char *p;
751
752 if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
753 out[o++] = '"';
754 for (p = in; p && *p; p++) {
755 if (*p == '"') {
756 if (o + 3 >= outsz) break;
757 out[o++] = '\\';
758 out[o++] = '"';
759 } else {
760 if (o + 2 >= outsz) break;
761 out[o++] = *p;
762 }
763 }
764 out[o++] = '"';
765 out[o] = '\0';
766}
767
768static int run_quota_one(const char *bin, const char *email, buf_t *out)
769{
770 char cmd[CMD_SZ];
771 char qbin[FIELD_SZ];
772 char qemail[EMAIL_SZ + 16];
773 FILE *f;
774 char line[2048];
775 size_t total = 0;
776 int rc;
777
778 if (!bin || !*bin || !is_safe_email(email)) return 0;
779 if (!bin_available(bin)) return -1;
780 shell_quote_into(bin, qbin, sizeof(qbin));
781 shell_quote_into(email, qemail, sizeof(qemail));
782 snprintf(cmd, sizeof(cmd), "%s --account %s --json 2>NUL", qbin, qemail);
783
784 f = popen(cmd, "r");
785 if (!f) return 0;
786 while (fgets(line, sizeof(line), f)) {
787 total += strlen(line);
788 if (total > OUT_MAX) break;
789 buf_adds(out, line);
790 }
791 rc = pclose(f);
792 if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
793 return (rc == 0) ? 1 : 0;
794}
795#else
796static int run_quota_one(const char *bin, const char *email, buf_t *out)
797{
798 int pfd[2];
799 pid_t pid;
800 char chunk[4096];
801 ssize_t n;
802 int status = 0;
803
804 if (!bin || !*bin || !is_safe_email(email)) return 0;
805 if (!bin_available(bin)) return -1;
806 if (pipe(pfd) != 0) return 0;
807
808 pid = fork();
809 if (pid < 0) {
810 close(pfd[0]);
811 close(pfd[1]);
812 return 0;
813 }
814 if (pid == 0) {
815 int devnull = open("/dev/null", O_WRONLY);
816 char *argv_exec[5];
817 close(pfd[0]);
818 dup2(pfd[1], STDOUT_FILENO);
819 close(pfd[1]);
820 if (devnull >= 0) {
821 dup2(devnull, STDERR_FILENO);
822 close(devnull);
823 }
824 argv_exec[0] = (char *)bin;
825 argv_exec[1] = "--account";
826 argv_exec[2] = (char *)email;
827 argv_exec[3] = "--json";
828 argv_exec[4] = NULL;
829 execvp(bin, argv_exec);
830 _exit(127);
831 }
832
833 close(pfd[1]);
834 while ((n = read(pfd[0], chunk, sizeof(chunk))) > 0) {
835 if (out->n + (size_t)n <= OUT_MAX) buf_add(out, chunk, (size_t)n);
836 }
837 close(pfd[0]);
838 if (waitpid(pid, &status, 0) < 0) return 0;
839 if (WIFEXITED(status) && WEXITSTATUS(status) == 127) return -1;
840 return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 1 : 0;
841}
842#endif
843
844/* ------------------------------------------------------------------ */
845/* Quota parsing & pool aggregation */
846/* ------------------------------------------------------------------ */
847
848typedef struct {
849 char id[MODEL_SZ];
850 char pool[16];
851 double pct;
852 int exhausted;
853 char reset_time[RESET_SZ];
854} model_quota_t;
855
856typedef struct {
857 int present;
858 double pct;
859 int exhausted;
860 char reset_time[RESET_SZ];
861 int count;
862} pool_summary_t;
863
864typedef struct {
865 int present;
866 char bucket_id[64];
867 double pct;
868 int exhausted;
869 char reset_time[RESET_SZ];
870} window_limit_t;
871
872typedef struct {
873 window_limit_t five_hour;
874 window_limit_t weekly;
875} pool_limits_t;
876
877typedef struct {
878 int ok;
879 int cli_missing;
880 char error[64];
881 char project[PROJ_SZ];
882 pool_summary_t gemini;
883 pool_summary_t argon;
884 pool_summary_t claude;
885 pool_limits_t gemini_limits;
886 pool_limits_t claude_limits;
887 model_quota_t models[MAX_MODELS];
888 int model_count;
889} acct_quota_t;
890static void pool_init(pool_summary_t *p)
891{
892 p->present = 0;
893 p->pct = -1.0;
894 p->exhausted = 0;
895 p->reset_time[0] = '\0';
896 p->count = 0;
897}
898
899static void pool_add(pool_summary_t *p, double pct, int exhausted, const char *reset)
900{
901 if (!p->present || pct < p->pct) p->pct = pct;
902 p->present = 1;
903 if (exhausted || pct <= 0.0) p->exhausted = 1;
904 if (reset && reset[0] && (!p->reset_time[0] || strcmp(reset, p->reset_time) < 0))
905 snprintf(p->reset_time, sizeof(p->reset_time), "%s", reset);
906 p->count++;
907}
908
909static const char *find_json_root(const buf_t *b)
910{
911 const char *p;
912 if (!b || !b->p) return NULL;
913 p = b->p;
914 while (*p) {
915 if (*p == '{') return p;
916 p = strchr(p, '\n');
917 if (!p) break;
918 p++;
919 }
920 return strchr(b->p, '{');
921}
922
923static void parse_quota_output(const buf_t *raw, int run_rc, acct_quota_t *q)
924{
925 const char *root;
926 const char *root_end;
927 const char *buckets;
928 const char *buckets_end;
929 const char *p;
930
931 memset(q, 0, sizeof(*q));
932 pool_init(&q->gemini);
933 pool_init(&q->argon);
934 pool_init(&q->claude);
935
936 if (run_rc == -1) {
937 q->cli_missing = 1;
938 snprintf(q->error, sizeof(q->error), "cli_unavailable");
939 return;
940 }
941
942 root = find_json_root(raw);
943 if (!root) {
944 snprintf(q->error, sizeof(q->error), "quota_fetch_failed");
945 return;
946 }
947 root_end = json_skip_value(root);
948 if (!root_end || root_end <= root) {
949 snprintf(q->error, sizeof(q->error), "invalid_quota_json");
950 return;
951 }
952
953 if (!json_bool_field(root, root_end, "ok", 0)) {
954 json_str_field(root, root_end, "error", q->error, sizeof(q->error));
955 if (!q->error[0]) snprintf(q->error, sizeof(q->error), "quota_fetch_failed");
956 return;
957 }
958
959 json_str_field(root, root_end, "project", q->project, sizeof(q->project));
960 buckets = json_find_key(root, root_end, "buckets");
961 if (!buckets || *buckets != '[') {
962 snprintf(q->error, sizeof(q->error), "missing_buckets");
963 return;
964 }
965 buckets_end = json_skip_value(buckets);
966 if (!buckets_end || buckets_end <= buckets) {
967 snprintf(q->error, sizeof(q->error), "invalid_buckets");
968 return;
969 }
970
971 p = buckets + 1;
972 while (p && p < buckets_end) {
973 const char *open = strchr(p, '{');
974 const char *end;
975 char mid[MODEL_SZ] = {0};
976 char rst[RESET_SZ] = {0};
977 double frac = 0.0;
978 double pct = 0.0;
979 int exhausted = 0;
980 const char *pool_name = "other";
981
982 if (!open || open >= buckets_end) break;
983 end = json_skip_value(open);
984 if (!end || end <= open || end > buckets_end) break;
985
986 json_str_field(open, end, "modelId", mid, sizeof(mid));
987 json_str_field(open, end, "resetTime", rst, sizeof(rst));
988
989 if (mid[0] && strncmp(mid, "chat_", 5) != 0 && strncmp(mid, "tab_", 4) != 0) {
990 if (json_double_field(open, end, "remainingFraction", &frac)) {
991 pct = frac * 100.0;
992 if (pct < 0.0) pct = 0.0;
993 if (pct > 100.0) pct = 100.0;
994 if (frac <= 0.0) exhausted = 1;
995 } else {
996 /* Absent or null remainingFraction means exhausted. */
997 pct = 0.0;
998 exhausted = 1;
999 }
1000
1001 if (strncmp(mid, "gemini-4-argon", 14) == 0) {
1002 pool_name = "argon";
1003 pool_add(&q->argon, pct, exhausted, rst);
1004 } else if (strncmp(mid, "gemini-", 7) == 0) {
1005 pool_name = "gemini";
1006 pool_add(&q->gemini, pct, exhausted, rst);
1007 } else if (strncmp(mid, "claude-", 7) == 0) {
1008 pool_name = "claude";
1009 pool_add(&q->claude, pct, exhausted, rst);
1010 }
1011
1012 if (q->model_count < MAX_MODELS) {
1013 model_quota_t *m = &q->models[q->model_count++];
1014 snprintf(m->id, sizeof(m->id), "%s", mid);
1015 snprintf(m->pool, sizeof(m->pool), "%s", pool_name);
1016 m->pct = pct;
1017 m->exhausted = exhausted;
1018 snprintf(m->reset_time, sizeof(m->reset_time), "%s", rst);
1019 }
1020 }
1021 p = end;
1022 }
1023
1024 /* Optional: parse summary.groups (from retrieveUserQuotaSummary) for
1025 * explicit 5-hour and weekly quota limits. */
1026 {
1027 const char *sum = json_find_key(root, root_end, "summary");
1028 if (sum && *sum == '{') {
1029 const char *sum_end = json_skip_value(sum);
1030 const char *groups = (sum_end && sum_end > sum)
1031 ? json_find_key(sum, sum_end, "groups") : NULL;
1032 if (groups && *groups == '[') {
1033 const char *groups_end = json_skip_value(groups);
1034 const char *gp = groups + 1;
1035 while (gp && groups_end && gp < groups_end) {
1036 const char *gopen = strchr(gp, '{');
1037 const char *gend;
1038 char gname[128] = {0};
1039 const char *gb;
1040 const char *gb_end;
1041 if (!gopen || gopen >= groups_end) break;
1042 gend = json_skip_value(gopen);
1043 if (!gend || gend <= gopen || gend > groups_end) break;
1044
1045 json_str_field(gopen, gend, "displayName", gname, sizeof(gname));
1046 gb = json_find_key(gopen, gend, "buckets");
1047 if (gb && *gb == '[') {
1048 gb_end = json_skip_value(gb);
1049 if (gb_end && gb_end > gb && gb_end <= gend) {
1050 const char *bp = gb + 1;
1051 while (bp && bp < gb_end) {
1052 const char *bopen = strchr(bp, '{');
1053 const char *bend;
1054 char bid[64] = {0};
1055 char win[32] = {0};
1056 char rst[RESET_SZ] = {0};
1057 double frac = 0.0;
1058 double pct = -1.0;
1059 int exhausted = 0;
1060 pool_limits_t *target_pool = NULL;
1061 window_limit_t *target_win = NULL;
1062
1063 if (!bopen || bopen >= gb_end) break;
1064 bend = json_skip_value(bopen);
1065 if (!bend || bend <= bopen || bend > gb_end) break;
1066
1067 json_str_field(bopen, bend, "bucketId", bid, sizeof(bid));
1068 json_str_field(bopen, bend, "window", win, sizeof(win));
1069 json_str_field(bopen, bend, "resetTime", rst, sizeof(rst));
1070
1071 if (json_double_field(bopen, bend, "remainingFraction", &frac)) {
1072 pct = frac * 100.0;
1073 if (pct < 0.0) pct = 0.0;
1074 if (pct > 100.0) pct = 100.0;
1075 if (frac <= 0.0) exhausted = 1;
1076 } else if (rst[0]) {
1077 pct = 0.0;
1078 exhausted = 1;
1079 }
1080
1081 if (strncmp(bid, "gemini-", 7) == 0 ||
1082 strstr(gname, "Gemini") || strstr(gname, "gemini")) {
1083 target_pool = &q->gemini_limits;
1084 } else if (strncmp(bid, "3p-", 3) == 0 ||
1085 strstr(gname, "Claude") || strstr(gname, "claude") ||
1086 strstr(gname, "GPT")) {
1087 target_pool = &q->claude_limits;
1088 }
1089
1090 if (target_pool && pct >= 0.0) {
1091 if (strcmp(win, "5h") == 0 || strstr(bid, "-5h"))
1092 target_win = &target_pool->five_hour;
1093 else if (strcmp(win, "weekly") == 0 || strstr(bid, "-weekly"))
1094 target_win = &target_pool->weekly;
1095 }
1096
1097 if (target_win) {
1098 target_win->present = 1;
1099 snprintf(target_win->bucket_id, sizeof(target_win->bucket_id), "%s", bid);
1100 target_win->pct = pct;
1101 target_win->exhausted = exhausted;
1102 snprintf(target_win->reset_time, sizeof(target_win->reset_time), "%s", rst);
1103 }
1104 bp = bend;
1105 }
1106 }
1107 }
1108 gp = gend;
1109 }
1110 }
1111 }
1112 }
1113
1114 q->ok = 1;
1115}
1116static void fetch_all_quotas(const char *bin, const acct_entry_t *accts, int count,
1117 acct_quota_t *out_q)
1118{
1119#if defined(_WIN32)
1120 int i;
1121 for (i = 0; i < count; i++) {
1122 buf_t raw;
1123 int rc;
1124 buf_init(&raw);
1125 rc = run_quota_one(bin, accts[i].email, &raw);
1126 parse_quota_output(&raw, rc, &out_q[i]);
1127 buf_free(&raw);
1128 }
1129#else
1130 int next_idx = 0;
1131 int done = 0;
1132
1133 if (count <= 0) return;
1134 if (!bin_available(bin)) {
1135 int i;
1136 for (i = 0; i < count; i++) {
1137 buf_t empty;
1138 buf_init(&empty);
1139 parse_quota_output(&empty, -1, &out_q[i]);
1140 }
1141 return;
1142 }
1143
1144 {
1145 typedef struct {
1146 int active;
1147 int acct_idx;
1148 int fd;
1149 pid_t pid;
1150 buf_t raw;
1151 } worker_t;
1152
1153 worker_t w[MAX_WORKERS];
1154 int i;
1155 memset(w, 0, sizeof(w));
1156
1157 while (done < count) {
1158 struct pollfd pfds[MAX_WORKERS];
1159 int pmap[MAX_WORKERS];
1160 int nfds = 0;
1161
1162 for (i = 0; i < MAX_WORKERS && next_idx < count; i++) {
1163 if (w[i].active) continue;
1164 {
1165 int pfd[2];
1166 pid_t pid;
1167 if (pipe(pfd) != 0) {
1168 buf_t empty;
1169 buf_init(&empty);
1170 parse_quota_output(&empty, 0, &out_q[next_idx]);
1171 next_idx++;
1172 done++;
1173 continue;
1174 }
1175 pid = fork();
1176 if (pid < 0) {
1177 close(pfd[0]);
1178 close(pfd[1]);
1179 buf_t empty;
1180 buf_init(&empty);
1181 parse_quota_output(&empty, 0, &out_q[next_idx]);
1182 next_idx++;
1183 done++;
1184 continue;
1185 }
1186 if (pid == 0) {
1187 int devnull = open("/dev/null", O_WRONLY);
1188 char *argv_exec[5];
1189 close(pfd[0]);
1190 dup2(pfd[1], STDOUT_FILENO);
1191 close(pfd[1]);
1192 if (devnull >= 0) {
1193 dup2(devnull, STDERR_FILENO);
1194 close(devnull);
1195 }
1196 argv_exec[0] = (char *)bin;
1197 argv_exec[1] = "--account";
1198 argv_exec[2] = (char *)accts[next_idx].email;
1199 argv_exec[3] = "--json";
1200 argv_exec[4] = NULL;
1201 execvp(bin, argv_exec);
1202 _exit(127);
1203 }
1204 close(pfd[1]);
1205 w[i].active = 1;
1206 w[i].acct_idx = next_idx;
1207 w[i].fd = pfd[0];
1208 w[i].pid = pid;
1209 buf_init(&w[i].raw);
1210 next_idx++;
1211 }
1212 }
1213
1214 for (i = 0; i < MAX_WORKERS; i++) {
1215 if (!w[i].active) continue;
1216 pfds[nfds].fd = w[i].fd;
1217 pfds[nfds].events = POLLIN;
1218 pfds[nfds].revents = 0;
1219 pmap[nfds] = i;
1220 nfds++;
1221 }
1222 if (nfds == 0) break;
1223
1224 if (poll(pfds, (nfds_t)nfds, 30000) < 0) {
1225 if (errno == EINTR) continue;
1226 break;
1227 }
1228
1229 for (i = 0; i < nfds; i++) {
1230 int wi = pmap[i];
1231 if (pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) {
1232 char chunk[4096];
1233 ssize_t n = read(w[wi].fd, chunk, sizeof(chunk));
1234 if (n > 0) {
1235 if (w[wi].raw.n + (size_t)n <= OUT_MAX)
1236 buf_add(&w[wi].raw, chunk, (size_t)n);
1237 } else if (n == 0 || (n < 0 && errno != EINTR)) {
1238 int status = 0;
1239 int rc = 0;
1240 close(w[wi].fd);
1241 if (waitpid(w[wi].pid, &status, 0) >= 0) {
1242 if (WIFEXITED(status) && WEXITSTATUS(status) == 127) rc = -1;
1243 else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) rc = 1;
1244 }
1245 parse_quota_output(&w[wi].raw, rc, &out_q[w[wi].acct_idx]);
1246 buf_free(&w[wi].raw);
1247 w[wi].active = 0;
1248 done++;
1249 }
1250 }
1251 }
1252 }
1253
1254 for (i = 0; i < MAX_WORKERS; i++) {
1255 if (w[i].active) {
1256 int status = 0;
1257 close(w[i].fd);
1258 waitpid(w[i].pid, &status, 0);
1259 parse_quota_output(&w[i].raw, 0, &out_q[w[i].acct_idx]);
1260 buf_free(&w[i].raw);
1261 w[i].active = 0;
1262 }
1263 }
1264 }
1265#endif
1266}
1267
1268/* ------------------------------------------------------------------ */
1269/* JSON emitters */
1270/* ------------------------------------------------------------------ */
1271
1272static void json_headers(void)
1273{
1274 fputs("Content-Type: application/json; charset=utf-8\r\n"
1275 "Cache-Control: no-store\r\n"
1276 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1277}
1278
1279static void emit_error(int code, const char *status, const char *err, const char *detail)
1280{
1281 buf_t b;
1282
1283 buf_init(&b);
1284 buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1285 "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1286 code, status);
1287 buf_adds(&b, "{\"ok\":false,\"error\":");
1288 buf_json(&b, err);
1289 if (detail && *detail) {
1290 buf_adds(&b, ",\"detail\":");
1291 buf_json(&b, detail);
1292 }
1293 buf_adds(&b, "}\n");
1294 fputs(buf_str(&b), stdout);
1295 buf_free(&b);
1296}
1297
1298static long long days_from_civil(int y, unsigned m, unsigned d)
1299{
1300 y -= (m <= 2) ? 1 : 0;
1301 {
1302 long long era = (y >= 0 ? y : y - 399) / 400;
1303 unsigned yoe = (unsigned)(y - era * 400);
1304 unsigned doy = (153U * (m + (m > 2 ? (unsigned)-3 : 9U)) + 2U) / 5U + d - 1U;
1305 unsigned doe = yoe * 365U + yoe / 4U - yoe / 100U + doy;
1306 return era * 146097LL + (long long)doe - 719468LL;
1307 }
1308}
1309
1310static int parse_iso_utc_epoch(const char *iso, long long *out_epoch)
1311{
1312 int y = 0, mo = 0, d = 0, hh = 0, mm = 0, ss = 0;
1313 const char *t;
1314 const char *tz;
1315
1316 if (!iso || !*iso) return 0;
1317 if (sscanf(iso, "%d-%d-%dT%d:%d:%d", &y, &mo, &d, &hh, &mm, &ss) != 6)
1318 return 0;
1319 if (mo < 1 || mo > 12 || d < 1 || d > 31 ||
1320 hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60)
1321 return 0;
1322 t = strchr(iso, 'T');
1323 if (!t) return 0;
1324 {
1325 long long days = days_from_civil(y, (unsigned)mo, (unsigned)d);
1326 long long epoch = days * 86400LL + (long long)hh * 3600LL +
1327 (long long)mm * 60LL + (long long)ss;
1328 tz = strpbrk(t, "Z+-");
1329 if (tz && (*tz == '+' || *tz == '-')) {
1330 int oh = 0, om = 0;
1331 if (sscanf(tz + 1, "%2d:%2d", &oh, &om) >= 1) {
1332 long long off = (long long)oh * 3600LL + (long long)om * 60LL;
1333 epoch += (*tz == '+') ? -off : off;
1334 }
1335 }
1336 *out_epoch = epoch;
1337 return 1;
1338 }
1339}
1340
1341static void compute_reset_fields(const char *iso, long long now_epoch,
1342 long long *secs_out, double *hrs_out,
1343 char *rem_out, size_t rem_sz)
1344{
1345 long long target = 0;
1346 long long diff;
1347
1348 if (!iso || !iso[0] || !parse_iso_utc_epoch(iso, &target)) {
1349 *secs_out = -1;
1350 *hrs_out = -1.0;
1351 if (rem_sz) rem_out[0] = '\0';
1352 return;
1353 }
1354 diff = target - now_epoch;
1355 if (diff <= 0) {
1356 *secs_out = 0;
1357 *hrs_out = 0.0;
1358 snprintf(rem_out, rem_sz, "due");
1359 return;
1360 }
1361 *secs_out = diff;
1362 *hrs_out = (double)diff / 3600.0;
1363 {
1364 long long days = diff / 86400LL;
1365 long long hrs = (diff % 86400LL) / 3600LL;
1366 long long mins = (diff % 3600LL) / 60LL;
1367 if (days > 0)
1368 snprintf(rem_out, rem_sz, "%lldd %lldh", days, hrs);
1369 else if (hrs > 0)
1370 snprintf(rem_out, rem_sz, "%lldh %02lldm", hrs, mins);
1371 else
1372 snprintf(rem_out, rem_sz, "%lldm", mins > 0 ? mins : 1LL);
1373 }
1374}
1375
1376static void emit_pool_json(buf_t *b, const pool_summary_t *p, long long now_epoch)
1377{
1378 long long rsecs = -1;
1379 double rhrs = -1.0;
1380 char rrem[32] = {0};
1381
1382 if (!p->present) {
1383 buf_adds(b, "{\"pct\":-1,\"exhausted\":false,\"reset_time\":\"\","
1384 "\"reset_in_seconds\":-1,\"reset_in_hours\":-1.00,"
1385 "\"reset_remaining\":\"\",\"count\":0}");
1386 return;
1387 }
1388 compute_reset_fields(p->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem));
1389 buf_addf(b, "{\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":",
1390 p->pct, p->exhausted ? "true" : "false");
1391 buf_json(b, p->reset_time);
1392 buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":",
1393 rsecs, rhrs);
1394 buf_json(b, rrem);
1395 buf_addf(b, ",\"count\":%d}", p->count);
1396}
1397
1398static void emit_window_limit_json(buf_t *b, const window_limit_t *w, long long now_epoch)
1399{
1400 long long rsecs = -1;
1401 double rhrs = -1.0;
1402 char rrem[32] = {0};
1403
1404 if (!w || !w->present) {
1405 buf_adds(b, "null");
1406 return;
1407 }
1408 compute_reset_fields(w->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem));
1409 buf_adds(b, "{\"bucket_id\":");
1410 buf_json(b, w->bucket_id);
1411 buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":",
1412 w->pct, w->exhausted ? "true" : "false");
1413 buf_json(b, w->reset_time);
1414 buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":",
1415 rsecs, rhrs);
1416 buf_json(b, rrem);
1417 buf_addc(b, '}');
1418}
1419static void emit_acct_quota_json(buf_t *b, const acct_entry_t *a, const acct_quota_t *q)
1420{
1421 int i;
1422 long long now_epoch = (long long)time(NULL);
1423
1424 buf_adds(b, "{\"email\":");
1425 buf_json(b, a->email);
1426 buf_addf(b, ",\"selected\":%s,\"has_refresh\":%s,\"ok\":%s",
1427 a->selected ? "true" : "false",
1428 a->has_refresh ? "true" : "false",
1429 q->ok ? "true" : "false");
1430
1431 if (!q->ok) {
1432 buf_adds(b, ",\"error\":");
1433 buf_json(b, q->error[0] ? q->error : "quota_fetch_failed");
1434 if (q->cli_missing) {
1435 buf_adds(b, ",\"detail\":");
1436 buf_json(b, "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN");
1437 }
1438 buf_addc(b, '}');
1439 return;
1440 }
1441
1442 buf_adds(b, ",\"project\":");
1443 buf_json(b, q->project);
1444 buf_adds(b, ",\"gemini\":");
1445 emit_pool_json(b, &q->gemini, now_epoch);
1446 buf_adds(b, ",\"argon\":");
1447 emit_pool_json(b, &q->argon, now_epoch);
1448 buf_adds(b, ",\"claude\":");
1449 emit_pool_json(b, &q->claude, now_epoch);
1450 buf_adds(b, ",\"limits\":{\"gemini\":{\"five_hour\":");
1451 emit_window_limit_json(b, &q->gemini_limits.five_hour, now_epoch);
1452 buf_adds(b, ",\"weekly\":");
1453 emit_window_limit_json(b, &q->gemini_limits.weekly, now_epoch);
1454 buf_adds(b, "},\"claude\":{\"five_hour\":");
1455 emit_window_limit_json(b, &q->claude_limits.five_hour, now_epoch);
1456 buf_adds(b, ",\"weekly\":");
1457 emit_window_limit_json(b, &q->claude_limits.weekly, now_epoch);
1458 buf_adds(b, "}}");
1459 buf_adds(b, ",\"models\":[");
1460 for (i = 0; i < q->model_count; i++) {
1461 const model_quota_t *m = &q->models[i];
1462 long long rsecs = -1;
1463 double rhrs = -1.0;
1464 char rrem[32] = {0};
1465 compute_reset_fields(m->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem));
1466 if (i > 0) buf_addc(b, ',');
1467 buf_adds(b, "{\"id\":");
1468 buf_json(b, m->id);
1469 buf_adds(b, ",\"pool\":");
1470 buf_json(b, m->pool);
1471 buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":",
1472 m->pct, m->exhausted ? "true" : "false");
1473 buf_json(b, m->reset_time);
1474 buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":",
1475 rsecs, rhrs);
1476 buf_json(b, rrem);
1477 buf_addc(b, '}');
1478 }
1479 buf_adds(b, "]}");
1480}
1481
1482/* ------------------------------------------------------------------ */
1483/* Actions */
1484/* ------------------------------------------------------------------ */
1485
1486static int action_status(void)
1487{
1488 acct_entry_t accts[MAX_ACCOUNTS];
1489 char selected[EMAIL_SZ];
1490 char apath[PATH_SZ], spath[PATH_SZ];
1491 int count, i;
1492 int cli_ok;
1493 buf_t b;
1494
1495 count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected));
1496 accounts_path(apath, sizeof(apath));
1497 selected_path(spath, sizeof(spath));
1498 cli_ok = bin_available(quota_bin());
1499
1500 buf_init(&b);
1501 buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":");
1502 buf_json(&b, selected);
1503 buf_adds(&b, ",\"accounts_path\":");
1504 buf_json(&b, apath);
1505 buf_adds(&b, ",\"selected_path\":");
1506 buf_json(&b, spath);
1507 buf_addf(&b, ",\"cli_present\":%s,\"count\":%d,\"accounts\":[",
1508 cli_ok ? "true" : "false", count);
1509
1510 for (i = 0; i < count; i++) {
1511 if (i > 0) buf_addc(&b, ',');
1512 buf_adds(&b, "{\"email\":");
1513 buf_json(&b, accts[i].email);
1514 buf_addf(&b, ",\"has_refresh\":%s,\"selected\":%s}",
1515 accts[i].has_refresh ? "true" : "false",
1516 accts[i].selected ? "true" : "false");
1517 }
1518 buf_adds(&b, "]}\n");
1519
1520 json_headers();
1521 fputs(buf_str(&b), stdout);
1522 buf_free(&b);
1523 return 0;
1524}
1525
1526static int action_quota(const char *target_email)
1527{
1528 acct_entry_t accts[MAX_ACCOUNTS];
1529 char selected[EMAIL_SZ];
1530 int count, i;
1531 const char *bin = quota_bin();
1532 buf_t b;
1533
1534 count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected));
1535 prepare_quota_env();
1536
1537 if (target_email && target_email[0]) {
1538 int idx = -1;
1539 buf_t raw;
1540 acct_quota_t q;
1541 int rc;
1542
1543 for (i = 0; i < count; i++) {
1544 if (strcmp(accts[i].email, target_email) == 0) { idx = i; break; }
1545 }
1546 if (idx < 0) {
1547 emit_error(404, "Not Found", "unknown_account", target_email);
1548 return 1;
1549 }
1550
1551 buf_init(&raw);
1552 rc = run_quota_one(bin, accts[idx].email, &raw);
1553 parse_quota_output(&raw, rc, &q);
1554 buf_free(&raw);
1555
1556 if (q.cli_missing) {
1557 emit_error(200, "OK", "cli_unavailable",
1558 "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN");
1559 return 1;
1560 }
1561
1562 buf_init(&b);
1563 buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":");
1564 buf_json(&b, selected);
1565 buf_adds(&b, ",\"account\":");
1566 emit_acct_quota_json(&b, &accts[idx], &q);
1567 buf_adds(&b, "}\n");
1568
1569 json_headers();
1570 fputs(buf_str(&b), stdout);
1571 buf_free(&b);
1572 return 0;
1573 }
1574
1575 {
1576 acct_quota_t *qs = NULL;
1577 const char *best_g = "";
1578 const char *best_a = "";
1579 const char *best_c = "";
1580 double best_gp = -1.0;
1581 double best_ap = -1.0;
1582 double best_cp = -1.0;
1583
1584 if (count > 0) {
1585 qs = (acct_quota_t *)calloc((size_t)count, sizeof(acct_quota_t));
1586 if (!qs) {
1587 emit_error(500, "Internal Server Error", "oom", "out of memory");
1588 return 1;
1589 }
1590 fetch_all_quotas(bin, accts, count, qs);
1591
1592 if (qs[0].cli_missing) {
1593 free(qs);
1594 emit_error(200, "OK", "cli_unavailable",
1595 "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN");
1596 return 1;
1597 }
1598
1599 for (i = 0; i < count; i++) {
1600 if (!qs[i].ok) continue;
1601 if (qs[i].gemini.present && !qs[i].gemini.exhausted && qs[i].gemini.pct > best_gp) {
1602 best_gp = qs[i].gemini.pct;
1603 best_g = accts[i].email;
1604 }
1605 if (qs[i].argon.present && !qs[i].argon.exhausted && qs[i].argon.pct > best_ap) {
1606 best_ap = qs[i].argon.pct;
1607 best_a = accts[i].email;
1608 }
1609 if (qs[i].claude.present && !qs[i].claude.exhausted && qs[i].claude.pct > best_cp) {
1610 best_cp = qs[i].claude.pct;
1611 best_c = accts[i].email;
1612 }
1613 }
1614 }
1615
1616 buf_init(&b);
1617 buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":");
1618 buf_json(&b, selected);
1619 buf_adds(&b, ",\"best_gemini\":");
1620 buf_json(&b, best_g);
1621 buf_adds(&b, ",\"best_argon\":");
1622 buf_json(&b, best_a);
1623 buf_adds(&b, ",\"best_claude\":");
1624 buf_json(&b, best_c);
1625 buf_addf(&b, ",\"count\":%d,\"accounts\":[", count);
1626 for (i = 0; i < count; i++) {
1627 if (i > 0) buf_addc(&b, ',');
1628 emit_acct_quota_json(&b, &accts[i], &qs[i]);
1629 }
1630 buf_adds(&b, "]}\n");
1631
1632 free(qs);
1633 json_headers();
1634 fputs(buf_str(&b), stdout);
1635 buf_free(&b);
1636 return 0;
1637 }
1638}
1639
1640static int action_switch(const char *target_email)
1641{
1642 acct_entry_t accts[MAX_ACCOUNTS];
1643 char selected[EMAIL_SZ];
1644 char spath[PATH_SZ];
1645 int count, i, found = 0;
1646 FILE *f;
1647 buf_t b;
1648
1649 if (!target_email || !target_email[0]) {
1650 emit_error(400, "Bad Request", "missing_account", "pass ?account=<email>");
1651 return 1;
1652 }
1653 if (!is_safe_email(target_email)) {
1654 emit_error(400, "Bad Request", "invalid_account", target_email);
1655 return 1;
1656 }
1657
1658 count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected));
1659 for (i = 0; i < count; i++) {
1660 if (strcmp(accts[i].email, target_email) == 0) { found = 1; break; }
1661 }
1662 if (!found) {
1663 emit_error(404, "Not Found", "unknown_account", target_email);
1664 return 1;
1665 }
1666
1667 selected_path(spath, sizeof(spath));
1668 f = fopen(spath, "wb");
1669 if (!f) {
1670 emit_error(500, "Internal Server Error", "write_failed", strerror(errno));
1671 return 1;
1672 }
1673 fprintf(f, "%s\n", target_email);
1674 fclose(f);
1675
1676 buf_init(&b);
1677 buf_adds(&b, "{\"ok\":true,\"selected\":");
1678 buf_json(&b, target_email);
1679 buf_adds(&b, "}\n");
1680 json_headers();
1681 fputs(buf_str(&b), stdout);
1682 buf_free(&b);
1683 return 0;
1684}
1685
1686/* ------------------------------------------------------------------ */
1687/* HTML emission */
1688/* ------------------------------------------------------------------ */
1689
1690static void emit_ui(void)
1691{
1692 const char *p = UI_HTML;
1693
1694 while (*p) {
1695 if (*p == '\001') {
1696 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1697 p++;
1698 } else if (*p == '\002') {
1699 fputs(SX_BOT_THEME_HANDOFF, stdout);
1700 p++;
1701 } else {
1702 putchar(*p++);
1703 }
1704 }
1705}
1706
1707/* ------------------------------------------------------------------ */
1708/* main */
1709/* ------------------------------------------------------------------ */
1710
1711static void read_post_account(char *out, size_t outsz)
1712{
1713 const char *cl = getenv("CONTENT_LENGTH");
1714 long n = (cl && *cl) ? atol(cl) : 0;
1715 char body[4096];
1716 size_t len = 0;
1717
1718 if (n > 0 && n < (long)sizeof(body)) {
1719 len = fread(body, 1, (size_t)n, stdin);
1720 } else {
1721 const char *pbf = getenv("POST_BODY_FILE");
1722 if (pbf && *pbf) {
1723 char *fbuf = read_file(pbf);
1724 if (fbuf) {
1725 len = strlen(fbuf);
1726 if (len >= sizeof(body)) len = sizeof(body) - 1;
1727 memcpy(body, fbuf, len);
1728 free(fbuf);
1729 }
1730 }
1731 }
1732 if (len == 0) return;
1733 body[len] = '\0';
1734 if (!json_str_field(body, body + len, "account", out, outsz))
1735 json_str_field(body, body + len, "email", out, outsz);
1736}
1737
1738int main(int argc, char **argv)
1739{
1740 const char *qs;
1741 char action[64] = {0};
1742
1743#if defined(_WIN32)
1744 _setmode(_fileno(stdout), _O_BINARY);
1745#endif
1746
1747 /* 1. Discovery metadata. Must stay unauthenticated. */
1748 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1749 puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1750 return 0;
1751 }
1752 if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1753 puts(PLUGIN_ID " " PLUGIN_VER);
1754 return 0;
1755 }
1756
1757 require_node_auth();
1758
1759 qs = getenv("QUERY_STRING");
1760 if (!qs) qs = "";
1761
1762 /* 2. JSON API mode. */
1763 if (query_has(qs, "action") || query_has(qs, "format")) {
1764 char fmt[32] = {0};
1765 char account[EMAIL_SZ] = {0};
1766
1767 get_query_val(qs, "action", action, sizeof(action));
1768 get_query_val(qs, "format", fmt, sizeof(fmt));
1769 if (!get_query_val(qs, "account", account, sizeof(account)))
1770 get_query_val(qs, "email", account, sizeof(account));
1771
1772 if (!action[0] && strcmp(fmt, "json") == 0)
1773 snprintf(action, sizeof(action), "quota");
1774
1775 if (strcmp(action, "status") == 0 || !action[0]) return action_status();
1776 if (strcmp(action, "quota") == 0) return action_quota(account);
1777 if (strcmp(action, "switch") == 0) {
1778 if (!account[0]) read_post_account(account, sizeof(account));
1779 return action_switch(account);
1780 }
1781 emit_error(404, "Not Found", "unknown_action", action);
1782 return 1;
1783 }
1784
1785 /* 3. HTML UI mode. */
1786 fputs("Content-Type: text/html; charset=utf-8\r\n"
1787 "Cache-Control: no-store\r\n"
1788 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1789 emit_ui();
1790 return 0;
1791}