scorpiox-bot-plugin-github
←sx_connector.cc
1305 lines · 43 KBHEADBlameDownload
1/*
2 * sx_connector.c -- SCORPIOX BOT Connector SDK core. See sx_connector.h.
3 *
4 * MIT License. Copyright (c) 2026 SCORPIOX INC.
5 */
6#define _DEFAULT_SOURCE
7#define _POSIX_C_SOURCE 200809L
8#define _GNU_SOURCE
9
10#include "sx_connector.h"
11
12#include <ctype.h>
13#include <errno.h>
14#include <stdarg.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <time.h>
19
20#if defined(_WIN32)
21# include <io.h>
22# include <direct.h>
23# include <fcntl.h> /* _O_BINARY (MinGW's <io.h> alone does not define it) */
24# include <sys/stat.h>
25# include <process.h>
26# define SX_MKDIR(p) _mkdir(p)
27#else
28# include <unistd.h>
29# include <signal.h>
30# include <sys/stat.h>
31# include <sys/types.h>
32# define SX_MKDIR(p) mkdir((p), 0755)
33#endif
34
35/* =====================================================================
36 * identity + dispatch
37 * ===================================================================== */
38
39void sx_copy(char *dst, size_t capsz, const char *src)
40{
41 if (!capsz) return;
42 if (!src) { dst[0] = '\0'; return; }
43 snprintf(dst, capsz, "%s", src);
44}
45
46int sx_ieq(const char *a, const char *b)
47{
48 if (!a || !b) return 0;
49 while (*a && *b) {
50 if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
51 a++; b++;
52 }
53 return *a == 0 && *b == 0;
54}
55
56void sx_info_fill(sx_plugin_info *info)
57{
58 if (!info->id) info->id = "connector";
59 if (!info->name || !*info->name) info->name = info->id;
60 if (!info->desc) info->desc = "";
61 if (!info->kind || !*info->kind) info->kind = SX_KIND_UI;
62 if (!info->verified || !*info->verified) info->verified = "mock";
63 if (!info->version) info->version = "1.0.0";
64 if (info->menus < 0)
65 info->menus = (strcmp(info->kind, SX_KIND_UI) == 0 ||
66 strcmp(info->kind, SX_KIND_HYBRID) == 0) ? 1 : 0;
67}
68
69void sx_meta_emit(const sx_plugin_info *info)
70{
71 sx_plugin_info in = *info;
72 yyjson_mut_doc *doc;
73 char *s;
74
75 sx_info_fill(&in);
76 doc = yyjson_mut_doc_new(NULL);
77 yyjson_mut_val *root = yyjson_mut_obj(doc);
78 yyjson_mut_doc_set_root(doc, root);
79 yyjson_mut_obj_add_strcpy(doc, root, "name", in.name);
80 yyjson_mut_obj_add_strcpy(doc, root, "desc", in.desc);
81 yyjson_mut_obj_add_strcpy(doc, root, "kind", in.kind);
82 yyjson_mut_obj_add_bool(doc, root, "mcp", in.mcp ? 1 : 0);
83 yyjson_mut_obj_add_bool(doc, root, "daemon", in.daemon ? 1 : 0);
84 yyjson_mut_obj_add_bool(doc, root, "menus", in.menus ? 1 : 0);
85 yyjson_mut_obj_add_strcpy(doc, root, "verified", in.verified);
86 yyjson_mut_obj_add_strcpy(doc, root, "version", in.version);
87 s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL);
88 if (s) { puts(s); free(s); }
89 yyjson_mut_doc_free(doc);
90 fflush(stdout);
91}
92
93void sx_stdio_binary(void)
94{
95#if defined(_WIN32)
96 _setmode(_fileno(stdin), _O_BINARY);
97 _setmode(_fileno(stdout), _O_BINARY);
98 _setmode(_fileno(stderr), _O_BINARY);
99#endif
100}
101
102/* Ignore SIGPIPE for the whole process.
103 *
104 * A connector writes to sockets whose peer can vanish at any moment: the
105 * node API closes after every `Connection: close` answer, a WebSocket relay
106 * drops between frames. The default SIGPIPE disposition kills the process
107 * (or, worse, returns into whatever frame the signal landed in and leaves a
108 * garbage errno behind on the socket call), which turns a recoverable
109 * "connection gone" into a crashed daemon or a nonsense HTTP status.
110 *
111 * With SIGPIPE ignored every lost write is an ordinary send() == -1 with
112 * EPIPE, which the SDK already reports as a clean error string.
113 *
114 * This is deliberately process-wide and safe to call more than once. A
115 * connector that genuinely wants SIGPIPE can reinstate it after calling
116 * sx_main()/sx_mcp_serve()/sx_daemon_run() setup. */
117void sx_ignore_sigpipe(void)
118{
119#if !defined(_WIN32)
120 signal(SIGPIPE, SIG_IGN);
121#endif
122}
123
124int sx_has_flag(int argc, char **argv, const char *flag)
125{
126 int i;
127 for (i = 1; i < argc; i++)
128 if (strcmp(argv[i], flag) == 0) return 1;
129 return 0;
130}
131
132/* =====================================================================
133 * CGI helpers
134 * ===================================================================== */
135
136const char *sx_node_password(void)
137{
138 const char *p = getenv("BOT_PASSWORD");
139 if (p && !*p) return NULL;
140 return p;
141}
142
143int sx_query_get(const char *query, const char *key, char *buf, size_t capsz)
144{
145 size_t klen;
146 const char *p = query;
147
148 if (buf && capsz) buf[0] = '\0';
149 if (!query || !*query || !key || !buf || !capsz) return 0;
150 klen = strlen(key);
151
152 while (*p) {
153 const char *eq = strchr(p, '=');
154 const char *amp = strchr(p, '&');
155 if (!amp) amp = p + strlen(p);
156 if (eq && eq < amp && (size_t)(eq - p) == klen &&
157 strncmp(p, key, klen) == 0) {
158 size_t o = 0;
159 const char *v = eq + 1;
160 while (v < amp && *v && o + 1 < capsz) {
161 if (*v == '%') {
162 int hi = -1, lo = -1;
163 if (isxdigit((unsigned char)v[1])) hi = toupper(v[1]);
164 hi = (hi >= 'A') ? hi - 'A' + 10 : (hi >= 0 ? hi - '0' : -1);
165 if (v[1] && isxdigit((unsigned char)v[1]) &&
166 v[2] && isxdigit((unsigned char)v[2])) {
167 int h = v[1], l = v[2];
168 h = (h >= 'A') ? (h | 0x20) - 'a' + 10 : h - '0';
169 l = (l >= 'A') ? (l | 0x20) - 'a' + 10 : l - '0';
170 buf[o++] = (char)((h << 4) | l);
171 v += 3;
172 (void)lo;
173 continue;
174 }
175 buf[o++] = *v++;
176 continue;
177 }
178 if (*v == '+') { buf[o++] = ' '; v++; continue; }
179 buf[o++] = *v++;
180 }
181 buf[o] = '\0';
182 return 1;
183 }
184 if (!*amp) break;
185 p = amp + 1;
186 }
187 return 0;
188}
189
190void sx_cgi_header(long status, const char *ctype)
191{
192 if (status && status != 200)
193 printf("Status: %ld %s\r\n", status,
194 status == 401 ? "Unauthorized" :
195 status == 400 ? "Bad Request" :
196 status == 404 ? "Not Found" :
197 status == 405 ? "Method Not Allowed" : "Error");
198 printf("Content-Type: %s\r\n\r\n", ctype ? ctype : "text/plain; charset=utf-8");
199}
200
201void sx_print_json_doc(yyjson_mut_doc *doc)
202{
203 char *s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL);
204 fputs(s ? s : "{\"ok\":false,\"error\":\"serialize failed\"}", stdout);
205 fputc('\n', stdout);
206 free(s);
207 fflush(stdout);
208}
209
210void sx_json_error(const char *msg, long status)
211{
212 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
213 yyjson_mut_val *root = yyjson_mut_obj(doc);
214 yyjson_mut_doc_set_root(doc, root);
215 yyjson_mut_obj_add_false(doc, root, "ok");
216 yyjson_mut_obj_add_strcpy(doc, root, "error", msg ? msg : "error");
217 sx_cgi_header(status, "application/json; charset=utf-8");
218 sx_print_json_doc(doc);
219 yyjson_mut_doc_free(doc);
220}
221
222char *sx_read_body(void)
223{
224 const char *pf = getenv("POST_BODY_FILE");
225 if (pf && *pf) {
226 char *buf = NULL; size_t len = 0;
227 if (sx_read_file(pf, &buf, &len) == 1) return buf;
228 return NULL;
229 }
230 {
231 const char *cl = getenv("CONTENT_LENGTH");
232 long n = cl ? atol(cl) : 0;
233 char *buf;
234 size_t rd;
235 if (n <= 0) return NULL;
236 if (n > 8 * 1024 * 1024) n = 8 * 1024 * 1024;
237 buf = (char *)malloc((size_t)n + 1);
238 if (!buf) return NULL;
239 rd = fread(buf, 1, (size_t)n, stdin);
240 buf[rd] = '\0';
241 return buf;
242 }
243}
244
245const char *sx_query_or(const char *query, const char *key, char *buf, size_t capsz,
246 const char *fallback)
247{
248 if (sx_query_get(query, key, buf, capsz) && buf[0]) return buf;
249 sx_copy(buf, capsz, fallback);
250 return buf;
251}
252
253void sx_require_node_auth(void)
254{
255 const char *np = sx_node_password();
256 const char *xp, *auth;
257 char qpwd[256];
258
259 if (!np) return; /* explicitly open node */
260
261 xp = getenv("HTTP_X_BOT_PASSWORD");
262 if (xp && strcmp(xp, np) == 0) return;
263
264 auth = getenv("HTTP_AUTHORIZATION");
265 if (auth) {
266 while (*auth == ' ') auth++;
267 if (strncmp(auth, "Bearer ", 7) == 0) {
268 const char *t = auth + 7;
269 while (*t == ' ') t++;
270 if (strcmp(t, np) == 0) return;
271 }
272 }
273
274 if (sx_query_get(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd) &&
275 strcmp(qpwd, np) == 0) return;
276
277 fputs("Status: 401 Unauthorized\r\n"
278 "Content-Type: application/json; charset=utf-8\r\n\r\n"
279 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
280 fflush(stdout);
281 exit(0);
282}
283
284/* =====================================================================
285 * theme + embed
286 * ===================================================================== */
287
288const char *const SX_THEME_CSS =
289":root{\n"
290" --bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;\n"
291" --surface:rgba(255,255,255,.03);--surface-2:rgba(255,255,255,.06);\n"
292" --line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);\n"
293" --text:#f5f5f7;--text-2:#86868b;\n"
294" --blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;\n"
295" --accent:var(--blue);--err:var(--red);\n"
296" --input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);\n"
297" --mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;\n"
298" --shadow:0 1px 2px rgba(0,0,0,.35);\n"
299"}\n"
300"@media (prefers-color-scheme:light){html:not([data-theme=dark]){\n"
301" --bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;\n"
302" --surface:rgba(0,0,0,.03);--surface-2:rgba(0,0,0,.06);\n"
303" --line:rgba(0,0,0,.10);--line-2:rgba(0,0,0,.18);\n"
304" --text:#1d1d1f;--text-2:#6e6e73;\n"
305" --blue:#0071e3;--green:#248a3d;--orange:#c93400;--red:#d70015;\n"
306" --input-bg:rgba(0,0,0,.04);--modal-bg:#ffffff;--code-bg:rgba(0,0,0,.05);\n"
307"}}\n"
308"html[data-theme=light]{\n"
309" --bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;\n"
310" --surface:rgba(0,0,0,.03);--surface-2:rgba(0,0,0,.06);\n"
311" --line:rgba(0,0,0,.10);--line-2:rgba(0,0,0,.18);\n"
312" --text:#1d1d1f;--text-2:#6e6e73;\n"
313" --blue:#0071e3;--green:#248a3d;--orange:#c93400;--red:#d70015;\n"
314" --input-bg:rgba(0,0,0,.04);--modal-bg:#ffffff;--code-bg:rgba(0,0,0,.05);\n"
315"}\n"
316"*{box-sizing:border-box}\n"
317"body{margin:0;background:var(--bg);color:var(--text);\n"
318" font:14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif}\n"
319"h1{font-size:20px;margin:16px 16px 4px}\n"
320".sub{color:var(--text-2);margin:0 16px 12px;font-size:13px}\n"
321".card{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;\n"
322" margin:10px 16px;padding:12px 14px}\n"
323"input,select,textarea{background:var(--input-bg);color:var(--text);\n"
324" border:1px solid var(--line);border-radius:8px;padding:7px 9px;font:inherit}\n"
325"button{background:var(--blue);color:#fff;border:0;border-radius:8px;\n"
326" padding:7px 12px;font:inherit;cursor:pointer}\n"
327"button.ghost{background:transparent;color:var(--blue);border:1px solid var(--line-2)}\n"
328"code,pre{font-family:var(--mono);background:var(--code-bg);border-radius:6px}\n"
329"pre{padding:8px 10px;overflow:auto}\n"
330".pill{display:inline-block;border:1px solid var(--line-2);border-radius:999px;\n"
331" padding:1px 9px;font-size:12px;color:var(--text-2)}\n"
332".ok{color:var(--green)}.err{color:var(--red)}.warn{color:var(--orange)}\n"
333".embed-hide,html.embedded .embed-hide{display:none!important}\n";
334
335const char *const SX_THEME_PREPAINT_JS =
336"<script>(function(){try{var p=new URLSearchParams(location.search);"
337"var t=p.get('theme');if(t!=='light'&&t!=='dark'){t=localStorage.getItem('bot_theme');}"
338"if(t==='light'||t==='dark')document.documentElement.setAttribute('data-theme',t);}catch(e){}"
339"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))"
340"document.documentElement.classList.add('embedded');}catch(e){}})();</script>\n";
341
342const char *const SX_THEME_HANDOFF_JS =
343"<script>(function(){function now(){try{var m=document.documentElement.getAttribute('data-theme');"
344"if(m==='light'||m==='dark')return m;}catch(e){}"
345"try{var l=localStorage.getItem('bot_theme');if(l==='light'||l==='dark')return l;}catch(e){}"
346"try{return matchMedia('(prefers-color-scheme: light)').matches?'light':'dark';}catch(e){return 'dark';}}"
347"function set(t){if(t==='light'||t==='dark')document.documentElement.setAttribute('data-theme',t);}"
348"window.sxThemeNow=now;"
349"window.addEventListener('message',function(e){var d=e.data;"
350"if(d&&d.type==='sx-theme')set(d.theme);});"
351"try{parent.postMessage({type:'sx-theme-request',plugin:location.pathname},'*');}catch(e){}})();</script>\n";
352
353int sx_is_embedded(const char *query)
354{
355 char v[16];
356 if (!query) return 0;
357 if (sx_query_get(query, "embed", v, sizeof v))
358 return strcmp(v, "1") == 0 || sx_ieq(v, "true");
359 return 0;
360}
361
362const char *sx_theme_from_query(const char *query, const char *fallback)
363{
364 char v[16];
365 if (sx_query_get(query, "theme", v, sizeof v)) {
366 if (sx_ieq(v, "light")) return "light";
367 if (sx_ieq(v, "dark")) return "dark";
368 }
369 return (fallback && (sx_ieq(fallback, "light"))) ? "light" : "dark";
370}
371
372void sx_html_head(const char *title)
373{
374 fputs("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n"
375 "<meta charset=\"utf-8\">\n"
376 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n",
377 stdout);
378 printf("<title>%s</title>\n", title ? title : "connector");
379 fputs(SX_THEME_PREPAINT_JS, stdout);
380 fputs("<style>", stdout);
381 fputs(SX_THEME_CSS, stdout);
382 fputs("</style>\n</head>\n<body>\n", stdout);
383}
384
385void sx_html_handoff_script(void)
386{
387 fputs(SX_THEME_HANDOFF_JS, stdout);
388}
389
390/* =====================================================================
391 * --mcp : stdio JSON-RPC 2.0
392 * ===================================================================== */
393
394#define MCP_PROTOCOL "2024-11-05"
395
396static void copy_id(yyjson_mut_doc *doc, yyjson_mut_val *root, yyjson_val *id)
397{
398 if (!id) return;
399 if (yyjson_is_int(id))
400 yyjson_mut_obj_add_int(doc, root, "id", (long long)yyjson_get_sint(id));
401 else if (yyjson_is_uint(id))
402 yyjson_mut_obj_add_uint(doc, root, "id", yyjson_get_uint(id));
403 else if (yyjson_is_str(id))
404 yyjson_mut_obj_add_strcpy(doc, root, "id", yyjson_get_str(id));
405 else if (yyjson_is_null(id))
406 yyjson_mut_obj_add_null(doc, root, "id");
407}
408
409static yyjson_mut_val *tool_defs(yyjson_mut_doc *doc,
410 const sx_mcp_tool *tools, size_t ntools)
411{
412 yyjson_mut_val *arr = yyjson_mut_arr(doc);
413 size_t i;
414 for (i = 0; i < ntools; i++) {
415 yyjson_mut_val *t = yyjson_mut_obj(doc);
416 yyjson_mut_obj_add_strcpy(doc, t, "name", tools[i].name);
417 yyjson_mut_obj_add_strcpy(doc, t, "description",
418 tools[i].description ? tools[i].description : "");
419 if (tools[i].input_schema_json && *tools[i].input_schema_json) {
420 yyjson_doc *sd = yyjson_read(tools[i].input_schema_json, strlen(tools[i].input_schema_json), 0);
421 if (sd) {
422 yyjson_mut_val *sc = yyjson_val_mut_copy(doc, yyjson_doc_get_root(sd));
423 yyjson_mut_obj_add_val(doc, t, "inputSchema", sc);
424 yyjson_doc_free(sd);
425 }
426 } else {
427 {
428 yyjson_mut_val *sc = yyjson_mut_obj(doc);
429 yyjson_mut_obj_add_strcpy(doc, sc, "type", "object");
430 yyjson_mut_obj_add_val(doc, t, "inputSchema", sc);
431 }
432 }
433 yyjson_mut_arr_add_val(arr, t);
434 }
435 return arr;
436}
437
438int sx_mcp_handle_line(const sx_plugin_info *info,
439 const sx_mcp_tool *tools, size_t ntools,
440 const char *line, int *did_reply)
441{
442 yyjson_doc *doc;
443 yyjson_val *root, *method, *id, *params;
444 yyjson_mut_doc *mo;
445 yyjson_mut_val *mroot;
446 const char *m;
447 int reply = 0;
448
449 if (did_reply) *did_reply = 0;
450 if (!line || !*line) return -1;
451 doc = yyjson_read(line, strlen(line), 0);
452 if (!doc) return -1;
453 root = yyjson_doc_get_root(doc);
454 method = yyjson_obj_get(root, "method");
455 id = yyjson_obj_get(root, "id");
456 params = yyjson_obj_get(root, "params");
457 m = (method && yyjson_is_str(method)) ? yyjson_get_str(method) : "";
458
459 mo = yyjson_mut_doc_new(NULL);
460 mroot = yyjson_mut_obj(mo);
461
462 if (strcmp(m, "initialize") == 0) {
463 sx_plugin_info in = *info;
464 yyjson_mut_val *res, *caps, *si;
465 sx_info_fill(&in);
466 copy_id(mo, mroot, id);
467 res = yyjson_mut_obj(mo);
468 yyjson_mut_obj_add_strcpy(mo, res, "protocolVersion", MCP_PROTOCOL);
469 caps = yyjson_mut_obj(mo);
470 yyjson_mut_obj_add_val(mo, res, "capabilities", caps);
471 si = yyjson_mut_obj(mo);
472 yyjson_mut_obj_add_strcpy(mo, si, "name", in.id);
473 yyjson_mut_obj_add_strcpy(mo, si, "version", in.version);
474 yyjson_mut_obj_add_val(mo, res, "serverInfo", si);
475 yyjson_mut_obj_add_val(mo, mroot, "result", res);
476 reply = 1;
477 } else if (strcmp(m, "ping") == 0) {
478 copy_id(mo, mroot, id);
479 yyjson_mut_obj_add_val(mo, mroot, "result", yyjson_mut_obj(mo));
480 reply = 1;
481 } else if (strcmp(m, "tools/list") == 0) {
482 yyjson_mut_val *res = yyjson_mut_obj(mo);
483 copy_id(mo, mroot, id);
484 yyjson_mut_obj_add_val(mo, res, "tools", tool_defs(mo, tools, ntools));
485 yyjson_mut_obj_add_val(mo, mroot, "result", res);
486 reply = 1;
487 } else if (strcmp(m, "tools/call") == 0) {
488 const char *name = NULL, *args = "{}";
489 char *args_buf = NULL;
490 char out[65536], errbuf[512];
491 int rc = -1, i;
492 size_t no;
493 yyjson_mut_val *res, *content, *block;
494 yyjson_val *pn, *pa;
495
496 if (params && yyjson_is_obj(params)) {
497 pn = yyjson_obj_get(params, "name");
498 pa = yyjson_obj_get(params, "arguments");
499 name = (pn && yyjson_is_str(pn)) ? yyjson_get_str(pn) : NULL;
500 if (pa) { args_buf = yyjson_val_write(pa, 0, NULL); if (args_buf) args = args_buf; }
501 }
502 out[0] = '\0'; errbuf[0] = '\0';
503 for (no = 0, i = 0; i < (int)ntools; i++) {
504 if (name && strcmp(tools[i].name, name) == 0) {
505 rc = tools[i].call(args, out, sizeof out, errbuf, sizeof errbuf);
506 no = 1;
507 break;
508 }
509 }
510 copy_id(mo, mroot, id);
511 res = yyjson_mut_obj(mo);
512 content = yyjson_mut_arr(mo);
513 block = yyjson_mut_obj(mo);
514 yyjson_mut_obj_add_strcpy(mo, block, "type", "text");
515 yyjson_mut_obj_add_strcpy(mo, block, "text",
516 rc == 0 ? out : (errbuf[0] ? errbuf : "tool failed"));
517 yyjson_mut_arr_add_val(content, block);
518 yyjson_mut_obj_add_val(mo, res, "content", content);
519 yyjson_mut_obj_add_bool(mo, res, "isError", (rc != 0 || !no) ? 1 : 0);
520 yyjson_mut_obj_add_val(mo, mroot, "result", res);
521 free(args_buf);
522 reply = 1;
523 } else if (strncmp(m, "notifications/", 14) == 0) {
524 reply = 0; /* never answer notifications */
525 } else if (id) {
526 yyjson_mut_val *err;
527 copy_id(mo, mroot, id);
528 err = yyjson_mut_obj(mo);
529 yyjson_mut_obj_add_int(mo, err, "code", -32601);
530 yyjson_mut_obj_add_strcpy(mo, err, "message", "method not found");
531 yyjson_mut_obj_add_val(mo, mroot, "error", err);
532 reply = 1;
533 }
534
535 if (reply) {
536 yyjson_mut_doc_set_root(mo, mroot);
537 yyjson_mut_obj_add_strcpy(mo, mroot, "jsonrpc", "2.0");
538 sx_print_json_doc(mo);
539 }
540 yyjson_mut_doc_free(mo);
541 yyjson_doc_free(doc);
542 if (did_reply) *did_reply = reply;
543 return 0;
544}
545/* Read one line from stdin into a malloc'd buffer (caller frees *line_out).
546 *
547 * Shared by both platforms on purpose. The Windows branch used to be its own
548 * hand-rolled getline() shim, which meant the MCP loop had two parsers and
549 * only one of them was exercised by the suite on the machine that ships the
550 * binaries. It also kept the carriage return: sx_stdio_binary() puts stdin in
551 * _O_BINARY so that our own CGI headers are never rewritten, and that also
552 * turns off the CRLF translation a text-mode stdin would have done, so a peer
553 * that sends CRLF lines handed the JSON parser a trailing '\r' here.
554 *
555 * cap always starts at 0 because line always starts NULL: a caller that hands
556 * back the previous line's capacity alongside a freed buffer would make the
557 * grow check skip its realloc and write into address zero -- the second MCP
558 * request of every session SEGVed on the zero page in the fgetc loop.
559 *
560 * Returns 1 when a line was read, 0 on clean EOF with nothing pending,
561 * -1 on allocation failure. */
562static int sx_read_line_stdin(char **line_out, size_t *cap_io)
563{
564 char *line = NULL;
565 size_t cap = 0, len = 0;
566 int ch, saw_any = 0;
567
568 for (;;) {
569 ch = fgetc(stdin);
570 if (ch == EOF) break;
571 saw_any = 1;
572 if (ch == '\n') break;
573 if (len + 2 > cap) {
574 char *nb;
575 cap = cap ? cap * 2 : 256;
576 nb = (char *)realloc(line, cap);
577 if (!nb) { free(line); if (cap_io) *cap_io = 0; return -1; }
578 line = nb;
579 }
580 line[len++] = (char)ch;
581 }
582 if (!saw_any) { free(line); if (cap_io) *cap_io = cap; return 0; }
583 if (len && line[len - 1] == '\r') len--; /* tolerate CRLF peers */
584 if (len + 1 > cap) { /* the stripped-\r edge */
585 char *nb = (char *)realloc(line, len + 1);
586 if (!nb) { free(line); if (cap_io) *cap_io = 0; return -1; }
587 line = nb;
588 cap = len + 1;
589 }
590 line[len] = '\0';
591 if (cap_io) *cap_io = cap;
592 *line_out = line;
593 return 1;
594}
595
596int sx_mcp_serve(const sx_plugin_info *info,
597 const sx_mcp_tool *tools, size_t ntools)
598{
599 char *line = NULL;
600 size_t cap = 0;
601 int r;
602
603 setvbuf(stdout, NULL, _IONBF, 0);
604 sx_ignore_sigpipe();
605 for (;;) {
606 line = NULL;
607 r = sx_read_line_stdin(&line, &cap);
608 if (r < 0) return 1;
609 if (r == 0) { free(line); return 0; }
610 if (*line) sx_mcp_handle_line(info, tools, ntools, line, NULL);
611 free(line);
612 }
613}
614
615int sx_mcp_schema(const sx_plugin_info *info,
616 const sx_mcp_tool *tools, size_t ntools)
617{
618 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
619 yyjson_mut_val *root = yyjson_mut_obj(doc);
620 yyjson_mut_doc_set_root(doc, root);
621 (void)info;
622 yyjson_mut_obj_add_val(doc, root, "tools", tool_defs(doc, tools, ntools));
623 sx_print_json_doc(doc);
624 yyjson_mut_doc_free(doc);
625 return 0;
626}
627
628/* =====================================================================
629 * dispatch
630 * ===================================================================== */
631
632int sx_main(int argc, char **argv, const sx_plugin_info *info,
633 sx_html_cb html_cb, sx_json_cb json_cb)
634{
635 sx_plugin_info in = *info;
636 const char *qs = getenv("QUERY_STRING");
637 const char *method = getenv("REQUEST_METHOD");
638 char action[64];
639
640 sx_info_fill(&in);
641 sx_stdio_binary();
642 sx_ignore_sigpipe();
643
644 if (getenv("SX_PLUGIN_META") || sx_has_flag(argc, argv, "--meta")) {
645 sx_meta_emit(&in);
646 return 0;
647 }
648 if (sx_has_flag(argc, argv, "--schema"))
649 return sx_mcp_schema(&in, NULL, 0);
650 if (sx_has_flag(argc, argv, "--mcp"))
651 return sx_mcp_serve(&in, NULL, 0);
652
653 /* connector modes are dispatched by the plugin's own main() before it
654 * reaches here (--daemon needs the plugin's tick function). */
655
656 action[0] = '\0';
657 sx_query_get(qs, "action", action, sizeof action);
658
659 if (json_cb && (action[0] ||
660 (qs && strstr(qs, "format=json")) ||
661 (method && sx_ieq(method, "POST")))) {
662 char *body = sx_read_body();
663 int rc;
664 sx_require_node_auth();
665 rc = json_cb(&in, qs ? qs : "", action, body);
666 free(body);
667 return rc;
668 }
669 if (html_cb)
670 return html_cb(&in, qs ? qs : "", sx_is_embedded(qs),
671 sx_theme_from_query(qs, "dark"));
672 return 0;
673}
674
675/* =====================================================================
676 * connector dir + files
677 * ===================================================================== */
678
679int sx_mkdir_p(const char *path)
680{
681 char tmp[1024];
682 char *p;
683 size_t len;
684
685 sx_copy(tmp, sizeof tmp, path);
686 len = strlen(tmp);
687 if (len == 0) return -1;
688 if (tmp[len - 1] == '/' || tmp[len - 1] == '\\') tmp[len - 1] = '\0';
689 for (p = tmp + 1; *p; p++) {
690 if (*p == '/' || *p == '\\') {
691 char save = *p;
692 *p = '\0';
693 SX_MKDIR(tmp);
694 *p = save;
695 }
696 }
697 SX_MKDIR(tmp);
698 {
699 struct stat st;
700 return stat(tmp, &st) == 0 && S_ISDIR(st.st_mode) ? 0 : -1;
701 }
702}
703
704int sx_read_file(const char *path, char **buf, size_t *len)
705{
706 FILE *f = fopen(path, "rb");
707 struct stat st;
708 char *b;
709 size_t rd;
710
711 if (!f) return 0;
712 if (fstat(fileno(f), &st) == 0 && st.st_size > 16 * 1024 * 1024) { fclose(f); return -1; }
713 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return -1; }
714 {
715 long sz = ftell(f);
716 fseek(f, 0, SEEK_SET);
717 if (sz < 0) { fclose(f); return -1; }
718 b = (char *)malloc((size_t)sz + 1);
719 if (!b) { fclose(f); return -1; }
720 rd = fread(b, 1, (size_t)sz, f);
721 b[rd] = '\0';
722 }
723 fclose(f);
724 *buf = b;
725 if (len) *len = strlen(b);
726 return 1;
727}
728
729int sx_write_file(const char *path, const void *buf, size_t len)
730{
731 char tmp[1088];
732 FILE *f;
733 size_t wr;
734 const char *slash;
735
736 /* create the parent directory */
737 sx_copy(tmp, sizeof tmp, path);
738 slash = strrchr(tmp, '/');
739#if defined(_WIN32)
740 { const char *bs = strrchr(tmp, '\\'); if (!slash || (bs && bs > slash)) slash = bs; }
741#endif
742 if (slash) {
743 char dir[1088];
744 size_t dl = (size_t)(slash - tmp);
745 if (dl >= sizeof dir) dl = sizeof dir - 1;
746 memcpy(dir, tmp, dl);
747 dir[dl] = '\0';
748 sx_mkdir_p(dir);
749 }
750
751 snprintf(tmp, sizeof tmp, "%s.tmp.%lu", path, (unsigned long)
752#if defined(_WIN32)
753 GetCurrentProcessId()
754#else
755 (unsigned long)getpid()
756#endif
757 );
758 f = fopen(tmp, "wb");
759 if (!f) return -1;
760 wr = fwrite(buf, 1, len, f);
761 fclose(f);
762 if (wr != len) { remove(tmp); return -1; }
763 remove(path); /* windows rename needs the target gone */
764 if (rename(tmp, path) != 0) { remove(tmp); return -1; }
765 return 0;
766}
767
768static const char *sx_home(void)
769{
770 const char *h = getenv("HOME");
771 if (h && *h) return h;
772 h = getenv("USERPROFILE");
773 if (h && *h) return h;
774 return ".";
775}
776
777int sx_connector_dir(const char *id, char *out, size_t capsz)
778{
779 const char *env = getenv("SX_CONNECTOR_DIR");
780 struct stat st;
781 int ok;
782
783 if (!id || !*id) id = "connector";
784 if (env && *env) {
785 snprintf(out, capsz, "%s", env);
786 } else if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) {
787 snprintf(out, capsz, "/workspace/.scorpiox/connectors/%s", id);
788 } else {
789 const char *la = getenv("LOCALAPPDATA");
790 if (la && *la)
791 snprintf(out, capsz, "%s\\scorpiox\\connectors\\%s", la, id);
792 else
793 snprintf(out, capsz, "%s/.scorpiox/connectors/%s", sx_home(), id);
794 }
795 ok = (stat(out, &st) == 0 && S_ISDIR(st.st_mode));
796 if (!ok) ok = (sx_mkdir_p(out) == 0);
797 return ok ? 0 : -1;
798}
799
800int sx_connector_path(const char *id, const char *name, char *out, size_t capsz)
801{
802 char dir[896];
803 if (sx_connector_dir(id, dir, sizeof dir) != 0) return -1;
804#if defined(_WIN32)
805 snprintf(out, capsz, "%s\\%s", dir, name);
806#else
807 snprintf(out, capsz, "%s/%s", dir, name);
808#endif
809 return 0;
810}
811
812int sx_json_file_load(const char *id, const char *name, yyjson_doc **doc)
813{
814 char path[1024], *buf = NULL; size_t len = 0;
815 if (sx_connector_path(id, name, path, sizeof path) != 0) return -1;
816 if (sx_read_file(path, &buf, &len) != 1) return -1;
817 *doc = yyjson_read(buf, len, 0);
818 free(buf);
819 return *doc ? 0 : -1;
820}
821
822int sx_json_file_save(const char *id, const char *name, yyjson_mut_doc *doc)
823{
824 char path[1024];
825 char *s;
826 int rc;
827 if (sx_connector_path(id, name, path, sizeof path) != 0) return -1;
828 s = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), YYJSON_WRITE_PRETTY, NULL);
829 if (!s) return -1;
830 rc = sx_write_file(path, s, strlen(s));
831 free(s);
832 return rc;
833}
834
835void sx_make_id(char *out, size_t capsz)
836{
837 static unsigned counter = 0;
838 counter++;
839 snprintf(out, capsz, "%llx-%04x", (unsigned long long)sx_now_ms(),
840 (unsigned)(counter ^ (unsigned)(size_t)out));
841}
842
843void sx_make_code(char *out, size_t capsz)
844{
845 static const char alpha[] = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; /* no I/O/0/1 */
846 size_t n = SX_CODE_LEN, i;
847 if (capsz < n + 1) { if (capsz) out[0] = '\0'; return; }
848 for (i = 0; i < n; i++)
849 out[i] = alpha[(unsigned)(rand() + (int)sx_now_ms() + (int)i * 773) % (sizeof alpha - 1)];
850 out[n] = '\0';
851}
852
853void sx_log(const char *id, const char *fmt, ...)
854{
855 va_list ap;
856 fprintf(stderr, "[%s] ", id ? id : "connector");
857 va_start(ap, fmt);
858 vfprintf(stderr, fmt, ap);
859 va_end(ap);
860 fputc('\n', stderr);
861 fflush(stderr);
862}
863
864/* =====================================================================
865 * senders + pairing (default-deny)
866 * ===================================================================== */
867
868#define SENDERS_FILE "senders.json"
869
870void sx_senders_free(sx_sender *items)
871{
872 free(items);
873}
874
875int sx_senders_load(const char *id, sx_sender **out, size_t *n_out)
876{
877 yyjson_doc *doc = NULL;
878 yyjson_val *arr, *it;
879 sx_sender *items = NULL;
880 size_t n = 0, cap = 0, i, max;
881
882 *out = NULL; *n_out = 0;
883 if (sx_json_file_load(id, SENDERS_FILE, &doc) != 0) return 0; /* none yet */
884 arr = yyjson_doc_get_root(doc);
885 if (!arr || !yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; }
886 max = yyjson_arr_size(arr);
887 items = (sx_sender *)calloc(max ? max : 1, sizeof *items);
888 if (!items) { yyjson_doc_free(doc); return -1; }
889 yyjson_arr_foreach(arr, i, max, it) {
890 yyjson_val *v;
891 if (n + 1 > cap) {
892 sx_sender *nb;
893 cap = cap ? cap * 2 : 16;
894 nb = (sx_sender *)realloc(items, cap * sizeof *items);
895 if (!nb) break;
896 items = nb;
897 }
898 memset(&items[n], 0, sizeof items[n]);
899 v = yyjson_obj_get(it, "key"); if (v) sx_copy(items[n].key, sizeof items[n].key, yyjson_get_str(v));
900 v = yyjson_obj_get(it, "label"); if (v) sx_copy(items[n].label, sizeof items[n].label, yyjson_get_str(v));
901 v = yyjson_obj_get(it, "code"); if (v) sx_copy(items[n].code, sizeof items[n].code, yyjson_get_str(v));
902 v = yyjson_obj_get(it, "created"); if (v && yyjson_is_int(v)) items[n].created = (long long)yyjson_get_sint(v);
903 v = yyjson_obj_get(it, "approved"); items[n].approved = (v && yyjson_is_true(v)) ? 1 : 0;
904 if (items[n].key[0]) n++;
905 }
906 yyjson_doc_free(doc);
907 *out = items; *n_out = n;
908 return 0;
909}
910
911int sx_senders_save(const char *id, const sx_sender *items, size_t n)
912{
913 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
914 yyjson_mut_val *arr = yyjson_mut_arr(doc);
915 size_t i;
916 int rc;
917 yyjson_mut_doc_set_root(doc, arr);
918 for (i = 0; i < n; i++) {
919 yyjson_mut_val *o = yyjson_mut_obj(doc);
920 yyjson_mut_obj_add_strcpy(doc, o, "key", items[i].key);
921 yyjson_mut_obj_add_strcpy(doc, o, "label", items[i].label);
922 yyjson_mut_obj_add_strcpy(doc, o, "code", items[i].code);
923 yyjson_mut_obj_add_int(doc, o, "created", (long long)items[i].created);
924 yyjson_mut_obj_add_bool(doc, o, "approved", items[i].approved);
925 yyjson_mut_arr_add_val(arr, o);
926 }
927 rc = sx_json_file_save(id, SENDERS_FILE, doc);
928 yyjson_mut_doc_free(doc);
929 return rc;
930}
931
932int sx_sender_allowed(const char *id, const char *key, const char *label,
933 int pairing_enabled, char *code_out, size_t codesz)
934{
935 sx_sender *items = NULL;
936 size_t n = 0, i;
937 int allowed = 0;
938
939 if (code_out && codesz) code_out[0] = '\0';
940 if (!key || !*key) return 0; /* default-deny */
941 if (sx_senders_load(id, &items, &n) != 0) return 0;
942
943 for (i = 0; i < n; i++) {
944 if (strcmp(items[i].key, key) == 0) {
945 if (items[i].approved) allowed = 1;
946 else if (pairing_enabled && code_out && codesz)
947 sx_copy(code_out, codesz, items[i].code);
948 sx_senders_free(items);
949 return allowed;
950 }
951 }
952 /* unknown sender: queue as pending with a fresh code (default-deny) */
953 if (pairing_enabled) {
954 sx_sender *nb = (sx_sender *)realloc(items, (n + 1) * sizeof *items);
955 if (nb) {
956 items = nb;
957 memset(&items[n], 0, sizeof items[n]);
958 sx_copy(items[n].key, sizeof items[n].key, key);
959 sx_copy(items[n].label, sizeof items[n].label, label ? label : "");
960 items[n].created = (long long)time(NULL);
961 items[n].approved = 0;
962 sx_make_code(items[n].code, sizeof items[n].code);
963 sx_copy(code_out, codesz, items[n].code);
964 sx_senders_save(id, items, n + 1);
965 }
966 }
967 sx_senders_free(items);
968 return 0;
969}
970
971static int sx_sender_set_field(const char *id, const char *key,
972 int approved, int remove_entry)
973{
974 sx_sender *items = NULL;
975 size_t n = 0, i, o = 0;
976 int found = 0;
977
978 if (sx_senders_load(id, &items, &n) != 0) return -1;
979 for (i = 0; i < n; i++) {
980 if (strcmp(items[i].key, key) != 0) {
981 if (o != i) items[o] = items[i];
982 o++;
983 continue;
984 }
985 found = 1;
986 if (remove_entry) continue;
987 items[o++] = items[i];
988 items[o - 1].approved = approved;
989 }
990 sx_senders_save(id, items, o);
991 sx_senders_free(items);
992 return found ? 0 : -1;
993}
994
995int sx_sender_approve(const char *id, const char *key)
996{
997 return sx_sender_set_field(id, key, 1, 0);
998}
999
1000int sx_sender_remove(const char *id, const char *key)
1001{
1002 return sx_sender_set_field(id, key, 0, 1);
1003}
1004
1005int sx_pairing_lookup(const char *id, const char *code, char *key_out, size_t capsz)
1006{
1007 sx_sender *items = NULL;
1008 size_t n = 0, i;
1009 int found = 0;
1010
1011 if (key_out && capsz) key_out[0] = '\0';
1012 if (!code || !*code) return 0;
1013 if (sx_senders_load(id, &items, &n) != 0) return 0;
1014 for (i = 0; i < n; i++) {
1015 if (items[i].code[0] && sx_ieq(items[i].code, code)) {
1016 items[i].approved = 1;
1017 sx_copy(key_out, capsz, items[i].key);
1018 sx_senders_save(id, items, n);
1019 found = 1;
1020 break;
1021 }
1022 }
1023 sx_senders_free(items);
1024 return found;
1025}
1026
1027/* =====================================================================
1028 * node loopback client
1029 * ===================================================================== */
1030
1031const char *sx_node_api_base(void)
1032{
1033 const char *b = getenv("SX_NODE_API");
1034 if (b && *b) return b;
1035 return "http://127.0.0.1:8150";
1036}
1037
1038static void sx_hdr_pwd(char *hdrs, size_t capsz)
1039{
1040 const char *pwd = sx_node_password();
1041 char safe[256];
1042 size_t i, o = 0;
1043 if (!pwd) { hdrs[0] = '\0'; return; }
1044 /* header-injection guard: strip CR/LF from the password */
1045 for (i = 0; pwd[i] && o + 1 < sizeof safe; i++)
1046 if (pwd[i] != '\r' && pwd[i] != '\n') safe[o++] = pwd[i];
1047 safe[o] = '\0';
1048 snprintf(hdrs, capsz, "X-Bot-Password: %s\r\n", safe);
1049}
1050
1051int sx_node_post_inbox(const char *session, const char *text,
1052 const char *mode, char *err, size_t errsz)
1053{
1054 sx_conn c;
1055 sx_url u;
1056 char path[512], hdrs[300], body[70000];
1057 yyjson_mut_doc *doc;
1058 char *bodystr;
1059 int rc = -1;
1060
1061 snprintf(path, sizeof path, "/inbox?id=%s%s%s",
1062 session ? session : "",
1063 mode ? "&mode=" : "", mode ? mode : "");
1064 doc = yyjson_mut_doc_new(NULL);
1065 yyjson_mut_val *root = yyjson_mut_obj(doc);
1066 yyjson_mut_doc_set_root(doc, root);
1067 yyjson_mut_obj_add_strcpy(doc, root, "text", text ? text : "");
1068 bodystr = yyjson_mut_val_write(yyjson_mut_doc_get_root(doc), 0, NULL);
1069 yyjson_mut_doc_free(doc);
1070 if (!bodystr) { sx_copy(err, errsz, "encode failed"); return -1; }
1071 sx_copy(body, sizeof body, bodystr);
1072 free(bodystr);
1073
1074 sx_hdr_pwd(hdrs, sizeof hdrs);
1075 {
1076 char url[1536];
1077 snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path);
1078 if (sx_url_parse(url, &u, err, errsz) != 0) return -1;
1079 if (sx_conn_open(&c, &u, 10000, err, errsz) != 0) return -1;
1080 }
1081 {
1082 char full[1536];
1083 snprintf(full, sizeof full, "Content-Type: application/json\r\n%s", hdrs);
1084 if (sx_http_request(&c, "POST", path, full, NULL,
1085 body, strlen(body), 10000, err, errsz) == 0 &&
1086 c.status >= 200 && c.status < 300)
1087 rc = 0;
1088 else if (err && errsz)
1089 snprintf(err, errsz, "node inbox status %ld", c.status);
1090 }
1091 sx_conn_close(&c);
1092 return rc;
1093}
1094
1095int sx_node_conversation(const char *session, long after, long limit,
1096 char **body_out, char *err, size_t errsz)
1097{
1098 sx_conn c;
1099 sx_url u;
1100 char path[512], hdrs[300], url[1536];
1101 char *body = NULL;
1102 int rc = -1;
1103
1104 snprintf(path, sizeof path, "/conversation?id=%s&after=%ld&limit=%ld",
1105 session ? session : "", after, limit);
1106 snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path);
1107 sx_hdr_pwd(hdrs, sizeof hdrs);
1108 if (sx_url_parse(url, &u, err, errsz) != 0) return -1;
1109 if (sx_conn_open(&c, &u, 10000, err, errsz) != 0) return -1;
1110 if (sx_http_request(&c, "GET", path, hdrs, NULL, NULL, 0,
1111 15000, err, errsz) == 0 && c.status == 200) {
1112 if (sx_read_all(&c, &body, NULL, 15000) == 1) {
1113 *body_out = body;
1114 rc = 0;
1115 }
1116 } else {
1117 snprintf(err, errsz, "node conversation status %ld", c.status);
1118 }
1119 sx_conn_close(&c);
1120 return rc;
1121}
1122
1123/* ------------------------------------------------------------------ SSE */
1124
1125int sx_sse_open(sx_sse *s, const char *session, long after,
1126 char *err, size_t errsz)
1127{
1128 sx_conn *c = &s->c;
1129 sx_url u;
1130 char path[512], url[1536], sse_hdrs[300];
1131 const char *pwd;
1132
1133 memset(s, 0, sizeof *s);
1134 if (after > 0)
1135 snprintf(path, sizeof path, "/hashes_sse?id=%s&after=%ld", session, after);
1136 else
1137 snprintf(path, sizeof path, "/hashes_sse?id=%s", session);
1138 snprintf(url, sizeof url, "%s%s", sx_node_api_base(), path);
1139 if (sx_url_parse(url, &u, err, errsz) != 0) return -1;
1140 if (sx_conn_open(c, &u, 10000, err, errsz) != 0) return -1;
1141
1142 pwd = sx_node_password();
1143 (void)pwd;
1144 sx_hdr_pwd(sse_hdrs, sizeof sse_hdrs);
1145 if (sx_http_request(c, "GET", path, sse_hdrs, NULL, NULL, 0,
1146 15000, err, errsz) != 0) {
1147 sx_conn_close(c);
1148 return -1;
1149 }
1150 if (c->status != 200) {
1151 snprintf(err, errsz, "hashes_sse status %ld", c->status);
1152 sx_conn_close(c);
1153 return -1;
1154 }
1155 (void)pwd;
1156 s->open = 1;
1157 return 0;
1158}
1159
1160int sx_sse_next(sx_sse *s, sx_sse_event *ev, long timeout_ms)
1161{
1162 char line[8192];
1163 int have_data = 0, have_event = 0;
1164 long long stop = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 30000);
1165
1166 if (!s->open) return -1;
1167 memset(ev, 0, sizeof *ev);
1168
1169 while (sx_now_ms() < stop) {
1170 int r = sx_read_line(&s->c, line, sizeof line,
1171 (long)(stop - sx_now_ms()));
1172 if (r < 0) { s->open = 0; return -1; }
1173 if (r == 0) { s->open = 0; return 0; }
1174 if (line[0] == '\0') { /* blank line: end of event */
1175 if (have_data) {
1176 /* parse the json payload for the convenience fields */
1177 yyjson_doc *d = yyjson_read(ev->json, strlen(ev->json), 0);
1178 if (d) {
1179 yyjson_val *root = yyjson_doc_get_root(d), *v;
1180 v = yyjson_obj_get(root, "id");
1181 if (v && yyjson_is_str(v)) sx_copy(ev->id, sizeof ev->id, yyjson_get_str(v));
1182 v = yyjson_obj_get(root, "session_id");
1183 if (v && yyjson_is_str(v)) sx_copy(ev->session_id, sizeof ev->session_id, yyjson_get_str(v));
1184 v = yyjson_obj_get(root, "total");
1185 if (v && yyjson_is_int(v)) ev->total = (long)yyjson_get_sint(v);
1186 v = yyjson_obj_get(root, "after");
1187 if (v && yyjson_is_int(v)) ev->after = (long)yyjson_get_sint(v);
1188 yyjson_doc_free(d);
1189 }
1190 return 1;
1191 }
1192 continue;
1193 }
1194 if (strncmp(line, "event:", 6) == 0) {
1195 const char *p = line + 6;
1196 while (*p == ' ') p++;
1197 sx_copy(ev->event, sizeof ev->event, p);
1198 have_event = 1;
1199 (void)have_event;
1200 } else if (strncmp(line, "data:", 5) == 0) {
1201 const char *p = line + 5;
1202 while (*p == ' ') p++;
1203 sx_copy(ev->json, sizeof ev->json, p);
1204 have_data = 1;
1205 }
1206 }
1207 return -1; /* timeout */
1208}
1209
1210void sx_sse_close(sx_sse *s)
1211{
1212 s->open = 0;
1213 sx_conn_close(&s->c);
1214}
1215
1216/* =====================================================================
1217 * daemon lifecycle
1218 * ===================================================================== */
1219
1220#if !defined(_WIN32)
1221static volatile sig_atomic_t g_got_signal = 0;
1222static void sx_on_sig(int sig) { (void)sig; g_got_signal = 1; }
1223#endif
1224
1225int sx_daemon_request_stop(const char *id)
1226{
1227 char path[1024];
1228 if (sx_connector_path(id, "stop", path, sizeof path) != 0) return -1;
1229 return sx_write_file(path, "stop\n", 5);
1230}
1231
1232int sx_daemon_stop_requested(const char *id)
1233{
1234 char path[1024];
1235 struct stat st;
1236 if (sx_connector_path(id, "stop", path, sizeof path) != 0) return 0;
1237 return stat(path, &st) == 0;
1238}
1239
1240static void sx_clear_stop(const char *id)
1241{
1242 char path[1024];
1243 if (sx_connector_path(id, "stop", path, sizeof path) == 0) remove(path);
1244}
1245
1246static void sx_sleep_ms(unsigned ms)
1247{
1248#if defined(_WIN32)
1249 Sleep(ms);
1250#else
1251 struct timespec ts;
1252 ts.tv_sec = (time_t)(ms / 1000);
1253 ts.tv_nsec = (long)((ms % 1000) * 1000000L);
1254 nanosleep(&ts, NULL);
1255#endif
1256}
1257
1258int sx_daemon_run(const sx_daemon_cfg *cfg, sx_daemon_tick tick)
1259{
1260 char dir[896], pidpath[1024];
1261 unsigned interval = cfg->interval_ms ? cfg->interval_ms : 1000;
1262 char pid[32];
1263 int rc = 0;
1264
1265 if (sx_connector_dir(cfg->id, dir, sizeof dir) != 0) {
1266 sx_log(cfg->id, "cannot create connector dir");
1267 return 1;
1268 }
1269 sx_clear_stop(cfg->id);
1270
1271 snprintf(pid, sizeof pid, "%lu\n", (unsigned long)
1272#if defined(_WIN32)
1273 GetCurrentProcessId()
1274#else
1275 (unsigned long)getpid()
1276#endif
1277 );
1278 if (sx_connector_path(cfg->id, "daemon.pid", pidpath, sizeof pidpath) == 0)
1279 sx_write_file(pidpath, pid, strlen(pid));
1280
1281#if !defined(_WIN32)
1282 signal(SIGTERM, sx_on_sig);
1283 signal(SIGINT, sx_on_sig);
1284 signal(SIGHUP, sx_on_sig);
1285 signal(SIGPIPE, SIG_IGN);
1286#endif
1287
1288 sx_log(cfg->id, "daemon up (session=%s interval=%ums dir=%s)",
1289 cfg->session ? cfg->session : "-", interval, dir);
1290
1291 for (;;) {
1292#if !defined(_WIN32)
1293 if (g_got_signal) break;
1294#endif
1295 if (sx_daemon_stop_requested(cfg->id)) break;
1296 if (tick && tick(cfg, cfg->user)) break;
1297 sx_sleep_ms(interval);
1298 }
1299
1300 sx_log(cfg->id, "daemon stopping");
1301 sx_clear_stop(cfg->id);
1302 if (pidpath[0]) remove(pidpath);
1303 (void)rc;
1304 return 0;
1305}