Files
bananarchy/src/dwm-plugins/sip_plugin.cpp
T

1595 lines
59 KiB
C++
Raw Normal View History

// 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 <atomic>
#include <fstream>
#include <mutex>
#include <thread>
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<int16_t>(-pcmVal);
if (pcmVal > kClip) pcmVal = kClip;
pcmVal = static_cast<int16_t>(pcmVal + kBias);
int seg = 0;
for (int thr = 0xFF; seg < 7 && pcmVal > thr; ++seg, thr = (thr << 1) | 1) {
}
uint8_t uval = static_cast<uint8_t>((seg << 4) | ((pcmVal >> (seg + 3)) & 0x0f));
return static_cast<uint8_t>(uval ^ mask);
}
int16_t ulawToLinear(uint8_t uval) {
uval = static_cast<uint8_t>(~uval);
int t = (((uval & 0x0f) << 3) + 0x84) << ((uval & 0x70) >> 4);
return static_cast<int16_t>((uval & 0x80) ? (0x84 - t) : (t - 0x84));
}
uint8_t linearToAlaw(int16_t pcmVal) {
int mask = 0x55;
if (pcmVal >= 0) {
mask |= 0x80;
} else {
pcmVal = static_cast<int16_t>(-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<uint8_t>((pcmVal >> 4) & 0x0f)
: static_cast<uint8_t>((seg << 4) | ((pcmVal >> (seg + 3)) & 0x0f));
return static_cast<uint8_t>(aval ^ mask);
}
int16_t alawToLinear(uint8_t aval) {
aval ^= 0x55;
int t = (aval & 0x0f) << 4;
int seg = (static_cast<unsigned>(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<int16_t>((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<SipAccount> loadSipAccounts() {
std::vector<SipAccount> list;
std::ifstream in(getSipAccountsPath());
std::string line;
while (std::getline(in, line)) {
line = trimStr(line);
if (line.empty() || line[0] == '#') continue;
std::vector<std::string> 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<SipAccount>& 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<SipCallLog> loadSipHistory() {
std::vector<SipCallLog> list;
std::ifstream in(getSipHistoryPath());
std::string line;
while (std::getline(in, line)) {
line = trimStr(line);
if (line.empty()) continue;
std::vector<std::string> 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<struct sockaddr*>(&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<uint16_t>(localPort));
if (::bind(sock, reinterpret_cast<struct sockaddr*>(&localAddr),
sizeof(localAddr)) < 0) {
localAddr.sin_port = 0;
::bind(sock, reinterpret_cast<struct sockaddr*>(&localAddr),
sizeof(localAddr));
}
struct sockaddr_in remAddr {};
remAddr.sin_family = AF_INET;
remAddr.sin_port = htons(static_cast<uint16_t>(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<struct sockaddr_in*>(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<std::mutex> 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<uint16_t>(nowMs() & 0xffff);
uint32_t ts = static_cast<uint32_t>(nowMs() * 8);
uint32_t ssrc = 0x51504241u ^ static_cast<uint32_t>(::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<ssize_t>(hdrLen)) continue;
const uint8_t* payload = rxPkt + hdrLen;
size_t payLen = static_cast<size_t>(n) - hdrLen;
if (playFp && (pt == 0 || pt == 8)) {
int16_t pcmOut[640];
size_t samples = std::min<size_t>(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<std::mutex> 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<uint8_t>(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<uint8_t>((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<uint8_t>((p == 2 ? 0x80 : 0x00) | 10);
uint16_t dur = htons(static_cast<uint16_t>((p + 1) * 160));
std::memcpy(pkt + 14, &dur, 2);
::sendto(sock_, pkt, sizeof(pkt), 0,
reinterpret_cast<const struct sockaddr*>(&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<uint8_t>(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<const struct sockaddr*>(&remAddr_),
sizeof(remAddr_));
ts += 160;
}
}
struct pollfd pfd { sock_, POLLIN, 0 };
int waitMs = static_cast<int>(std::max<int64_t>(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<bool> 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<int>(::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<uint16_t>(localSipPort));
if (::bind(sipUdpFd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
addr.sin_port = 0;
if (::bind(sipUdpFd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == 0) {
socklen_t sl = sizeof(addr);
if (::getsockname(sipUdpFd, reinterpret_cast<struct sockaddr*>(&addr), &sl) == 0) {
localSipPort = ntohs(addr.sin_port);
}
}
}
}
std::vector<SipAccount> accounts = loadSipAccounts();
std::vector<SipCallLog> 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<const struct sockaddr*>(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 << "\" <sip:" << acct.username << "@"
<< acct.domain << ">;tag=" << acct.fromTag << "\r\n"
<< "To: <sip:" << acct.username << "@" << acct.domain << ">\r\n"
<< "Call-ID: " << acct.callId << "\r\n"
<< "CSeq: " << acct.cseq++ << " REGISTER\r\n"
<< "Contact: <sip:" << acct.username << "@" << localIp << ":"
<< localSipPort << ">\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<uint32_t>(::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<int>(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 << "\" <sip:" << acct.username << "@"
<< acct.domain << ">;tag=" << activeLocalTag << "\r\n"
<< "To: <" << targetUri << ">\r\n"
<< "Call-ID: " << activeSipCallId << "\r\n"
<< "CSeq: " << activeCseq << " INVITE\r\n"
<< "Contact: <sip:" << acct.username << "@" << localIp << ":"
<< localSipPort << ">\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<int>(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: <sip:user@" << localIp << ":" << localSipPort << ">\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<const struct sockaddr*>(&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<int>(accounts.size()))
? accounts[activeAccountIdx].label
: "SIP";
int durSec = (callState == SipCallState::Active && callStartedMs > 0)
? static_cast<int>((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<const struct sockaddr*>(&activePeerSin),
sizeof(activePeerSin));
appendSipHistory("MISSED", activePeerUri, acctLbl, 0);
} else if (callState == SipCallState::Outgoing ||
callState == SipCallState::Active) {
if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(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 << "\" <sip:" << acct.username << "@"
<< acct.domain << ">;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 <code> <reason>)
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<int>(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 << "\" <sip:" << acct.username
<< "@" << acct.domain << ">;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<int>(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 << "\" <sip:" << acct.username
<< "@" << acct.domain << ">;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<const struct sockaddr*>(&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<const struct sockaddr*>(&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<const struct sockaddr*>(&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<const struct sockaddr*>(&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<int>(accounts.size()))
? accounts[activeAccountIdx].label
: "SIP";
int durSec = (callState == SipCallState::Active && callStartedMs > 0)
? static_cast<int>((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<int>(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<int>(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<int>(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<int>(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<int>(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<int>(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<int>(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<int>(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<int>(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<int>(::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<struct sockaddr*>(&fromSin), &sl);
if (n <= 0) break;
rxBuf[n] = '\0';
handleIncomingSipPacket(std::string(rxBuf, static_cast<size_t>(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<int>(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<int>(accounts.size());
} else if (menuSel == 3 && activeTab == 1 &&
selectedRow >= 0 && selectedRow < static_cast<int>(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<int>(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<int>(accounts.size()) - 1),
target);
}
} else if (activeTab == 1) {
if (accounts.empty()) {
editAcctIdx = -1;
editAcctDraft = SipAccount{};
} else {
editAcctIdx = std::clamp(selectedRow, 0,
static_cast<int>(accounts.size()) - 1);
editAcctDraft = accounts[editAcctIdx];
}
editFieldIdx = 0;
editModalOpen = true;
syncInputBufferForFocus();
} else if (activeTab == 2 && selectedRow >= 0 &&
selectedRow < static_cast<int>(history.size()) &&
!accounts.empty()) {
sendSipInvite(std::clamp(activeAccountIdx, 0,
static_cast<int>(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
};