/* * sx_connectors.c -- persistent state for plugin_ntfy. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0601 # endif # define WIN32_LEAN_AND_MEAN #else # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif # if defined(__APPLE__) # undef _DARWIN_C_SOURCE # define _DARWIN_C_SOURCE 1 # endif #endif #include "sx_connectors.h" #include "sx_http.h" #include #include #include #include #include #include #include #include #if defined(_WIN32) # include # include # define sx_mkdir(p) _mkdir(p) # define sx_sep '\\' #else # include # include # include # include # define sx_mkdir(p) mkdir((p), 0700) # define sx_sep '/' #endif #include "yyjson.h" #define PENDING_CAP 64 #define APPROVED_CAP 256 #define SENT_CAP 512 /* ------------------------------------------------------------------ misc */ long long sx_ntfy_now_epoch(void) { return (long long)time(NULL); } static void set_err(char *err, size_t errsz, const char *fmt, ...) { va_list ap; if (!err || !errsz) return; va_start(ap, fmt); vsnprintf(err, errsz, fmt, ap); va_end(ap); } void sx_ntfy_json_escape(const char *in, char *out, size_t capsz) { static const char *hex = "0123456789abcdef"; size_t o = 0; const unsigned char *p; if (!capsz) return; if (!in) in = ""; for (p = (const unsigned char *)in; *p; p++) { unsigned char c = *p; char tmp[8]; const char *src = tmp; size_t l; switch (c) { case '"': snprintf(tmp, sizeof tmp, "%s", "\\\""); break; case '\\': snprintf(tmp, sizeof tmp, "%s", "\\\\"); break; case '\n': snprintf(tmp, sizeof tmp, "%s", "\\n"); break; case '\r': snprintf(tmp, sizeof tmp, "%s", "\\r"); break; case '\t': snprintf(tmp, sizeof tmp, "%s", "\\t"); break; default: if (c < 0x20) snprintf(tmp, sizeof tmp, "\\u%04x", c); else { tmp[0] = (char)c; tmp[1] = '\0'; } break; } l = strlen(src); if (o + l + 1 > capsz) break; memcpy(out + o, src, l); o += l; } out[o] = '\0'; (void)hex; } int sx_ntfy_read_file(const char *path, char **buf, size_t *len) { FILE *f; long sz; char *b; size_t rd; if (buf) *buf = NULL; if (len) *len = 0; f = fopen(path, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return -1; } b = malloc((size_t)sz + 1); if (!b) { fclose(f); return -1; } rd = fread(b, 1, (size_t)sz, f); fclose(f); b[rd] = '\0'; if (buf) *buf = b; else free(b); if (len) *len = rd; return 0; } int sx_ntfy_write_file_atomic(const char *path, const void *data, size_t len, int mode600) { char tmp[1200]; FILE *f; int rc; snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long) #if defined(_WIN32) GetCurrentProcessId() #else (long)getpid() #endif ); f = fopen(tmp, "wb"); if (!f) return -1; if (len && fwrite(data, 1, len, f) != len) { fclose(f); remove(tmp); return -1; } fflush(f); #if !defined(_WIN32) fsync(fileno(f)); #endif fclose(f); #if !defined(_WIN32) if (mode600) chmod(tmp, 0600); #else (void)mode600; #endif remove(path); /* rename over an existing file: EEXIST on Windows */ rc = rename(tmp, path); if (rc != 0) { remove(tmp); return -1; } return 0; } /* ----------------------------------------------------------------- paths */ static void mkdir_p(const char *path) { char work[1000]; size_t i, n; snprintf(work, sizeof work, "%s", path); n = strlen(work); for (i = 1; i < n; i++) { if (work[i] == '/' || work[i] == '\\') { char save = work[i]; work[i] = '\0'; if (work[0]) sx_mkdir(work); work[i] = save; } } sx_mkdir(work); } int sx_ntfy_dir(char *out, size_t capsz) { const char *v = getenv("SX_CONNECTORS_DIR"); out[0] = '\0'; if (v && *v) { /* Explicit override (the test suite and any operator who wants the * state elsewhere). Only the directory itself is taken from the * environment; the plugin name is appended by us so one override * cannot point the plugin at somebody else's state. */ size_t l; snprintf(out, capsz, "%s", v); l = strlen(out); while (l > 0 && (out[l - 1] == '/' || out[l - 1] == '\\')) out[--l] = '\0'; if (l == 0 || strlen(out) + 24 >= capsz) { out[0] = '\0'; return -1; } strncat(out, sx_sep == '\\' ? "\\plugin_ntfy" : "/plugin_ntfy", capsz - strlen(out) - 1); } #if defined(_WIN32) else { char base[600]; const char *la = getenv("LOCALAPPDATA"); const char *up = getenv("USERPROFILE"); snprintf(base, sizeof base, "%s", (la && *la) ? la : ((up && *up) ? up : "C:\\Users\\Default")); snprintf(out, capsz, "%s\\scorpiox\\connectors\\plugin_ntfy", base); } #else else { struct stat st; if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) snprintf(out, capsz, "%s", "/workspace/.scorpiox/connectors/plugin_ntfy"); else { const char *home = getenv("HOME"); if (!home || !*home) { struct passwd *pw = getpwuid(getuid()); home = (pw && pw->pw_dir) ? pw->pw_dir : "/tmp"; } snprintf(out, capsz, "%s/.scorpiox/connectors/plugin_ntfy", home); } } #endif if (!out[0]) return -1; mkdir_p(out); { char probe[1100]; FILE *f; snprintf(probe, sizeof probe, "%s%c.sxwritable", out, sx_sep); f = fopen(probe, "wb"); if (!f) return -1; /* exists but not writable */ fclose(f); remove(probe); } #if !defined(_WIN32) chmod(out, 0700); #endif return 0; } int sx_ntfy_path(char *out, size_t capsz, const char *file) { char dir[1000]; if (sx_ntfy_dir(dir, sizeof dir) != 0) return -1; if (strchr(file, '/') || strchr(file, '\\') || strstr(file, "..")) return -1; snprintf(out, capsz, "%s%c%s", dir, sx_sep, file); return 0; } /* ----------------------------------------------------------------- config */ void sx_ntfy_config_defaults(sx_ntfy_config *c) { memset(c, 0, sizeof *c); snprintf(c->server_url, sizeof c->server_url, "%s", "https://ntfy.sh"); snprintf(c->bot_api_url, sizeof c->bot_api_url, "%s", "http://127.0.0.1:8150"); snprintf(c->title_prefix, sizeof c->title_prefix, "%s", "SCORPIOX BOT"); c->priority = 3; c->markdown = 0; c->allow_all = 0; c->pairing_code_enabled = 1; c->reply_poll_ms = 700; c->idle_timeout_ms = 45000; c->reconnect_min_ms = 1000; c->reconnect_max_ms = 60000; } static void cp_str(char *dst, size_t capsz, const char *src) { if (!src) return; snprintf(dst, capsz, "%s", src); } static int env_int(const char *k, int dflt) { const char *v = getenv(k); if (!v || !*v) return dflt; if (!strcmp(v, "1") || !strcasecmp(v, "true") || !strcasecmp(v, "yes") || !strcasecmp(v, "on")) return 1; if (!strcmp(v, "0") || !strcasecmp(v, "false") || !strcasecmp(v, "no") || !strcasecmp(v, "off")) return 0; return dflt; } static long long env_ll(const char *k, long long dflt) { const char *v = getenv(k); if (!v || !*v) return dflt; return strtoll(v, NULL, 10); } int sx_ntfy_tls_insecure(void) { return env_int("NTFY_TLS_INSECURE", 0); } static void apply_env(sx_ntfy_config *c) { struct { const char *env, *cfg; size_t cap; } strs[] = { { "NTFY_SERVER_URL", c->server_url, sizeof c->server_url }, { "NTFY_TOPIC", c->topic, sizeof c->topic }, { "NTFY_PUBLISH_TOPIC",c->publish_topic,sizeof c->publish_topic }, { "NTFY_TOKEN", c->bearer_token, sizeof c->bearer_token }, { "NTFY_TARGET_SESSION", c->target_session, sizeof c->target_session }, { "NTFY_BOT_API_URL", c->bot_api_url, sizeof c->bot_api_url }, { "BOT_PASSWORD", c->bot_password, sizeof c->bot_password }, { "NTFY_TAGS", c->tags, sizeof c->tags }, { "NTFY_REPLY_PREFIX", c->reply_prefix, sizeof c->reply_prefix }, { "NTFY_TITLE_PREFIX", c->title_prefix, sizeof c->title_prefix }, { "NTFY_CA_FILE", c->ca_file, sizeof c->ca_file }, { "NTFY_TLS_PIN", c->allowed_pins, sizeof c->allowed_pins }, { (const char *)0, (const char *)0, 0 } }; int i; for (i = 0; strs[i].env; i++) { const char *v = getenv(strs[i].env); if (v && *v) cp_str((char *)strs[i].cfg, strs[i].cap, v); } c->markdown = env_int("NTFY_MARKDOWN", c->markdown); c->allow_all = env_int("NTFY_ALLOW_ALL", c->allow_all); c->pairing_code_enabled = env_int("NTFY_PAIRING_CODE", c->pairing_code_enabled); { const char *p = getenv("NTFY_PRIORITY"); if (p && *p) { int v = atoi(p); if (v >= 1 && v <= 5) c->priority = v; } } c->reply_poll_ms = env_ll("NTFY_REPLY_POLL_MS", c->reply_poll_ms); c->idle_timeout_ms = env_ll("NTFY_IDLE_TIMEOUT_MS", c->idle_timeout_ms); c->reconnect_min_ms = env_ll("NTFY_RECONNECT_MIN_MS", c->reconnect_min_ms); c->reconnect_max_ms = env_ll("NTFY_RECONNECT_MAX_MS", c->reconnect_max_ms); if (c->reply_poll_ms < 100) c->reply_poll_ms = 100; if (c->reply_poll_ms > 60000) c->reply_poll_ms = 60000; if (c->idle_timeout_ms < 2000) c->idle_timeout_ms = 2000; if (c->idle_timeout_ms > 300000) c->idle_timeout_ms = 300000; if (c->reconnect_min_ms < 200) c->reconnect_min_ms = 200; if (c->reconnect_max_ms < c->reconnect_min_ms) c->reconnect_max_ms = c->reconnect_min_ms * 2; if (c->reconnect_max_ms > 600000) c->reconnect_max_ms = 600000; } int sx_ntfy_config_load(sx_ntfy_config *c, char *err, size_t errsz) { char path[1100]; char *buf = NULL; size_t len = 0; yyjson_doc *doc; yyjson_val *root; sx_ntfy_config_defaults(c); if (sx_ntfy_path(path, sizeof path, "config.json") != 0) { apply_env(c); return 0; /* no home yet: env-only config */ } if (sx_ntfy_read_file(path, &buf, &len) == 0 && buf && len) { doc = yyjson_read(buf, len, 0); if (!doc) { set_err(err, errsz, "config.json is not valid JSON"); free(buf); apply_env(c); return -1; } root = yyjson_doc_get_root(doc); if (yyjson_is_obj(root)) { yyjson_val *v; #define GETSTR(key, field) do { v = yyjson_obj_get(root, key); \ if (yyjson_is_str(v)) cp_str(c->field, sizeof c->field, yyjson_get_str(v)); } while (0) GETSTR("server_url", server_url); GETSTR("topic", topic); GETSTR("publish_topic", publish_topic); GETSTR("bearer_token", bearer_token); GETSTR("ca_file", ca_file); GETSTR("allowed_pins", allowed_pins); GETSTR("bot_api_url", bot_api_url); GETSTR("bot_password", bot_password); GETSTR("target_session", target_session); GETSTR("tags", tags); GETSTR("reply_prefix", reply_prefix); GETSTR("title_prefix", title_prefix); #undef GETSTR } yyjson_doc_free(doc); free(buf); } apply_env(c); if (!c->publish_topic[0]) cp_str(c->publish_topic, sizeof c->publish_topic, c->topic); if (!c->bot_api_url[0]) cp_str(c->bot_api_url, sizeof c->bot_api_url, "http://127.0.0.1:8150"); if (!c->server_url[0]) cp_str(c->server_url, sizeof c->server_url, "https://ntfy.sh"); return 0; } int sx_ntfy_config_save(const sx_ntfy_config *c, char *err, size_t errsz) { char path[1100]; yyjson_mut_doc *doc; yyjson_mut_val *root; char *txt; size_t sz; int rc; if (sx_ntfy_path(path, sizeof path, "config.json") != 0) { set_err(err, errsz, "connector state directory is not usable"); return -1; } doc = yyjson_mut_doc_new(NULL); root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); yyjson_mut_obj_add_strcpy(doc, root, "server_url", c->server_url); yyjson_mut_obj_add_strcpy(doc, root, "topic", c->topic); yyjson_mut_obj_add_strcpy(doc, root, "publish_topic", c->publish_topic); yyjson_mut_obj_add_strcpy(doc, root, "bearer_token", c->bearer_token); yyjson_mut_obj_add_strcpy(doc, root, "ca_file", c->ca_file); yyjson_mut_obj_add_strcpy(doc, root, "allowed_pins", c->allowed_pins); yyjson_mut_obj_add_strcpy(doc, root, "bot_api_url", c->bot_api_url); yyjson_mut_obj_add_strcpy(doc, root, "bot_password", c->bot_password); yyjson_mut_obj_add_strcpy(doc, root, "target_session", c->target_session); yyjson_mut_obj_add_strcpy(doc, root, "tags", c->tags); yyjson_mut_obj_add_strcpy(doc, root, "reply_prefix", c->reply_prefix); yyjson_mut_obj_add_strcpy(doc, root, "title_prefix", c->title_prefix); yyjson_mut_obj_add_int(doc, root, "priority", c->priority); yyjson_mut_obj_add_int(doc, root, "markdown", c->markdown); yyjson_mut_obj_add_int(doc, root, "allow_all", c->allow_all); yyjson_mut_obj_add_int(doc, root, "pairing_code_enabled", c->pairing_code_enabled); yyjson_mut_obj_add_sint(doc, root, "reply_poll_ms", c->reply_poll_ms); yyjson_mut_obj_add_sint(doc, root, "idle_timeout_ms", c->idle_timeout_ms); yyjson_mut_obj_add_sint(doc, root, "reconnect_min_ms", c->reconnect_min_ms); yyjson_mut_obj_add_sint(doc, root, "reconnect_max_ms", c->reconnect_max_ms); yyjson_mut_obj_add_sint(doc, root, "updated_at", (long long)time(NULL)); txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz); yyjson_mut_doc_free(doc); if (!txt) { set_err(err, errsz, "cannot serialise config"); return -1; } rc = sx_ntfy_write_file_atomic(path, txt, sz, 1); free(txt); if (rc != 0) { set_err(err, errsz, "cannot write config.json"); return -1; } return 0; } static int valid_topic_name(const char *t) { size_t n = strlen(t), i; if (n == 0 || n > 128) return 0; for (i = 0; i < n; i++) { char c = t[i]; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.')) return 0; } return 1; } int sx_ntfy_config_validate(const sx_ntfy_config *c, char *err, size_t errsz) { sx_url u; if (!c->topic[0]) { set_err(err, errsz, "topic is required"); return -1; } if (!valid_topic_name(c->topic)) { set_err(err, errsz, "topic contains forbidden characters"); return -1; } if (c->publish_topic[0] && !valid_topic_name(c->publish_topic)) { set_err(err, errsz, "publish_topic contains forbidden characters"); return -1; } if (sx_url_parse(c->server_url, &u, err, errsz) != 0) return -1; if (!u.tls && !sx_ntfy_tls_insecure()) { /* Plain http to a non-loopback host would put the bearer token on the * wire in clear text. Refuse it; a loopback mock in the test suite is * fine, and an operator who really wants cleartext sets the env. */ if (strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost") && strcmp(u.host, "::1")) { set_err(err, errsz, "plain http:// is refused for a non-loopback server (a bearer token would travel in the clear)"); return -1; } } if (sx_url_parse(c->bot_api_url, &u, err, errsz) != 0) return -1; if (u.tls) { set_err(err, errsz, "bot_api_url must be plain http: the node API is loopback-only"); return -1; } if (strcmp(u.host, "127.0.0.1") && strcmp(u.host, "localhost")) { set_err(err, errsz, "bot_api_url must point at 127.0.0.1 or localhost"); return -1; } if (!c->target_session[0]) { set_err(err, errsz, "target_session is required before the daemon can route messages"); return -1; } { size_t i, n = strlen(c->target_session); for (i = 0; i < n; i++) { char ch = c->target_session[i]; if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '.' || ch == ':')) { set_err(err, errsz, "target_session contains forbidden characters"); return -1; } } } return 0; } /* ------------------------------------------------------------ pairing io */ static int load_array(const char *file, yyjson_doc **doc_out, char **buf_out) { char path[1100]; char *buf = NULL; size_t len = 0; if (sx_ntfy_path(path, sizeof path, file) != 0) return -1; if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf || !len) { free(buf); return -1; } *doc_out = yyjson_read(buf, len, 0); if (!*doc_out) { free(buf); return -1; } if (buf_out) *buf_out = buf; else free(buf); return 0; } int sx_ntfy_pending_load(sx_ntfy_pending **out, size_t *n_out) { yyjson_doc *doc = NULL; yyjson_val *arr, *item; size_t i, max, n = 0; sx_ntfy_pending *items; /* alias of *out after the calloc below */ *out = calloc(PENDING_CAP, sizeof **out); /* ALWAYS a real zeroed array: callers pass this pointer straight into * sx_ntfy_pending_touch, which memsets into (*items)[*n]. An empty * queue must never be NULL. (ASan caught exactly this: the first ever * unapproved message wrote through a NULL items pointer and the daemon * segfaulted -- the default-deny gate itself was the crash.) */ *n_out = 0; if (!*out) return -1; if (load_array("pending.json", &doc, NULL) != 0) return 0; /* none yet */ arr = yyjson_doc_get_root(doc); if (!yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; } items = *out; yyjson_arr_foreach(arr, i, max, item) { yyjson_val *v; if (n >= PENDING_CAP) break; v = yyjson_obj_get(item, "key"); if (!yyjson_is_str(v)) continue; snprintf(items[n].key, sizeof items[n].key, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "label"); if (yyjson_is_str(v)) snprintf(items[n].label, sizeof items[n].label, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "code"); if (yyjson_is_str(v)) snprintf(items[n].code, sizeof items[n].code, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "sample"); if (yyjson_is_str(v)) snprintf(items[n].sample, sizeof items[n].sample, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "first_seen"); if (yyjson_is_int(v)) items[n].first_seen = yyjson_get_sint(v); v = yyjson_obj_get(item, "last_seen"); if (yyjson_is_int(v)) items[n].last_seen = yyjson_get_sint(v); v = yyjson_obj_get(item, "last_challenge_at"); if (yyjson_is_int(v)) items[n].last_challenge_at = yyjson_get_sint(v); v = yyjson_obj_get(item, "count"); if (yyjson_is_int(v)) items[n].count = (int)yyjson_get_int(v); n++; } yyjson_doc_free(doc); *out = items; *n_out = n; return 0; } int sx_ntfy_pending_save(const sx_ntfy_pending *items, size_t n) { char path[1100]; yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *arr = yyjson_mut_arr(doc); size_t i; char *txt; size_t sz; 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_arr_add_val(arr, o); 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_strcpy(doc, o, "sample", items[i].sample); yyjson_mut_obj_add_sint(doc, o, "first_seen", items[i].first_seen); yyjson_mut_obj_add_sint(doc, o, "last_seen", items[i].last_seen); yyjson_mut_obj_add_sint(doc, o, "last_challenge_at", items[i].last_challenge_at); yyjson_mut_obj_add_int(doc, o, "count", items[i].count); } if (sx_ntfy_path(path, sizeof path, "pending.json") != 0) { yyjson_mut_doc_free(doc); return -1; } txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz); yyjson_mut_doc_free(doc); if (!txt) return -1; rc = sx_ntfy_write_file_atomic(path, txt, sz, 1); free(txt); return rc; } sx_ntfy_pending *sx_ntfy_pending_touch(sx_ntfy_pending **items, size_t *n, size_t *cap, const char *key, const char *label, const char *sample) { size_t i; (void)cap; for (i = 0; i < *n; i++) { if (strcmp((*items)[i].key, key) == 0) { (*items)[i].last_seen = sx_ntfy_now_epoch(); (*items)[i].count++; if (label && *label) snprintf((*items)[i].label, sizeof (*items)[i].label, "%s", label); if (sample && *sample && !(*items)[i].sample[0]) snprintf((*items)[i].sample, sizeof (*items)[i].sample, "%s", sample); return &(*items)[i]; } } if (*n >= PENDING_CAP) return NULL; /* queue full: fail closed */ memset(&(*items)[*n], 0, sizeof **items); snprintf((*items)[*n].key, sizeof (*items)[*n].key, "%s", key); if (label) snprintf((*items)[*n].label, sizeof (*items)[*n].label, "%s", label); if (sample) snprintf((*items)[*n].sample, sizeof (*items)[*n].sample, "%s", sample); (*items)[*n].first_seen = (*items)[*n].last_seen = sx_ntfy_now_epoch(); (*items)[*n].count = 1; sx_ntfy_random_code((*items)[*n].code); return &(*items)[(*n)++]; } int sx_ntfy_pending_remove(const char *key) { sx_ntfy_pending *items = NULL; size_t n = 0, i, o = 0; int rc = 0; if (sx_ntfy_pending_load(&items, &n) != 0) return -1; for (i = 0; i < n; i++) if (strcmp(items[i].key, key)) items[o++] = items[i]; if (o != n) rc = sx_ntfy_pending_save(items, o); free(items); return rc; } int sx_ntfy_pending_find_code(const char *code_upper, char *key_out, size_t capsz) { sx_ntfy_pending *items = NULL; size_t n = 0, i; int found = 0; if (!code_upper || !*code_upper) return 0; if (sx_ntfy_pending_load(&items, &n) != 0) return 0; for (i = 0; i < n; i++) { if (items[i].code[0] && !strcasecmp(items[i].code, code_upper)) { snprintf(key_out, capsz, "%s", items[i].key); found = 1; break; } } free(items); return found; } int sx_ntfy_approved_load(sx_ntfy_approved **out, size_t *n_out) { yyjson_doc *doc = NULL; yyjson_val *arr, *item; size_t i, max, n = 0; sx_ntfy_approved *items; *out = calloc(APPROVED_CAP, sizeof **out); /* never NULL, see pending */ *n_out = 0; if (!*out) return -1; if (load_array("approved.json", &doc, NULL) != 0) return 0; arr = yyjson_doc_get_root(doc); if (!yyjson_is_arr(arr)) { yyjson_doc_free(doc); return 0; } items = *out; yyjson_arr_foreach(arr, i, max, item) { yyjson_val *v; if (n >= APPROVED_CAP) break; v = yyjson_obj_get(item, "key"); if (!yyjson_is_str(v)) continue; snprintf(items[n].key, sizeof items[n].key, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "label"); if (yyjson_is_str(v)) snprintf(items[n].label, sizeof items[n].label, "%s", yyjson_get_str(v)); v = yyjson_obj_get(item, "added_at"); if (yyjson_is_int(v)) items[n].added_at = yyjson_get_sint(v); v = yyjson_obj_get(item, "last_seen"); if (yyjson_is_int(v)) items[n].last_seen = yyjson_get_sint(v); v = yyjson_obj_get(item, "count"); if (yyjson_is_int(v)) items[n].count = (int)yyjson_get_int(v); v = yyjson_obj_get(item, "via"); if (yyjson_is_int(v)) items[n].via = (int)yyjson_get_int(v); n++; } yyjson_doc_free(doc); *out = items; *n_out = n; return 0; } int sx_ntfy_approved_save(const sx_ntfy_approved *items, size_t n) { char path[1100]; yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *arr = yyjson_mut_arr(doc); size_t i; char *txt; size_t sz; 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_arr_add_val(arr, o); 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_sint(doc, o, "added_at", items[i].added_at); yyjson_mut_obj_add_sint(doc, o, "last_seen", items[i].last_seen); yyjson_mut_obj_add_int(doc, o, "count", items[i].count); yyjson_mut_obj_add_int(doc, o, "via", items[i].via); } if (sx_ntfy_path(path, sizeof path, "approved.json") != 0) { yyjson_mut_doc_free(doc); return -1; } txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz); yyjson_mut_doc_free(doc); if (!txt) return -1; rc = sx_ntfy_write_file_atomic(path, txt, sz, 1); free(txt); return rc; } int sx_ntfy_approved_has(const char *key) { sx_ntfy_approved *items = NULL; size_t n = 0, i; int found = 0; if (!key || !*key) return 0; if (sx_ntfy_approved_load(&items, &n) != 0) return 0; for (i = 0; i < n; i++) if (!strcmp(items[i].key, key)) { found = 1; break; } free(items); return found; } int sx_ntfy_approved_add(const char *key, const char *label, int via) { sx_ntfy_approved *items = NULL; size_t n = 0, i; int rc; if (sx_ntfy_approved_load(&items, &n) != 0) return -1; for (i = 0; i < n; i++) { if (!strcmp(items[i].key, key)) { int rc; if (label && *label) snprintf(items[i].label, sizeof items[i].label, "%s", label); items[i].via = via; rc = sx_ntfy_approved_save(items, n); free(items); return rc; } } if (n >= APPROVED_CAP) { free(items); return -1; } memset(&items[n], 0, sizeof items[n]); snprintf(items[n].key, sizeof items[n].key, "%s", key); if (label) snprintf(items[n].label, sizeof items[n].label, "%s", label); items[n].added_at = items[n].last_seen = sx_ntfy_now_epoch(); items[n].via = via; rc = sx_ntfy_approved_save(items, n + 1); free(items); return rc; } int sx_ntfy_approved_remove(const char *key) { sx_ntfy_approved *items = NULL; size_t n = 0, i, o = 0; int rc = 0; if (sx_ntfy_approved_load(&items, &n) != 0) return -1; for (i = 0; i < n; i++) if (strcmp(items[i].key, key)) items[o++] = items[i]; if (o != n) rc = sx_ntfy_approved_save(items, o); free(items); return rc; } int sx_ntfy_approved_touch_seen(const char *key) { sx_ntfy_approved *items = NULL; size_t n = 0, i; int hit = 0; if (sx_ntfy_approved_load(&items, &n) != 0) return -1; for (i = 0; i < n; i++) if (!strcmp(items[i].key, key)) { items[i].last_seen = sx_ntfy_now_epoch(); items[i].count++; hit = 1; break; } if (hit) sx_ntfy_approved_save(items, n); free(items); return hit; } /* ------------------------------------------------------ self-echo ledger */ static int sent_load_ids(char ids[][40], size_t cap) { yyjson_doc *doc = NULL; yyjson_val *arr, *item; size_t i, max, n = 0; if (load_array("sent.json", &doc, NULL) != 0) return 0; arr = yyjson_doc_get_root(doc); if (yyjson_is_arr(arr)) { yyjson_arr_foreach(arr, i, max, item) { if (n >= cap) break; if (yyjson_is_str(item)) { const char *s = yyjson_get_str(item); if (s && strlen(s) < 40) { snprintf(ids[n], 40, "%s", s); n++; } } else if (yyjson_is_obj(item)) { yyjson_val *v = yyjson_obj_get(item, "id"); if (yyjson_is_str(v)) { const char *s = yyjson_get_str(v); if (s && strlen(s) < 40) { snprintf(ids[n], 40, "%s", s); n++; } } } } } yyjson_doc_free(doc); return (int)n; } int sx_ntfy_sent_note(const char *id) { static char ids[SENT_CAP][40]; static int loaded = 0; static int head = 0; int n, i; char path[1100]; yyjson_mut_doc *doc; yyjson_mut_val *arr; char *txt; size_t sz; int rc; if (!id || !*id || strlen(id) >= 40) return -1; if (!loaded) { n = sent_load_ids(ids, SENT_CAP); loaded = 1; head = n % SENT_CAP; } else n = SENT_CAP; for (i = 0; i < n; i++) if (!strcmp(ids[i], id)) return 0; /* already known */ snprintf(ids[head], 40, "%s", id); head = (head + 1) % SENT_CAP; doc = yyjson_mut_doc_new(NULL); arr = yyjson_mut_arr(doc); yyjson_mut_doc_set_root(doc, arr); for (i = 0; i < n; i++) if (ids[i][0]) yyjson_mut_arr_add_strcpy(doc, arr, ids[i]); if (sx_ntfy_path(path, sizeof path, "sent.json") != 0) { yyjson_mut_doc_free(doc); return -1; } txt = yyjson_mut_write(doc, 0, &sz); yyjson_mut_doc_free(doc); if (!txt) return -1; rc = sx_ntfy_write_file_atomic(path, txt, sz, 1); free(txt); return rc; } int sx_ntfy_sent_has(const char *id) { static char ids[SENT_CAP][40]; static int loaded = 0, n = 0; int i; if (!id || !*id) return 0; if (!loaded) { n = sent_load_ids(ids, SENT_CAP); loaded = 1; } for (i = 0; i < n; i++) if (ids[i][0] && !strcmp(ids[i], id)) return 1; /* also consult the file, in case another process wrote it */ { yyjson_doc *doc = NULL; yyjson_val *arr, *item; size_t j, max; int found = 0; if (loaded && n == 0) return 0; if (load_array("sent.json", &doc, NULL) != 0) return 0; arr = yyjson_doc_get_root(doc); if (yyjson_is_arr(arr)) yyjson_arr_foreach(arr, j, max, item) { const char *s = yyjson_is_str(item) ? yyjson_get_str(item) : NULL; if (!s && yyjson_is_obj(item)) { yyjson_val *v = yyjson_obj_get(item, "id"); s = yyjson_is_str(v) ? yyjson_get_str(v) : NULL; } if (s && !strcmp(s, id)) { found = 1; break; } } yyjson_doc_free(doc); return found; } } /* ----------------------------------------------------- daemon plumbing */ int sx_ntfy_pidfile_write(long pid) { char path[1100], buf[32]; int n; if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1; n = snprintf(buf, sizeof buf, "%ld\n", pid); return sx_ntfy_write_file_atomic(path, buf, (size_t)n, 0); } int sx_ntfy_pidfile_read(long *pid_out) { char path[1100], *buf = NULL; size_t len = 0; long v; char *end; if (pid_out) *pid_out = 0; if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1; if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf) return -1; v = strtol(buf, &end, 10); free(buf); if (end == buf || v <= 0) return -1; if (pid_out) *pid_out = v; return 0; } int sx_ntfy_pidfile_remove(void) { char path[1100]; if (sx_ntfy_path(path, sizeof path, "daemon.pid") != 0) return -1; remove(path); return 0; } int sx_ntfy_daemon_running(void) { long pid = 0; if (sx_ntfy_pidfile_read(&pid) != 0) return 0; #if defined(_WIN32) { HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)pid); if (!h) { sx_ntfy_pidfile_remove(); return 0; } { DWORD code = 0; int alive = 1; if (GetExitCodeProcess(h, &code) && code != STILL_ACTIVE) alive = 0; CloseHandle(h); if (!alive) { sx_ntfy_pidfile_remove(); return 0; } } return 1; } #else if (kill((pid_t)pid, 0) == 0) return 1; if (errno == EPERM) return 1; /* exists, owned by someone else */ sx_ntfy_pidfile_remove(); /* stale pidfile */ return 0; #endif } int sx_ntfy_log_open(int append) { char path[1100]; struct stat st; if (sx_ntfy_path(path, sizeof path, "daemon.log") != 0) return -1; if (stat(path, &st) == 0 && st.st_size > 1024 * 1024) { char rot[1200]; snprintf(rot, sizeof rot, "%s.1", path); remove(rot); rename(path, rot); } { FILE *f = fopen(path, append ? "a" : "w"); if (!f) return -1; fclose(f); } return 0; } void sx_ntfy_logf(const char *fmt, ...) { char path[1100]; FILE *f; va_list ap; char line[1024]; va_start(ap, fmt); vsnprintf(line, sizeof line, fmt, ap); va_end(ap); { time_t t = time(NULL); struct tm tmv; char stamp[32]; #if defined(_WIN32) tmv = *localtime(&t); #else localtime_r(&t, &tmv); #endif strftime(stamp, sizeof stamp, "%Y-%m-%dT%H:%M:%S", &tmv); fprintf(stderr, "%s plugin_ntfy: %s\n", stamp, line); fflush(stderr); } if (sx_ntfy_path(path, sizeof path, "daemon.log") == 0) { f = fopen(path, "a"); if (f) { struct tm tmv; time_t t = time(NULL); char stamp[32]; #if defined(_WIN32) tmv = *localtime(&t); #else localtime_r(&t, &tmv); #endif strftime(stamp, sizeof stamp, "%Y-%m-%dT%H:%M:%S", &tmv); fprintf(f, "%s %s\n", stamp, line); fclose(f); } } } /* ------------------------------------------------------------ status.json */ void sx_ntfy_status_defaults(sx_ntfy_status *s) { memset(s, 0, sizeof *s); } int sx_ntfy_status_load(sx_ntfy_status *s) { char path[1100], *buf = NULL; size_t len = 0; yyjson_doc *doc; yyjson_val *root; sx_ntfy_status_defaults(s); if (sx_ntfy_path(path, sizeof path, "status.json") != 0) return -1; if (sx_ntfy_read_file(path, &buf, &len) != 0 || !buf || !len) { free(buf); return -1; } doc = yyjson_read(buf, len, 0); free(buf); if (!doc) return -1; root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; } #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) S_INT(started_at); S_INT(last_seen_at); S_INT(last_inbound_at); S_INT(last_outbound_at); S_INT(inbound_count); S_INT(outbound_count); S_INT(blocked_count); S_INT(pending_count); S_INT(connect_count); S_INT(error_count); S_INT(connected); S_INT(last_message_time); S_INT(configured); S_INT(allow_all); S_INT(pairing_code_enabled); S_INT(markdown); S_INT(has_bearer); S_INT(has_bot_password); S_INT(tls_insecure); S_INT(pinned); #undef S_INT #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) S_STR(last_error); S_STR(last_event); S_STR(topic); S_STR(publish_topic); S_STR(target_session); S_STR(server_url); #undef S_STR yyjson_doc_free(doc); return 0; } int sx_ntfy_status_save(const sx_ntfy_status *s) { char path[1100]; yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); yyjson_mut_val *root = yyjson_mut_obj(doc); char *txt; size_t sz; int rc; yyjson_mut_doc_set_root(doc, root); #define P_INT(f) yyjson_mut_obj_add_sint(doc, root, #f, s->f) P_INT(started_at); P_INT(last_seen_at); P_INT(last_inbound_at); P_INT(last_outbound_at); P_INT(inbound_count); P_INT(outbound_count); P_INT(blocked_count); P_INT(pending_count); P_INT(connect_count); P_INT(error_count); P_INT(connected); P_INT(last_message_time); P_INT(configured); P_INT(allow_all); P_INT(pairing_code_enabled); P_INT(markdown); P_INT(has_bearer); P_INT(has_bot_password); P_INT(tls_insecure); P_INT(pinned); #undef P_INT #define P_STR(f) yyjson_mut_obj_add_strcpy(doc, root, #f, s->f) P_STR(last_error); P_STR(last_event); P_STR(topic); P_STR(publish_topic); P_STR(target_session); P_STR(server_url); #undef P_STR if (sx_ntfy_path(path, sizeof path, "status.json") != 0) { yyjson_mut_doc_free(doc); return -1; } txt = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY, &sz); yyjson_mut_doc_free(doc); if (!txt) return -1; rc = sx_ntfy_write_file_atomic(path, txt, sz, 1); free(txt); return rc; } /* ---------------------------------------------------------------- random */ void sx_ntfy_random_code(char out[SX_NTFY_CODE_LEN + 1]) { /* Unambiguous alphabet: no 0/O, 1/I so a code read off a phone screen * cannot be mistyped into a permanently-usable pairing token. */ static const char *alpha = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; unsigned char rnd[SX_NTFY_CODE_LEN]; int got = 0; int i; #if defined(_WIN32) { HMODULE bc = LoadLibraryA("bcrypt.dll"); if (bc) { typedef long (WINAPI *bgr)(void *, unsigned char *, unsigned long, unsigned long); bgr fn = (bgr)GetProcAddress(bc, "BCryptGenRandom"); if (fn && fn(NULL, rnd, sizeof rnd, 1 /* BCRYPT_USE_SYSTEM_PREFERRED_RNG */ ) == 0) got = 1; FreeLibrary(bc); } } #else { int fd = open("/dev/urandom", O_RDONLY); if (fd >= 0) { ssize_t rd = read(fd, rnd, sizeof rnd); close(fd); if (rd == (ssize_t)sizeof rnd) got = 1; } } #endif if (!got) { unsigned long long seed = (unsigned long long)sx_ntfy_now_epoch() ^ ((unsigned long long)(size_t)out << 17); for (i = 0; i < (int)sizeof rnd; i++) { seed = seed * 6364136223846793005ULL + 1442695040888963407ULL; rnd[i] = (unsigned char)(seed >> 33); } } for (i = 0; i < SX_NTFY_CODE_LEN; i++) out[i] = alpha[rnd[i] % 32]; out[SX_NTFY_CODE_LEN] = '\0'; }