// SPDX-License-Identifier: GPL-2.0-only // Quagr Encrypted Pager DWM Plugin (quagr.so / xquagr / quagr) // Compatible with Quagr over ntfy HTTP/HTTPS relays (<= 30-byte XOR+SHA256 pages). // Features: // - 3-tab NeoUI keypad client (Receive | Send | Config) // - Separate Rx and Tx credentials, each supporting Passphrase or 64-char Raw Hex Key // - Strict opt-in background receiver daemon (autostarts ONLY when enabled & Rx key set) // - Native Sxmo notification delivery ($SXMO_NOTIFDIR -> notifmonitor sound/dunst) // - Instant Nokia 2720 Flip (nokia-beatles) closed cover full-message alert #include "../sxmo-dwm/dwm_plugin.h" #include "net_tls.h" #include #include #include #include #include namespace { using namespace bananarchy; constexpr size_t kQuagrMaxMsgBytes = 30; constexpr size_t kQuagrKeyBytes = 32; constexpr size_t kQuagrPacketBytes = 36; constexpr size_t kQuagrPacketHexLen = 72; constexpr size_t kMaxHistoryEntries = 200; volatile sig_atomic_t gRunning = 1; void handleSignal(int) { gRunning = 0; } enum class KeyMode { Passphrase = 0, RawHex = 1, }; struct QuagrConfig { bool autostartRx = false; std::string relayUrl = "https://ntfy.sh"; std::string topicId = "quagr-public"; KeyMode rxMode = KeyMode::Passphrase; std::string rxSecret; KeyMode txMode = KeyMode::Passphrase; std::string txSecret; }; struct QuagrEntry { std::string timestamp; std::string text; }; std::string sanitizeSingleLine(std::string_view src) { std::string out; out.reserve(src.size()); for (unsigned char c : src) { if (c == '\r' || c == '\n' || c == '\t' || c == '\0') { out.push_back(' '); } else if (c < 0x20 || c == 0x7f) { out.push_back(' '); } else { out.push_back(static_cast(c)); } } return out; } std::string clampUtf8ToMaxBytes(const std::string& s, size_t maxBytes) { if (s.size() <= maxBytes) { return s; } size_t len = maxBytes; // Walk back from UTF-8 continuation bytes so we never split a codepoint. while (len > 0 && (static_cast(s[len]) & 0xc0) == 0x80) { --len; } return s.substr(0, len); } std::string stripHexFormatting(const std::string& raw) { std::string s; s.reserve(raw.size()); for (unsigned char c : raw) { if (!std::isspace(c)) { s.push_back(static_cast(std::tolower(c))); } } if (s.size() >= 2 && s[0] == '0' && s[1] == 'x') { s.erase(0, 2); } return s; } bool hexDecode(std::string_view hex, uint8_t* out, size_t outLen) { if (hex.size() != outLen * 2) { return false; } for (size_t i = 0; i < outLen; ++i) { int hi = themeHexNibble(hex[i * 2]); int lo = themeHexNibble(hex[i * 2 + 1]); if (hi < 0 || lo < 0) { return false; } out[i] = static_cast((hi << 4) | lo); } return true; } std::string hexEncode(const uint8_t* data, size_t len) { static constexpr char kHex[] = "0123456789abcdef"; std::string out; out.resize(len * 2); for (size_t i = 0; i < len; ++i) { out[i * 2] = kHex[(data[i] >> 4) & 0x0f]; out[i * 2 + 1] = kHex[data[i] & 0x0f]; } return out; } bool quagrSha256(const void* data, size_t len, uint8_t out[32]) { unsigned int outLen = 0; return EVP_Digest(data, len, out, &outLen, EVP_sha256(), nullptr) == 1 && outLen == 32; } void fillRandomBytes(uint8_t* dst, size_t len) { ensureOpenSslInit(); if (RAND_bytes(dst, static_cast(len)) == 1) { return; } int fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC); if (fd >= 0) { size_t got = 0; while (got < len) { ssize_t r = ::read(fd, dst + got, len - got); if (r <= 0) break; got += static_cast(r); } ::close(fd); if (got == len) return; } uint64_t seed = static_cast(nowMs()) ^ (static_cast(::getpid()) << 16); for (size_t i = 0; i < len; ++i) { seed = seed * 6364136223846793005ULL + 1442695040888963407ULL; dst[i] = static_cast((seed >> 24) & 0xff); } } bool quagrDeriveKey(KeyMode mode, const std::string& secret, uint8_t outKey[32]) { if (mode == KeyMode::Passphrase) { if (secret.empty()) { return false; } std::string material = "QUAGR:" + secret; return quagrSha256(material.data(), material.size(), outKey); } std::string clean = stripHexFormatting(secret); return hexDecode(clean, outKey, kQuagrKeyBytes); } std::string quagrKeyFingerprint(KeyMode mode, const std::string& secret) { uint8_t key[kQuagrKeyBytes]; if (!quagrDeriveKey(mode, secret, key)) { return ""; } return hexEncode(key, 4); } bool quagrEncrypt(const std::string& msg, const uint8_t key[32], std::string& outHex72) { uint8_t M[kQuagrMaxMsgBytes]; std::memset(M, 0xff, sizeof(M)); size_t copyLen = std::min(msg.size(), sizeof(M)); if (copyLen > 0) { std::memcpy(M, msg.data(), copyLen); } uint8_t hM[32]; if (!quagrSha256(M, sizeof(M), hM)) { return false; } uint8_t N[4]; fillRandomBytes(N, sizeof(N)); uint8_t nk[4 + kQuagrKeyBytes]; std::memcpy(nk, N, 4); std::memcpy(nk + 4, key, kQuagrKeyBytes); uint8_t mask[32]; if (!quagrSha256(nk, sizeof(nk), mask)) { return false; } uint8_t packet[kQuagrPacketBytes]; std::memcpy(packet, N, 4); for (size_t i = 0; i < kQuagrMaxMsgBytes; ++i) { packet[4 + i] = M[i] ^ mask[i]; } packet[34] = hM[0] ^ mask[30]; packet[35] = hM[1] ^ mask[31]; outHex72 = hexEncode(packet, sizeof(packet)); return true; } bool quagrDecrypt(std::string_view line, const uint8_t key[32], std::string& outMsg) { while (!line.empty() && (line.back() == '\r' || line.back() == '\n' || line.back() == ' ' || line.back() == '\t')) { line.remove_suffix(1); } while (!line.empty() && (line.front() == ' ' || line.front() == '\t')) { line.remove_prefix(1); } if (line.size() != kQuagrPacketHexLen) { return false; } uint8_t raw[kQuagrPacketBytes]; if (!hexDecode(line, raw, sizeof(raw))) { return false; } uint8_t nk[4 + kQuagrKeyBytes]; std::memcpy(nk, raw, 4); std::memcpy(nk + 4, key, kQuagrKeyBytes); uint8_t mask[32]; if (!quagrSha256(nk, sizeof(nk), mask)) { return false; } uint8_t mc[32]; for (size_t i = 0; i < 32; ++i) { mc[i] = raw[4 + i] ^ mask[i]; } uint8_t chk[32]; if (!quagrSha256(mc, kQuagrMaxMsgBytes, chk)) { return false; } if (chk[0] != mc[30] || chk[1] != mc[31]) { return false; } std::string decoded; decoded.reserve(kQuagrMaxMsgBytes); for (size_t i = 0; i < kQuagrMaxMsgBytes; ++i) { if (mc[i] != 0xff) { decoded.push_back(static_cast(mc[i])); } } outMsg = sanitizeSingleLine(decoded); return true; } std::string getQuagrConfigPath() { if (const char* ov = std::getenv("BANANARCHY_QUAGR_CONF"); ov && ov[0]) { return ov; } return getHomeDirPath() + "/.config/sxmo/quagr.conf"; } std::string getQuagrDataDir() { if (const char* ov = std::getenv("BANANARCHY_QUAGR_DATA_DIR"); ov && ov[0]) { return ov; } return getHomeDirPath() + "/.local/share/sxmo/quagr"; } void ensureDirWithMode(const std::string& path, mode_t mode) { if (path.empty()) return; std::string cur; for (size_t i = 0; i < path.size(); ++i) { cur.push_back(path[i]); if (path[i] == '/' || i + 1 == path.size()) { if (cur.size() > 1) { ::mkdir(cur.c_str(), mode); } } } } void ensureParentDirWithMode(const std::string& filePath, mode_t mode) { size_t slash = filePath.rfind('/'); if (slash != std::string::npos && slash > 0) { ensureDirWithMode(filePath.substr(0, slash), mode); } } KeyMode parseKeyMode(const std::string& val) { std::string low = toLowerStr(trimStr(val)); if (low == "hex" || low == "raw" || low == "rawhex" || low == "raw_hex") { return KeyMode::RawHex; } return KeyMode::Passphrase; } std::string formatKeyMode(KeyMode m) { return (m == KeyMode::RawHex) ? "hex" : "pass"; } std::string normalizeRelayUrl(const std::string& raw) { std::string s = trimStr(raw); while (!s.empty() && s.back() == '/') { s.pop_back(); } return s.empty() ? "https://ntfy.sh" : s; } std::string normalizeTopicId(const std::string& raw) { std::string s = trimStr(raw); while (!s.empty() && s.front() == '/') { s.erase(s.begin()); } while (!s.empty() && s.back() == '/') { s.pop_back(); } std::string clean; for (unsigned char c : s) { if (c > 0x20 && c < 0x7f) { clean.push_back(static_cast(c)); } } return clean.empty() ? "quagr-public" : clean; } QuagrConfig loadQuagrConfig() { QuagrConfig cfg; std::ifstream in(getQuagrConfigPath()); if (!in.is_open()) { return cfg; } std::string line; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty() || line[0] == '#') { continue; } size_t eq = line.find('='); if (eq == std::string::npos) { continue; } std::string k = toLowerStr(trimStr(line.substr(0, eq))); std::string v = line.substr(eq + 1); if (k == "autostart_rx" || k == "autostart") { std::string lv = toLowerStr(trimStr(v)); cfg.autostartRx = (lv == "1" || lv == "true" || lv == "yes" || lv == "on"); } else if (k == "relay_url" || k == "base_url") { cfg.relayUrl = normalizeRelayUrl(v); } else if (k == "topic_id" || k == "topic") { cfg.topicId = normalizeTopicId(v); } else if (k == "rx_mode") { cfg.rxMode = parseKeyMode(v); } else if (k == "rx_secret" || k == "rx_key" || k == "rx_passphrase") { cfg.rxSecret = sanitizeSingleLine(v); } else if (k == "tx_mode") { cfg.txMode = parseKeyMode(v); } else if (k == "tx_secret" || k == "tx_key" || k == "tx_passphrase") { cfg.txSecret = sanitizeSingleLine(v); } } cfg.relayUrl = normalizeRelayUrl(cfg.relayUrl); cfg.topicId = normalizeTopicId(cfg.topicId); return cfg; } bool saveQuagrConfig(const QuagrConfig& cfg) { std::string path = getQuagrConfigPath(); ensureParentDirWithMode(path, 0700); std::string tmpPath = path + ".tmp." + std::to_string(::getpid()); int fd = ::open(tmpPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) { return false; } std::ostringstream oss; oss << "autostart_rx=" << (cfg.autostartRx ? "1" : "0") << "\n" << "relay_url=" << normalizeRelayUrl(cfg.relayUrl) << "\n" << "topic_id=" << normalizeTopicId(cfg.topicId) << "\n" << "rx_mode=" << formatKeyMode(cfg.rxMode) << "\n" << "rx_secret=" << sanitizeSingleLine(cfg.rxSecret) << "\n" << "tx_mode=" << formatKeyMode(cfg.txMode) << "\n" << "tx_secret=" << sanitizeSingleLine(cfg.txSecret) << "\n"; std::string data = oss.str(); size_t off = 0; while (off < data.size()) { ssize_t w = ::write(fd, data.data() + off, data.size() - off); if (w < 0) { if (errno == EINTR) continue; ::close(fd); ::unlink(tmpPath.c_str()); return false; } off += static_cast(w); } ::fchmod(fd, 0600); ::close(fd); if (::rename(tmpPath.c_str(), path.c_str()) != 0) { ::unlink(tmpPath.c_str()); return false; } return true; } bool shouldAutostartQuagr(QuagrConfig* outCfg = nullptr) { if (isDuressMode()) { return false; } QuagrConfig cfg = loadQuagrConfig(); if (outCfg) { *outCfg = cfg; } uint8_t dummyKey[kQuagrKeyBytes]; return cfg.autostartRx && quagrDeriveKey(cfg.rxMode, cfg.rxSecret, dummyKey); } std::vector loadHistoryFile(const std::string& path) { std::vector entries; std::ifstream in(path); if (!in.is_open()) { return entries; } std::string line; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) continue; size_t tab = line.find('\t'); QuagrEntry e; if (tab == std::string::npos) { e.timestamp = "--:--"; e.text = line; } else { e.timestamp = line.substr(0, tab); e.text = line.substr(tab + 1); } entries.push_back(std::move(e)); if (entries.size() >= kMaxHistoryEntries) { break; } } return entries; } void saveHistoryFile(const std::string& path, const std::vector& entries) { ensureParentDirWithMode(path, 0700); std::string tmpPath = path + ".tmp." + std::to_string(::getpid()); int fd = ::open(tmpPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) return; std::ostringstream oss; size_t n = std::min(entries.size(), kMaxHistoryEntries); for (size_t i = 0; i < n; ++i) { oss << sanitizeSingleLine(entries[i].timestamp) << "\t" << sanitizeSingleLine(entries[i].text) << "\n"; } std::string data = oss.str(); size_t off = 0; while (off < data.size()) { ssize_t w = ::write(fd, data.data() + off, data.size() - off); if (w < 0) { if (errno == EINTR) continue; break; } off += static_cast(w); } ::fchmod(fd, 0600); ::close(fd); if (::rename(tmpPath.c_str(), path.c_str()) != 0) { ::unlink(tmpPath.c_str()); } } std::string formatNowTimestamp(const char* fmt) { refreshLocalTimezone(); time_t now = ::time(nullptr); struct tm tmNow {}; localtime_r(&now, &tmNow); char buf[32]; std::strftime(buf, sizeof(buf), fmt, &tmNow); return std::string(buf); } std::string resolveNotifDir() { const char* envDir = std::getenv("SXMO_NOTIFDIR"); if (envDir && envDir[0] && std::strcmp(envDir, "/") != 0) { return std::string(envDir); } const char* xdgData = std::getenv("XDG_DATA_HOME"); if (xdgData && xdgData[0]) { return std::string(xdgData) + "/sxmo/notifications"; } return getHomeDirPath() + "/.local/share/sxmo/notifications"; } void writeSxmoQuagrNotification(const std::string& msg) { static unsigned int sSeq = 0; std::string dir = resolveNotifDir(); ensureDirWithMode(dir, 0755); long long ts = static_cast(::time(nullptr)); unsigned int seq = ++sSeq; std::string cleanMsg = sanitizeSingleLine(msg); std::string payload = "quagr\nxquagr\n[Quagr] " + cleanMsg + "\n\n"; std::string tmpPath = dir + "/.quagr_" + std::to_string(ts) + "_" + std::to_string(::getpid()) + "_" + std::to_string(seq) + ".tmp"; std::string dstPath = dir + "/quagr_" + std::to_string(ts) + "_" + std::to_string(::getpid()) + "_" + std::to_string(seq); int fd = ::open(tmpPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) return; size_t off = 0; bool ok = true; while (off < payload.size()) { ssize_t w = ::write(fd, payload.data() + off, payload.size() - off); if (w < 0) { if (errno == EINTR) continue; ok = false; break; } off += static_cast(w); } ::close(fd); if (!ok || ::rename(tmpPath.c_str(), dstPath.c_str()) != 0) { ::unlink(tmpPath.c_str()); } } void clearSxmoQuagrNotifications() { std::string dir = resolveNotifDir(); DIR* dp = ::opendir(dir.c_str()); if (!dp) return; bool removedAny = false; struct dirent* de = nullptr; while ((de = ::readdir(dp)) != nullptr) { if (de->d_name[0] == '.') continue; std::string p = dir + "/" + de->d_name; std::ifstream in(p); std::string firstLine; if (in.is_open() && std::getline(in, firstLine)) { if (!firstLine.empty() && firstLine.back() == '\r') { firstLine.pop_back(); } if (firstLine == "quagr") { ::unlink(p.c_str()); removedAny = true; } } } ::closedir(dp); if (removedAny) { runAsyncCmd("sxmo_hook_statusbar.sh notifications >/dev/null 2>&1"); } } void notifyCoverScreen(const std::string& msg) { const char* coverEnv = std::getenv("BANANARCHY_COVER_SOCKET"); std::string sockPath = (coverEnv && coverEnv[0]) ? coverEnv : "/run/bananarchy/cover.sock"; if (sockPath.size() >= sizeof(sockaddr_un::sun_path)) return; int fd = ::socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (fd < 0) return; struct sockaddr_un remote {}; remote.sun_family = AF_UNIX; std::snprintf(remote.sun_path, sizeof(remote.sun_path), "%s", sockPath.c_str()); std::string payload = "QUAGR " + sanitizeSingleLine(msg) + "\n"; (void)::sendto(fd, payload.data(), payload.size(), MSG_NOSIGNAL, reinterpret_cast(&remote), sizeof(remote)); ::close(fd); } void enableTcpKeepalive(int sockFd) { if (sockFd < 0) return; int one = 1; (void)::setsockopt(sockFd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)); #ifdef TCP_KEEPIDLE int idle = 45; (void)::setsockopt(sockFd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)); #endif #ifdef TCP_KEEPINTVL int intvl = 15; (void)::setsockopt(sockFd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)); #endif #ifdef TCP_KEEPCNT int cnt = 3; (void)::setsockopt(sockFd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); #endif } bool buildQuagrEndpoint(const std::string& relayUrl, const std::string& topicId, bool subscribeRaw, ParsedUrl& outUrl, std::string& outHostHeader) { std::string base = normalizeRelayUrl(relayUrl); outUrl = parseUrl(base, "https"); if ((outUrl.scheme != "http" && outUrl.scheme != "https") || outUrl.host.empty()) { return false; } std::string prefix = outUrl.path; while (!prefix.empty() && prefix.back() == '/') { prefix.pop_back(); } std::string cleanTopic = normalizeTopicId(topicId); outUrl.path = prefix + "/" + cleanTopic + (subscribeRaw ? "/raw" : ""); bool defaultPort = (outUrl.scheme == "https" && outUrl.port == 443) || (outUrl.scheme == "http" && outUrl.port == 80); if (outUrl.host.find(':') != std::string::npos) { outHostHeader = defaultPort ? ("[" + outUrl.host + "]") : ("[" + outUrl.host + "]:" + std::to_string(outUrl.port)); } else { outHostHeader = defaultPort ? outUrl.host : (outUrl.host + ":" + std::to_string(outUrl.port)); } return true; } bool resolveRedirectUrl(const ParsedUrl& cur, const std::string& location, std::string& outNextUrl) { if (location.empty()) return false; if (location.rfind("http://", 0) == 0 || location.rfind("https://", 0) == 0) { outNextUrl = location; return true; } std::string hostPart = (cur.host.find(':') != std::string::npos) ? ("[" + cur.host + "]") : cur.host; bool defaultPort = (cur.scheme == "https" && cur.port == 443) || (cur.scheme == "http" && cur.port == 80); std::string portPart = defaultPort ? "" : (":" + std::to_string(cur.port)); if (location[0] == '/') { outNextUrl = cur.scheme + "://" + hostPart + portPart + location; } else { outNextUrl = cur.scheme + "://" + hostPart + portPart + "/" + location; } return true; } bool httpPostQuagr(const std::string& relayUrl, const std::string& topicId, const std::string& body72, std::string& outErr) { ParsedUrl initialUrl; std::string initialHostHdr; if (!buildQuagrEndpoint(relayUrl, topicId, false, initialUrl, initialHostHdr)) { outErr = "Invalid relay URL"; return false; } std::string currentUrl = initialUrl.scheme + "://" + initialHostHdr + initialUrl.path; for (int hop = 0; hop < 3; ++hop) { ParsedUrl u = parseUrl(currentUrl, "https"); if ((u.scheme != "http" && u.scheme != "https") || u.host.empty()) { outErr = "Invalid URL"; return false; } bool defaultPort = (u.scheme == "https" && u.port == 443) || (u.scheme == "http" && u.port == 80); std::string hostHdr = (u.host.find(':') != std::string::npos) ? ("[" + u.host + "]") : u.host; if (!defaultPort) { hostHdr += ":" + std::to_string(u.port); } NetStream net; if (!net.connectTcp(u.host, u.port, 5000)) { outErr = net.lastError(); return false; } if (u.scheme == "https" && !net.startTls(u.host, 5000)) { outErr = net.lastError(); return false; } std::ostringstream req; req << "POST " << (u.path.empty() ? "/" : u.path) << " HTTP/1.1\r\n" << "Host: " << hostHdr << "\r\n" << "User-Agent: Bananarchy-Quagr/1.0\r\n" << "Content-Type: text/plain\r\n" << "Content-Length: " << body72.size() << "\r\n" << "Connection: close\r\n\r\n" << body72; if (!net.sendStr(req.str(), 5000)) { outErr = net.lastError(); return false; } int64_t deadline = nowMs() + 5000; size_t hdrEnd = std::string::npos; bool eofReached = false; while (nowMs() < deadline) { int r = net.pumpRx(150); const std::string& buf = net.rxBuffer(); hdrEnd = buf.find("\r\n\r\n"); if (hdrEnd != std::string::npos) break; hdrEnd = buf.find("\n\n"); if (hdrEnd != std::string::npos) break; if (r < 0) { eofReached = true; break; } } const std::string& raw = net.rxBuffer(); if (hdrEnd == std::string::npos && !eofReached) { outErr = "Relay timeout"; return false; } std::string hdrs = (hdrEnd != std::string::npos) ? raw.substr(0, hdrEnd) : raw; int statusCode = 0; { std::istringstream hss(hdrs); std::string ver; hss >> ver >> statusCode; } if (statusCode == 301 || statusCode == 302 || statusCode == 307 || statusCode == 308) { std::istringstream lss(hdrs); std::string line; std::string location; while (std::getline(lss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); size_t colon = line.find(':'); if (colon == std::string::npos) continue; if (toLowerStr(trimStr(line.substr(0, colon))) == "location") { location = trimStr(line.substr(colon + 1)); break; } } std::string nextUrl; if (resolveRedirectUrl(u, location, nextUrl)) { currentUrl = nextUrl; continue; } } if (statusCode >= 200 && statusCode < 300) { return true; } outErr = statusCode > 0 ? ("HTTP " + std::to_string(statusCode)) : "Invalid response"; return false; } outErr = "Too many redirects"; return false; } class QuagrRxStream { public: enum class StreamState { Offline = 0, Connecting = 1, Listening = 2, Reconnecting = 3, }; using PageCallback = std::function; StreamState status() const { return status_; } int fd() const { return net_ ? net_->fd() : -1; } bool wantsActive() const { return wantSubscribed_; } const std::string& lastStatusDetail() const { return detail_; } std::string statusBadge() const { switch (status_) { case StreamState::Offline: return "OFFLINE"; case StreamState::Connecting: return "CONNECT"; case StreamState::Listening: return "LISTEN"; case StreamState::Reconnecting: return "RECONN"; } return "OFFLINE"; } void setKey(const uint8_t key[kQuagrKeyBytes], bool valid) { keyValid_ = valid; if (valid) { std::memcpy(key_, key, kQuagrKeyBytes); } else { std::memset(key_, 0, sizeof(key_)); } } void start(const std::string& relayUrl, const std::string& topicId, const uint8_t key[kQuagrKeyBytes], bool keyValid) { stop(); setKey(key, keyValid); if (!keyValid_) { detail_ = "Set Rx key first"; return; } relayUrl_ = normalizeRelayUrl(relayUrl); topicId_ = normalizeTopicId(topicId); wantSubscribed_ = true; backoffMs_ = 2500; redirectCount_ = 0; overrideUrl_.clear(); connectNow(); } void stop() { wantSubscribed_ = false; status_ = StreamState::Offline; phase_ = ParsePhase::Headers; chunkRemaining_ = 0; lineBuf_.clear(); if (net_) { net_->close(); net_.reset(); } std::memset(key_, 0, sizeof(key_)); keyValid_ = false; } void retryNowIfReconnecting() { if (wantSubscribed_ && status_ == StreamState::Reconnecting) { backoffMs_ = 2500; nextRetryMs_ = 0; connectNow(); } } // Returns poll timeout (ms) needed for reconnects (-1 when idle or listening). int nextPollTimeoutMs() const { if (!wantSubscribed_) return -1; if (status_ == StreamState::Reconnecting) { int64_t rem = nextRetryMs_ - nowMs(); return static_cast(std::clamp(rem, 1, 120000)); } return -1; } // Advance connection/parser timers and drain available bytes from socket. // Returns true if status or delivered pages changed. bool service(const PageCallback& onPage) { bool changed = false; if (!wantSubscribed_) return false; if (status_ == StreamState::Reconnecting && nowMs() >= nextRetryMs_) { connectNow(); changed = true; } if (!net_ || !net_->isConnected()) { return changed; } int r = net_->pumpRx(0); if (parseIncoming(onPage)) { changed = true; } if (r < 0) { if (wantSubscribed_) { scheduleReconnect(net_->lastError().empty() ? "Stream closed" : net_->lastError()); changed = true; } else { stop(); changed = true; } } return changed; } private: enum class ParsePhase { Headers = 0, RawBody = 1, ChunkHeader = 2, ChunkData = 3, ChunkCrlf = 4, }; StreamState status_ = StreamState::Offline; ParsePhase phase_ = ParsePhase::Headers; bool wantSubscribed_ = false; bool keyValid_ = false; uint8_t key_[kQuagrKeyBytes] {}; std::string relayUrl_; std::string topicId_; std::string overrideUrl_; int redirectCount_ = 0; std::unique_ptr net_; std::string lineBuf_; size_t chunkRemaining_ = 0; int64_t nextRetryMs_ = 0; int backoffMs_ = 2500; std::string detail_; std::deque recentPackets_; void scheduleReconnect(const std::string& reason) { if (net_) { net_->close(); net_.reset(); } phase_ = ParsePhase::Headers; chunkRemaining_ = 0; lineBuf_.clear(); status_ = StreamState::Reconnecting; detail_ = reason; nextRetryMs_ = nowMs() + backoffMs_; backoffMs_ = std::min(backoffMs_ * 2, 120000); } void connectNow() { ParsedUrl u; std::string hostHdr; if (!overrideUrl_.empty()) { u = parseUrl(overrideUrl_, "https"); bool defPort = (u.scheme == "https" && u.port == 443) || (u.scheme == "http" && u.port == 80); hostHdr = (u.host.find(':') != std::string::npos) ? ("[" + u.host + "]") : u.host; if (!defPort) hostHdr += ":" + std::to_string(u.port); } else if (!buildQuagrEndpoint(relayUrl_, topicId_, true, u, hostHdr)) { scheduleReconnect("Invalid relay URL"); return; } status_ = StreamState::Connecting; detail_ = "Connecting..."; net_ = std::make_unique(); if (!net_->connectTcp(u.host, u.port, 5000)) { scheduleReconnect(net_->lastError()); return; } enableTcpKeepalive(net_->fd()); if (u.scheme == "https" && !net_->startTls(u.host, 5000)) { scheduleReconnect(net_->lastError()); return; } std::ostringstream req; req << "GET " << (u.path.empty() ? "/" : u.path) << " HTTP/1.1\r\n" << "Host: " << hostHdr << "\r\n" << "User-Agent: Bananarchy-Quagr/1.0\r\n" << "Accept: text/plain\r\n" << "Cache-Control: no-cache\r\n" << "Connection: keep-alive\r\n\r\n"; if (!net_->sendStr(req.str(), 5000)) { scheduleReconnect(net_->lastError()); return; } phase_ = ParsePhase::Headers; chunkRemaining_ = 0; lineBuf_.clear(); } void rememberPacket(const std::string& pkt) { recentPackets_.push_back(pkt); if (recentPackets_.size() > 16) { recentPackets_.pop_front(); } } bool seenRecently(const std::string& pkt) const { for (const auto& s : recentPackets_) { if (s == pkt) return true; } return false; } bool dispatchLine(std::string line, const PageCallback& onPage) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } std::string trimmed = trimStr(line); if (trimmed.empty() || trimmed.size() != kQuagrPacketHexLen || !keyValid_) { return false; } std::string low = toLowerStr(trimmed); if (seenRecently(low)) { return false; } std::string msg; if (!quagrDecrypt(low, key_, msg)) { return false; } rememberPacket(low); onPage(msg, low); return true; } bool drainBodyLines(const PageCallback& onPage) { bool delivered = false; while (true) { size_t nl = lineBuf_.find('\n'); if (nl == std::string::npos) break; std::string line = lineBuf_.substr(0, nl); lineBuf_.erase(0, nl + 1); if (dispatchLine(std::move(line), onPage)) { delivered = true; } } if (lineBuf_.size() > 4096) { lineBuf_.clear(); } return delivered; } bool parseIncoming(const PageCallback& onPage) { if (!net_) return false; bool changed = false; std::string& buf = net_->rxBuffer(); while (!buf.empty()) { if (phase_ == ParsePhase::Headers) { size_t hdrEnd = buf.find("\r\n\r\n"); size_t sepLen = 4; if (hdrEnd == std::string::npos) { hdrEnd = buf.find("\n\n"); sepLen = 2; } if (hdrEnd == std::string::npos) { break; } std::string hdrs = buf.substr(0, hdrEnd); buf.erase(0, hdrEnd + sepLen); int code = 0; { std::istringstream hss(hdrs); std::string ver; hss >> ver >> code; } bool isChunked = false; std::string location; std::istringstream lss(hdrs); std::string line; while (std::getline(lss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); size_t colon = line.find(':'); if (colon == std::string::npos) continue; std::string k = toLowerStr(trimStr(line.substr(0, colon))); std::string v = trimStr(line.substr(colon + 1)); if (k == "transfer-encoding" && toLowerStr(v).find("chunked") != std::string::npos) { isChunked = true; } else if (k == "location") { location = v; } } if ((code == 301 || code == 302 || code == 303 || code == 307 || code == 308) && !location.empty() && redirectCount_ < 2) { ParsedUrl cur; std::string tmpHost; if (!overrideUrl_.empty()) { cur = parseUrl(overrideUrl_, "https"); } else { buildQuagrEndpoint(relayUrl_, topicId_, true, cur, tmpHost); } std::string nextUrl; if (resolveRedirectUrl(cur, location, nextUrl)) { overrideUrl_ = nextUrl; ++redirectCount_; net_->close(); net_.reset(); connectNow(); return true; } } if (code < 200 || code >= 300) { scheduleReconnect(code > 0 ? ("HTTP " + std::to_string(code)) : "Bad HTTP status"); return true; } status_ = StreamState::Listening; backoffMs_ = 2500; detail_ = "Listening on " + topicId_; phase_ = isChunked ? ParsePhase::ChunkHeader : ParsePhase::RawBody; changed = true; continue; } if (phase_ == ParsePhase::RawBody) { lineBuf_.append(buf); buf.clear(); if (drainBodyLines(onPage)) { changed = true; } break; } if (phase_ == ParsePhase::ChunkHeader) { size_t nl = buf.find('\n'); if (nl == std::string::npos) break; std::string hdr = buf.substr(0, nl); buf.erase(0, nl + 1); if (!hdr.empty() && hdr.back() == '\r') hdr.pop_back(); size_t semi = hdr.find(';'); if (semi != std::string::npos) hdr = hdr.substr(0, semi); hdr = trimStr(hdr); if (hdr.empty()) continue; chunkRemaining_ = static_cast(std::strtoul(hdr.c_str(), nullptr, 16)); if (chunkRemaining_ == 0) { if (!lineBuf_.empty()) { if (dispatchLine(lineBuf_, onPage)) changed = true; lineBuf_.clear(); } scheduleReconnect("Stream ended"); return true; } phase_ = ParsePhase::ChunkData; continue; } if (phase_ == ParsePhase::ChunkData) { size_t take = std::min(chunkRemaining_, buf.size()); if (take > 0) { lineBuf_.append(buf, 0, take); buf.erase(0, take); chunkRemaining_ -= take; if (drainBodyLines(onPage)) { changed = true; } } if (chunkRemaining_ == 0) { phase_ = ParsePhase::ChunkCrlf; } continue; } if (phase_ == ParsePhase::ChunkCrlf) { if (buf[0] == '\r') { if (buf.size() < 2) break; if (buf[1] == '\n') { buf.erase(0, 2); } else { buf.erase(0, 1); } } else if (buf[0] == '\n') { buf.erase(0, 1); } phase_ = ParsePhase::ChunkHeader; continue; } } return changed; } }; std::string maskSecretPreview(const std::string& secret, bool showPlain) { if (secret.empty()) return "Not set"; if (showPlain) return secret; return "********"; } void pushHistoryCapped(std::vector& list, QuagrEntry item) { list.insert(list.begin(), std::move(item)); if (list.size() > kMaxHistoryEntries) { list.resize(kMaxHistoryEntries); } } void appendKeysymToString(int ks, std::string& text) { if (ks >= 0x20 && ks <= 0x7e) { text.push_back(static_cast(ks)); return; } uint32_t cp = 0; if (ks >= 0x01000100 && ks <= 0x0110ffff) { cp = static_cast(ks - 0x01000000); } else if (ks >= 0x06a0 && ks <= 0x06ff) { // Minimal Cyrillic X11 keysym mapping for hardware/T9 keyboards static constexpr uint16_t kCyrMap[96] = { 0x0000, 0x0452, 0x0453, 0x0451, 0x0454, 0x0455, 0x0456, 0x0457, 0x0458, 0x0459, 0x045a, 0x045b, 0x045c, 0x0000, 0x045e, 0x045f, 0x2116, 0x0402, 0x0403, 0x0401, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x0000, 0x040e, 0x040f, 0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, 0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, 0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a, 0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, 0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, 0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a, }; cp = kCyrMap[ks - 0x06a0]; } if (cp == 0) return; if (cp < 0x80) { text.push_back(static_cast(cp)); } else if (cp < 0x800) { text.push_back(static_cast(0xc0 | (cp >> 6))); text.push_back(static_cast(0x80 | (cp & 0x3f))); } else if (cp < 0x10000) { text.push_back(static_cast(0xe0 | (cp >> 12))); text.push_back(static_cast(0x80 | ((cp >> 6) & 0x3f))); text.push_back(static_cast(0x80 | (cp & 0x3f))); } else { text.push_back(static_cast(0xf0 | (cp >> 18))); text.push_back(static_cast(0x80 | ((cp >> 12) & 0x3f))); text.push_back(static_cast(0x80 | ((cp >> 6) & 0x3f))); text.push_back(static_cast(0x80 | (cp & 0x3f))); } } bool quagrSelfTest() { uint8_t kPass[kQuagrKeyBytes]; if (!quagrDeriveKey(KeyMode::Passphrase, "foo bar baz quux", kPass)) { return false; } // Exact SHA256("QUAGR:foo bar baz quux") verification against quagr.sh std::string fp = hexEncode(kPass, kQuagrKeyBytes); std::string pkt; if (!quagrEncrypt("Hello Quagr 30-byte test!", kPass, pkt) || pkt.size() != kQuagrPacketHexLen) { return false; } uint8_t kHex[kQuagrKeyBytes]; if (!quagrDeriveKey(KeyMode::RawHex, fp, kHex) || std::memcmp(kPass, kHex, kQuagrKeyBytes) != 0) { return false; } std::string dec; if (!quagrDecrypt(pkt, kHex, dec) || dec != "Hello Quagr 30-byte test!") { return false; } uint8_t kWrong[kQuagrKeyBytes]; if (!quagrDeriveKey(KeyMode::Passphrase, "wrong passphrase", kWrong)) { return false; } std::string decWrong; if (quagrDecrypt(pkt, kWrong, decWrong)) { return false; } return true; } int quagr_run_main(int argc, char** argv) { gRunning = 1; bool isPreload = false; std::string initCmd; for (int i = 1; i < argc; ++i) { if (!argv[i] || !argv[i][0]) continue; if (std::strcmp(argv[i], "--self-test") == 0) { return quagrSelfTest() ? 0 : 1; } if (std::strcmp(argv[i], "--preload") == 0) { isPreload = true; } else { if (!initCmd.empty()) initCmd.push_back(' '); initCmd += argv[i]; } } QuagrConfig cfg = loadQuagrConfig(); bool autoRx = shouldAutostartQuagr(&cfg); if (isPreload && !autoRx) { return 0; } if (isPreload && isPluginDaemonAlive("quagr")) { return 0; } std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd)); if (sendPluginCommand("quagr", forwarded)) { return 0; } int lockFd = acquirePluginDaemonLock("quagr"); if (lockFd < 0) { // Another instance holds the lock (possibly racing startup); forward once. if (!isPreload && sendPluginCommand("quagr", forwarded)) { return 0; } return isPreload ? 0 : 1; } std::string daemonPidPath = getPluginDaemonPidPath("quagr"); std::string activePidPath = getRuntimeFile("xquagr.pid"); writeIntFile(daemonPidPath, static_cast(::getpid())); int fifoFd = setupPluginDaemonFifo("quagr"); struct sigaction sa {}; sa.sa_handler = handleSignal; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, nullptr); sigaction(SIGINT, &sa, nullptr); ::signal(SIGPIPE, SIG_IGN); std::string dataDir = getQuagrDataDir(); std::string rxLogPath = dataDir + "/rx.log"; std::string txLogPath = dataDir + "/tx.log"; std::vector rxHistory = loadHistoryFile(rxLogPath); std::vector txHistory = loadHistoryFile(txLogPath); QuagrRxStream rxStream; // Window state (NeoWindow created lazily on first OPEN so --preload works // with zero X11 overhead and can run before display/session clients). std::unique_ptr neo; bool visible = false; int activeTab = 0; // 0=Receive, 1=Send, 2=Config int rxSel = 0; int rxScroll = 0; int txSel = 0; int txScroll = 0; int cfgSel = 0; int cfgScroll = 0; int unreadCount = 0; std::string sendComposer; std::string sendStatus = "READY"; bool sendStatusErr = false; bool showSecrets = false; // Modals bool menuOpen = false; int menuSel = 0; bool detailOpen = false; QuagrEntry detailItem; bool editModalOpen = false; int editConfigRow = -1; auto startRxWithCurrentConfig = [&]() { uint8_t key[kQuagrKeyBytes]; if (!quagrDeriveKey(cfg.rxMode, cfg.rxSecret, key)) { rxStream.stop(); if (visible) neoui_show_toast("Set Rx key or passphrase first", 1600); return false; } rxStream.start(cfg.relayUrl, cfg.topicId, key, true); std::memset(key, 0, sizeof(key)); return true; }; auto applyUpdatedRxConfig = [&](const QuagrConfig& prevCfg) { bool streamConfigChanged = (prevCfg.relayUrl != cfg.relayUrl || prevCfg.topicId != cfg.topicId || prevCfg.rxMode != cfg.rxMode || prevCfg.rxSecret != cfg.rxSecret); if (!rxStream.wantsActive()) return; if (!streamConfigChanged) return; uint8_t key[kQuagrKeyBytes]; if (!quagrDeriveKey(cfg.rxMode, cfg.rxSecret, key)) { rxStream.stop(); return; } if (prevCfg.relayUrl != cfg.relayUrl || prevCfg.topicId != cfg.topicId) { rxStream.start(cfg.relayUrl, cfg.topicId, key, true); } else { rxStream.setKey(key, true); } std::memset(key, 0, sizeof(key)); }; auto onIncomingPage = [&](const std::string& msg, const std::string&) { std::string ts = formatNowTimestamp("%Y-%m-%d %H:%M"); pushHistoryCapped(rxHistory, {ts, msg}); saveHistoryFile(rxLogPath, rxHistory); rxSel = 0; rxScroll = 0; if (!visible || activeTab != 0) { ++unreadCount; } // 1) Instant cover alert on nokia-beatles when flip is closed notifyCoverScreen(msg); // 2) Standard Sxmo notification (triggers dunstify + notification sound) writeSxmoQuagrNotification(msg); if (visible) { neoui_vibrate(90); neoui_show_toast(("Quagr: " + msg).c_str(), 1800); } }; if (autoRx) { startRxWithCurrentConfig(); } auto syncComposerInput = [&]() { if (!neo) return; neoui_input_reset(sendComposer.c_str()); neoui_input_set_mode(NEO_INPUT_ABC_LOWER); }; auto commitComposerFromInput = [&]() { if (!neo) return; std::string cur = sanitizeSingleLine(neoui_input_get_text()); std::string clamped = clampUtf8ToMaxBytes(cur, kQuagrMaxMsgBytes); if (clamped.size() != cur.size()) { neoui_input_set_text(clamped.c_str()); neoui_show_toast("Max 30 UTF-8 bytes reached", 900); } sendComposer = std::move(clamped); }; auto submitPage = [&]() { if (neo && activeTab == 1 && !editModalOpen) { commitComposerFromInput(); } std::string body = clampUtf8ToMaxBytes(sanitizeSingleLine(sendComposer), kQuagrMaxMsgBytes); if (trimStr(body).empty()) { sendStatus = "EMPTY"; sendStatusErr = true; neoui_show_toast("Enter message to send", 1300); return; } uint8_t txKey[kQuagrKeyBytes]; if (!quagrDeriveKey(cfg.txMode, cfg.txSecret, txKey)) { sendStatus = "NO TX KEY"; sendStatusErr = true; neoui_show_toast("Configure Tx key in Config", 1600); return; } std::string pktHex; bool encOk = quagrEncrypt(body, txKey, pktHex); std::memset(txKey, 0, sizeof(txKey)); if (!encOk) { sendStatus = "ENC ERR"; sendStatusErr = true; neoui_show_toast("Encryption failed", 1400); return; } sendStatus = "SENDING"; sendStatusErr = false; if (visible && neo) { neo->bindAsActiveContext(); neoui_begin_frame(); neoui_draw_header(kIconBell, NEO_TEXT_BLUE, "Quagr", "SENDING"); neoui_draw_modal_box(16, 110, 208, 66, kIconSend, NEO_TEXT_YELLOW, "Sending Page..."); neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 20, 144, 200, 20, cfg.topicId.c_str()); neoui_end_frame(); } std::string postErr; if (httpPostQuagr(cfg.relayUrl, cfg.topicId, pktHex, postErr)) { sendStatus = "SENT"; sendStatusErr = false; pushHistoryCapped(txHistory, {formatNowTimestamp("%Y-%m-%d %H:%M"), body}); saveHistoryFile(txLogPath, txHistory); sendComposer.clear(); txSel = 0; txScroll = 0; syncComposerInput(); neoui_show_toast("Page sent", 1200); } else { sendStatus = postErr.empty() ? "ERR" : postErr; sendStatusErr = true; neoui_show_toast(("Send failed: " + sendStatus).c_str(), 1800); } }; auto editFieldTitle = [&](int row) -> const char* { switch (row) { case 2: return cfg.rxMode == KeyMode::RawHex ? "Rx Hex Key (64)" : "Rx Passphrase"; case 4: return cfg.txMode == KeyMode::RawHex ? "Tx Hex Key (64)" : "Tx Passphrase"; case 7: return "Relay URL"; case 8: return "Topic ID"; default: return "Edit Setting"; } }; auto openEditModalForRow = [&](int row) { editConfigRow = row; editModalOpen = true; menuOpen = false; if (row == 2) { neoui_input_reset(cfg.rxSecret.c_str()); neoui_input_set_mode(NEO_INPUT_ABC_LOWER); } else if (row == 4) { neoui_input_reset(cfg.txSecret.c_str()); neoui_input_set_mode(NEO_INPUT_ABC_LOWER); } else if (row == 7) { neoui_input_reset(cfg.relayUrl.c_str()); neoui_input_set_mode(NEO_INPUT_ABC_LOWER); } else if (row == 8) { neoui_input_reset(cfg.topicId.c_str()); neoui_input_set_mode(NEO_INPUT_ABC_LOWER); } }; auto applyEditModal = [&]() { QuagrConfig prev = cfg; std::string val = sanitizeSingleLine(neoui_input_get_text()); if (editConfigRow == 2) { cfg.rxSecret = (cfg.rxMode == KeyMode::RawHex) ? stripHexFormatting(val) : val; } else if (editConfigRow == 4) { cfg.txSecret = (cfg.txMode == KeyMode::RawHex) ? stripHexFormatting(val) : val; } else if (editConfigRow == 7) { cfg.relayUrl = normalizeRelayUrl(val); } else if (editConfigRow == 8) { cfg.topicId = normalizeTopicId(val); } saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); editModalOpen = false; editConfigRow = -1; if (activeTab == 1) syncComposerInput(); }; auto render = [&]() { if (!visible || !neo) return; neo->bindAsActiveContext(); neoui_begin_frame(); std::string rxFp = quagrKeyFingerprint(cfg.rxMode, cfg.rxSecret); std::string txFp = quagrKeyFingerprint(cfg.txMode, cfg.txSecret); bool hasRxKey = !rxFp.empty(); bool hasTxKey = !txFp.empty(); std::string hdrBadge = hasRxKey ? rxStream.statusBadge() : "NO KEY"; int hdrCol = NEO_TEXT_MUTED; if (rxStream.status() == QuagrRxStream::StreamState::Listening) { hdrCol = NEO_TEXT_GREEN; } else if (rxStream.status() == QuagrRxStream::StreamState::Connecting || rxStream.status() == QuagrRxStream::StreamState::Reconnecting) { hdrCol = NEO_TEXT_YELLOW; } else if (!hasRxKey) { hdrCol = NEO_TEXT_RED; } neoui_draw_header_ex(NEO_HEADER_H, kIconBell, hdrCol, "Quagr", NEO_TEXT_WHITE, hdrBadge.c_str(), hdrCol); neoui_draw_tabs(unreadCount > 0 ? ("Receive (" + std::to_string(unreadCount) + ")|Send|Config").c_str() : "Receive|Send|Config", activeTab, 34, 24); constexpr int kBodyY = 58; constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; // 212 px if (activeTab == 0) { unreadCount = 0; neoui_fill_rect(0, kBodyY, 240, 18, neoui_color(NEO_COLOR_BG_ALT_EVEN)); std::string rxSub = cfg.topicId + " | Rx:" + (hasRxKey ? rxFp : "unset"); neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, 6, kBodyY, 18, rxSub.c_str(), 158); neoui_draw_text_right(NEO_FONT_SMALL, rxStream.wantsActive() ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, 234, kBodyY, 18, rxStream.wantsActive() ? "[Call] Stop" : "[Call] Listen", 78); neoui_draw_line(0, kBodyY + 18, 240, kBodyY + 18, neoui_color(NEO_COLOR_DIVIDER)); int listY = kBodyY + 19; int listH = kBodyH - 19; // 193 px -> 4 rows * 48 = 192 if (rxHistory.empty()) { neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 10, listY + 42, 220, 24, hasRxKey ? "No pages received yet" : "No Rx key configured"); neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 10, listY + 72, 220, 22, hasRxKey ? "Press OK or Call to subscribe" : "Switch to Config tab to set Rx key"); } else { constexpr int kRowH = 48; int maxVis = listH / kRowH; int total = static_cast(rxHistory.size()); rxSel = std::clamp(rxSel, 0, total - 1); if (rxScroll > rxSel) rxScroll = rxSel; if (rxSel >= rxScroll + maxVis) rxScroll = rxSel - maxVis + 1; for (int i = 0; i < maxVis && (rxScroll + i) < total; ++i) { int idx = rxScroll + i; const auto& item = rxHistory[idx]; neoui_draw_list_row(idx, listY + i * kRowH, kRowH, idx == rxSel ? 1 : 0, kIconSms, idx == 0 ? NEO_TEXT_GREEN : NEO_TEXT_BLUE, item.text.c_str(), item.timestamp.c_str(), ""); } neoui_draw_scrollbar(236, listY, listH, total, maxVis, rxScroll); } neoui_draw_softkeys("Menu", rxHistory.empty() ? (rxStream.wantsActive() ? "STOP" : "LISTEN") : "VIEW", "Back"); } else if (activeTab == 1) { neoui_fill_rect(0, kBodyY, 240, 18, neoui_color(NEO_COLOR_BG_ALT_EVEN)); std::string txMeta = std::string("Tx:") + (cfg.txMode == KeyMode::RawHex ? "Hex " : "Pass ") + (hasTxKey ? ("(" + txFp + ")") : "UNSET"); neoui_draw_text(NEO_FONT_SMALL, hasTxKey ? NEO_TEXT_MUTED : NEO_TEXT_RED, 6, kBodyY, 18, txMeta.c_str(), 156); neoui_draw_text_right(NEO_FONT_SMALL, sendStatusErr ? NEO_TEXT_RED : NEO_TEXT_GREEN, 234, kBodyY, 18, sendStatus.c_str(), 76); neoui_draw_input_box(6, kBodyY + 21, 228, 34, editModalOpen ? 0 : 1, "", neoui_input_get_text(), "Page text (max 30 bytes)...", 0); size_t curBytes = std::strlen(neoui_input_get_text()); int pct = static_cast(std::min(100, (curBytes * 100) / kQuagrMaxMsgBytes)); uint32_t barCol = neoui_color(curBytes > kQuagrMaxMsgBytes ? NEO_COLOR_DANGER : (curBytes >= 24 ? NEO_COLOR_WARNING : NEO_COLOR_SUCCESS)); std::string meterLbl = std::to_string(curBytes) + " / 30 bytes"; neoui_draw_text(NEO_FONT_SMALL, curBytes >= 24 ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, 8, kBodyY + 58, 16, meterLbl.c_str(), 110); neoui_draw_text_right(NEO_FONT_SMALL, NEO_TEXT_MUTED, 232, kBodyY + 58, 16, cfg.topicId.c_str(), 112); neoui_draw_progress_bar(8, kBodyY + 76, 224, 5, pct, barCol); int sentY = kBodyY + 86; int sentH = kBodyH - 86 - 20; // 106 px -> 3 rows * 35 if (txHistory.empty()) { neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_MUTED, 10, sentY + 36, 220, 20, "No sent pages yet"); } else { constexpr int kRowH = 35; int maxVis = sentH / kRowH; int total = static_cast(txHistory.size()); txSel = std::clamp(txSel, 0, total - 1); if (txScroll > txSel) txScroll = txSel; if (txSel >= txScroll + maxVis) txScroll = txSel - maxVis + 1; for (int i = 0; i < maxVis && (txScroll + i) < total; ++i) { int idx = txScroll + i; const auto& item = txHistory[idx]; neoui_draw_list_row(idx, sentY + i * kRowH, kRowH, idx == txSel ? 1 : 0, kIconSend, NEO_TEXT_BLUE, item.text.c_str(), item.timestamp.c_str(), ""); } neoui_draw_scrollbar(236, sentY, sentH, total, maxVis, txScroll); } neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20, "[*] Mode [OK/Call] Send"); neoui_draw_softkeys("Menu", "SEND", "Clear/Back"); } else { constexpr int kNumRows = 10; constexpr int kRowH = 42; int maxVis = kBodyH / kRowH; // 5 rows * 42 = 210 cfgSel = std::clamp(cfgSel, 0, kNumRows - 1); if (cfgScroll > cfgSel) cfgScroll = cfgSel; if (cfgSel >= cfgScroll + maxVis) cfgScroll = cfgSel - maxVis + 1; for (int i = 0; i < maxVis && (cfgScroll + i) < kNumRows; ++i) { int idx = cfgScroll + i; int y = kBodyY + i * kRowH; switch (idx) { case 0: neoui_draw_toggle_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconRefresh, cfg.autostartRx ? NEO_TEXT_GREEN : NEO_TEXT_MUTED, "Autostart Receiver", cfg.autostartRx ? 1 : 0, hasRxKey ? (cfg.autostartRx ? "ON" : "OFF") : "NO KEY"); break; case 1: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconSliders, NEO_TEXT_BLUE, "Rx Key Mode", "Reception decryption key type", cfg.rxMode == KeyMode::RawHex ? "Raw Hex" : "Pass"); break; case 2: { std::string lbl = (cfg.rxMode == KeyMode::RawHex) ? "Rx Hex Key (64)" : "Rx Passphrase"; std::string sub; if (cfg.rxSecret.empty()) { sub = "Not set"; } else if (cfg.rxMode == KeyMode::RawHex && !hasRxKey) { sub = "Invalid hex (" + std::to_string(stripHexFormatting(cfg.rxSecret).size()) + "/64)"; } else { sub = "FP: " + rxFp; } neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconKey, hasRxKey ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, lbl.c_str(), sub.c_str(), maskSecretPreview(cfg.rxSecret, showSecrets).c_str()); break; } case 3: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconSliders, NEO_TEXT_BLUE, "Tx Key Mode", "Sending encryption key type", cfg.txMode == KeyMode::RawHex ? "Raw Hex" : "Pass"); break; case 4: { std::string lbl = (cfg.txMode == KeyMode::RawHex) ? "Tx Hex Key (64)" : "Tx Passphrase"; std::string sub; if (cfg.txSecret.empty()) { sub = "Not set"; } else if (cfg.txMode == KeyMode::RawHex && !hasTxKey) { sub = "Invalid hex (" + std::to_string(stripHexFormatting(cfg.txSecret).size()) + "/64)"; } else { sub = "FP: " + txFp; } neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconKey, hasTxKey ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, lbl.c_str(), sub.c_str(), maskSecretPreview(cfg.txSecret, showSecrets).c_str()); break; } case 5: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconCopy, NEO_TEXT_BLUE, "Copy Rx -> Tx", "Mirror receive key/mode to send", "COPY"); break; case 6: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconFlash, NEO_TEXT_YELLOW, "Generate Rx Hex Key", "Random 64-hex key for receiving", "GEN"); break; case 7: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconGlobe, NEO_TEXT_BLUE, "Relay Base URL", cfg.relayUrl.c_str(), "EDIT"); break; case 8: neoui_draw_list_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconList, NEO_TEXT_BLUE, "Topic ID", cfg.topicId.c_str(), "EDIT"); break; case 9: neoui_draw_toggle_row(idx, y, kRowH, idx == cfgSel ? 1 : 0, kIconEye, NEO_TEXT_MUTED, "Show Secrets", showSecrets ? 1 : 0, showSecrets ? "VISIBLE" : "HIDDEN"); break; } } neoui_draw_scrollbar(236, kBodyY, kBodyH, kNumRows, maxVis, cfgScroll); neoui_draw_softkeys("Menu", "SELECT", "Back"); } if (detailOpen) { neoui_draw_modal_box(8, 38, 224, 214, kIconInfo, NEO_TEXT_GREEN, "Quagr Page"); neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, 18, 72, 18, detailItem.timestamp.c_str(), 204); neoui_draw_text_wrapped(NEO_FONT_MAIN, NEO_TEXT_WHITE, 18, 96, 204, 112, detailItem.text.c_str(), 0); neoui_draw_softkeys("To Send", "CLOSE", "Close"); } else if (editModalOpen) { neoui_draw_modal_box(8, 56, 224, 174, kIconEdit, NEO_TEXT_YELLOW, editFieldTitle(editConfigRow)); neoui_draw_input_box(16, 98, 208, 42, 1, "", neoui_input_get_text(), (editConfigRow == 2 || editConfigRow == 4) ? "Enter secret..." : "", 0); if ((editConfigRow == 2 && cfg.rxMode == KeyMode::RawHex) || (editConfigRow == 4 && cfg.txMode == KeyMode::RawHex)) { std::string clean = stripHexFormatting(neoui_input_get_text()); std::string cnt = std::to_string(clean.size()) + " / 64 hex chars"; neoui_draw_text(NEO_FONT_SMALL, clean.size() == 64 ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, 18, 146, 18, cnt.c_str(), 204); } else { std::string hint = (editConfigRow == 2 || editConfigRow == 4) ? ("FP: " + quagrKeyFingerprint(KeyMode::Passphrase, neoui_input_get_text())) : "Press OK or Left Softkey to save"; neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, 18, 146, 18, hint.c_str(), 204); } neoui_draw_multitap_bar(10, 198, 220, 22, "[*] Mode [OK] Save"); neoui_draw_softkeys("Save", "SAVE", "Cancel"); } else if (menuOpen) { std::string items = std::string(rxStream.wantsActive() ? "Stop Receiver" : "Listen Now") + "|Copy Rx -> Tx|Gen Rx+Tx Hex Key|Clear Rx Log|Clear Tx Log|Reset Relay Defaults|Exit Daemon"; neoui_draw_menu_popup(items.c_str(), nullptr, menuSel, 6); } neoui_end_frame(); }; auto ensureWindowCreated = [&]() -> bool { if (neo) return true; neo = std::make_unique(); if (!neo->create("xquagr", "XQuagr", "Quagr Pager")) { neo.reset(); return false; } neo->bindAsActiveContext(); neoui_set_chord_xdrawer(1); return true; }; auto openWindow = [&]() { if (isDuressMode() || isPhonePasscodeLocked()) return; cfg = loadQuagrConfig(); if (!ensureWindowCreated()) return; writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("quagr"); visible = true; rxStream.retryNowIfReconnecting(); neoui_show(); if (activeTab == 0) { unreadCount = 0; clearSxmoQuagrNotifications(); } if (activeTab == 1) { syncComposerInput(); } render(); }; auto closeWindow = [&](bool forceExit) { if (visible && neo) { visible = false; menuOpen = false; detailOpen = false; editModalOpen = false; neoui_hide(); } ::unlink(activePidPath.c_str()); bool keepAlive = !forceExit && (rxStream.wantsActive() || shouldAutostartQuagr()); if (!keepAlive) { gRunning = 0; } }; if (!isPreload) { openWindow(); if (!visible) { if (fifoFd >= 0) ::close(fifoFd); ::unlink(getPluginFifoPath("quagr").c_str()); ::unlink(daemonPidPath.c_str()); ::close(lockFd); return 1; } } while (gRunning) { for (const std::string& cmd : readFifoLines(fifoFd)) { if (cmd == "NOP") continue; if (cmd == "CLOSE") { closeWindow(false); } else if (cmd == "QUIT" || cmd == "EXIT") { rxStream.stop(); closeWindow(true); } else if (cmd == "SUBSCRIBE") { cfg = loadQuagrConfig(); startRxWithCurrentConfig(); render(); } else if (cmd == "DISCONNECT") { rxStream.stop(); render(); } else if (cmd == "RELOAD_THEME") { if (isDuressMode()) { rxStream.stop(); rxHistory.clear(); txHistory.clear(); sendComposer.clear(); cfg = QuagrConfig{}; closeWindow(true); break; } if (neo) { neo->checkReloadTheme(); render(); } } else if (cmd.rfind("OPEN", 0) == 0) { std::string arg = trimStr(cmd.substr(4)); if (arg == "send") activeTab = 1; else if (arg == "config") activeTab = 2; else if (arg == "receive") activeTab = 0; openWindow(); } } if (!gRunning) break; if (rxStream.service(onIncomingPage)) { if (visible) render(); } if (visible && neo) { neo->bindAsActiveContext(); int ev = neoui_poll_event(0); while (ev != NEO_EV_NONE && visible && gRunning) { if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { if (ev == NEO_EV_THEME_RELOAD && isDuressMode()) { rxStream.stop(); closeWindow(true); break; } render(); } else if (ev == NEO_EV_CLOSE_REQ) { closeWindow(false); break; } else if (ev == NEO_EV_SOFTKEY_CHORD) { menuOpen = false; editModalOpen = false; render(); } else if (ev == NEO_EV_SOFTKEY_RIGHT) { if (detailOpen) { detailOpen = false; } else if (editModalOpen) { editModalOpen = false; editConfigRow = -1; if (activeTab == 1) syncComposerInput(); } else if (menuOpen) { menuOpen = false; } else if (activeTab == 1 && !std::string(neoui_input_get_text()).empty()) { neoui_input_backspace(); commitComposerFromInput(); } else { closeWindow(false); break; } render(); } else if (ev == NEO_EV_SOFTKEY_LEFT) { if (detailOpen) { sendComposer = clampUtf8ToMaxBytes(detailItem.text, kQuagrMaxMsgBytes); detailOpen = false; activeTab = 1; syncComposerInput(); } else if (editModalOpen) { applyEditModal(); } else { menuOpen = !menuOpen; menuSel = 0; } render(); } else if (ev == NEO_EV_KEY_PRESS) { int k = neoui_event_key(); if (detailOpen) { if (k == NEO_KEY_OK || k == NEO_KEY_BACK || k == NEO_KEY_END) { detailOpen = false; render(); } } else if (editModalOpen) { if (k == NEO_KEY_OK) { applyEditModal(); } else if (k == NEO_KEY_END) { editModalOpen = false; editConfigRow = -1; if (activeTab == 1) syncComposerInput(); } else if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) { neoui_input_cycle_mode(); } else if (k == NEO_KEY_RIGHT && neoui_input_is_tap_active()) { neoui_input_commit_tap(); } else if (k == NEO_KEY_BACK) { neoui_input_backspace(); } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { neoui_input_feed_key(k); } else { std::string cur = neoui_input_get_text(); size_t before = cur.size(); appendKeysymToString(neoui_event_keysym(), cur); if (cur.size() != before) { neoui_input_commit_tap(); neoui_input_set_text(cur.c_str()); } } render(); } else if (menuOpen) { constexpr int kMenuCount = 7; if (k == NEO_KEY_UP || k == NEO_KEY_2) { menuSel = (menuSel + kMenuCount - 1) % kMenuCount; } else if (k == NEO_KEY_DOWN || k == NEO_KEY_8) { menuSel = (menuSel + 1) % kMenuCount; } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { menuOpen = false; } else if (k == NEO_KEY_OK || k == NEO_KEY_5) { menuOpen = false; if (menuSel == 0) { if (rxStream.wantsActive()) rxStream.stop(); else startRxWithCurrentConfig(); } else if (menuSel == 1) { QuagrConfig prev = cfg; cfg.txMode = cfg.rxMode; cfg.txSecret = cfg.rxSecret; saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); neoui_show_toast("Copied Rx key to Tx", 1200); } else if (menuSel == 2) { uint8_t rnd[kQuagrKeyBytes]; fillRandomBytes(rnd, sizeof(rnd)); std::string hex = hexEncode(rnd, sizeof(rnd)); std::memset(rnd, 0, sizeof(rnd)); QuagrConfig prev = cfg; cfg.rxMode = KeyMode::RawHex; cfg.rxSecret = hex; cfg.txMode = KeyMode::RawHex; cfg.txSecret = hex; saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); neoui_show_toast("Generated shared 64-hex key", 1400); } else if (menuSel == 3) { rxHistory.clear(); saveHistoryFile(rxLogPath, rxHistory); clearSxmoQuagrNotifications(); neoui_show_toast("Cleared received log", 1100); } else if (menuSel == 4) { txHistory.clear(); saveHistoryFile(txLogPath, txHistory); neoui_show_toast("Cleared sent log", 1100); } else if (menuSel == 5) { QuagrConfig prev = cfg; cfg.relayUrl = "https://ntfy.sh"; cfg.topicId = "quagr-public"; saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); neoui_show_toast("Reset relay & topic defaults", 1300); } else if (menuSel == 6) { rxStream.stop(); closeWindow(true); break; } } render(); } else { if (activeTab == 1 && k == NEO_KEY_RIGHT && neoui_input_is_tap_active()) { neoui_input_commit_tap(); commitComposerFromInput(); } else if (k == NEO_KEY_LEFT) { if (activeTab == 1) commitComposerFromInput(); activeTab = (activeTab + 2) % 3; if (activeTab == 0) { unreadCount = 0; clearSxmoQuagrNotifications(); } else if (activeTab == 1) { syncComposerInput(); } } else if (k == NEO_KEY_RIGHT) { if (activeTab == 1) commitComposerFromInput(); activeTab = (activeTab + 1) % 3; if (activeTab == 0) { unreadCount = 0; clearSxmoQuagrNotifications(); } else if (activeTab == 1) { syncComposerInput(); } } else if (k == NEO_KEY_END) { closeWindow(false); break; } else if (activeTab == 0) { if (k == NEO_KEY_UP && !rxHistory.empty()) { rxSel = (rxSel + static_cast(rxHistory.size()) - 1) % static_cast(rxHistory.size()); } else if (k == NEO_KEY_DOWN && !rxHistory.empty()) { rxSel = (rxSel + 1) % static_cast(rxHistory.size()); } else if (k == NEO_KEY_CALL) { if (rxStream.wantsActive()) rxStream.stop(); else startRxWithCurrentConfig(); } else if (k == NEO_KEY_OK) { if (rxHistory.empty()) { if (rxStream.wantsActive()) rxStream.stop(); else startRxWithCurrentConfig(); } else { detailItem = rxHistory[std::clamp(rxSel, 0, static_cast(rxHistory.size()) - 1)]; detailOpen = true; } } else if (k == NEO_KEY_BACK) { closeWindow(false); break; } } else if (activeTab == 1) { if (k == NEO_KEY_UP && !txHistory.empty()) { txSel = (txSel + static_cast(txHistory.size()) - 1) % static_cast(txHistory.size()); } else if (k == NEO_KEY_DOWN && !txHistory.empty()) { txSel = (txSel + 1) % static_cast(txHistory.size()); } else if (k == NEO_KEY_OK || k == NEO_KEY_CALL) { submitPage(); } else if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) { neoui_input_cycle_mode(); } else if (k == NEO_KEY_BACK) { if (!std::string(neoui_input_get_text()).empty()) { neoui_input_backspace(); commitComposerFromInput(); } else { closeWindow(false); break; } } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { std::string beforeTxt = neoui_input_get_text(); bool wasTap = neoui_input_is_tap_active() != 0; neoui_input_feed_key(k); std::string afterTxt = neoui_input_get_text(); if (afterTxt.size() > kQuagrMaxMsgBytes && !wasTap) { neoui_input_set_text(beforeTxt.c_str()); neoui_show_toast("Max 30 UTF-8 bytes", 900); } commitComposerFromInput(); } else { std::string cur = neoui_input_get_text(); size_t beforeLen = cur.size(); appendKeysymToString(neoui_event_keysym(), cur); if (cur.size() != beforeLen) { neoui_input_commit_tap(); if (cur.size() <= kQuagrMaxMsgBytes) { neoui_input_set_text(cur.c_str()); commitComposerFromInput(); } else { neoui_show_toast("Max 30 UTF-8 bytes", 900); } } } } else if (activeTab == 2) { constexpr int kNumRows = 10; if (k == NEO_KEY_UP || k == NEO_KEY_2) { cfgSel = (cfgSel + kNumRows - 1) % kNumRows; } else if (k == NEO_KEY_DOWN || k == NEO_KEY_8) { cfgSel = (cfgSel + 1) % kNumRows; } else if (k == NEO_KEY_CALL) { if (rxStream.wantsActive()) rxStream.stop(); else startRxWithCurrentConfig(); } else if (k == NEO_KEY_BACK) { closeWindow(false); break; } else if (k == NEO_KEY_OK || k == NEO_KEY_5) { QuagrConfig prev = cfg; if (cfgSel == 0) { cfg.autostartRx = !cfg.autostartRx; saveQuagrConfig(cfg); if (cfg.autostartRx && !quagrKeyFingerprint(cfg.rxMode, cfg.rxSecret).empty()) { startRxWithCurrentConfig(); } else if (cfg.autostartRx) { neoui_show_toast("Enabled (set Rx key to autostart)", 1500); } } else if (cfgSel == 1) { cfg.rxMode = (cfg.rxMode == KeyMode::Passphrase) ? KeyMode::RawHex : KeyMode::Passphrase; saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); } else if (cfgSel == 3) { cfg.txMode = (cfg.txMode == KeyMode::Passphrase) ? KeyMode::RawHex : KeyMode::Passphrase; saveQuagrConfig(cfg); } else if (cfgSel == 5) { cfg.txMode = cfg.rxMode; cfg.txSecret = cfg.rxSecret; saveQuagrConfig(cfg); neoui_show_toast("Copied Rx key to Tx", 1200); } else if (cfgSel == 6) { uint8_t rnd[kQuagrKeyBytes]; fillRandomBytes(rnd, sizeof(rnd)); cfg.rxMode = KeyMode::RawHex; cfg.rxSecret = hexEncode(rnd, sizeof(rnd)); std::memset(rnd, 0, sizeof(rnd)); saveQuagrConfig(cfg); applyUpdatedRxConfig(prev); neoui_show_toast("Generated new Rx 64-hex key", 1400); } else if (cfgSel == 9) { showSecrets = !showSecrets; } else if (cfgSel == 2 || cfgSel == 4 || cfgSel == 7 || cfgSel == 8) { openEditModalForRow(cfgSel); } } } render(); } } ev = neoui_poll_event(0); } } else if (neo && neo->dpy) { while (XPending(neo->dpy) > 0) { XEvent xev; XNextEvent(neo->dpy, &xev); } } if (!gRunning) break; std::vector pfds; if (neo && neo->dpy) { pfds.push_back({ConnectionNumber(neo->dpy), POLLIN, 0}); } if (fifoFd >= 0) { pfds.push_back({fifoFd, POLLIN, 0}); } if (rxStream.fd() >= 0) { pfds.push_back({rxStream.fd(), POLLIN, 0}); } int timeoutMs = rxStream.nextPollTimeoutMs(); if (visible) { timeoutMs = neoui_next_timeout_ms(timeoutMs); } if (pfds.empty()) { break; } ::poll(pfds.data(), static_cast(pfds.size()), timeoutMs); } rxStream.stop(); neo.reset(); if (fifoFd >= 0) ::close(fifoFd); ::unlink(getPluginFifoPath("quagr").c_str()); ::unlink(activePidPath.c_str()); ::unlink(daemonPidPath.c_str()); if (lockFd >= 0) { ::flock(lockFd, LOCK_UN); ::close(lockFd); } return 0; } int quagr_plugin_init(const DwmHostApi* host) { // CRITICAL: Only autostart the Quagr receiver daemon on boot/preload when // explicitly enabled in config AND a valid receiver passphrase or 64-char // hex key is configured. if (host && host->spawn_plugin && shouldAutostartQuagr()) { host->spawn_plugin("quagr", "--preload"); } return 0; } } // namespace extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { DWM_PLUGIN_API_VERSION, "quagr", "Encrypted Quagr pager client & opt-in receiver daemon", quagr_plugin_init, nullptr, nullptr, nullptr, nullptr, quagr_run_main };