scorpiox-bot-plugin-ntfy
←sx_connectors.cc
1117 lines · 37 KBHEADBlameDownload
1/*
2 * sx_connectors.c -- persistent state for plugin_ntfy.
3 *
4 * MIT License. Copyright (c) 2026 SCORPIOX INC.
5 */
6
7#if defined(_WIN32)
8# ifndef _WIN32_WINNT
9# define _WIN32_WINNT 0x0601
10# endif
11# define WIN32_LEAN_AND_MEAN
12#else
13# if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L
14# undef _POSIX_C_SOURCE
15# define _POSIX_C_SOURCE 200809L
16# endif
17# ifndef _DEFAULT_SOURCE
18# define _DEFAULT_SOURCE 1
19# endif
20# if defined(__APPLE__)
21# undef _DARWIN_C_SOURCE
22# define _DARWIN_C_SOURCE 1
23# endif
24#endif
25
26#include "sx_connectors.h"
27#include "sx_http.h"
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <stdarg.h>
32#include <string.h>
33#include <ctype.h>
34#include <errno.h>
35#include <time.h>
36#include <sys/stat.h>
37
38#if defined(_WIN32)
39# include <windows.h>
40# include <direct.h>
41# define sx_mkdir(p) _mkdir(p)
42# define sx_sep '\\'
43#else
44# include <unistd.h>
45# include <signal.h>
46# include <fcntl.h>
47# include <pwd.h>
48# define sx_mkdir(p) mkdir((p), 0700)
49# define sx_sep '/'
50#endif
51
52#include "yyjson.h"
53
54#define PENDING_CAP 64
55#define APPROVED_CAP 256
56#define SENT_CAP 512
57
58/* ------------------------------------------------------------------ misc */
59
60long long sx_ntfy_now_epoch(void)
61{
62 return (long long)time(NULL);
63}
64
65static void set_err(char *err, size_t errsz, const char *fmt, ...)
66{
67 va_list ap;
68 if (!err || !errsz) return;
69 va_start(ap, fmt);
70 vsnprintf(err, errsz, fmt, ap);
71 va_end(ap);
72}
73
74void sx_ntfy_json_escape(const char *in, char *out, size_t capsz)
75{
76 static const char *hex = "0123456789abcdef";
77 size_t o = 0;
78 const unsigned char *p;
79 if (!capsz) return;
80 if (!in) in = "";
81 for (p = (const unsigned char *)in; *p; p++) {
82 unsigned char c = *p;
83 char tmp[8];
84 const char *src = tmp;
85 size_t l;
86 switch (c) {
87 case '"': snprintf(tmp, sizeof tmp, "%s", "\\\""); break;
88 case '\\': snprintf(tmp, sizeof tmp, "%s", "\\\\"); break;
89 case '\n': snprintf(tmp, sizeof tmp, "%s", "\\n"); break;
90 case '\r': snprintf(tmp, sizeof tmp, "%s", "\\r"); break;
91 case '\t': snprintf(tmp, sizeof tmp, "%s", "\\t"); break;
92 default:
93 if (c < 0x20) snprintf(tmp, sizeof tmp, "\\u%04x", c);
94 else { tmp[0] = (char)c; tmp[1] = '\0'; }
95 break;
96 }
97 l = strlen(src);
98 if (o + l + 1 > capsz) break;
99 memcpy(out + o, src, l);
100 o += l;
101 }
102 out[o] = '\0';
103 (void)hex;
104}
105
106int sx_ntfy_read_file(const char *path, char **buf, size_t *len)
107{
108 FILE *f;
109 long sz;
110 char *b;
111 size_t rd;
112
113 if (buf) *buf = NULL;
114 if (len) *len = 0;
115 f = fopen(path, "rb");
116 if (!f) return -1;
117 fseek(f, 0, SEEK_END);
118 sz = ftell(f);
119 fseek(f, 0, SEEK_SET);
120 if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return -1; }
121 b = malloc((size_t)sz + 1);
122 if (!b) { fclose(f); return -1; }
123 rd = fread(b, 1, (size_t)sz, f);
124 fclose(f);
125 b[rd] = '\0';
126 if (buf) *buf = b; else free(b);
127 if (len) *len = rd;
128 return 0;
129}
130
131int sx_ntfy_write_file_atomic(const char *path, const void *data, size_t len,
132 int mode600)
133{
134 char tmp[1200];
135 FILE *f;
136 int rc;
137
138 snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long)
139#if defined(_WIN32)
140 GetCurrentProcessId()
141#else
142 (long)getpid()
143#endif
144 );
145 f = fopen(tmp, "wb");
146 if (!f) return -1;
147 if (len && fwrite(data, 1, len, f) != len) {
148 fclose(f);
149 remove(tmp);
150 return -1;
151 }
152 fflush(f);
153#if !defined(_WIN32)
154 fsync(fileno(f));
155#endif
156 fclose(f);
157#if !defined(_WIN32)
158 if (mode600) chmod(tmp, 0600);
159#else
160 (void)mode600;
161#endif
162 remove(path); /* rename over an existing file: EEXIST on Windows */
163 rc = rename(tmp, path);
164 if (rc != 0) {
165 remove(tmp);
166 return -1;
167 }
168 return 0;
169}
170
171/* ----------------------------------------------------------------- paths */
172
173static void mkdir_p(const char *path)
174{
175 char work[1000];
176 size_t i, n;
177
178 snprintf(work, sizeof work, "%s", path);
179 n = strlen(work);
180 for (i = 1; i < n; i++) {
181 if (work[i] == '/' || work[i] == '\\') {
182 char save = work[i];
183 work[i] = '\0';
184 if (work[0]) sx_mkdir(work);
185 work[i] = save;
186 }
187 }
188 sx_mkdir(work);
189}
190
191int sx_ntfy_dir(char *out, size_t capsz)
192{
193 const char *v = getenv("SX_CONNECTORS_DIR");
194
195 out[0] = '\0';
196 if (v && *v) {
197 /* Explicit override (the test suite and any operator who wants the
198 * state elsewhere). Only the directory itself is taken from the
199 * environment; the plugin name is appended by us so one override
200 * cannot point the plugin at somebody else's state. */
201 size_t l;
202 snprintf(out, capsz, "%s", v);
203 l = strlen(out);
204 while (l > 0 && (out[l - 1] == '/' || out[l - 1] == '\\')) out[--l] = '\0';
205 if (l == 0 || strlen(out) + 24 >= capsz) { out[0] = '\0'; return -1; }
206 strncat(out, sx_sep == '\\' ? "\\plugin_ntfy" : "/plugin_ntfy",
207 capsz - strlen(out) - 1);
208 }
209#if defined(_WIN32)
210 else {
211 char base[600];
212 const char *la = getenv("LOCALAPPDATA");
213 const char *up = getenv("USERPROFILE");
214 snprintf(base, sizeof base, "%s", (la && *la) ? la : ((up && *up) ? up : "C:\\Users\\Default"));
215 snprintf(out, capsz, "%s\\scorpiox\\connectors\\plugin_ntfy", base);
216 }
217#else
218 else {
219 struct stat st;
220 if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode))
221 snprintf(out, capsz, "%s", "/workspace/.scorpiox/connectors/plugin_ntfy");
222 else {
223 const char *home = getenv("HOME");
224 if (!home || !*home) {
225 struct passwd *pw = getpwuid(getuid());
226 home = (pw && pw->pw_dir) ? pw->pw_dir : "/tmp";
227 }
228 snprintf(out, capsz, "%s/.scorpiox/connectors/plugin_ntfy", home);
229 }
230 }
231#endif
232 if (!out[0]) return -1;
233 mkdir_p(out);
234 {
235 char probe[1100];
236 FILE *f;
237 snprintf(probe, sizeof probe, "%s%c.sxwritable", out, sx_sep);
238 f = fopen(probe, "wb");
239 if (!f) return -1; /* exists but not writable */
240 fclose(f);
241 remove(probe);
242 }
243#if !defined(_WIN32)
244 chmod(out, 0700);
245#endif
246 return 0;
247}
248
249int sx_ntfy_path(char *out, size_t capsz, const char *file)
250{
251 char dir[1000];
252 if (sx_ntfy_dir(dir, sizeof dir) != 0) return -1;
253 if (strchr(file, '/') || strchr(file, '\\') || strstr(file, "..")) return -1;
254 snprintf(out, capsz, "%s%c%s", dir, sx_sep, file);
255 return 0;
256}
257
258/* ----------------------------------------------------------------- config */
259
260void sx_ntfy_config_defaults(sx_ntfy_config *c)
261{
262 memset(c, 0, sizeof *c);
263 snprintf(c->server_url, sizeof c->server_url, "%s", "https://ntfy.sh");
264 snprintf(c->bot_api_url, sizeof c->bot_api_url, "%s", "http://127.0.0.1:8150");
265 snprintf(c->title_prefix, sizeof c->title_prefix, "%s", "SCORPIOX BOT");
266 c->priority = 3;
267 c->markdown = 0;
268 c->allow_all = 0;
269 c->pairing_code_enabled = 1;
270 c->reply_poll_ms = 700;
271 c->idle_timeout_ms = 45000;
272 c->reconnect_min_ms = 1000;
273 c->reconnect_max_ms = 60000;
274}
275
276static void cp_str(char *dst, size_t capsz, const char *src)
277{
278 if (!src) return;
279 snprintf(dst, capsz, "%s", src);
280}
281
282static int env_int(const char *k, int dflt)
283{
284 const char *v = getenv(k);
285 if (!v || !*v) return dflt;
286 if (!strcmp(v, "1") || !strcasecmp(v, "true") || !strcasecmp(v, "yes") ||
287 !strcasecmp(v, "on")) return 1;
288 if (!strcmp(v, "0") || !strcasecmp(v, "false") || !strcasecmp(v, "no") ||
289 !strcasecmp(v, "off")) return 0;
290 return dflt;
291}
292
293static long long env_ll(const char *k, long long dflt)
294{
295 const char *v = getenv(k);
296 if (!v || !*v) return dflt;
297 return strtoll(v, NULL, 10);
298}
299
300int sx_ntfy_tls_insecure(void)
301{
302 return env_int("NTFY_TLS_INSECURE", 0);
303}
304
305static void apply_env(sx_ntfy_config *c)
306{
307 struct { const char *env, *cfg; size_t cap; } strs[] = {
308 { "NTFY_SERVER_URL", c->server_url, sizeof c->server_url },
309 { "NTFY_TOPIC", c->topic, sizeof c->topic },
310 { "NTFY_PUBLISH_TOPIC",c->publish_topic,sizeof c->publish_topic },
311 { "NTFY_TOKEN", c->bearer_token, sizeof c->bearer_token },
312 { "NTFY_TARGET_SESSION", c->target_session, sizeof c->target_session },
313 { "NTFY_BOT_API_URL", c->bot_api_url, sizeof c->bot_api_url },
314 { "BOT_PASSWORD", c->bot_password, sizeof c->bot_password },
315 { "NTFY_TAGS", c->tags, sizeof c->tags },
316 { "NTFY_REPLY_PREFIX", c->reply_prefix, sizeof c->reply_prefix },
317 { "NTFY_TITLE_PREFIX", c->title_prefix, sizeof c->title_prefix },
318 { "NTFY_CA_FILE", c->ca_file, sizeof c->ca_file },
319 { "NTFY_TLS_PIN", c->allowed_pins, sizeof c->allowed_pins },
320 { (const char *)0, (const char *)0, 0 }
321 };
322 int i;
323 for (i = 0; strs[i].env; i++) {
324 const char *v = getenv(strs[i].env);
325 if (v && *v) cp_str((char *)strs[i].cfg, strs[i].cap, v);
326 }
327 c->markdown = env_int("NTFY_MARKDOWN", c->markdown);
328 c->allow_all = env_int("NTFY_ALLOW_ALL", c->allow_all);
329 c->pairing_code_enabled = env_int("NTFY_PAIRING_CODE", c->pairing_code_enabled);
330 {
331 const char *p = getenv("NTFY_PRIORITY");
332 if (p && *p) { int v = atoi(p); if (v >= 1 && v <= 5) c->priority = v; }
333 }
334 c->reply_poll_ms = env_ll("NTFY_REPLY_POLL_MS", c->reply_poll_ms);
335 c->idle_timeout_ms = env_ll("NTFY_IDLE_TIMEOUT_MS", c->idle_timeout_ms);
336 c->reconnect_min_ms = env_ll("NTFY_RECONNECT_MIN_MS", c->reconnect_min_ms);
337 c->reconnect_max_ms = env_ll("NTFY_RECONNECT_MAX_MS", c->reconnect_max_ms);
338 if (c->reply_poll_ms < 100) c->reply_poll_ms = 100;
339 if (c->reply_poll_ms > 60000) c->reply_poll_ms = 60000;
340 if (c->idle_timeout_ms < 2000) c->idle_timeout_ms = 2000;
341 if (c->idle_timeout_ms > 300000) c->idle_timeout_ms = 300000;
342 if (c->reconnect_min_ms < 200) c->reconnect_min_ms = 200;
343 if (c->reconnect_max_ms < c->reconnect_min_ms)
344 c->reconnect_max_ms = c->reconnect_min_ms * 2;
345 if (c->reconnect_max_ms > 600000) c->reconnect_max_ms = 600000;
346}
347
348int sx_ntfy_config_load(sx_ntfy_config *c, char *err, size_t errsz)
349{
350 char path[1100];
351 char *buf = NULL;
352 size_t len = 0;
353 yyjson_doc *doc;
354 yyjson_val *root;
355
356 sx_ntfy_config_defaults(c);
357 if (sx_ntfy_path(path, sizeof path, "config.json") != 0) {
358 apply_env(c);
359 return 0; /* no home yet: env-only config */
360 }
361 if (sx_ntfy_read_file(path, &buf, &len) == 0 && buf && len) {
362 doc = yyjson_read(buf, len, 0);
363 if (!doc) {
364 set_err(err, errsz, "config.json is not valid JSON");
365 free(buf);
366 apply_env(c);
367 return -1;
368 }
369 root = yyjson_doc_get_root(doc);
370 if (yyjson_is_obj(root)) {
371 yyjson_val *v;
372#define GETSTR(key, field) do { v = yyjson_obj_get(root, key); \
373 if (yyjson_is_str(v)) cp_str(c->field, sizeof c->field, yyjson_get_str(v)); } while (0)
374 GETSTR("server_url", server_url);
375 GETSTR("topic", topic);
376 GETSTR("publish_topic", publish_topic);
377 GETSTR("bearer_token", bearer_token);
378 GETSTR("ca_file", ca_file);
379 GETSTR("allowed_pins", allowed_pins);
380 GETSTR("bot_api_url", bot_api_url);
381 GETSTR("bot_password", bot_password);
382 GETSTR("target_session", target_session);
383 GETSTR("tags", tags);
384 GETSTR("reply_prefix", reply_prefix);
385 GETSTR("title_prefix", title_prefix);
386#undef GETSTR
387 }
388 yyjson_doc_free(doc);
389 free(buf);
390 }
391 apply_env(c);
392 if (!c->publish_topic[0]) cp_str(c->publish_topic, sizeof c->publish_topic, c->topic);
393 if (!c->bot_api_url[0]) cp_str(c->bot_api_url, sizeof c->bot_api_url, "http://127.0.0.1:8150");
394 if (!c->server_url[0]) cp_str(c->server_url, sizeof c->server_url, "https://ntfy.sh");
395 return 0;
396}
397
398int sx_ntfy_config_save(const sx_ntfy_config *c, char *err, size_t errsz)
399{
400 char path[1100];
401 yyjson_mut_doc *doc;
402 yyjson_mut_val *root;
403 char *txt;
404 size_t sz;
405 int rc;
406
407 if (sx_ntfy_path(path, sizeof path, "config.json") != 0) {
408 set_err(err, errsz, "connector state directory is not usable");
409 return -1;
410 }
411 doc = yyjson_mut_doc_new(NULL);
412 root = yyjson_mut_obj(doc);
413 yyjson_mut_doc_set_root(doc, root);
414 yyjson_mut_obj_add_strcpy(doc, root, "server_url", c->server_url);
415 yyjson_mut_obj_add_strcpy(doc, root, "topic", c->topic);
416 yyjson_mut_obj_add_strcpy(doc, root, "publish_topic", c->publish_topic);
417 yyjson_mut_obj_add_strcpy(doc, root, "bearer_token", c->bearer_token);
418 yyjson_mut_obj_add_strcpy(doc, root, "ca_file", c->ca_file);
419 yyjson_mut_obj_add_strcpy(doc, root, "allowed_pins", c->allowed_pins);
420 yyjson_mut_obj_add_strcpy(doc, root, "bot_api_url", c->bot_api_url);
421 yyjson_mut_obj_add_strcpy(doc, root, "bot_password", c->bot_password);
422 yyjson_mut_obj_add_strcpy(doc, root, "target_session", c->target_session);
423 yyjson_mut_obj_add_strcpy(doc, root, "tags", c->tags);
424 yyjson_mut_obj_add_strcpy(doc, root, "reply_prefix", c->reply_prefix);
425 yyjson_mut_obj_add_strcpy(doc, root, "title_prefix", c->title_prefix);
426 yyjson_mut_obj_add_int(doc, root, "priority", c->priority);
427 yyjson_mut_obj_add_int(doc, root, "markdown", c->markdown);
428 yyjson_mut_obj_add_int(doc, root, "allow_all", c->allow_all);
429 yyjson_mut_obj_add_int(doc, root, "pairing_code_enabled", c->pairing_code_enabled);
430 yyjson_mut_obj_add_sint(doc, root, "reply_poll_ms", c->reply_poll_ms);
431 yyjson_mut_obj_add_sint(doc, root, "idle_timeout_ms", c->idle_timeout_ms);
432 yyjson_mut_obj_add_sint(doc, root, "reconnect_min_ms", c->reconnect_min_ms);
433 yyjson_mut_obj_add_sint(doc, root, "reconnect_max_ms", c->reconnect_max_ms);
434 yyjson_mut_obj_add_sint(doc, root, "updated_at", (long long)time(NULL));
435 txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz);
436 yyjson_mut_doc_free(doc);
437 if (!txt) { set_err(err, errsz, "cannot serialise config"); return -1; }
438 rc = sx_ntfy_write_file_atomic(path, txt, sz, 1);
439 free(txt);
440 if (rc != 0) { set_err(err, errsz, "cannot write config.json"); return -1; }
441 return 0;
442}
443
444static int valid_topic_name(const char *t)
445{
446 size_t n = strlen(t), i;
447 if (n == 0 || n > 128) return 0;
448 for (i = 0; i < n; i++) {
449 char c = t[i];
450 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
451 (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.'))
452 return 0;
453 }
454 return 1;
455}
456
457int sx_ntfy_config_validate(const sx_ntfy_config *c, char *err, size_t errsz)
458{
459 sx_url u;
460 if (!c->topic[0]) { set_err(err, errsz, "topic is required"); return -1; }
461 if (!valid_topic_name(c->topic)) { set_err(err, errsz, "topic contains forbidden characters"); return -1; }
462 if (c->publish_topic[0] && !valid_topic_name(c->publish_topic)) {
463 set_err(err, errsz, "publish_topic contains forbidden characters");
464 return -1;
465 }
466 if (sx_url_parse(c->server_url, &u, err, errsz) != 0) return -1;
467 if (!u.tls && !sx_ntfy_tls_insecure()) {
468 /* Plain http to a non-loopback host would put the bearer token on the
469 * wire in clear text. Refuse it; a loopback mock in the test suite is
470 * fine, and an operator who really wants cleartext sets the env. */
471 if (strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost") &&
472 strcmp(u.host, "::1")) {
473 set_err(err, errsz, "plain http:// is refused for a non-loopback server (a bearer token would travel in the clear)");
474 return -1;
475 }
476 }
477 if (sx_url_parse(c->bot_api_url, &u, err, errsz) != 0) return -1;
478 if (u.tls) {
479 set_err(err, errsz, "bot_api_url must be plain http: the node API is loopback-only");
480 return -1;
481 }
482 if (strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost")) {
483 set_err(err, errsz, "bot_api_url must point at 127.0.0.1 or localhost");
484 return -1;
485 }
486 if (!c->target_session[0]) {
487 set_err(err, errsz, "target_session is required before the daemon can route messages");
488 return -1;
489 }
490 {
491 size_t i, n = strlen(c->target_session);
492 for (i = 0; i < n; i++) {
493 char ch = c->target_session[i];
494 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
495 (ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '.' ||
496 ch == ':')) {
497 set_err(err, errsz, "target_session contains forbidden characters");
498 return -1;
499 }
500 }
501 }
502 return 0;
503}
504
505/* ------------------------------------------------------------ pairing io */
506
507static int load_array(const char *file, yyjson_doc **doc_out, char **buf_out)
508{
509 char path[1100];
510 char *buf = NULL;
511 size_t len = 0;
512
513 if (sx_ntfy_path(path, sizeof path, file) != 0) return -1;
514 if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf || !len) { free(buf); return -1; }
515 *doc_out = yyjson_read(buf, len, 0);
516 if (!*doc_out) { free(buf); return -1; }
517 if (buf_out) *buf_out = buf; else free(buf);
518 return 0;
519}
520
521int sx_ntfy_pending_load(sx_ntfy_pending **out, size_t *n_out)
522{
523 yyjson_doc *doc = NULL;
524 yyjson_val *arr, *item;
525 size_t i, max, n = 0;
526 sx_ntfy_pending *items; /* alias of *out after the calloc below */
527
528 *out = calloc(PENDING_CAP, sizeof **out);
529 /* ALWAYS a real zeroed array: callers pass this pointer straight into
530 * sx_ntfy_pending_touch, which memsets into (*items)[*n]. An empty
531 * queue must never be NULL. (ASan caught exactly this: the first ever
532 * unapproved message wrote through a NULL items pointer and the daemon
533 * segfaulted -- the default-deny gate itself was the crash.) */
534 *n_out = 0;
535 if (!*out) return -1;
536 if (load_array("pending.json", &doc, NULL) != 0) return 0; /* none yet */
537 arr = yyjson_doc_get_root(doc);
538 if (!yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; }
539 items = *out;
540 yyjson_arr_foreach(arr, i, max, item) {
541 yyjson_val *v;
542 if (n >= PENDING_CAP) break;
543 v = yyjson_obj_get(item, "key");
544 if (!yyjson_is_str(v)) continue;
545 snprintf(items[n].key, sizeof items[n].key, "%s", yyjson_get_str(v));
546 v = yyjson_obj_get(item, "label");
547 if (yyjson_is_str(v)) snprintf(items[n].label, sizeof items[n].label, "%s", yyjson_get_str(v));
548 v = yyjson_obj_get(item, "code");
549 if (yyjson_is_str(v)) snprintf(items[n].code, sizeof items[n].code, "%s", yyjson_get_str(v));
550 v = yyjson_obj_get(item, "sample");
551 if (yyjson_is_str(v)) snprintf(items[n].sample, sizeof items[n].sample, "%s", yyjson_get_str(v));
552 v = yyjson_obj_get(item, "first_seen"); if (yyjson_is_int(v)) items[n].first_seen = yyjson_get_sint(v);
553 v = yyjson_obj_get(item, "last_seen"); if (yyjson_is_int(v)) items[n].last_seen = yyjson_get_sint(v);
554 v = yyjson_obj_get(item, "last_challenge_at"); if (yyjson_is_int(v)) items[n].last_challenge_at = yyjson_get_sint(v);
555 v = yyjson_obj_get(item, "count"); if (yyjson_is_int(v)) items[n].count = (int)yyjson_get_int(v);
556 n++;
557 }
558 yyjson_doc_free(doc);
559 *out = items;
560 *n_out = n;
561 return 0;
562}
563
564int sx_ntfy_pending_save(const sx_ntfy_pending *items, size_t n)
565{
566 char path[1100];
567 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
568 yyjson_mut_val *arr = yyjson_mut_arr(doc);
569 size_t i;
570 char *txt;
571 size_t sz;
572 int rc;
573
574 yyjson_mut_doc_set_root(doc, arr);
575 for (i = 0; i < n; i++) {
576 yyjson_mut_val *o = yyjson_mut_obj(doc);
577 yyjson_mut_arr_add_val(arr, o);
578 yyjson_mut_obj_add_strcpy(doc, o, "key", items[i].key);
579 yyjson_mut_obj_add_strcpy(doc, o, "label", items[i].label);
580 yyjson_mut_obj_add_strcpy(doc, o, "code", items[i].code);
581 yyjson_mut_obj_add_strcpy(doc, o, "sample", items[i].sample);
582 yyjson_mut_obj_add_sint(doc, o, "first_seen", items[i].first_seen);
583 yyjson_mut_obj_add_sint(doc, o, "last_seen", items[i].last_seen);
584 yyjson_mut_obj_add_sint(doc, o, "last_challenge_at", items[i].last_challenge_at);
585 yyjson_mut_obj_add_int(doc, o, "count", items[i].count);
586 }
587 if (sx_ntfy_path(path, sizeof path, "pending.json") != 0) { yyjson_mut_doc_free(doc); return -1; }
588 txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz);
589 yyjson_mut_doc_free(doc);
590 if (!txt) return -1;
591 rc = sx_ntfy_write_file_atomic(path, txt, sz, 1);
592 free(txt);
593 return rc;
594}
595
596sx_ntfy_pending *sx_ntfy_pending_touch(sx_ntfy_pending **items, size_t *n, size_t *cap,
597 const char *key, const char *label,
598 const char *sample)
599{
600 size_t i;
601 (void)cap;
602 for (i = 0; i < *n; i++) {
603 if (strcmp((*items)[i].key, key) == 0) {
604 (*items)[i].last_seen = sx_ntfy_now_epoch();
605 (*items)[i].count++;
606 if (label && *label) snprintf((*items)[i].label, sizeof (*items)[i].label, "%s", label);
607 if (sample && *sample && !(*items)[i].sample[0])
608 snprintf((*items)[i].sample, sizeof (*items)[i].sample, "%s", sample);
609 return &(*items)[i];
610 }
611 }
612 if (*n >= PENDING_CAP) return NULL; /* queue full: fail closed */
613 memset(&(*items)[*n], 0, sizeof **items);
614 snprintf((*items)[*n].key, sizeof (*items)[*n].key, "%s", key);
615 if (label) snprintf((*items)[*n].label, sizeof (*items)[*n].label, "%s", label);
616 if (sample) snprintf((*items)[*n].sample, sizeof (*items)[*n].sample, "%s", sample);
617 (*items)[*n].first_seen = (*items)[*n].last_seen = sx_ntfy_now_epoch();
618 (*items)[*n].count = 1;
619 sx_ntfy_random_code((*items)[*n].code);
620 return &(*items)[(*n)++];
621}
622
623int sx_ntfy_pending_remove(const char *key)
624{
625 sx_ntfy_pending *items = NULL;
626 size_t n = 0, i, o = 0;
627 int rc = 0;
628
629 if (sx_ntfy_pending_load(&items, &n) != 0) return -1;
630 for (i = 0; i < n; i++) if (strcmp(items[i].key, key)) items[o++] = items[i];
631 if (o != n) rc = sx_ntfy_pending_save(items, o);
632 free(items);
633 return rc;
634}
635
636int sx_ntfy_pending_find_code(const char *code_upper, char *key_out, size_t capsz)
637{
638 sx_ntfy_pending *items = NULL;
639 size_t n = 0, i;
640 int found = 0;
641
642 if (!code_upper || !*code_upper) return 0;
643 if (sx_ntfy_pending_load(&items, &n) != 0) return 0;
644 for (i = 0; i < n; i++) {
645 if (items[i].code[0] && !strcasecmp(items[i].code, code_upper)) {
646 snprintf(key_out, capsz, "%s", items[i].key);
647 found = 1;
648 break;
649 }
650 }
651 free(items);
652 return found;
653}
654
655int sx_ntfy_approved_load(sx_ntfy_approved **out, size_t *n_out)
656{
657 yyjson_doc *doc = NULL;
658 yyjson_val *arr, *item;
659 size_t i, max, n = 0;
660 sx_ntfy_approved *items;
661
662 *out = calloc(APPROVED_CAP, sizeof **out); /* never NULL, see pending */
663 *n_out = 0;
664 if (!*out) return -1;
665 if (load_array("approved.json", &doc, NULL) != 0) return 0;
666 arr = yyjson_doc_get_root(doc);
667 if (!yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; }
668 items = *out;
669 yyjson_arr_foreach(arr, i, max, item) {
670 yyjson_val *v;
671 if (n >= APPROVED_CAP) break;
672 v = yyjson_obj_get(item, "key");
673 if (!yyjson_is_str(v)) continue;
674 snprintf(items[n].key, sizeof items[n].key, "%s", yyjson_get_str(v));
675 v = yyjson_obj_get(item, "label");
676 if (yyjson_is_str(v)) snprintf(items[n].label, sizeof items[n].label, "%s", yyjson_get_str(v));
677 v = yyjson_obj_get(item, "added_at"); if (yyjson_is_int(v)) items[n].added_at = yyjson_get_sint(v);
678 v = yyjson_obj_get(item, "last_seen"); if (yyjson_is_int(v)) items[n].last_seen = yyjson_get_sint(v);
679 v = yyjson_obj_get(item, "count"); if (yyjson_is_int(v)) items[n].count = (int)yyjson_get_int(v);
680 v = yyjson_obj_get(item, "via"); if (yyjson_is_int(v)) items[n].via = (int)yyjson_get_int(v);
681 n++;
682 }
683 yyjson_doc_free(doc);
684 *out = items;
685 *n_out = n;
686 return 0;
687}
688
689int sx_ntfy_approved_save(const sx_ntfy_approved *items, size_t n)
690{
691 char path[1100];
692 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
693 yyjson_mut_val *arr = yyjson_mut_arr(doc);
694 size_t i;
695 char *txt;
696 size_t sz;
697 int rc;
698
699 yyjson_mut_doc_set_root(doc, arr);
700 for (i = 0; i < n; i++) {
701 yyjson_mut_val *o = yyjson_mut_obj(doc);
702 yyjson_mut_arr_add_val(arr, o);
703 yyjson_mut_obj_add_strcpy(doc, o, "key", items[i].key);
704 yyjson_mut_obj_add_strcpy(doc, o, "label", items[i].label);
705 yyjson_mut_obj_add_sint(doc, o, "added_at", items[i].added_at);
706 yyjson_mut_obj_add_sint(doc, o, "last_seen", items[i].last_seen);
707 yyjson_mut_obj_add_int(doc, o, "count", items[i].count);
708 yyjson_mut_obj_add_int(doc, o, "via", items[i].via);
709 }
710 if (sx_ntfy_path(path, sizeof path, "approved.json") != 0) { yyjson_mut_doc_free(doc); return -1; }
711 txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz);
712 yyjson_mut_doc_free(doc);
713 if (!txt) return -1;
714 rc = sx_ntfy_write_file_atomic(path, txt, sz, 1);
715 free(txt);
716 return rc;
717}
718
719int sx_ntfy_approved_has(const char *key)
720{
721 sx_ntfy_approved *items = NULL;
722 size_t n = 0, i;
723 int found = 0;
724 if (!key || !*key) return 0;
725 if (sx_ntfy_approved_load(&items, &n) != 0) return 0;
726 for (i = 0; i < n; i++) if (!strcmp(items[i].key, key)) { found = 1; break; }
727 free(items);
728 return found;
729}
730
731int sx_ntfy_approved_add(const char *key, const char *label, int via)
732{
733 sx_ntfy_approved *items = NULL;
734 size_t n = 0, i;
735 int rc;
736
737 if (sx_ntfy_approved_load(&items, &n) != 0) return -1;
738 for (i = 0; i < n; i++) {
739 if (!strcmp(items[i].key, key)) {
740 int rc;
741 if (label && *label) snprintf(items[i].label, sizeof items[i].label, "%s", label);
742 items[i].via = via;
743 rc = sx_ntfy_approved_save(items, n);
744 free(items);
745 return rc;
746 }
747 }
748 if (n >= APPROVED_CAP) { free(items); return -1; }
749 memset(&items[n], 0, sizeof items[n]);
750 snprintf(items[n].key, sizeof items[n].key, "%s", key);
751 if (label) snprintf(items[n].label, sizeof items[n].label, "%s", label);
752 items[n].added_at = items[n].last_seen = sx_ntfy_now_epoch();
753 items[n].via = via;
754 rc = sx_ntfy_approved_save(items, n + 1);
755 free(items);
756 return rc;
757}
758
759int sx_ntfy_approved_remove(const char *key)
760{
761 sx_ntfy_approved *items = NULL;
762 size_t n = 0, i, o = 0;
763 int rc = 0;
764
765 if (sx_ntfy_approved_load(&items, &n) != 0) return -1;
766 for (i = 0; i < n; i++) if (strcmp(items[i].key, key)) items[o++] = items[i];
767 if (o != n) rc = sx_ntfy_approved_save(items, o);
768 free(items);
769 return rc;
770}
771
772int sx_ntfy_approved_touch_seen(const char *key)
773{
774 sx_ntfy_approved *items = NULL;
775 size_t n = 0, i;
776 int hit = 0;
777
778 if (sx_ntfy_approved_load(&items, &n) != 0) return -1;
779 for (i = 0; i < n; i++)
780 if (!strcmp(items[i].key, key)) { items[i].last_seen = sx_ntfy_now_epoch(); items[i].count++; hit = 1; break; }
781 if (hit) sx_ntfy_approved_save(items, n);
782 free(items);
783 return hit;
784}
785
786/* ------------------------------------------------------ self-echo ledger */
787
788static int sent_load_ids(char ids[][40], size_t cap)
789{
790 yyjson_doc *doc = NULL;
791 yyjson_val *arr, *item;
792 size_t i, max, n = 0;
793
794 if (load_array("sent.json", &doc, NULL) != 0) return 0;
795 arr = yyjson_doc_get_root(doc);
796 if (yyjson_is_arr(arr)) {
797 yyjson_arr_foreach(arr, i, max, item) {
798 if (n >= cap) break;
799 if (yyjson_is_str(item)) {
800 const char *s = yyjson_get_str(item);
801 if (s && strlen(s) < 40) { snprintf(ids[n], 40, "%s", s); n++; }
802 } else if (yyjson_is_obj(item)) {
803 yyjson_val *v = yyjson_obj_get(item, "id");
804 if (yyjson_is_str(v)) {
805 const char *s = yyjson_get_str(v);
806 if (s && strlen(s) < 40) { snprintf(ids[n], 40, "%s", s); n++; }
807 }
808 }
809 }
810 }
811 yyjson_doc_free(doc);
812 return (int)n;
813}
814
815int sx_ntfy_sent_note(const char *id)
816{
817 static char ids[SENT_CAP][40];
818 static int loaded = 0;
819 static int head = 0;
820 int n, i;
821 char path[1100];
822 yyjson_mut_doc *doc;
823 yyjson_mut_val *arr;
824 char *txt;
825 size_t sz;
826 int rc;
827
828 if (!id || !*id || strlen(id) >= 40) return -1;
829 if (!loaded) { n = sent_load_ids(ids, SENT_CAP); loaded = 1; head = n % SENT_CAP; }
830 else n = SENT_CAP;
831 for (i = 0; i < n; i++) if (!strcmp(ids[i], id)) return 0; /* already known */
832 snprintf(ids[head], 40, "%s", id);
833 head = (head + 1) % SENT_CAP;
834
835 doc = yyjson_mut_doc_new(NULL);
836 arr = yyjson_mut_arr(doc);
837 yyjson_mut_doc_set_root(doc, arr);
838 for (i = 0; i < n; i++)
839 if (ids[i][0]) yyjson_mut_arr_add_strcpy(doc, arr, ids[i]);
840 if (sx_ntfy_path(path, sizeof path, "sent.json") != 0) { yyjson_mut_doc_free(doc); return -1; }
841 txt = yyjson_mut_write(doc, 0, &sz);
842 yyjson_mut_doc_free(doc);
843 if (!txt) return -1;
844 rc = sx_ntfy_write_file_atomic(path, txt, sz, 1);
845 free(txt);
846 return rc;
847}
848
849int sx_ntfy_sent_has(const char *id)
850{
851 static char ids[SENT_CAP][40];
852 static int loaded = 0, n = 0;
853 int i;
854
855 if (!id || !*id) return 0;
856 if (!loaded) { n = sent_load_ids(ids, SENT_CAP); loaded = 1; }
857 for (i = 0; i < n; i++) if (ids[i][0] && !strcmp(ids[i], id)) return 1;
858 /* also consult the file, in case another process wrote it */
859 {
860 yyjson_doc *doc = NULL;
861 yyjson_val *arr, *item;
862 size_t j, max;
863 int found = 0;
864 if (loaded && n == 0) return 0;
865 if (load_array("sent.json", &doc, NULL) != 0) return 0;
866 arr = yyjson_doc_get_root(doc);
867 if (yyjson_is_arr(arr))
868 yyjson_arr_foreach(arr, j, max, item) {
869 const char *s = yyjson_is_str(item) ? yyjson_get_str(item) : NULL;
870 if (!s && yyjson_is_obj(item)) {
871 yyjson_val *v = yyjson_obj_get(item, "id");
872 s = yyjson_is_str(v) ? yyjson_get_str(v) : NULL;
873 }
874 if (s && !strcmp(s, id)) { found = 1; break; }
875 }
876 yyjson_doc_free(doc);
877 return found;
878 }
879}
880
881/* ----------------------------------------------------- daemon plumbing */
882
883int sx_ntfy_pidfile_write(long pid)
884{
885 char path[1100], buf[32];
886 int n;
887 if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1;
888 n = snprintf(buf, sizeof buf, "%ld\n", pid);
889 return sx_ntfy_write_file_atomic(path, buf, (size_t)n, 0);
890}
891
892int sx_ntfy_pidfile_read(long *pid_out)
893{
894 char path[1100], *buf = NULL;
895 size_t len = 0;
896 long v;
897 char *end;
898
899 if (pid_out) *pid_out = 0;
900 if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1;
901 if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf) return -1;
902 v = strtol(buf, &end, 10);
903 free(buf);
904 if (end == buf || v <= 0) return -1;
905 if (pid_out) *pid_out = v;
906 return 0;
907}
908
909int sx_ntfy_pidfile_remove(void)
910{
911 char path[1100];
912 if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1;
913 remove(path);
914 return 0;
915}
916
917int sx_ntfy_daemon_running(void)
918{
919 long pid = 0;
920 if (sx_ntfy_pidfile_read(&pid) != 0) return 0;
921#if defined(_WIN32)
922 {
923 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
924 FALSE, (DWORD)pid);
925 if (!h) { sx_ntfy_pidfile_remove(); return 0; }
926 {
927 DWORD code = 0;
928 int alive = 1;
929 if (GetExitCodeProcess(h, &code) && code != STILL_ACTIVE) alive = 0;
930 CloseHandle(h);
931 if (!alive) { sx_ntfy_pidfile_remove(); return 0; }
932 }
933 return 1;
934 }
935#else
936 if (kill((pid_t)pid, 0) == 0) return 1;
937 if (errno == EPERM) return 1; /* exists, owned by someone else */
938 sx_ntfy_pidfile_remove(); /* stale pidfile */
939 return 0;
940#endif
941}
942
943int sx_ntfy_log_open(int append)
944{
945 char path[1100];
946 struct stat st;
947
948 if (sx_ntfy_path(path, sizeof path, "daemon.log") != 0) return -1;
949 if (stat(path, &st) == 0 && st.st_size > 1024 * 1024) {
950 char rot[1200];
951 snprintf(rot, sizeof rot, "%s.1", path);
952 remove(rot);
953 rename(path, rot);
954 }
955 {
956 FILE *f = fopen(path, append ? "a" : "w");
957 if (!f) return -1;
958 fclose(f);
959 }
960 return 0;
961}
962
963void sx_ntfy_logf(const char *fmt, ...)
964{
965 char path[1100];
966 FILE *f;
967 va_list ap;
968 char line[1024];
969 va_start(ap, fmt);
970 vsnprintf(line, sizeof line, fmt, ap);
971 va_end(ap);
972 {
973 time_t t = time(NULL);
974 struct tm tmv;
975 char stamp[32];
976#if defined(_WIN32)
977 tmv = *localtime(&t);
978#else
979 localtime_r(&t, &tmv);
980#endif
981 strftime(stamp, sizeof stamp, "%Y-%m-%dT%H:%M:%S", &tmv);
982 fprintf(stderr, "%s plugin_ntfy: %s\n", stamp, line);
983 fflush(stderr);
984 }
985 if (sx_ntfy_path(path, sizeof path, "daemon.log") == 0) {
986 f = fopen(path, "a");
987 if (f) {
988 struct tm tmv;
989 time_t t = time(NULL);
990 char stamp[32];
991#if defined(_WIN32)
992 tmv = *localtime(&t);
993#else
994 localtime_r(&t, &tmv);
995#endif
996 strftime(stamp, sizeof stamp, "%Y-%m-%dT%H:%M:%S", &tmv);
997 fprintf(f, "%s %s\n", stamp, line);
998 fclose(f);
999 }
1000 }
1001}
1002
1003/* ------------------------------------------------------------ status.json */
1004
1005void sx_ntfy_status_defaults(sx_ntfy_status *s)
1006{
1007 memset(s, 0, sizeof *s);
1008}
1009
1010int sx_ntfy_status_load(sx_ntfy_status *s)
1011{
1012 char path[1100], *buf = NULL;
1013 size_t len = 0;
1014 yyjson_doc *doc;
1015 yyjson_val *root;
1016
1017 sx_ntfy_status_defaults(s);
1018 if (sx_ntfy_path(path, sizeof path, "status.json") != 0) return -1;
1019 if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf || !len) { free(buf); return -1; }
1020 doc = yyjson_read(buf, len, 0);
1021 free(buf);
1022 if (!doc) return -1;
1023 root = yyjson_doc_get_root(doc);
1024 if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; }
1025#define S_INT(f) do { yyjson_val *v = yyjson_obj_get(root, #f); if (yyjson_is_int(v)) s->f = yyjson_get_sint(v); } while (0)
1026 S_INT(started_at); S_INT(last_seen_at); S_INT(last_inbound_at);
1027 S_INT(last_outbound_at); S_INT(inbound_count); S_INT(outbound_count);
1028 S_INT(blocked_count); S_INT(pending_count); S_INT(connect_count);
1029 S_INT(error_count); S_INT(connected); S_INT(last_message_time);
1030 S_INT(configured); S_INT(allow_all); S_INT(pairing_code_enabled);
1031 S_INT(markdown); S_INT(has_bearer); S_INT(has_bot_password);
1032 S_INT(tls_insecure); S_INT(pinned);
1033#undef S_INT
1034#define S_STR(f) do { yyjson_val *v = yyjson_obj_get(root, #f); if (yyjson_is_str(v)) snprintf(s->f, sizeof s->f, "%s", yyjson_get_str(v)); } while (0)
1035 S_STR(last_error); S_STR(last_event); S_STR(topic); S_STR(publish_topic);
1036 S_STR(target_session); S_STR(server_url);
1037#undef S_STR
1038 yyjson_doc_free(doc);
1039 return 0;
1040}
1041
1042int sx_ntfy_status_save(const sx_ntfy_status *s)
1043{
1044 char path[1100];
1045 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
1046 yyjson_mut_val *root = yyjson_mut_obj(doc);
1047 char *txt;
1048 size_t sz;
1049 int rc;
1050
1051 yyjson_mut_doc_set_root(doc, root);
1052#define P_INT(f) yyjson_mut_obj_add_sint(doc, root, #f, s->f)
1053 P_INT(started_at); P_INT(last_seen_at); P_INT(last_inbound_at);
1054 P_INT(last_outbound_at); P_INT(inbound_count); P_INT(outbound_count);
1055 P_INT(blocked_count); P_INT(pending_count); P_INT(connect_count);
1056 P_INT(error_count); P_INT(connected); P_INT(last_message_time);
1057 P_INT(configured); P_INT(allow_all); P_INT(pairing_code_enabled);
1058 P_INT(markdown); P_INT(has_bearer); P_INT(has_bot_password);
1059 P_INT(tls_insecure); P_INT(pinned);
1060#undef P_INT
1061#define P_STR(f) yyjson_mut_obj_add_strcpy(doc, root, #f, s->f)
1062 P_STR(last_error); P_STR(last_event); P_STR(topic); P_STR(publish_topic);
1063 P_STR(target_session); P_STR(server_url);
1064#undef P_STR
1065 if (sx_ntfy_path(path, sizeof path, "status.json") != 0) { yyjson_mut_doc_free(doc); return -1; }
1066 txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz);
1067 yyjson_mut_doc_free(doc);
1068 if (!txt) return -1;
1069 rc = sx_ntfy_write_file_atomic(path, txt, sz, 1);
1070 free(txt);
1071 return rc;
1072}
1073
1074/* ---------------------------------------------------------------- random */
1075
1076void sx_ntfy_random_code(char out[SX_NTFY_CODE_LEN + 1])
1077{
1078 /* Unambiguous alphabet: no 0/O, 1/I so a code read off a phone screen
1079 * cannot be mistyped into a permanently-usable pairing token. */
1080 static const char *alpha = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1081 unsigned char rnd[SX_NTFY_CODE_LEN];
1082 int got = 0;
1083 int i;
1084
1085#if defined(_WIN32)
1086 {
1087 HMODULE bc = LoadLibraryA("bcrypt.dll");
1088 if (bc) {
1089 typedef long (WINAPI *bgr)(void *, unsigned char *, unsigned long, unsigned long);
1090 bgr fn = (bgr)GetProcAddress(bc, "BCryptGenRandom");
1091 if (fn && fn(NULL, rnd, sizeof rnd, 1 /* BCRYPT_USE_SYSTEM_PREFERRED_RNG */ ) == 0)
1092 got = 1;
1093 FreeLibrary(bc);
1094 }
1095 }
1096#else
1097 {
1098 int fd = open("/dev/urandom", O_RDONLY);
1099 if (fd >= 0) {
1100 ssize_t rd = read(fd, rnd, sizeof rnd);
1101 close(fd);
1102 if (rd == (ssize_t)sizeof rnd) got = 1;
1103 }
1104 }
1105#endif
1106 if (!got) {
1107 unsigned long long seed = (unsigned long long)sx_ntfy_now_epoch() ^
1108 ((unsigned long long)(size_t)out << 17);
1109 for (i = 0; i < (int)sizeof rnd; i++) {
1110 seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;
1111 rnd[i] = (unsigned char)(seed >> 33);
1112 }
1113 }
1114 for (i = 0; i < SX_NTFY_CODE_LEN; i++)
1115 out[i] = alpha[rnd[i] % 32];
1116 out[SX_NTFY_CODE_LEN] = '\0';
1117}