/* * plugin_google_quota - SCORPIOX BOT open-source Google Antigravity * multi-account quota monitor and active-account switcher for your node. * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=... / ?format=json -> JSON node API * 3. GET (default) -> responsive HTML UI * * DESIGN NOTE (why there is no TLS and no OAuth client secret here): * Refreshing Google OAuth tokens and calling cloudcode-pa requires an OAuth * client identity and TLS. A public clean-room repository must never carry an * OAuth client secret, so this plugin does not speak TLS at all. It reads the * local account list and active selection files written by * scorpiox-antigravity-login and invokes the node's scorpiox-google-quota CLI: * * ~/.config/google-accounts/antigravity_accounts.json (emails + presence) * ~/.config/google-accounts/selected_account.txt (active email) * * Every path and the quota CLI can be overridden for testing or relocation: * * GOOGLE_ACCOUNTS_FILE accounts JSON (also accepts ANTIGRAVITY_CREDS_PATH) * GOOGLE_SELECTED_FILE selected account file (default: sibling selected_account.txt) * GOOGLE_QUOTA_BIN quota CLI binary (default: scorpiox-google-quota) * * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. When reading * antigravity_accounts.json, only email and refresh_token presence (boolean) * are recorded; token strings are never copied or emitted. * * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang * and x86_64-w64-mingw32-gcc -static. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include # define popen _popen # define pclose _pclose # define PATH_SEP '\\' #else # include # include # include # include # include # include # define PATH_SEP '/' #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "google-quota" #define PLUGIN_ID "plugin_google_quota" #define PLUGIN_VER "1.0.3" #define PLUGIN_NAME "google quota" #define PLUGIN_DESC "Account quotas" #define DEFAULT_QUOTA_BIN "scorpiox-google-quota" #define PATH_SZ 1024 #define EMAIL_SZ 256 #define PROJ_SZ 256 #define MODEL_SZ 128 #define RESET_SZ 64 #define CMD_SZ 4096 #define FIELD_SZ 512 #define OUT_MAX (512 * 1024) #define MAX_ACCOUNTS 64 #define MAX_MODELS 128 #define MAX_WORKERS 8 /* ------------------------------------------------------------------ */ /* Growable byte buffer */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t n; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } static int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; if (want <= b->cap) return 1; if (b->cap == 0) b->cap = 1024; while (b->cap < want) { if (b->cap > (size_t)32 * 1024 * 1024) return 0; b->cap *= 2; } np = (char *)realloc(b->p, b->cap); if (!np) return 0; b->p = np; return 1; } static int buf_add(buf_t *b, const char *s, size_t len) { if (!s || len == 0) return 1; if (!buf_need(b, len)) return 0; memcpy(b->p + b->n, s, len); b->n += len; b->p[b->n] = '\0'; return 1; } static int buf_adds(buf_t *b, const char *s) { return s ? buf_add(b, s, strlen(s)) : 1; } static int buf_addc(buf_t *b, char c) { return buf_add(b, &c, 1); } static int buf_addf(buf_t *b, const char *fmt, ...) { char tmp[2048]; int n; va_list ap; va_start(ap, fmt); n = vsnprintf(tmp, sizeof(tmp), fmt, ap); va_end(ap); if (n < 0) return 0; if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); { char *big = (char *)malloc((size_t)n + 1); int ok; if (!big) return 0; va_start(ap, fmt); vsnprintf(big, (size_t)n + 1, fmt, ap); va_end(ap); ok = buf_add(b, big, (size_t)n); free(big); return ok; } } static int buf_json(buf_t *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); if (!buf_addc(b, '"')) return 0; for (; *p; p++) { switch (*p) { case '"': if (!buf_adds(b, "\\\"")) return 0; break; case '\\': if (!buf_adds(b, "\\\\")) return 0; break; case '\n': if (!buf_adds(b, "\\n")) return 0; break; case '\r': if (!buf_adds(b, "\\r")) return 0; break; case '\t': if (!buf_adds(b, "\\t")) return 0; break; default: if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", (unsigned)*p)) return 0; } else { if (!buf_addc(b, (char)*p)) return 0; } } } return buf_addc(b, '"'); } static const char *buf_str(const buf_t *b) { return b->p ? b->p : ""; } static void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->n = 0; b->cap = 0; } /* ------------------------------------------------------------------ */ /* String, query & env helpers */ /* ------------------------------------------------------------------ */ static int ascii_strncasecmp(const char *a, const char *b, size_t n) { size_t i; for (i = 0; i < n; i++) { unsigned char ca = (unsigned char)a[i]; unsigned char cb = (unsigned char)b[i]; int da = tolower(ca); int db = tolower(cb); if (da != db) return da - db; if (ca == '\0') return 0; } return 0; } static void trim_tail(char *s) { size_t n; if (!s) return; n = strlen(s); while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || s[n - 1] == '\r' || s[n - 1] == '\n')) { s[--n] = '\0'; } } static void url_decode(char *s) { char *w = s; char *r = s; if (!s) return; while (*r) { if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; *w++ = (char)((hi << 4) | lo); r += 3; } else if (*r == '+') { *w++ = ' '; r++; } else { *w++ = *r++; } } *w = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static int query_has(const char *qs, const char *key) { size_t klen; const char *p; if (!qs || !key) return 0; klen = strlen(key); p = qs; while (p && *p) { if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) return 1; p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void set_env_var(const char *k, const char *v) { #if defined(_WIN32) _putenv_s(k, v ? v : ""); #else setenv(k, v ? v : "", 1); #endif } static void unset_env_var(const char *k) { #if defined(_WIN32) _putenv_s(k, ""); #else unsetenv(k); #endif } /* ------------------------------------------------------------------ */ /* Node auth (X-Bot-Password / Bearer / ?pwd=) */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256] = {0}; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (ascii_strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Paths & files */ /* ------------------------------------------------------------------ */ static const char *home_dir(void) { #ifdef _WIN32 static char home[512]; DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); if (n > 0 && n < sizeof(home)) return home; { const char *h = getenv("USERPROFILE"); if (h && *h) return h; h = getenv("HOME"); return (h && *h) ? h : NULL; } #else const char *h = getenv("HOME"); return (h && *h) ? h : NULL; #endif } static void accounts_path(char *out, size_t n) { const char *env = getenv("GOOGLE_ACCOUNTS_FILE"); const char *home; if (env && *env) { snprintf(out, n, "%s", env); return; } env = getenv("ANTIGRAVITY_CREDS_PATH"); if (env && *env) { snprintf(out, n, "%s", env); return; } home = home_dir(); if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; } snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json", home, PATH_SEP, PATH_SEP, PATH_SEP); } static void selected_path(char *out, size_t n) { const char *env = getenv("GOOGLE_SELECTED_FILE"); char base[PATH_SZ]; char *slash; if (env && *env) { snprintf(out, n, "%s", env); return; } accounts_path(base, sizeof(base)); slash = strrchr(base, PATH_SEP); if (!slash) slash = strrchr(base, '/'); if (!slash) { snprintf(out, n, "selected_account.txt"); return; } *(slash + 1) = '\0'; snprintf(out, n, "%sselected_account.txt", base); } static const char *quota_bin(void) { const char *b = getenv("GOOGLE_QUOTA_BIN"); return (b && *b) ? b : DEFAULT_QUOTA_BIN; } #if defined(_WIN32) static int file_exists(const char *p) { DWORD a = GetFileAttributesA(p); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); } #endif static int bin_available(const char *bin) { if (!bin || !*bin) return 0; #if defined(_WIN32) { char full[MAX_PATH]; DWORD n; if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) return file_exists(bin); n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); return n > 0 && n < (DWORD)sizeof(full); } #else if (strchr(bin, '/')) { struct stat st; return stat(bin, &st) == 0 && S_ISREG(st.st_mode) && access(bin, X_OK) == 0; } { const char *path_env = getenv("PATH"); const char *p; if (!path_env || !*path_env) return 0; p = path_env; while (*p) { const char *colon = strchr(p, ':'); size_t dlen = colon ? (size_t)(colon - p) : strlen(p); char cand[PATH_SZ]; if (dlen > 0 && dlen + 1 + strlen(bin) + 1 < sizeof(cand)) { struct stat st; memcpy(cand, p, dlen); cand[dlen] = '/'; strcpy(cand + dlen + 1, bin); if (stat(cand, &st) == 0 && S_ISREG(st.st_mode) && access(cand, X_OK) == 0) return 1; } if (!colon) break; p = colon + 1; } return 0; } #endif } static char *read_file(const char *path) { FILE *f; long sz; char *buf; if (!path || !*path) return NULL; f = fopen(path, "rb"); if (!f) return NULL; if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } sz = ftell(f); if (sz < 0 || sz > 4 * 1024 * 1024) { fclose(f); return NULL; } rewind(f); buf = (char *)malloc((size_t)sz + 1); if (!buf) { fclose(f); return NULL; } if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { free(buf); fclose(f); return NULL; } buf[sz] = '\0'; fclose(f); return buf; } /* ------------------------------------------------------------------ */ /* Minimal JSON scanner (read-only, zero dependencies) */ /* ------------------------------------------------------------------ */ static const char *json_skip_ws(const char *p, const char *end) { while (p && p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; return p; } static const char *json_skip_value(const char *p) { int depth = 0; int in_str = 0; if (!p) return NULL; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; if (!*p) return NULL; if (*p != '{' && *p != '[' && *p != '"') { while (*p && *p != ',' && *p != '}' && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++; return p; } for (; *p; p++) { if (in_str) { if (*p == '\\' && p[1]) { p++; continue; } if (*p == '"') { in_str = 0; if (depth == 0) return p + 1; } continue; } if (*p == '"') { in_str = 1; continue; } if (*p == '{' || *p == '[') { depth++; continue; } if (*p == '}' || *p == ']') { depth--; if (depth <= 0) return p + 1; } } return p; } static int json_read_string_at(const char **pp, char *out, size_t outsz) { const char *p = *pp; size_t o = 0; if (!p || *p != '"') return 0; p++; while (*p && *p != '"') { unsigned char c = (unsigned char)*p++; if (c == '\\' && *p) { char e = *p++; switch (e) { case '"': c = '"'; break; case '\\': c = '\\'; break; case '/': c = '/'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = (unsigned char)e; break; } } if (o + 1 < outsz) out[o++] = (char)c; } if (*p == '"') p++; out[o] = '\0'; *pp = p; return 1; } static const char *json_find_key(const char *obj, const char *end, const char *key) { const char *p = obj; size_t klen = strlen(key); int depth = 0; p = json_skip_ws(p, end); if (p < end && *p == '{') p++; while (p && p < end) { if (*p == '"') { char name[128]; json_read_string_at(&p, name, sizeof(name)); if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { const char *q = json_skip_ws(p, end); if (q < end && *q == ':') { q = json_skip_ws(q + 1, end); return (q < end) ? q : NULL; } } continue; } if (*p == '{' || *p == '[') depth++; else if (*p == '}' || *p == ']') depth--; p++; } return NULL; } static int json_str_field(const char *obj, const char *end, const char *key, char *out, size_t outsz) { const char *v; if (!out || outsz == 0) return 0; v = json_find_key(obj, end, key); if (!v || *v == 'n') return 0; out[0] = '\0'; if (*v == '"') return json_read_string_at(&v, out, outsz); { size_t i = 0; while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; trim_tail(out); return out[0] ? 1 : 0; } } static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) { const char *v = json_find_key(obj, end, key); if (!v) return dflt; if (strncmp(v, "true", 4) == 0) return 1; if (strncmp(v, "false", 5) == 0) return 0; if (*v == '1') return 1; return 0; } /* Returns 1 if numeric value parsed into *out, 0 if missing or null. */ static int json_double_field(const char *obj, const char *end, const char *key, double *out) { const char *v = json_find_key(obj, end, key); char *ep = NULL; double val; if (!v || *v == 'n') return 0; if (*v != '-' && !isdigit((unsigned char)*v) && *v != '.') return 0; val = strtod(v, &ep); if (ep == v) return 0; *out = val; return 1; } /* ------------------------------------------------------------------ */ /* Account list loading (never copies refresh_token) */ /* ------------------------------------------------------------------ */ typedef struct { char email[EMAIL_SZ]; int has_refresh; int selected; } acct_entry_t; static int is_safe_email(const char *s) { int has_at = 0; const char *p; if (!s || !*s || strlen(s) >= EMAIL_SZ) return 0; for (p = s; *p; p++) { unsigned char c = (unsigned char)*p; if (c == '@') { has_at = 1; continue; } if (isalnum(c) || c == '.' || c == '_' || c == '-' || c == '+') continue; return 0; } return has_at; } static int load_accounts(acct_entry_t *list, int max_n, char *selected_out, size_t sel_sz) { char apath[PATH_SZ], spath[PATH_SZ]; char *raw_sel, *raw_accts; int count = 0; selected_out[0] = '\0'; selected_path(spath, sizeof(spath)); raw_sel = read_file(spath); if (raw_sel) { trim_tail(raw_sel); if (is_safe_email(raw_sel)) snprintf(selected_out, sel_sz, "%s", raw_sel); free(raw_sel); } accounts_path(apath, sizeof(apath)); raw_accts = read_file(apath); if (!raw_accts) return 0; { const char *p = raw_accts; while (p && *p && count < max_n) { const char *open = strchr(p, '{'); const char *end; char email[EMAIL_SZ] = {0}; char rt_probe[8] = {0}; int has_rt = 0; int dup = 0; int i; if (!open) break; end = json_skip_value(open); if (!end || end <= open) break; json_str_field(open, end, "email", email, sizeof(email)); /* Presence check only: never copy or retain the refresh token. */ if (json_str_field(open, end, "refresh_token", rt_probe, sizeof(rt_probe)) && rt_probe[0]) has_rt = 1; if (is_safe_email(email)) { for (i = 0; i < count; i++) { if (strcmp(list[i].email, email) == 0) { if (has_rt) list[i].has_refresh = 1; dup = 1; break; } } if (!dup) { snprintf(list[count].email, sizeof(list[count].email), "%s", email); list[count].has_refresh = has_rt; list[count].selected = (selected_out[0] && strcmp(selected_out, email) == 0) ? 1 : 0; count++; } } p = end; } } free(raw_accts); return count; } /* ------------------------------------------------------------------ */ /* Child process execution */ /* ------------------------------------------------------------------ */ static void prepare_quota_env(void) { char apath[PATH_SZ]; accounts_path(apath, sizeof(apath)); /* Clear profile/token overrides so --account always resolves from the * local accounts file rather than an inherited agent profile. */ unset_env_var("ACTIVE_PROFILE"); unset_env_var("GOOGLE_ACCESS_TOKEN"); unset_env_var("GOOGLE_REMOTE_URL"); unset_env_var("GOOGLE_PROJECT_ID"); unset_env_var("GOOGLE_ACCOUNT"); set_env_var("GOOGLE_TOKEN_SOURCE", "local"); set_env_var("GOOGLE_ACCOUNTS_FILE", apath); } #if defined(_WIN32) static void shell_quote_into(const char *in, char *out, size_t outsz) { size_t o = 0; const char *p; if (outsz < 3) { if (outsz) out[0] = '\0'; return; } out[o++] = '"'; for (p = in; p && *p; p++) { if (*p == '"') { if (o + 3 >= outsz) break; out[o++] = '\\'; out[o++] = '"'; } else { if (o + 2 >= outsz) break; out[o++] = *p; } } out[o++] = '"'; out[o] = '\0'; } static int run_quota_one(const char *bin, const char *email, buf_t *out) { char cmd[CMD_SZ]; char qbin[FIELD_SZ]; char qemail[EMAIL_SZ + 16]; FILE *f; char line[2048]; size_t total = 0; int rc; if (!bin || !*bin || !is_safe_email(email)) return 0; if (!bin_available(bin)) return -1; shell_quote_into(bin, qbin, sizeof(qbin)); shell_quote_into(email, qemail, sizeof(qemail)); snprintf(cmd, sizeof(cmd), "%s --account %s --json 2>NUL", qbin, qemail); f = popen(cmd, "r"); if (!f) return 0; while (fgets(line, sizeof(line), f)) { total += strlen(line); if (total > OUT_MAX) break; buf_adds(out, line); } rc = pclose(f); if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1; return (rc == 0) ? 1 : 0; } #else static int run_quota_one(const char *bin, const char *email, buf_t *out) { int pfd[2]; pid_t pid; char chunk[4096]; ssize_t n; int status = 0; if (!bin || !*bin || !is_safe_email(email)) return 0; if (!bin_available(bin)) return -1; if (pipe(pfd) != 0) return 0; pid = fork(); if (pid < 0) { close(pfd[0]); close(pfd[1]); return 0; } if (pid == 0) { int devnull = open("/dev/null", O_WRONLY); char *argv_exec[5]; close(pfd[0]); dup2(pfd[1], STDOUT_FILENO); close(pfd[1]); if (devnull >= 0) { dup2(devnull, STDERR_FILENO); close(devnull); } argv_exec[0] = (char *)bin; argv_exec[1] = "--account"; argv_exec[2] = (char *)email; argv_exec[3] = "--json"; argv_exec[4] = NULL; execvp(bin, argv_exec); _exit(127); } close(pfd[1]); while ((n = read(pfd[0], chunk, sizeof(chunk))) > 0) { if (out->n + (size_t)n <= OUT_MAX) buf_add(out, chunk, (size_t)n); } close(pfd[0]); if (waitpid(pid, &status, 0) < 0) return 0; if (WIFEXITED(status) && WEXITSTATUS(status) == 127) return -1; return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 1 : 0; } #endif /* ------------------------------------------------------------------ */ /* Quota parsing & pool aggregation */ /* ------------------------------------------------------------------ */ typedef struct { char id[MODEL_SZ]; char pool[16]; double pct; int exhausted; char reset_time[RESET_SZ]; } model_quota_t; typedef struct { int present; double pct; int exhausted; char reset_time[RESET_SZ]; int count; } pool_summary_t; typedef struct { int present; char bucket_id[64]; double pct; int exhausted; char reset_time[RESET_SZ]; } window_limit_t; typedef struct { window_limit_t five_hour; window_limit_t weekly; } pool_limits_t; typedef struct { int ok; int cli_missing; char error[64]; char project[PROJ_SZ]; pool_summary_t gemini; pool_summary_t argon; pool_summary_t claude; pool_limits_t gemini_limits; pool_limits_t claude_limits; model_quota_t models[MAX_MODELS]; int model_count; } acct_quota_t; static void pool_init(pool_summary_t *p) { p->present = 0; p->pct = -1.0; p->exhausted = 0; p->reset_time[0] = '\0'; p->count = 0; } static void pool_add(pool_summary_t *p, double pct, int exhausted, const char *reset) { if (!p->present || pct < p->pct) p->pct = pct; p->present = 1; if (exhausted || pct <= 0.0) p->exhausted = 1; if (reset && reset[0] && (!p->reset_time[0] || strcmp(reset, p->reset_time) < 0)) snprintf(p->reset_time, sizeof(p->reset_time), "%s", reset); p->count++; } static const char *find_json_root(const buf_t *b) { const char *p; if (!b || !b->p) return NULL; p = b->p; while (*p) { if (*p == '{') return p; p = strchr(p, '\n'); if (!p) break; p++; } return strchr(b->p, '{'); } static void parse_quota_output(const buf_t *raw, int run_rc, acct_quota_t *q) { const char *root; const char *root_end; const char *buckets; const char *buckets_end; const char *p; memset(q, 0, sizeof(*q)); pool_init(&q->gemini); pool_init(&q->argon); pool_init(&q->claude); if (run_rc == -1) { q->cli_missing = 1; snprintf(q->error, sizeof(q->error), "cli_unavailable"); return; } root = find_json_root(raw); if (!root) { snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); return; } root_end = json_skip_value(root); if (!root_end || root_end <= root) { snprintf(q->error, sizeof(q->error), "invalid_quota_json"); return; } if (!json_bool_field(root, root_end, "ok", 0)) { json_str_field(root, root_end, "error", q->error, sizeof(q->error)); if (!q->error[0]) snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); return; } json_str_field(root, root_end, "project", q->project, sizeof(q->project)); buckets = json_find_key(root, root_end, "buckets"); if (!buckets || *buckets != '[') { snprintf(q->error, sizeof(q->error), "missing_buckets"); return; } buckets_end = json_skip_value(buckets); if (!buckets_end || buckets_end <= buckets) { snprintf(q->error, sizeof(q->error), "invalid_buckets"); return; } p = buckets + 1; while (p && p < buckets_end) { const char *open = strchr(p, '{'); const char *end; char mid[MODEL_SZ] = {0}; char rst[RESET_SZ] = {0}; double frac = 0.0; double pct = 0.0; int exhausted = 0; const char *pool_name = "other"; if (!open || open >= buckets_end) break; end = json_skip_value(open); if (!end || end <= open || end > buckets_end) break; json_str_field(open, end, "modelId", mid, sizeof(mid)); json_str_field(open, end, "resetTime", rst, sizeof(rst)); if (mid[0] && strncmp(mid, "chat_", 5) != 0 && strncmp(mid, "tab_", 4) != 0) { if (json_double_field(open, end, "remainingFraction", &frac)) { pct = frac * 100.0; if (pct < 0.0) pct = 0.0; if (pct > 100.0) pct = 100.0; if (frac <= 0.0) exhausted = 1; } else { /* Absent or null remainingFraction means exhausted. */ pct = 0.0; exhausted = 1; } if (strncmp(mid, "gemini-4-argon", 14) == 0) { pool_name = "argon"; pool_add(&q->argon, pct, exhausted, rst); } else if (strncmp(mid, "gemini-", 7) == 0) { pool_name = "gemini"; pool_add(&q->gemini, pct, exhausted, rst); } else if (strncmp(mid, "claude-", 7) == 0) { pool_name = "claude"; pool_add(&q->claude, pct, exhausted, rst); } if (q->model_count < MAX_MODELS) { model_quota_t *m = &q->models[q->model_count++]; snprintf(m->id, sizeof(m->id), "%s", mid); snprintf(m->pool, sizeof(m->pool), "%s", pool_name); m->pct = pct; m->exhausted = exhausted; snprintf(m->reset_time, sizeof(m->reset_time), "%s", rst); } } p = end; } /* Optional: parse summary.groups (from retrieveUserQuotaSummary) for * explicit 5-hour and weekly quota limits. */ { const char *sum = json_find_key(root, root_end, "summary"); if (sum && *sum == '{') { const char *sum_end = json_skip_value(sum); const char *groups = (sum_end && sum_end > sum) ? json_find_key(sum, sum_end, "groups") : NULL; if (groups && *groups == '[') { const char *groups_end = json_skip_value(groups); const char *gp = groups + 1; while (gp && groups_end && gp < groups_end) { const char *gopen = strchr(gp, '{'); const char *gend; char gname[128] = {0}; const char *gb; const char *gb_end; if (!gopen || gopen >= groups_end) break; gend = json_skip_value(gopen); if (!gend || gend <= gopen || gend > groups_end) break; json_str_field(gopen, gend, "displayName", gname, sizeof(gname)); gb = json_find_key(gopen, gend, "buckets"); if (gb && *gb == '[') { gb_end = json_skip_value(gb); if (gb_end && gb_end > gb && gb_end <= gend) { const char *bp = gb + 1; while (bp && bp < gb_end) { const char *bopen = strchr(bp, '{'); const char *bend; char bid[64] = {0}; char win[32] = {0}; char rst[RESET_SZ] = {0}; double frac = 0.0; double pct = -1.0; int exhausted = 0; pool_limits_t *target_pool = NULL; window_limit_t *target_win = NULL; if (!bopen || bopen >= gb_end) break; bend = json_skip_value(bopen); if (!bend || bend <= bopen || bend > gb_end) break; json_str_field(bopen, bend, "bucketId", bid, sizeof(bid)); json_str_field(bopen, bend, "window", win, sizeof(win)); json_str_field(bopen, bend, "resetTime", rst, sizeof(rst)); if (json_double_field(bopen, bend, "remainingFraction", &frac)) { pct = frac * 100.0; if (pct < 0.0) pct = 0.0; if (pct > 100.0) pct = 100.0; if (frac <= 0.0) exhausted = 1; } else if (rst[0]) { pct = 0.0; exhausted = 1; } if (strncmp(bid, "gemini-", 7) == 0 || strstr(gname, "Gemini") || strstr(gname, "gemini")) { target_pool = &q->gemini_limits; } else if (strncmp(bid, "3p-", 3) == 0 || strstr(gname, "Claude") || strstr(gname, "claude") || strstr(gname, "GPT")) { target_pool = &q->claude_limits; } if (target_pool && pct >= 0.0) { if (strcmp(win, "5h") == 0 || strstr(bid, "-5h")) target_win = &target_pool->five_hour; else if (strcmp(win, "weekly") == 0 || strstr(bid, "-weekly")) target_win = &target_pool->weekly; } if (target_win) { target_win->present = 1; snprintf(target_win->bucket_id, sizeof(target_win->bucket_id), "%s", bid); target_win->pct = pct; target_win->exhausted = exhausted; snprintf(target_win->reset_time, sizeof(target_win->reset_time), "%s", rst); } bp = bend; } } } gp = gend; } } } } q->ok = 1; } static void fetch_all_quotas(const char *bin, const acct_entry_t *accts, int count, acct_quota_t *out_q) { #if defined(_WIN32) int i; for (i = 0; i < count; i++) { buf_t raw; int rc; buf_init(&raw); rc = run_quota_one(bin, accts[i].email, &raw); parse_quota_output(&raw, rc, &out_q[i]); buf_free(&raw); } #else int next_idx = 0; int done = 0; if (count <= 0) return; if (!bin_available(bin)) { int i; for (i = 0; i < count; i++) { buf_t empty; buf_init(&empty); parse_quota_output(&empty, -1, &out_q[i]); } return; } { typedef struct { int active; int acct_idx; int fd; pid_t pid; buf_t raw; } worker_t; worker_t w[MAX_WORKERS]; int i; memset(w, 0, sizeof(w)); while (done < count) { struct pollfd pfds[MAX_WORKERS]; int pmap[MAX_WORKERS]; int nfds = 0; for (i = 0; i < MAX_WORKERS && next_idx < count; i++) { if (w[i].active) continue; { int pfd[2]; pid_t pid; if (pipe(pfd) != 0) { buf_t empty; buf_init(&empty); parse_quota_output(&empty, 0, &out_q[next_idx]); next_idx++; done++; continue; } pid = fork(); if (pid < 0) { close(pfd[0]); close(pfd[1]); buf_t empty; buf_init(&empty); parse_quota_output(&empty, 0, &out_q[next_idx]); next_idx++; done++; continue; } if (pid == 0) { int devnull = open("/dev/null", O_WRONLY); char *argv_exec[5]; close(pfd[0]); dup2(pfd[1], STDOUT_FILENO); close(pfd[1]); if (devnull >= 0) { dup2(devnull, STDERR_FILENO); close(devnull); } argv_exec[0] = (char *)bin; argv_exec[1] = "--account"; argv_exec[2] = (char *)accts[next_idx].email; argv_exec[3] = "--json"; argv_exec[4] = NULL; execvp(bin, argv_exec); _exit(127); } close(pfd[1]); w[i].active = 1; w[i].acct_idx = next_idx; w[i].fd = pfd[0]; w[i].pid = pid; buf_init(&w[i].raw); next_idx++; } } for (i = 0; i < MAX_WORKERS; i++) { if (!w[i].active) continue; pfds[nfds].fd = w[i].fd; pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; pmap[nfds] = i; nfds++; } if (nfds == 0) break; if (poll(pfds, (nfds_t)nfds, 30000) < 0) { if (errno == EINTR) continue; break; } for (i = 0; i < nfds; i++) { int wi = pmap[i]; if (pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) { char chunk[4096]; ssize_t n = read(w[wi].fd, chunk, sizeof(chunk)); if (n > 0) { if (w[wi].raw.n + (size_t)n <= OUT_MAX) buf_add(&w[wi].raw, chunk, (size_t)n); } else if (n == 0 || (n < 0 && errno != EINTR)) { int status = 0; int rc = 0; close(w[wi].fd); if (waitpid(w[wi].pid, &status, 0) >= 0) { if (WIFEXITED(status) && WEXITSTATUS(status) == 127) rc = -1; else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) rc = 1; } parse_quota_output(&w[wi].raw, rc, &out_q[w[wi].acct_idx]); buf_free(&w[wi].raw); w[wi].active = 0; done++; } } } } for (i = 0; i < MAX_WORKERS; i++) { if (w[i].active) { int status = 0; close(w[i].fd); waitpid(w[i].pid, &status, 0); parse_quota_output(&w[i].raw, 0, &out_q[w[i].acct_idx]); buf_free(&w[i].raw); w[i].active = 0; } } } #endif } /* ------------------------------------------------------------------ */ /* JSON emitters */ /* ------------------------------------------------------------------ */ static void json_headers(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void emit_error(int code, const char *status, const char *err, const char *detail) { buf_t b; buf_init(&b); buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", code, status); buf_adds(&b, "{\"ok\":false,\"error\":"); buf_json(&b, err); if (detail && *detail) { buf_adds(&b, ",\"detail\":"); buf_json(&b, detail); } buf_adds(&b, "}\n"); fputs(buf_str(&b), stdout); buf_free(&b); } static long long days_from_civil(int y, unsigned m, unsigned d) { y -= (m <= 2) ? 1 : 0; { long long era = (y >= 0 ? y : y - 399) / 400; unsigned yoe = (unsigned)(y - era * 400); unsigned doy = (153U * (m + (m > 2 ? (unsigned)-3 : 9U)) + 2U) / 5U + d - 1U; unsigned doe = yoe * 365U + yoe / 4U - yoe / 100U + doy; return era * 146097LL + (long long)doe - 719468LL; } } static int parse_iso_utc_epoch(const char *iso, long long *out_epoch) { int y = 0, mo = 0, d = 0, hh = 0, mm = 0, ss = 0; const char *t; const char *tz; if (!iso || !*iso) return 0; if (sscanf(iso, "%d-%d-%dT%d:%d:%d", &y, &mo, &d, &hh, &mm, &ss) != 6) return 0; if (mo < 1 || mo > 12 || d < 1 || d > 31 || hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60) return 0; t = strchr(iso, 'T'); if (!t) return 0; { long long days = days_from_civil(y, (unsigned)mo, (unsigned)d); long long epoch = days * 86400LL + (long long)hh * 3600LL + (long long)mm * 60LL + (long long)ss; tz = strpbrk(t, "Z+-"); if (tz && (*tz == '+' || *tz == '-')) { int oh = 0, om = 0; if (sscanf(tz + 1, "%2d:%2d", &oh, &om) >= 1) { long long off = (long long)oh * 3600LL + (long long)om * 60LL; epoch += (*tz == '+') ? -off : off; } } *out_epoch = epoch; return 1; } } static void compute_reset_fields(const char *iso, long long now_epoch, long long *secs_out, double *hrs_out, char *rem_out, size_t rem_sz) { long long target = 0; long long diff; if (!iso || !iso[0] || !parse_iso_utc_epoch(iso, &target)) { *secs_out = -1; *hrs_out = -1.0; if (rem_sz) rem_out[0] = '\0'; return; } diff = target - now_epoch; if (diff <= 0) { *secs_out = 0; *hrs_out = 0.0; snprintf(rem_out, rem_sz, "due"); return; } *secs_out = diff; *hrs_out = (double)diff / 3600.0; { long long days = diff / 86400LL; long long hrs = (diff % 86400LL) / 3600LL; long long mins = (diff % 3600LL) / 60LL; if (days > 0) snprintf(rem_out, rem_sz, "%lldd %lldh", days, hrs); else if (hrs > 0) snprintf(rem_out, rem_sz, "%lldh %02lldm", hrs, mins); else snprintf(rem_out, rem_sz, "%lldm", mins > 0 ? mins : 1LL); } } static void emit_pool_json(buf_t *b, const pool_summary_t *p, long long now_epoch) { long long rsecs = -1; double rhrs = -1.0; char rrem[32] = {0}; if (!p->present) { buf_adds(b, "{\"pct\":-1,\"exhausted\":false,\"reset_time\":\"\"," "\"reset_in_seconds\":-1,\"reset_in_hours\":-1.00," "\"reset_remaining\":\"\",\"count\":0}"); return; } compute_reset_fields(p->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem)); buf_addf(b, "{\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", p->pct, p->exhausted ? "true" : "false"); buf_json(b, p->reset_time); buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":", rsecs, rhrs); buf_json(b, rrem); buf_addf(b, ",\"count\":%d}", p->count); } static void emit_window_limit_json(buf_t *b, const window_limit_t *w, long long now_epoch) { long long rsecs = -1; double rhrs = -1.0; char rrem[32] = {0}; if (!w || !w->present) { buf_adds(b, "null"); return; } compute_reset_fields(w->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem)); buf_adds(b, "{\"bucket_id\":"); buf_json(b, w->bucket_id); buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", w->pct, w->exhausted ? "true" : "false"); buf_json(b, w->reset_time); buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":", rsecs, rhrs); buf_json(b, rrem); buf_addc(b, '}'); } static void emit_acct_quota_json(buf_t *b, const acct_entry_t *a, const acct_quota_t *q) { int i; long long now_epoch = (long long)time(NULL); buf_adds(b, "{\"email\":"); buf_json(b, a->email); buf_addf(b, ",\"selected\":%s,\"has_refresh\":%s,\"ok\":%s", a->selected ? "true" : "false", a->has_refresh ? "true" : "false", q->ok ? "true" : "false"); if (!q->ok) { buf_adds(b, ",\"error\":"); buf_json(b, q->error[0] ? q->error : "quota_fetch_failed"); if (q->cli_missing) { buf_adds(b, ",\"detail\":"); buf_json(b, "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); } buf_addc(b, '}'); return; } buf_adds(b, ",\"project\":"); buf_json(b, q->project); buf_adds(b, ",\"gemini\":"); emit_pool_json(b, &q->gemini, now_epoch); buf_adds(b, ",\"argon\":"); emit_pool_json(b, &q->argon, now_epoch); buf_adds(b, ",\"claude\":"); emit_pool_json(b, &q->claude, now_epoch); buf_adds(b, ",\"limits\":{\"gemini\":{\"five_hour\":"); emit_window_limit_json(b, &q->gemini_limits.five_hour, now_epoch); buf_adds(b, ",\"weekly\":"); emit_window_limit_json(b, &q->gemini_limits.weekly, now_epoch); buf_adds(b, "},\"claude\":{\"five_hour\":"); emit_window_limit_json(b, &q->claude_limits.five_hour, now_epoch); buf_adds(b, ",\"weekly\":"); emit_window_limit_json(b, &q->claude_limits.weekly, now_epoch); buf_adds(b, "}}"); buf_adds(b, ",\"models\":["); for (i = 0; i < q->model_count; i++) { const model_quota_t *m = &q->models[i]; long long rsecs = -1; double rhrs = -1.0; char rrem[32] = {0}; compute_reset_fields(m->reset_time, now_epoch, &rsecs, &rhrs, rrem, sizeof(rrem)); if (i > 0) buf_addc(b, ','); buf_adds(b, "{\"id\":"); buf_json(b, m->id); buf_adds(b, ",\"pool\":"); buf_json(b, m->pool); buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", m->pct, m->exhausted ? "true" : "false"); buf_json(b, m->reset_time); buf_addf(b, ",\"reset_in_seconds\":%lld,\"reset_in_hours\":%.2f,\"reset_remaining\":", rsecs, rhrs); buf_json(b, rrem); buf_addc(b, '}'); } buf_adds(b, "]}"); } /* ------------------------------------------------------------------ */ /* Actions */ /* ------------------------------------------------------------------ */ static int action_status(void) { acct_entry_t accts[MAX_ACCOUNTS]; char selected[EMAIL_SZ]; char apath[PATH_SZ], spath[PATH_SZ]; int count, i; int cli_ok; buf_t b; count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); accounts_path(apath, sizeof(apath)); selected_path(spath, sizeof(spath)); cli_ok = bin_available(quota_bin()); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); buf_json(&b, selected); buf_adds(&b, ",\"accounts_path\":"); buf_json(&b, apath); buf_adds(&b, ",\"selected_path\":"); buf_json(&b, spath); buf_addf(&b, ",\"cli_present\":%s,\"count\":%d,\"accounts\":[", cli_ok ? "true" : "false", count); for (i = 0; i < count; i++) { if (i > 0) buf_addc(&b, ','); buf_adds(&b, "{\"email\":"); buf_json(&b, accts[i].email); buf_addf(&b, ",\"has_refresh\":%s,\"selected\":%s}", accts[i].has_refresh ? "true" : "false", accts[i].selected ? "true" : "false"); } buf_adds(&b, "]}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } static int action_quota(const char *target_email) { acct_entry_t accts[MAX_ACCOUNTS]; char selected[EMAIL_SZ]; int count, i; const char *bin = quota_bin(); buf_t b; count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); prepare_quota_env(); if (target_email && target_email[0]) { int idx = -1; buf_t raw; acct_quota_t q; int rc; for (i = 0; i < count; i++) { if (strcmp(accts[i].email, target_email) == 0) { idx = i; break; } } if (idx < 0) { emit_error(404, "Not Found", "unknown_account", target_email); return 1; } buf_init(&raw); rc = run_quota_one(bin, accts[idx].email, &raw); parse_quota_output(&raw, rc, &q); buf_free(&raw); if (q.cli_missing) { emit_error(200, "OK", "cli_unavailable", "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); return 1; } buf_init(&b); buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); buf_json(&b, selected); buf_adds(&b, ",\"account\":"); emit_acct_quota_json(&b, &accts[idx], &q); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } { acct_quota_t *qs = NULL; const char *best_g = ""; const char *best_a = ""; const char *best_c = ""; double best_gp = -1.0; double best_ap = -1.0; double best_cp = -1.0; if (count > 0) { qs = (acct_quota_t *)calloc((size_t)count, sizeof(acct_quota_t)); if (!qs) { emit_error(500, "Internal Server Error", "oom", "out of memory"); return 1; } fetch_all_quotas(bin, accts, count, qs); if (qs[0].cli_missing) { free(qs); emit_error(200, "OK", "cli_unavailable", "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); return 1; } for (i = 0; i < count; i++) { if (!qs[i].ok) continue; if (qs[i].gemini.present && !qs[i].gemini.exhausted && qs[i].gemini.pct > best_gp) { best_gp = qs[i].gemini.pct; best_g = accts[i].email; } if (qs[i].argon.present && !qs[i].argon.exhausted && qs[i].argon.pct > best_ap) { best_ap = qs[i].argon.pct; best_a = accts[i].email; } if (qs[i].claude.present && !qs[i].claude.exhausted && qs[i].claude.pct > best_cp) { best_cp = qs[i].claude.pct; best_c = accts[i].email; } } } buf_init(&b); buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); buf_json(&b, selected); buf_adds(&b, ",\"best_gemini\":"); buf_json(&b, best_g); buf_adds(&b, ",\"best_argon\":"); buf_json(&b, best_a); buf_adds(&b, ",\"best_claude\":"); buf_json(&b, best_c); buf_addf(&b, ",\"count\":%d,\"accounts\":[", count); for (i = 0; i < count; i++) { if (i > 0) buf_addc(&b, ','); emit_acct_quota_json(&b, &accts[i], &qs[i]); } buf_adds(&b, "]}\n"); free(qs); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } } static int action_switch(const char *target_email) { acct_entry_t accts[MAX_ACCOUNTS]; char selected[EMAIL_SZ]; char spath[PATH_SZ]; int count, i, found = 0; FILE *f; buf_t b; if (!target_email || !target_email[0]) { emit_error(400, "Bad Request", "missing_account", "pass ?account="); return 1; } if (!is_safe_email(target_email)) { emit_error(400, "Bad Request", "invalid_account", target_email); return 1; } count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); for (i = 0; i < count; i++) { if (strcmp(accts[i].email, target_email) == 0) { found = 1; break; } } if (!found) { emit_error(404, "Not Found", "unknown_account", target_email); return 1; } selected_path(spath, sizeof(spath)); f = fopen(spath, "wb"); if (!f) { emit_error(500, "Internal Server Error", "write_failed", strerror(errno)); return 1; } fprintf(f, "%s\n", target_email); fclose(f); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"selected\":"); buf_json(&b, target_email); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } /* ------------------------------------------------------------------ */ /* HTML emission */ /* ------------------------------------------------------------------ */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ static void read_post_account(char *out, size_t outsz) { const char *cl = getenv("CONTENT_LENGTH"); long n = (cl && *cl) ? atol(cl) : 0; char body[4096]; size_t len = 0; if (n > 0 && n < (long)sizeof(body)) { len = fread(body, 1, (size_t)n, stdin); } else { const char *pbf = getenv("POST_BODY_FILE"); if (pbf && *pbf) { char *fbuf = read_file(pbf); if (fbuf) { len = strlen(fbuf); if (len >= sizeof(body)) len = sizeof(body) - 1; memcpy(body, fbuf, len); free(fbuf); } } } if (len == 0) return; body[len] = '\0'; if (!json_str_field(body, body + len, "account", out, outsz)) json_str_field(body, body + len, "email", out, outsz); } int main(int argc, char **argv) { const char *qs; char action[64] = {0}; #if defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); #endif /* 1. Discovery metadata. Must stay unauthenticated. */ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); return 0; } if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { puts(PLUGIN_ID " " PLUGIN_VER); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; /* 2. JSON API mode. */ if (query_has(qs, "action") || query_has(qs, "format")) { char fmt[32] = {0}; char account[EMAIL_SZ] = {0}; get_query_val(qs, "action", action, sizeof(action)); get_query_val(qs, "format", fmt, sizeof(fmt)); if (!get_query_val(qs, "account", account, sizeof(account))) get_query_val(qs, "email", account, sizeof(account)); if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "quota"); if (strcmp(action, "status") == 0 || !action[0]) return action_status(); if (strcmp(action, "quota") == 0) return action_quota(account); if (strcmp(action, "switch") == 0) { if (!account[0]) read_post_account(account, sizeof(account)); return action_switch(account); } emit_error(404, "Not Found", "unknown_action", action); return 1; } /* 3. HTML UI mode. */ fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); emit_ui(); return 0; }