/* * sx_connector.c -- SCORPIOX BOT Connector SDK core. See sx_connector.h. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #define _DEFAULT_SOURCE #define _POSIX_C_SOURCE 200809L #define _GNU_SOURCE #include "sx_connector.h" #include #include #include #include #include #include #include #if defined(_WIN32) # include # include # include /* _O_BINARY (MinGW's alone does not define it) */ # include # include # define SX_MKDIR(p) _mkdir(p) #else # include # include # include # include # define SX_MKDIR(p) mkdir((p), 0755) #endif /* ===================================================================== * identity + dispatch * ===================================================================== */ void sx_copy(char *dst, size_t capsz, const char *src) { if (!capsz) return; if (!src) { dst[0] = '\0'; return; } snprintf(dst, capsz, "%s", src); } int sx_ieq(const char *a, const char *b) { if (!a || !b) return 0; while (*a && *b) { if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0; a++; b++; } return *a == 0 && *b == 0; } void sx_info_fill(sx_plugin_info *info) { if (!info->id) info->id = "connector"; if (!info->name || !*info->name) info->name = info->id; if (!info->desc) info->desc = ""; if (!info->kind || !*info->kind) info->kind = SX_KIND_UI; if (!info->verified || !*info->verified) info->verified = "mock"; if (!info->version) info->version = "1.0.0"; if (info->menus < 0) info->menus = (strcmp(info->kind, SX_KIND_UI) == 0 || strcmp(info->kind, SX_KIND_HYBRID) == 0) ? 1 : 0; } void sx_meta_emit(const sx_plugin_info *info) { sx_plugin_info in = *info; yyjson_mut_doc *doc; char *s; sx_info_fill(&in); doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_strcpy(doc, root, "name", in.name); yyjson_mut_obj_add_strcpy(doc, root, "desc", in.desc); yyjson_mut_obj_add_strcpy(doc, root, "kind", in.kind); yyjson_mut_obj_add_bool(doc, root, "mcp", in.mcp ? 1 : 0); yyjson_mut_obj_add_bool(doc, root, "daemon", in.daemon ? 1 : 0); yyjson_mut_obj_add_bool(doc, root, "menus", in.menus ? 1 : 0); yyjson_mut_obj_add_strcpy(doc, root, "verified", in.verified); yyjson_mut_obj_add_strcpy(doc, root, "version", in.version); s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL); if (s) { puts(s); free(s); } yyjson_mut_doc_free(doc); fflush(stdout); } void sx_stdio_binary(void) { #if defined(_WIN32) _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stderr), _O_BINARY); #endif } /* Ignore SIGPIPE for the whole process. * * A connector writes to sockets whose peer can vanish at any moment: the * node API closes after every `Connection: close` answer, a WebSocket relay * drops between frames. The default SIGPIPE disposition kills the process * (or, worse, returns into whatever frame the signal landed in and leaves a * garbage errno behind on the socket call), which turns a recoverable * "connection gone" into a crashed daemon or a nonsense HTTP status. * * With SIGPIPE ignored every lost write is an ordinary send() == -1 with * EPIPE, which the SDK already reports as a clean error string. * * This is deliberately process-wide and safe to call more than once. A * connector that genuinely wants SIGPIPE can reinstate it after calling * sx_main()/sx_mcp_serve()/sx_daemon_run() setup. */ void sx_ignore_sigpipe(void) { #if !defined(_WIN32) signal(SIGPIPE, SIG_IGN); #endif } int sx_has_flag(int argc, char **argv, const char *flag) { int i; for (i = 1; i < argc; i++) if (strcmp(argv[i], flag) == 0) return 1; return 0; } /* ===================================================================== * CGI helpers * ===================================================================== */ const char *sx_node_password(void) { const char *p = getenv("BOT_PASSWORD"); if (p && !*p) return NULL; return p; } int sx_query_get(const char *query, const char *key, char *buf, size_t capsz) { size_t klen; const char *p = query; if (buf && capsz) buf[0] = '\0'; if (!query || !*query || !key || !buf || !capsz) return 0; klen = strlen(key); while (*p) { const char *eq = strchr(p, '='); const char *amp = strchr(p, '&'); if (!amp) amp = p + strlen(p); if (eq && eq < amp && (size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { size_t o = 0; const char *v = eq + 1; while (v < amp && *v && o + 1 < capsz) { if (*v == '%') { int hi = -1, lo = -1; if (isxdigit((unsigned char)v[1])) hi = toupper(v[1]); hi = (hi >= 'A') ? hi - 'A' + 10 : (hi >= 0 ? hi - '0' : -1); if (v[1] && isxdigit((unsigned char)v[1]) && v[2] && isxdigit((unsigned char)v[2])) { int h = v[1], l = v[2]; h = (h >= 'A') ? (h | 0x20) - 'a' + 10 : h - '0'; l = (l >= 'A') ? (l | 0x20) - 'a' + 10 : l - '0'; buf[o++] = (char)((h << 4) | l); v += 3; (void)lo; continue; } buf[o++] = *v++; continue; } if (*v == '+') { buf[o++] = ' '; v++; continue; } buf[o++] = *v++; } buf[o] = '\0'; return 1; } if (!*amp) break; p = amp + 1; } return 0; } void sx_cgi_header(long status, const char *ctype) { if (status && status != 200) printf("Status: %ld %s\r\n", status, status == 401 ? "Unauthorized" : status == 400 ? "Bad Request" : status == 404 ? "Not Found" : status == 405 ? "Method Not Allowed" : "Error"); printf("Content-Type: %s\r\n\r\n", ctype ? ctype : "text/plain; charset=utf-8"); } void sx_print_json_doc(yyjson_mut_doc *doc) { char *s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL); fputs(s ? s : "{\"ok\":false,\"error\":\"serialize failed\"}", stdout); fputc('\n', stdout); free(s); fflush(stdout); } void sx_json_error(const char *msg, long status) { yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_false(doc, root, "ok"); yyjson_mut_obj_add_strcpy(doc, root, "error", msg ? msg : "error"); sx_cgi_header(status, "application/json; charset=utf-8"); sx_print_json_doc(doc); yyjson_mut_doc_free(doc); } char *sx_read_body(void) { const char *pf = getenv("POST_BODY_FILE"); if (pf && *pf) { char *buf = NULL; size_t len = 0; if (sx_read_file(pf, &buf, &len) == 1) return buf; return NULL; } { const char *cl = getenv("CONTENT_LENGTH"); long n = cl ? atol(cl) : 0; char *buf; size_t rd; if (n <= 0) return NULL; if (n > 8 * 1024 * 1024) n = 8 * 1024 * 1024; buf = (char *)malloc((size_t)n + 1); if (!buf) return NULL; rd = fread(buf, 1, (size_t)n, stdin); buf[rd] = '\0'; return buf; } } const char *sx_query_or(const char *query, const char *key, char *buf, size_t capsz, const char *fallback) { if (sx_query_get(query, key, buf, capsz) && buf[0]) return buf; sx_copy(buf, capsz, fallback); return buf; } void sx_require_node_auth(void) { const char *np = sx_node_password(); const char *xp, *auth; char qpwd[256]; if (!np) return; /* explicitly open node */ xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { const char *t = auth + 7; while (*t == ' ') t++; if (strcmp(t, np) == 0) return; } } if (sx_query_get(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\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); fflush(stdout); exit(0); } /* ===================================================================== * theme + embed * ===================================================================== */ const char *const SX_THEME_CSS = ":root{\n" " --bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;\n" " --surface:rgba(255,255,255,.03);--surface-2:rgba(255,255,255,.06);\n" " --line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);\n" " --text:#f5f5f7;--text-2:#86868b;\n" " --blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;\n" " --accent:var(--blue);--err:var(--red);\n" " --input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);\n" " --mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;\n" " --shadow:0 1px 2px rgba(0,0,0,.35);\n" "}\n" "@media (prefers-color-scheme:light){html:not([data-theme=dark]){\n" " --bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;\n" " --surface:rgba(0,0,0,.03);--surface-2:rgba(0,0,0,.06);\n" " --line:rgba(0,0,0,.10);--line-2:rgba(0,0,0,.18);\n" " --text:#1d1d1f;--text-2:#6e6e73;\n" " --blue:#0071e3;--green:#248a3d;--orange:#c93400;--red:#d70015;\n" " --input-bg:rgba(0,0,0,.04);--modal-bg:#ffffff;--code-bg:rgba(0,0,0,.05);\n" "}}\n" "html[data-theme=light]{\n" " --bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;\n" " --surface:rgba(0,0,0,.03);--surface-2:rgba(0,0,0,.06);\n" " --line:rgba(0,0,0,.10);--line-2:rgba(0,0,0,.18);\n" " --text:#1d1d1f;--text-2:#6e6e73;\n" " --blue:#0071e3;--green:#248a3d;--orange:#c93400;--red:#d70015;\n" " --input-bg:rgba(0,0,0,.04);--modal-bg:#ffffff;--code-bg:rgba(0,0,0,.05);\n" "}\n" "*{box-sizing:border-box}\n" "body{margin:0;background:var(--bg);color:var(--text);\n" " font:14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif}\n" "h1{font-size:20px;margin:16px 16px 4px}\n" ".sub{color:var(--text-2);margin:0 16px 12px;font-size:13px}\n" ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;\n" " margin:10px 16px;padding:12px 14px}\n" "input,select,textarea{background:var(--input-bg);color:var(--text);\n" " border:1px solid var(--line);border-radius:8px;padding:7px 9px;font:inherit}\n" "button{background:var(--blue);color:#fff;border:0;border-radius:8px;\n" " padding:7px 12px;font:inherit;cursor:pointer}\n" "button.ghost{background:transparent;color:var(--blue);border:1px solid var(--line-2)}\n" "code,pre{font-family:var(--mono);background:var(--code-bg);border-radius:6px}\n" "pre{padding:8px 10px;overflow:auto}\n" ".pill{display:inline-block;border:1px solid var(--line-2);border-radius:999px;\n" " padding:1px 9px;font-size:12px;color:var(--text-2)}\n" ".ok{color:var(--green)}.err{color:var(--red)}.warn{color:var(--orange)}\n" ".embed-hide,html.embedded .embed-hide{display:none!important}\n"; const char *const SX_THEME_PREPAINT_JS = "\n"; const char *const SX_THEME_HANDOFF_JS = "\n"; int sx_is_embedded(const char *query) { char v[16]; if (!query) return 0; if (sx_query_get(query, "embed", v, sizeof v)) return strcmp(v, "1") == 0 || sx_ieq(v, "true"); return 0; } const char *sx_theme_from_query(const char *query, const char *fallback) { char v[16]; if (sx_query_get(query, "theme", v, sizeof v)) { if (sx_ieq(v, "light")) return "light"; if (sx_ieq(v, "dark")) return "dark"; } return (fallback && (sx_ieq(fallback, "light"))) ? "light" : "dark"; } void sx_html_head(const char *title) { fputs("\n\n\n" "\n" "\n", stdout); printf("%s\n", title ? title : "connector"); fputs(SX_THEME_PREPAINT_JS, stdout); fputs("\n\n\n", stdout); } void sx_html_handoff_script(void) { fputs(SX_THEME_HANDOFF_JS, stdout); } /* ===================================================================== * --mcp : stdio JSON-RPC 2.0 * ===================================================================== */ #define MCP_PROTOCOL "2024-11-05" static void copy_id(yyjson_mut_doc *doc, yyjson_mut_val *root, yyjson_val *id) { if (!id) return; if (yyjson_is_int(id)) yyjson_mut_obj_add_int(doc, root, "id", (long long)yyjson_get_sint(id)); else if (yyjson_is_uint(id)) yyjson_mut_obj_add_uint(doc, root, "id", yyjson_get_uint(id)); else if (yyjson_is_str(id)) yyjson_mut_obj_add_strcpy(doc, root, "id", yyjson_get_str(id)); else if (yyjson_is_null(id)) yyjson_mut_obj_add_null(doc, root, "id"); } static yyjson_mut_val *tool_defs(yyjson_mut_doc *doc, const sx_mcp_tool *tools, size_t ntools) { yyjson_mut_val *arr = yyjson_mut_arr(doc); size_t i; for (i = 0; i < ntools; i++) { yyjson_mut_val *t = yyjson_mut_obj(doc); yyjson_mut_obj_add_strcpy(doc, t, "name", tools[i].name); yyjson_mut_obj_add_strcpy(doc, t, "description", tools[i].description ? tools[i].description : ""); if (tools[i].input_schema_json && *tools[i].input_schema_json) { yyjson_doc *sd = yyjson_read(tools[i].input_schema_json, strlen(tools[i].input_schema_json), 0); if (sd) { yyjson_mut_val *sc = yyjson_val_mut_copy(doc, yyjson_doc_get_root(sd)); yyjson_mut_obj_add_val(doc, t, "inputSchema", sc); yyjson_doc_free(sd); } } else { { yyjson_mut_val *sc = yyjson_mut_obj(doc); yyjson_mut_obj_add_strcpy(doc, sc, "type", "object"); yyjson_mut_obj_add_val(doc, t, "inputSchema", sc); } } yyjson_mut_arr_add_val(arr, t); } return arr; } int sx_mcp_handle_line(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools, const char *line, int *did_reply) { yyjson_doc *doc; yyjson_val *root, *method, *id, *params; yyjson_mut_doc *mo; yyjson_mut_val *mroot; const char *m; int reply = 0; if (did_reply) *did_reply = 0; if (!line || !*line) return -1; doc = yyjson_read(line, strlen(line), 0); if (!doc) return -1; root = yyjson_doc_get_root(doc); method = yyjson_obj_get(root, "method"); id = yyjson_obj_get(root, "id"); params = yyjson_obj_get(root, "params"); m = (method && yyjson_is_str(method)) ? yyjson_get_str(method) : ""; mo = yyjson_mut_doc_new(NULL); mroot = yyjson_mut_obj(mo); if (strcmp(m, "initialize") == 0) { sx_plugin_info in = *info; yyjson_mut_val *res, *caps, *si; sx_info_fill(&in); copy_id(mo, mroot, id); res = yyjson_mut_obj(mo); yyjson_mut_obj_add_strcpy(mo, res, "protocolVersion", MCP_PROTOCOL); caps = yyjson_mut_obj(mo); yyjson_mut_obj_add_val(mo, res, "capabilities", caps); si = yyjson_mut_obj(mo); yyjson_mut_obj_add_strcpy(mo, si, "name", in.id); yyjson_mut_obj_add_strcpy(mo, si, "version", in.version); yyjson_mut_obj_add_val(mo, res, "serverInfo", si); yyjson_mut_obj_add_val(mo, mroot, "result", res); reply = 1; } else if (strcmp(m, "ping") == 0) { copy_id(mo, mroot, id); yyjson_mut_obj_add_val(mo, mroot, "result", yyjson_mut_obj(mo)); reply = 1; } else if (strcmp(m, "tools/list") == 0) { yyjson_mut_val *res = yyjson_mut_obj(mo); copy_id(mo, mroot, id); yyjson_mut_obj_add_val(mo, res, "tools", tool_defs(mo, tools, ntools)); yyjson_mut_obj_add_val(mo, mroot, "result", res); reply = 1; } else if (strcmp(m, "tools/call") == 0) { const char *name = NULL, *args = "{}"; char *args_buf = NULL; char out[65536], errbuf[512]; int rc = -1, i; size_t no; yyjson_mut_val *res, *content, *block; yyjson_val *pn, *pa; if (params && yyjson_is_obj(params)) { pn = yyjson_obj_get(params, "name"); pa = yyjson_obj_get(params, "arguments"); name = (pn && yyjson_is_str(pn)) ? yyjson_get_str(pn) : NULL; if (pa) { args_buf = yyjson_val_write(pa, 0, NULL); if (args_buf) args = args_buf; } } out[0] = '\0'; errbuf[0] = '\0'; for (no = 0, i = 0; i < (int)ntools; i++) { if (name && strcmp(tools[i].name, name) == 0) { rc = tools[i].call(args, out, sizeof out, errbuf, sizeof errbuf); no = 1; break; } } copy_id(mo, mroot, id); res = yyjson_mut_obj(mo); content = yyjson_mut_arr(mo); block = yyjson_mut_obj(mo); yyjson_mut_obj_add_strcpy(mo, block, "type", "text"); yyjson_mut_obj_add_strcpy(mo, block, "text", rc == 0 ? out : (errbuf[0] ? errbuf : "tool failed")); yyjson_mut_arr_add_val(content, block); yyjson_mut_obj_add_val(mo, res, "content", content); yyjson_mut_obj_add_bool(mo, res, "isError", (rc != 0 || !no) ? 1 : 0); yyjson_mut_obj_add_val(mo, mroot, "result", res); free(args_buf); reply = 1; } else if (strncmp(m, "notifications/", 14) == 0) { reply = 0; /* never answer notifications */ } else if (id) { yyjson_mut_val *err; copy_id(mo, mroot, id); err = yyjson_mut_obj(mo); yyjson_mut_obj_add_int(mo, err, "code", -32601); yyjson_mut_obj_add_strcpy(mo, err, "message", "method not found"); yyjson_mut_obj_add_val(mo, mroot, "error", err); reply = 1; } if (reply) { yyjson_mut_doc_set_root(mo, mroot); yyjson_mut_obj_add_strcpy(mo, mroot, "jsonrpc", "2.0"); sx_print_json_doc(mo); } yyjson_mut_doc_free(mo); yyjson_doc_free(doc); if (did_reply) *did_reply = reply; return 0; } /* Read one line from stdin into a malloc'd buffer (caller frees *line_out). * * Shared by both platforms on purpose. The Windows branch used to be its own * hand-rolled getline() shim, which meant the MCP loop had two parsers and * only one of them was exercised by the suite on the machine that ships the * binaries. It also kept the carriage return: sx_stdio_binary() puts stdin in * _O_BINARY so that our own CGI headers are never rewritten, and that also * turns off the CRLF translation a text-mode stdin would have done, so a peer * that sends CRLF lines handed the JSON parser a trailing '\r' here. * * cap always starts at 0 because line always starts NULL: a caller that hands * back the previous line's capacity alongside a freed buffer would make the * grow check skip its realloc and write into address zero -- the second MCP * request of every session SEGVed on the zero page in the fgetc loop. * * Returns 1 when a line was read, 0 on clean EOF with nothing pending, * -1 on allocation failure. */ static int sx_read_line_stdin(char **line_out, size_t *cap_io) { char *line = NULL; size_t cap = 0, len = 0; int ch, saw_any = 0; for (;;) { ch = fgetc(stdin); if (ch == EOF) break; saw_any = 1; if (ch == '\n') break; if (len + 2 > cap) { char *nb; cap = cap ? cap * 2 : 256; nb = (char *)realloc(line, cap); if (!nb) { free(line); if (cap_io) *cap_io = 0; return -1; } line = nb; } line[len++] = (char)ch; } if (!saw_any) { free(line); if (cap_io) *cap_io = cap; return 0; } if (len && line[len - 1] == '\r') len--; /* tolerate CRLF peers */ if (len + 1 > cap) { /* the stripped-\r edge */ char *nb = (char *)realloc(line, len + 1); if (!nb) { free(line); if (cap_io) *cap_io = 0; return -1; } line = nb; cap = len + 1; } line[len] = '\0'; if (cap_io) *cap_io = cap; *line_out = line; return 1; } int sx_mcp_serve(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools) { char *line = NULL; size_t cap = 0; int r; setvbuf(stdout, NULL, _IONBF, 0); sx_ignore_sigpipe(); for (;;) { line = NULL; r = sx_read_line_stdin(&line, &cap); if (r < 0) return 1; if (r == 0) { free(line); return 0; } if (*line) sx_mcp_handle_line(info, tools, ntools, line, NULL); free(line); } } int sx_mcp_schema(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools) { yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); (void)info; yyjson_mut_obj_add_val(doc, root, "tools", tool_defs(doc, tools, ntools)); sx_print_json_doc(doc); yyjson_mut_doc_free(doc); return 0; } /* ===================================================================== * dispatch * ===================================================================== */ int sx_main(int argc, char **argv, const sx_plugin_info *info, sx_html_cb html_cb, sx_json_cb json_cb) { sx_plugin_info in = *info; const char *qs = getenv("QUERY_STRING"); const char *method = getenv("REQUEST_METHOD"); char action[64]; sx_info_fill(&in); sx_stdio_binary(); sx_ignore_sigpipe(); if (getenv("SX_PLUGIN_META") || sx_has_flag(argc, argv, "--meta")) { sx_meta_emit(&in); return 0; } if (sx_has_flag(argc, argv, "--schema")) return sx_mcp_schema(&in, NULL, 0); if (sx_has_flag(argc, argv, "--mcp")) return sx_mcp_serve(&in, NULL, 0); /* connector modes are dispatched by the plugin's own main() before it * reaches here (--daemon needs the plugin's tick function). */ action[0] = '\0'; sx_query_get(qs, "action", action, sizeof action); if (json_cb && (action[0] || (qs && strstr(qs, "format=json")) || (method && sx_ieq(method, "POST")))) { char *body = sx_read_body(); int rc; sx_require_node_auth(); rc = json_cb(&in, qs ? qs : "", action, body); free(body); return rc; } if (html_cb) return html_cb(&in, qs ? qs : "", sx_is_embedded(qs), sx_theme_from_query(qs, "dark")); return 0; } /* ===================================================================== * connector dir + files * ===================================================================== */ int sx_mkdir_p(const char *path) { char tmp[1024]; char *p; size_t len; sx_copy(tmp, sizeof tmp, path); len = strlen(tmp); if (len == 0) return -1; if (tmp[len - 1] == '/' || tmp[len - 1] == '\\') tmp[len - 1] = '\0'; for (p = tmp + 1; *p; p++) { if (*p == '/' || *p == '\\') { char save = *p; *p = '\0'; SX_MKDIR(tmp); *p = save; } } SX_MKDIR(tmp); { struct stat st; return stat(tmp, &st) == 0 && S_ISDIR(st.st_mode) ? 0 : -1; } } int sx_read_file(const char *path, char **buf, size_t *len) { FILE *f = fopen(path, "rb"); struct stat st; char *b; size_t rd; if (!f) return 0; if (fstat(fileno(f), &st) == 0 && st.st_size > 16 * 1024 * 1024) { fclose(f); return -1; } if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return -1; } { long sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz < 0) { fclose(f); return -1; } b = (char *)malloc((size_t)sz + 1); if (!b) { fclose(f); return -1; } rd = fread(b, 1, (size_t)sz, f); b[rd] = '\0'; } fclose(f); *buf = b; if (len) *len = strlen(b); return 1; } int sx_write_file(const char *path, const void *buf, size_t len) { char tmp[1088]; FILE *f; size_t wr; const char *slash; /* create the parent directory */ sx_copy(tmp, sizeof tmp, path); slash = strrchr(tmp, '/'); #if defined(_WIN32) { const char *bs = strrchr(tmp, '\\'); if (!slash || (bs && bs > slash)) slash = bs; } #endif if (slash) { char dir[1088]; size_t dl = (size_t)(slash - tmp); if (dl >= sizeof dir) dl = sizeof dir - 1; memcpy(dir, tmp, dl); dir[dl] = '\0'; sx_mkdir_p(dir); } snprintf(tmp, sizeof tmp, "%s.tmp.%lu", path, (unsigned long) #if defined(_WIN32) GetCurrentProcessId() #else (unsigned long)getpid() #endif ); f = fopen(tmp, "wb"); if (!f) return -1; wr = fwrite(buf, 1, len, f); fclose(f); if (wr != len) { remove(tmp); return -1; } remove(path); /* windows rename needs the target gone */ if (rename(tmp, path) != 0) { remove(tmp); return -1; } return 0; } static const char *sx_home(void) { const char *h = getenv("HOME"); if (h && *h) return h; h = getenv("USERPROFILE"); if (h && *h) return h; return "."; } int sx_connector_dir(const char *id, char *out, size_t capsz) { const char *env = getenv("SX_CONNECTOR_DIR"); struct stat st; int ok; if (!id || !*id) id = "connector"; if (env && *env) { snprintf(out, capsz, "%s", env); } else if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) { snprintf(out, capsz, "/workspace/.scorpiox/connectors/%s", id); } else { const char *la = getenv("LOCALAPPDATA"); if (la && *la) snprintf(out, capsz, "%s\\scorpiox\\connectors\\%s", la, id); else snprintf(out, capsz, "%s/.scorpiox/connectors/%s", sx_home(), id); } ok = (stat(out, &st) == 0 && S_ISDIR(st.st_mode)); if (!ok) ok = (sx_mkdir_p(out) == 0); return ok ? 0 : -1; } int sx_connector_path(const char *id, const char *name, char *out, size_t capsz) { char dir[896]; if (sx_connector_dir(id, dir, sizeof dir) != 0) return -1; #if defined(_WIN32) snprintf(out, capsz, "%s\\%s", dir, name); #else snprintf(out, capsz, "%s/%s", dir, name); #endif return 0; } int sx_json_file_load(const char *id, const char *name, yyjson_doc **doc) { char path[1024], *buf = NULL; size_t len = 0; if (sx_connector_path(id, name, path, sizeof path) != 0) return -1; if (sx_read_file(path, &buf, &len) != 1) return -1; *doc = yyjson_read(buf, len, 0); free(buf); return *doc ? 0 : -1; } int sx_json_file_save(const char *id, const char *name, yyjson_mut_doc *doc) { char path[1024]; char *s; int rc; if (sx_connector_path(id, name, path, sizeof path) != 0) return -1; s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), YYJSON_WRITE_PRETTY, NULL); if (!s) return -1; rc = sx_write_file(path, s, strlen(s)); free(s); return rc; } void sx_make_id(char *out, size_t capsz) { static unsigned counter = 0; counter++; snprintf(out, capsz, "%llx-%04x", (unsigned long long)sx_now_ms(), (unsigned)(counter ^ (unsigned)(size_t)out)); } void sx_make_code(char *out, size_t capsz) { static const char alpha[] = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; /* no I/O/0/1 */ size_t n = SX_CODE_LEN, i; if (capsz < n + 1) { if (capsz) out[0] = '\0'; return; } for (i = 0; i < n; i++) out[i] = alpha[(unsigned)(rand() + (int)sx_now_ms() + (int)i * 773) % (sizeof alpha - 1)]; out[n] = '\0'; } void sx_log(const char *id, const char *fmt, ...) { va_list ap; fprintf(stderr, "[%s] ", id ? id : "connector"); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); fflush(stderr); } /* ===================================================================== * senders + pairing (default-deny) * ===================================================================== */ #define SENDERS_FILE "senders.json" void sx_senders_free(sx_sender *items) { free(items); } int sx_senders_load(const char *id, sx_sender **out, size_t *n_out) { yyjson_doc *doc = NULL; yyjson_val *arr, *it; sx_sender *items = NULL; size_t n = 0, cap = 0, i, max; *out = NULL; *n_out = 0; if (sx_json_file_load(id, SENDERS_FILE, &doc) != 0) return 0; /* none yet */ arr = yyjson_doc_get_root(doc); if (!arr || !yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; } max = yyjson_arr_size(arr); items = (sx_sender *)calloc(max ? max : 1, sizeof *items); if (!items) { yyjson_doc_free(doc); return -1; } yyjson_arr_foreach(arr, i, max, it) { yyjson_val *v; if (n + 1 > cap) { sx_sender *nb; cap = cap ? cap * 2 : 16; nb = (sx_sender *)realloc(items, cap * sizeof *items); if (!nb) break; items = nb; } memset(&items[n], 0, sizeof items[n]); v = yyjson_obj_get(it, "key"); if (v) sx_copy(items[n].key, sizeof items[n].key, yyjson_get_str(v)); v = yyjson_obj_get(it, "label"); if (v) sx_copy(items[n].label, sizeof items[n].label, yyjson_get_str(v)); v = yyjson_obj_get(it, "code"); if (v) sx_copy(items[n].code, sizeof items[n].code, yyjson_get_str(v)); v = yyjson_obj_get(it, "created"); if (v && yyjson_is_int(v)) items[n].created = (long long)yyjson_get_sint(v); v = yyjson_obj_get(it, "approved"); items[n].approved = (v && yyjson_is_true(v)) ? 1 : 0; if (items[n].key[0]) n++; } yyjson_doc_free(doc); *out = items; *n_out = n; return 0; } int sx_senders_save(const char *id, const sx_sender *items, size_t n) { yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *arr = yyjson_mut_arr(doc); size_t i; int rc; yyjson_mut_doc_set_root(doc, arr); for (i = 0; i < n; i++) { yyjson_mut_val *o = yyjson_mut_obj(doc); yyjson_mut_obj_add_strcpy(doc, o, "key", items[i].key); yyjson_mut_obj_add_strcpy(doc, o, "label", items[i].label); yyjson_mut_obj_add_strcpy(doc, o, "code", items[i].code); yyjson_mut_obj_add_int(doc, o, "created", (long long)items[i].created); yyjson_mut_obj_add_bool(doc, o, "approved", items[i].approved); yyjson_mut_arr_add_val(arr, o); } rc = sx_json_file_save(id, SENDERS_FILE, doc); yyjson_mut_doc_free(doc); return rc; } int sx_sender_allowed(const char *id, const char *key, const char *label, int pairing_enabled, char *code_out, size_t codesz) { sx_sender *items = NULL; size_t n = 0, i; int allowed = 0; if (code_out && codesz) code_out[0] = '\0'; if (!key || !*key) return 0; /* default-deny */ if (sx_senders_load(id, &items, &n) != 0) return 0; for (i = 0; i < n; i++) { if (strcmp(items[i].key, key) == 0) { if (items[i].approved) allowed = 1; else if (pairing_enabled && code_out && codesz) sx_copy(code_out, codesz, items[i].code); sx_senders_free(items); return allowed; } } /* unknown sender: queue as pending with a fresh code (default-deny) */ if (pairing_enabled) { sx_sender *nb = (sx_sender *)realloc(items, (n + 1) * sizeof *items); if (nb) { items = nb; memset(&items[n], 0, sizeof items[n]); sx_copy(items[n].key, sizeof items[n].key, key); sx_copy(items[n].label, sizeof items[n].label, label ? label : ""); items[n].created = (long long)time(NULL); items[n].approved = 0; sx_make_code(items[n].code, sizeof items[n].code); sx_copy(code_out, codesz, items[n].code); sx_senders_save(id, items, n + 1); } } sx_senders_free(items); return 0; } static int sx_sender_set_field(const char *id, const char *key, int approved, int remove_entry) { sx_sender *items = NULL; size_t n = 0, i, o = 0; int found = 0; if (sx_senders_load(id, &items, &n) != 0) return -1; for (i = 0; i < n; i++) { if (strcmp(items[i].key, key) != 0) { if (o != i) items[o] = items[i]; o++; continue; } found = 1; if (remove_entry) continue; items[o++] = items[i]; items[o - 1].approved = approved; } sx_senders_save(id, items, o); sx_senders_free(items); return found ? 0 : -1; } int sx_sender_approve(const char *id, const char *key) { return sx_sender_set_field(id, key, 1, 0); } int sx_sender_remove(const char *id, const char *key) { return sx_sender_set_field(id, key, 0, 1); } int sx_pairing_lookup(const char *id, const char *code, char *key_out, size_t capsz) { sx_sender *items = NULL; size_t n = 0, i; int found = 0; if (key_out && capsz) key_out[0] = '\0'; if (!code || !*code) return 0; if (sx_senders_load(id, &items, &n) != 0) return 0; for (i = 0; i < n; i++) { if (items[i].code[0] && sx_ieq(items[i].code, code)) { items[i].approved = 1; sx_copy(key_out, capsz, items[i].key); sx_senders_save(id, items, n); found = 1; break; } } sx_senders_free(items); return found; } /* ===================================================================== * node loopback client * ===================================================================== */ const char *sx_node_api_base(void) { const char *b = getenv("SX_NODE_API"); if (b && *b) return b; return "http://127.0.0.1:8150"; } static void sx_hdr_pwd(char *hdrs, size_t capsz) { const char *pwd = sx_node_password(); char safe[256]; size_t i, o = 0; if (!pwd) { hdrs[0] = '\0'; return; } /* header-injection guard: strip CR/LF from the password */ for (i = 0; pwd[i] && o + 1 < sizeof safe; i++) if (pwd[i] != '\r' && pwd[i] != '\n') safe[o++] = pwd[i]; safe[o] = '\0'; snprintf(hdrs, capsz, "X-Bot-Password: %s\r\n", safe); } int sx_node_post_inbox(const char *session, const char *text, const char *mode, char *err, size_t errsz) { sx_conn c; sx_url u; char path[512], hdrs[300], body[70000]; yyjson_mut_doc *doc; char *bodystr; int rc = -1; snprintf(path, sizeof path, "/inbox?id=%s%s%s", session ? session : "", mode ? "&mode=" : "", mode ? mode : ""); doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_strcpy(doc, root, "text", text ? text : ""); bodystr = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL); yyjson_mut_doc_free(doc); if (!bodystr) { sx_copy(err, errsz, "encode failed"); return -1; } sx_copy(body, sizeof body, bodystr); free(bodystr); sx_hdr_pwd(hdrs, sizeof hdrs); { char url[1536]; snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path); if (sx_url_parse(url, &u, err, errsz) != 0) return -1; if (sx_conn_open(&c, &u, 10000, err, errsz) != 0) return -1; } { char full[1536]; snprintf(full, sizeof full, "Content-Type: application/json\r\n%s", hdrs); if (sx_http_request(&c, "POST", path, full, NULL, body, strlen(body), 10000, err, errsz) == 0 && c.status >= 200 && c.status < 300) rc = 0; else if (err && errsz) snprintf(err, errsz, "node inbox status %ld", c.status); } sx_conn_close(&c); return rc; } int sx_node_conversation(const char *session, long after, long limit, char **body_out, char *err, size_t errsz) { sx_conn c; sx_url u; char path[512], hdrs[300], url[1536]; char *body = NULL; int rc = -1; snprintf(path, sizeof path, "/conversation?id=%s&after=%ld&limit=%ld", session ? session : "", after, limit); snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path); sx_hdr_pwd(hdrs, sizeof hdrs); if (sx_url_parse(url, &u, err, errsz) != 0) return -1; if (sx_conn_open(&c, &u, 10000, err, errsz) != 0) return -1; if (sx_http_request(&c, "GET", path, hdrs, NULL, NULL, 0, 15000, err, errsz) == 0 && c.status == 200) { if (sx_read_all(&c, &body, NULL, 15000) == 1) { *body_out = body; rc = 0; } } else { snprintf(err, errsz, "node conversation status %ld", c.status); } sx_conn_close(&c); return rc; } /* ------------------------------------------------------------------ SSE */ int sx_sse_open(sx_sse *s, const char *session, long after, char *err, size_t errsz) { sx_conn *c = &s->c; sx_url u; char path[512], url[1536], sse_hdrs[300]; const char *pwd; memset(s, 0, sizeof *s); if (after > 0) snprintf(path, sizeof path, "/hashes_sse?id=%s&after=%ld", session, after); else snprintf(path, sizeof path, "/hashes_sse?id=%s", session); snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path); if (sx_url_parse(url, &u, err, errsz) != 0) return -1; if (sx_conn_open(c, &u, 10000, err, errsz) != 0) return -1; pwd = sx_node_password(); (void)pwd; sx_hdr_pwd(sse_hdrs, sizeof sse_hdrs); if (sx_http_request(c, "GET", path, sse_hdrs, NULL, NULL, 0, 15000, err, errsz) != 0) { sx_conn_close(c); return -1; } if (c->status != 200) { snprintf(err, errsz, "hashes_sse status %ld", c->status); sx_conn_close(c); return -1; } (void)pwd; s->open = 1; return 0; } int sx_sse_next(sx_sse *s, sx_sse_event *ev, long timeout_ms) { char line[8192]; int have_data = 0, have_event = 0; long long stop = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 30000); if (!s->open) return -1; memset(ev, 0, sizeof *ev); while (sx_now_ms() < stop) { int r = sx_read_line(&s->c, line, sizeof line, (long)(stop - sx_now_ms())); if (r < 0) { s->open = 0; return -1; } if (r == 0) { s->open = 0; return 0; } if (line[0] == '\0') { /* blank line: end of event */ if (have_data) { /* parse the json payload for the convenience fields */ yyjson_doc *d = yyjson_read(ev->json, strlen(ev->json), 0); if (d) { yyjson_val *root = yyjson_doc_get_root(d), *v; v = yyjson_obj_get(root, "id"); if (v && yyjson_is_str(v)) sx_copy(ev->id, sizeof ev->id, yyjson_get_str(v)); v = yyjson_obj_get(root, "session_id"); if (v && yyjson_is_str(v)) sx_copy(ev->session_id, sizeof ev->session_id, yyjson_get_str(v)); v = yyjson_obj_get(root, "total"); if (v && yyjson_is_int(v)) ev->total = (long)yyjson_get_sint(v); v = yyjson_obj_get(root, "after"); if (v && yyjson_is_int(v)) ev->after = (long)yyjson_get_sint(v); yyjson_doc_free(d); } return 1; } continue; } if (strncmp(line, "event:", 6) == 0) { const char *p = line + 6; while (*p == ' ') p++; sx_copy(ev->event, sizeof ev->event, p); have_event = 1; (void)have_event; } else if (strncmp(line, "data:", 5) == 0) { const char *p = line + 5; while (*p == ' ') p++; sx_copy(ev->json, sizeof ev->json, p); have_data = 1; } } return -1; /* timeout */ } void sx_sse_close(sx_sse *s) { s->open = 0; sx_conn_close(&s->c); } /* ===================================================================== * daemon lifecycle * ===================================================================== */ #if !defined(_WIN32) static volatile sig_atomic_t g_got_signal = 0; static void sx_on_sig(int sig) { (void)sig; g_got_signal = 1; } #endif int sx_daemon_request_stop(const char *id) { char path[1024]; if (sx_connector_path(id, "stop", path, sizeof path) != 0) return -1; return sx_write_file(path, "stop\n", 5); } int sx_daemon_stop_requested(const char *id) { char path[1024]; struct stat st; if (sx_connector_path(id, "stop", path, sizeof path) != 0) return 0; return stat(path, &st) == 0; } static void sx_clear_stop(const char *id) { char path[1024]; if (sx_connector_path(id, "stop", path, sizeof path) == 0) remove(path); } static void sx_sleep_ms(unsigned ms) { #if defined(_WIN32) Sleep(ms); #else struct timespec ts; ts.tv_sec = (time_t)(ms / 1000); ts.tv_nsec = (long)((ms % 1000) * 1000000L); nanosleep(&ts, NULL); #endif } int sx_daemon_run(const sx_daemon_cfg *cfg, sx_daemon_tick tick) { char dir[896], pidpath[1024]; unsigned interval = cfg->interval_ms ? cfg->interval_ms : 1000; char pid[32]; int rc = 0; if (sx_connector_dir(cfg->id, dir, sizeof dir) != 0) { sx_log(cfg->id, "cannot create connector dir"); return 1; } sx_clear_stop(cfg->id); snprintf(pid, sizeof pid, "%lu\n", (unsigned long) #if defined(_WIN32) GetCurrentProcessId() #else (unsigned long)getpid() #endif ); if (sx_connector_path(cfg->id, "daemon.pid", pidpath, sizeof pidpath) == 0) sx_write_file(pidpath, pid, strlen(pid)); #if !defined(_WIN32) signal(SIGTERM, sx_on_sig); signal(SIGINT, sx_on_sig); signal(SIGHUP, sx_on_sig); signal(SIGPIPE, SIG_IGN); #endif sx_log(cfg->id, "daemon up (session=%s interval=%ums dir=%s)", cfg->session ? cfg->session : "-", interval, dir); for (;;) { #if !defined(_WIN32) if (g_got_signal) break; #endif if (sx_daemon_stop_requested(cfg->id)) break; if (tick && tick(cfg, cfg->user)) break; sx_sleep_ms(interval); } sx_log(cfg->id, "daemon stopping"); sx_clear_stop(cfg->id); if (pidpath[0]) remove(pidpath); (void)rc; return 0; }