diff --git a/overlay/rootfs/usr/bin/kopher b/overlay/rootfs/usr/bin/kopher new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/kopher @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xemail b/overlay/rootfs/usr/bin/xemail new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xemail @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xirc b/overlay/rootfs/usr/bin/xirc new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xirc @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xkopher b/overlay/rootfs/usr/bin/xkopher new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xkopher @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xmail b/overlay/rootfs/usr/bin/xmail new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xmail @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xsip b/overlay/rootfs/usr/bin/xsip new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xsip @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xsmallweb b/overlay/rootfs/usr/bin/xsmallweb new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xsmallweb @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/bin/xtox b/overlay/rootfs/usr/bin/xtox new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/overlay/rootfs/usr/bin/xtox @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so index bdc7633..a05bd59 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so and b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/email.so b/overlay/rootfs/usr/lib/dwm/plugins/email.so new file mode 100755 index 0000000..04c18b1 Binary files /dev/null and b/overlay/rootfs/usr/lib/dwm/plugins/email.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/irc.so b/overlay/rootfs/usr/lib/dwm/plugins/irc.so new file mode 100755 index 0000000..f1d98d0 Binary files /dev/null and b/overlay/rootfs/usr/lib/dwm/plugins/irc.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/sip.so b/overlay/rootfs/usr/lib/dwm/plugins/sip.so new file mode 100755 index 0000000..756202c Binary files /dev/null and b/overlay/rootfs/usr/lib/dwm/plugins/sip.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/smallweb.so b/overlay/rootfs/usr/lib/dwm/plugins/smallweb.so new file mode 100755 index 0000000..66d3b34 Binary files /dev/null and b/overlay/rootfs/usr/lib/dwm/plugins/smallweb.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/tox.so b/overlay/rootfs/usr/lib/dwm/plugins/tox.so new file mode 100755 index 0000000..370f4fe Binary files /dev/null and b/overlay/rootfs/usr/lib/dwm/plugins/tox.so differ diff --git a/overlay/rootfs/usr/lib/libneoui.so b/overlay/rootfs/usr/lib/libneoui.so index 7285744..f44fd36 100755 Binary files a/overlay/rootfs/usr/lib/libneoui.so and b/overlay/rootfs/usr/lib/libneoui.so differ diff --git a/overlay/rootfs/usr/lib/libtoxcore.so b/overlay/rootfs/usr/lib/libtoxcore.so new file mode 120000 index 0000000..bcd229e --- /dev/null +++ b/overlay/rootfs/usr/lib/libtoxcore.so @@ -0,0 +1 @@ +libtoxcore.so.2 \ No newline at end of file diff --git a/overlay/rootfs/usr/lib/libtoxcore.so.2 b/overlay/rootfs/usr/lib/libtoxcore.so.2 new file mode 120000 index 0000000..a12824a --- /dev/null +++ b/overlay/rootfs/usr/lib/libtoxcore.so.2 @@ -0,0 +1 @@ +libtoxcore.so.2.23.0 \ No newline at end of file diff --git a/overlay/rootfs/usr/lib/libtoxcore.so.2.23.0 b/overlay/rootfs/usr/lib/libtoxcore.so.2.23.0 new file mode 100755 index 0000000..0e4dadf Binary files /dev/null and b/overlay/rootfs/usr/lib/libtoxcore.so.2.23.0 differ diff --git a/prebuilt/sxmo-x11/usr/bin/kopher b/prebuilt/sxmo-x11/usr/bin/kopher new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/kopher @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xemail b/prebuilt/sxmo-x11/usr/bin/xemail new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xemail @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xirc b/prebuilt/sxmo-x11/usr/bin/xirc new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xirc @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xkopher b/prebuilt/sxmo-x11/usr/bin/xkopher new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xkopher @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xmail b/prebuilt/sxmo-x11/usr/bin/xmail new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xmail @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xsip b/prebuilt/sxmo-x11/usr/bin/xsip new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xsip @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xsmallweb b/prebuilt/sxmo-x11/usr/bin/xsmallweb new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xsmallweb @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/bin/xtox b/prebuilt/sxmo-x11/usr/bin/xtox new file mode 120000 index 0000000..e492465 --- /dev/null +++ b/prebuilt/sxmo-x11/usr/bin/xtox @@ -0,0 +1 @@ +dwm-plugin \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so index bdc7633..a05bd59 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so new file mode 100755 index 0000000..04c18b1 Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so new file mode 100755 index 0000000..f1d98d0 Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so new file mode 100755 index 0000000..756202c Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/smallweb.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/smallweb.so new file mode 100755 index 0000000..66d3b34 Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/smallweb.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so new file mode 100755 index 0000000..370f4fe Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/libneoui.so b/prebuilt/sxmo-x11/usr/lib/libneoui.so index 7285744..f44fd36 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/libneoui.so and b/prebuilt/sxmo-x11/usr/lib/libneoui.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so new file mode 120000 index 0000000..bcd229e --- /dev/null +++ b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so @@ -0,0 +1 @@ +libtoxcore.so.2 \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 new file mode 120000 index 0000000..a12824a --- /dev/null +++ b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2 @@ -0,0 +1 @@ +libtoxcore.so.2.23.0 \ No newline at end of file diff --git a/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.23.0 b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.23.0 new file mode 100755 index 0000000..0e4dadf Binary files /dev/null and b/prebuilt/sxmo-x11/usr/lib/libtoxcore.so.2.23.0 differ diff --git a/src/dwm-plugins/callscreen_plugin.cpp b/src/dwm-plugins/callscreen_plugin.cpp index 57d3ad7..674c58e 100644 --- a/src/dwm-plugins/callscreen_plugin.cpp +++ b/src/dwm-plugins/callscreen_plugin.cpp @@ -503,12 +503,19 @@ int callscreen_run_main(int argc, char** argv) { statusNoticeUntilMs = nowMs() + 2000; }; + auto isVoipCallId = [&](const std::string& cid) -> bool { + return cid.rfind("sip:", 0) == 0 || cid.rfind("tox:", 0) == 0; + }; + auto setSpeakerRoute = [&](bool toSpeaker) { speakerOn = toSpeaker; bool jackPlugged = (readIntFile("/tmp/sxmo_jack_plugged", 0) == 1); long hwVol = pctToHwVol(callVolumePct, toSpeaker, !toSpeaker && jackPlugged); - alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", true); - alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !micMuted); + bool voip = isVoipCallId(callId); + if (!voip) { + alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", true); + alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !micMuted); + } alsa.setEnum("CIC1 MUX", 0); if (!micMuted) { alsa.setEnum("DEC1 MUX", savedMicMux > 0 ? savedMicMux : 1); @@ -760,9 +767,14 @@ int callscreen_run_main(int argc, char** argv) { XftColor* stateCol = &colBlue; unsigned long stateAccentPx = theme.spec.accent; - std::string simTag = (activeSimSlot == 1 || activeSimSlot == 2) - ? (" [SIM " + std::to_string(activeSimSlot) + "]") - : ""; + std::string simTag; + if (activeSimSlot == 3 || callId.rfind("sip:", 0) == 0) { + simTag = " [SIP]"; + } else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) { + simTag = " [TOX]"; + } else if (activeSimSlot == 1 || activeSimSlot == 2) { + simTag = " [SIM " + std::to_string(activeSimSlot) + "]"; + } if (callState == CallState::SelectSim) { stateIcon = kIconOutCall; stateBadge = "SELECT SIM CARD"; @@ -1233,7 +1245,11 @@ int callscreen_run_main(int argc, char** argv) { setSpeakerRoute(false); render(); - if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { + if (cid.rfind("sip:", 0) == 0) { + sendPluginCommand("sip", "CALL_ACCEPT " + cid); + } else if (cid.rfind("tox:", 0) == 0) { + sendPluginCommand("tox", "CALL_ACCEPT " + cid); + } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str()); } }; @@ -1245,7 +1261,11 @@ int callscreen_run_main(int argc, char** argv) { ringMuted = true; stopRingingJobs(); std::string cid = resolveActiveModemCallId(); - if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { + if (cid.rfind("sip:", 0) == 0) { + sendPluginCommand("sip", "CALL_MUTE_RING " + cid); + } else if (cid.rfind("tox:", 0) == 0) { + sendPluginCommand("tox", "CALL_MUTE_RING " + cid); + } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str()); } statusNotice = "Ringtone silenced"; @@ -1289,7 +1309,11 @@ int callscreen_run_main(int argc, char** argv) { std::string cid = resolveActiveModemCallId(); bool wasIncoming = (callState == CallState::Incoming); stopRingingJobs(); - if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { + if (cid.rfind("sip:", 0) == 0) { + sendPluginCommand("sip", "CALL_HANGUP " + cid); + } else if (cid.rfind("tox:", 0) == 0) { + sendPluginCommand("tox", "CALL_HANGUP " + cid); + } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "hangup", cid.c_str()); } else { runAsyncCmd("mmcli -m any --voice-hangup-all >/dev/null 2>&1"); @@ -1303,7 +1327,10 @@ int callscreen_run_main(int argc, char** argv) { dtmfSent.erase(0, dtmfSent.size() - 16); } std::string cid = resolveActiveModemCallId(); - if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { + if (cid.rfind("sip:", 0) == 0) { + sendPluginCommand("sip", std::string("CALL_DTMF ") + ch); + } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" && + cid.rfind("tox:", 0) != 0) { if (cid.rfind("sub", 0) == 0) { char cmd[160]; std::snprintf(cmd, sizeof(cmd), @@ -1473,7 +1500,7 @@ int callscreen_run_main(int argc, char** argv) { }; auto syncModemCalls = [&]() { - if (callId == "sim" || callId == "test") { + if (callId == "sim" || callId == "test" || isVoipCallId(callId)) { return; } std::string foundId; @@ -1690,6 +1717,14 @@ int callscreen_run_main(int argc, char** argv) { } auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) { + if (tagStr == "SIP" || cidStr.rfind("sip:", 0) == 0) { + activeSimSlot = 3; + return; + } + if (tagStr == "TOX" || cidStr.rfind("tox:", 0) == 0) { + activeSimSlot = 4; + return; + } simInfo = queryDualSimInfo(); if (tagStr == "SIM1") { activeSimSlot = 1; diff --git a/src/dwm-plugins/email_plugin.cpp b/src/dwm-plugins/email_plugin.cpp new file mode 100644 index 0000000..2c8937d --- /dev/null +++ b/src/dwm-plugins/email_plugin.cpp @@ -0,0 +1,1086 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Email DWM Plugin (email.so / xemail / xmail) for Bananarchy (240x320) +// Supports IMAP4rev1, POP3, and SMTP with implicit TLS, STARTTLS, and SASL +// authentication (PLAIN / LOGIN), MIME RFC 2047 / Base64 / Quoted-Printable +// decoding, local offline inbox caching, message reader, and composer. + +#include "../sxmo-dwm/dwm_plugin.h" +#include "net_tls.h" + +#include + +namespace { + +using namespace bananarchy; + +volatile sig_atomic_t gRunning = 1; + +void handleSignal(int) { + gRunning = 0; +} + +struct EmailAccount { + std::string label = "Personal"; + std::string address; + std::string username; + std::string password; + std::string inProtocol = "IMAP"; // IMAP or POP3 + std::string inHost; + int inPort = 993; + std::string inSecurity = "TLS"; // TLS, STARTTLS, PLAIN + std::string smtpHost; + int smtpPort = 465; + std::string smtpSecurity = "TLS"; // TLS, STARTTLS, PLAIN +}; + +struct EmailMessage { + std::string id; + std::string from; + std::string to; + std::string subject; + std::string date; + std::string body; + bool unread = false; +}; + +std::string getEmailAccountsPath() { + return getHomeDirPath() + "/.config/sxmo/email_accounts.tsv"; +} + +std::string getEmailCacheDir() { + std::string dir = getHomeDirPath() + "/.local/share/sxmo/email"; + ContactBook::ensureParentDir(dir + "/index.tsv"); + return dir; +} + +std::vector loadEmailAccounts() { + std::vector list; + std::ifstream in(getEmailAccountsPath()); + std::string line; + while (std::getline(in, line)) { + line = trimStr(line); + if (line.empty() || line[0] == '#') continue; + std::vector c; + std::stringstream ss(line); + std::string col; + while (std::getline(ss, col, '\t')) c.push_back(col); + if (c.size() >= 11) { + EmailAccount a; + a.label = c[0]; + a.address = c[1]; + a.username = c[2]; + a.password = c[3]; + a.inProtocol = c[4]; + a.inHost = c[5]; + a.inPort = std::max(1, std::atoi(c[6].c_str())); + a.inSecurity = c[7]; + a.smtpHost = c[8]; + a.smtpPort = std::max(1, std::atoi(c[9].c_str())); + a.smtpSecurity = c[10]; + list.push_back(a); + } + } + return list; +} + +void saveEmailAccounts(const std::vector& list) { + std::string path = getEmailAccountsPath(); + ContactBook::ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + for (const auto& a : list) { + out << a.label << "\t" << a.address << "\t" << a.username << "\t" + << a.password << "\t" << a.inProtocol << "\t" << a.inHost << "\t" + << a.inPort << "\t" << a.inSecurity << "\t" << a.smtpHost << "\t" + << a.smtpPort << "\t" << a.smtpSecurity << "\n"; + } +} + +std::vector loadCachedMessages() { + std::vector list; + std::string dir = getEmailCacheDir(); + std::ifstream in(dir + "/index.tsv"); + std::string line; + while (std::getline(in, line)) { + line = trimStr(line); + if (line.empty()) continue; + std::vector c; + std::stringstream ss(line); + std::string col; + while (std::getline(ss, col, '\t')) c.push_back(col); + if (c.size() >= 5) { + EmailMessage m; + m.id = c[0]; + m.from = c[1]; + m.subject = c[2]; + m.date = c[3]; + m.unread = (c[4] == "1"); + std::ifstream bf(dir + "/msg_" + m.id + ".txt"); + if (bf.is_open()) { + std::ostringstream oss; + oss << bf.rdbuf(); + m.body = oss.str(); + } + list.push_back(m); + } + } + return list; +} + +void saveCachedMessages(const std::vector& list) { + std::string dir = getEmailCacheDir(); + std::ofstream out(dir + "/index.tsv", std::ios::trunc); + if (!out.is_open()) return; + for (const auto& m : list) { + auto cleanField = [](std::string s) { + for (char& ch : s) { + if (ch == '\t' || ch == '\r' || ch == '\n') ch = ' '; + } + return s; + }; + out << cleanField(m.id) << "\t" << cleanField(m.from) << "\t" + << cleanField(m.subject) << "\t" << cleanField(m.date) << "\t" + << (m.unread ? "1" : "0") << "\n"; + std::ofstream bf(dir + "/msg_" + cleanField(m.id) + ".txt", std::ios::trunc); + if (bf.is_open()) { + bf << m.body; + } + } +} + +EmailMessage parseRawRfc5322Message(const std::string& raw, const std::string& fallbackId) { + EmailMessage msg; + msg.id = fallbackId; + msg.subject = "(No Subject)"; + msg.from = "(Unknown)"; + msg.unread = true; + + size_t split = raw.find("\r\n\r\n"); + size_t sepLen = 4; + if (split == std::string::npos) { + split = raw.find("\n\n"); + sepLen = 2; + } + std::string hdrBlock = (split == std::string::npos) ? raw : raw.substr(0, split); + std::string bodyBlock = (split == std::string::npos) ? "" : raw.substr(split + sepLen); + + // Unfold multi-line RFC 5322 headers + std::vector hdrLines; + std::istringstream hss(hdrBlock); + std::string line; + while (std::getline(hss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (!line.empty() && (line[0] == ' ' || line[0] == '\t') && !hdrLines.empty()) { + hdrLines.back() += " " + trimStr(line); + } else { + hdrLines.push_back(line); + } + } + + std::string contentType; + std::string transferEnc; + for (const auto& h : hdrLines) { + size_t colon = h.find(':'); + if (colon == std::string::npos) continue; + std::string k = toLowerStr(trimStr(h.substr(0, colon))); + std::string v = trimStr(h.substr(colon + 1)); + if (k == "from") msg.from = decodeMimeHeader(v); + else if (k == "to") msg.to = decodeMimeHeader(v); + else if (k == "subject") msg.subject = decodeMimeHeader(v); + else if (k == "date") msg.date = v.substr(0, std::min(22, v.size())); + else if (k == "content-type") contentType = v; + else if (k == "content-transfer-encoding") transferEnc = toLowerStr(v); + } + + auto decodePartPayload = [](const std::string& payload, + const std::string& enc, + const std::string& ctype) -> std::string { + std::string decoded = payload; + std::string lowEnc = toLowerStr(enc); + if (lowEnc.find("base64") != std::string::npos) { + decoded = base64Decode(payload); + } else if (lowEnc.find("quoted-printable") != std::string::npos) { + decoded = decodeQuotedPrintable(payload, false); + } + if (toLowerStr(ctype).find("text/html") != std::string::npos) { + decoded = stripHtmlTags(decoded); + } + return trimStr(decoded); + }; + + // Handle multipart boundary if present + std::string lowCt = toLowerStr(contentType); + size_t bpos = lowCt.find("boundary="); + if (bpos != std::string::npos) { + std::string bval = contentType.substr(bpos + 9); + if (!bval.empty() && bval[0] == '"') { + size_t eq = bval.find('"', 1); + bval = (eq == std::string::npos) ? bval.substr(1) : bval.substr(1, eq - 1); + } else { + size_t sc = bval.find(';'); + if (sc != std::string::npos) bval = trimStr(bval.substr(0, sc)); + } + std::string marker = "--" + bval; + std::string htmlFallback; + size_t pos = bodyBlock.find(marker); + while (pos != std::string::npos) { + size_t partStart = bodyBlock.find('\n', pos); + if (partStart == std::string::npos) break; + ++partStart; + size_t nextMarker = bodyBlock.find(marker, partStart); + std::string part = (nextMarker == std::string::npos) + ? bodyBlock.substr(partStart) + : bodyBlock.substr(partStart, nextMarker - partStart); + size_t pSplit = part.find("\r\n\r\n"); + size_t pSep = 4; + if (pSplit == std::string::npos) { + pSplit = part.find("\n\n"); + pSep = 2; + } + if (pSplit != std::string::npos) { + std::string pHdr = part.substr(0, pSplit); + std::string pBody = part.substr(pSplit + pSep); + std::string pCt = "text/plain"; + std::string pEnc; + std::istringstream pss(pHdr); + std::string pl; + while (std::getline(pss, pl)) { + if (!pl.empty() && pl.back() == '\r') pl.pop_back(); + size_t c = pl.find(':'); + if (c == std::string::npos) continue; + std::string pk = toLowerStr(trimStr(pl.substr(0, c))); + std::string pv = trimStr(pl.substr(c + 1)); + if (pk == "content-type") pCt = pv; + else if (pk == "content-transfer-encoding") pEnc = pv; + } + if (toLowerStr(pCt).find("text/plain") != std::string::npos) { + msg.body = decodePartPayload(pBody, pEnc, pCt); + break; + } else if (toLowerStr(pCt).find("text/html") != std::string::npos && + htmlFallback.empty()) { + htmlFallback = decodePartPayload(pBody, pEnc, pCt); + } + } + pos = nextMarker; + } + if (msg.body.empty()) { + msg.body = htmlFallback; + } + } else { + msg.body = decodePartPayload(bodyBlock, transferEnc, contentType); + } + return msg; +} + +std::string imapQuote(const std::string& s) { + std::string out = "\""; + for (char c : s) { + if (c == '"' || c == '\\') out.push_back('\\'); + out.push_back(c); + } + out.push_back('"'); + return out; +} + +bool fetchAccountEmails(const EmailAccount& acct, + std::vector& outMsgs, + std::string& outError) { + if (acct.inHost.empty() || acct.username.empty()) { + outError = "Account incomplete"; + return false; + } + NetStream net; + if (!net.connectTcp(acct.inHost, acct.inPort, 6000)) { + outError = net.lastError(); + return false; + } + if (acct.inSecurity == "TLS" && !net.startTls(acct.inHost, 6000)) { + outError = net.lastError(); + return false; + } + + std::string line; + if (!net.readLine(line, 6000)) { + outError = "No greeting from server"; + return false; + } + + if (toLowerStr(acct.inProtocol) == "pop3") { + if (acct.inSecurity == "STARTTLS") { + net.sendStr("STLS\r\n"); + if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0 || + !net.startTls(acct.inHost, 6000)) { + outError = "POP3 STLS failed"; + return false; + } + } + net.sendStr("USER " + acct.username + "\r\n"); + if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) { + outError = "POP3 USER rejected"; + return false; + } + net.sendStr("PASS " + acct.password + "\r\n"); + if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) { + outError = "POP3 login failed"; + return false; + } + net.sendStr("STAT\r\n"); + if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) { + outError = "POP3 STAT failed"; + return false; + } + int totalCount = 0; + { + std::istringstream iss(line.substr(3)); + iss >> totalCount; + } + int startIdx = std::max(1, totalCount - 14); + for (int i = totalCount; i >= startIdx; --i) { + net.sendStr("RETR " + std::to_string(i) + "\r\n"); + if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) continue; + std::string rawMsg; + while (net.readLine(line, 5000)) { + if (line == ".") break; + if (!line.empty() && line[0] == '.') line.erase(0, 1); + rawMsg += line + "\r\n"; + } + outMsgs.push_back(parseRawRfc5322Message(rawMsg, "pop_" + std::to_string(i))); + } + net.sendStr("QUIT\r\n"); + return true; + } + + // IMAP4rev1 flow + auto runImapCmd = [&](const std::string& tag, const std::string& cmd, + std::string& outBlock) -> bool { + outBlock.clear(); + if (!net.sendStr(tag + " " + cmd + "\r\n")) return false; + std::string l; + while (net.readLine(l, 6000)) { + if (l.rfind(tag + " ", 0) == 0) { + return l.find(tag + " OK") == 0; + } + outBlock += l + "\r\n"; + } + return false; + }; + + std::string resp; + if (acct.inSecurity == "STARTTLS") { + if (!runImapCmd("A01", "STARTTLS", resp) || !net.startTls(acct.inHost, 6000)) { + outError = "IMAP STARTTLS failed"; + return false; + } + } + if (!runImapCmd("A02", + "LOGIN " + imapQuote(acct.username) + " " + imapQuote(acct.password), + resp)) { + outError = "IMAP login failed"; + return false; + } + if (!runImapCmd("A03", "SELECT INBOX", resp)) { + outError = "SELECT INBOX failed"; + return false; + } + int existsCount = 0; + { + std::istringstream iss(resp); + std::string l; + while (std::getline(iss, l)) { + if (l.find(" EXISTS") != std::string::npos && l.rfind("* ", 0) == 0) { + existsCount = std::atoi(l.substr(2).c_str()); + } + } + } + int startSeq = std::max(1, existsCount - 14); + for (int seq = existsCount; seq >= startSeq && seq >= 1; --seq) { + std::string tag = "F" + std::to_string(seq); + if (runImapCmd(tag, + "FETCH " + std::to_string(seq) + " (BODY.PEEK[])", + resp)) { + size_t firstNl = resp.find("\r\n"); + std::string rawRfc = (firstNl == std::string::npos) ? resp : resp.substr(firstNl + 2); + if (rawRfc.size() > 3 && rawRfc.substr(rawRfc.size() - 3) == ")\r\n") { + rawRfc.erase(rawRfc.size() - 3); + } + outMsgs.push_back(parseRawRfc5322Message(rawRfc, "imap_" + std::to_string(seq))); + } + } + net.sendStr("A99 LOGOUT\r\n"); + return true; +} + +bool sendSmtpEmail(const EmailAccount& acct, const std::string& toAddr, + const std::string& subject, const std::string& body, + std::string& outError) { + if (acct.smtpHost.empty() || toAddr.empty()) { + outError = "Missing SMTP host or recipient"; + return false; + } + NetStream net; + if (!net.connectTcp(acct.smtpHost, acct.smtpPort, 6000)) { + outError = net.lastError(); + return false; + } + if (acct.smtpSecurity == "TLS" && !net.startTls(acct.smtpHost, 6000)) { + outError = net.lastError(); + return false; + } + + auto readSmtpCode = [&](int& codeOut) -> bool { + std::string l; + while (net.readLine(l, 6000)) { + if (l.size() >= 3 && std::isdigit(static_cast(l[0]))) { + codeOut = std::atoi(l.substr(0, 3).c_str()); + if (l.size() == 3 || l[3] == ' ') return true; + } + } + return false; + }; + + int code = 0; + if (!readSmtpCode(code) || code != 220) { + outError = "SMTP greeting failed"; + return false; + } + net.sendStr("EHLO bananarchy.local\r\n"); + if (!readSmtpCode(code) || code != 250) { + outError = "SMTP EHLO failed"; + return false; + } + if (acct.smtpSecurity == "STARTTLS") { + net.sendStr("STARTTLS\r\n"); + if (!readSmtpCode(code) || code != 220 || !net.startTls(acct.smtpHost, 6000)) { + outError = "SMTP STARTTLS failed"; + return false; + } + net.sendStr("EHLO bananarchy.local\r\n"); + if (!readSmtpCode(code) || code != 250) { + outError = "SMTP EHLO after TLS failed"; + return false; + } + } + + if (!acct.username.empty() && !acct.password.empty()) { + std::string authRaw; + authRaw.push_back('\0'); + authRaw += acct.username; + authRaw.push_back('\0'); + authRaw += acct.password; + net.sendStr("AUTH PLAIN " + base64EncodeStr(authRaw) + "\r\n"); + if (!readSmtpCode(code) || code != 235) { + // Fallback to AUTH LOGIN + net.sendStr("AUTH LOGIN\r\n"); + if (readSmtpCode(code) && code == 334) { + net.sendStr(base64EncodeStr(acct.username) + "\r\n"); + if (readSmtpCode(code) && code == 334) { + net.sendStr(base64EncodeStr(acct.password) + "\r\n"); + readSmtpCode(code); + } + } + if (code != 235) { + outError = "SMTP authentication failed"; + return false; + } + } + } + + std::string fromAddr = acct.address.empty() ? acct.username : acct.address; + net.sendStr("MAIL FROM:<" + fromAddr + ">\r\n"); + if (!readSmtpCode(code) || (code != 250 && code != 251)) { + outError = "MAIL FROM rejected"; + return false; + } + net.sendStr("RCPT TO:<" + trimStr(toAddr) + ">\r\n"); + if (!readSmtpCode(code) || (code != 250 && code != 251)) { + outError = "RCPT TO rejected"; + return false; + } + net.sendStr("DATA\r\n"); + if (!readSmtpCode(code) || code != 354) { + outError = "SMTP DATA rejected"; + return false; + } + + time_t now = ::time(nullptr); + struct tm tmNow {}; + localtime_r(&now, &tmNow); + char dateBuf[64]; + std::strftime(dateBuf, sizeof(dateBuf), "%a, %d %b %Y %H:%M:%S %z", &tmNow); + + std::ostringstream payload; + payload << "From: \"" << acct.label << "\" <" << fromAddr << ">\r\n" + << "To: <" << trimStr(toAddr) << ">\r\n" + << "Subject: " << subject << "\r\n" + << "Date: " << dateBuf << "\r\n" + << "Message-ID: <" << randomHexToken(8) << "@" << acct.smtpHost << ">\r\n" + << "MIME-Version: 1.0\r\n" + << "Content-Type: text/plain; charset=UTF-8\r\n" + << "User-Agent: Bananarchy-XEmail/1.0\r\n\r\n" + << body << "\r\n.\r\n"; + net.sendStr(payload.str()); + if (!readSmtpCode(code) || code != 250) { + outError = "SMTP message send failed"; + return false; + } + net.sendStr("QUIT\r\n"); + return true; +} + +int email_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], "--preload") == 0) isPreload = true; + else { + if (!initCmd.empty()) initCmd.push_back(' '); + initCmd += argv[i]; + } + } + + std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd)); + if (sendPluginCommand("email", forwarded)) { + return 0; + } + + std::string daemonPidPath = getPluginDaemonPidPath("email"); + std::string activePidPath = getRuntimeFile("xemail.pid"); + writeIntFile(daemonPidPath, static_cast(::getpid())); + int fifoFd = setupPluginDaemonFifo("email"); + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + NeoWindow neo; + if (!neo.create("xemail", "XEmail", "Email Client")) { + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(daemonPidPath.c_str()); + return 1; + } + neo.bindAsActiveContext(); + + std::vector accounts = loadEmailAccounts(); + std::vector messages = loadCachedMessages(); + + bool visible = false; + int activeTab = 0; // 0=Inbox, 1=Compose, 2=Accounts + int activeAcctIdx = 0; + int selectedRow = 0; + int scrollOffset = 0; + bool readingMsg = false; + int readScrollLine = 0; + bool menuOpen = false; + int menuSel = 0; + + // Compose fields + int composeField = 0; // 0=To, 1=Subject, 2=Body + std::string composeTo; + std::string composeSubject; + std::string composeBody; + + // Account editor modal + bool editModalOpen = false; + int editAcctIdx = -1; + int editFieldIdx = 0; + EmailAccount editDraft; + + auto syncInputBuffer = [&]() { + if (editModalOpen) { + if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str()); + else if (editFieldIdx == 1) neoui_input_reset(editDraft.address.c_str()); + else if (editFieldIdx == 2) neoui_input_reset(editDraft.username.c_str()); + else if (editFieldIdx == 3) neoui_input_reset(editDraft.password.c_str()); + else if (editFieldIdx == 5) neoui_input_reset(editDraft.inHost.c_str()); + else if (editFieldIdx == 6) { + neoui_input_set_mode(NEO_INPUT_123); + neoui_input_reset(std::to_string(editDraft.inPort).c_str()); + } else if (editFieldIdx == 8) neoui_input_reset(editDraft.smtpHost.c_str()); + else if (editFieldIdx == 9) { + neoui_input_set_mode(NEO_INPUT_123); + neoui_input_reset(std::to_string(editDraft.smtpPort).c_str()); + } + } else if (activeTab == 1) { + if (composeField == 0) neoui_input_reset(composeTo.c_str()); + else if (composeField == 1) neoui_input_reset(composeSubject.c_str()); + else neoui_input_reset(composeBody.c_str()); + } + }; + + auto applyInputBuffer = [&]() { + std::string txt = neoui_input_get_text(); + if (editModalOpen) { + if (editFieldIdx == 0) editDraft.label = txt; + else if (editFieldIdx == 1) { + editDraft.address = txt; + if (editDraft.username.empty()) editDraft.username = txt; + } else if (editFieldIdx == 2) editDraft.username = txt; + else if (editFieldIdx == 3) editDraft.password = txt; + else if (editFieldIdx == 5) editDraft.inHost = txt; + else if (editFieldIdx == 6) editDraft.inPort = std::max(1, std::atoi(txt.c_str())); + else if (editFieldIdx == 8) editDraft.smtpHost = txt; + else if (editFieldIdx == 9) editDraft.smtpPort = std::max(1, std::atoi(txt.c_str())); + } else if (activeTab == 1) { + if (composeField == 0) composeTo = txt; + else if (composeField == 1) composeSubject = txt; + else composeBody = txt; + } + }; + + auto render = [&]() { + if (!visible) return; + neo.bindAsActiveContext(); + neoui_begin_frame(); + + std::string badge = accounts.empty() + ? "NO ACCT" + : accounts[std::clamp(activeAcctIdx, 0, + static_cast(accounts.size()) - 1)] + .label; + neoui_draw_header(kIconSms, NEO_TEXT_BLUE, "Email", badge.c_str()); + + if (readingMsg && selectedRow >= 0 && + selectedRow < static_cast(messages.size())) { + const auto& m = messages[selectedRow]; + neoui_fill_rect(0, 34, 240, 44, neoui_color(NEO_COLOR_BG_ALT_EVEN)); + neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, 6, 35, 20, m.subject.c_str(), 228); + std::string meta = m.from + " | " + m.date; + neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 6, 56, 18, meta.c_str(), 228); + neoui_draw_line(0, 78, 240, 78, neoui_color(NEO_COLOR_BORDER)); + neoui_draw_text_wrapped(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 6, 82, 228, + 296 - 82 - NEO_SOFTBAR_H, m.body.c_str(), + readScrollLine); + neoui_draw_softkeys("Reply", "SCROLL", "Back"); + neoui_end_frame(); + return; + } + + neoui_draw_tabs("Inbox|Compose|Accounts", activeTab, 34, 24); + constexpr int kBodyY = 58; + constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; + + if (activeTab == 0) { + int rowH = 42; + int maxVis = kBodyH / rowH; + if (messages.empty()) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60, + 240, 24, "Inbox Empty"); + neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 86, + 240, 20, "Press Call or Menu -> Sync Inbox"); + } else { + selectedRow = std::clamp(selectedRow, 0, static_cast(messages.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(messages.size()); ++i) { + int idx = scrollOffset + i; + const auto& m = messages[idx]; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconSms, m.unread ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, + m.subject.c_str(), m.from.c_str(), m.date.c_str()); + } + neoui_draw_scrollbar(236, kBodyY, kBodyH, static_cast(messages.size()), + maxVis, scrollOffset); + } + neoui_draw_softkeys("Menu", messages.empty() ? "SYNC" : "READ", "Close"); + } else if (activeTab == 1) { + neoui_draw_input_box(6, kBodyY + 4, 228, 34, composeField == 0 ? 1 : 0, + "To:", composeField == 0 ? neoui_input_get_text() : composeTo.c_str(), + "recipient@example.com", 0); + neoui_draw_input_box(6, kBodyY + 42, 228, 34, composeField == 1 ? 1 : 0, + "Subject:", composeField == 1 ? neoui_input_get_text() : composeSubject.c_str(), + "Subject line", 0); + neoui_draw_input_box(6, kBodyY + 80, 228, 86, composeField == 2 ? 1 : 0, + "Message Body:", composeField == 2 ? neoui_input_get_text() : composeBody.c_str(), + "Write message...", 0); + neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 22, 240, 22, + "[Call/OK] Send [*] Input Mode"); + neoui_draw_softkeys("Menu", "SEND", "Back"); + } else { + int rowH = 42; + int maxVis = kBodyH / rowH; + if (accounts.empty()) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60, + 240, 24, "No Email Accounts"); + neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 86, + 240, 20, "Press OK to Add IMAP/POP3/SMTP"); + } else { + selectedRow = std::clamp(selectedRow, 0, static_cast(accounts.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(accounts.size()); ++i) { + int idx = scrollOffset + i; + const auto& a = accounts[idx]; + std::string sub = a.inProtocol + ":" + a.inHost + " / SMTP:" + a.smtpHost; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconUser, idx == activeAcctIdx ? NEO_TEXT_GREEN : NEO_TEXT_LIGHT, + a.label.c_str(), sub.c_str(), a.inSecurity.c_str()); + } + } + neoui_draw_softkeys("Menu", accounts.empty() ? "ADD" : "EDIT", "Back"); + } + + if (editModalOpen) { + neoui_draw_modal_box(4, 28, 232, 238, kIconEdit, NEO_TEXT_YELLOW, + editAcctIdx < 0 ? "Add Email Account" : "Edit Email Account"); + const char* labels[11] = { + "Label", "Address", "Username", "Password", "Protocol", + "In Host", "In Port", "In TLS", "SMTP Host", "SMTP Port", "SMTP TLS" + }; + std::string vals[11] = { + editDraft.label, editDraft.address, editDraft.username, + editDraft.password.empty() ? "" : "******", + editDraft.inProtocol, editDraft.inHost, std::to_string(editDraft.inPort), + editDraft.inSecurity, editDraft.smtpHost, std::to_string(editDraft.smtpPort), + editDraft.smtpSecurity + }; + int startF = std::max(0, std::min(editFieldIdx - 2, 7)); + for (int i = 0; i < 4 && (startF + i) < 11; ++i) { + int f = startF + i; + bool isText = (f != 4 && f != 7 && f != 10); + std::string v = (f == editFieldIdx && isText) ? neoui_input_get_text() : vals[f]; + std::string rowStr = std::string(labels[f]) + ": " + v; + neoui_draw_list_row(f, 56 + i * 36, 36, f == editFieldIdx ? 1 : 0, + kIconKey, f == editFieldIdx ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, + rowStr.c_str(), "", ""); + } + neoui_draw_multitap_bar(6, 204, 228, 22, "[*] Mode [OK] Cycle Option"); + neoui_draw_softkeys("Save", "EDIT", "Cancel"); + } else if (menuOpen) { + neoui_draw_menu_popup( + "Sync Inbox Now|Compose Email|Add Account|Switch Account|Delete Selected", + nullptr, menuSel, 5); + } + + neoui_end_frame(); + }; + + auto syncActiveInbox = [&]() { + if (accounts.empty()) { + neoui_show_toast("Configure an account first", 2000); + render(); + return; + } + int idx = std::clamp(activeAcctIdx, 0, static_cast(accounts.size()) - 1); + neoui_show_toast("Syncing inbox...", 1500); + render(); + std::vector fetched; + std::string err; + if (fetchAccountEmails(accounts[idx], fetched, err)) { + messages = std::move(fetched); + saveCachedMessages(messages); + neoui_show_toast( + ("Synced " + std::to_string(messages.size()) + " messages").c_str(), + 2000); + } else { + neoui_show_toast(("Sync failed: " + err).c_str(), 2500); + } + render(); + }; + + auto openWindow = [&]() { + if (isPhonePasscodeLocked()) return; + writeIntFile(activePidPath, static_cast(::getpid())); + closeOtherPlugins("email"); + visible = true; + neoui_show(); + syncInputBuffer(); + render(); + }; + + auto closeWindow = [&]() { + if (!visible) return; + visible = false; + readingMsg = false; + editModalOpen = false; + menuOpen = false; + neoui_hide(); + ::unlink(activePidPath.c_str()); + }; + + if (!isPreload) { + openWindow(); + } + + while (gRunning) { + for (const std::string& cmd : readFifoLines(fifoFd)) { + if (cmd == "NOP") continue; + if (cmd == "CLOSE") closeWindow(); + else if (cmd == "RELOAD_THEME") { + neo.reloadTheme(); + if (visible) render(); + } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + openWindow(); + } + } + + if (visible) { + neo.bindAsActiveContext(); + int ev = neoui_poll_event(0); + while (ev != NEO_EV_NONE) { + if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { + render(); + } else if (ev == NEO_EV_CLOSE_REQ) { + closeWindow(); + break; + } else if (ev == NEO_EV_SOFTKEY_LEFT) { + if (editModalOpen) { + applyInputBuffer(); + if (editAcctIdx < 0) accounts.push_back(editDraft); + else if (editAcctIdx < static_cast(accounts.size())) { + accounts[editAcctIdx] = editDraft; + } + saveEmailAccounts(accounts); + editModalOpen = false; + syncInputBuffer(); + render(); + } else if (readingMsg && selectedRow >= 0 && + selectedRow < static_cast(messages.size())) { + composeTo = messages[selectedRow].from; + size_t lt = composeTo.find('<'); + size_t gt = composeTo.find('>'); + if (lt != std::string::npos && gt != std::string::npos && gt > lt + 1) { + composeTo = composeTo.substr(lt + 1, gt - lt - 1); + } + composeSubject = "Re: " + messages[selectedRow].subject; + composeBody.clear(); + readingMsg = false; + activeTab = 1; + composeField = 2; + syncInputBuffer(); + render(); + } else { + menuOpen = !menuOpen; + menuSel = 0; + render(); + } + } else if (ev == NEO_EV_SOFTKEY_RIGHT) { + if (editModalOpen) { + editModalOpen = false; + syncInputBuffer(); + render(); + } else if (menuOpen) { + menuOpen = false; + render(); + } else if (readingMsg) { + readingMsg = false; + render(); + } else if (activeTab != 0) { + applyInputBuffer(); + activeTab = 0; + render(); + } else { + closeWindow(); + break; + } + } else if (ev == NEO_EV_KEY_PRESS) { + int k = neoui_event_key(); + if (menuOpen) { + if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5; + else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5; + else if (k == NEO_KEY_OK) { + menuOpen = false; + if (menuSel == 0) syncActiveInbox(); + else if (menuSel == 1) { + activeTab = 1; + composeField = 0; + syncInputBuffer(); + } else if (menuSel == 2) { + editAcctIdx = -1; + editDraft = EmailAccount{}; + editFieldIdx = 0; + editModalOpen = true; + syncInputBuffer(); + } else if (menuSel == 3 && !accounts.empty()) { + activeAcctIdx = (activeAcctIdx + 1) % static_cast(accounts.size()); + } else if (menuSel == 4) { + if (activeTab == 2 && selectedRow >= 0 && + selectedRow < static_cast(accounts.size())) { + accounts.erase(accounts.begin() + selectedRow); + saveEmailAccounts(accounts); + } else if (activeTab == 0 && selectedRow >= 0 && + selectedRow < static_cast(messages.size())) { + messages.erase(messages.begin() + selectedRow); + saveCachedMessages(messages); + } + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + menuOpen = false; + } + render(); + } else if (editModalOpen) { + if (k == NEO_KEY_UP) { + applyInputBuffer(); + editFieldIdx = (editFieldIdx + 10) % 11; + syncInputBuffer(); + } else if (k == NEO_KEY_DOWN) { + applyInputBuffer(); + editFieldIdx = (editFieldIdx + 1) % 11; + syncInputBuffer(); + } else if (k == NEO_KEY_OK) { + if (editFieldIdx == 4) { + editDraft.inProtocol = (editDraft.inProtocol == "IMAP") ? "POP3" : "IMAP"; + editDraft.inPort = (editDraft.inProtocol == "IMAP") ? 993 : 995; + } else if (editFieldIdx == 7) { + if (editDraft.inSecurity == "TLS") editDraft.inSecurity = "STARTTLS"; + else if (editDraft.inSecurity == "STARTTLS") editDraft.inSecurity = "PLAIN"; + else editDraft.inSecurity = "TLS"; + } else if (editFieldIdx == 10) { + if (editDraft.smtpSecurity == "TLS") editDraft.smtpSecurity = "STARTTLS"; + else if (editDraft.smtpSecurity == "STARTTLS") editDraft.smtpSecurity = "PLAIN"; + else editDraft.smtpSecurity = "TLS"; + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + neoui_input_backspace(); + applyInputBuffer(); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyInputBuffer(); + } + render(); + } else if (readingMsg) { + if (k == NEO_KEY_UP) { + if (readScrollLine > 0) --readScrollLine; + } else if (k == NEO_KEY_DOWN || k == NEO_KEY_OK) { + ++readScrollLine; + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + readingMsg = false; + } + render(); + } else { + if (k == NEO_KEY_LEFT) { + applyInputBuffer(); + activeTab = (activeTab + 2) % 3; + selectedRow = 0; + scrollOffset = 0; + syncInputBuffer(); + } else if (k == NEO_KEY_RIGHT) { + applyInputBuffer(); + activeTab = (activeTab + 1) % 3; + selectedRow = 0; + scrollOffset = 0; + syncInputBuffer(); + } else if (activeTab == 0) { + if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow; + else if (k == NEO_KEY_DOWN) ++selectedRow; + else if (k == NEO_KEY_CALL) syncActiveInbox(); + else if (k == NEO_KEY_OK) { + if (messages.empty()) { + syncActiveInbox(); + } else if (selectedRow >= 0 && + selectedRow < static_cast(messages.size())) { + messages[selectedRow].unread = false; + saveCachedMessages(messages); + readingMsg = true; + readScrollLine = 0; + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + closeWindow(); + break; + } + } else if (activeTab == 1) { + if (k == NEO_KEY_UP) { + applyInputBuffer(); + composeField = (composeField + 2) % 3; + syncInputBuffer(); + } else if (k == NEO_KEY_DOWN) { + applyInputBuffer(); + composeField = (composeField + 1) % 3; + syncInputBuffer(); + } else if (k == NEO_KEY_CALL || k == NEO_KEY_OK) { + applyInputBuffer(); + if (accounts.empty()) { + neoui_show_toast("Configure an account first", 2000); + } else { + neoui_show_toast("Sending email...", 1500); + render(); + std::string err; + int idx = std::clamp(activeAcctIdx, 0, + static_cast(accounts.size()) - 1); + if (sendSmtpEmail(accounts[idx], composeTo, composeSubject, + composeBody, err)) { + composeTo.clear(); + composeSubject.clear(); + composeBody.clear(); + syncInputBuffer(); + neoui_show_toast("Email sent!", 2000); + } else { + neoui_show_toast(("Send failed: " + err).c_str(), 2500); + } + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + neoui_input_backspace(); + applyInputBuffer(); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyInputBuffer(); + } + } else if (activeTab == 2) { + if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow; + else if (k == NEO_KEY_DOWN) ++selectedRow; + else if (k == NEO_KEY_OK) { + if (accounts.empty()) { + editAcctIdx = -1; + editDraft = EmailAccount{}; + } else { + editAcctIdx = std::clamp(selectedRow, 0, + static_cast(accounts.size()) - 1); + editDraft = accounts[editAcctIdx]; + } + editFieldIdx = 0; + editModalOpen = true; + syncInputBuffer(); + } + } + render(); + } + } + ev = neoui_poll_event(0); + } + } else { + while (XPending(neo.dpy) > 0) { + XEvent xev; + XNextEvent(neo.dpy, &xev); + } + } + + struct pollfd pfds[2] {}; + pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 }; + pfds[1] = { fifoFd, POLLIN, 0 }; + int timeoutMs = visible ? (neoui_input_is_tap_active() ? 150 : 1000) : -1; + ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); + } + + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(getPluginFifoPath("email").c_str()); + ::unlink(daemonPidPath.c_str()); + return 0; +} + +int email_plugin_init(const DwmHostApi* host) { + if (host && host->spawn_plugin) { + host->spawn_plugin("email", "--preload"); + } + return 0; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { + DWM_PLUGIN_API_VERSION, + "email", + "IMAP4 / POP3 / SMTP Email client with TLS and STARTTLS support", + email_plugin_init, + nullptr, + nullptr, + nullptr, + nullptr, + email_run_main +}; diff --git a/src/dwm-plugins/files_plugin.cpp b/src/dwm-plugins/files_plugin.cpp index 99e3266..872ab1d 100644 --- a/src/dwm-plugins/files_plugin.cpp +++ b/src/dwm-plugins/files_plugin.cpp @@ -2067,8 +2067,7 @@ int runFilesApp(int argc, char** argv) { drawUI(); } else { editLastTapDigit = -1; - int lineLen = - static_cast(editLines[editCursorRow].size()); + size_t lineLen = editLines[editCursorRow].size(); if (editCursorCol < lineLen) { editCursorCol = nextUtf8Pos(editLines[editCursorRow], editCursorCol); diff --git a/src/dwm-plugins/irc_plugin.cpp b/src/dwm-plugins/irc_plugin.cpp new file mode 100644 index 0000000..32b37ec --- /dev/null +++ b/src/dwm-plugins/irc_plugin.cpp @@ -0,0 +1,1012 @@ +// SPDX-License-Identifier: GPL-2.0-only +// IRC Client DWM Plugin (irc.so / xirc) for Bananarchy (240x320) +// Features: +// - Multi-server simultaneous connections over OpenSSL TLS or plain TCP +// - IRCv3 capability negotiation (CAP LS 302: sasl, server-time, message-tags, +// multi-prefix, away-notify, account-notify, chghost, cap-notify) +// - SASL PLAIN authentication + automatic PING/PONG background keepalive +// - Resident background mode with highlight/DM vibration alerts +// - NeoUI 3-tab interface: Chat View, Buffers List, and Server Manager + +#include "../sxmo-dwm/dwm_plugin.h" +#include "net_tls.h" + +#include +#include + +namespace { + +using namespace bananarchy; + +volatile sig_atomic_t gRunning = 1; + +void handleSignal(int) { + gRunning = 0; +} + +struct IrcMessageLine { + std::string timeStr; + std::string sender; + std::string text; + bool isHighlight = false; + bool isSystem = false; +}; + +struct IrcBuffer { + int serverIdx = 0; + std::string name; // e.g. "*status*", "#bananarchy", or "nick" + std::string topic; + std::vector lines; + int unreadCount = 0; + bool hasHighlight = false; + + void append(const std::string& sender, const std::string& txt, + bool highlight = false, bool sys = false, + const std::string& customTime = "") { + IrcMessageLine m; + if (!customTime.empty()) { + m.timeStr = customTime; + } else { + time_t now = ::time(nullptr); + struct tm tmNow {}; + localtime_r(&now, &tmNow); + char buf[16]; + std::strftime(buf, sizeof(buf), "%H:%M", &tmNow); + m.timeStr = buf; + } + m.sender = sender; + m.text = txt; + m.isHighlight = highlight; + m.isSystem = sys; + lines.push_back(std::move(m)); + if (lines.size() > 250) { + lines.erase(lines.begin(), lines.begin() + (lines.size() - 250)); + } + } +}; + +struct IrcServerConfig { + std::string label = "Libera.Chat"; + std::string host = "irc.libera.chat"; + int port = 6697; + bool useTls = true; + std::string nick = "bananarchy"; + std::string username = "bananarchy"; + std::string realname = "Bananarchy Linux User"; + std::string saslUser; + std::string saslPass; + std::string autoJoin = "#bananarchy"; + bool keepInBackground = true; + + // Runtime state + std::unique_ptr net; + std::string state = "DISC"; + bool capNegotiating = false; + bool saslPending = false; + bool registered = false; +}; + +std::string getIrcServersPath() { + return getHomeDirPath() + "/.config/sxmo/irc_servers.tsv"; +} + +std::vector loadIrcServers() { + std::vector list; + std::ifstream in(getIrcServersPath()); + std::string line; + while (std::getline(in, line)) { + line = trimStr(line); + if (line.empty() || line[0] == '#') continue; + std::vector c; + std::stringstream ss(line); + std::string col; + while (std::getline(ss, col, '\t')) c.push_back(col); + if (c.size() >= 10) { + IrcServerConfig s; + s.label = c[0]; + s.host = c[1]; + s.port = std::max(1, std::atoi(c[2].c_str())); + s.useTls = (c[3] == "1" || toLowerStr(c[3]) == "true"); + s.nick = c[4]; + s.username = c[5]; + s.realname = c[6]; + s.saslUser = c[7]; + s.saslPass = c[8]; + s.autoJoin = c[9]; + if (c.size() >= 11) { + s.keepInBackground = (c[10] == "1" || toLowerStr(c[10]) == "true"); + } + list.push_back(std::move(s)); + } + } + if (list.empty()) { + IrcServerConfig def; + def.label = "Libera.Chat"; + def.host = "irc.libera.chat"; + def.port = 6697; + def.useTls = true; + def.nick = "banana" + std::to_string(::getpid() % 900 + 100); + def.username = "bananarchy"; + def.realname = "Bananarchy Linux"; + def.autoJoin = "#bananarchy"; + list.push_back(std::move(def)); + } + return list; +} + +void saveIrcServers(const std::vector& list) { + std::string path = getIrcServersPath(); + ContactBook::ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + for (const auto& s : list) { + out << s.label << "\t" << s.host << "\t" << s.port << "\t" + << (s.useTls ? "1" : "0") << "\t" << s.nick << "\t" << s.username + << "\t" << s.realname << "\t" << s.saslUser << "\t" << s.saslPass + << "\t" << s.autoJoin << "\t" << (s.keepInBackground ? "1" : "0") + << "\n"; + } +} + +int irc_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], "--preload") == 0) isPreload = true; + else { + if (!initCmd.empty()) initCmd.push_back(' '); + initCmd += argv[i]; + } + } + + std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd)); + if (sendPluginCommand("irc", forwarded)) { + return 0; + } + + std::string daemonPidPath = getPluginDaemonPidPath("irc"); + std::string activePidPath = getRuntimeFile("xirc.pid"); + writeIntFile(daemonPidPath, static_cast(::getpid())); + int fifoFd = setupPluginDaemonFifo("irc"); + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + NeoWindow neo; + if (!neo.create("xirc", "XIrc", "IRC Client")) { + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(daemonPidPath.c_str()); + return 1; + } + neo.bindAsActiveContext(); + + std::vector servers = loadIrcServers(); + std::vector buffers; + int activeBufIdx = 0; + + auto findOrCreateBuffer = [&](int srvIdx, const std::string& name) -> int { + std::string lowName = toLowerStr(name); + for (size_t i = 0; i < buffers.size(); ++i) { + if (buffers[i].serverIdx == srvIdx && + toLowerStr(buffers[i].name) == lowName) { + return static_cast(i); + } + } + IrcBuffer b; + b.serverIdx = srvIdx; + b.name = name; + buffers.push_back(std::move(b)); + return static_cast(buffers.size()) - 1; + }; + + for (size_t i = 0; i < servers.size(); ++i) { + findOrCreateBuffer(static_cast(i), "*status*"); + } + + auto sendIrcRaw = [&](int srvIdx, const std::string& rawLine) -> bool { + if (srvIdx < 0 || srvIdx >= static_cast(servers.size())) return false; + auto& s = servers[srvIdx]; + if (!s.net || !s.net->isConnected()) return false; + return s.net->sendStr(rawLine + "\r\n"); + }; + + auto connectServer = [&](int srvIdx) -> bool { + if (srvIdx < 0 || srvIdx >= static_cast(servers.size())) return false; + auto& s = servers[srvIdx]; + s.net = std::make_unique(); + int stBuf = findOrCreateBuffer(srvIdx, "*status*"); + buffers[stBuf].append("*", "Connecting to " + s.host + ":" + + std::to_string(s.port) + + (s.useTls ? " (TLS)..." : "..."), + false, true); + if (!s.net->connectTcp(s.host, s.port, 6000)) { + buffers[stBuf].append("!", "Connect failed: " + s.net->lastError(), false, true); + s.net->close(); + s.state = "ERR"; + return false; + } + if (s.useTls && !s.net->startTls(s.host, 6000)) { + buffers[stBuf].append("!", "TLS failed: " + s.net->lastError(), false, true); + s.net->close(); + s.state = "TLS ERR"; + return false; + } + s.state = s.useTls ? "TLS..." : "CONN..."; + s.capNegotiating = true; + s.saslPending = false; + s.registered = false; + + sendIrcRaw(srvIdx, "CAP LS 302"); + if (s.nick.empty()) s.nick = "banana"; + if (s.username.empty()) s.username = s.nick; + if (s.realname.empty()) s.realname = s.nick; + sendIrcRaw(srvIdx, "NICK " + s.nick); + sendIrcRaw(srvIdx, "USER " + s.username + " 0 * :" + s.realname); + return true; + }; + + auto disconnectServer = [&](int srvIdx, const std::string& reason = "Bananarchy IRC") { + if (srvIdx < 0 || srvIdx >= static_cast(servers.size())) return; + auto& s = servers[srvIdx]; + if (s.net && s.net->isConnected()) { + sendIrcRaw(srvIdx, "QUIT :" + reason); + s.net->close(); + } + s.state = "DISC"; + s.registered = false; + int stBuf = findOrCreateBuffer(srvIdx, "*status*"); + buffers[stBuf].append("*", "Disconnected from " + s.label, false, true); + }; + + bool visible = false; + int activeTab = 0; // 0=Chat, 1=Buffers, 2=Servers + int chatScrollBack = 0; + std::string chatInput; + int selectedRow = 0; + int scrollOffset = 0; + bool menuOpen = false; + int menuSel = 0; + + // Server editor modal + bool editModalOpen = false; + int editSrvIdx = -1; + int editFieldIdx = 0; + IrcServerConfig editDraft; + + auto handleIncomingIrcLine = [&](int srvIdx, std::string line) { + if (line.empty()) return; + auto& srv = servers[srvIdx]; + int stBuf = findOrCreateBuffer(srvIdx, "*status*"); + + // 1. Parse optional IRCv3 @tags prefix + std::string serverTimeHHMM; + if (line[0] == '@') { + size_t sp = line.find(' '); + if (sp != std::string::npos) { + std::string tags = line.substr(1, sp - 1); + line = trimStr(line.substr(sp + 1)); + size_t tpos = tags.find("time="); + if (tpos != std::string::npos) { + size_t tend = tags.find(';', tpos); + std::string iso = tags.substr( + tpos + 5, (tend == std::string::npos) ? std::string::npos : (tend - tpos - 5)); + size_t tchar = iso.find('T'); + if (tchar != std::string::npos && tchar + 6 <= iso.size()) { + serverTimeHHMM = iso.substr(tchar + 1, 5); + } + } + } + } + + // 2. Parse prefix (:nick!user@host) + std::string prefix; + std::string senderNick = "*"; + if (!line.empty() && line[0] == ':') { + size_t sp = line.find(' '); + if (sp != std::string::npos) { + prefix = line.substr(1, sp - 1); + line = trimStr(line.substr(sp + 1)); + size_t bang = prefix.find('!'); + senderNick = (bang == std::string::npos) ? prefix : prefix.substr(0, bang); + } + } + + // 3. Split command and args / trailing (:...) + std::string trailing; + size_t trailPos = line.find(" :"); + std::string head = (trailPos == std::string::npos) ? line : line.substr(0, trailPos); + if (trailPos != std::string::npos) { + trailing = line.substr(trailPos + 2); + } + std::istringstream hss(head); + std::string cmd; + hss >> cmd; + std::vector params; + std::string p; + while (hss >> p) params.push_back(p); + cmd = toLowerStr(cmd); + + if (cmd == "ping") { + sendIrcRaw(srvIdx, "PONG :" + (trailing.empty() ? (params.empty() ? "server" : params[0]) : trailing)); + return; + } + + if (cmd == "cap") { + std::string sub = (params.size() >= 2) ? toLowerStr(params[1]) : ""; + if (sub == "ls") { + std::string reqCaps; + std::string avail = toLowerStr(trailing); + const char* want[] = { + "sasl", "server-time", "message-tags", "multi-prefix", + "away-notify", "account-notify", "chghost", "cap-notify" + }; + for (const char* w : want) { + if (avail.find(w) != std::string::npos) { + if (std::strcmp(w, "sasl") == 0 && srv.saslUser.empty()) continue; + if (!reqCaps.empty()) reqCaps.push_back(' '); + reqCaps += w; + } + } + if (!reqCaps.empty()) { + sendIrcRaw(srvIdx, "CAP REQ :" + reqCaps); + } else { + srv.capNegotiating = false; + sendIrcRaw(srvIdx, "CAP END"); + } + } else if (sub == "ack") { + if (toLowerStr(trailing).find("sasl") != std::string::npos && + !srv.saslUser.empty()) { + srv.saslPending = true; + sendIrcRaw(srvIdx, "AUTHENTICATE PLAIN"); + } else { + srv.capNegotiating = false; + sendIrcRaw(srvIdx, "CAP END"); + } + } else if (sub == "nak") { + srv.capNegotiating = false; + sendIrcRaw(srvIdx, "CAP END"); + } + return; + } + + if (cmd == "authenticate") { + if ((trailing == "+" || (!params.empty() && params[0] == "+")) && + srv.saslPending) { + std::string rawAuth; + rawAuth.push_back('\0'); + rawAuth += srv.saslUser; + rawAuth.push_back('\0'); + rawAuth += srv.saslPass; + sendIrcRaw(srvIdx, "AUTHENTICATE " + base64EncodeStr(rawAuth)); + } + return; + } + + if (cmd == "903" || cmd == "904" || cmd == "905") { + srv.saslPending = false; + srv.capNegotiating = false; + sendIrcRaw(srvIdx, "CAP END"); + buffers[stBuf].append("*", (cmd == "903") ? "SASL auth succeeded" : "SASL auth failed", + false, true, serverTimeHHMM); + return; + } + + if (cmd == "001") { + srv.registered = true; + srv.state = srv.useTls ? "ONLINE(TLS)" : "ONLINE"; + buffers[stBuf].append("*", trailing, false, true, serverTimeHHMM); + if (!srv.autoJoin.empty()) { + std::stringstream ss(srv.autoJoin); + std::string ch; + while (std::getline(ss, ch, ',')) { + ch = trimStr(ch); + if (!ch.empty()) { + sendIrcRaw(srvIdx, "JOIN " + ch); + } + } + } + return; + } + + if (cmd == "join") { + std::string chan = !trailing.empty() ? trailing : (params.empty() ? "" : params[0]); + if (!chan.empty()) { + int bIdx = findOrCreateBuffer(srvIdx, chan); + buffers[bIdx].append("*", senderNick + " joined " + chan, false, true, serverTimeHHMM); + if (toLowerStr(senderNick) == toLowerStr(srv.nick)) { + activeBufIdx = bIdx; + } + } + return; + } + + if (cmd == "part") { + std::string chan = params.empty() ? "" : params[0]; + if (!chan.empty()) { + int bIdx = findOrCreateBuffer(srvIdx, chan); + buffers[bIdx].append("*", senderNick + " left " + chan, false, true, serverTimeHHMM); + } + return; + } + + if (cmd == "privmsg" || cmd == "notice") { + std::string target = params.empty() ? "*status*" : params[0]; + bool isChan = (!target.empty() && (target[0] == '#' || target[0] == '&')); + std::string bufName = isChan ? target : (cmd == "notice" ? "*status*" : senderNick); + int bIdx = findOrCreateBuffer(srvIdx, bufName); + bool hl = (!isChan && cmd == "privmsg") || + (toLowerStr(trailing).find(toLowerStr(srv.nick)) != std::string::npos); + + std::string displayTxt = trailing; + if (displayTxt.size() >= 7 && displayTxt[0] == '\x01' && + displayTxt.rfind("\x01" "ACTION ", 0) == 0) { + displayTxt = "* " + senderNick + " " + + displayTxt.substr(8, displayTxt.size() - 9); + buffers[bIdx].append("*", displayTxt, hl, false, serverTimeHHMM); + } else { + buffers[bIdx].append(senderNick, displayTxt, hl, cmd == "notice", + serverTimeHHMM); + } + if (bIdx != activeBufIdx || !visible) { + buffers[bIdx].unreadCount++; + if (hl) { + buffers[bIdx].hasHighlight = true; + neoui_vibrate(60); + } + } + return; + } + + if (cmd == "332" && params.size() >= 2) { + int bIdx = findOrCreateBuffer(srvIdx, params[1]); + buffers[bIdx].topic = trailing; + buffers[bIdx].append("*", "Topic: " + trailing, false, true, serverTimeHHMM); + return; + } + + if (!trailing.empty()) { + buffers[stBuf].append(senderNick, trailing, false, true, serverTimeHHMM); + } + }; + + auto submitChatLine = [&]() { + chatInput = neoui_input_get_text(); + std::string line = trimStr(chatInput); + if (line.empty()) return; + chatInput.clear(); + neoui_input_reset(""); + + activeBufIdx = std::clamp(activeBufIdx, 0, static_cast(buffers.size()) - 1); + int srvIdx = buffers[activeBufIdx].serverIdx; + auto& srv = servers[srvIdx]; + + if (line[0] == '/') { + std::istringstream iss(line.substr(1)); + std::string cmd; + iss >> cmd; + std::string rest; + std::getline(iss, rest); + rest = trimStr(rest); + std::string low = toLowerStr(cmd); + + if (low == "join" || low == "j") { + if (!rest.empty()) { + if (rest[0] != '#' && rest[0] != '&') rest = "#" + rest; + sendIrcRaw(srvIdx, "JOIN " + rest); + activeBufIdx = findOrCreateBuffer(srvIdx, rest); + } + } else if (low == "part" || low == "leave") { + std::string ch = buffers[activeBufIdx].name; + if (!ch.empty() && ch[0] == '#') { + sendIrcRaw(srvIdx, "PART " + ch + (rest.empty() ? "" : (" :" + rest))); + } + } else if (low == "msg" || low == "query") { + std::istringstream mss(rest); + std::string target, text; + mss >> target; + std::getline(mss, text); + text = trimStr(text); + if (!target.empty()) { + int bIdx = findOrCreateBuffer(srvIdx, target); + activeBufIdx = bIdx; + if (!text.empty()) { + sendIrcRaw(srvIdx, "PRIVMSG " + target + " :" + text); + buffers[bIdx].append(srv.nick, text); + } + } + } else if (low == "me") { + std::string target = buffers[activeBufIdx].name; + if (target != "*status*") { + sendIrcRaw(srvIdx, "PRIVMSG " + target + " :\x01" "ACTION " + rest + "\x01"); + buffers[activeBufIdx].append("*", "* " + srv.nick + " " + rest); + } + } else if (low == "nick") { + if (!rest.empty()) { + srv.nick = rest; + sendIrcRaw(srvIdx, "NICK " + rest); + } + } else if (low == "clear") { + buffers[activeBufIdx].lines.clear(); + } else if (low == "connect") { + connectServer(srvIdx); + } else if (low == "disconnect" || low == "quit") { + disconnectServer(srvIdx, rest.empty() ? "Bye" : rest); + } else if (low == "raw" || low == "quote") { + sendIrcRaw(srvIdx, rest); + } else { + sendIrcRaw(srvIdx, cmd + (rest.empty() ? "" : (" " + rest))); + } + return; + } + + std::string target = buffers[activeBufIdx].name; + if (target == "*status*") { + sendIrcRaw(srvIdx, line); + buffers[activeBufIdx].append(srv.nick, line, false, true); + } else { + if (!sendIrcRaw(srvIdx, "PRIVMSG " + target + " :" + line)) { + buffers[activeBufIdx].append("!", "Not connected (Server -> Connect)", false, true); + } else { + buffers[activeBufIdx].append(srv.nick, line); + } + } + }; + + auto syncEditInput = [&]() { + if (!editModalOpen) { + neoui_input_reset(chatInput.c_str()); + return; + } + if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str()); + else if (editFieldIdx == 1) neoui_input_reset(editDraft.host.c_str()); + else if (editFieldIdx == 2) { + neoui_input_set_mode(NEO_INPUT_123); + neoui_input_reset(std::to_string(editDraft.port).c_str()); + } else if (editFieldIdx == 4) neoui_input_reset(editDraft.nick.c_str()); + else if (editFieldIdx == 5) neoui_input_reset(editDraft.saslUser.c_str()); + else if (editFieldIdx == 6) neoui_input_reset(editDraft.saslPass.c_str()); + else if (editFieldIdx == 7) neoui_input_reset(editDraft.autoJoin.c_str()); + }; + + auto applyEditInput = [&]() { + std::string txt = neoui_input_get_text(); + if (!editModalOpen) { + chatInput = txt; + return; + } + if (editFieldIdx == 0) editDraft.label = txt; + else if (editFieldIdx == 1) editDraft.host = txt; + else if (editFieldIdx == 2) editDraft.port = std::max(1, std::atoi(txt.c_str())); + else if (editFieldIdx == 4) { + editDraft.nick = txt; + editDraft.username = txt; + } else if (editFieldIdx == 5) editDraft.saslUser = txt; + else if (editFieldIdx == 6) editDraft.saslPass = txt; + else if (editFieldIdx == 7) editDraft.autoJoin = txt; + }; + + auto render = [&]() { + if (!visible) return; + neo.bindAsActiveContext(); + neoui_begin_frame(); + + activeBufIdx = std::clamp(activeBufIdx, 0, static_cast(buffers.size()) - 1); + auto& curBuf = buffers[activeBufIdx]; + curBuf.unreadCount = 0; + curBuf.hasHighlight = false; + int srvIdx = std::clamp(curBuf.serverIdx, 0, static_cast(servers.size()) - 1); + + neoui_draw_header(kIconGlobe, NEO_TEXT_GREEN, curBuf.name.c_str(), + servers[srvIdx].state.c_str()); + neoui_draw_tabs("Chat|Buffers|Servers", activeTab, 34, 24); + + constexpr int kBodyY = 58; + constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; + + if (activeTab == 0) { + int msgAreaH = kBodyH - 48; + int lineH = 16; + int maxLines = msgAreaH / lineH; + int total = static_cast(curBuf.lines.size()); + chatScrollBack = std::clamp(chatScrollBack, 0, std::max(0, total - maxLines)); + int startIdx = std::max(0, total - maxLines - chatScrollBack); + + for (int i = 0; i < maxLines && (startIdx + i) < total; ++i) { + const auto& m = curBuf.lines[startIdx + i]; + int y = kBodyY + 2 + i * lineH; + std::string row = m.timeStr + " "; + int col = NEO_TEXT_LIGHT; + if (m.isHighlight) col = NEO_TEXT_YELLOW; + else if (m.isSystem) col = NEO_TEXT_MUTED; + if (m.sender == "*") { + row += "* " + m.text; + } else { + row += "<" + m.sender + "> " + m.text; + } + neoui_draw_text(NEO_FONT_SMALL, col, 4, y, lineH, row.c_str(), 232); + } + + neoui_draw_input_box(4, kBodyY + msgAreaH, 232, 26, 1, "", + neoui_input_get_text(), "Message or /join #chan", 0); + neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20, + "[OK/Call] Send [*] Mode"); + neoui_draw_softkeys("Menu", "SEND", "BG/Close"); + } else if (activeTab == 1) { + int rowH = 38; + int maxVis = kBodyH / rowH; + selectedRow = std::clamp(selectedRow, 0, static_cast(buffers.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(buffers.size()); ++i) { + int idx = scrollOffset + i; + const auto& b = buffers[idx]; + std::string srvLbl = servers[b.serverIdx].label; + std::string badge = b.unreadCount > 0 ? ("+" + std::to_string(b.unreadCount)) : ""; + int col = b.hasHighlight ? NEO_TEXT_YELLOW + : (idx == activeBufIdx ? NEO_TEXT_GREEN : NEO_TEXT_LIGHT); + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconList, col, b.name.c_str(), srvLbl.c_str(), + badge.c_str()); + } + neoui_draw_softkeys("Menu", "OPEN", "Back"); + } else { + int rowH = 42; + int maxVis = kBodyH / rowH; + selectedRow = std::clamp(selectedRow, 0, static_cast(servers.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(servers.size()); ++i) { + int idx = scrollOffset + i; + const auto& s = servers[idx]; + std::string sub = s.nick + "@" + s.host + ":" + std::to_string(s.port); + int col = (s.state.rfind("ONLINE", 0) == 0) ? NEO_TEXT_GREEN : NEO_TEXT_MUTED; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconGlobe, col, s.label.c_str(), sub.c_str(), + s.state.c_str()); + } + neoui_draw_softkeys("Menu", "CONN/DISC", "Back"); + } + + if (editModalOpen) { + neoui_draw_modal_box(4, 28, 232, 238, kIconEdit, NEO_TEXT_YELLOW, + editSrvIdx < 0 ? "Add IRC Server" : "Edit IRC Server"); + const char* labels[9] = { + "Label", "Host", "Port", "TLS", "Nick", "SASL User", + "SASL Pass", "AutoJoin", "BG Mode" + }; + std::string vals[9] = { + editDraft.label, editDraft.host, std::to_string(editDraft.port), + editDraft.useTls ? "ON" : "OFF", editDraft.nick, editDraft.saslUser, + editDraft.saslPass.empty() ? "" : "******", editDraft.autoJoin, + editDraft.keepInBackground ? "ON" : "OFF" + }; + int startF = std::max(0, std::min(editFieldIdx - 2, 5)); + for (int i = 0; i < 4 && (startF + i) < 9; ++i) { + int f = startF + i; + bool isText = (f != 3 && f != 8); + std::string v = (f == editFieldIdx && isText) ? neoui_input_get_text() : vals[f]; + std::string rowStr = std::string(labels[f]) + ": " + v; + neoui_draw_list_row(f, 56 + i * 36, 36, f == editFieldIdx ? 1 : 0, + kIconKey, f == editFieldIdx ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, + rowStr.c_str(), "", ""); + } + neoui_draw_multitap_bar(6, 204, 228, 22, "[*] Mode [OK] Toggle"); + neoui_draw_softkeys("Save", "EDIT", "Cancel"); + } else if (menuOpen) { + neoui_draw_menu_popup( + "Connect / Disconnect|Add Server|Edit Selected Server|Join #bananarchy|Close Buffer", + nullptr, menuSel, 5); + } + + neoui_end_frame(); + }; + + auto openWindow = [&]() { + if (isPhonePasscodeLocked()) return; + writeIntFile(activePidPath, static_cast(::getpid())); + closeOtherPlugins("irc"); + visible = true; + neoui_show(); + syncEditInput(); + render(); + }; + + auto closeWindow = [&]() { + if (!visible) return; + visible = false; + editModalOpen = false; + menuOpen = false; + for (size_t i = 0; i < servers.size(); ++i) { + if (!servers[i].keepInBackground) { + disconnectServer(static_cast(i)); + } + } + neoui_hide(); + ::unlink(activePidPath.c_str()); + }; + + if (!isPreload) { + openWindow(); + } + + while (gRunning) { + for (const std::string& cmd : readFifoLines(fifoFd)) { + if (cmd == "NOP") continue; + if (cmd == "CLOSE") closeWindow(); + else if (cmd == "RELOAD_THEME") { + neo.reloadTheme(); + if (visible) render(); + } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + openWindow(); + } + } + + // Pump all active IRC server sockets (even while UI window is hidden in background mode!) + for (size_t i = 0; i < servers.size(); ++i) { + if (!servers[i].net || !servers[i].net->isConnected()) continue; + int r = servers[i].net->pumpRx(0); + std::string line; + bool anyLine = false; + while (servers[i].net->popLine(line)) { + handleIncomingIrcLine(static_cast(i), line); + anyLine = true; + } + if (r < 0) { + servers[i].net->close(); + servers[i].state = "DISC"; + servers[i].registered = false; + int stBuf = findOrCreateBuffer(static_cast(i), "*status*"); + buffers[stBuf].append("!", "Connection closed by server", false, true); + anyLine = true; + } + if (anyLine && visible) { + render(); + } + } + + if (visible) { + neo.bindAsActiveContext(); + int ev = neoui_poll_event(0); + while (ev != NEO_EV_NONE) { + if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { + render(); + } else if (ev == NEO_EV_CLOSE_REQ) { + closeWindow(); + break; + } else if (ev == NEO_EV_SOFTKEY_LEFT) { + if (editModalOpen) { + applyEditInput(); + if (editSrvIdx < 0) { + servers.push_back(std::move(editDraft)); + findOrCreateBuffer(static_cast(servers.size()) - 1, "*status*"); + } else if (editSrvIdx < static_cast(servers.size())) { + servers[editSrvIdx].label = editDraft.label; + servers[editSrvIdx].host = editDraft.host; + servers[editSrvIdx].port = editDraft.port; + servers[editSrvIdx].useTls = editDraft.useTls; + servers[editSrvIdx].nick = editDraft.nick; + servers[editSrvIdx].username = editDraft.username; + servers[editSrvIdx].saslUser = editDraft.saslUser; + servers[editSrvIdx].saslPass = editDraft.saslPass; + servers[editSrvIdx].autoJoin = editDraft.autoJoin; + servers[editSrvIdx].keepInBackground = editDraft.keepInBackground; + } + saveIrcServers(servers); + editModalOpen = false; + syncEditInput(); + render(); + } else { + menuOpen = !menuOpen; + menuSel = 0; + render(); + } + } else if (ev == NEO_EV_SOFTKEY_RIGHT) { + if (editModalOpen) { + editModalOpen = false; + syncEditInput(); + render(); + } else if (menuOpen) { + menuOpen = false; + render(); + } else if (activeTab != 0) { + activeTab = 0; + syncEditInput(); + render(); + } else { + closeWindow(); + break; + } + } else if (ev == NEO_EV_KEY_PRESS) { + int k = neoui_event_key(); + if (menuOpen) { + if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5; + else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5; + else if (k == NEO_KEY_OK) { + menuOpen = false; + int srvIdx = buffers[activeBufIdx].serverIdx; + if (menuSel == 0) { + if (servers[srvIdx].net && servers[srvIdx].net->isConnected()) { + disconnectServer(srvIdx); + } else { + connectServer(srvIdx); + } + } else if (menuSel == 1) { + editSrvIdx = -1; + editDraft = IrcServerConfig{}; + editFieldIdx = 0; + editModalOpen = true; + syncEditInput(); + } else if (menuSel == 2) { + int idx = (activeTab == 2) ? selectedRow : srvIdx; + idx = std::clamp(idx, 0, static_cast(servers.size()) - 1); + editSrvIdx = idx; + editDraft.label = servers[idx].label; + editDraft.host = servers[idx].host; + editDraft.port = servers[idx].port; + editDraft.useTls = servers[idx].useTls; + editDraft.nick = servers[idx].nick; + editDraft.username = servers[idx].username; + editDraft.saslUser = servers[idx].saslUser; + editDraft.saslPass = servers[idx].saslPass; + editDraft.autoJoin = servers[idx].autoJoin; + editDraft.keepInBackground = servers[idx].keepInBackground; + editFieldIdx = 0; + editModalOpen = true; + syncEditInput(); + } else if (menuSel == 3) { + sendIrcRaw(srvIdx, "JOIN #bananarchy"); + activeBufIdx = findOrCreateBuffer(srvIdx, "#bananarchy"); + activeTab = 0; + } else if (menuSel == 4 && buffers[activeBufIdx].name != "*status*" && + buffers.size() > 1) { + buffers.erase(buffers.begin() + activeBufIdx); + activeBufIdx = 0; + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + menuOpen = false; + } + render(); + } else if (editModalOpen) { + if (k == NEO_KEY_UP) { + applyEditInput(); + editFieldIdx = (editFieldIdx + 8) % 9; + syncEditInput(); + } else if (k == NEO_KEY_DOWN) { + applyEditInput(); + editFieldIdx = (editFieldIdx + 1) % 9; + syncEditInput(); + } else if (k == NEO_KEY_OK) { + if (editFieldIdx == 3) { + editDraft.useTls = !editDraft.useTls; + editDraft.port = editDraft.useTls ? 6697 : 6667; + } else if (editFieldIdx == 8) { + editDraft.keepInBackground = !editDraft.keepInBackground; + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + neoui_input_backspace(); + applyEditInput(); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyEditInput(); + } + render(); + } else { + if (k == NEO_KEY_LEFT) { + applyEditInput(); + activeTab = (activeTab + 2) % 3; + selectedRow = 0; + scrollOffset = 0; + syncEditInput(); + } else if (k == NEO_KEY_RIGHT) { + applyEditInput(); + activeTab = (activeTab + 1) % 3; + selectedRow = 0; + scrollOffset = 0; + syncEditInput(); + } else if (activeTab == 0) { + if (k == NEO_KEY_UP) ++chatScrollBack; + else if (k == NEO_KEY_DOWN && chatScrollBack > 0) --chatScrollBack; + else if (k == NEO_KEY_OK || k == NEO_KEY_CALL) { + submitChatLine(); + chatScrollBack = 0; + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + if (!std::string(neoui_input_get_text()).empty()) { + neoui_input_backspace(); + applyEditInput(); + } else { + closeWindow(); + break; + } + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyEditInput(); + } else if (k == NEO_KEY_END) { + closeWindow(); + break; + } + } else if (activeTab == 1) { + if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow; + else if (k == NEO_KEY_DOWN) ++selectedRow; + else if (k == NEO_KEY_OK) { + activeBufIdx = std::clamp(selectedRow, 0, + static_cast(buffers.size()) - 1); + activeTab = 0; + chatScrollBack = 0; + syncEditInput(); + } + } else if (activeTab == 2) { + if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow; + else if (k == NEO_KEY_DOWN) ++selectedRow; + else if (k == NEO_KEY_OK) { + int idx = std::clamp(selectedRow, 0, + static_cast(servers.size()) - 1); + if (servers[idx].net && servers[idx].net->isConnected()) { + disconnectServer(idx); + } else { + connectServer(idx); + } + } + } + render(); + } + } + ev = neoui_poll_event(0); + } + } else { + while (XPending(neo.dpy) > 0) { + XEvent xev; + XNextEvent(neo.dpy, &xev); + } + } + + // Build pollfd array across X11, FIFO, and all active IRC server sockets + std::vector pfds; + pfds.push_back({ ConnectionNumber(neo.dpy), POLLIN, 0 }); + if (fifoFd >= 0) pfds.push_back({ fifoFd, POLLIN, 0 }); + for (const auto& s : servers) { + if (s.net && s.net->isConnected() && s.net->fd() >= 0) { + pfds.push_back({ s.net->fd(), POLLIN, 0 }); + } + } + int timeoutMs = visible ? (neoui_input_is_tap_active() ? 150 : 1000) : -1; + ::poll(pfds.data(), static_cast(pfds.size()), timeoutMs); + } + + for (size_t i = 0; i < servers.size(); ++i) { + disconnectServer(static_cast(i)); + } + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(getPluginFifoPath("irc").c_str()); + ::unlink(daemonPidPath.c_str()); + return 0; +} + +int irc_plugin_init(const DwmHostApi* host) { + if (host && host->spawn_plugin) { + host->spawn_plugin("irc", "--preload"); + } + return 0; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { + DWM_PLUGIN_API_VERSION, + "irc", + "Multi-server IRCv3 + TLS client with background mode", + irc_plugin_init, + nullptr, + nullptr, + nullptr, + nullptr, + irc_run_main +}; diff --git a/src/dwm-plugins/net_tls.h b/src/dwm-plugins/net_tls.h new file mode 100644 index 0000000..8df94e8 --- /dev/null +++ b/src/dwm-plugins/net_tls.h @@ -0,0 +1,738 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Shared C++20 TCP / OpenSSL TLS / STARTTLS / Digest / MIME / HTTPS helpers +// for Bananarchy NeoUI DWM plugins (SIP, Email, IRC, SmallWeb, GPS/OSM). + +#ifndef DWM_PLUGINS_NET_TLS_H +#define DWM_PLUGINS_NET_TLS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "phone_data.h" + +namespace bananarchy { + +inline void ensureOpenSslInit() { + static bool initialized = false; + if (!initialized) { + OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | + OPENSSL_INIT_LOAD_CRYPTO_STRINGS, + nullptr); + initialized = true; + } +} + +inline std::string md5Hex(const std::string& input) { + ensureOpenSslInit(); + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int digestLen = 0; + EVP_MD_CTX* ctx = EVP_MD_CTX_new(); + if (!ctx) { + return ""; + } + if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) != 1 || + EVP_DigestUpdate(ctx, input.data(), input.size()) != 1 || + EVP_DigestFinal_ex(ctx, digest, &digestLen) != 1) { + EVP_MD_CTX_free(ctx); + return ""; + } + EVP_MD_CTX_free(ctx); + char hex[64]; + for (unsigned int i = 0; i < digestLen && i < 16; ++i) { + std::snprintf(hex + i * 2, 3, "%02x", digest[i]); + } + hex[digestLen * 2] = '\0'; + return std::string(hex); +} + +inline std::string randomHexToken(size_t numBytes = 8) { + ensureOpenSslInit(); + std::vector buf(numBytes); + if (RAND_bytes(buf.data(), static_cast(numBytes)) != 1) { + uint64_t t = static_cast(nowMs()) ^ + (static_cast(::getpid()) << 16); + for (size_t i = 0; i < numBytes; ++i) { + buf[i] = static_cast((t >> ((i % 8) * 8)) & 0xff); + t = t * 6364136223846793005ULL + 1442695040888963407ULL; + } + } + std::string out; + out.reserve(numBytes * 2); + char tmp[4]; + for (size_t i = 0; i < numBytes; ++i) { + std::snprintf(tmp, sizeof(tmp), "%02x", buf[i]); + out += tmp; + } + return out; +} + +inline std::string base64Encode(const void* rawData, size_t len) { + static constexpr char kTable[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const auto* in = static_cast(rawData); + std::string out; + out.reserve(((len + 2) / 3) * 4); + for (size_t i = 0; i < len; i += 3) { + uint32_t v = static_cast(in[i]) << 16; + if (i + 1 < len) v |= static_cast(in[i + 1]) << 8; + if (i + 2 < len) v |= static_cast(in[i + 2]); + out.push_back(kTable[(v >> 18) & 0x3f]); + out.push_back(kTable[(v >> 12) & 0x3f]); + out.push_back((i + 1 < len) ? kTable[(v >> 6) & 0x3f] : '='); + out.push_back((i + 2 < len) ? kTable[v & 0x3f] : '='); + } + return out; +} + +inline std::string base64EncodeStr(const std::string& s) { + return base64Encode(s.data(), s.size()); +} + +inline std::string base64Decode(const std::string& input) { + std::string out; + out.reserve((input.size() * 3) / 4); + uint32_t val = 0; + int valb = -8; + for (unsigned char c : input) { + int d = -1; + if (c >= 'A' && c <= 'Z') d = c - 'A'; + else if (c >= 'a' && c <= 'z') d = c - 'a' + 26; + else if (c >= '0' && c <= '9') d = c - '0' + 52; + else if (c == '+') d = 62; + else if (c == '/') d = 63; + else if (c == '=') break; + else continue; + val = (val << 6) + static_cast(d); + valb += 6; + if (valb >= 0) { + out.push_back(static_cast((val >> valb) & 0xff)); + valb -= 8; + } + } + return out; +} + +inline std::string decodeQuotedPrintable(const std::string& input, + bool underscoreAsSpace = false) { + std::string out; + out.reserve(input.size()); + for (size_t i = 0; i < input.size(); ++i) { + if (input[i] == '=' && i + 1 < input.size()) { + if (input[i + 1] == '\r' && i + 2 < input.size() && input[i + 2] == '\n') { + i += 2; + continue; + } + if (input[i + 1] == '\n') { + i += 1; + continue; + } + if (i + 2 < input.size()) { + int hi = themeHexNibble(input[i + 1]); + int lo = themeHexNibble(input[i + 2]); + if (hi >= 0 && lo >= 0) { + out.push_back(static_cast((hi << 4) | lo)); + i += 2; + continue; + } + } + } else if (underscoreAsSpace && input[i] == '_') { + out.push_back(' '); + continue; + } + out.push_back(input[i]); + } + return out; +} + +// Decode RFC 2047 encoded words (=?utf-8?B?...?= or =?utf-8?Q?...?=) +inline std::string decodeMimeHeader(const std::string& raw) { + std::string out; + size_t pos = 0; + while (pos < raw.size()) { + size_t start = raw.find("=?", pos); + if (start == std::string::npos) { + out.append(raw.substr(pos)); + break; + } + std::string between = raw.substr(pos, start - pos); + bool onlySpace = !out.empty(); + for (char c : between) { + if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { + onlySpace = false; + break; + } + } + if (!onlySpace) { + out.append(between); + } + size_t q1 = raw.find('?', start + 2); + if (q1 == std::string::npos || q1 + 3 >= raw.size() || raw[q1 + 2] != '?') { + out.append(raw.substr(start, 2)); + pos = start + 2; + continue; + } + char enc = static_cast(std::toupper(static_cast(raw[q1 + 1]))); + size_t end = raw.find("?=", q1 + 3); + if (end == std::string::npos) { + out.append(raw.substr(start)); + break; + } + std::string payload = raw.substr(q1 + 3, end - (q1 + 3)); + if (enc == 'B') { + out.append(base64Decode(payload)); + } else if (enc == 'Q') { + out.append(decodeQuotedPrintable(payload, true)); + } else { + out.append(payload); + } + pos = end + 2; + } + // Strip CR/LF in single-line headers + std::string clean; + clean.reserve(out.size()); + for (char c : out) { + if (c == '\r' || c == '\n') { + if (!clean.empty() && clean.back() != ' ') { + clean.push_back(' '); + } + } else { + clean.push_back(c); + } + } + return trimStr(clean); +} + +inline std::string stripHtmlTags(const std::string& html) { + std::string out; + out.reserve(html.size()); + bool inTag = false; + bool inStyleOrScript = false; + std::string tagName; + for (size_t i = 0; i < html.size(); ++i) { + char c = html[i]; + if (c == '<') { + inTag = true; + tagName.clear(); + continue; + } + if (c == '>') { + inTag = false; + std::string low = toLowerStr(trimStr(tagName)); + if (low.rfind("script", 0) == 0 || low.rfind("style", 0) == 0) { + inStyleOrScript = true; + } else if (low.rfind("/script", 0) == 0 || low.rfind("/style", 0) == 0) { + inStyleOrScript = false; + } else if (low == "br" || low == "br/" || low == "p" || low == "/p" || + low == "div" || low == "/div" || low == "li" || low == "tr") { + if (!out.empty() && out.back() != '\n') { + out.push_back('\n'); + } + } + continue; + } + if (inTag) { + if (tagName.size() < 24) { + tagName.push_back(c); + } + continue; + } + if (inStyleOrScript) { + continue; + } + if (c == '&') { + size_t semi = html.find(';', i + 1); + if (semi != std::string::npos && semi - i <= 10) { + std::string ent = toLowerStr(html.substr(i + 1, semi - i - 1)); + if (ent == "amp") { out.push_back('&'); i = semi; continue; } + if (ent == "lt") { out.push_back('<'); i = semi; continue; } + if (ent == "gt") { out.push_back('>'); i = semi; continue; } + if (ent == "quot") { out.push_back('"'); i = semi; continue; } + if (ent == "apos" || ent == "#39") { out.push_back('\''); i = semi; continue; } + if (ent == "nbsp") { out.push_back(' '); i = semi; continue; } + } + } + out.push_back(c); + } + return trimStr(out); +} + +class NetStream { + public: + NetStream() = default; + ~NetStream() { close(); } + + NetStream(const NetStream&) = delete; + NetStream& operator=(const NetStream&) = delete; + + int fd() const { return fd_; } + bool isConnected() const { return fd_ >= 0; } + bool isTls() const { return ssl_ != nullptr; } + const std::string& lastError() const { return lastErr_; } + + void close() { + if (ssl_) { + SSL_shutdown(ssl_); + SSL_free(ssl_); + ssl_ = nullptr; + } + if (ctx_) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + if (fd_ >= 0) { + ::close(fd_); + fd_ = -1; + } + rxBuf_.clear(); + } + + bool connectTcp(const std::string& host, int port, int timeoutMs = 6000) { + close(); + struct addrinfo hints {}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + struct addrinfo* res = nullptr; + char portStr[16]; + std::snprintf(portStr, sizeof(portStr), "%d", port); + int rc = ::getaddrinfo(host.c_str(), portStr, &hints, &res); + if (rc != 0 || !res) { + lastErr_ = std::string("DNS failed: ") + host; + return false; + } + + int sock = -1; + for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) { + sock = ::socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, + p->ai_protocol); + if (sock < 0) continue; + int one = 1; + ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + int c = ::connect(sock, p->ai_addr, p->ai_addrlen); + if (c == 0) { + break; + } + if (errno == EINPROGRESS) { + struct pollfd pfd { sock, POLLOUT, 0 }; + if (::poll(&pfd, 1, timeoutMs) > 0 && (pfd.revents & POLLOUT)) { + int soErr = 0; + socklen_t sl = sizeof(soErr); + if (::getsockopt(sock, SOL_SOCKET, SO_ERROR, &soErr, &sl) == 0 && + soErr == 0) { + break; + } + } + } + ::close(sock); + sock = -1; + } + ::freeaddrinfo(res); + + if (sock < 0) { + lastErr_ = "Connection failed to " + host + ":" + portStr; + return false; + } + fd_ = sock; + return true; + } + + bool startTls(const std::string& serverName, int timeoutMs = 6000) { + if (fd_ < 0) { + lastErr_ = "Socket not connected"; + return false; + } + ensureOpenSslInit(); + ctx_ = SSL_CTX_new(TLS_client_method()); + if (!ctx_) { + lastErr_ = "SSL_CTX_new failed"; + return false; + } + SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr); + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + ssl_ = SSL_new(ctx_); + if (!ssl_) { + lastErr_ = "SSL_new failed"; + return false; + } + if (!serverName.empty()) { + SSL_set_tlsext_host_name(ssl_, serverName.c_str()); + } + SSL_set_fd(ssl_, fd_); + + int64_t deadline = nowMs() + timeoutMs; + while (nowMs() < deadline) { + int r = SSL_connect(ssl_); + if (r == 1) { + return true; + } + int err = SSL_get_error(ssl_, r); + if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { + struct pollfd pfd { + fd_, static_cast(err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT), 0 + }; + int waitMs = static_cast(std::max(10, deadline - nowMs())); + if (::poll(&pfd, 1, std::min(waitMs, 250)) < 0 && errno != EINTR) { + break; + } + continue; + } + break; + } + lastErr_ = "TLS handshake failed with " + serverName; + return false; + } + + bool sendAll(const void* data, size_t len, int timeoutMs = 5000) { + if (fd_ < 0) return false; + const auto* ptr = static_cast(data); + size_t sent = 0; + int64_t deadline = nowMs() + timeoutMs; + while (sent < len && nowMs() < deadline) { + if (ssl_) { + int w = SSL_write(ssl_, ptr + sent, static_cast(len - sent)); + if (w > 0) { + sent += static_cast(w); + continue; + } + int err = SSL_get_error(ssl_, w); + if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { + struct pollfd pfd { + fd_, static_cast(err == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT), 0 + }; + ::poll(&pfd, 1, 100); + continue; + } + lastErr_ = "TLS write failed"; + return false; + } else { + ssize_t w = ::send(fd_, ptr + sent, len - sent, MSG_NOSIGNAL); + if (w > 0) { + sent += static_cast(w); + continue; + } + if (w < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { + struct pollfd pfd { fd_, POLLOUT, 0 }; + ::poll(&pfd, 1, 100); + continue; + } + lastErr_ = "Socket write failed"; + return false; + } + } + return sent == len; + } + + bool sendStr(const std::string& s, int timeoutMs = 5000) { + return sendAll(s.data(), s.size(), timeoutMs); + } + + // Pump non-blocking incoming bytes into rxBuf_. Returns <0 on EOF/error. + int pumpRx(int waitMs = 0) { + if (fd_ < 0) return -1; + if (waitMs > 0 && (!ssl_ || SSL_pending(ssl_) == 0)) { + struct pollfd pfd { fd_, POLLIN, 0 }; + int pr = ::poll(&pfd, 1, waitMs); + if (pr == 0) return 0; + if (pr < 0) return (errno == EINTR) ? 0 : -1; + } + int totalAdded = 0; + char buf[4096]; + while (true) { + if (ssl_) { + int n = SSL_read(ssl_, buf, sizeof(buf)); + if (n > 0) { + rxBuf_.append(buf, static_cast(n)); + totalAdded += n; + continue; + } + int err = SSL_get_error(ssl_, n); + if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { + break; + } + return totalAdded > 0 ? totalAdded : -1; + } else { + ssize_t n = ::recv(fd_, buf, sizeof(buf), 0); + if (n > 0) { + rxBuf_.append(buf, static_cast(n)); + totalAdded += static_cast(n); + continue; + } + if (n == 0) { + return totalAdded > 0 ? totalAdded : -1; + } + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + break; + } + return totalAdded > 0 ? totalAdded : -1; + } + } + return totalAdded; + } + + bool popLine(std::string& outLine) { + size_t nl = rxBuf_.find('\n'); + if (nl == std::string::npos) { + return false; + } + outLine = rxBuf_.substr(0, nl); + if (!outLine.empty() && outLine.back() == '\r') { + outLine.pop_back(); + } + rxBuf_.erase(0, nl + 1); + return true; + } + + bool readLine(std::string& outLine, int timeoutMs = 5000) { + if (popLine(outLine)) { + return true; + } + int64_t deadline = nowMs() + timeoutMs; + while (nowMs() < deadline) { + int waitMs = static_cast(std::min(150, deadline - nowMs())); + int r = pumpRx(std::max(1, waitMs)); + if (popLine(outLine)) { + return true; + } + if (r < 0) { + if (!rxBuf_.empty()) { + outLine = rxBuf_; + if (!outLine.empty() && outLine.back() == '\r') outLine.pop_back(); + rxBuf_.clear(); + return true; + } + return false; + } + } + return popLine(outLine); + } + + bool readUntilClose(std::string& outData, size_t maxBytes = 2 * 1024 * 1024, + int timeoutMs = 8000) { + int64_t deadline = nowMs() + timeoutMs; + while (nowMs() < deadline && rxBuf_.size() < maxBytes) { + int waitMs = static_cast(std::min(200, deadline - nowMs())); + int r = pumpRx(std::max(1, waitMs)); + if (r < 0) { + break; + } + } + outData = std::move(rxBuf_); + rxBuf_.clear(); + return !outData.empty(); + } + + std::string& rxBuffer() { return rxBuf_; } + + private: + int fd_ = -1; + SSL_CTX* ctx_ = nullptr; + SSL* ssl_ = nullptr; + std::string rxBuf_; + std::string lastErr_; +}; + +struct ParsedUrl { + std::string scheme; + std::string host; + int port = 0; + std::string path; + char gopherType = '1'; + std::string gopherSelector; +}; + +inline ParsedUrl parseUrl(const std::string& rawUrl, + const std::string& defaultScheme = "gopher") { + ParsedUrl u; + std::string s = trimStr(rawUrl); + size_t schemeEnd = s.find("://"); + std::string rest; + if (schemeEnd != std::string::npos) { + u.scheme = toLowerStr(s.substr(0, schemeEnd)); + rest = s.substr(schemeEnd + 3); + } else { + u.scheme = toLowerStr(defaultScheme); + rest = s; + } + + size_t slash = rest.find('/'); + std::string hostPort = (slash == std::string::npos) ? rest : rest.substr(0, slash); + u.path = (slash == std::string::npos) ? "/" : rest.substr(slash); + + if (!hostPort.empty() && hostPort.front() == '[') { + size_t rb = hostPort.find(']'); + if (rb != std::string::npos) { + u.host = hostPort.substr(1, rb - 1); + if (rb + 1 < hostPort.size() && hostPort[rb + 1] == ':') { + u.port = std::atoi(hostPort.substr(rb + 2).c_str()); + } + } else { + u.host = hostPort; + } + } else { + size_t colon = hostPort.rfind(':'); + if (colon != std::string::npos) { + u.host = hostPort.substr(0, colon); + u.port = std::atoi(hostPort.substr(colon + 1).c_str()); + } else { + u.host = hostPort; + } + } + + if (u.port <= 0) { + if (u.scheme == "gopher" || u.scheme == "gophers") u.port = 70; + else if (u.scheme == "gemini") u.port = 1965; + else if (u.scheme == "spartan") u.port = 300; + else if (u.scheme == "nex") u.port = 1900; + else if (u.scheme == "https") u.port = 443; + else if (u.scheme == "http") u.port = 80; + else u.port = 70; + } + + if (u.scheme == "gopher" || u.scheme == "gophers") { + if (u.path.size() >= 2 && u.path[0] == '/') { + u.gopherType = u.path[1]; + u.gopherSelector = u.path.substr(2); + } else { + u.gopherType = '1'; + u.gopherSelector = ""; + } + } + return u; +} + +// Minimal HTTP/1.1 + HTTPS GET client (handles Content-Length, chunked, redirects) +inline bool httpGet(const std::string& url, std::string& outBody, + std::string* outContentType = nullptr, + int timeoutMs = 7000, + const std::string& userAgent = "Bananarchy/1.0 (Linux armv7)") { + std::string currentUrl = url; + for (int redirects = 0; redirects < 4; ++redirects) { + ParsedUrl u = parseUrl(currentUrl, "https"); + if (u.host.empty()) return false; + NetStream net; + if (!net.connectTcp(u.host, u.port, timeoutMs)) { + return false; + } + if (u.scheme == "https" && !net.startTls(u.host, timeoutMs)) { + return false; + } + std::ostringstream req; + req << "GET " << (u.path.empty() ? "/" : u.path) << " HTTP/1.1\r\n" + << "Host: " << u.host << "\r\n" + << "User-Agent: " << userAgent << "\r\n" + << "Accept: */*\r\n" + << "Connection: close\r\n\r\n"; + if (!net.sendStr(req.str(), timeoutMs)) { + return false; + } + std::string raw; + if (!net.readUntilClose(raw, 4 * 1024 * 1024, timeoutMs)) { + return false; + } + size_t hdrEnd = raw.find("\r\n\r\n"); + size_t sepLen = 4; + if (hdrEnd == std::string::npos) { + hdrEnd = raw.find("\n\n"); + sepLen = 2; + } + if (hdrEnd == std::string::npos) { + return false; + } + std::string hdrs = raw.substr(0, hdrEnd); + std::string body = raw.substr(hdrEnd + sepLen); + + int statusCode = 0; + { + std::istringstream hss(hdrs); + std::string httpVer; + hss >> httpVer >> statusCode; + } + + bool chunked = 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) { + chunked = true; + } else if (k == "location") { + location = v; + } else if (k == "content-type" && outContentType) { + *outContentType = v; + } + } + + if ((statusCode == 301 || statusCode == 302 || statusCode == 303 || + statusCode == 307 || statusCode == 308) && !location.empty()) { + if (location.rfind("http://", 0) == 0 || location.rfind("https://", 0) == 0) { + currentUrl = location; + } else if (!location.empty() && location[0] == '/') { + currentUrl = u.scheme + "://" + u.host + location; + } else { + currentUrl = u.scheme + "://" + u.host + "/" + location; + } + continue; + } + if (statusCode < 200 || statusCode >= 300) { + return false; + } + + if (chunked) { + std::string unchunked; + size_t pos = 0; + while (pos < body.size()) { + size_t crlf = body.find("\r\n", pos); + if (crlf == std::string::npos) break; + std::string hexLen = trimStr(body.substr(pos, crlf - pos)); + size_t semi = hexLen.find(';'); + if (semi != std::string::npos) hexLen = hexLen.substr(0, semi); + unsigned long chunkLen = std::strtoul(hexLen.c_str(), nullptr, 16); + pos = crlf + 2; + if (chunkLen == 0) break; + if (pos + chunkLen > body.size()) { + unchunked.append(body.substr(pos)); + break; + } + unchunked.append(body.substr(pos, chunkLen)); + pos += chunkLen + 2; + } + outBody = std::move(unchunked); + } else { + outBody = std::move(body); + } + return true; + } + return false; +} + +} // namespace bananarchy + +#endif // DWM_PLUGINS_NET_TLS_H diff --git a/src/dwm-plugins/sip_plugin.cpp b/src/dwm-plugins/sip_plugin.cpp new file mode 100644 index 0000000..ec9a915 --- /dev/null +++ b/src/dwm-plugins/sip_plugin.cpp @@ -0,0 +1,1595 @@ +// SPDX-License-Identifier: GPL-2.0-only +// SIP VoIP DWM Plugin (sip.so / xsip) for Bananarchy (240x320) +// Features: +// - Preloaded standby SIP User Agent daemon with background REGISTER keepalive +// - Digest MD5 authentication (RFC 2617 / RFC 3261) for REGISTER and INVITE +// - Incoming call standby wakeup and full CallScreen (callscreen.so) integration +// - Bidirectional G.711 (PCMU/PCMA 8 kHz) RTP audio + RFC 2833 DTMF +// - NeoUI 3-tab interface: Dialer, Accounts, and Call History + +#include "../sxmo-dwm/dwm_plugin.h" +#include "net_tls.h" + +#include +#include +#include +#include + +namespace { + +using namespace bananarchy; + +volatile sig_atomic_t gRunning = 1; + +void handleSignal(int) { + gRunning = 0; +} + +// G.711 u-law and A-law codecs (ITU-T G.711) +uint8_t linearToUlaw(int16_t pcmVal) { + constexpr int kBias = 0x84; + constexpr int kClip = 32635; + int mask = (pcmVal < 0) ? 0x7f : 0xff; + if (pcmVal < 0) pcmVal = static_cast(-pcmVal); + if (pcmVal > kClip) pcmVal = kClip; + pcmVal = static_cast(pcmVal + kBias); + int seg = 0; + for (int thr = 0xFF; seg < 7 && pcmVal > thr; ++seg, thr = (thr << 1) | 1) { + } + uint8_t uval = static_cast((seg << 4) | ((pcmVal >> (seg + 3)) & 0x0f)); + return static_cast(uval ^ mask); +} + +int16_t ulawToLinear(uint8_t uval) { + uval = static_cast(~uval); + int t = (((uval & 0x0f) << 3) + 0x84) << ((uval & 0x70) >> 4); + return static_cast((uval & 0x80) ? (0x84 - t) : (t - 0x84)); +} + +uint8_t linearToAlaw(int16_t pcmVal) { + int mask = 0x55; + if (pcmVal >= 0) { + mask |= 0x80; + } else { + pcmVal = static_cast(-pcmVal - 1); + } + int seg = 0; + for (int thr = 0xFF; seg < 7 && pcmVal > thr; ++seg, thr = (thr << 1) | 1) { + } + uint8_t aval = (seg == 0) + ? static_cast((pcmVal >> 4) & 0x0f) + : static_cast((seg << 4) | ((pcmVal >> (seg + 3)) & 0x0f)); + return static_cast(aval ^ mask); +} + +int16_t alawToLinear(uint8_t aval) { + aval ^= 0x55; + int t = (aval & 0x0f) << 4; + int seg = (static_cast(aval) & 0x70) >> 4; + switch (seg) { + case 0: + t += 8; + break; + case 1: + t += 0x108; + break; + default: + t += 0x108; + t <<= seg - 1; + break; + } + return static_cast((aval & 0x80) ? t : -t); +} + +struct SipAccount { + bool enabled = true; + std::string label = "SIP Account"; + std::string username; + std::string authUser; + std::string password; + std::string domain; + int port = 5060; + std::string transport = "UDP"; // UDP, TCP, TLS + + // Runtime state + std::string regStatus = "OFF"; + int64_t lastRegAttemptMs = 0; + int64_t regExpiresAtMs = 0; + int cseq = 1; + std::string callId; + std::string fromTag; +}; + +struct SipCallLog { + std::string timestamp; + std::string direction; // IN, OUT, MISSED + std::string peerUri; + std::string accountLabel; + int durationSec = 0; +}; + +struct DigestChallenge { + bool valid = false; + bool isProxy = false; + std::string realm; + std::string nonce; + std::string opaque; + std::string qop; + std::string algorithm = "MD5"; +}; + +std::string getSipAccountsPath() { + return getHomeDirPath() + "/.config/sxmo/sip_accounts.tsv"; +} + +std::string getSipHistoryPath() { + return getHomeDirPath() + "/.local/share/sxmo/sip_calls.tsv"; +} + +std::vector loadSipAccounts() { + std::vector list; + std::ifstream in(getSipAccountsPath()); + std::string line; + while (std::getline(in, line)) { + line = trimStr(line); + if (line.empty() || line[0] == '#') continue; + std::vector cols; + std::stringstream ss(line); + std::string item; + while (std::getline(ss, item, '\t')) { + cols.push_back(item); + } + if (cols.size() >= 6) { + SipAccount a; + a.enabled = (cols[0] == "1" || toLowerStr(cols[0]) == "true"); + a.label = cols[1]; + a.username = cols[2]; + a.authUser = cols[3].empty() ? cols[2] : cols[3]; + a.password = cols[4]; + a.domain = cols[5]; + if (cols.size() >= 7 && !cols[6].empty()) { + a.port = std::max(1, std::atoi(cols[6].c_str())); + } + if (cols.size() >= 8 && !cols[7].empty()) { + a.transport = cols[7]; + } + a.regStatus = a.enabled ? "IDLE" : "OFF"; + a.callId = randomHexToken(8) + "@" + a.domain; + a.fromTag = randomHexToken(6); + list.push_back(a); + } + } + return list; +} + +void saveSipAccounts(const std::vector& list) { + std::string path = getSipAccountsPath(); + ContactBook::ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + for (const auto& a : list) { + out << (a.enabled ? "1" : "0") << "\t" + << a.label << "\t" + << a.username << "\t" + << (a.authUser.empty() ? a.username : a.authUser) << "\t" + << a.password << "\t" + << a.domain << "\t" + << a.port << "\t" + << a.transport << "\n"; + } +} + +std::vector loadSipHistory() { + std::vector list; + std::ifstream in(getSipHistoryPath()); + std::string line; + while (std::getline(in, line)) { + line = trimStr(line); + if (line.empty()) continue; + std::vector cols; + std::stringstream ss(line); + std::string item; + while (std::getline(ss, item, '\t')) { + cols.push_back(item); + } + if (cols.size() >= 4) { + SipCallLog c; + c.timestamp = cols[0]; + c.direction = cols[1]; + c.peerUri = cols[2]; + c.accountLabel = cols[3]; + if (cols.size() >= 5) c.durationSec = std::atoi(cols[4].c_str()); + list.push_back(c); + } + } + std::reverse(list.begin(), list.end()); + return list; +} + +void appendSipHistory(const std::string& dir, const std::string& peer, + const std::string& acctLabel, int durSec) { + std::string path = getSipHistoryPath(); + ContactBook::ensureParentDir(path); + time_t now = ::time(nullptr); + struct tm tmNow {}; + localtime_r(&now, &tmNow); + char ts[32]; + std::strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M", &tmNow); + std::ofstream out(path, std::ios::app); + if (out.is_open()) { + out << ts << "\t" << dir << "\t" << peer << "\t" << acctLabel << "\t" + << durSec << "\n"; + } +} + +std::string detectLocalIpForHost(const std::string& remoteHost) { + struct addrinfo hints {}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + struct addrinfo* res = nullptr; + if (::getaddrinfo(remoteHost.c_str(), "5060", &hints, &res) == 0 && res) { + int s = ::socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (s >= 0) { + if (::connect(s, res->ai_addr, res->ai_addrlen) == 0) { + struct sockaddr_in localAddr {}; + socklen_t sl = sizeof(localAddr); + if (::getsockname(s, reinterpret_cast(&localAddr), &sl) == 0) { + char ipBuf[INET_ADDRSTRLEN] = {0}; + if (::inet_ntop(AF_INET, &localAddr.sin_addr, ipBuf, sizeof(ipBuf))) { + ::close(s); + ::freeaddrinfo(res); + return std::string(ipBuf); + } + } + } + ::close(s); + } + ::freeaddrinfo(res); + } + return "127.0.0.1"; +} + +DigestChallenge parseDigestChallenge(const std::string& sipMsg) { + DigestChallenge ch; + std::istringstream iss(sipMsg); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + std::string low = toLowerStr(line); + bool isWww = (low.rfind("www-authenticate:", 0) == 0); + bool isProxy = (low.rfind("proxy-authenticate:", 0) == 0); + if (!isWww && !isProxy) continue; + size_t digestPos = low.find("digest"); + if (digestPos == std::string::npos) continue; + ch.valid = true; + ch.isProxy = isProxy; + std::string params = line.substr(digestPos + 6); + + auto extractParam = [&](const std::string& key) -> std::string { + std::string lowParams = toLowerStr(params); + size_t p = lowParams.find(key + "="); + if (p == std::string::npos) return ""; + p += key.size() + 1; + while (p < params.size() && params[p] == ' ') ++p; + if (p < params.size() && params[p] == '"') { + size_t e = params.find('"', p + 1); + if (e != std::string::npos) return params.substr(p + 1, e - p - 1); + } else { + size_t e = params.find(',', p); + return trimStr(params.substr( + p, (e == std::string::npos) ? std::string::npos : (e - p))); + } + return ""; + }; + + ch.realm = extractParam("realm"); + ch.nonce = extractParam("nonce"); + ch.opaque = extractParam("opaque"); + ch.qop = extractParam("qop"); + std::string alg = extractParam("algorithm"); + if (!alg.empty()) ch.algorithm = alg; + break; + } + return ch; +} + +std::string buildDigestAuthHeader(const DigestChallenge& ch, + const SipAccount& acct, + const std::string& method, + const std::string& uri) { + std::string user = acct.authUser.empty() ? acct.username : acct.authUser; + std::string ha1 = md5Hex(user + ":" + ch.realm + ":" + acct.password); + std::string ha2 = md5Hex(method + ":" + uri); + std::string cnonce = randomHexToken(4); + std::string nc = "00000001"; + bool useAuthQop = (toLowerStr(ch.qop).find("auth") != std::string::npos); + + std::string response; + if (useAuthQop) { + response = md5Hex(ha1 + ":" + ch.nonce + ":" + nc + ":" + cnonce + + ":auth:" + ha2); + } else { + response = md5Hex(ha1 + ":" + ch.nonce + ":" + ha2); + } + + std::ostringstream oss; + oss << (ch.isProxy ? "Proxy-Authorization" : "Authorization") + << ": Digest username=\"" << user << "\", realm=\"" << ch.realm + << "\", nonce=\"" << ch.nonce << "\", uri=\"" << uri + << "\", response=\"" << response << "\", algorithm=MD5"; + if (useAuthQop) { + oss << ", qop=auth, nc=" << nc << ", cnonce=\"" << cnonce << "\""; + } + if (!ch.opaque.empty()) { + oss << ", opaque=\"" << ch.opaque << "\""; + } + oss << "\r\n"; + return oss.str(); +} + +std::string getSipHeaderValue(const std::string& msg, const std::string& hdrName, + const std::string& compactName = "") { + std::istringstream iss(msg); + std::string line; + std::string lowName = toLowerStr(hdrName) + ":"; + std::string lowCompact = compactName.empty() ? "" : (toLowerStr(compactName) + ":"); + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty()) break; + std::string low = toLowerStr(line); + if (low.rfind(lowName, 0) == 0) { + return trimStr(line.substr(lowName.size())); + } + if (!lowCompact.empty() && low.rfind(lowCompact, 0) == 0) { + return trimStr(line.substr(lowCompact.size())); + } + } + return ""; +} + +void parseSdpMedia(const std::string& msg, std::string& outIp, int& outPort, + int& outPayloadType) { + size_t bodyPos = msg.find("\r\n\r\n"); + if (bodyPos == std::string::npos) return; + std::istringstream iss(msg.substr(bodyPos + 4)); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.rfind("c=IN IP4 ", 0) == 0) { + outIp = trimStr(line.substr(9)); + } else if (line.rfind("m=audio ", 0) == 0) { + std::istringstream mss(line.substr(8)); + std::string proto; + int pt = 0; + mss >> outPort >> proto; + while (mss >> pt) { + if (pt == 0 || pt == 8) { + outPayloadType = pt; + break; + } + } + } + } +} + +class RtpAudioSession { + public: + ~RtpAudioSession() { stop(); } + + bool start(int localPort, const std::string& remoteIp, int remotePort, + int payloadType) { + stop(); + if (remoteIp.empty() || remotePort <= 0) return false; + + int sock = ::socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sock < 0) return false; + int reuse = 1; + ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + struct sockaddr_in localAddr {}; + localAddr.sin_family = AF_INET; + localAddr.sin_addr.s_addr = htonl(INADDR_ANY); + localAddr.sin_port = htons(static_cast(localPort)); + if (::bind(sock, reinterpret_cast(&localAddr), + sizeof(localAddr)) < 0) { + localAddr.sin_port = 0; + ::bind(sock, reinterpret_cast(&localAddr), + sizeof(localAddr)); + } + + struct sockaddr_in remAddr {}; + remAddr.sin_family = AF_INET; + remAddr.sin_port = htons(static_cast(remotePort)); + if (::inet_pton(AF_INET, remoteIp.c_str(), &remAddr.sin_addr) != 1) { + struct addrinfo hints {}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + struct addrinfo* res = nullptr; + if (::getaddrinfo(remoteIp.c_str(), nullptr, &hints, &res) == 0 && res) { + remAddr.sin_addr = + reinterpret_cast(res->ai_addr)->sin_addr; + ::freeaddrinfo(res); + } else { + ::close(sock); + return false; + } + } + + sock_ = sock; + remAddr_ = remAddr; + payloadType_ = (payloadType == 8) ? 8 : 0; + running_.store(true); + worker_ = std::thread([this]() { runLoop(); }); + return true; + } + + void stop() { + running_.store(false); + if (worker_.joinable()) { + worker_.join(); + } + if (sock_ >= 0) { + ::close(sock_); + sock_ = -1; + } + } + + void queueDtmf(char digit) { + std::lock_guard lk(dtmfMtx_); + dtmfQueue_.push_back(digit); + } + + private: + void runLoop() { + FILE* capFp = ::popen("arecord -q -f S16_LE -r 8000 -c 1 -t raw 2>/dev/null", "r"); + FILE* playFp = ::popen("aplay -q -f S16_LE -r 8000 -c 1 -t raw 2>/dev/null", "w"); + int capFd = capFp ? ::fileno(capFp) : -1; + if (capFd >= 0) { + int fl = ::fcntl(capFd, F_GETFL, 0); + ::fcntl(capFd, F_SETFL, fl | O_NONBLOCK); + } + + uint16_t seq = static_cast(nowMs() & 0xffff); + uint32_t ts = static_cast(nowMs() * 8); + uint32_t ssrc = 0x51504241u ^ static_cast(::getpid()); + int64_t nextTxMs = nowMs() + 20; + + while (running_.load()) { + // 1. Receive incoming RTP packets and play to speaker/earpiece + uint8_t rxPkt[1500]; + while (true) { + ssize_t n = ::recv(sock_, rxPkt, sizeof(rxPkt), 0); + if (n <= 12) break; + uint8_t pt = rxPkt[1] & 0x7f; + size_t hdrLen = 12 + (rxPkt[0] & 0x0f) * 4; + if (n <= static_cast(hdrLen)) continue; + const uint8_t* payload = rxPkt + hdrLen; + size_t payLen = static_cast(n) - hdrLen; + if (playFp && (pt == 0 || pt == 8)) { + int16_t pcmOut[640]; + size_t samples = std::min(payLen, 640); + for (size_t i = 0; i < samples; ++i) { + pcmOut[i] = (pt == 8) ? alawToLinear(payload[i]) + : ulawToLinear(payload[i]); + } + std::fwrite(pcmOut, sizeof(int16_t), samples, playFp); + std::fflush(playFp); + } + } + + // 2. Transmit 20ms (160 samples) audio frame or RFC 2833 DTMF event + int64_t now = nowMs(); + if (now >= nextTxMs) { + nextTxMs = now + 20; + char dtmfCh = '\0'; + { + std::lock_guard lk(dtmfMtx_); + if (!dtmfQueue_.empty()) { + dtmfCh = dtmfQueue_.front(); + dtmfQueue_.erase(dtmfQueue_.begin()); + } + } + if (dtmfCh != '\0') { + uint8_t evCode = 0; + if (dtmfCh >= '0' && dtmfCh <= '9') evCode = static_cast(dtmfCh - '0'); + else if (dtmfCh == '*') evCode = 10; + else if (dtmfCh == '#') evCode = 11; + for (int p = 0; p < 3; ++p) { + uint8_t pkt[16]; + pkt[0] = 0x80; + pkt[1] = static_cast((p == 0 ? 0x80 : 0x00) | 101); + uint16_t netSeq = htons(seq++); + uint32_t netTs = htonl(ts); + uint32_t netSsrc = htonl(ssrc); + std::memcpy(pkt + 2, &netSeq, 2); + std::memcpy(pkt + 4, &netTs, 4); + std::memcpy(pkt + 8, &netSsrc, 4); + pkt[12] = evCode; + pkt[13] = static_cast((p == 2 ? 0x80 : 0x00) | 10); + uint16_t dur = htons(static_cast((p + 1) * 160)); + std::memcpy(pkt + 14, &dur, 2); + ::sendto(sock_, pkt, sizeof(pkt), 0, + reinterpret_cast(&remAddr_), + sizeof(remAddr_)); + } + ts += 480; + } else { + int16_t pcmIn[160] = {0}; + if (capFd >= 0) { + ssize_t r = ::read(capFd, pcmIn, sizeof(pcmIn)); + (void)r; + } + uint8_t pkt[12 + 160]; + pkt[0] = 0x80; + pkt[1] = static_cast(payloadType_ & 0x7f); + uint16_t netSeq = htons(seq++); + uint32_t netTs = htonl(ts); + uint32_t netSsrc = htonl(ssrc); + std::memcpy(pkt + 2, &netSeq, 2); + std::memcpy(pkt + 4, &netTs, 4); + std::memcpy(pkt + 8, &netSsrc, 4); + for (int i = 0; i < 160; ++i) { + pkt[12 + i] = (payloadType_ == 8) ? linearToAlaw(pcmIn[i]) + : linearToUlaw(pcmIn[i]); + } + ::sendto(sock_, pkt, sizeof(pkt), 0, + reinterpret_cast(&remAddr_), + sizeof(remAddr_)); + ts += 160; + } + } + + struct pollfd pfd { sock_, POLLIN, 0 }; + int waitMs = static_cast(std::max(2, nextTxMs - nowMs())); + ::poll(&pfd, 1, std::min(waitMs, 20)); + } + + if (capFp) ::pclose(capFp); + if (playFp) ::pclose(playFp); + } + + int sock_ = -1; + struct sockaddr_in remAddr_ {}; + int payloadType_ = 0; + std::atomic running_{false}; + std::thread worker_; + std::mutex dtmfMtx_; + std::string dtmfQueue_; +}; + +int sip_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], "--preload") == 0) { + isPreload = true; + } else { + if (!initCmd.empty()) initCmd.push_back(' '); + initCmd += argv[i]; + } + } + + std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd)); + if (sendPluginCommand("sip", forwarded)) { + return 0; + } + + std::string daemonPidPath = getPluginDaemonPidPath("sip"); + std::string activePidPath = getRuntimeFile("xsip.pid"); + writeIntFile(daemonPidPath, static_cast(::getpid())); + int fifoFd = setupPluginDaemonFifo("sip"); + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + NeoWindow neo; + if (!neo.create("xsip", "XSip", "SIP VoIP Client")) { + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(daemonPidPath.c_str()); + return 1; + } + neo.bindAsActiveContext(); + + // Open non-blocking UDP SIP socket (port 5062 fallback random) + int sipUdpFd = ::socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + int localSipPort = 5062; + if (sipUdpFd >= 0) { + int reuse = 1; + ::setsockopt(sipUdpFd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + struct sockaddr_in addr {}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_ANY); + addr.sin_port = htons(static_cast(localSipPort)); + if (::bind(sipUdpFd, reinterpret_cast(&addr), sizeof(addr)) < 0) { + addr.sin_port = 0; + if (::bind(sipUdpFd, reinterpret_cast(&addr), sizeof(addr)) == 0) { + socklen_t sl = sizeof(addr); + if (::getsockname(sipUdpFd, reinterpret_cast(&addr), &sl) == 0) { + localSipPort = ntohs(addr.sin_port); + } + } + } + } + + std::vector accounts = loadSipAccounts(); + std::vector history = loadSipHistory(); + + enum class SipCallState { Idle = 0, Incoming = 1, Outgoing = 2, Active = 3 }; + SipCallState callState = SipCallState::Idle; + int activeAccountIdx = 0; + std::string activeSipCallId; + std::string activePeerUri; + std::string activeFromHeader; + std::string activeToHeader; + std::string activeViaHeader; + std::string activeContactUri; + std::string activeRemoteTag; + std::string activeLocalTag; + std::string activeBranch; + int activeCseq = 1; + struct sockaddr_in activePeerSin {}; + std::string remoteRtpIp; + int remoteRtpPort = 0; + int remotePayloadType = 0; + int localRtpPort = 16400 + (::getpid() % 1000) * 2; + int64_t callStartedMs = 0; + RtpAudioSession rtpSession; + + auto sendUdpPacket = [&](const std::string& host, int port, const std::string& payload, + const struct sockaddr_in* directSin = nullptr) -> bool { + if (sipUdpFd < 0) return false; + if (directSin && directSin->sin_port != 0) { + return ::sendto(sipUdpFd, payload.data(), payload.size(), 0, + reinterpret_cast(directSin), + sizeof(*directSin)) >= 0; + } + struct addrinfo hints {}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + struct addrinfo* res = nullptr; + char portStr[16]; + std::snprintf(portStr, sizeof(portStr), "%d", port > 0 ? port : 5060); + if (::getaddrinfo(host.c_str(), portStr, &hints, &res) != 0 || !res) { + return false; + } + ssize_t w = ::sendto(sipUdpFd, payload.data(), payload.size(), 0, + res->ai_addr, res->ai_addrlen); + ::freeaddrinfo(res); + return w >= 0; + }; + + auto sendSipRegister = [&](SipAccount& acct, const DigestChallenge* auth = nullptr) { + if (!acct.enabled || acct.domain.empty() || acct.username.empty()) return; + std::string localIp = detectLocalIpForHost(acct.domain); + std::string uri = "sip:" + acct.domain; + std::string branch = "z9hG4bK" + randomHexToken(6); + if (acct.callId.empty()) acct.callId = randomHexToken(8) + "@" + localIp; + if (acct.fromTag.empty()) acct.fromTag = randomHexToken(6); + + std::ostringstream req; + req << "REGISTER " << uri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=" << branch << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << acct.label << "\" ;tag=" << acct.fromTag << "\r\n" + << "To: \r\n" + << "Call-ID: " << acct.callId << "\r\n" + << "CSeq: " << acct.cseq++ << " REGISTER\r\n" + << "Contact: \r\n" + << "Expires: 300\r\n" + << "User-Agent: Bananarchy-XSip/1.0\r\n"; + if (auth && auth->valid) { + req << buildDigestAuthHeader(*auth, acct, "REGISTER", uri); + } + req << "Content-Length: 0\r\n\r\n"; + + acct.lastRegAttemptMs = nowMs(); + if (!auth) acct.regStatus = "REG..."; + sendUdpPacket(acct.domain, acct.port, req.str()); + }; + + auto buildLocalSdp = [&](const std::string& localIp) -> std::string { + std::ostringstream sdp; + uint32_t sessId = static_cast(::time(nullptr)); + sdp << "v=0\r\n" + << "o=" << (accounts.empty() ? "user" : accounts[0].username) << " " + << sessId << " " << sessId << " IN IP4 " << localIp << "\r\n" + << "s=Bananarchy SIP Call\r\n" + << "c=IN IP4 " << localIp << "\r\n" + << "t=0 0\r\n" + << "m=audio " << localRtpPort << " RTP/AVP 0 8 101\r\n" + << "a=rtpmap:0 PCMU/8000\r\n" + << "a=rtpmap:8 PCMA/8000\r\n" + << "a=rtpmap:101 telephone-event/8000\r\n" + << "a=fmtp:101 0-15\r\n" + << "a=ptime:20\r\n" + << "a=sendrecv\r\n"; + return sdp.str(); + }; + + auto sendSipInvite = [&](int acctIdx, const std::string& targetRaw, + const DigestChallenge* auth = nullptr) -> bool { + if (acctIdx < 0 || acctIdx >= static_cast(accounts.size())) { + return false; + } + SipAccount& acct = accounts[acctIdx]; + if (acct.domain.empty() || acct.username.empty()) return false; + + std::string targetUri = trimStr(targetRaw); + if (targetUri.rfind("sip:", 0) != 0) { + if (targetUri.find('@') == std::string::npos) { + targetUri = "sip:" + targetUri + "@" + acct.domain; + } else { + targetUri = "sip:" + targetUri; + } + } + + std::string localIp = detectLocalIpForHost(acct.domain); + if (!auth) { + activeAccountIdx = acctIdx; + activePeerUri = targetUri; + activeSipCallId = randomHexToken(8) + "@" + localIp; + activeLocalTag = randomHexToken(6); + activeRemoteTag.clear(); + activeCseq = 1; + } else { + ++activeCseq; + } + activeBranch = "z9hG4bK" + randomHexToken(6); + std::string sdp = buildLocalSdp(localIp); + + std::ostringstream req; + req << "INVITE " << targetUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=" << activeBranch << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: <" << targetUri << ">\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << activeCseq << " INVITE\r\n" + << "Contact: \r\n" + << "Allow: INVITE, ACK, CANCEL, BYE, OPTIONS, INFO\r\n" + << "User-Agent: Bananarchy-XSip/1.0\r\n"; + if (auth && auth->valid) { + req << buildDigestAuthHeader(*auth, acct, "INVITE", targetUri); + } + req << "Content-Type: application/sdp\r\n" + << "Content-Length: " << sdp.size() << "\r\n\r\n" + << sdp; + + callState = SipCallState::Outgoing; + callStartedMs = nowMs(); + sendUdpPacket(acct.domain, acct.port, req.str()); + if (!auth) { + sendPluginCommand("callscreen", "OUTGOING sip:1 " + targetUri + " SIP"); + } + return true; + }; + + auto acceptActiveSipCall = [&]() { + if (callState != SipCallState::Incoming) return; + std::string host = (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) + ? accounts[activeAccountIdx].domain + : "8.8.8.8"; + std::string localIp = detectLocalIpForHost(host); + std::string sdp = buildLocalSdp(localIp); + std::ostringstream resp; + resp << "SIP/2.0 200 OK\r\n" + << "Via: " << activeViaHeader << "\r\n" + << "From: " << activeFromHeader << "\r\n" + << "To: " << activeToHeader << ";tag=" << activeLocalTag << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << std::max(1, activeCseq) << " INVITE\r\n" + << "Contact: \r\n" + << "Content-Type: application/sdp\r\n" + << "Content-Length: " << sdp.size() << "\r\n\r\n" + << sdp; + ::sendto(sipUdpFd, resp.str().data(), resp.str().size(), 0, + reinterpret_cast(&activePeerSin), + sizeof(activePeerSin)); + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + callState = SipCallState::Active; + callStartedMs = nowMs(); + rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort, remotePayloadType); + sendPluginCommand("callscreen", "ACTIVE sip:1 " + activePeerUri + " SIP"); + }; + + auto hangupActiveSipCall = [&](bool notifyCallscreen) { + if (callState == SipCallState::Idle) return; + rtpSession.stop(); + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + + std::string acctLbl = (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) + ? accounts[activeAccountIdx].label + : "SIP"; + int durSec = (callState == SipCallState::Active && callStartedMs > 0) + ? static_cast((nowMs() - callStartedMs) / 1000) + : 0; + + if (callState == SipCallState::Incoming) { + std::ostringstream resp; + resp << "SIP/2.0 603 Decline\r\n" + << "Via: " << activeViaHeader << "\r\n" + << "From: " << activeFromHeader << "\r\n" + << "To: " << activeToHeader << ";tag=" << activeLocalTag << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << std::max(1, activeCseq) << " INVITE\r\n" + << "Content-Length: 0\r\n\r\n"; + ::sendto(sipUdpFd, resp.str().data(), resp.str().size(), 0, + reinterpret_cast(&activePeerSin), + sizeof(activePeerSin)); + appendSipHistory("MISSED", activePeerUri, acctLbl, 0); + } else if (callState == SipCallState::Outgoing || + callState == SipCallState::Active) { + if (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) { + SipAccount& acct = accounts[activeAccountIdx]; + std::string localIp = detectLocalIpForHost(acct.domain); + std::string method = (callState == SipCallState::Outgoing) ? "CANCEL" : "BYE"; + int seqNum = (method == "CANCEL") ? activeCseq : ++activeCseq; + std::string br = (method == "CANCEL") ? activeBranch + : ("z9hG4bK" + randomHexToken(6)); + std::ostringstream req; + req << method << " " << activePeerUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=" << br << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: <" << activePeerUri << ">" + << (activeRemoteTag.empty() ? "" : (";tag=" + activeRemoteTag)) << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << seqNum << " " << method << "\r\n" + << "Content-Length: 0\r\n\r\n"; + sendUdpPacket(acct.domain, acct.port, req.str()); + } + appendSipHistory("OUT", activePeerUri, acctLbl, durSec); + } + history = loadSipHistory(); + callState = SipCallState::Idle; + if (notifyCallscreen) { + sendPluginCommand("callscreen", "ENDED SIP CALL ENDED"); + } + }; + + auto handleIncomingSipPacket = [&](const std::string& msg, + const struct sockaddr_in& fromSin) { + std::istringstream iss(msg); + std::string firstLine; + std::getline(iss, firstLine); + if (!firstLine.empty() && firstLine.back() == '\r') firstLine.pop_back(); + std::string callIdHdr = getSipHeaderValue(msg, "Call-ID", "i"); + std::string cseqHdr = getSipHeaderValue(msg, "CSeq"); + std::string viaHdr = getSipHeaderValue(msg, "Via", "v"); + std::string fromHdr = getSipHeaderValue(msg, "From", "f"); + std::string toHdr = getSipHeaderValue(msg, "To", "t"); + + // 1. SIP Response (SIP/2.0 ) + if (firstLine.rfind("SIP/2.0 ", 0) == 0) { + int statusCode = std::atoi(firstLine.substr(8).c_str()); + // Match REGISTER response + for (size_t i = 0; i < accounts.size(); ++i) { + if (accounts[i].callId == callIdHdr && + cseqHdr.find("REGISTER") != std::string::npos) { + if (statusCode == 200) { + accounts[i].regStatus = "ONLINE"; + accounts[i].regExpiresAtMs = nowMs() + 240000; + } else if (statusCode == 401 || statusCode == 407) { + DigestChallenge ch = parseDigestChallenge(msg); + if (ch.valid && accounts[i].regStatus != "AUTH...") { + accounts[i].regStatus = "AUTH..."; + sendSipRegister(accounts[i], &ch); + } else { + accounts[i].regStatus = "AUTH ERR"; + } + } else if (statusCode >= 400) { + accounts[i].regStatus = "ERR " + std::to_string(statusCode); + } + return; + } + } + + // Match active INVITE response + if (callIdHdr == activeSipCallId && + cseqHdr.find("INVITE") != std::string::npos) { + size_t tagPos = toHdr.find(";tag="); + if (tagPos != std::string::npos) { + activeRemoteTag = trimStr(toHdr.substr(tagPos + 5)); + } + if (statusCode == 401 || statusCode == 407) { + DigestChallenge ch = parseDigestChallenge(msg); + if (ch.valid) { + // Send ACK for 401/407 then authenticated INVITE + if (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) { + SipAccount& acct = accounts[activeAccountIdx]; + std::string localIp = detectLocalIpForHost(acct.domain); + std::ostringstream ack; + ack << "ACK " << activePeerUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=" << activeBranch << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: " << toHdr << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << activeCseq << " ACK\r\n" + << "Content-Length: 0\r\n\r\n"; + sendUdpPacket(acct.domain, acct.port, ack.str()); + sendSipInvite(activeAccountIdx, activePeerUri, &ch); + } + } + } else if (statusCode == 200 && callState == SipCallState::Outgoing) { + parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType); + if (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) { + SipAccount& acct = accounts[activeAccountIdx]; + std::string localIp = detectLocalIpForHost(acct.domain); + std::ostringstream ack; + ack << "ACK " << activePeerUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=z9hG4bK" << randomHexToken(6) << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: " << toHdr << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << activeCseq << " ACK\r\n" + << "Content-Length: 0\r\n\r\n"; + sendUdpPacket(acct.domain, acct.port, ack.str()); + } + callState = SipCallState::Active; + callStartedMs = nowMs(); + rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort, + remotePayloadType); + sendPluginCommand("callscreen", "ACTIVE sip:1 " + activePeerUri + " SIP"); + } else if (statusCode >= 400 && callState != SipCallState::Idle) { + hangupActiveSipCall(true); + } + } + return; + } + + // 2. Incoming SIP Request (INVITE, OPTIONS, BYE, CANCEL, ACK) + if (firstLine.rfind("OPTIONS ", 0) == 0) { + std::ostringstream resp; + resp << "SIP/2.0 200 OK\r\n" + << "Via: " << viaHdr << "\r\n" + << "From: " << fromHdr << "\r\n" + << "To: " << toHdr << ";tag=" << randomHexToken(4) << "\r\n" + << "Call-ID: " << callIdHdr << "\r\n" + << "CSeq: " << cseqHdr << "\r\n" + << "Allow: INVITE, ACK, CANCEL, BYE, OPTIONS, INFO\r\n" + << "Content-Length: 0\r\n\r\n"; + ::sendto(sipUdpFd, resp.str().data(), resp.str().size(), 0, + reinterpret_cast(&fromSin), sizeof(fromSin)); + return; + } + + if (firstLine.rfind("INVITE ", 0) == 0) { + if (callState != SipCallState::Idle && callIdHdr != activeSipCallId) { + std::ostringstream busy; + busy << "SIP/2.0 486 Busy Here\r\n" + << "Via: " << viaHdr << "\r\n" + << "From: " << fromHdr << "\r\n" + << "To: " << toHdr << ";tag=" << randomHexToken(4) << "\r\n" + << "Call-ID: " << callIdHdr << "\r\n" + << "CSeq: " << cseqHdr << "\r\n" + << "Content-Length: 0\r\n\r\n"; + ::sendto(sipUdpFd, busy.str().data(), busy.str().size(), 0, + reinterpret_cast(&fromSin), sizeof(fromSin)); + return; + } + + activeSipCallId = callIdHdr; + activeViaHeader = viaHdr; + activeFromHeader = fromHdr; + activeToHeader = toHdr; + activeLocalTag = randomHexToken(6); + activeCseq = std::max(1, std::atoi(cseqHdr.c_str())); + activePeerSin = fromSin; + parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType); + + // Extract clean caller URI from From header + std::string caller = fromHdr; + size_t lt = caller.find('<'); + size_t gt = caller.find('>'); + if (lt != std::string::npos && gt != std::string::npos && gt > lt + 1) { + caller = caller.substr(lt + 1, gt - lt - 1); + } + if (caller.rfind("sip:", 0) == 0) { + caller = caller.substr(4); + } + activePeerUri = caller; + + std::ostringstream ring; + ring << "SIP/2.0 180 Ringing\r\n" + << "Via: " << viaHdr << "\r\n" + << "From: " << fromHdr << "\r\n" + << "To: " << toHdr << ";tag=" << activeLocalTag << "\r\n" + << "Call-ID: " << callIdHdr << "\r\n" + << "CSeq: " << cseqHdr << "\r\n" + << "Content-Length: 0\r\n\r\n"; + ::sendto(sipUdpFd, ring.str().data(), ring.str().size(), 0, + reinterpret_cast(&fromSin), sizeof(fromSin)); + + if (callState != SipCallState::Incoming) { + callState = SipCallState::Incoming; + callStartedMs = nowMs(); + writeIntFile("/tmp/sxmo_call_ringing", 1); + runAsyncCmd("sxmo_jobs.sh start ringing sxmo_hook_ring.sh >/dev/null 2>&1"); + if (!sendPluginCommand("callscreen", "INCOMING sip:1 " + caller + " SIP")) { + runAsyncArgv("xcallscreen", "incoming", "sip:1", caller.c_str()); + } + } + return; + } + + if (firstLine.rfind("CANCEL ", 0) == 0 || firstLine.rfind("BYE ", 0) == 0) { + std::ostringstream ok; + ok << "SIP/2.0 200 OK\r\n" + << "Via: " << viaHdr << "\r\n" + << "From: " << fromHdr << "\r\n" + << "To: " << toHdr << "\r\n" + << "Call-ID: " << callIdHdr << "\r\n" + << "CSeq: " << cseqHdr << "\r\n" + << "Content-Length: 0\r\n\r\n"; + ::sendto(sipUdpFd, ok.str().data(), ok.str().size(), 0, + reinterpret_cast(&fromSin), sizeof(fromSin)); + if (callIdHdr == activeSipCallId && callState != SipCallState::Idle) { + rtpSession.stop(); + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + std::string acctLbl = (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) + ? accounts[activeAccountIdx].label + : "SIP"; + int durSec = (callState == SipCallState::Active && callStartedMs > 0) + ? static_cast((nowMs() - callStartedMs) / 1000) + : 0; + appendSipHistory( + callState == SipCallState::Incoming ? "MISSED" : "IN", + activePeerUri, acctLbl, durSec); + history = loadSipHistory(); + callState = SipCallState::Idle; + sendPluginCommand("callscreen", "ENDED SIP CALL ENDED"); + } + return; + } + }; + + // UI state + bool visible = false; + int activeTab = 0; // 0=Dial, 1=Accounts, 2=History + std::string dialInput; + int selectedRow = 0; + int scrollOffset = 0; + bool menuOpen = false; + int menuSel = 0; + + // Account editor modal state + bool editModalOpen = false; + int editAcctIdx = -1; + int editFieldIdx = 0; // 0=Label, 1=Username, 2=Password, 3=Domain, 4=Port, 5=Transport, 6=Enabled + SipAccount editAcctDraft; + + auto syncInputBufferForFocus = [&]() { + if (editModalOpen) { + if (editFieldIdx == 0) neoui_input_reset(editAcctDraft.label.c_str()); + else if (editFieldIdx == 1) neoui_input_reset(editAcctDraft.username.c_str()); + else if (editFieldIdx == 2) neoui_input_reset(editAcctDraft.password.c_str()); + else if (editFieldIdx == 3) neoui_input_reset(editAcctDraft.domain.c_str()); + else if (editFieldIdx == 4) { + neoui_input_set_mode(NEO_INPUT_123); + neoui_input_reset(std::to_string(editAcctDraft.port).c_str()); + } + } else if (activeTab == 0) { + neoui_input_reset(dialInput.c_str()); + } + }; + + auto applyInputBufferToFocus = [&]() { + std::string txt = neoui_input_get_text(); + if (editModalOpen) { + if (editFieldIdx == 0) editAcctDraft.label = txt; + else if (editFieldIdx == 1) { + editAcctDraft.username = txt; + editAcctDraft.authUser = txt; + } else if (editFieldIdx == 2) editAcctDraft.password = txt; + else if (editFieldIdx == 3) editAcctDraft.domain = txt; + else if (editFieldIdx == 4) editAcctDraft.port = std::max(1, std::atoi(txt.c_str())); + } else if (activeTab == 0) { + dialInput = txt; + } + }; + + auto render = [&]() { + if (!visible) return; + neo.bindAsActiveContext(); + neoui_begin_frame(); + + std::string regBadge = "NO ACCT"; + for (const auto& a : accounts) { + if (a.enabled) { + regBadge = a.regStatus; + if (a.regStatus == "ONLINE") break; + } + } + neoui_draw_header(kIconPhone, NEO_TEXT_GREEN, "SIP VoIP", regBadge.c_str()); + neoui_draw_tabs("Dialer|Accounts|History", activeTab, 34, 24); + + constexpr int kBodyY = 58; + constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; + + if (activeTab == 0) { + // Active account indicator + std::string acctLine = "Account: None (Add in Accounts tab)"; + if (!accounts.empty()) { + int idx = std::clamp(activeAccountIdx, 0, static_cast(accounts.size()) - 1); + acctLine = "Acct: " + accounts[idx].label + " [" + accounts[idx].regStatus + "]"; + } + neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 2, 18, + acctLine.c_str(), 224); + + neoui_draw_input_box(6, kBodyY + 22, 228, 38, 1, + "SIP URI / Extension (* mode):", dialInput.c_str(), + "user@domain or 1001", 0); + + // Recent SIP peers below input box + neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_MUTED, 8, kBodyY + 64, 16, + "Recent SIP Calls (Up/Down):", 224); + int listY = kBodyY + 82; + int rowH = 32; + int maxVis = 3; + if (history.empty()) { + neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_MUTED, 0, listY + 18, + 240, 24, "No recent SIP calls"); + } else { + selectedRow = std::clamp(selectedRow, 0, static_cast(history.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(history.size()); ++i) { + int idx = scrollOffset + i; + const auto& h = history[idx]; + const char* ic = (h.direction == "IN") ? kIconInCall + : ((h.direction == "MISSED") ? kIconMissedCall : kIconOutCall); + int icCol = (h.direction == "MISSED") ? NEO_TEXT_RED + : ((h.direction == "IN") ? NEO_TEXT_GREEN : NEO_TEXT_BLUE); + neoui_draw_list_row(idx, listY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + ic, icCol, h.peerUri.c_str(), h.timestamp.c_str(), + h.accountLabel.c_str()); + } + } + neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 22, 240, 22, + "[Call/OK] Dial [*] Input Mode"); + neoui_draw_softkeys("Menu", "CALL", "Close"); + } else if (activeTab == 1) { + int rowH = 42; + int maxVis = kBodyH / rowH; + if (accounts.empty()) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60, + 240, 24, "No SIP accounts configured"); + neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 88, + 240, 20, "Press OK or Left Softkey to Add"); + } else { + selectedRow = std::clamp(selectedRow, 0, static_cast(accounts.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(accounts.size()); ++i) { + int idx = scrollOffset + i; + const auto& a = accounts[idx]; + std::string sub = a.username + "@" + a.domain + ":" + std::to_string(a.port); + int col = (a.regStatus == "ONLINE") ? NEO_TEXT_GREEN + : (a.enabled ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED); + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconUser, col, a.label.c_str(), sub.c_str(), + a.regStatus.c_str()); + } + neoui_draw_scrollbar(236, kBodyY, kBodyH, static_cast(accounts.size()), + maxVis, scrollOffset); + } + neoui_draw_softkeys("Menu", accounts.empty() ? "ADD" : "EDIT", "Back"); + } else { + int rowH = 40; + int maxVis = kBodyH / rowH; + if (history.empty()) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 70, + 240, 24, "SIP Call History Empty"); + } else { + selectedRow = std::clamp(selectedRow, 0, static_cast(history.size()) - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(history.size()); ++i) { + int idx = scrollOffset + i; + const auto& h = history[idx]; + const char* ic = (h.direction == "IN") ? kIconInCall + : ((h.direction == "MISSED") ? kIconMissedCall : kIconOutCall); + int icCol = (h.direction == "MISSED") ? NEO_TEXT_RED + : ((h.direction == "IN") ? NEO_TEXT_GREEN : NEO_TEXT_BLUE); + std::string dur = std::to_string(h.durationSec) + "s"; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + ic, icCol, h.peerUri.c_str(), h.timestamp.c_str(), + dur.c_str()); + } + neoui_draw_scrollbar(236, kBodyY, kBodyH, static_cast(history.size()), + maxVis, scrollOffset); + } + neoui_draw_softkeys("Menu", "REDIAL", "Back"); + } + + if (editModalOpen) { + neoui_draw_modal_box(6, 36, 228, 230, kIconEdit, NEO_TEXT_YELLOW, + editAcctIdx < 0 ? "Add SIP Account" : "Edit SIP Account"); + const char* labels[7] = { + "Label", "Username", "Password", "Domain", "Port", "Transport", "Enabled" + }; + std::string vals[7] = { + editAcctDraft.label, + editAcctDraft.username, + editAcctDraft.password.empty() ? "" : "******", + editAcctDraft.domain, + std::to_string(editAcctDraft.port), + editAcctDraft.transport, + editAcctDraft.enabled ? "ON" : "OFF" + }; + int startIdx = std::max(0, std::min(editFieldIdx - 2, 3)); + for (int i = 0; i < 4 && (startIdx + i) < 7; ++i) { + int f = startIdx + i; + std::string rowTxt = std::string(labels[f]) + ": " + + (f == editFieldIdx && f <= 4 ? neoui_input_get_text() : vals[f]); + neoui_draw_list_row(f, 66 + i * 34, 34, f == editFieldIdx ? 1 : 0, + kIconKey, f == editFieldIdx ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, + rowTxt.c_str(), "", ""); + } + neoui_draw_multitap_bar(8, 206, 224, 22, "[*] Mode [Up/Dn] Field"); + neoui_draw_softkeys("Save", "TOGGLE", "Cancel"); + } else if (menuOpen) { + neoui_draw_menu_popup( + "Add SIP Account|Register All Now|Switch Account|Delete Selected|Clear History", + nullptr, menuSel, 5); + } + + neoui_end_frame(); + }; + + auto openWindow = [&]() { + if (isPhonePasscodeLocked()) return; + writeIntFile(activePidPath, static_cast(::getpid())); + closeOtherPlugins("sip"); + visible = true; + neoui_show(); + syncInputBufferForFocus(); + render(); + }; + + auto closeWindow = [&]() { + if (!visible) return; + visible = false; + editModalOpen = false; + menuOpen = false; + neoui_hide(); + ::unlink(activePidPath.c_str()); + }; + + // Trigger initial background registration for enabled accounts + for (auto& acct : accounts) { + if (acct.enabled) { + sendSipRegister(acct); + } + } + + if (!isPreload) { + openWindow(); + } + + while (gRunning) { + // 1. Read FIFO commands + for (const std::string& cmd : readFifoLines(fifoFd)) { + if (cmd == "NOP") continue; + if (cmd == "CLOSE") { + closeWindow(); + } else if (cmd == "RELOAD_THEME") { + neo.reloadTheme(); + if (visible) render(); + } else if (cmd.rfind("CALL_ACCEPT", 0) == 0) { + acceptActiveSipCall(); + if (visible) render(); + } else if (cmd.rfind("CALL_HANGUP", 0) == 0) { + hangupActiveSipCall(false); + if (visible) render(); + } else if (cmd.rfind("CALL_MUTE_RING", 0) == 0) { + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + } else if (cmd.rfind("CALL_DTMF ", 0) == 0 && cmd.size() >= 11) { + rtpSession.queueDtmf(cmd[10]); + } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + if (cmd.size() > 5) { + std::string arg = trimStr(cmd.substr(5)); + if (arg.rfind("dial ", 0) == 0) { + dialInput = trimStr(arg.substr(5)); + activeTab = 0; + } + } + openWindow(); + } + } + + // 2. Read incoming SIP UDP messages + if (sipUdpFd >= 0) { + char rxBuf[4096]; + struct sockaddr_in fromSin {}; + socklen_t sl = sizeof(fromSin); + while (true) { + ssize_t n = ::recvfrom(sipUdpFd, rxBuf, sizeof(rxBuf) - 1, 0, + reinterpret_cast(&fromSin), &sl); + if (n <= 0) break; + rxBuf[n] = '\0'; + handleIncomingSipPacket(std::string(rxBuf, static_cast(n)), fromSin); + if (visible) render(); + } + } + + // 3. Periodic REGISTER keepalive for enabled accounts + int64_t now = nowMs(); + bool anyEnabled = false; + for (auto& acct : accounts) { + if (!acct.enabled) continue; + anyEnabled = true; + if (acct.lastRegAttemptMs == 0 || + (acct.regStatus == "ONLINE" && now >= acct.regExpiresAtMs) || + (acct.regStatus != "ONLINE" && now - acct.lastRegAttemptMs >= 45000)) { + sendSipRegister(acct); + if (visible) render(); + } + } + + // 4. Process UI events when visible + if (visible) { + neo.bindAsActiveContext(); + int ev = neoui_poll_event(0); + while (ev != NEO_EV_NONE) { + if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { + render(); + } else if (ev == NEO_EV_CLOSE_REQ) { + closeWindow(); + break; + } else if (ev == NEO_EV_SOFTKEY_LEFT) { + if (editModalOpen) { + applyInputBufferToFocus(); + if (editAcctIdx < 0) { + editAcctDraft.callId = randomHexToken(8) + "@" + editAcctDraft.domain; + editAcctDraft.fromTag = randomHexToken(6); + accounts.push_back(editAcctDraft); + sendSipRegister(accounts.back()); + } else if (editAcctIdx < static_cast(accounts.size())) { + accounts[editAcctIdx] = editAcctDraft; + sendSipRegister(accounts[editAcctIdx]); + } + saveSipAccounts(accounts); + editModalOpen = false; + syncInputBufferForFocus(); + render(); + } else { + menuOpen = !menuOpen; + menuSel = 0; + render(); + } + } else if (ev == NEO_EV_SOFTKEY_RIGHT) { + if (editModalOpen) { + editModalOpen = false; + syncInputBufferForFocus(); + render(); + } else if (menuOpen) { + menuOpen = false; + render(); + } else if (activeTab != 0) { + activeTab = 0; + syncInputBufferForFocus(); + render(); + } else { + closeWindow(); + break; + } + } else if (ev == NEO_EV_KEY_PRESS) { + int k = neoui_event_key(); + if (menuOpen) { + if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5; + else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5; + else if (k == NEO_KEY_OK) { + menuOpen = false; + if (menuSel == 0) { + editAcctIdx = -1; + editAcctDraft = SipAccount{}; + editFieldIdx = 0; + editModalOpen = true; + syncInputBufferForFocus(); + } else if (menuSel == 1) { + for (auto& a : accounts) { + if (a.enabled) sendSipRegister(a); + } + neoui_show_toast("REGISTER sent", 1500); + } else if (menuSel == 2 && !accounts.empty()) { + activeAccountIdx = (activeAccountIdx + 1) % static_cast(accounts.size()); + } else if (menuSel == 3 && activeTab == 1 && + selectedRow >= 0 && selectedRow < static_cast(accounts.size())) { + accounts.erase(accounts.begin() + selectedRow); + saveSipAccounts(accounts); + } else if (menuSel == 4) { + ::unlink(getSipHistoryPath().c_str()); + history.clear(); + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + menuOpen = false; + } + render(); + } else if (editModalOpen) { + if (k == NEO_KEY_UP) { + applyInputBufferToFocus(); + editFieldIdx = (editFieldIdx + 6) % 7; + syncInputBufferForFocus(); + } else if (k == NEO_KEY_DOWN) { + applyInputBufferToFocus(); + editFieldIdx = (editFieldIdx + 1) % 7; + syncInputBufferForFocus(); + } else if (k == NEO_KEY_OK) { + if (editFieldIdx == 5) { + if (editAcctDraft.transport == "UDP") editAcctDraft.transport = "TCP"; + else if (editAcctDraft.transport == "TCP") editAcctDraft.transport = "TLS"; + else editAcctDraft.transport = "UDP"; + } else if (editFieldIdx == 6) { + editAcctDraft.enabled = !editAcctDraft.enabled; + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + if (editFieldIdx <= 4) { + neoui_input_backspace(); + applyInputBufferToFocus(); + } + } else if (editFieldIdx <= 4 && k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyInputBufferToFocus(); + } + render(); + } else { + if (k == NEO_KEY_LEFT) { + applyInputBufferToFocus(); + activeTab = (activeTab + 2) % 3; + selectedRow = 0; + scrollOffset = 0; + syncInputBufferForFocus(); + } else if (k == NEO_KEY_RIGHT) { + applyInputBufferToFocus(); + activeTab = (activeTab + 1) % 3; + selectedRow = 0; + scrollOffset = 0; + syncInputBufferForFocus(); + } else if (k == NEO_KEY_UP) { + if (selectedRow > 0) --selectedRow; + } else if (k == NEO_KEY_DOWN) { + ++selectedRow; + } else if (k == NEO_KEY_CALL || k == NEO_KEY_OK) { + if (activeTab == 0) { + applyInputBufferToFocus(); + std::string target = dialInput; + if (target.empty() && selectedRow >= 0 && + selectedRow < static_cast(history.size())) { + target = history[selectedRow].peerUri; + } + if (accounts.empty()) { + neoui_show_toast("Add a SIP account first", 2000); + } else if (!target.empty()) { + sendSipInvite(std::clamp(activeAccountIdx, 0, + static_cast(accounts.size()) - 1), + target); + } + } else if (activeTab == 1) { + if (accounts.empty()) { + editAcctIdx = -1; + editAcctDraft = SipAccount{}; + } else { + editAcctIdx = std::clamp(selectedRow, 0, + static_cast(accounts.size()) - 1); + editAcctDraft = accounts[editAcctIdx]; + } + editFieldIdx = 0; + editModalOpen = true; + syncInputBufferForFocus(); + } else if (activeTab == 2 && selectedRow >= 0 && + selectedRow < static_cast(history.size()) && + !accounts.empty()) { + sendSipInvite(std::clamp(activeAccountIdx, 0, + static_cast(accounts.size()) - 1), + history[selectedRow].peerUri); + } + } else if (activeTab == 0) { + if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + if (!dialInput.empty()) { + neoui_input_backspace(); + applyInputBufferToFocus(); + } else { + closeWindow(); + break; + } + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + applyInputBufferToFocus(); + } + } else if (k == NEO_KEY_END || k == NEO_KEY_BACK) { + closeWindow(); + break; + } + render(); + } + } + ev = neoui_poll_event(0); + } + } else { + while (XPending(neo.dpy) > 0) { + XEvent xev; + XNextEvent(neo.dpy, &xev); + } + } + + // 5. Block on poll() (0% CPU when no active call and no enabled accounts) + struct pollfd pfds[3] {}; + int nfds = 0; + pfds[nfds++] = { ConnectionNumber(neo.dpy), POLLIN, 0 }; + if (fifoFd >= 0) pfds[nfds++] = { fifoFd, POLLIN, 0 }; + if (sipUdpFd >= 0) pfds[nfds++] = { sipUdpFd, POLLIN, 0 }; + + int timeoutMs = -1; + if (visible) { + timeoutMs = neoui_input_is_tap_active() ? 150 : 1000; + } else if (anyEnabled) { + timeoutMs = 15000; + } + ::poll(pfds, nfds, timeoutMs); + } + + rtpSession.stop(); + if (sipUdpFd >= 0) ::close(sipUdpFd); + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(getPluginFifoPath("sip").c_str()); + ::unlink(daemonPidPath.c_str()); + return 0; +} + +int sip_plugin_init(const DwmHostApi* host) { + if (host && host->spawn_plugin) { + host->spawn_plugin("sip", "--preload"); + } + return 0; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { + DWM_PLUGIN_API_VERSION, + "sip", + "SIP VoIP client with standby registration and CallScreen integration", + sip_plugin_init, + nullptr, + nullptr, + nullptr, + nullptr, + sip_run_main +}; diff --git a/src/dwm-plugins/smallweb_plugin.cpp b/src/dwm-plugins/smallweb_plugin.cpp new file mode 100644 index 0000000..0a13b3a --- /dev/null +++ b/src/dwm-plugins/smallweb_plugin.cpp @@ -0,0 +1,1079 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Small Web Protocol Client DWM Plugin (smallweb.so / xkopher / xsmallweb) +// Supports: +// - Gopher (gopher://) with optional TLS (gophers://) +// - Gemini (gemini://) with gemtext rendering, redirects, and input prompts +// - Spartan (spartan://) with gemtext and Spartan (=:) input links +// - Nex (nex://) plain-text & directory navigation +// - Kopher (https://code.luxferre.top/luxferre/kopher.git) default WAP-style +// controls + user-adjustable keybindings stored in ~/.config/sxmo/ + +#include "../sxmo-dwm/dwm_plugin.h" +#include "net_tls.h" + +#include + +namespace { + +using namespace bananarchy; + +volatile sig_atomic_t gRunning = 1; + +void handleSignal(int) { + gRunning = 0; +} + +struct SmallWebControls { + char keyBack = '1'; + char keyPrevLink = '2'; + char keyForward = '3'; + char keyToggleTheme = '4'; + char keyNextLink = '5'; + char keyToggleWrap = '6'; + char keyLineStart = '7'; + char keyPageTop = '8'; + char keyLineEnd = '9'; + char keyPageEnd = '0'; + + void resetKopherDefaults() { + keyBack = '1'; + keyPrevLink = '2'; + keyForward = '3'; + keyToggleTheme = '4'; + keyNextLink = '5'; + keyToggleWrap = '6'; + keyLineStart = '7'; + keyPageTop = '8'; + keyLineEnd = '9'; + keyPageEnd = '0'; + } +}; + +std::string getControlsPath() { + return getHomeDirPath() + "/.config/sxmo/smallweb_controls.tsv"; +} + +std::string getBookmarksPath() { + return getHomeDirPath() + "/.config/sxmo/smallweb_bookmarks.tsv"; +} + +SmallWebControls loadControls() { + SmallWebControls c; + std::ifstream in(getControlsPath()); + std::string k, v; + while (in >> k >> v) { + if (v.empty()) continue; + char ch = v[0]; + if (k == "back") c.keyBack = ch; + else if (k == "prev_link") c.keyPrevLink = ch; + else if (k == "forward") c.keyForward = ch; + else if (k == "toggle_theme") c.keyToggleTheme = ch; + else if (k == "next_link") c.keyNextLink = ch; + else if (k == "toggle_wrap") c.keyToggleWrap = ch; + else if (k == "line_start") c.keyLineStart = ch; + else if (k == "page_top") c.keyPageTop = ch; + else if (k == "line_end") c.keyLineEnd = ch; + else if (k == "page_end") c.keyPageEnd = ch; + } + return c; +} + +void saveControls(const SmallWebControls& c) { + std::string path = getControlsPath(); + ContactBook::ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + out << "back\t" << c.keyBack << "\n" + << "prev_link\t" << c.keyPrevLink << "\n" + << "forward\t" << c.keyForward << "\n" + << "toggle_theme\t" << c.keyToggleTheme << "\n" + << "next_link\t" << c.keyNextLink << "\n" + << "toggle_wrap\t" << c.keyToggleWrap << "\n" + << "line_start\t" << c.keyLineStart << "\n" + << "page_top\t" << c.keyPageTop << "\n" + << "line_end\t" << c.keyLineEnd << "\n" + << "page_end\t" << c.keyPageEnd << "\n"; +} + +std::vector loadBookmarks() { + std::vector bm(11, ""); + std::ifstream in(getBookmarksPath()); + std::string line; + int idx = 0; + while (std::getline(in, line) && idx < 11) { + bm[idx++] = trimStr(line); + } + return bm; +} + +void saveBookmarks(const std::vector& bm) { + std::string path = getBookmarksPath(); + ContactBook::ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + for (size_t i = 0; i < 11; ++i) { + out << (i < bm.size() ? bm[i] : "") << "\n"; + } +} + +std::string stripAnsiCodes(const std::string& s) { + std::string out; + out.reserve(s.size()); + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '\x1b' && i + 1 < s.size() && s[i + 1] == '[') { + i += 2; + while (i < s.size() && + !(static_cast(s[i]) >= 0x40 && + static_cast(s[i]) <= 0x7e)) { + ++i; + } + continue; + } + if (s[i] != '\r') { + out.push_back(s[i]); + } + } + return out; +} + +std::string urlEncode(const std::string& s) { + std::string out; + char hex[4]; + for (unsigned char c : s) { + if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + out.push_back(static_cast(c)); + } else { + std::snprintf(hex, sizeof(hex), "%%%02X", c); + out += hex; + } + } + return out; +} + +std::string resolveRelativeUrl(const std::string& baseUrl, + const std::string& target) { + std::string t = trimStr(target); + if (t.empty()) return baseUrl; + if (t.find("://") != std::string::npos || t.rfind("about:", 0) == 0) { + return t; + } + ParsedUrl b = parseUrl(baseUrl, "gemini"); + std::string portPart; + if ((b.scheme == "gopher" && b.port != 70) || + (b.scheme == "gemini" && b.port != 1965) || + (b.scheme == "spartan" && b.port != 300) || + (b.scheme == "nex" && b.port != 1900)) { + portPart = ":" + std::to_string(b.port); + } + if (t[0] == '/') { + return b.scheme + "://" + b.host + portPart + t; + } + std::string baseDir = b.path; + size_t lastSlash = baseDir.rfind('/'); + if (lastSlash == std::string::npos) { + baseDir = "/"; + } else { + baseDir = baseDir.substr(0, lastSlash + 1); + } + return b.scheme + "://" + b.host + portPart + baseDir + t; +} + +struct DocLine { + std::string text; + int linkIndex = -1; + bool isHeading = false; + bool isQuote = false; + bool isError = false; +}; + +struct LinkItem { + std::string label; + std::string url; + bool requiresInput = false; +}; + +struct PageDocument { + std::string url; + std::string hostTitle; + std::string statusMsg; + std::vector lines; + std::vector links; +}; + +void parseGophermap(const std::string& raw, const std::string& scheme, + PageDocument& doc) { + std::istringstream iss(raw); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == ".") break; + if (line.empty()) { + doc.lines.push_back({"", -1, false, false, false}); + continue; + } + if (line.find('\t') == std::string::npos) { + doc.lines.push_back({stripAnsiCodes(line), -1, false, false, false}); + continue; + } + char type = line[0]; + std::string rest = line.substr(1); + std::vector parts; + std::stringstream ss(rest); + std::string col; + while (std::getline(ss, col, '\t')) parts.push_back(col); + + std::string display = parts.empty() ? "" : stripAnsiCodes(parts[0]); + std::string sel = (parts.size() >= 2) ? parts[1] : ""; + std::string host = (parts.size() >= 3) ? trimStr(parts[2]) : ""; + int port = (parts.size() >= 4) ? std::atoi(parts[3].c_str()) : 70; + if (port <= 0) port = 70; + + if (type == 'i') { + doc.lines.push_back({display, -1, false, false, false}); + } else if (type == '3') { + doc.lines.push_back({"[ERR] " + display, -1, false, false, true}); + } else { + LinkItem lnk; + lnk.label = display; + if (type == 'h' && sel.rfind("URL:", 0) == 0) { + lnk.url = sel.substr(4); + } else if (type == '8') { + lnk.url = "telnet://" + host + ":" + std::to_string(port); + } else { + std::string portPart = (port == 70) ? "" : (":" + std::to_string(port)); + if (!sel.empty() && sel[0] == '/') { + lnk.url = scheme + "://" + host + portPart + "/" + type + sel.substr(1); + } else { + lnk.url = scheme + "://" + host + portPart + "/" + type + sel; + } + } + lnk.requiresInput = (type == '7'); + int lIdx = static_cast(doc.links.size()); + doc.links.push_back(lnk); + std::string prefix = "[LINK] "; + if (type == '1') prefix = "[DIR] "; + else if (type == '0') prefix = "[TXT] "; + else if (type == '7') prefix = "[?] "; + else if (type == 'I' || type == 'g') prefix = "[IMG] "; + else if (type == '9' || type == '5' || type == 's') prefix = "[BIN] "; + else if (type == 'h') prefix = "[URL] "; + doc.lines.push_back({prefix + display, lIdx, false, false, false}); + } + } +} + +void parseGemtext(const std::string& raw, const std::string& baseUrl, + PageDocument& doc, bool allowSpartanPrompt) { + std::istringstream iss(raw); + std::string line; + bool preformatted = false; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.rfind("```", 0) == 0) { + preformatted = !preformatted; + continue; + } + if (preformatted) { + doc.lines.push_back({line, -1, false, false, false}); + continue; + } + bool isLink = (line.rfind("=>", 0) == 0); + bool isPromptLink = (allowSpartanPrompt && line.rfind("=:", 0) == 0); + if (isLink || isPromptLink) { + std::string rest = trimStr(line.substr(2)); + if (!rest.empty()) { + size_t sp = 0; + while (sp < rest.size() && !std::isspace(static_cast(rest[sp]))) { + ++sp; + } + std::string rawTarget = rest.substr(0, sp); + std::string label = (sp < rest.size()) ? trimStr(rest.substr(sp)) : rawTarget; + LinkItem lnk; + lnk.url = resolveRelativeUrl(baseUrl, rawTarget); + lnk.label = label; + lnk.requiresInput = isPromptLink; + int lIdx = static_cast(doc.links.size()); + doc.links.push_back(lnk); + doc.lines.push_back({(isPromptLink ? "[?] " : "-> ") + label, + lIdx, false, false, false}); + continue; + } + } + if (!line.empty() && line[0] == '#') { + doc.lines.push_back({line, -1, true, false, false}); + } else if (!line.empty() && line[0] == '>') { + doc.lines.push_back({line, -1, false, true, false}); + } else { + doc.lines.push_back({line, -1, false, false, false}); + } + } +} + +void parsePlainText(const std::string& raw, PageDocument& doc) { + std::istringstream iss(raw); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + doc.lines.push_back({stripAnsiCodes(line), -1, false, false, false}); + } +} + +bool loadSmallWebUrl(const std::string& rawUrl, const std::string& queryInput, + bool gopherUseTlsByDefault, const SmallWebControls& ctrls, + PageDocument& outDoc, bool& outNeedsPrompt, + std::string& outPromptLabel) { + outDoc = PageDocument{}; + outNeedsPrompt = false; + outPromptLabel.clear(); + + std::string url = trimStr(rawUrl); + if (url.empty()) url = "about:kopher"; + + if (url.rfind("about:", 0) == 0) { + outDoc.url = url; + outDoc.hostTitle = url; + outDoc.statusMsg = url; + if (url == "about:help") { + std::ostringstream h; + h << "iKopher / SmallWeb Controls\t\tlocalhost\t70\r\n" + << "i* Scroll: Up/Down/Left/Right\t\tlocalhost\t70\r\n" + << "i* Prev/Next link: " << ctrls.keyPrevLink << "/" << ctrls.keyNextLink << "\t\tlocalhost\t70\r\n" + << "i* Open link: Center / OK\t\tlocalhost\t70\r\n" + << "i* Enter address / Menu: LSK\t\tlocalhost\t70\r\n" + << "i* Go back: " << ctrls.keyBack << " or RSK\t\tlocalhost\t70\r\n" + << "i* Go forward: " << ctrls.keyForward << "\t\tlocalhost\t70\r\n" + << "i* Refresh: Call\t\tlocalhost\t70\r\n" + << "i* Page start/end: " << ctrls.keyPageTop << "/" << ctrls.keyPageEnd << "\t\tlocalhost\t70\r\n" + << "i* Line start/end: " << ctrls.keyLineStart << "/" << ctrls.keyLineEnd << "\t\tlocalhost\t70\r\n" + << "i* Open homepage: # *\t\tlocalhost\t70\r\n" + << "i* Open bookmark: # [1-0]\t\tlocalhost\t70\r\n" + << "i* Save homepage: * *\t\tlocalhost\t70\r\n" + << "i* Save bookmark: * [1-0]\t\tlocalhost\t70\r\n" + << "i* Share URL: * Call\t\tlocalhost\t70\r\n" + << "i* Toggle light/dark: " << ctrls.keyToggleTheme << "\t\tlocalhost\t70\r\n" + << "i* Toggle line wrap: " << ctrls.keyToggleWrap << "\t\tlocalhost\t70\r\n" + << "i* Page info: # #\t\tlocalhost\t70\r\n" + << "i* Customize keys: # 6\t\tlocalhost\t70\r\n" + << "1Back to about:kopher\t\tabout:kopher\t70\r\n"; + parseGophermap(h.str(), "gopher", outDoc); + if (!outDoc.links.empty()) { + outDoc.links.back().url = "about:kopher"; + } + return true; + } + std::string kopherPage = + "Welcome to Kopher / SmallWeb\r\n" + "hControls help\tURL:about:help\tlocalhost\t70\r\n" + "Useful Gopher links:\r\n" + "1Quarry\t/quarry\tgopher.icu\t70\r\n" + "1Magical Fish\t/\tmagical.fish\t70\r\n" + "1Floodgap portal\t/\tgopher.floodgap.com\t70\r\n" + "Gemini, Spartan & Nex portals:\r\n" + "hProject Gemini\tURL:gemini://geminiprotocol.net/\tlocalhost\t70\r\n" + "hSpartan Portal\tURL:spartan://spartan.mozz.us/\tlocalhost\t70\r\n" + "hNex Nightfall City\tURL:nex://nightfall.city/\tlocalhost\t70\r\n" + "\r\n" + "Created by Luxferre, public domain\r\n"; + parseGophermap(kopherPage, "gopher", outDoc); + return true; + } + + for (int redirects = 0; redirects < 5; ++redirects) { + ParsedUrl u = parseUrl(url, gopherUseTlsByDefault ? "gophers" : "gopher"); + outDoc.url = u.scheme + "://" + u.host + + ((u.port == 70 || u.port == 1965 || u.port == 300 || u.port == 1900) + ? "" + : (":" + std::to_string(u.port))) + + u.path; + outDoc.hostTitle = u.host; + outDoc.statusMsg = u.path; + + if (u.scheme == "gopher" || u.scheme == "gophers") { + if (u.gopherType == '7' && queryInput.empty()) { + outNeedsPrompt = true; + outPromptLabel = "Search query:"; + return false; + } + NetStream net; + if (!net.connectTcp(u.host, u.port, 6000)) { + outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true}); + return true; + } + bool useTls = (u.scheme == "gophers" || gopherUseTlsByDefault); + if (useTls && !net.startTls(u.host, 4000)) { + // Fallback to plain Gopher if opportunistic TLS fails on gopher:// + if (u.scheme == "gopher") { + net.connectTcp(u.host, u.port, 6000); + } else { + outDoc.lines.push_back({"[ERR] Gopher TLS handshake failed", -1, false, false, true}); + return true; + } + } + std::string req = u.gopherSelector; + if (!queryInput.empty()) { + req += "\t" + queryInput; + } + req += "\r\n"; + net.sendStr(req); + std::string raw; + net.readUntilClose(raw, 2 * 1024 * 1024, 8000); + + if (u.gopherType == '1' || u.gopherType == '7') { + parseGophermap(raw, u.scheme, outDoc); + } else if (u.gopherType == '9' || u.gopherType == 'I' || u.gopherType == 'g' || + u.gopherType == '5' || u.gopherType == 's') { + size_t sl = u.gopherSelector.rfind('/'); + std::string fn = (sl == std::string::npos) ? u.gopherSelector + : u.gopherSelector.substr(sl + 1); + if (fn.empty()) fn = "download.bin"; + std::string savePath = getHomeDirPath() + "/" + fn; + std::ofstream out(savePath, std::ios::binary | std::ios::trunc); + if (out.is_open()) { + out.write(raw.data(), static_cast(raw.size())); + outDoc.statusMsg = "Saved " + savePath; + outDoc.lines.push_back({"Saved binary file to: " + savePath, -1, false, false, false}); + } + } else { + parsePlainText(raw, outDoc); + } + return true; + } + + if (u.scheme == "gemini") { + std::string fullUrl = url; + if (!queryInput.empty()) { + size_t q = fullUrl.find('?'); + if (q != std::string::npos) fullUrl = fullUrl.substr(0, q); + fullUrl += "?" + urlEncode(queryInput); + outDoc.url = fullUrl; + } + NetStream net; + if (!net.connectTcp(u.host, u.port, 6000) || + !net.startTls(u.host, 6000)) { + outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true}); + return true; + } + net.sendStr(fullUrl + "\r\n"); + std::string hdrLine; + if (!net.readLine(hdrLine, 6000) || hdrLine.size() < 2) { + outDoc.lines.push_back({"[ERR] Empty Gemini header", -1, false, false, true}); + return true; + } + int status = std::atoi(hdrLine.substr(0, 2).c_str()); + std::string meta = (hdrLine.size() > 3) ? trimStr(hdrLine.substr(3)) : ""; + if (status >= 10 && status < 20) { + outNeedsPrompt = true; + outPromptLabel = meta.empty() ? "Gemini Input:" : meta; + return false; + } + if (status >= 30 && status < 40 && !meta.empty()) { + url = resolveRelativeUrl(fullUrl, meta); + continue; + } + if (status < 20 || status >= 30) { + outDoc.lines.push_back( + {"[Gemini " + std::to_string(status) + "] " + meta, -1, false, false, true}); + return true; + } + std::string body; + net.readUntilClose(body, 2 * 1024 * 1024, 8000); + if (meta.empty() || toLowerStr(meta).find("text/gemini") != std::string::npos) { + parseGemtext(body, fullUrl, outDoc, false); + } else { + parsePlainText(body, outDoc); + } + return true; + } + + if (u.scheme == "spartan") { + NetStream net; + if (!net.connectTcp(u.host, u.port, 6000)) { + outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true}); + return true; + } + std::ostringstream req; + req << u.host << " " << (u.path.empty() ? "/" : u.path) << " " + << queryInput.size() << "\r\n" << queryInput; + net.sendStr(req.str()); + std::string hdrLine; + if (!net.readLine(hdrLine, 6000) || hdrLine.empty()) { + outDoc.lines.push_back({"[ERR] Empty Spartan response", -1, false, false, true}); + return true; + } + int status = hdrLine[0] - '0'; + std::string meta = (hdrLine.size() > 2) ? trimStr(hdrLine.substr(2)) : ""; + if (status == 3 && !meta.empty()) { + url = resolveRelativeUrl(url, meta); + continue; + } + if (status != 2) { + outDoc.lines.push_back({"[Spartan " + std::to_string(status) + "] " + meta, + -1, false, false, true}); + return true; + } + std::string body; + net.readUntilClose(body, 2 * 1024 * 1024, 8000); + if (toLowerStr(meta).find("text/gemini") != std::string::npos) { + parseGemtext(body, url, outDoc, true); + } else { + parsePlainText(body, outDoc); + } + return true; + } + + if (u.scheme == "nex") { + NetStream net; + if (!net.connectTcp(u.host, u.port, 6000)) { + outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true}); + return true; + } + net.sendStr((u.path.empty() ? "/" : u.path) + "\r\n"); + std::string body; + net.readUntilClose(body, 2 * 1024 * 1024, 8000); + parseGemtext(body, url, outDoc, false); + return true; + } + + outDoc.lines.push_back({"[ERR] Unsupported scheme: " + u.scheme, -1, false, false, true}); + return true; + } + return true; +} + +int smallweb_run_main(int argc, char** argv) { + gRunning = 1; + bool isPreload = false; + std::string initUrl; + for (int i = 1; i < argc; ++i) { + if (!argv[i] || !argv[i][0]) continue; + if (std::strcmp(argv[i], "--preload") == 0) isPreload = true; + else if (initUrl.empty()) initUrl = argv[i]; + } + + std::string forwarded = isPreload ? "NOP" : (initUrl.empty() ? "OPEN" : ("OPEN " + initUrl)); + if (sendPluginCommand("smallweb", forwarded)) { + return 0; + } + + std::string daemonPidPath = getPluginDaemonPidPath("smallweb"); + std::string activePidPath = getRuntimeFile("xsmallweb.pid"); + writeIntFile(daemonPidPath, static_cast(::getpid())); + int fifoFd = setupPluginDaemonFifo("smallweb"); + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + NeoWindow neo; + if (!neo.create("xkopher", "XKopher", "Kopher / SmallWeb")) { + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(daemonPidPath.c_str()); + return 1; + } + neo.bindAsActiveContext(); + + SmallWebControls ctrls = loadControls(); + std::vector bookmarks = loadBookmarks(); + std::vector history; + int historyIdx = -1; + + PageDocument currentDoc; + int scrollTopLine = 0; + int scrollLeftCol = 0; + int focusedLinkIdx = 0; + bool wrapLines = false; + bool lightThemeOverride = false; + bool gopherTlsDefault = false; + std::string chordPrefix; + + bool visible = false; + bool promptModalOpen = false; + std::string promptTitle = "Enter address:"; + std::string pendingPromptUrl; + bool promptIsAddressBar = true; + + bool infoModalOpen = false; + std::string infoModalLine1; + std::string infoModalLine2; + + bool controlsModalOpen = false; + int controlsSelRow = 0; + + auto navigateTo = [&](const std::string& targetUrl, + const std::string& query = "", + bool pushHistory = true) { + std::string normUrl = trimStr(targetUrl); + if (normUrl.empty()) return; + if (normUrl.find("://") == std::string::npos && + normUrl.rfind("about:", 0) != 0) { + normUrl = (gopherTlsDefault ? "gophers://" : "gopher://") + normUrl; + } + + bool needsPrompt = false; + std::string promptLbl; + PageDocument doc; + if (!loadSmallWebUrl(normUrl, query, gopherTlsDefault, ctrls, doc, + needsPrompt, promptLbl)) { + if (needsPrompt) { + promptModalOpen = true; + promptIsAddressBar = false; + promptTitle = promptLbl; + pendingPromptUrl = normUrl; + neoui_input_reset(""); + return; + } + } + + currentDoc = std::move(doc); + scrollTopLine = 0; + scrollLeftCol = 0; + focusedLinkIdx = 0; + if (pushHistory) { + if (historyIdx + 1 < static_cast(history.size())) { + history.erase(history.begin() + historyIdx + 1, history.end()); + } + history.push_back(currentDoc.url); + historyIdx = static_cast(history.size()) - 1; + } + }; + + // Load initial homepage (bookmark #0 or about:kopher) + navigateTo(!bookmarks[0].empty() ? bookmarks[0] : "about:kopher"); + + auto focusLinkRelative = [&](int delta) { + if (currentDoc.links.empty()) return; + int cnt = static_cast(currentDoc.links.size()); + focusedLinkIdx = (focusedLinkIdx + delta + cnt) % cnt; + for (size_t i = 0; i < currentDoc.lines.size(); ++i) { + if (currentDoc.lines[i].linkIndex == focusedLinkIdx) { + scrollTopLine = std::max(0, static_cast(i) - 4); + break; + } + } + }; + + auto render = [&]() { + if (!visible) return; + neo.bindAsActiveContext(); + neoui_begin_frame(); + + if (lightThemeOverride) { + neoui_clear(0xF5F5F0); + } + + std::string protoBadge = "GOPHER"; + if (currentDoc.url.rfind("gophers:", 0) == 0) protoBadge = "GOPHERS"; + else if (currentDoc.url.rfind("gemini:", 0) == 0) protoBadge = "GEMINI"; + else if (currentDoc.url.rfind("spartan:", 0) == 0) protoBadge = "SPARTAN"; + else if (currentDoc.url.rfind("nex:", 0) == 0) protoBadge = "NEX"; + else if (currentDoc.url.rfind("about:", 0) == 0) protoBadge = "KOPHER"; + + neoui_draw_header(kIconGlobe, NEO_TEXT_GREEN, + currentDoc.hostTitle.c_str(), protoBadge.c_str()); + + constexpr int kContentY = 36; + constexpr int kStatusY = 296 - NEO_SOFTBAR_H - 18; + constexpr int kContentH = kStatusY - kContentY; + constexpr int kLineH = 16; + int maxVisLines = kContentH / kLineH; + + // Expand wrapped lines if wrapLines is enabled + struct RenderRow { + std::string text; + int linkIndex; + bool isHeading; + bool isQuote; + bool isError; + }; + std::vector rows; + for (const auto& dl : currentDoc.lines) { + if (!wrapLines || dl.text.size() <= 30) { + std::string sliced = dl.text; + if (!wrapLines && scrollLeftCol > 0) { + if (static_cast(scrollLeftCol) < sliced.size()) { + sliced = sliced.substr(scrollLeftCol); + } else { + sliced.clear(); + } + } + rows.push_back({sliced, dl.linkIndex, dl.isHeading, dl.isQuote, dl.isError}); + } else { + size_t pos = 0; + while (pos < dl.text.size()) { + size_t take = std::min(30, dl.text.size() - pos); + rows.push_back({dl.text.substr(pos, take), dl.linkIndex, + dl.isHeading, dl.isQuote, dl.isError}); + pos += take; + } + } + } + + int totalRows = static_cast(rows.size()); + scrollTopLine = std::clamp(scrollTopLine, 0, std::max(0, totalRows - maxVisLines)); + + for (int i = 0; i < maxVisLines && (scrollTopLine + i) < totalRows; ++i) { + const auto& r = rows[scrollTopLine + i]; + int y = kContentY + i * kLineH; + bool isSelLink = (r.linkIndex >= 0 && r.linkIndex == focusedLinkIdx); + if (isSelLink) { + neoui_fill_rect(2, y, 234, kLineH, neoui_color(NEO_COLOR_SEL_BG)); + } + int col = lightThemeOverride ? NEO_TEXT_MUTED : NEO_TEXT_LIGHT; + if (isSelLink) col = NEO_TEXT_WHITE; + else if (r.linkIndex >= 0) col = NEO_TEXT_BLUE; + else if (r.isHeading) col = NEO_TEXT_YELLOW; + else if (r.isQuote) col = NEO_TEXT_GREEN; + else if (r.isError) col = NEO_TEXT_RED; + + neoui_draw_text(NEO_FONT_SMALL, col, 4, y, kLineH, r.text.c_str(), 230); + } + + neoui_draw_scrollbar(236, kContentY, kContentH, totalRows, maxVisLines, + scrollTopLine); + + // Kopher bottom status bar (above softkeys) + neoui_fill_rect(0, kStatusY, 240, 18, neoui_color(NEO_COLOR_BG_ALT_EVEN)); + std::string stText = !chordPrefix.empty() + ? ("Key chord: " + chordPrefix + "_") + : currentDoc.statusMsg; + neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 6, kStatusY, 18, + stText.c_str(), 228); + + neoui_draw_softkeys("Address", "OPEN", "Back"); + + if (promptModalOpen) { + neoui_draw_modal_box(6, 46, 228, 174, kIconGlobe, NEO_TEXT_YELLOW, + promptTitle.c_str()); + neoui_draw_input_box(12, 80, 216, 42, 1, + "gopher://, gemini://, spartan://, nex://", + neoui_input_get_text(), "gopher.floodgap.com", 0); + neoui_draw_multitap_bar(12, 130, 216, 22, "[*] Mode [Call] Gopher-TLS"); + neoui_draw_softkeys("Go", "OPEN", "Cancel"); + } else if (infoModalOpen) { + neoui_draw_confirm_dialog("Kopher / SmallWeb", infoModalLine1.c_str(), + infoModalLine2.c_str(), "Close", "Keys", 0); + } else if (controlsModalOpen) { + neoui_draw_modal_box(6, 30, 228, 232, kIconSliders, NEO_TEXT_YELLOW, + "Adjustable Controls (Press 0-9)"); + const char* names[10] = { + "Go Back", "Prev Link", "Go Forward", "Light/Dark", "Next Link", + "Line Wrap", "Line Start", "Page Start", "Line End", "Page End" + }; + char curKeys[10] = { + ctrls.keyBack, ctrls.keyPrevLink, ctrls.keyForward, ctrls.keyToggleTheme, + ctrls.keyNextLink, ctrls.keyToggleWrap, ctrls.keyLineStart, + ctrls.keyPageTop, ctrls.keyLineEnd, ctrls.keyPageEnd + }; + int startIdx = std::max(0, std::min(controlsSelRow - 2, 5)); + for (int i = 0; i < 5 && (startIdx + i) < 10; ++i) { + int r = startIdx + i; + std::string kstr(1, curKeys[r]); + neoui_draw_list_row(r, 60 + i * 32, 32, r == controlsSelRow ? 1 : 0, + kIconKey, r == controlsSelRow ? NEO_TEXT_YELLOW : NEO_TEXT_LIGHT, + names[r], "", kstr.c_str()); + } + neoui_draw_softkeys("Save", "RESET DEF", "Cancel"); + } + + neoui_end_frame(); + }; + + auto openWindow = [&]() { + if (isPhonePasscodeLocked()) return; + writeIntFile(activePidPath, static_cast(::getpid())); + closeOtherPlugins("smallweb"); + visible = true; + neoui_show(); + render(); + }; + + auto closeWindow = [&]() { + if (!visible) return; + visible = false; + promptModalOpen = false; + infoModalOpen = false; + controlsModalOpen = false; + chordPrefix.clear(); + neoui_hide(); + ::unlink(activePidPath.c_str()); + }; + + if (!isPreload) { + openWindow(); + } + + while (gRunning) { + for (const std::string& cmd : readFifoLines(fifoFd)) { + if (cmd == "NOP") continue; + if (cmd == "CLOSE") closeWindow(); + else if (cmd == "RELOAD_THEME") { + neo.reloadTheme(); + if (visible) render(); + } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + if (cmd.size() > 5) { + navigateTo(trimStr(cmd.substr(5))); + } + openWindow(); + } + } + + if (visible) { + neo.bindAsActiveContext(); + int ev = neoui_poll_event(0); + while (ev != NEO_EV_NONE) { + if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { + render(); + } else if (ev == NEO_EV_CLOSE_REQ) { + closeWindow(); + break; + } else if (ev == NEO_EV_SOFTKEY_LEFT) { + if (promptModalOpen) { + std::string val = trimStr(neoui_input_get_text()); + promptModalOpen = false; + if (!val.empty()) { + if (promptIsAddressBar) navigateTo(val); + else navigateTo(pendingPromptUrl, val); + } + render(); + } else if (controlsModalOpen) { + saveControls(ctrls); + controlsModalOpen = false; + neoui_show_toast("Controls saved", 1500); + render(); + } else if (infoModalOpen) { + infoModalOpen = false; + render(); + } else { + promptModalOpen = true; + promptIsAddressBar = true; + promptTitle = "Enter Address:"; + neoui_input_reset(currentDoc.url.c_str()); + render(); + } + } else if (ev == NEO_EV_SOFTKEY_RIGHT) { + if (promptModalOpen) { + promptModalOpen = false; + render(); + } else if (controlsModalOpen) { + controlsModalOpen = false; + render(); + } else if (infoModalOpen) { + infoModalOpen = false; + controlsModalOpen = true; + render(); + } else { + if (historyIdx > 0) { + --historyIdx; + navigateTo(history[historyIdx], "", false); + render(); + } else { + closeWindow(); + break; + } + } + } else if (ev == NEO_EV_KEY_PRESS) { + int k = neoui_event_key(); + if (promptModalOpen) { + if (k == NEO_KEY_OK) { + std::string val = trimStr(neoui_input_get_text()); + promptModalOpen = false; + if (!val.empty()) { + if (promptIsAddressBar) navigateTo(val); + else navigateTo(pendingPromptUrl, val); + } + } else if (k == NEO_KEY_CALL) { + gopherTlsDefault = !gopherTlsDefault; + neoui_show_toast( + gopherTlsDefault ? "Gopher TLS: ON" : "Gopher TLS: OFF", 1500); + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + neoui_input_backspace(); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + } + render(); + } else if (controlsModalOpen) { + if (k == NEO_KEY_UP) controlsSelRow = (controlsSelRow + 9) % 10; + else if (k == NEO_KEY_DOWN) controlsSelRow = (controlsSelRow + 1) % 10; + else if (k == NEO_KEY_OK) { + ctrls.resetKopherDefaults(); + saveControls(ctrls); + neoui_show_toast("Reset to Kopher defaults", 1500); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + char ch = static_cast(k); + if (controlsSelRow == 0) ctrls.keyBack = ch; + else if (controlsSelRow == 1) ctrls.keyPrevLink = ch; + else if (controlsSelRow == 2) ctrls.keyForward = ch; + else if (controlsSelRow == 3) ctrls.keyToggleTheme = ch; + else if (controlsSelRow == 4) ctrls.keyNextLink = ch; + else if (controlsSelRow == 5) ctrls.keyToggleWrap = ch; + else if (controlsSelRow == 6) ctrls.keyLineStart = ch; + else if (controlsSelRow == 7) ctrls.keyPageTop = ch; + else if (controlsSelRow == 8) ctrls.keyLineEnd = ch; + else if (controlsSelRow == 9) ctrls.keyPageEnd = ch; + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + controlsModalOpen = false; + } + render(); + } else if (infoModalOpen) { + infoModalOpen = false; + render(); + } else { + // Handle Kopher 2-key chords starting with * or # + if (!chordPrefix.empty()) { + std::string prefix = chordPrefix; + chordPrefix.clear(); + if (prefix == "*") { + if (k == NEO_KEY_STAR) { + bookmarks[0] = currentDoc.url; + saveBookmarks(bookmarks); + neoui_show_toast("Saved as Homepage", 1800); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + int bIdx = (k == NEO_KEY_0) ? 10 : (k - NEO_KEY_0); + bookmarks[bIdx] = currentDoc.url; + saveBookmarks(bookmarks); + neoui_show_toast( + ("Saved Bookmark #" + std::to_string(bIdx)).c_str(), 1800); + } else if (k == NEO_KEY_CALL) { + std::ofstream sf("/tmp/shared_url.txt", std::ios::trunc); + if (sf.is_open()) sf << currentDoc.url << "\n"; + neoui_show_toast("Shared URL -> /tmp/shared_url.txt", 2000); + } + } else if (prefix == "#") { + if (k == NEO_KEY_STAR) { + navigateTo(!bookmarks[0].empty() ? bookmarks[0] : "about:kopher"); + } else if (k == NEO_KEY_HASH) { + infoModalLine1 = "Kopher SmallWeb v1.0"; + infoModalLine2 = currentDoc.url; + infoModalOpen = true; + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + int bIdx = (k == NEO_KEY_0) ? 10 : (k - NEO_KEY_0); + if (!bookmarks[bIdx].empty()) { + navigateTo(bookmarks[bIdx]); + } else if (bIdx == 6) { + controlsModalOpen = true; + } else { + neoui_show_toast( + ("No bookmark at #" + std::to_string(bIdx)).c_str(), 1500); + } + } + } + render(); + } else if (k == NEO_KEY_STAR) { + chordPrefix = "*"; + render(); + } else if (k == NEO_KEY_HASH) { + chordPrefix = "#"; + render(); + } else if (k == NEO_KEY_UP) { + if (scrollTopLine > 0) --scrollTopLine; + render(); + } else if (k == NEO_KEY_DOWN) { + ++scrollTopLine; + render(); + } else if (k == NEO_KEY_LEFT) { + scrollLeftCol = std::max(0, scrollLeftCol - 6); + render(); + } else if (k == NEO_KEY_RIGHT) { + scrollLeftCol += 6; + render(); + } else if (k == NEO_KEY_OK) { + if (focusedLinkIdx >= 0 && + focusedLinkIdx < static_cast(currentDoc.links.size())) { + const auto& lnk = currentDoc.links[focusedLinkIdx]; + if (lnk.requiresInput) { + promptModalOpen = true; + promptIsAddressBar = false; + promptTitle = lnk.label; + pendingPromptUrl = lnk.url; + neoui_input_reset(""); + } else { + navigateTo(lnk.url); + } + } + render(); + } else if (k == NEO_KEY_CALL) { + navigateTo(currentDoc.url, "", false); + render(); + } else if (k == NEO_KEY_END || k == NEO_KEY_BACK) { + closeWindow(); + break; + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + char ch = static_cast(k); + if (ch == ctrls.keyBack) { + if (historyIdx > 0) { + --historyIdx; + navigateTo(history[historyIdx], "", false); + } + } else if (ch == ctrls.keyForward) { + if (historyIdx + 1 < static_cast(history.size())) { + ++historyIdx; + navigateTo(history[historyIdx], "", false); + } + } else if (ch == ctrls.keyPrevLink) { + focusLinkRelative(-1); + } else if (ch == ctrls.keyNextLink) { + focusLinkRelative(1); + } else if (ch == ctrls.keyToggleTheme) { + lightThemeOverride = !lightThemeOverride; + } else if (ch == ctrls.keyToggleWrap) { + wrapLines = !wrapLines; + scrollLeftCol = 0; + } else if (ch == ctrls.keyLineStart) { + scrollLeftCol = 0; + } else if (ch == ctrls.keyLineEnd) { + scrollLeftCol = 40; + } else if (ch == ctrls.keyPageTop) { + scrollTopLine = 0; + } else if (ch == ctrls.keyPageEnd) { + scrollTopLine = static_cast(currentDoc.lines.size()); + } + render(); + } + } + } + ev = neoui_poll_event(0); + } + } else { + while (XPending(neo.dpy) > 0) { + XEvent xev; + XNextEvent(neo.dpy, &xev); + } + } + + struct pollfd pfds[2] {}; + pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 }; + pfds[1] = { fifoFd, POLLIN, 0 }; + int timeoutMs = visible ? (neoui_input_is_tap_active() ? 150 : 1000) : -1; + ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); + } + + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(getPluginFifoPath("smallweb").c_str()); + ::unlink(daemonPidPath.c_str()); + return 0; +} + +int smallweb_plugin_init(const DwmHostApi* host) { + if (host && host->spawn_plugin) { + host->spawn_plugin("smallweb", "--preload"); + } + return 0; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { + DWM_PLUGIN_API_VERSION, + "smallweb", + "Kopher SmallWeb browser for Gopher(s), Gemini, Spartan, and Nex", + smallweb_plugin_init, + nullptr, + nullptr, + nullptr, + nullptr, + smallweb_run_main +}; diff --git a/src/dwm-plugins/tox_plugin.cpp b/src/dwm-plugins/tox_plugin.cpp new file mode 100644 index 0000000..e1f00cc --- /dev/null +++ b/src/dwm-plugins/tox_plugin.cpp @@ -0,0 +1,967 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Tox / Trifa P2P Messenger & VoIP DWM Plugin (tox.so / xtox) for Bananarchy (240x320) +// Built on c-toxcore (libtoxcore / tox.h + toxav.h) with: +// - Persistent Tox profile (~/.local/share/sxmo/tox/profile.tox) +// - DHT + TCP relay bootstrap with standby background mode +// - Friend requests, P2P encrypted messaging, and per-friend chat logs +// - ToxAV Opus audio calls integrated with CallScreen (callscreen.so) + +#include "../sxmo-dwm/dwm_plugin.h" +#include "phone_data.h" + +#include +#include + +#include +#include + +namespace { + +using namespace bananarchy; + +volatile sig_atomic_t gRunning = 1; + +void handleSignal(int) { + gRunning = 0; +} + +std::string bytesToHexUpper(const uint8_t* data, size_t len) { + std::string out; + out.reserve(len * 2); + char buf[4]; + for (size_t i = 0; i < len; ++i) { + std::snprintf(buf, sizeof(buf), "%02X", data[i]); + out += buf; + } + return out; +} + +bool hexToBytes(const std::string& hex, uint8_t* out, size_t expectedBytes) { + std::string clean; + for (char c : hex) { + if (!std::isspace(static_cast(c))) { + clean.push_back(c); + } + } + if (clean.size() != expectedBytes * 2) return false; + for (size_t i = 0; i < expectedBytes; ++i) { + int hi = themeHexNibble(clean[i * 2]); + int lo = themeHexNibble(clean[i * 2 + 1]); + if (hi < 0 || lo < 0) return false; + out[i] = static_cast((hi << 4) | lo); + } + return true; +} + +std::string getToxDataDir() { + std::string dir = getHomeDirPath() + "/.local/share/sxmo/tox"; + ContactBook::ensureParentDir(dir + "/profile.tox"); + return dir; +} + +std::string getToxProfilePath() { + return getToxDataDir() + "/profile.tox"; +} + +struct ToxChatEntry { + std::string timeStr; + bool outgoing = false; + std::string text; +}; + +struct PendingFriendReq { + uint8_t pubKey[TOX_PUBLIC_KEY_SIZE] {}; + std::string pubKeyHex; + std::string message; +}; + +struct ToxRuntimeContext { + Tox* tox = nullptr; + ToxAV* toxav = nullptr; + bool dhtConnected = false; + std::string connBadge = "OFFLINE"; + std::vector pendingReqs; + + // Active ToxAV call state + bool inCall = false; + bool callIncoming = false; + bool callActive = false; + uint32_t callFriendNum = UINT32_MAX; + FILE* playPipe = nullptr; + FILE* capPipe = nullptr; + int capFd = -1; + std::mutex audioMtx; + bool uiDirty = false; +}; + +std::string getFriendChatLogPath(const std::string& pubKeyHex) { + return getToxDataDir() + "/chat_" + pubKeyHex.substr(0, 16) + ".tsv"; +} + +std::vector loadFriendChat(const std::string& pubKeyHex) { + std::vector list; + std::ifstream in(getFriendChatLogPath(pubKeyHex)); + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty()) continue; + size_t t1 = line.find('\t'); + size_t t2 = (t1 == std::string::npos) ? std::string::npos : line.find('\t', t1 + 1); + if (t1 != std::string::npos && t2 != std::string::npos) { + ToxChatEntry e; + e.timeStr = line.substr(0, t1); + e.outgoing = (line.substr(t1 + 1, t2 - t1 - 1) == "OUT"); + e.text = line.substr(t2 + 1); + list.push_back(std::move(e)); + } + } + return list; +} + +void appendFriendChat(const std::string& pubKeyHex, bool outgoing, + const std::string& text) { + time_t now = ::time(nullptr); + struct tm tmNow {}; + localtime_r(&now, &tmNow); + char ts[16]; + std::strftime(ts, sizeof(ts), "%H:%M", &tmNow); + std::string clean = text; + for (char& c : clean) { + if (c == '\r' || c == '\n' || c == '\t') c = ' '; + } + std::ofstream out(getFriendChatLogPath(pubKeyHex), std::ios::app); + if (out.is_open()) { + out << ts << "\t" << (outgoing ? "OUT" : "IN") << "\t" << clean << "\n"; + } +} + +void saveToxProfile(Tox* tox) { + if (!tox) return; + size_t sz = tox_get_savedata_size(tox); + if (sz == 0) return; + std::vector buf(sz); + tox_get_savedata(tox, buf.data()); + std::string path = getToxProfilePath(); + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (out.is_open()) { + out.write(reinterpret_cast(buf.data()), + static_cast(buf.size())); + } +} + +std::string getFriendDisplayName(Tox* tox, uint32_t friendNum) { + Tox_Err_Friend_Query err; + size_t sz = tox_friend_get_name_size(tox, friendNum, &err); + if (err == TOX_ERR_FRIEND_QUERY_OK && sz > 0 && sz < 256) { + std::vector buf(sz); + if (tox_friend_get_name(tox, friendNum, buf.data(), &err)) { + std::string name(reinterpret_cast(buf.data()), sz); + if (!trimStr(name).empty()) return trimStr(name); + } + } + uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; + if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) { + return "Tox:" + bytesToHexUpper(pk, 4); + } + return "Friend #" + std::to_string(friendNum); +} + +std::string getFriendPubKeyHex(Tox* tox, uint32_t friendNum) { + uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; + if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) { + return bytesToHexUpper(pk, TOX_PUBLIC_KEY_SIZE); + } + return "0000000000000000"; +} + +void startToxAvAudioPipes(ToxRuntimeContext* ctx) { + std::lock_guard lk(ctx->audioMtx); + if (!ctx->playPipe) { + ctx->playPipe = ::popen("aplay -q -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "w"); + } + if (!ctx->capPipe) { + ctx->capPipe = ::popen("arecord -q -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "r"); + if (ctx->capPipe) { + ctx->capFd = ::fileno(ctx->capPipe); + int fl = ::fcntl(ctx->capFd, F_GETFL, 0); + ::fcntl(ctx->capFd, F_SETFL, fl | O_NONBLOCK); + } + } +} + +void stopToxAvAudioPipes(ToxRuntimeContext* ctx) { + std::lock_guard lk(ctx->audioMtx); + if (ctx->capPipe) { + ::pclose(ctx->capPipe); + ctx->capPipe = nullptr; + ctx->capFd = -1; + } + if (ctx->playPipe) { + ::pclose(ctx->playPipe); + ctx->playPipe = nullptr; + } +} + +// c-toxcore callbacks +void onSelfConnectionStatus(Tox*, Tox_Connection status, void* userData) { + auto* ctx = static_cast(userData); + if (status == TOX_CONNECTION_UDP) { + ctx->dhtConnected = true; + ctx->connBadge = "DHT(UDP)"; + } else if (status == TOX_CONNECTION_TCP) { + ctx->dhtConnected = true; + ctx->connBadge = "DHT(TCP)"; + } else { + ctx->dhtConnected = false; + ctx->connBadge = "SEARCHING"; + } + ctx->uiDirty = true; +} + +void onFriendRequest(Tox*, const Tox_Public_Key publicKey, + const uint8_t message[], size_t length, void* userData) { + auto* ctx = static_cast(userData); + std::string hex = bytesToHexUpper(publicKey, TOX_PUBLIC_KEY_SIZE); + for (const auto& r : ctx->pendingReqs) { + if (r.pubKeyHex == hex) return; + } + PendingFriendReq req; + std::memcpy(req.pubKey, publicKey, TOX_PUBLIC_KEY_SIZE); + req.pubKeyHex = hex; + req.message.assign(reinterpret_cast(message), length); + ctx->pendingReqs.push_back(std::move(req)); + neoui_vibrate(70); + ctx->uiDirty = true; +} + +void onFriendMessage(Tox* tox, Tox_Friend_Number friendNum, + Tox_Message_Type, const uint8_t message[], + size_t length, void* userData) { + auto* ctx = static_cast(userData); + std::string pkHex = getFriendPubKeyHex(tox, friendNum); + std::string txt(reinterpret_cast(message), length); + appendFriendChat(pkHex, false, txt); + neoui_vibrate(60); + ctx->uiDirty = true; +} + +void onFriendName(Tox* tox, Tox_Friend_Number, const uint8_t[], size_t, + void* userData) { + auto* ctx = static_cast(userData); + saveToxProfile(tox); + ctx->uiDirty = true; +} + +void onFriendConnectionStatus(Tox*, Tox_Friend_Number, Tox_Connection, + void* userData) { + auto* ctx = static_cast(userData); + ctx->uiDirty = true; +} + +void onToxAvCall(ToxAV*, Tox_Friend_Number friendNum, bool, bool, + void* userData) { + auto* ctx = static_cast(userData); + if (ctx->inCall) { + toxav_call_control(ctx->toxav, friendNum, TOXAV_CALL_CONTROL_CANCEL, nullptr); + return; + } + ctx->inCall = true; + ctx->callIncoming = true; + ctx->callActive = false; + ctx->callFriendNum = friendNum; + + std::string caller = getFriendDisplayName(ctx->tox, friendNum); + for (char& c : caller) { + if (c == ' ') c = '_'; + } + std::string cid = "tox:" + std::to_string(friendNum); + writeIntFile("/tmp/sxmo_call_ringing", 1); + runAsyncCmd("sxmo_jobs.sh start ringing sxmo_hook_ring.sh >/dev/null 2>&1"); + if (!sendPluginCommand("callscreen", "INCOMING " + cid + " " + caller + " TOX")) { + runAsyncArgv("xcallscreen", "incoming", cid.c_str(), caller.c_str()); + } + ctx->uiDirty = true; +} + +void onToxAvCallState(ToxAV*, Tox_Friend_Number friendNum, uint32_t state, + void* userData) { + auto* ctx = static_cast(userData); + if (friendNum != ctx->callFriendNum) return; + + if (state & (TOXAV_FRIEND_CALL_STATE_FINISHED | TOXAV_FRIEND_CALL_STATE_ERROR)) { + stopToxAvAudioPipes(ctx); + ctx->inCall = false; + ctx->callIncoming = false; + ctx->callActive = false; + ctx->callFriendNum = UINT32_MAX; + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + sendPluginCommand("callscreen", "ENDED TOX CALL ENDED"); + ctx->uiDirty = true; + } else if (state & (TOXAV_FRIEND_CALL_STATE_SENDING_A | + TOXAV_FRIEND_CALL_STATE_ACCEPTING_A)) { + if (!ctx->callActive) { + ctx->callActive = true; + ctx->callIncoming = false; + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + startToxAvAudioPipes(ctx); + std::string caller = getFriendDisplayName(ctx->tox, friendNum); + for (char& c : caller) { + if (c == ' ') c = '_'; + } + sendPluginCommand("callscreen", + "ACTIVE tox:" + std::to_string(friendNum) + " " + caller + " TOX"); + ctx->uiDirty = true; + } + } +} + +void onToxAvAudioReceiveFrame(ToxAV*, Tox_Friend_Number, const int16_t pcm[], + size_t sampleCount, uint8_t channels, + uint32_t, void* userData) { + auto* ctx = static_cast(userData); + std::lock_guard lk(ctx->audioMtx); + if (!ctx->playPipe || !pcm || sampleCount == 0) return; + if (channels == 1) { + std::fwrite(pcm, sizeof(int16_t), sampleCount, ctx->playPipe); + } else { + std::vector mono(sampleCount); + for (size_t i = 0; i < sampleCount; ++i) { + mono[i] = pcm[i * channels]; + } + std::fwrite(mono.data(), sizeof(int16_t), sampleCount, ctx->playPipe); + } + std::fflush(ctx->playPipe); +} + +void bootstrapToxDht(Tox* tox) { + struct BootstrapNode { + const char* host; + uint16_t port; + const char* pubKeyHex; + }; + static const BootstrapNode kNodes[] = { + {"114.35.245.150", 33445, + "3F0A45A268367C1BEA652F258C85F4A66DA76BCAA667A49E770BCC4917AB6A25"}, + {"24.87.200.32", 33445, + "10C00EB250C3233E343E2AEBA07115A5C28920E9C8D29492F6D00B29049EDC7E"}, + {"144.217.167.73", 33445, + "7E5668E0EE09E19F320AD47902419331FFEE147BB3606769CFBE921A2A2FD34C"} + }; + for (const auto& n : kNodes) { + uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; + if (hexToBytes(n.pubKeyHex, pk, TOX_PUBLIC_KEY_SIZE)) { + tox_bootstrap(tox, n.host, n.port, pk, nullptr); + tox_add_tcp_relay(tox, n.host, n.port, pk, nullptr); + } + } +} + +int tox_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], "--preload") == 0) isPreload = true; + else { + if (!initCmd.empty()) initCmd.push_back(' '); + initCmd += argv[i]; + } + } + + std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd)); + if (sendPluginCommand("tox", forwarded)) { + return 0; + } + + std::string daemonPidPath = getPluginDaemonPidPath("tox"); + std::string activePidPath = getRuntimeFile("xtox.pid"); + writeIntFile(daemonPidPath, static_cast(::getpid())); + int fifoFd = setupPluginDaemonFifo("tox"); + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + NeoWindow neo; + if (!neo.create("xtox", "XTox", "Tox Messenger")) { + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(daemonPidPath.c_str()); + return 1; + } + neo.bindAsActiveContext(); + + // Initialize c-toxcore instance from savedata or fresh profile + Tox_Options* opts = tox_options_new(nullptr); + tox_options_set_ipv6_enabled(opts, false); + tox_options_set_udp_enabled(opts, true); + tox_options_set_local_discovery_enabled(opts, true); + + std::vector savedData; + { + std::ifstream in(getToxProfilePath(), std::ios::binary); + if (in.is_open()) { + savedData.assign(std::istreambuf_iterator(in), + std::istreambuf_iterator()); + if (!savedData.empty()) { + tox_options_set_savedata_type(opts, TOX_SAVEDATA_TYPE_TOX_SAVE); + tox_options_set_savedata_data(opts, savedData.data(), savedData.size()); + } + } + } + + Tox_Err_New newErr = TOX_ERR_NEW_OK; + Tox* tox = tox_new(opts, &newErr); + tox_options_free(opts); + if (!tox) { + tox = tox_new(nullptr, &newErr); + } + + ToxRuntimeContext ctx; + ctx.tox = tox; + if (tox) { + if (tox_self_get_name_size(tox) == 0) { + const char* defName = "Bananarchy"; + tox_self_set_name(tox, reinterpret_cast(defName), + std::strlen(defName), nullptr); + const char* defStatus = "On Bananarchy Linux"; + tox_self_set_status_message(tox, reinterpret_cast(defStatus), + std::strlen(defStatus), nullptr); + } + saveToxProfile(tox); + + tox_callback_self_connection_status(tox, onSelfConnectionStatus); + tox_callback_friend_request(tox, onFriendRequest); + tox_callback_friend_message(tox, onFriendMessage); + tox_callback_friend_name(tox, onFriendName); + tox_callback_friend_connection_status(tox, onFriendConnectionStatus); + + ctx.toxav = toxav_new(tox, nullptr); + if (ctx.toxav) { + toxav_callback_call(ctx.toxav, onToxAvCall, &ctx); + toxav_callback_call_state(ctx.toxav, onToxAvCallState, &ctx); + toxav_callback_audio_receive_frame(ctx.toxav, onToxAvAudioReceiveFrame, &ctx); + } + } + + // Export Tox ID to /tmp/tox_id.txt for easy sharing + std::string selfToxIdHex; + if (tox) { + uint8_t addr[TOX_ADDRESS_SIZE] = {0}; + tox_self_get_address(tox, addr); + selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE); + std::ofstream idOut("/tmp/tox_id.txt", std::ios::trunc); + if (idOut.is_open()) { + idOut << selfToxIdHex << "\n"; + } + } + + bool networkActive = false; + int64_t lastBootstrapMs = 0; + + bool visible = false; + int activeTab = 0; // 0=Friends, 1=Chat, 2=My Tox ID + int selectedRow = 0; + int scrollOffset = 0; + uint32_t activeFriendNum = 0; + bool hasActiveFriend = false; + int chatScrollBack = 0; + std::string chatInput; + bool menuOpen = false; + int menuSel = 0; + + // Add friend modal + bool addModalOpen = false; + std::string addToxIdStr; + + auto getFriendList = [&]() -> std::vector { + std::vector list; + if (!tox) return list; + size_t cnt = tox_self_get_friend_list_size(tox); + if (cnt > 0) { + list.resize(cnt); + tox_self_get_friend_list(tox, list.data()); + } + return list; + }; + + auto ensureNetworkStarted = [&]() { + if (!tox) return; + if (!networkActive) { + networkActive = true; + ctx.connBadge = "CONNECTING"; + bootstrapToxDht(tox); + lastBootstrapMs = nowMs(); + } + }; + + auto render = [&]() { + if (!visible) return; + neo.bindAsActiveContext(); + neoui_begin_frame(); + + neoui_draw_header(kIconShield, ctx.dhtConnected ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, + "Tox / Trifa", ctx.connBadge.c_str()); + neoui_draw_tabs("Friends|Chat|Tox ID", activeTab, 34, 24); + + constexpr int kBodyY = 58; + constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; + std::vector friends = getFriendList(); + + if (activeTab == 0) { + int totalItems = static_cast(ctx.pendingReqs.size() + friends.size()); + int rowH = 42; + int maxVis = kBodyH / rowH; + if (totalItems == 0) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 55, + 240, 24, "No Tox Friends Yet"); + neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 82, + 240, 20, "Press OK or Menu -> Add Friend"); + } else { + selectedRow = std::clamp(selectedRow, 0, totalItems - 1); + if (selectedRow < scrollOffset) scrollOffset = selectedRow; + if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; + for (int i = 0; i < maxVis && (scrollOffset + i) < totalItems; ++i) { + int idx = scrollOffset + i; + if (idx < static_cast(ctx.pendingReqs.size())) { + const auto& r = ctx.pendingReqs[idx]; + std::string title = "Req: " + r.pubKeyHex.substr(0, 12) + "..."; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconPlus, NEO_TEXT_YELLOW, title.c_str(), + r.message.c_str(), "ACCEPT"); + } else { + uint32_t fnum = friends[idx - static_cast(ctx.pendingReqs.size())]; + std::string name = getFriendDisplayName(tox, fnum); + std::string pkHex = getFriendPubKeyHex(tox, fnum).substr(0, 16); + Tox_Connection cstat = tox_friend_get_connection_status(tox, fnum, nullptr); + const char* badge = (cstat == TOX_CONNECTION_UDP) ? "UDP" + : ((cstat == TOX_CONNECTION_TCP) ? "TCP" : "OFF"); + int col = (cstat != TOX_CONNECTION_NONE) ? NEO_TEXT_GREEN : NEO_TEXT_MUTED; + neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, + kIconUser, col, name.c_str(), pkHex.c_str(), badge); + } + } + neoui_draw_scrollbar(236, kBodyY, kBodyH, totalItems, maxVis, scrollOffset); + } + neoui_draw_softkeys("Menu", totalItems == 0 ? "ADD" : "CHAT", "Close"); + } else if (activeTab == 1) { + if (!hasActiveFriend && !friends.empty()) { + activeFriendNum = friends[0]; + hasActiveFriend = true; + } + if (!hasActiveFriend) { + neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 70, + 240, 24, "Select a friend first"); + neoui_draw_softkeys("Menu", "FRIENDS", "Back"); + } else { + std::string pkHex = getFriendPubKeyHex(tox, activeFriendNum); + std::vector chat = loadFriendChat(pkHex); + int msgAreaH = kBodyH - 48; + int lineH = 18; + int maxLines = msgAreaH / lineH; + int total = static_cast(chat.size()); + chatScrollBack = std::clamp(chatScrollBack, 0, std::max(0, total - maxLines)); + int startIdx = std::max(0, total - maxLines - chatScrollBack); + + for (int i = 0; i < maxLines && (startIdx + i) < total; ++i) { + const auto& m = chat[startIdx + i]; + std::string line = m.timeStr + (m.outgoing ? " Me: " : " Peer: ") + m.text; + neoui_draw_text(NEO_FONT_SMALL, + m.outgoing ? NEO_TEXT_GREEN : NEO_TEXT_WHITE, + 6, kBodyY + 2 + i * lineH, lineH, line.c_str(), 228); + } + neoui_draw_input_box(4, kBodyY + msgAreaH, 232, 26, 1, "", + neoui_input_get_text(), "Encrypted Tox message...", 0); + neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20, + "[OK] Send [Call] Voice Call [*] Mode"); + neoui_draw_softkeys("Menu", "SEND", "Back"); + } + } else { + neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 4, 18, + "Your 76-char Tox ID (saved in /tmp/tox_id.txt):", 224); + // Display 76 hex chars across 4 clean lines of 19 chars + for (int row = 0; row < 4; ++row) { + size_t pos = static_cast(row * 19); + if (pos < selfToxIdHex.size()) { + std::string chunk = selfToxIdHex.substr(pos, 19); + neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, 12, + kBodyY + 26 + row * 22, 20, chunk.c_str(), 216); + } + } + neoui_draw_button(12, kBodyY + 124, 216, 32, 1, 0, kIconPlus, + "Add Friend by Tox ID"); + neoui_draw_softkeys("Menu", "ADD FRIEND", "Back"); + } + + if (addModalOpen) { + neoui_draw_modal_box(6, 48, 228, 170, kIconPlus, NEO_TEXT_YELLOW, + "Add Friend (76-hex Tox ID)"); + neoui_draw_input_box(12, 82, 216, 48, 1, "Tox ID:", + neoui_input_get_text(), "76 hex chars...", 0); + neoui_draw_multitap_bar(12, 140, 216, 22, "[*] Mode [Left Soft] Add"); + neoui_draw_softkeys("Add", "PASTE /TMP", "Cancel"); + } else if (menuOpen) { + neoui_draw_menu_popup( + "Add Friend by Tox ID|Start Voice Call|Bootstrap DHT Now|Rotate NoSpam|Delete Friend", + nullptr, menuSel, 5); + } + + neoui_end_frame(); + }; + + auto startOutgoingToxCall = [&](uint32_t friendNum) { + if (!ctx.toxav || ctx.inCall) return; + Toxav_Err_Call err; + if (toxav_call(ctx.toxav, friendNum, 32, 0, &err)) { + ctx.inCall = true; + ctx.callIncoming = false; + ctx.callActive = false; + ctx.callFriendNum = friendNum; + std::string name = getFriendDisplayName(tox, friendNum); + for (char& c : name) { + if (c == ' ') c = '_'; + } + sendPluginCommand("callscreen", + "OUTGOING tox:" + std::to_string(friendNum) + " " + name + " TOX"); + } else { + neoui_show_toast("Friend is offline or busy", 2000); + } + }; + + auto openWindow = [&]() { + if (isPhonePasscodeLocked()) return; + writeIntFile(activePidPath, static_cast(::getpid())); + closeOtherPlugins("tox"); + visible = true; + neoui_show(); + neoui_input_reset(chatInput.c_str()); + render(); + ensureNetworkStarted(); + }; + + auto closeWindow = [&]() { + if (!visible) return; + visible = false; + addModalOpen = false; + menuOpen = false; + neoui_hide(); + ::unlink(activePidPath.c_str()); + }; + + if (!isPreload) { + openWindow(); + } + + while (gRunning) { + for (const std::string& cmd : readFifoLines(fifoFd)) { + if (cmd == "NOP") continue; + if (cmd == "CLOSE") closeWindow(); + else if (cmd == "RELOAD_THEME") { + neo.reloadTheme(); + if (visible) render(); + } else if (cmd.rfind("CALL_ACCEPT", 0) == 0) { + if (ctx.inCall && ctx.callIncoming && ctx.toxav) { + if (toxav_answer(ctx.toxav, ctx.callFriendNum, 32, 0, nullptr)) { + ctx.callActive = true; + ctx.callIncoming = false; + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + startToxAvAudioPipes(&ctx); + std::string caller = getFriendDisplayName(tox, ctx.callFriendNum); + for (char& c : caller) { + if (c == ' ') c = '_'; + } + sendPluginCommand("callscreen", + "ACTIVE tox:" + std::to_string(ctx.callFriendNum) + + " " + caller + " TOX"); + } + } + } else if (cmd.rfind("CALL_HANGUP", 0) == 0) { + if (ctx.inCall && ctx.toxav) { + toxav_call_control(ctx.toxav, ctx.callFriendNum, + TOXAV_CALL_CONTROL_CANCEL, nullptr); + stopToxAvAudioPipes(&ctx); + ctx.inCall = false; + ctx.callIncoming = false; + ctx.callActive = false; + ctx.callFriendNum = UINT32_MAX; + } + } else if (cmd.rfind("CALL_MUTE_RING", 0) == 0) { + ::unlink("/tmp/sxmo_call_ringing"); + runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " + "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); + } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + openWindow(); + } + } + + // Iterate Tox and ToxAV when visible, in a call, or when friends are configured + bool shouldIterateTox = + networkActive && tox && + (visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0); + if (shouldIterateTox) { + tox_iterate(tox, &ctx); + if (ctx.toxav) { + toxav_iterate(ctx.toxav); + } + if (ctx.inCall && ctx.callActive && ctx.capFd >= 0 && ctx.toxav) { + // Send 20ms (960 samples @ 48kHz) audio frames when available + int16_t pcmFrame[960]; + ssize_t r = ::read(ctx.capFd, pcmFrame, sizeof(pcmFrame)); + if (r == sizeof(pcmFrame)) { + toxav_audio_send_frame(ctx.toxav, ctx.callFriendNum, pcmFrame, 960, 1, + 48000, nullptr); + } + } + if (!ctx.dhtConnected && nowMs() - lastBootstrapMs >= 30000) { + bootstrapToxDht(tox); + lastBootstrapMs = nowMs(); + } + if (ctx.uiDirty && visible) { + ctx.uiDirty = false; + render(); + } + } + + if (visible) { + neo.bindAsActiveContext(); + int ev = neoui_poll_event(0); + while (ev != NEO_EV_NONE) { + if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) { + render(); + } else if (ev == NEO_EV_CLOSE_REQ) { + closeWindow(); + break; + } else if (ev == NEO_EV_SOFTKEY_LEFT) { + if (addModalOpen) { + std::string rawId = trimStr(neoui_input_get_text()); + uint8_t addrBytes[TOX_ADDRESS_SIZE] = {0}; + if (hexToBytes(rawId, addrBytes, TOX_ADDRESS_SIZE)) { + const char* msg = "Hello from Bananarchy Linux"; + Tox_Err_Friend_Add addErr; + tox_friend_add(tox, addrBytes, + reinterpret_cast(msg), + std::strlen(msg), &addErr); + saveToxProfile(tox); + addModalOpen = false; + neoui_show_toast("Friend request sent", 2000); + } else { + neoui_show_toast("Invalid 76-hex Tox ID", 2000); + } + render(); + } else { + menuOpen = !menuOpen; + menuSel = 0; + render(); + } + } else if (ev == NEO_EV_SOFTKEY_RIGHT) { + if (addModalOpen) { + addModalOpen = false; + render(); + } else if (menuOpen) { + menuOpen = false; + render(); + } else if (activeTab != 0) { + activeTab = 0; + render(); + } else { + closeWindow(); + break; + } + } else if (ev == NEO_EV_KEY_PRESS) { + int k = neoui_event_key(); + std::vector friends = getFriendList(); + if (menuOpen) { + if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5; + else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5; + else if (k == NEO_KEY_OK) { + menuOpen = false; + if (menuSel == 0) { + addModalOpen = true; + neoui_input_reset(""); + } else if (menuSel == 1 && hasActiveFriend) { + startOutgoingToxCall(activeFriendNum); + } else if (menuSel == 2) { + ensureNetworkStarted(); + bootstrapToxDht(tox); + neoui_show_toast("DHT bootstrap triggered", 1500); + } else if (menuSel == 3 && tox) { + tox_self_set_nospam(tox, static_cast(nowMs())); + uint8_t addr[TOX_ADDRESS_SIZE] = {0}; + tox_self_get_address(tox, addr); + selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE); + saveToxProfile(tox); + } else if (menuSel == 4 && activeTab == 0 && !friends.empty()) { + int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); + if (fIdx >= 0 && fIdx < static_cast(friends.size())) { + tox_friend_delete(tox, friends[fIdx], nullptr); + saveToxProfile(tox); + } + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + menuOpen = false; + } + render(); + } else if (addModalOpen) { + if (k == NEO_KEY_OK) { + // Paste from /tmp/tox_add.txt if present + std::ifstream pf("/tmp/tox_add.txt"); + if (pf.is_open()) { + std::string line; + std::getline(pf, line); + neoui_input_set_text(trimStr(line).c_str()); + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + neoui_input_backspace(); + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + } + render(); + } else { + if (k == NEO_KEY_LEFT) { + activeTab = (activeTab + 2) % 3; + selectedRow = 0; + scrollOffset = 0; + } else if (k == NEO_KEY_RIGHT) { + activeTab = (activeTab + 1) % 3; + selectedRow = 0; + scrollOffset = 0; + } else if (activeTab == 0) { + if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow; + else if (k == NEO_KEY_DOWN) ++selectedRow; + else if (k == NEO_KEY_CALL) { + int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); + if (fIdx >= 0 && fIdx < static_cast(friends.size())) { + startOutgoingToxCall(friends[fIdx]); + } + } else if (k == NEO_KEY_OK) { + if (ctx.pendingReqs.empty() && friends.empty()) { + addModalOpen = true; + neoui_input_reset(""); + } else if (selectedRow >= 0 && + selectedRow < static_cast(ctx.pendingReqs.size())) { + auto req = ctx.pendingReqs[selectedRow]; + ctx.pendingReqs.erase(ctx.pendingReqs.begin() + selectedRow); + tox_friend_add_norequest(tox, req.pubKey, nullptr); + saveToxProfile(tox); + neoui_show_toast("Friend request accepted", 1500); + } else { + int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); + if (fIdx >= 0 && fIdx < static_cast(friends.size())) { + activeFriendNum = friends[fIdx]; + hasActiveFriend = true; + activeTab = 1; + chatScrollBack = 0; + neoui_input_reset(""); + } + } + } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { + closeWindow(); + break; + } + } else if (activeTab == 1) { + if (k == NEO_KEY_UP) ++chatScrollBack; + else if (k == NEO_KEY_DOWN && chatScrollBack > 0) --chatScrollBack; + else if (k == NEO_KEY_CALL && hasActiveFriend) { + startOutgoingToxCall(activeFriendNum); + } else if (k == NEO_KEY_OK && hasActiveFriend) { + std::string txt = trimStr(neoui_input_get_text()); + if (!txt.empty()) { + Tox_Err_Friend_Send_Message sendErr; + tox_friend_send_message(tox, activeFriendNum, + TOX_MESSAGE_TYPE_NORMAL, + reinterpret_cast(txt.data()), + txt.size(), &sendErr); + if (sendErr == TOX_ERR_FRIEND_SEND_MESSAGE_OK) { + appendFriendChat(getFriendPubKeyHex(tox, activeFriendNum), + true, txt); + neoui_input_reset(""); + } else { + neoui_show_toast("Friend is currently offline", 2000); + } + } + } else if (k == NEO_KEY_STAR) { + neoui_input_cycle_mode(); + } else if (k == NEO_KEY_BACK) { + if (!std::string(neoui_input_get_text()).empty()) { + neoui_input_backspace(); + } else { + activeTab = 0; + } + } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + neoui_input_feed_key(k); + } + } else if (activeTab == 2) { + if (k == NEO_KEY_OK) { + addModalOpen = true; + neoui_input_reset(""); + } + } + render(); + } + } + ev = neoui_poll_event(0); + } + } else { + while (XPending(neo.dpy) > 0) { + XEvent xev; + XNextEvent(neo.dpy, &xev); + } + } + + struct pollfd pfds[2] {}; + pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 }; + pfds[1] = { fifoFd, POLLIN, 0 }; + int timeoutMs = -1; + if (ctx.inCall && ctx.callActive) { + timeoutMs = 20; + } else if (visible) { + timeoutMs = neoui_input_is_tap_active() ? 100 : 200; + } else if (shouldIterateTox) { + timeoutMs = static_cast( + std::clamp(tox_iteration_interval(tox), 250, 1000)); + } + ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); + } + + stopToxAvAudioPipes(&ctx); + if (ctx.toxav) toxav_kill(ctx.toxav); + if (tox) { + saveToxProfile(tox); + tox_kill(tox); + } + if (fifoFd >= 0) ::close(fifoFd); + ::unlink(getPluginFifoPath("tox").c_str()); + ::unlink(daemonPidPath.c_str()); + return 0; +} + +int tox_plugin_init(const DwmHostApi* host) { + if (host && host->spawn_plugin) { + host->spawn_plugin("tox", "--preload"); + } + return 0; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { + DWM_PLUGIN_API_VERSION, + "tox", + "Tox / Trifa P2P messenger and audio call client (c-toxcore)", + tox_plugin_init, + nullptr, + nullptr, + nullptr, + nullptr, + tox_run_main +}; diff --git a/src/neoui/neoui.cpp b/src/neoui/neoui.cpp index 647b5a2..da40514 100644 --- a/src/neoui/neoui.cpp +++ b/src/neoui/neoui.cpp @@ -1659,7 +1659,7 @@ int neoui_hide(void) { XUnmapWindow(ctx->w->dpy, ctx->w->win); ctx->visible = false; ctx->softkeyPending = 0; - XFlush(ctx->w->dpy); + XSync(ctx->w->dpy, True); return 1; }