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

2794 lines
106 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
// - Direct peer-to-peer / URI outbound calling without a SIP account
// - 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
// - RFC 6189 ZRTP media key agreement (DH3k/DH2k + B32 SAS) + RFC 3711 SRTP
// - NeoUI 3-tab interface: Dialer, Accounts, and Call History
#include "../sxmo-dwm/dwm_plugin.h"
#include "net_tls.h"
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/sha.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);
}
// ---------------------------------------------------------------------------
// RFC 6189 ZRTP & RFC 3711 SRTP Cryptographic Helpers
// ---------------------------------------------------------------------------
// RFC 3526 Group 15 (3072-bit MODP Group for ZRTP "DH3k")
constexpr const char* kDh3kPrimeHex =
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
// RFC 3526 Group 14 (2048-bit MODP Group for ZRTP "DH2k")
constexpr const char* kDh2kPrimeHex =
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
// Castagnoli CRC-32C (polynomial 0x1EDC6F41, reversed 0x82F63B78) per RFC 6189 Section 5
uint32_t zrtpCrc32c(const uint8_t* data, size_t len) {
uint32_t crc = 0xFFFFFFFFu;
for (size_t i = 0; i < len; ++i) {
crc ^= data[i];
for (int b = 0; b < 8; ++b) {
if (crc & 1u) {
crc = (crc >> 1) ^ 0x82F63B78u;
} else {
crc >>= 1;
}
}
}
return ~crc;
}
void sha256Bytes(const uint8_t* data, size_t len, uint8_t out[32]) {
SHA256(data, len, out);
}
std::string bytesToHexLower(const uint8_t* data, size_t len) {
static const char kHex[] = "0123456789abcdef";
std::string s;
s.reserve(len * 2);
for (size_t i = 0; i < len; ++i) {
s.push_back(kHex[(data[i] >> 4) & 0x0f]);
s.push_back(kHex[data[i] & 0x0f]);
}
return s;
}
void hmacSha256(const uint8_t* key, size_t keyLen,
const uint8_t* data, size_t dataLen,
uint8_t out[32]) {
unsigned int outLen = 32;
HMAC(EVP_sha256(), key, static_cast<int>(keyLen), data, dataLen, out, &outLen);
}
void hmacSha1(const uint8_t* key, size_t keyLen,
const uint8_t* data, size_t dataLen,
uint8_t out[20]) {
unsigned int outLen = 20;
HMAC(EVP_sha1(), key, static_cast<int>(keyLen), data, dataLen, out, &outLen);
}
// RFC 6189 Section 4.5.1 KDF(KI, Label, Context, L)
std::vector<uint8_t> zrtpKdf(const uint8_t ki[32], const std::string& label,
const std::vector<uint8_t>& context,
uint32_t numBits) {
std::vector<uint8_t> input;
input.reserve(4 + label.size() + 1 + context.size() + 4);
// Counter = 0x00000001
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x01);
input.insert(input.end(), label.begin(), label.end());
input.push_back(0x00);
input.insert(input.end(), context.begin(), context.end());
input.push_back(static_cast<uint8_t>((numBits >> 24) & 0xff));
input.push_back(static_cast<uint8_t>((numBits >> 16) & 0xff));
input.push_back(static_cast<uint8_t>((numBits >> 8) & 0xff));
input.push_back(static_cast<uint8_t>(numBits & 0xff));
uint8_t digest[32];
hmacSha256(ki, 32, input.data(), input.size(), digest);
size_t outBytes = (numBits + 7) / 8;
return std::vector<uint8_t>(digest, digest + std::min<size_t>(outBytes, 32));
}
// RFC 3711 Section 4.1.1 AES-128 Counter Mode keystream generation
void aes128CtrCrypt(const uint8_t key[16], const uint8_t iv[16],
uint8_t* buf, size_t len) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) return;
int outLen = 0;
int finalLen = 0;
std::vector<uint8_t> out(len + 16);
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key, iv) == 1) {
EVP_EncryptUpdate(ctx, out.data(), &outLen, buf, static_cast<int>(len));
EVP_EncryptFinal_ex(ctx, out.data() + outLen, &finalLen);
std::memcpy(buf, out.data(), len);
}
EVP_CIPHER_CTX_free(ctx);
}
// AES-128-CFB128 encryption/decryption for ZRTP Confirm1/Confirm2 (RFC 6189 Section 5.7)
void aes128CfbCrypt(const uint8_t key[16], const uint8_t ivIn[16],
uint8_t* buf, size_t len, bool encrypt) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) return;
uint8_t iv[16];
std::memcpy(iv, ivIn, 16);
std::vector<uint8_t> out(len + 16);
int outLen = 0;
int finalLen = 0;
if (EVP_CipherInit_ex(ctx, EVP_aes_128_cfb128(), nullptr, key, iv,
encrypt ? 1 : 0) == 1) {
EVP_CipherUpdate(ctx, out.data(), &outLen, buf, static_cast<int>(len));
EVP_CipherFinal_ex(ctx, out.data() + outLen, &finalLen);
std::memcpy(buf, out.data(), len);
}
EVP_CIPHER_CTX_free(ctx);
}
// RFC 3711 Section 4.3.1 SRTP Key Derivation using AES-128-CM PRF
struct SrtpDirectionKeys {
uint8_t cipherKey[16] {};
uint8_t authKey[20] {};
uint8_t salt[14] {};
uint32_t roc = 0;
uint16_t lastSeq = 0;
bool seqInitialized = false;
int tagBytes = 10; // 10 bytes for HS80, 4 bytes for HS32
void deriveFromMaster(const uint8_t masterKey[16],
const uint8_t masterSalt[14],
int authTagBytes) {
tagBytes = authTagBytes;
roc = 0;
lastSeq = 0;
seqInitialized = false;
auto deriveLabel = [&](uint8_t label, uint8_t* out, size_t outLen) {
uint8_t iv[16] {};
std::memcpy(iv, masterSalt, 14);
iv[7] ^= label; // r = index DIV kdr = 0, so label is at byte 7 (salt[7])
std::memset(out, 0, outLen);
aes128CtrCrypt(masterKey, iv, out, outLen);
};
deriveLabel(0x00, cipherKey, sizeof(cipherKey));
deriveLabel(0x01, authKey, sizeof(authKey));
deriveLabel(0x02, salt, sizeof(salt));
}
void computePacketIv(uint32_t ssrc, uint64_t pktIndex, uint8_t ivOut[16]) const {
std::memset(ivOut, 0, 16);
std::memcpy(ivOut, salt, 14);
// XOR SSRC at bytes 4..7 and 48-bit packet index at bytes 8..13
ivOut[4] ^= static_cast<uint8_t>((ssrc >> 24) & 0xff);
ivOut[5] ^= static_cast<uint8_t>((ssrc >> 16) & 0xff);
ivOut[6] ^= static_cast<uint8_t>((ssrc >> 8) & 0xff);
ivOut[7] ^= static_cast<uint8_t>(ssrc & 0xff);
ivOut[8] ^= static_cast<uint8_t>((pktIndex >> 40) & 0xff);
ivOut[9] ^= static_cast<uint8_t>((pktIndex >> 32) & 0xff);
ivOut[10] ^= static_cast<uint8_t>((pktIndex >> 24) & 0xff);
ivOut[11] ^= static_cast<uint8_t>((pktIndex >> 16) & 0xff);
ivOut[12] ^= static_cast<uint8_t>((pktIndex >> 8) & 0xff);
ivOut[13] ^= static_cast<uint8_t>(pktIndex & 0xff);
}
};
void loadOrCreateLocalZid(uint8_t zidOut[12]) {
std::string path = getHomeDirPath() + "/.local/share/sxmo/sip_zid.bin";
std::ifstream in(path, std::ios::binary);
if (in.is_open()) {
in.read(reinterpret_cast<char*>(zidOut), 12);
if (in.gcount() == 12) return;
}
if (RAND_bytes(zidOut, 12) != 1) {
for (int i = 0; i < 12; ++i) {
zidOut[i] = static_cast<uint8_t>((nowMs() >> (i * 3)) ^ (::getpid() + i * 37));
}
}
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (out.is_open()) {
out.write(reinterpret_cast<const char*>(zidOut), 12);
}
}
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
bool zrtpEnabled = true;
// 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];
}
if (cols.size() >= 9 && !cols[8].empty()) {
a.zrtpEnabled = (cols[8] != "0" && toLowerStr(cols[8]) != "false" &&
toLowerStr(cols[8]) != "off");
}
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 << "\t"
<< (a.zrtpEnabled ? "1" : "0") << "\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) {
std::string target = remoteHost.empty() ? "8.8.8.8" : remoteHost;
struct addrinfo hints {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
struct addrinfo* res = nullptr;
if (::getaddrinfo(target.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";
}
// Parse a dial string ("user@host:port", "sip:user@host", "192.168.1.50:5060", "1001")
bool resolveSipTarget(const std::string& rawInput,
const SipAccount* acct,
std::string& outTargetUri,
std::string& outHost,
int& outPort) {
std::string s = trimStr(rawInput);
if (s.empty()) return false;
if (s.front() == '<' && s.back() == '>' && s.size() > 2) {
s = trimStr(s.substr(1, s.size() - 2));
}
if (toLowerStr(s).rfind("sip:", 0) == 0) {
s = s.substr(4);
} else if (toLowerStr(s).rfind("sips:", 0) == 0) {
s = s.substr(5);
}
// Strip any URI parameters (;transport=...)
size_t semi = s.find(';');
if (semi != std::string::npos) {
s = s.substr(0, semi);
}
if (s.empty()) return false;
std::string userPart;
std::string hostPortPart;
size_t atPos = s.find('@');
if (atPos != std::string::npos) {
userPart = s.substr(0, atPos);
hostPortPart = s.substr(atPos + 1);
} else if (acct && !acct->domain.empty()) {
userPart = s;
hostPortPart = acct->domain;
outHost = acct->domain;
outPort = acct->port > 0 ? acct->port : 5060;
outTargetUri = "sip:" + userPart + "@" + acct->domain;
return true;
} else {
// Direct host/IP without user part (e.g. "192.168.1.10" or "192.168.1.10:5060")
if (s.find('.') == std::string::npos && s.find(':') == std::string::npos &&
toLowerStr(s) != "localhost") {
return false;
}
userPart = "user";
hostPortPart = s;
}
outPort = (acct && acct->port > 0 && acct->domain == hostPortPart) ? acct->port : 5060;
outHost = hostPortPart;
size_t colonPos = hostPortPart.rfind(':');
if (colonPos != std::string::npos) {
outHost = hostPortPart.substr(0, colonPos);
int p = std::atoi(hostPortPart.substr(colonPos + 1).c_str());
if (p > 0 && p <= 65535) {
outPort = p;
}
}
if (outHost.empty()) return false;
if (userPart.empty()) userPart = "user";
if (acct && !acct->domain.empty() && acct->enabled &&
toLowerStr(outHost) == toLowerStr(acct->domain)) {
outTargetUri = "sip:" + userPart + "@" + outHost;
outPort = acct->port > 0 ? acct->port : outPort;
} else {
outTargetUri = "sip:" + userPart + "@" + hostPortPart;
}
return true;
}
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, std::string& outPeerZrtpHash) {
outPeerZrtpHash.clear();
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;
}
}
} else if (line.rfind("a=zrtp-hash:", 0) == 0) {
std::istringstream zss(line.substr(12));
std::string ver, hashHex;
zss >> ver >> hashHex;
if (!hashHex.empty()) {
outPeerZrtpHash = hashHex;
}
}
}
}
// ---------------------------------------------------------------------------
// RTP + RFC 6189 ZRTP + RFC 3711 SRTP Session Engine
// ---------------------------------------------------------------------------
class RtpAudioSession {
public:
~RtpAudioSession() { stop(); }
std::string prepareZrtp(bool enableZrtp) {
std::lock_guard<std::mutex> lk(zrtpMtx_);
zrtpEnabled_ = enableZrtp;
srtpActive_.store(false);
zrtpSecure_.store(false);
zrtpNotified_.store(false);
zrtpSas_.clear();
zrtpState_ = ZrtpState::Discovery;
if (!enableZrtp) {
return "";
}
initZrtpMaterialLocked();
uint8_t h[32];
sha256Bytes(localHelloMsg_.data(), localHelloMsg_.size(), h);
return bytesToHexLower(h, 32);
}
bool start(int localPort, const std::string& remoteIp, int remotePort,
int payloadType, bool enableZrtp) {
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;
}
}
{
std::lock_guard<std::mutex> lk(zrtpMtx_);
zrtpEnabled_ = enableZrtp;
if (enableZrtp && localHelloMsg_.empty()) {
initZrtpMaterialLocked();
}
}
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;
}
std::lock_guard<std::mutex> lk(zrtpMtx_);
localHelloMsg_.clear();
srtpActive_.store(false);
zrtpSecure_.store(false);
}
void queueDtmf(char digit) {
std::lock_guard<std::mutex> lk(dtmfMtx_);
dtmfQueue_.push_back(digit);
}
bool isZrtpSecure() const { return zrtpSecure_.load(); }
bool consumeZrtpNotification(std::string& outSas) {
if (!zrtpSecure_.load() || zrtpNotified_.load()) return false;
std::lock_guard<std::mutex> lk(zrtpMtx_);
if (zrtpSas_.empty()) return false;
outSas = zrtpSas_;
zrtpNotified_.store(true);
return true;
}
std::string getZrtpSas() const {
std::lock_guard<std::mutex> lk(zrtpMtx_);
return zrtpSas_;
}
private:
enum class ZrtpState {
Discovery = 0,
CommitSent,
WaitDHPart2,
WaitConfirm1,
WaitConfirm2,
Secure
};
void initZrtpMaterialLocked() {
loadOrCreateLocalZid(localZid_);
if (RAND_bytes(h0_, 32) != 1) {
for (int i = 0; i < 32; ++i) {
h0_[i] = static_cast<uint8_t>((nowMs() >> (i & 7)) ^ (i * 73 + ::getpid()));
}
}
sha256Bytes(h0_, 32, h1_);
sha256Bytes(h1_, 32, h2_);
sha256Bytes(h2_, 32, h3_);
useDh2k_ = false;
useHs32_ = false;
generateDhKeypairLocked(false);
// Build RFC 6189 Section 5.2 Hello message (88 bytes = 22 words + 8 byte MAC = 24 words?
// Wait: RFC 6189 Section 5.2: Hello with 0 optional counts is 22 32-bit words = 88 bytes
// INCLUDING the 8-byte MAC:
// 0..3: 0x50 0x5a, len=22 (0x0016)
// 4..11: "Hello "
// 12..15: "1.10"
// 16..31: Client ID (16 bytes)
// 32..63: H3 (32 bytes)
// 64..75: ZID (12 bytes)
// 76..79: flags & counts (4 bytes: 0,0,0,0)
// 80..87: MAC (8 bytes, HMAC-SHA256(H2, bytes 0..79)[0..7])
localHelloMsg_.assign(88, 0);
localHelloMsg_[0] = 0x50;
localHelloMsg_[1] = 0x5a;
localHelloMsg_[2] = 0x00;
localHelloMsg_[3] = 22;
std::memcpy(localHelloMsg_.data() + 4, "Hello ", 8);
std::memcpy(localHelloMsg_.data() + 12, "1.10", 4);
std::memcpy(localHelloMsg_.data() + 16, "BananarchyXSip ", 16);
std::memcpy(localHelloMsg_.data() + 32, h3_, 32);
std::memcpy(localHelloMsg_.data() + 64, localZid_, 12);
localHelloMsg_[76] = 0x00;
localHelloMsg_[77] = 0x00;
localHelloMsg_[78] = 0x00;
localHelloMsg_[79] = 0x00;
uint8_t mac[32];
hmacSha256(h2_, 32, localHelloMsg_.data(), 80, mac);
std::memcpy(localHelloMsg_.data() + 80, mac, 8);
peerHelloReceived_ = false;
peerHelloAcked_ = false;
helloSendCount_ = 0;
zrtpSeq_ = static_cast<uint16_t>((nowMs() ^ ::getpid()) & 0x7fff);
}
void generateDhKeypairLocked(bool dh2k) {
size_t pubBytes = dh2k ? 256 : 384;
const char* primeHex = dh2k ? kDh2kPrimeHex : kDh3kPrimeHex;
BIGNUM* p = nullptr;
BIGNUM* g = BN_new();
BIGNUM* x = BN_new();
BIGNUM* pv = BN_new();
BN_CTX* ctx = BN_CTX_new();
BN_hex2bn(&p, primeHex);
BN_set_word(g, 2);
BN_rand(x, 256, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
BN_mod_exp(pv, g, x, p, ctx);
dhPrivBytes_.assign(32, 0);
BN_bn2binpad(x, dhPrivBytes_.data(), 32);
localDhPub_.assign(pubBytes, 0);
BN_bn2binpad(pv, localDhPub_.data(), static_cast<int>(pubBytes));
BN_free(p);
BN_free(g);
BN_free(x);
BN_free(pv);
BN_CTX_free(ctx);
buildLocalDhPartMsgLocked("DHPart1 ", localDhPart1Msg_);
buildLocalDhPartMsgLocked("DHPart2 ", localDhPart2Msg_);
}
void buildLocalDhPartMsgLocked(const char* type8, std::vector<uint8_t>& outMsg) {
// RFC 6189 Section 5.5/5.6:
// 0..3: 0x50 0x5a, length in words (21 + pubBytes/4: 117 for DH3k, 85 for DH2k)
// 4..11: "DHPart1 " or "DHPart2 "
// 12..43: H1 (32 bytes)
// 44..51: rs1ID (8 bytes)
// 52..59: rs2ID (8 bytes)
// 60..67: auxsecretID (8 bytes)
// 68..75: pbxsecretID (8 bytes)
// 76..76+pubBytes-1: pv
// last 8 bytes: MAC = HMAC-SHA256(H0, msg[0..end-8])[0..7]
size_t pubBytes = localDhPub_.size();
uint16_t words = static_cast<uint16_t>(21 + pubBytes / 4);
size_t totalBytes = words * 4;
outMsg.assign(totalBytes, 0);
outMsg[0] = 0x50;
outMsg[1] = 0x5a;
outMsg[2] = static_cast<uint8_t>((words >> 8) & 0xff);
outMsg[3] = static_cast<uint8_t>(words & 0xff);
std::memcpy(outMsg.data() + 4, type8, 8);
std::memcpy(outMsg.data() + 12, h1_, 32);
// Secret IDs derived from random dummy retained secrets when no cache exists
uint8_t dummyId[32];
hmacSha256(h0_, 32, reinterpret_cast<const uint8_t*>(type8), 8, dummyId);
std::memcpy(outMsg.data() + 44, dummyId, 32);
std::memcpy(outMsg.data() + 76, localDhPub_.data(), pubBytes);
uint8_t mac[32];
hmacSha256(h0_, 32, outMsg.data(), totalBytes - 8, mac);
std::memcpy(outMsg.data() + totalBytes - 8, mac, 8);
}
void buildLocalCommitMsgLocked() {
// RFC 6189 Section 5.4 Commit Message (29 words = 116 bytes):
// 0..3: 0x50 0x5a, len=29
// 4..11: "Commit "
// 12..43: H2 (32 bytes)
// 44..55: ZID (12 bytes)
// 56..59: hash alg "S256"
// 60..63: cipher alg "AES1"
// 64..67: auth tag alg ("HS80" or "HS32")
// 68..71: key agreement ("DH3k" or "DH2k")
// 72..75: SAS type "B32 "
// 76..107: hvi = SHA256(localDhPart2Msg_ || peerHelloMsg_)
// 108..115: MAC = HMAC-SHA256(H1, Commit[0..107])[0..7]
std::vector<uint8_t> hviInput;
hviInput.reserve(localDhPart2Msg_.size() + peerHelloMsg_.size());
hviInput.insert(hviInput.end(), localDhPart2Msg_.begin(), localDhPart2Msg_.end());
hviInput.insert(hviInput.end(), peerHelloMsg_.begin(), peerHelloMsg_.end());
sha256Bytes(hviInput.data(), hviInput.size(), localHvi_);
localCommitMsg_.assign(116, 0);
localCommitMsg_[0] = 0x50;
localCommitMsg_[1] = 0x5a;
localCommitMsg_[2] = 0x00;
localCommitMsg_[3] = 29;
std::memcpy(localCommitMsg_.data() + 4, "Commit ", 8);
std::memcpy(localCommitMsg_.data() + 12, h2_, 32);
std::memcpy(localCommitMsg_.data() + 44, localZid_, 12);
std::memcpy(localCommitMsg_.data() + 56, "S256", 4);
std::memcpy(localCommitMsg_.data() + 60, "AES1", 4);
std::memcpy(localCommitMsg_.data() + 64, useHs32_ ? "HS32" : "HS80", 4);
std::memcpy(localCommitMsg_.data() + 68, useDh2k_ ? "DH2k" : "DH3k", 4);
std::memcpy(localCommitMsg_.data() + 72, "B32 ", 4);
std::memcpy(localCommitMsg_.data() + 76, localHvi_, 32);
uint8_t mac[32];
hmacSha256(h1_, 32, localCommitMsg_.data(), 108, mac);
std::memcpy(localCommitMsg_.data() + 108, mac, 8);
}
bool deriveSharedKeysLocked(const uint8_t* peerPv, size_t peerPvLen,
bool weAreInitiator) {
const char* primeHex = (peerPvLen == 256) ? kDh2kPrimeHex : kDh3kPrimeHex;
BIGNUM* p = nullptr;
BIGNUM* remPv = BN_bin2bn(peerPv, static_cast<int>(peerPvLen), nullptr);
BIGNUM* x = BN_bin2bn(dhPrivBytes_.data(),
static_cast<int>(dhPrivBytes_.size()), nullptr);
BIGNUM* shared = BN_new();
BN_CTX* ctx = BN_CTX_new();
BN_hex2bn(&p, primeHex);
// Validate 1 < remPv < p - 1 (RFC 6189 Section 5.5/5.6)
BIGNUM* one = BN_new();
BIGNUM* pMinusOne = BN_dup(p);
BN_set_word(one, 1);
BN_sub_word(pMinusOne, 1);
bool validPv = (BN_cmp(remPv, one) > 0 && BN_cmp(remPv, pMinusOne) < 0);
if (!validPv) {
BN_free(one);
BN_free(pMinusOne);
BN_free(p);
BN_free(remPv);
BN_free(x);
BN_free(shared);
BN_CTX_free(ctx);
return false;
}
BN_mod_exp(shared, remPv, x, p, ctx);
std::vector<uint8_t> dhResult(peerPvLen, 0);
BN_bn2binpad(shared, dhResult.data(), static_cast<int>(peerPvLen));
BN_free(one);
BN_free(pMinusOne);
BN_free(p);
BN_free(remPv);
BN_free(x);
BN_free(shared);
BN_CTX_free(ctx);
// total_hash = SHA256(Hello_responder || Commit || DHPart1 || DHPart2)
const std::vector<uint8_t>& helloR = weAreInitiator ? peerHelloMsg_ : localHelloMsg_;
const std::vector<uint8_t>& commitMsg = weAreInitiator ? localCommitMsg_ : peerCommitMsg_;
const std::vector<uint8_t>& dhPart1 = weAreInitiator ? peerDhPart1Msg_ : localDhPart1Msg_;
const std::vector<uint8_t>& dhPart2 = weAreInitiator ? localDhPart2Msg_ : peerDhPart2Msg_;
std::vector<uint8_t> thBuf;
thBuf.reserve(helloR.size() + commitMsg.size() + dhPart1.size() + dhPart2.size());
thBuf.insert(thBuf.end(), helloR.begin(), helloR.end());
thBuf.insert(thBuf.end(), commitMsg.begin(), commitMsg.end());
thBuf.insert(thBuf.end(), dhPart1.begin(), dhPart1.end());
thBuf.insert(thBuf.end(), dhPart2.begin(), dhPart2.end());
uint8_t totalHash[32];
sha256Bytes(thBuf.data(), thBuf.size(), totalHash);
const uint8_t* zidI = weAreInitiator ? localZid_ : peerZid_;
const uint8_t* zidR = weAreInitiator ? peerZid_ : localZid_;
std::vector<uint8_t> kdfContext;
kdfContext.reserve(12 + 12 + 32);
kdfContext.insert(kdfContext.end(), zidI, zidI + 12);
kdfContext.insert(kdfContext.end(), zidR, zidR + 12);
kdfContext.insert(kdfContext.end(), totalHash, totalHash + 32);
// RFC 6189 Section 4.4.1.4 s0 calculation (with 0 retained secrets)
std::vector<uint8_t> s0Input;
const char* kZrtpKdfStr = "ZRTP-HMAC-KDF";
s0Input.push_back(0x00);
s0Input.push_back(0x00);
s0Input.push_back(0x00);
s0Input.push_back(0x01);
s0Input.insert(s0Input.end(), dhResult.begin(), dhResult.end());
s0Input.insert(s0Input.end(), kZrtpKdfStr, kZrtpKdfStr + 13);
s0Input.insert(s0Input.end(), kdfContext.begin(), kdfContext.end());
// len(s1)=0, len(s2)=0, len(s3)=0 (three 32-bit zero lengths, RFC 6189 Section 4.4.1.4)
for (int i = 0; i < 12; ++i) s0Input.push_back(0x00);
uint8_t s0[32];
sha256Bytes(s0Input.data(), s0Input.size(), s0);
// SAS derivation ("B32 ": 4 base32 chars from top 20 bits of 32-bit sasvalue, RFC 6189 Section 4.5.2)
std::vector<uint8_t> sasBytes = zrtpKdf(s0, "SAS", kdfContext, 32);
static const char kZrtpBase32[] = "ybndrfg8ejkmcpqxot1uwisza345h769";
uint32_t sas20 = ((static_cast<uint32_t>(sasBytes[0]) << 16) |
(static_cast<uint32_t>(sasBytes[1]) << 8) |
static_cast<uint32_t>(sasBytes[2])) >> 4;
zrtpSas_.resize(4);
zrtpSas_[0] = kZrtpBase32[(sas20 >> 15) & 0x1f];
zrtpSas_[1] = kZrtpBase32[(sas20 >> 10) & 0x1f];
zrtpSas_[2] = kZrtpBase32[(sas20 >> 5) & 0x1f];
zrtpSas_[3] = kZrtpBase32[sas20 & 0x1f];
// SRTP and ZRTP Confirm keys
std::vector<uint8_t> srtpKeyI = zrtpKdf(s0, "Initiator SRTP master key", kdfContext, 128);
std::vector<uint8_t> srtpSaltI = zrtpKdf(s0, "Initiator SRTP master salt", kdfContext, 112);
std::vector<uint8_t> srtpKeyR = zrtpKdf(s0, "Responder SRTP master key", kdfContext, 128);
std::vector<uint8_t> srtpSaltR = zrtpKdf(s0, "Responder SRTP master salt", kdfContext, 112);
std::vector<uint8_t> hmacKeyI = zrtpKdf(s0, "Initiator HMAC key", kdfContext, 256);
std::vector<uint8_t> hmacKeyR = zrtpKdf(s0, "Responder HMAC key", kdfContext, 256);
std::vector<uint8_t> zrtpKeyI = zrtpKdf(s0, "Initiator ZRTP key", kdfContext, 128);
std::vector<uint8_t> zrtpKeyR = zrtpKdf(s0, "Responder ZRTP key", kdfContext, 128);
std::memcpy(hmacKeyI_, hmacKeyI.data(), 32);
std::memcpy(hmacKeyR_, hmacKeyR.data(), 32);
std::memcpy(zrtpKeyI_, zrtpKeyI.data(), 16);
std::memcpy(zrtpKeyR_, zrtpKeyR.data(), 16);
int tagBytes = useHs32_ ? 4 : 10;
if (weAreInitiator) {
txSrtp_.deriveFromMaster(srtpKeyI.data(), srtpSaltI.data(), tagBytes);
rxSrtp_.deriveFromMaster(srtpKeyR.data(), srtpSaltR.data(), tagBytes);
} else {
txSrtp_.deriveFromMaster(srtpKeyR.data(), srtpSaltR.data(), tagBytes);
rxSrtp_.deriveFromMaster(srtpKeyI.data(), srtpSaltI.data(), tagBytes);
}
return true;
}
void buildConfirmMsgLocked(bool isConfirm2, std::vector<uint8_t>& outMsg) {
// RFC 6189 Section 5.7 Confirm1 / Confirm2 (19 words = 76 bytes):
// 0..3: 0x50 0x5a, len=19
// 4..11: "Confirm1" or "Confirm2"
// 12..19: confirm_mac (8 bytes)
// 20..35: CFB IV (16 bytes)
// 36..75: encrypted 40 bytes (H0[32] + zeros[4] + cache_exp[4])
outMsg.assign(76, 0);
outMsg[0] = 0x50;
outMsg[1] = 0x5a;
outMsg[2] = 0x00;
outMsg[3] = 19;
std::memcpy(outMsg.data() + 4, isConfirm2 ? "Confirm2" : "Confirm1", 8);
if (RAND_bytes(outMsg.data() + 20, 16) != 1) {
for (int i = 0; i < 16; ++i) outMsg[20 + i] = static_cast<uint8_t>(i * 19 + nowMs());
}
std::memcpy(outMsg.data() + 36, h0_, 32);
outMsg[68] = 0x00;
outMsg[69] = 0x00;
outMsg[70] = 0x00;
outMsg[71] = 0x00;
outMsg[72] = 0xff;
outMsg[73] = 0xff;
outMsg[74] = 0xff;
outMsg[75] = 0xff;
const uint8_t* encKey = isConfirm2 ? zrtpKeyI_ : zrtpKeyR_;
const uint8_t* macKey = isConfirm2 ? hmacKeyI_ : hmacKeyR_;
aes128CfbCrypt(encKey, outMsg.data() + 20, outMsg.data() + 36, 40, true);
uint8_t mac[32];
hmacSha256(macKey, 32, outMsg.data() + 36, 40, mac);
std::memcpy(outMsg.data() + 12, mac, 8);
}
bool verifyAndDecryptConfirmLocked(const uint8_t* msg, size_t len, bool isConfirm2) {
if (len < 76) return false;
const uint8_t* encKey = isConfirm2 ? zrtpKeyI_ : zrtpKeyR_;
const uint8_t* macKey = isConfirm2 ? hmacKeyI_ : hmacKeyR_;
uint8_t mac[32];
hmacSha256(macKey, 32, msg + 36, len - 36, mac);
if (std::memcmp(mac, msg + 12, 8) != 0) {
return false;
}
std::vector<uint8_t> dec(msg + 36, msg + len);
aes128CfbCrypt(encKey, msg + 20, dec.data(), dec.size(), false);
uint8_t checkH1[32];
sha256Bytes(dec.data(), 32, checkH1);
return std::memcmp(checkH1, peerH1_, 32) == 0;
}
void sendZrtpMessageLocked(uint32_t ssrc, const uint8_t* zrtpMsg, size_t msgLen) {
if (sock_ < 0 || !zrtpMsg || msgLen == 0) return;
std::vector<uint8_t> pkt(12 + msgLen + 4, 0);
pkt[0] = 0x10;
pkt[1] = 0x00;
uint16_t netSeq = htons(zrtpSeq_++);
std::memcpy(pkt.data() + 2, &netSeq, 2);
pkt[4] = 'Z';
pkt[5] = 'R';
pkt[6] = 'T';
pkt[7] = 'P';
uint32_t netSsrc = htonl(ssrc);
std::memcpy(pkt.data() + 8, &netSsrc, 4);
std::memcpy(pkt.data() + 12, zrtpMsg, msgLen);
uint32_t crc = htonl(zrtpCrc32c(pkt.data(), 12 + msgLen));
std::memcpy(pkt.data() + 12 + msgLen, &crc, 4);
::sendto(sock_, pkt.data(), pkt.size(), 0,
reinterpret_cast<const struct sockaddr*>(&remAddr_),
sizeof(remAddr_));
}
void sendSimpleZrtpAckLocked(uint32_t ssrc, const char* type8) {
uint8_t msg[12] = { 0x50, 0x5a, 0x00, 0x03 };
std::memcpy(msg + 4, type8, 8);
sendZrtpMessageLocked(ssrc, msg, sizeof(msg));
}
void handleZrtpPacket(uint32_t localSsrc, const uint8_t* pkt, size_t pktLen) {
if (pktLen < 24) return;
uint32_t rxCrc = 0;
std::memcpy(&rxCrc, pkt + pktLen - 4, 4);
rxCrc = ntohl(rxCrc);
if (zrtpCrc32c(pkt, pktLen - 4) != rxCrc) {
return;
}
const uint8_t* msg = pkt + 12;
size_t msgLen = pktLen - 16;
if (msg[0] != 0x50 || msg[1] != 0x5a || msgLen < 12) return;
std::string mtype(reinterpret_cast<const char*>(msg + 4), 8);
std::lock_guard<std::mutex> lk(zrtpMtx_);
if (!zrtpEnabled_) return;
if (mtype == "Hello " && msgLen >= 88) {
if (!peerHelloReceived_) {
peerHelloMsg_.assign(msg, msg + msgLen);
std::memcpy(peerH3_, msg + 32, 32);
std::memcpy(peerZid_, msg + 64, 12);
// Check if peer advertises DH2k only or HS32 only
std::string helloStr(reinterpret_cast<const char*>(msg), msgLen);
if (helloStr.find("DH3k") == std::string::npos &&
helloStr.find("DH2k") != std::string::npos) {
useDh2k_ = true;
generateDhKeypairLocked(true);
}
if (helloStr.find("HS80") == std::string::npos &&
helloStr.find("HS32") != std::string::npos) {
useHs32_ = true;
}
peerHelloReceived_ = true;
}
sendSimpleZrtpAckLocked(localSsrc, "HelloACK");
if (zrtpState_ == ZrtpState::Discovery && peerHelloAcked_) {
buildLocalCommitMsgLocked();
sendZrtpMessageLocked(localSsrc, localCommitMsg_.data(), localCommitMsg_.size());
zrtpState_ = ZrtpState::CommitSent;
lastZrtpTxMs_ = nowMs();
}
} else if (mtype == "HelloACK") {
peerHelloAcked_ = true;
if (zrtpState_ == ZrtpState::Discovery && peerHelloReceived_) {
buildLocalCommitMsgLocked();
sendZrtpMessageLocked(localSsrc, localCommitMsg_.data(), localCommitMsg_.size());
zrtpState_ = ZrtpState::CommitSent;
lastZrtpTxMs_ = nowMs();
}
} else if (mtype == "Commit " && msgLen >= 116) {
if (!peerHelloReceived_) return;
// Verify SHA256(Commit.H2) == peerH3_ and Hello MAC
const uint8_t* remH2 = msg + 12;
uint8_t checkH3[32];
sha256Bytes(remH2, 32, checkH3);
if (std::memcmp(checkH3, peerH3_, 32) != 0) return;
bool becomeResponder = true;
if (zrtpState_ == ZrtpState::CommitSent) {
// Tie-breaker per RFC 6189 Section 4.2: higher hvi is Initiator
if (std::memcmp(localHvi_, msg + 76, 32) > 0) {
becomeResponder = false;
}
}
if (becomeResponder) {
std::memcpy(peerH2_, remH2, 32);
std::memcpy(peerHvi_, msg + 76, 32);
peerCommitMsg_.assign(msg, msg + msgLen);
if (std::memcmp(msg + 64, "HS32", 4) == 0) useHs32_ = true;
if (std::memcmp(msg + 68, "DH2k", 4) == 0 && !useDh2k_) {
useDh2k_ = true;
generateDhKeypairLocked(true);
}
sendZrtpMessageLocked(localSsrc, localDhPart1Msg_.data(), localDhPart1Msg_.size());
zrtpState_ = ZrtpState::WaitDHPart2;
lastZrtpTxMs_ = nowMs();
}
} else if (mtype == "DHPart1 " && msgLen >= 84) {
if (zrtpState_ != ZrtpState::CommitSent && zrtpState_ != ZrtpState::WaitConfirm1) return;
const uint8_t* remH1 = msg + 12;
uint8_t checkH2[32];
sha256Bytes(remH1, 32, checkH2);
// Verify against peerH3_ (since Initiator didn't receive peer Commit, SHA256(SHA256(remH1)) == peerH3_)
uint8_t checkH3[32];
sha256Bytes(checkH2, 32, checkH3);
if (std::memcmp(checkH3, peerH3_, 32) != 0) return;
std::memcpy(peerH1_, remH1, 32);
peerDhPart1Msg_.assign(msg, msg + msgLen);
size_t pvLen = msgLen - 84;
if (pvLen != 384 && pvLen != 256) return;
if (deriveSharedKeysLocked(msg + 76, pvLen, true)) {
sendZrtpMessageLocked(localSsrc, localDhPart2Msg_.data(), localDhPart2Msg_.size());
zrtpState_ = ZrtpState::WaitConfirm1;
lastZrtpTxMs_ = nowMs();
}
} else if (mtype == "DHPart2 " && msgLen >= 84) {
if (zrtpState_ != ZrtpState::WaitDHPart2 && zrtpState_ != ZrtpState::WaitConfirm2) return;
const uint8_t* remH1 = msg + 12;
uint8_t checkH2[32];
sha256Bytes(remH1, 32, checkH2);
if (std::memcmp(checkH2, peerH2_, 32) != 0) return;
// Verify hvi == SHA256(peerDHPart2 || localHello)
std::vector<uint8_t> hviCheck(msg, msg + msgLen);
hviCheck.insert(hviCheck.end(), localHelloMsg_.begin(), localHelloMsg_.end());
uint8_t calcHvi[32];
sha256Bytes(hviCheck.data(), hviCheck.size(), calcHvi);
if (std::memcmp(calcHvi, peerHvi_, 32) != 0) return;
std::memcpy(peerH1_, remH1, 32);
peerDhPart2Msg_.assign(msg, msg + msgLen);
size_t pvLen = msgLen - 84;
if (pvLen != 384 && pvLen != 256) return;
if (deriveSharedKeysLocked(msg + 76, pvLen, false)) {
buildConfirmMsgLocked(false, localConfirm1Msg_);
sendZrtpMessageLocked(localSsrc, localConfirm1Msg_.data(), localConfirm1Msg_.size());
zrtpState_ = ZrtpState::WaitConfirm2;
lastZrtpTxMs_ = nowMs();
}
} else if (mtype == "Confirm1" && msgLen >= 76) {
if (zrtpState_ == ZrtpState::WaitConfirm1 || zrtpState_ == ZrtpState::Secure) {
if (verifyAndDecryptConfirmLocked(msg, msgLen, false)) {
buildConfirmMsgLocked(true, localConfirm2Msg_);
sendZrtpMessageLocked(localSsrc, localConfirm2Msg_.data(), localConfirm2Msg_.size());
srtpActive_.store(true);
zrtpSecure_.store(true);
zrtpState_ = ZrtpState::Secure;
}
}
} else if (mtype == "Confirm2" && msgLen >= 76) {
if (zrtpState_ == ZrtpState::WaitConfirm2 || zrtpState_ == ZrtpState::Secure) {
if (verifyAndDecryptConfirmLocked(msg, msgLen, true)) {
sendSimpleZrtpAckLocked(localSsrc, "Conf2ACK");
srtpActive_.store(true);
zrtpSecure_.store(true);
zrtpState_ = ZrtpState::Secure;
}
}
} else if (mtype == "Conf2ACK") {
if (zrtpState_ == ZrtpState::WaitConfirm2 || zrtpState_ == ZrtpState::Secure) {
srtpActive_.store(true);
zrtpSecure_.store(true);
zrtpState_ = ZrtpState::Secure;
}
}
}
void periodicZrtpTick(uint32_t localSsrc, int64_t now) {
std::lock_guard<std::mutex> lk(zrtpMtx_);
if (!zrtpEnabled_ || zrtpState_ == ZrtpState::Secure) return;
if (now - lastZrtpTxMs_ < 180) return;
lastZrtpTxMs_ = now;
if (zrtpState_ == ZrtpState::Discovery) {
if (helloSendCount_ < 25 && !localHelloMsg_.empty()) {
++helloSendCount_;
sendZrtpMessageLocked(localSsrc, localHelloMsg_.data(), localHelloMsg_.size());
}
} else if (zrtpState_ == ZrtpState::CommitSent && !localCommitMsg_.empty()) {
sendZrtpMessageLocked(localSsrc, localCommitMsg_.data(), localCommitMsg_.size());
} else if (zrtpState_ == ZrtpState::WaitDHPart2 && !localDhPart1Msg_.empty()) {
sendZrtpMessageLocked(localSsrc, localDhPart1Msg_.data(), localDhPart1Msg_.size());
} else if (zrtpState_ == ZrtpState::WaitConfirm1 && !localDhPart2Msg_.empty()) {
sendZrtpMessageLocked(localSsrc, localDhPart2Msg_.data(), localDhPart2Msg_.size());
} else if (zrtpState_ == ZrtpState::WaitConfirm2 && !localConfirm1Msg_.empty()) {
sendZrtpMessageLocked(localSsrc, localConfirm1Msg_.data(), localConfirm1Msg_.size());
}
}
size_t protectRtpPacket(uint8_t* pkt, size_t clearLen, uint16_t seq, uint32_t ssrc) {
if (!srtpActive_.load() || clearLen < 12) return clearLen;
std::lock_guard<std::mutex> lk(zrtpMtx_);
if (txSrtp_.seqInitialized && seq < txSrtp_.lastSeq &&
(txSrtp_.lastSeq - seq) > 0x8000) {
++txSrtp_.roc;
}
txSrtp_.lastSeq = seq;
txSrtp_.seqInitialized = true;
uint64_t pktIdx = (static_cast<uint64_t>(txSrtp_.roc) << 16) | seq;
uint8_t iv[16];
txSrtp_.computePacketIv(ssrc, pktIdx, iv);
aes128CtrCrypt(txSrtp_.cipherKey, iv, pkt + 12, clearLen - 12);
// Compute HMAC-SHA1 over (RTP header + encrypted payload + ROC_be32)
uint32_t netRoc = htonl(txSrtp_.roc);
std::memcpy(pkt + clearLen, &netRoc, 4);
uint8_t tag[20];
hmacSha1(txSrtp_.authKey, 20, pkt, clearLen + 4, tag);
std::memcpy(pkt + clearLen, tag, static_cast<size_t>(txSrtp_.tagBytes));
return clearLen + static_cast<size_t>(txSrtp_.tagBytes);
}
bool unprotectRtpPacket(uint8_t* pkt, size_t& ioLen, size_t hdrLen) {
if (!srtpActive_.load()) return true;
std::lock_guard<std::mutex> lk(zrtpMtx_);
size_t tagBytes = static_cast<size_t>(rxSrtp_.tagBytes);
if (ioLen <= hdrLen + tagBytes) return false;
size_t encRtpLen = ioLen - tagBytes;
uint16_t seq = (static_cast<uint16_t>(pkt[2]) << 8) | pkt[3];
uint32_t ssrc = (static_cast<uint32_t>(pkt[8]) << 24) |
(static_cast<uint32_t>(pkt[9]) << 16) |
(static_cast<uint32_t>(pkt[10]) << 8) |
static_cast<uint32_t>(pkt[11]);
uint32_t estRoc = rxSrtp_.roc;
if (!rxSrtp_.seqInitialized) {
rxSrtp_.lastSeq = seq;
rxSrtp_.seqInitialized = true;
} else if (seq < rxSrtp_.lastSeq && (rxSrtp_.lastSeq - seq) > 0x8000) {
estRoc = rxSrtp_.roc + 1;
} else if (seq > rxSrtp_.lastSeq && (seq - rxSrtp_.lastSeq) > 0x8000 &&
rxSrtp_.roc > 0) {
estRoc = rxSrtp_.roc - 1;
}
std::vector<uint8_t> authBuf(pkt, pkt + encRtpLen);
uint32_t netRoc = htonl(estRoc);
authBuf.insert(authBuf.end(), reinterpret_cast<const uint8_t*>(&netRoc),
reinterpret_cast<const uint8_t*>(&netRoc) + 4);
uint8_t calcTag[20];
hmacSha1(rxSrtp_.authKey, 20, authBuf.data(), authBuf.size(), calcTag);
if (std::memcmp(calcTag, pkt + encRtpLen, tagBytes) != 0) {
return false;
}
if (estRoc > rxSrtp_.roc ||
(estRoc == rxSrtp_.roc && seq > rxSrtp_.lastSeq)) {
rxSrtp_.roc = estRoc;
rxSrtp_.lastSeq = seq;
}
uint64_t pktIdx = (static_cast<uint64_t>(estRoc) << 16) | seq;
uint8_t iv[16];
rxSrtp_.computePacketIv(ssrc, pktIdx, iv);
aes128CtrCrypt(rxSrtp_.cipherKey, iv, pkt + hdrLen, encRtpLen - hdrLen);
ioLen = encRtpLen;
return true;
}
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 / SRTP / ZRTP packets
uint8_t rxPkt[1500];
while (true) {
ssize_t n = ::recv(sock_, rxPkt, sizeof(rxPkt), 0);
if (n <= 12) break;
size_t pktLen = static_cast<size_t>(n);
// Demultiplex RFC 6189 ZRTP packet (0x10 0x00 ... "ZRTP")
if (pktLen >= 16 && (rxPkt[0] & 0xf0) == 0x10 &&
rxPkt[4] == 'Z' && rxPkt[5] == 'R' &&
rxPkt[6] == 'T' && rxPkt[7] == 'P') {
handleZrtpPacket(ssrc, rxPkt, pktLen);
continue;
}
if ((rxPkt[0] & 0xc0) != 0x80) continue;
uint8_t pt = rxPkt[1] & 0x7f;
size_t hdrLen = 12 + (rxPkt[0] & 0x0f) * 4;
if (pktLen <= hdrLen) continue;
if (!unprotectRtpPacket(rxPkt, pktLen, hdrLen)) {
continue;
}
const uint8_t* payload = rxPkt + hdrLen;
size_t payLen = pktLen - 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 + ZRTP tick
int64_t now = nowMs();
periodicZrtpTick(ssrc, now);
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 + 16];
uint16_t curSeq = seq++;
pkt[0] = 0x80;
pkt[1] = static_cast<uint8_t>((p == 0 ? 0x80 : 0x00) | 101);
uint16_t netSeq = htons(curSeq);
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);
size_t sendLen = protectRtpPacket(pkt, 16, curSeq, ssrc);
::sendto(sock_, pkt, sendLen, 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 + 16];
uint16_t curSeq = seq++;
pkt[0] = 0x80;
pkt[1] = static_cast<uint8_t>(payloadType_ & 0x7f);
uint16_t netSeq = htons(curSeq);
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]);
}
size_t sendLen = protectRtpPacket(pkt, 12 + 160, curSeq, ssrc);
::sendto(sock_, pkt, sendLen, 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_;
// ZRTP & SRTP state
mutable std::mutex zrtpMtx_;
bool zrtpEnabled_ = true;
std::atomic<bool> srtpActive_{false};
std::atomic<bool> zrtpSecure_{false};
std::atomic<bool> zrtpNotified_{false};
ZrtpState zrtpState_ = ZrtpState::Discovery;
uint16_t zrtpSeq_ = 1;
int helloSendCount_ = 0;
int64_t lastZrtpTxMs_ = 0;
bool peerHelloReceived_ = false;
bool peerHelloAcked_ = false;
bool useDh2k_ = false;
bool useHs32_ = false;
uint8_t localZid_[12] {};
uint8_t peerZid_[12] {};
uint8_t h0_[32] {};
uint8_t h1_[32] {};
uint8_t h2_[32] {};
uint8_t h3_[32] {};
uint8_t peerH1_[32] {};
uint8_t peerH2_[32] {};
uint8_t peerH3_[32] {};
uint8_t localHvi_[32] {};
uint8_t peerHvi_[32] {};
std::vector<uint8_t> dhPrivBytes_;
std::vector<uint8_t> localDhPub_;
std::vector<uint8_t> localHelloMsg_;
std::vector<uint8_t> localCommitMsg_;
std::vector<uint8_t> localDhPart1Msg_;
std::vector<uint8_t> localDhPart2Msg_;
std::vector<uint8_t> localConfirm1Msg_;
std::vector<uint8_t> localConfirm2Msg_;
std::vector<uint8_t> peerHelloMsg_;
std::vector<uint8_t> peerCommitMsg_;
std::vector<uint8_t> peerDhPart1Msg_;
std::vector<uint8_t> peerDhPart2Msg_;
uint8_t hmacKeyI_[32] {};
uint8_t hmacKeyR_[32] {};
uint8_t zrtpKeyI_[16] {};
uint8_t zrtpKeyR_[16] {};
std::string zrtpSas_;
SrtpDirectionKeys txSrtp_;
SrtpDirectionKeys rxSrtp_;
};
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;
// activeAccountIdx: -1 = Direct (No Account), 0..N-1 = configured account
int activeAccountIdx = accounts.empty() ? -1 : 0;
bool directZrtpEnabled = true;
std::string activeSipCallId;
std::string activePeerUri;
std::string activeTargetHost;
int activeTargetPort = 5060;
std::string activeFromDisplay = "Bananarchy";
std::string activeFromUser = "user";
std::string activeFromDomain = "127.0.0.1";
bool activeCallZrtp = true;
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;
std::string remoteZrtpHash;
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.1\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,
const std::string& zrtpHashHex) -> std::string {
std::ostringstream sdp;
uint32_t sessId = static_cast<uint32_t>(::time(nullptr));
sdp << "v=0\r\n"
<< "o=" << activeFromUser << " "
<< 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";
if (!zrtpHashHex.empty()) {
sdp << "a=zrtp-hash:1.10 " << zrtpHashHex << "\r\n";
}
sdp << "a=sendrecv\r\n";
return sdp.str();
};
auto sendSipInvite = [&](int acctIdx, const std::string& targetRaw,
const DigestChallenge* auth = nullptr) -> bool {
const SipAccount* acctPtr = nullptr;
if (acctIdx >= 0 && acctIdx < static_cast<int>(accounts.size())) {
const SipAccount& cand = accounts[acctIdx];
if (!cand.domain.empty() && !cand.username.empty() && cand.enabled) {
acctPtr = &cand;
}
}
std::string targetUri;
std::string destHost;
int destPort = 5060;
if (!resolveSipTarget(targetRaw, acctPtr, targetUri, destHost, destPort)) {
neoui_show_toast("Enter user@host or add account", 2200);
return false;
}
std::string localIp = detectLocalIpForHost(destHost);
if (!auth) {
activeAccountIdx = acctPtr ? acctIdx : -1;
activePeerUri = targetUri;
activeTargetHost = destHost;
activeTargetPort = destPort;
activeFromDisplay = acctPtr ? acctPtr->label : "Bananarchy";
activeFromUser = acctPtr ? acctPtr->username : "user";
activeFromDomain = acctPtr ? acctPtr->domain
: (localIp + ":" + std::to_string(localSipPort));
activeCallZrtp = acctPtr ? acctPtr->zrtpEnabled : directZrtpEnabled;
activeSipCallId = randomHexToken(8) + "@" + localIp;
activeLocalTag = randomHexToken(6);
activeRemoteTag.clear();
std::memset(&activePeerSin, 0, sizeof(activePeerSin));
activeCseq = 1;
} else {
++activeCseq;
}
activeBranch = "z9hG4bK" + randomHexToken(6);
std::string zrtpHelloHash = rtpSession.prepareZrtp(activeCallZrtp);
std::string sdp = buildLocalSdp(localIp, zrtpHelloHash);
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: \"" << activeFromDisplay << "\" <sip:" << activeFromUser << "@"
<< activeFromDomain << ">;tag=" << activeLocalTag << "\r\n"
<< "To: <" << targetUri << ">\r\n"
<< "Call-ID: " << activeSipCallId << "\r\n"
<< "CSeq: " << activeCseq << " INVITE\r\n"
<< "Contact: <sip:" << activeFromUser << "@" << localIp << ":"
<< localSipPort << ">\r\n"
<< "Allow: INVITE, ACK, CANCEL, BYE, OPTIONS, INFO\r\n"
<< "User-Agent: Bananarchy-XSip/1.1\r\n";
if (auth && auth->valid && acctPtr) {
req << buildDigestAuthHeader(*auth, *acctPtr, "INVITE", targetUri);
}
req << "Content-Type: application/sdp\r\n"
<< "Content-Length: " << sdp.size() << "\r\n\r\n"
<< sdp;
callState = SipCallState::Outgoing;
callStartedMs = nowMs();
sendUdpPacket(activeTargetHost, activeTargetPort, req.str());
if (!auth) {
sendPluginCommand("callscreen", "OUTGOING sip:1 " + targetUri + " SIP");
}
return true;
};
auto acceptActiveSipCall = [&]() {
if (callState != SipCallState::Incoming) return;
std::string host = !activeTargetHost.empty()
? activeTargetHost
: ((activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size()))
? accounts[activeAccountIdx].domain
: "8.8.8.8");
std::string localIp = detectLocalIpForHost(host);
activeCallZrtp = (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size()))
? accounts[activeAccountIdx].zrtpEnabled
: directZrtpEnabled;
std::string zrtpHelloHash = rtpSession.prepareZrtp(activeCallZrtp);
std::string sdp = buildLocalSdp(localIp, zrtpHelloHash);
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:" << activeFromUser << "@" << 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,
activeCallZrtp);
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
: "Direct 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) {
std::string localIp = detectLocalIpForHost(activeTargetHost);
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: \"" << activeFromDisplay << "\" <sip:" << activeFromUser << "@"
<< activeFromDomain << ">;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";
if (!activeTargetHost.empty()) {
sendUdpPacket(activeTargetHost, activeTargetPort, req.str());
} else {
sendUdpPacket("", 5060, req.str(), &activePeerSin);
}
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) {
activePeerSin = fromSin;
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 && activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
// Send ACK for 401/407 then authenticated INVITE
std::string localIp = detectLocalIpForHost(activeTargetHost);
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: \"" << activeFromDisplay << "\" <sip:" << activeFromUser
<< "@" << activeFromDomain << ">;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(activeTargetHost, activeTargetPort, ack.str(), &fromSin);
sendSipInvite(activeAccountIdx, activePeerUri, &ch);
} else {
hangupActiveSipCall(true);
}
} else if (statusCode == 200 && callState == SipCallState::Outgoing) {
parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType,
remoteZrtpHash);
std::string localIp = detectLocalIpForHost(activeTargetHost);
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: \"" << activeFromDisplay << "\" <sip:" << activeFromUser
<< "@" << activeFromDomain << ">;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";
if (!activeTargetHost.empty()) {
sendUdpPacket(activeTargetHost, activeTargetPort, ack.str());
} else {
sendUdpPacket("", 5060, ack.str(), &fromSin);
}
callState = SipCallState::Active;
callStartedMs = nowMs();
rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort,
remotePayloadType, activeCallZrtp);
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;
char peerIpBuf[INET_ADDRSTRLEN] = {0};
if (::inet_ntop(AF_INET, &fromSin.sin_addr, peerIpBuf, sizeof(peerIpBuf))) {
activeTargetHost = peerIpBuf;
}
activeTargetPort = ntohs(fromSin.sin_port);
parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType,
remoteZrtpHash);
// 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
: "Direct 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 (8 fields):
// 0=Label, 1=Username, 2=Password, 3=Domain, 4=Port, 5=Transport, 6=ZRTP, 7=Enabled
constexpr int kNumEditFields = 8;
bool editModalOpen = false;
int editAcctIdx = -1;
int editFieldIdx = 0;
SipAccount editAcctDraft;
auto syncInputBufferForFocus = [&]() {
if (editModalOpen) {
if (editFieldIdx == 0) {
neoui_input_set_mode(NEO_INPUT_ABC_TITLE);
neoui_input_reset(editAcctDraft.label.c_str());
} else if (editFieldIdx == 1) {
neoui_input_set_mode(NEO_INPUT_ABC_LOWER);
neoui_input_reset(editAcctDraft.username.c_str());
} else if (editFieldIdx == 2) {
neoui_input_set_mode(NEO_INPUT_ABC_LOWER);
neoui_input_reset(editAcctDraft.password.c_str());
} else if (editFieldIdx == 3) {
neoui_input_set_mode(NEO_INPUT_ABC_LOWER);
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 {
neoui_input_commit_tap();
}
} else if (activeTab == 0) {
if (neoui_input_get_mode() == NEO_INPUT_123 && dialInput.empty()) {
neoui_input_set_mode(NEO_INPUT_ABC_LOWER);
}
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 = "DIRECT";
if (callState == SipCallState::Active && rtpSession.isZrtpSecure()) {
regBadge = "ZRTP:" + rtpSession.getZrtpSas();
} else if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
regBadge = accounts[activeAccountIdx].regStatus;
} else {
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 / Direct mode + ZRTP indicator
std::string acctLine;
if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
const auto& a = accounts[activeAccountIdx];
acctLine = "Acct: " + a.label + " [" + a.regStatus +
(a.zrtpEnabled ? " ZRTP]" : "]");
} else {
acctLine = std::string("Mode: Direct URI [") +
(directZrtpEnabled ? "ZRTP ON]" : "ZRTP OFF]");
}
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 2, 18,
acctLine.c_str(), 224);
std::string dialLbl = std::string("SIP URI / Ext ") +
neoui_input_mode_badge() + " (*/# mode):";
neoui_draw_input_box(6, kBodyY + 22, 228, 38, 1,
dialLbl.c_str(), dialInput.c_str(),
"user@host 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 [*/#] 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 + 46,
240, 24, "No SIP accounts configured");
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_GREEN, 0, kBodyY + 74,
240, 20, "Direct URI calling is active");
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 98,
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 +
(a.zrtpEnabled ? " [ZRTP]" : "");
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) {
std::string modalTitle = (editAcctIdx < 0 ? "Add SIP " : "Edit SIP ") +
std::string(neoui_input_mode_badge());
neoui_draw_modal_box(6, 36, 228, 230, kIconEdit, NEO_TEXT_YELLOW,
modalTitle.c_str());
const char* labels[kNumEditFields] = {
"Label", "User", "Pass", "Domain", "Port", "Proto", "ZRTP", "Active"
};
std::string vals[kNumEditFields] = {
editAcctDraft.label,
editAcctDraft.username,
editAcctDraft.password.empty() ? "" : "******",
editAcctDraft.domain,
std::to_string(editAcctDraft.port),
editAcctDraft.transport,
editAcctDraft.zrtpEnabled ? "ON (SRTP)" : "OFF",
editAcctDraft.enabled ? "ON" : "OFF"
};
int startIdx = std::max(0, std::min(editFieldIdx - 2, kNumEditFields - 4));
for (int i = 0; i < 4 && (startIdx + i) < kNumEditFields; ++i) {
int f = startIdx + i;
std::string valStr = vals[f];
if (f == editFieldIdx && f <= 4) {
valStr = std::string(neoui_input_get_text()) + "_";
}
std::string rowTxt = std::string(labels[f]) + ": " + valStr;
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", editFieldIdx <= 4 ? "NEXT" : "TOGGLE", "Cancel");
} else if (menuOpen) {
neoui_draw_menu_popup(
"Add SIP Account|Switch Account / Direct|Toggle Direct ZRTP|Register All Now|Delete Selected|Clear History",
nullptr, menuSel, 6);
}
neoui_end_frame();
};
auto openWindow = [&]() {
if (isDuressMode() || 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
if (!isDuressMode()) {
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") {
if (isDuressMode()) {
hangupActiveSipCall(false);
accounts.clear();
history.clear();
closeWindow();
continue;
}
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.rfind("DIAL ", 0) == 0 && cmd.size() > 5) {
dialInput = trimStr(cmd.substr(5));
activeTab = 0;
openWindow();
sendSipInvite(activeAccountIdx, dialInput);
if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
bool autoCall = false;
if (cmd.size() > 5) {
std::string arg = trimStr(cmd.substr(5));
if (arg.rfind("dial ", 0) == 0) {
dialInput = trimStr(arg.substr(5));
activeTab = 0;
} else if (arg.rfind("call ", 0) == 0) {
dialInput = trimStr(arg.substr(5));
activeTab = 0;
autoCall = true;
}
}
openWindow();
if (autoCall && !dialInput.empty()) {
sendSipInvite(activeAccountIdx, dialInput);
if (visible) render();
}
}
}
// 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;
if (isDuressMode()) continue;
rxBuf[n] = '\0';
handleIncomingSipPacket(std::string(rxBuf, static_cast<size_t>(n)), fromSin);
if (visible) render();
}
}
// 2b. Check if ZRTP completed handshake on active call
if (callState == SipCallState::Active) {
std::string sas;
if (rtpSession.consumeZrtpNotification(sas)) {
sendPluginCommand("callscreen",
"ACTIVE sip:1 " + activePeerUri + " SIP:" + sas);
sendPluginCommand("callscreen",
"NOTICE ZRTP Encrypted (SAS: " + sas + ")");
if (visible) {
neoui_show_toast(("ZRTP Secure SAS: " + sas).c_str(), 3000);
render();
}
}
}
// 3. Periodic REGISTER keepalive for enabled accounts
int64_t now = nowMs();
bool anyEnabled = false;
if (!isDuressMode()) {
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) {
neoui_input_commit_tap();
applyInputBufferToFocus();
if (editAcctIdx < 0) {
editAcctDraft.callId = randomHexToken(8) + "@" + editAcctDraft.domain;
editAcctDraft.fromTag = randomHexToken(6);
accounts.push_back(editAcctDraft);
activeAccountIdx = static_cast<int>(accounts.size()) - 1;
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();
int ks = neoui_event_keysym();
if (menuOpen) {
if (k == NEO_KEY_UP) menuSel = (menuSel + 5) % 6;
else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 6;
else if (k == NEO_KEY_OK) {
menuOpen = false;
if (menuSel == 0) {
editAcctIdx = -1;
editAcctDraft = SipAccount{};
editFieldIdx = 0;
editModalOpen = true;
syncInputBufferForFocus();
} else if (menuSel == 1) {
// Cycle through configured accounts (0..N-1) and Direct Mode (-1)
if (accounts.empty()) {
activeAccountIdx = -1;
} else if (activeAccountIdx < 0) {
activeAccountIdx = 0;
} else if (activeAccountIdx + 1 < static_cast<int>(accounts.size())) {
++activeAccountIdx;
} else {
activeAccountIdx = -1;
}
} else if (menuSel == 2) {
directZrtpEnabled = !directZrtpEnabled;
neoui_show_toast(directZrtpEnabled ? "Direct ZRTP: ON" : "Direct ZRTP: OFF", 1500);
} else if (menuSel == 3) {
for (auto& a : accounts) {
if (a.enabled) sendSipRegister(a);
}
neoui_show_toast("REGISTER sent", 1500);
} else if (menuSel == 4 && activeTab == 1 &&
selectedRow >= 0 && selectedRow < static_cast<int>(accounts.size())) {
accounts.erase(accounts.begin() + selectedRow);
if (activeAccountIdx >= static_cast<int>(accounts.size())) {
activeAccountIdx = static_cast<int>(accounts.size()) - 1;
}
saveSipAccounts(accounts);
} else if (menuSel == 5) {
::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) {
neoui_input_commit_tap();
applyInputBufferToFocus();
editFieldIdx = (editFieldIdx + kNumEditFields - 1) % kNumEditFields;
syncInputBufferForFocus();
} else if (k == NEO_KEY_DOWN) {
neoui_input_commit_tap();
applyInputBufferToFocus();
editFieldIdx = (editFieldIdx + 1) % kNumEditFields;
syncInputBufferForFocus();
} else if (k == NEO_KEY_RIGHT && editFieldIdx <= 4 &&
neoui_input_is_tap_active()) {
neoui_input_commit_tap();
applyInputBufferToFocus();
} else if (k == NEO_KEY_OK) {
if (editFieldIdx <= 4) {
if (neoui_input_is_tap_active()) {
neoui_input_commit_tap();
applyInputBufferToFocus();
} else {
applyInputBufferToFocus();
editFieldIdx = (editFieldIdx + 1) % kNumEditFields;
syncInputBufferForFocus();
}
} else 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.zrtpEnabled = !editAcctDraft.zrtpEnabled;
} else if (editFieldIdx == 7) {
editAcctDraft.enabled = !editAcctDraft.enabled;
}
} else if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) {
if (editFieldIdx < 4) {
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) || k == NEO_KEY_PLUS)) {
neoui_input_feed_key(k);
applyInputBufferToFocus();
} else if (editFieldIdx <= 4 && k == NEO_KEY_NONE &&
ks >= 0x20 && ks <= 0x7e) {
if (editFieldIdx != 4 || (ks >= '0' && ks <= '9')) {
std::string cur = neoui_input_get_text();
cur.push_back(static_cast<char>(ks));
neoui_input_set_text(cur.c_str());
applyInputBufferToFocus();
}
}
render();
} else {
if (k == NEO_KEY_LEFT) {
neoui_input_commit_tap();
applyInputBufferToFocus();
activeTab = (activeTab + 2) % 3;
selectedRow = 0;
scrollOffset = 0;
syncInputBufferForFocus();
} else if (k == NEO_KEY_RIGHT) {
if (activeTab == 0 && neoui_input_is_tap_active()) {
neoui_input_commit_tap();
applyInputBufferToFocus();
} else {
neoui_input_commit_tap();
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) {
neoui_input_commit_tap();
applyInputBufferToFocus();
std::string target = dialInput;
if (target.empty() && selectedRow >= 0 &&
selectedRow < static_cast<int>(history.size())) {
target = history[selectedRow].peerUri;
}
if (!target.empty()) {
sendSipInvite(activeAccountIdx, target);
} else {
neoui_show_toast("Enter SIP URI (user@host)", 1800);
}
} 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())) {
sendSipInvite(activeAccountIdx, history[selectedRow].peerUri);
}
} else if (activeTab == 0) {
if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) {
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) || k == NEO_KEY_PLUS) {
neoui_input_feed_key(k);
applyInputBufferToFocus();
} else if (k == NEO_KEY_NONE && ks >= 0x20 && ks <= 0x7e) {
std::string cur = neoui_input_get_text();
cur.push_back(static_cast<char>(ks));
neoui_input_set_text(cur.c_str());
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 (callState == SipCallState::Active) {
timeoutMs = 150;
} else 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 ZRTP/SRTP, direct URI calling, and CallScreen integration",
sip_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
sip_run_main
};