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

4171 lines
154 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 multi-codec RTP audio (Opus, G.722, G.711 PCMU/PCMA,
// GSM 06.10, G.726-32, IMA ADPCM DVI4, and L16 PCM) + 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 <opus/opus.h>
#if __has_include(<gsm/gsm.h>)
#include <gsm/gsm.h>
#else
#include <gsm.h>
#endif
#include <atomic>
#include <fstream>
#include <map>
#include <mutex>
#include <thread>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
// ---------------------------------------------------------------------------
// Supported SIP / RTP Audio Codecs
// ---------------------------------------------------------------------------
enum class SipCodecId {
Pcmu = 0, // PT 0: G.711 u-law 8 kHz (64 kbps)
Pcma = 1, // PT 8: G.711 A-law 8 kHz (64 kbps)
Opus = 2, // PT 111: Opus 48 kHz RTP clock / 16 kHz wideband VoIP
G722 = 3, // PT 9: ITU-T G.722 16 kHz wideband HD Voice (64 kbps, 8 kHz RTP clock)
Gsm = 4, // PT 3: GSM 06.10 Full Rate 8 kHz (13 kbps, 33-byte frame)
G726_32 = 5, // PT 112: ITU-T G.726-32 ADPCM 8 kHz (32 kbps, 4-bit)
Dvi4_8k = 6, // PT 5: IMA ADPCM (DVI4) 8 kHz (32 kbps + 4-byte state hdr)
Dvi4_16k = 7, // PT 6: IMA ADPCM (DVI4) 16 kHz (64 kbps + 4-byte state hdr)
L16_8k = 8, // PT 100: Uncompressed 16-bit big-endian PCM 8 kHz (128 kbps)
L16_16k = 9 // PT 102: Uncompressed 16-bit big-endian PCM 16 kHz (256 kbps)
};
const char* codecShortName(SipCodecId id) {
switch (id) {
case SipCodecId::Opus: return "OPUS";
case SipCodecId::G722: return "G722";
case SipCodecId::Pcmu: return "PCMU";
case SipCodecId::Pcma: return "PCMA";
case SipCodecId::Gsm: return "GSM";
case SipCodecId::G726_32: return "G726-32";
case SipCodecId::Dvi4_8k: return "DVI4";
case SipCodecId::Dvi4_16k: return "DVI4-16K";
case SipCodecId::L16_8k: return "L16";
case SipCodecId::L16_16k: return "L16-16K";
}
return "PCMU";
}
int codecDefaultPt(SipCodecId id) {
switch (id) {
case SipCodecId::Pcmu: return 0;
case SipCodecId::Gsm: return 3;
case SipCodecId::Dvi4_8k: return 5;
case SipCodecId::Dvi4_16k: return 6;
case SipCodecId::Pcma: return 8;
case SipCodecId::G722: return 9;
case SipCodecId::L16_8k: return 100;
case SipCodecId::L16_16k: return 102;
case SipCodecId::Opus: return 111;
case SipCodecId::G726_32: return 112;
}
return 0;
}
int codecAudioSampleRate(SipCodecId id) {
switch (id) {
case SipCodecId::Opus:
case SipCodecId::G722:
case SipCodecId::Dvi4_16k:
case SipCodecId::L16_16k:
return 16000;
default:
return 8000;
}
}
uint32_t codecRtpTimestampStep20ms(SipCodecId id) {
switch (id) {
case SipCodecId::Opus:
return 960; // RFC 7587: 48 kHz RTP clock -> 960 ticks per 20 ms
case SipCodecId::Dvi4_16k:
case SipCodecId::L16_16k:
return 320; // 16 kHz RTP clock -> 320 ticks per 20 ms
case SipCodecId::G722:
return 160; // RFC 3551 Section 4.5.2: G.722 uses 8 kHz RTP clock -> 160 ticks per 20 ms
default:
return 160; // 8 kHz RTP clock -> 160 ticks per 20 ms
}
}
std::string toUpperStr(std::string s) {
for (char& ch : s) {
if (ch >= 'a' && ch <= 'z') {
ch = static_cast<char>(ch - 'a' + 'A');
}
}
return s;
}
std::string normalizePreferredCodec(const std::string& raw) {
std::string up = toUpperStr(trimStr(raw));
if (up == "OPUS" || up == "G722" || up == "PCMU" || up == "PCMA" ||
up == "GSM" || up == "G726-32" || up == "DVI4" || up == "L16") {
return up;
}
return "AUTO";
}
std::string cyclePreferredCodec(const std::string& cur) {
static const char* kList[] = {
"AUTO", "PCMU", "PCMA", "GSM", "OPUS", "G722", "G726-32", "DVI4", "L16"
};
std::string norm = normalizePreferredCodec(cur);
for (size_t i = 0; i < sizeof(kList) / sizeof(kList[0]); ++i) {
if (norm == kList[i]) {
return kList[(i + 1) % (sizeof(kList) / sizeof(kList[0]))];
}
}
return "AUTO";
}
// 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 pcm = pcmVal;
int mask = (pcm < 0) ? 0x7f : 0xff;
if (pcm < 0) pcm = -pcm;
if (pcm > kClip) pcm = kClip;
pcm += kBias;
int seg = 0;
for (int thr = 0xFF; seg < 7 && pcm > thr; ++seg, thr = (thr << 1) | 1) {
}
uint8_t uval = static_cast<uint8_t>((seg << 4) | ((pcm >> (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 pcm = pcmVal;
int mask = 0x55;
if (pcm >= 0) {
mask |= 0x80;
} else {
pcm = -pcm - 1;
}
if (pcm > 32767) pcm = 32767;
int seg = 0;
for (int thr = 0xFF; seg < 7 && pcm > thr; ++seg, thr = (thr << 1) | 1) {
}
uint8_t aval = (seg == 0)
? static_cast<uint8_t>((pcm >> 4) & 0x0f)
: static_cast<uint8_t>((seg << 4) | ((pcm >> (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 3551 Section 4.5.1 IMA ADPCM (DVI4) Codec (8 kHz and 16 kHz)
// ---------------------------------------------------------------------------
struct ImaAdpcmState {
int valprev = 0;
int index = 0;
static constexpr int kStepTable[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};
static constexpr int kIndexTable[16] = {
-1, -1, -1, -1, 2, 4, 6, 8,
-1, -1, -1, -1, 2, 4, 6, 8
};
uint8_t encodeSample(int16_t sample) {
int step = kStepTable[index];
int diff = sample - valprev;
uint8_t nibble = 0;
if (diff < 0) {
nibble = 8;
diff = -diff;
}
int vpdiff = step >> 3;
if (diff >= step) {
nibble |= 4;
diff -= step;
vpdiff += step;
}
step >>= 1;
if (diff >= step) {
nibble |= 2;
diff -= step;
vpdiff += step;
}
step >>= 1;
if (diff >= step) {
nibble |= 1;
vpdiff += step;
}
if (nibble & 8) valprev -= vpdiff;
else valprev += vpdiff;
valprev = std::clamp(valprev, -32768, 32767);
index = std::clamp(index + kIndexTable[nibble & 0x0f], 0, 88);
return nibble & 0x0f;
}
int16_t decodeNibble(uint8_t nibble) {
int step = kStepTable[index];
int vpdiff = step >> 3;
if (nibble & 4) vpdiff += step;
if (nibble & 2) vpdiff += (step >> 1);
if (nibble & 1) vpdiff += (step >> 2);
if (nibble & 8) valprev -= vpdiff;
else valprev += vpdiff;
valprev = std::clamp(valprev, -32768, 32767);
index = std::clamp(index + kIndexTable[nibble & 0x0f], 0, 88);
return static_cast<int16_t>(valprev);
}
// RFC 3551 Section 4.5.1: 4-byte DVI4 header + packed 4-bit nibbles
size_t encodeFrame(const int16_t* pcm, size_t numSamples, uint8_t* outBuf) {
int16_t hdrVal = static_cast<int16_t>(valprev);
outBuf[0] = static_cast<uint8_t>((static_cast<uint16_t>(hdrVal) >> 8) & 0xff);
outBuf[1] = static_cast<uint8_t>(static_cast<uint16_t>(hdrVal) & 0xff);
outBuf[2] = static_cast<uint8_t>(index & 0xff);
outBuf[3] = 0;
size_t outIdx = 4;
for (size_t i = 0; i + 1 < numSamples; i += 2) {
uint8_t hi = encodeSample(pcm[i]);
uint8_t lo = encodeSample(pcm[i + 1]);
outBuf[outIdx++] = static_cast<uint8_t>((hi << 4) | lo);
}
return outIdx;
}
size_t decodeFrame(const uint8_t* inBuf, size_t inLen, int16_t* outPcm, size_t maxSamples) {
if (inLen < 4) return 0;
int16_t hdrVal = static_cast<int16_t>(
(static_cast<uint16_t>(inBuf[0]) << 8) | inBuf[1]);
valprev = hdrVal;
index = std::clamp(static_cast<int>(inBuf[2]), 0, 88);
size_t count = 0;
for (size_t i = 4; i < inLen && count + 1 < maxSamples; ++i) {
outPcm[count++] = decodeNibble((inBuf[i] >> 4) & 0x0f);
outPcm[count++] = decodeNibble(inBuf[i] & 0x0f);
}
return count;
}
};
// ---------------------------------------------------------------------------
// ITU-T G.726 32 kbps (4-bit) ADPCM Codec (8 kHz)
// ---------------------------------------------------------------------------
struct G726_32State {
int stepIndex = 0;
int predVal = 0;
uint8_t encodeSample(int16_t sample) {
int step = ImaAdpcmState::kStepTable[stepIndex];
int diff = sample - predVal;
uint8_t code = 0;
if (diff < 0) {
code = 8;
diff = -diff;
}
int dq = step >> 3;
if (diff >= step) {
code |= 4;
diff -= step;
dq += step;
}
if (diff >= (step >> 1)) {
code |= 2;
diff -= (step >> 1);
dq += (step >> 1);
}
if (diff >= (step >> 2)) {
code |= 1;
dq += (step >> 2);
}
if (code & 8) predVal -= dq;
else predVal += dq;
predVal = std::clamp((predVal * 253) >> 8, -32768, 32767);
stepIndex = std::clamp(stepIndex + ImaAdpcmState::kIndexTable[code & 0x0f], 0, 88);
return code & 0x0f;
}
int16_t decodeSample(uint8_t code) {
int step = ImaAdpcmState::kStepTable[stepIndex];
int dq = step >> 3;
if (code & 4) dq += step;
if (code & 2) dq += (step >> 1);
if (code & 1) dq += (step >> 2);
if (code & 8) predVal -= dq;
else predVal += dq;
predVal = std::clamp((predVal * 253) >> 8, -32768, 32767);
stepIndex = std::clamp(stepIndex + ImaAdpcmState::kIndexTable[code & 0x0f], 0, 88);
return static_cast<int16_t>(predVal);
}
size_t encodeFrame(const int16_t* pcm, size_t numSamples, uint8_t* outBuf) {
size_t outIdx = 0;
for (size_t i = 0; i + 1 < numSamples; i += 2) {
uint8_t c0 = encodeSample(pcm[i]);
uint8_t c1 = encodeSample(pcm[i + 1]);
// RFC 3551 Section 4.5.4 packing
outBuf[outIdx++] = static_cast<uint8_t>(c0 | (c1 << 4));
}
return outIdx;
}
size_t decodeFrame(const uint8_t* inBuf, size_t inLen, int16_t* outPcm, size_t maxSamples) {
size_t count = 0;
for (size_t i = 0; i < inLen && count + 1 < maxSamples; ++i) {
outPcm[count++] = decodeSample(inBuf[i] & 0x0f);
outPcm[count++] = decodeSample((inBuf[i] >> 4) & 0x0f);
}
return count;
}
};
// ---------------------------------------------------------------------------
// ITU-T G.722 Wideband 16 kHz (64 kbps SB-ADPCM) Codec (RFC 3551 PT 9)
// ---------------------------------------------------------------------------
class G722State {
public:
G722State() { reset(); }
void reset() {
band_[0] = Band{};
band_[1] = Band{};
band_[0].det = 32;
band_[1].det = 8;
std::memset(txQmf_, 0, sizeof(txQmf_));
std::memset(rxQmf_, 0, sizeof(rxQmf_));
}
size_t encodeFrame(const int16_t* pcm16k, size_t numSamples, uint8_t* outBuf) {
size_t outIdx = 0;
for (size_t i = 0; i + 1 < numSamples; i += 2) {
// 24-tap QMF analysis filter
for (int j = 23; j >= 2; --j) {
txQmf_[j] = txQmf_[j - 2];
}
txQmf_[1] = pcm16k[i];
txQmf_[0] = pcm16k[i + 1];
int sumEven = 0;
int sumOdd = 0;
for (int j = 0; j < 12; ++j) {
sumEven += txQmf_[2 * j] * kQmfCoeffs[j];
sumOdd += txQmf_[2 * j + 1] * kQmfCoeffs[11 - j];
}
int xlow = std::clamp((sumEven + sumOdd) >> 14, -16384, 16383);
int xhigh = std::clamp((sumEven - sumOdd) >> 14, -16384, 16383);
// Lower sub-band (6-bit quantizer)
int el = std::clamp(xlow - band_[0].s, -16384, 16383);
int wd = (el >= 0) ? el : -(el + 1);
int mila = 0;
for (int m = 1; m < 30; ++m) {
if (wd < ((kQ6[m] * band_[0].det) >> 12)) break;
mila = m;
}
int il = (el < 0) ? kMisn[mila] : kMisp[mila];
int ril = il >> 2;
int dlt = (band_[0].det * kQ6m4[ril]) >> 15;
updateBand(0, dlt, ril, true);
// Higher sub-band (2-bit quantizer)
int eh = std::clamp(xhigh - band_[1].s, -16384, 16383);
int wdh = (eh >= 0) ? eh : -(eh + 1);
int mih = (wdh >= ((564 * band_[1].det) >> 12)) ? 2 : 1;
int ih = (eh < 0) ? ((mih == 1) ? 1 : 0) : ((mih == 1) ? 3 : 2);
int dhy = (band_[1].det * kQm2[ih]) >> 15;
updateBand(1, dhy, ih, false);
outBuf[outIdx++] = static_cast<uint8_t>(((ih & 0x03) << 6) | (il & 0x3f));
}
return outIdx;
}
size_t decodeFrame(const uint8_t* inBuf, size_t inLen, int16_t* outPcm16k, size_t maxSamples) {
size_t outCount = 0;
for (size_t i = 0; i < inLen && outCount + 1 < maxSamples; ++i) {
uint8_t code = inBuf[i];
int il = code & 0x3f;
int ih = (code >> 6) & 0x03;
// Lower sub-band reconstruction (6-bit)
int ril = il >> 2;
int dlt = (band_[0].det * kQ6b[il]) >> 15;
int rlow = std::clamp(band_[0].s + dlt, -16384, 16383);
updateBand(0, (band_[0].det * kQ6m4[ril]) >> 15, ril, true);
// Higher sub-band reconstruction (2-bit)
int dhy = (band_[1].det * kQm2[ih]) >> 15;
int rhigh = std::clamp(band_[1].s + dhy, -16384, 16383);
updateBand(1, dhy, ih, false);
// 24-tap QMF synthesis filter
for (int j = 23; j >= 2; --j) {
rxQmf_[j] = rxQmf_[j - 2];
}
rxQmf_[1] = rlow - rhigh;
rxQmf_[0] = rlow + rhigh;
int sumA = 0;
int sumB = 0;
for (int j = 0; j < 12; ++j) {
sumA += rxQmf_[2 * j] * kQmfCoeffs[j];
sumB += rxQmf_[2 * j + 1] * kQmfCoeffs[11 - j];
}
outPcm16k[outCount++] = static_cast<int16_t>(std::clamp(sumB >> 13, -32768, 32767));
outPcm16k[outCount++] = static_cast<int16_t>(std::clamp(sumA >> 13, -32768, 32767));
}
return outCount;
}
private:
struct Band {
int s = 0;
int sp = 0;
int sz = 0;
int r[3] {};
int a[3] {};
int ap[3] {};
int p[3] {};
int d[7] {};
int b[7] {};
int bp[7] {};
int sg[7] {};
int nb = 0;
int det = 32;
};
void updateBand(int bIdx, int dlt, int idx, bool isLow) {
Band& b = band_[bIdx];
b.d[0] = dlt;
b.r[0] = std::clamp(b.s + dlt, -16384, 16383);
b.p[0] = std::clamp(b.sz + dlt, -16384, 16383);
// Adaptive zero section
for (int i = 1; i <= 6; ++i) {
int wd1 = (dlt == 0) ? 0 : (((dlt ^ b.d[i]) >= 0) ? 128 : -128);
int wd2 = (b.b[i] * 32640) >> 15;
b.bp[i] = std::clamp(wd1 + wd2, -32768, 32767);
}
// Adaptive pole section
b.sg[0] = (b.p[0] >= 0) ? 0 : 1;
b.sg[1] = (b.p[1] >= 0) ? 0 : 1;
b.sg[2] = (b.p[2] >= 0) ? 0 : 1;
int wd1 = std::clamp(b.a[1], -8191, 8191);
int wd2 = (b.sg[0] == b.sg[1]) ? -wd1 : wd1;
if (wd2 > 32767) wd2 = 32767;
int wd3 = (b.sg[0] == b.sg[2]) ? 128 : -128;
wd3 += (wd2 >> 7);
wd3 += (b.a[2] * 32512) >> 15;
b.ap[2] = std::clamp(wd3, -12288, 12288);
int wd4 = (b.p[0] == 0) ? 0 : ((b.sg[0] == b.sg[1]) ? 192 : -192);
int wd5 = (b.a[1] * 32640) >> 15;
int limit = 15360 - b.ap[2];
b.ap[1] = std::clamp(wd4 + wd5, -limit, limit);
// Log scale factor adaptation
int wl = isLow ? kWl[idx] : kWh[idx];
b.nb = std::clamp(((b.nb * 127) >> 7) + wl, 0, isLow ? 18432 : 22528);
int shift = (b.nb >> 11) + (isLow ? 0 : 2);
int ilb = kIlb[(b.nb & 0x7ff) >> 6];
b.det = std::max(1, (shift >= 9) ? (ilb << (shift - 9)) : (ilb >> (9 - shift)));
// Shift delay lines and compute new predictor outputs
for (int i = 6; i >= 1; --i) {
b.d[i] = b.d[i - 1];
b.b[i] = b.bp[i];
}
b.r[2] = b.r[1];
b.r[1] = b.r[0];
b.p[2] = b.p[1];
b.p[1] = b.p[0];
b.a[2] = b.ap[2];
b.a[1] = b.ap[1];
b.sz = 0;
for (int i = 1; i <= 6; ++i) {
b.sz += (b.b[i] * b.d[i]) >> 14;
}
b.sz = std::clamp(b.sz, -16384, 16383);
b.sp = std::clamp(((b.a[1] * b.r[1]) + (b.a[2] * b.r[2])) >> 14, -16384, 16383);
b.s = std::clamp(b.sp + b.sz, -16384, 16383);
}
static constexpr int kQmfCoeffs[12] = {
3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11
};
static constexpr int kQ6[30] = {
0, 35, 72, 110, 150, 190, 233, 276, 323, 370,
422, 473, 530, 587, 650, 714, 786, 858, 940, 1023,
1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, 2557, 2919
};
static constexpr int kMisn[30] = {
63, 62, 31, 30, 29, 28, 27, 26, 25, 24,
23, 22, 21, 20, 19, 18, 17, 16, 15, 14,
13, 12, 11, 10, 9, 8, 7, 6, 5, 4
};
static constexpr int kMisp[30] = {
61, 60, 59, 58, 57, 56, 55, 54, 53, 52,
51, 50, 49, 48, 47, 46, 45, 44, 43, 42,
41, 40, 39, 38, 37, 36, 35, 34, 33, 32
};
static constexpr int kQ6m4[16] = {
0, -20456, -12896, -8968, -6288, -4240, -2584, -1200,
20456, 12896, 8968, 6288, 4240, 2584, 1200, 0
};
static constexpr int kQ6b[64] = {
-136, -136, -136, -136, -24808, -21904, -19008, -16704,
-14984, -13512, -12280, -11192, -10232, -9360, -8576, -7856,
-7192, -6576, -6000, -5456, -4944, -4464, -4008, -3576,
-3168, -2776, -2400, -2032, -1688, -1360, -1040, -728,
24808, 21904, 19008, 16704, 14984, 13512, 12280, 11192,
10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456,
4944, 4464, 4008, 3576, 3168, 2776, 2400, 2032,
1688, 1360, 1040, 728, 432, 136, -432, -136
};
static constexpr int kQm2[4] = { -7408, -1616, 7408, 1616 };
static constexpr int kWl[16] = {
-60, 3042, 1198, 538, 334, 172, 58, -30,
3042, 1198, 538, 334, 172, 58, -30, -60
};
static constexpr int kWh[4] = { 798, -214, 798, -214 };
static constexpr int kIlb[32] = {
2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383,
2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,
3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008
};
Band band_[2];
int txQmf_[24] {};
int rxQmf_[24] {};
};
// ---------------------------------------------------------------------------
// 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;
std::string preferredCodec = "AUTO"; // AUTO, OPUS, G722, PCMU, PCMA, GSM, G726-32, DVI4, L16
// 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");
}
if (cols.size() >= 10 && !cols[9].empty()) {
a.preferredCodec = normalizePreferredCodec(cols[9]);
}
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") << "\t"
<< normalizePreferredCodec(a.preferredCodec) << "\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";
}
}
// Decode a DNS compressed name from packet `pkt` at offset `pos`
std::string decodeDnsName(const uint8_t* pkt, size_t pktLen, size_t& ioPos) {
std::string out;
size_t pos = ioPos;
bool jumped = false;
int jumps = 0;
while (pos < pktLen && jumps < 16) {
uint8_t len = pkt[pos];
if (len == 0) {
++pos;
if (!jumped) ioPos = pos;
break;
}
if ((len & 0xc0) == 0xc0) {
if (pos + 1 >= pktLen) break;
size_t ptr = (static_cast<size_t>(len & 0x3f) << 8) | pkt[pos + 1];
if (!jumped) ioPos = pos + 2;
pos = ptr;
jumped = true;
++jumps;
continue;
}
++pos;
if (pos + len > pktLen) break;
if (!out.empty()) out.push_back('.');
out.append(reinterpret_cast<const char*>(pkt + pos), len);
pos += len;
if (!jumped) ioPos = pos;
}
return out;
}
bool sendDnsQueryUdp(const std::string& qname, uint16_t qtype,
std::vector<uint8_t>& outResp) {
std::vector<uint8_t> req = {
0x42, 0x53, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
std::istringstream iss(qname);
std::string label;
while (std::getline(iss, label, '.')) {
if (label.empty() || label.size() > 63) continue;
req.push_back(static_cast<uint8_t>(label.size()));
req.insert(req.end(), label.begin(), label.end());
}
req.push_back(0x00);
req.push_back(static_cast<uint8_t>((qtype >> 8) & 0xff));
req.push_back(static_cast<uint8_t>(qtype & 0xff));
req.push_back(0x00);
req.push_back(0x01); // IN
const char* dnsServers[] = { "127.0.0.1", "1.1.1.1", "8.8.8.8" };
for (const char* ns : dnsServers) {
int s = ::socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (s < 0) continue;
struct sockaddr_in sin {};
sin.sin_family = AF_INET;
sin.sin_port = htons(53);
::inet_pton(AF_INET, ns, &sin.sin_addr);
::sendto(s, req.data(), req.size(), 0,
reinterpret_cast<const struct sockaddr*>(&sin), sizeof(sin));
struct pollfd pfd { s, POLLIN, 0 };
if (::poll(&pfd, 1, 350) > 0 && (pfd.revents & POLLIN)) {
uint8_t buf[1024];
ssize_t n = ::recv(s, buf, sizeof(buf), 0);
if (n >= 12 && (buf[3] & 0x0f) == 0) {
outResp.assign(buf, buf + n);
::close(s);
return true;
}
}
::close(s);
}
return false;
}
// RFC 3263 DNS SRV (_sip._udp.<domain>) + A record resolution
void resolveSipSrvAndA(const std::string& domain, int explicitPort,
std::string& outProxyHost, int& outProxyPort,
std::vector<std::string>& outIps) {
outProxyHost = domain;
outProxyPort = explicitPort > 0 ? explicitPort : 5060;
outIps.clear();
if (domain.empty()) return;
struct in_addr literalAddr {};
if (::inet_pton(AF_INET, domain.c_str(), &literalAddr) == 1) {
outIps.push_back(domain);
return;
}
if (toLowerStr(domain) == "localhost") {
outIps.push_back("127.0.0.1");
return;
}
// 1. If no explicit non-5060 port was specified, query _sip._udp.<domain> SRV (QTYPE=33)
if (explicitPort <= 0 || explicitPort == 5060) {
std::vector<uint8_t> resp;
if (sendDnsQueryUdp("_sip._udp." + domain, 33, resp) && resp.size() >= 12) {
uint16_t qdcount = (static_cast<uint16_t>(resp[4]) << 8) | resp[5];
uint16_t ancount = (static_cast<uint16_t>(resp[6]) << 8) | resp[7];
size_t pos = 12;
for (uint16_t i = 0; i < qdcount && pos < resp.size(); ++i) {
decodeDnsName(resp.data(), resp.size(), pos);
pos += 4;
}
uint16_t bestPrio = 0xffff;
uint16_t bestWeight = 0;
for (uint16_t i = 0; i < ancount && pos < resp.size(); ++i) {
decodeDnsName(resp.data(), resp.size(), pos);
if (pos + 10 > resp.size()) break;
uint16_t rtype = (static_cast<uint16_t>(resp[pos]) << 8) | resp[pos + 1];
uint16_t rdlen = (static_cast<uint16_t>(resp[pos + 8]) << 8) | resp[pos + 9];
pos += 10;
if (pos + rdlen > resp.size()) break;
if (rtype == 33 && rdlen >= 7) {
uint16_t prio = (static_cast<uint16_t>(resp[pos]) << 8) | resp[pos + 1];
uint16_t weight = (static_cast<uint16_t>(resp[pos + 2]) << 8) | resp[pos + 3];
uint16_t srvPort = (static_cast<uint16_t>(resp[pos + 4]) << 8) | resp[pos + 5];
size_t tpos = pos + 6;
std::string target = decodeDnsName(resp.data(), resp.size(), tpos);
if (!target.empty() && srvPort > 0 &&
(prio < bestPrio || (prio == bestPrio && weight >= bestWeight))) {
bestPrio = prio;
bestWeight = weight;
outProxyHost = target;
outProxyPort = srvPort;
}
}
pos += rdlen;
}
}
}
// 2. Resolve outProxyHost -> all IPv4 A records (QTYPE=1)
std::vector<uint8_t> aResp;
if (sendDnsQueryUdp(outProxyHost, 1, aResp) && aResp.size() >= 12) {
uint16_t qdcount = (static_cast<uint16_t>(aResp[4]) << 8) | aResp[5];
uint16_t ancount = (static_cast<uint16_t>(aResp[6]) << 8) | aResp[7];
size_t pos = 12;
for (uint16_t i = 0; i < qdcount && pos < aResp.size(); ++i) {
decodeDnsName(aResp.data(), aResp.size(), pos);
pos += 4;
}
for (uint16_t i = 0; i < ancount && pos < aResp.size(); ++i) {
decodeDnsName(aResp.data(), aResp.size(), pos);
if (pos + 10 > aResp.size()) break;
uint16_t rtype = (static_cast<uint16_t>(aResp[pos]) << 8) | aResp[pos + 1];
uint16_t rdlen = (static_cast<uint16_t>(aResp[pos + 8]) << 8) | aResp[pos + 9];
pos += 10;
if (pos + rdlen > aResp.size()) break;
if (rtype == 1 && rdlen == 4) {
char ipStr[INET_ADDRSTRLEN] = {0};
if (::inet_ntop(AF_INET, aResp.data() + pos, ipStr, sizeof(ipStr))) {
outIps.push_back(ipStr);
}
}
pos += rdlen;
}
}
if (outIps.empty()) {
struct addrinfo hints {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
struct addrinfo* res = nullptr;
if (::getaddrinfo(outProxyHost.c_str(), nullptr, &hints, &res) == 0 && res) {
for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) {
char ipStr[INET_ADDRSTRLEN] = {0};
auto* sin = reinterpret_cast<struct sockaddr_in*>(p->ai_addr);
if (::inet_ntop(AF_INET, &sin->sin_addr, ipStr, sizeof(ipStr))) {
outIps.push_back(ipStr);
}
}
::freeaddrinfo(res);
}
}
}
std::string detectLocalIpForHost(const std::string& remoteHost) {
std::string target = remoteHost.empty() ? "8.8.8.8" : remoteHost;
struct in_addr probeSinAddr {};
if (::inet_pton(AF_INET, target.c_str(), &probeSinAddr) != 1) {
std::string pHost;
int pPort = 5060;
std::vector<std::string> ips;
resolveSipSrvAndA(target, 5060, pHost, pPort, ips);
if (!ips.empty()) {
target = ips.front();
} else {
target = "8.8.8.8";
}
}
int s = ::socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (s >= 0) {
struct sockaddr_in rem {};
rem.sin_family = AF_INET;
rem.sin_port = htons(5060);
if (::inet_pton(AF_INET, target.c_str(), &rem.sin_addr) != 1) {
::inet_pton(AF_INET, "8.8.8.8", &rem.sin_addr);
}
if (::connect(s, reinterpret_cast<struct sockaddr*>(&rem), sizeof(rem)) == 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);
return std::string(ipBuf);
}
}
}
::close(s);
}
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::vector<std::string>* outProxyIps = nullptr) {
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;
outTargetUri = "sip:" + userPart + "@" + acct->domain;
std::vector<std::string> ips;
resolveSipSrvAndA(acct->domain, acct->port > 0 ? acct->port : 5060,
outHost, outPort, ips);
if (outProxyIps) *outProxyIps = ips;
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;
}
int explicitPort = (acct && acct->port > 0 && acct->domain == hostPortPart) ? acct->port : 0;
std::string domainPart = hostPortPart;
size_t colonPos = hostPortPart.rfind(':');
if (colonPos != std::string::npos) {
domainPart = hostPortPart.substr(0, colonPos);
int p = std::atoi(hostPortPart.substr(colonPos + 1).c_str());
if (p > 0 && p <= 65535) {
explicitPort = p;
}
}
if (domainPart.empty()) return false;
if (userPart.empty()) userPart = "user";
if (acct && !acct->domain.empty() && acct->enabled &&
toLowerStr(domainPart) == toLowerStr(acct->domain)) {
outTargetUri = "sip:" + userPart + "@" + domainPart;
explicitPort = acct->port > 0 ? acct->port : explicitPort;
} else {
outTargetUri = "sip:" + userPart + "@" + hostPortPart;
}
std::vector<std::string> ips;
resolveSipSrvAndA(domainPart, explicitPort, outHost, outPort, ips);
if (outProxyIps) *outProxyIps = ips;
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 "";
}
std::vector<std::string> getSipHeaderValues(const std::string& msg,
const std::string& hdrName) {
std::vector<std::string> out;
std::istringstream iss(msg);
std::string line;
std::string lowName = toLowerStr(hdrName) + ":";
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) {
std::string val = trimStr(line.substr(lowName.size()));
if (!val.empty()) out.push_back(val);
}
}
return out;
}
std::string extractSipUriFromHeader(const std::string& hdrVal) {
size_t lt = hdrVal.find('<');
size_t gt = hdrVal.find('>');
if (lt != std::string::npos && gt != std::string::npos && gt > lt + 1) {
return trimStr(hdrVal.substr(lt + 1, gt - lt - 1));
}
size_t semi = hdrVal.find(';');
return trimStr(semi == std::string::npos ? hdrVal : hdrVal.substr(0, semi));
}
bool codecMatchesPreference(SipCodecId id, const std::string& pref) {
std::string up = normalizePreferredCodec(pref);
if (up == "OPUS") return id == SipCodecId::Opus;
if (up == "G722") return id == SipCodecId::G722;
if (up == "PCMU") return id == SipCodecId::Pcmu;
if (up == "PCMA") return id == SipCodecId::Pcma;
if (up == "GSM") return id == SipCodecId::Gsm;
if (up == "G726-32") return id == SipCodecId::G726_32;
if (up == "DVI4") return id == SipCodecId::Dvi4_16k || id == SipCodecId::Dvi4_8k;
if (up == "L16") return id == SipCodecId::L16_16k || id == SipCodecId::L16_8k;
return false;
}
std::vector<SipCodecId> orderedCodecsForPreference(const std::string& pref) {
static const SipCodecId kDefaultOrder[] = {
SipCodecId::Pcmu,
SipCodecId::Pcma,
SipCodecId::Gsm,
SipCodecId::Opus,
SipCodecId::G722,
SipCodecId::G726_32,
SipCodecId::Dvi4_8k,
SipCodecId::Dvi4_16k,
SipCodecId::L16_8k,
SipCodecId::L16_16k
};
std::vector<SipCodecId> out;
for (SipCodecId c : kDefaultOrder) {
if (codecMatchesPreference(c, pref)) {
out.push_back(c);
}
}
for (SipCodecId c : kDefaultOrder) {
if (!codecMatchesPreference(c, pref)) {
out.push_back(c);
}
}
return out;
}
std::string codecRtpmapLine(int pt, SipCodecId id) {
std::ostringstream oss;
oss << "a=rtpmap:" << pt << " ";
switch (id) {
case SipCodecId::Opus:
oss << "opus/48000/2\r\n"
<< "a=fmtp:" << pt
<< " minptime=10;useinbandfec=1;maxaveragebitrate=24000;"
"maxplaybackrate=16000;sprop-maxcapturerate=16000;stereo=0;sprop-stereo=0\r\n";
break;
case SipCodecId::G722:
oss << "G722/8000\r\n";
break;
case SipCodecId::Pcmu:
oss << "PCMU/8000\r\n";
break;
case SipCodecId::Pcma:
oss << "PCMA/8000\r\n";
break;
case SipCodecId::Gsm:
oss << "GSM/8000\r\n";
break;
case SipCodecId::G726_32:
oss << "G726-32/8000\r\n";
break;
case SipCodecId::Dvi4_8k:
oss << "DVI4/8000\r\n";
break;
case SipCodecId::Dvi4_16k:
oss << "DVI4/16000\r\n";
break;
case SipCodecId::L16_8k:
oss << "L16/8000\r\n";
break;
case SipCodecId::L16_16k:
oss << "L16/16000\r\n";
break;
}
return oss.str();
}
void parseSdpMedia(const std::string& msg, const std::string& preferredCodec,
std::string& outIp, int& outPort,
SipCodecId& outCodec, int& outPayloadType,
int& outDtmfPt, std::map<int, SipCodecId>& outPtMap,
std::string& outPeerZrtpHash) {
outPeerZrtpHash.clear();
outCodec = SipCodecId::Pcmu;
outPayloadType = 0;
outDtmfPt = 101;
outPtMap.clear();
// Default static + Bananarchy dynamic PT mappings
outPtMap[0] = SipCodecId::Pcmu;
outPtMap[2] = SipCodecId::G726_32;
outPtMap[3] = SipCodecId::Gsm;
outPtMap[5] = SipCodecId::Dvi4_8k;
outPtMap[6] = SipCodecId::Dvi4_16k;
outPtMap[8] = SipCodecId::Pcma;
outPtMap[9] = SipCodecId::G722;
outPtMap[11] = SipCodecId::L16_8k;
outPtMap[100] = SipCodecId::L16_8k;
outPtMap[102] = SipCodecId::L16_16k;
outPtMap[111] = SipCodecId::Opus;
outPtMap[112] = SipCodecId::G726_32;
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;
std::vector<int> offeredPts;
std::map<int, std::string> rtpmapSpecs;
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) {
offeredPts.push_back(pt);
}
} else if (line.rfind("a=rtpmap:", 0) == 0) {
std::istringstream rss(line.substr(9));
int pt = -1;
std::string spec;
rss >> pt >> spec;
if (pt >= 0 && !spec.empty()) {
rtpmapSpecs[pt] = toUpperStr(trimStr(spec));
}
} 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;
}
}
}
std::vector<int> nonAudioPts;
for (const auto& kv : rtpmapSpecs) {
int pt = kv.first;
const std::string& spec = kv.second;
if (spec.rfind("TELEPHONE-EVENT/", 0) == 0) {
outDtmfPt = pt;
outPtMap.erase(pt);
nonAudioPts.push_back(pt);
} else if (spec.rfind("OPUS/", 0) == 0) {
outPtMap[pt] = SipCodecId::Opus;
} else if (spec.rfind("G722/", 0) == 0) {
outPtMap[pt] = SipCodecId::G722;
} else if (spec.rfind("PCMU/", 0) == 0) {
outPtMap[pt] = SipCodecId::Pcmu;
} else if (spec.rfind("PCMA/", 0) == 0) {
outPtMap[pt] = SipCodecId::Pcma;
} else if (spec.rfind("GSM/", 0) == 0) {
outPtMap[pt] = SipCodecId::Gsm;
} else if (spec.rfind("G726-32/", 0) == 0 || spec.rfind("G721/", 0) == 0 ||
spec.rfind("AAL2-G726-32/", 0) == 0) {
outPtMap[pt] = SipCodecId::G726_32;
} else if (spec.rfind("DVI4/16000", 0) == 0) {
outPtMap[pt] = SipCodecId::Dvi4_16k;
} else if (spec.rfind("DVI4/8000", 0) == 0) {
outPtMap[pt] = SipCodecId::Dvi4_8k;
} else if (spec.rfind("L16/16000", 0) == 0) {
outPtMap[pt] = SipCodecId::L16_16k;
} else if (spec.rfind("L16/8000", 0) == 0) {
outPtMap[pt] = SipCodecId::L16_8k;
} else {
// Unknown dynamic codec on this PT: remove default assumption if dynamic
if (pt >= 96) {
outPtMap.erase(pt);
}
nonAudioPts.push_back(pt);
}
}
// 1. If a specific preferredCodec is configured, pick it if offered by peer
std::string normPref = normalizePreferredCodec(preferredCodec);
if (normPref != "AUTO") {
for (int pt : offeredPts) {
auto it = outPtMap.find(pt);
if (it != outPtMap.end() && codecMatchesPreference(it->second, normPref)) {
outCodec = it->second;
outPayloadType = pt;
return;
}
}
}
// 2. In AUTO mode, prefer our ordered priority list (G.711 PCMU/PCMA first)
// among all codecs offered by the peer.
for (SipCodecId prefId : orderedCodecsForPreference("AUTO")) {
for (int pt : offeredPts) {
auto it = outPtMap.find(pt);
if (it != outPtMap.end() && it->second == prefId) {
outCodec = it->second;
outPayloadType = pt;
return;
}
}
}
// 3. Otherwise pick the first mutually supported codec in peer's m=audio line
for (int pt : offeredPts) {
auto it = outPtMap.find(pt);
if (it != outPtMap.end()) {
outCodec = it->second;
outPayloadType = pt;
return;
}
}
}
// ---------------------------------------------------------------------------
// 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,
SipCodecId codec, int payloadType, int dtmfPt,
const std::map<int, SipCodecId>& ptMap, bool enableZrtp,
bool peerHasZrtpSdp = false) {
if (remoteIp.empty() || remotePort <= 0) {
stop();
return false;
}
if (running_.load() && sock_ >= 0 && remoteIp == activeRemoteIp_ &&
remotePort == activeRemotePort_ && codec == codec_ &&
payloadType == payloadType_) {
dtmfPt_ = (dtmfPt > 0 && dtmfPt <= 127) ? dtmfPt : 101;
return true;
}
stop();
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;
peerHasZrtpSdp_ = peerHasZrtpSdp;
txAudioFrames_ = 0;
if (enableZrtp && localHelloMsg_.empty()) {
initZrtpMaterialLocked();
}
}
sock_ = sock;
remAddr_ = remAddr;
activeRemoteIp_ = remoteIp;
activeRemotePort_ = remotePort;
codec_ = codec;
payloadType_ = payloadType;
dtmfPt_ = (dtmfPt > 0 && dtmfPt <= 127) ? dtmfPt : 101;
rxPtMap_ = ptMap;
rxPtMap_[payloadType] = codec;
running_.store(true);
worker_ = std::thread([this]() { runLoop(); });
return true;
}
void stop() {
running_.store(false);
pid_t cp = capPid_.load();
if (cp > 1) ::kill(cp, SIGTERM);
pid_t pp = playPid_.load();
if (pp > 1) ::kill(pp, SIGTERM);
if (worker_.joinable()) {
worker_.join();
}
if (sock_ >= 0) {
::close(sock_);
sock_ = -1;
}
activeRemoteIp_.clear();
activeRemotePort_ = 0;
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(); }
SipCodecId activeCodec() const { return codec_; }
const char* activeCodecName() const { return codecShortName(codec_); }
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 (!peerHasZrtpSdp_ && !peerHelloReceived_ && txAudioFrames_ < 5) {
return;
}
int maxHellos = (peerHasZrtpSdp_ || peerHelloReceived_) ? 25 : 6;
if (helloSendCount_ < maxHellos && !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() {
::system("amixer -c 0 cset \"name='PRI_MI2S_RX Audio Mixer MultiMedia1'\" 1 >/dev/null 2>&1; "
"amixer -c 0 cset \"name='MultiMedia2 Mixer TERT_MI2S_TX'\" 1 >/dev/null 2>&1");
int audioRate = codecAudioSampleRate(codec_);
size_t frameSamples = static_cast<size_t>(audioRate / 50); // 160 @ 8k, 320 @ 16k
size_t frameBytes = frameSamples * sizeof(int16_t);
std::string rateStr = std::to_string(audioRate);
int capPipe[2] = {-1, -1};
int capFd = -1;
pid_t capPid = -1;
if (::pipe(capPipe) == 0) {
capPid = ::fork();
if (capPid == 0) {
::close(capPipe[0]);
::dup2(capPipe[1], STDOUT_FILENO);
::close(capPipe[1]);
int nullFd = ::open("/dev/null", O_RDWR);
if (nullFd >= 0) {
::dup2(nullFd, STDIN_FILENO);
::dup2(nullFd, STDERR_FILENO);
if (nullFd > 2) ::close(nullFd);
}
::execlp("arecord", "arecord", "-q", "--buffer-time=160000",
"--period-time=20000", "-f", "S16_LE", "-r", rateStr.c_str(),
"-c", "1", "-t", "raw", static_cast<char*>(nullptr));
::_exit(1);
} else if (capPid > 0) {
::close(capPipe[1]);
capFd = capPipe[0];
int fl = ::fcntl(capFd, F_GETFL, 0);
::fcntl(capFd, F_SETFL, fl | O_NONBLOCK);
capPid_.store(capPid);
} else {
::close(capPipe[0]);
::close(capPipe[1]);
}
}
int playPipe[2] = {-1, -1};
int playFd = -1;
pid_t playPid = -1;
if (::pipe(playPipe) == 0) {
playPid = ::fork();
if (playPid == 0) {
::close(playPipe[1]);
::dup2(playPipe[0], STDIN_FILENO);
::close(playPipe[0]);
int nullFd = ::open("/dev/null", O_RDWR);
if (nullFd >= 0) {
::dup2(nullFd, STDOUT_FILENO);
::dup2(nullFd, STDERR_FILENO);
if (nullFd > 2) ::close(nullFd);
}
::execlp("aplay", "aplay", "-q", "--buffer-time=200000",
"--period-time=20000", "-f", "S16_LE", "-r", rateStr.c_str(),
"-c", "1", "-t", "raw", static_cast<char*>(nullptr));
::_exit(1);
} else if (playPid > 0) {
::close(playPipe[0]);
playFd = playPipe[1];
int fl = ::fcntl(playFd, F_GETFL, 0);
::fcntl(playFd, F_SETFL, fl | O_NONBLOCK);
playPid_.store(playPid);
} else {
::close(playPipe[0]);
::close(playPipe[1]);
}
}
int opusErr = OPUS_OK;
OpusEncoder* opusEnc = opus_encoder_create(16000, 1, OPUS_APPLICATION_VOIP, &opusErr);
if (opusEnc) {
opus_encoder_ctl(opusEnc, OPUS_SET_BITRATE(24000));
opus_encoder_ctl(opusEnc, OPUS_SET_VBR(1));
opus_encoder_ctl(opusEnc, OPUS_SET_INBAND_FEC(1));
opus_encoder_ctl(opusEnc, OPUS_SET_COMPLEXITY(5));
opus_encoder_ctl(opusEnc, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
}
OpusDecoder* opusDec = opus_decoder_create(16000, 1, &opusErr);
gsm gsmEnc = gsm_create();
gsm gsmDec = gsm_create();
G722State g722Enc;
G722State g722Dec;
G726_32State g726Enc;
G726_32State g726Dec;
ImaAdpcmState dvi4Enc;
ImaAdpcmState dvi4Dec;
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;
bool playPrimed = false;
uint8_t capRing[2560];
size_t capAvail = 0;
while (running_.load()) {
// Drain available microphone capture bytes into capRing without blocking
if (capFd >= 0 && capAvail < sizeof(capRing)) {
ssize_t r = ::read(capFd, capRing + capAvail, sizeof(capRing) - capAvail);
if (r > 0) {
capAvail += static_cast<size_t>(r);
}
}
// 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;
int pt = rxPkt[1] & 0x7f;
size_t hdrLen = 12 + (rxPkt[0] & 0x0f) * 4;
if (pktLen <= hdrLen) continue;
if (!unprotectRtpPacket(rxPkt, pktLen, hdrLen)) {
continue;
}
if (pt == dtmfPt_) continue;
auto itCodec = rxPtMap_.find(pt);
if (itCodec == rxPtMap_.end()) continue;
SipCodecId rxCodec = itCodec->second;
const uint8_t* payload = rxPkt + hdrLen;
size_t payLen = pktLen - hdrLen;
if (playFd < 0 || payLen == 0) continue;
int16_t pcmDecoded[1920];
size_t decodedSamples = 0;
switch (rxCodec) {
case SipCodecId::Opus:
if (opusDec) {
int r = opus_decode(opusDec, payload,
static_cast<opus_int32>(payLen),
pcmDecoded, 1920, 0);
if (r > 0) decodedSamples = static_cast<size_t>(r);
}
break;
case SipCodecId::G722:
decodedSamples = g722Dec.decodeFrame(payload, payLen, pcmDecoded, 1920);
break;
case SipCodecId::Pcmu:
decodedSamples = std::min<size_t>(payLen, 1920);
for (size_t i = 0; i < decodedSamples; ++i) {
pcmDecoded[i] = ulawToLinear(payload[i]);
}
break;
case SipCodecId::Pcma:
decodedSamples = std::min<size_t>(payLen, 1920);
for (size_t i = 0; i < decodedSamples; ++i) {
pcmDecoded[i] = alawToLinear(payload[i]);
}
break;
case SipCodecId::Gsm:
if (gsmDec) {
for (size_t off = 0; off + 33 <= payLen && decodedSamples + 160 <= 1920; off += 33) {
gsm_byte frame[33];
std::memcpy(frame, payload + off, 33);
if (gsm_decode(gsmDec, frame, pcmDecoded + decodedSamples) == 0) {
decodedSamples += 160;
}
}
}
break;
case SipCodecId::G726_32:
decodedSamples = g726Dec.decodeFrame(payload, payLen, pcmDecoded, 1920);
break;
case SipCodecId::Dvi4_8k:
case SipCodecId::Dvi4_16k:
decodedSamples = dvi4Dec.decodeFrame(payload, payLen, pcmDecoded, 1920);
break;
case SipCodecId::L16_8k:
case SipCodecId::L16_16k:
for (size_t i = 0; i + 1 < payLen && decodedSamples < 1920; i += 2) {
uint16_t be = (static_cast<uint16_t>(payload[i]) << 8) | payload[i + 1];
pcmDecoded[decodedSamples++] = static_cast<int16_t>(be);
}
break;
}
if (decodedSamples > 0) {
if (!playPrimed) {
playPrimed = true;
int16_t silence[960] = {0};
(void)::write(playFd, silence, frameSamples * 3 * sizeof(int16_t));
}
int rxRate = codecAudioSampleRate(rxCodec);
if (rxRate == audioRate) {
(void)::write(playFd, pcmDecoded, decodedSamples * sizeof(int16_t));
} else if (rxRate == 8000 && audioRate == 16000) {
int16_t pcmUp[1920];
size_t upCount = 0;
for (size_t i = 0; i < decodedSamples && upCount + 1 < 1920; ++i) {
int16_t s0 = pcmDecoded[i];
int16_t s1 = (i + 1 < decodedSamples) ? pcmDecoded[i + 1] : s0;
pcmUp[upCount++] = s0;
pcmUp[upCount++] = static_cast<int16_t>((static_cast<int>(s0) + s1) / 2);
}
(void)::write(playFd, pcmUp, upCount * sizeof(int16_t));
} else if (rxRate == 16000 && audioRate == 8000) {
int16_t pcmDown[960];
size_t downCount = 0;
for (size_t i = 0; i + 1 < decodedSamples && downCount < 960; i += 2) {
pcmDown[downCount++] = static_cast<int16_t>(
(static_cast<int>(pcmDecoded[i]) + pcmDecoded[i + 1]) / 2);
}
(void)::write(playFd, pcmDown, downCount * sizeof(int16_t));
}
}
}
// 2. Transmit 20ms audio frame or RFC 2833 DTMF event + ZRTP tick
int64_t now = nowMs();
periodicZrtpTick(ssrc, now);
if (now >= nextTxMs) {
nextTxMs += 20;
if (now - nextTxMs > 60) {
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) | (dtmfPt_ & 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);
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 += codecRtpTimestampStep20ms(codec_) * 3;
} else {
int16_t pcmIn[320] = {0};
if (capAvail >= frameBytes) {
std::memcpy(pcmIn, capRing, frameBytes);
capAvail -= frameBytes;
if (capAvail > 0) {
std::memmove(capRing, capRing + frameBytes, capAvail);
}
}
uint8_t pkt[12 + 768 + 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);
size_t encBytes = 0;
switch (codec_) {
case SipCodecId::Opus:
if (opusEnc) {
int r = opus_encode(opusEnc, pcmIn, static_cast<int>(frameSamples),
pkt + 12, 512);
if (r > 0) encBytes = static_cast<size_t>(r);
}
break;
case SipCodecId::G722:
encBytes = g722Enc.encodeFrame(pcmIn, frameSamples, pkt + 12);
break;
case SipCodecId::Pcmu:
for (size_t i = 0; i < frameSamples; ++i) {
pkt[12 + i] = linearToUlaw(pcmIn[i]);
}
encBytes = frameSamples;
break;
case SipCodecId::Pcma:
for (size_t i = 0; i < frameSamples; ++i) {
pkt[12 + i] = linearToAlaw(pcmIn[i]);
}
encBytes = frameSamples;
break;
case SipCodecId::Gsm:
if (gsmEnc) {
gsm_encode(gsmEnc, pcmIn, reinterpret_cast<gsm_byte*>(pkt + 12));
encBytes = 33;
}
break;
case SipCodecId::G726_32:
encBytes = g726Enc.encodeFrame(pcmIn, frameSamples, pkt + 12);
break;
case SipCodecId::Dvi4_8k:
case SipCodecId::Dvi4_16k:
encBytes = dvi4Enc.encodeFrame(pcmIn, frameSamples, pkt + 12);
break;
case SipCodecId::L16_8k:
case SipCodecId::L16_16k:
for (size_t i = 0; i < frameSamples; ++i) {
uint16_t u = static_cast<uint16_t>(pcmIn[i]);
pkt[12 + 2 * i] = static_cast<uint8_t>((u >> 8) & 0xff);
pkt[12 + 2 * i + 1] = static_cast<uint8_t>(u & 0xff);
}
encBytes = frameSamples * 2;
break;
}
if (encBytes > 0) {
size_t sendLen = protectRtpPacket(pkt, 12 + encBytes, curSeq, ssrc);
::sendto(sock_, pkt, sendLen, 0,
reinterpret_cast<const struct sockaddr*>(&remAddr_),
sizeof(remAddr_));
++txAudioFrames_;
}
ts += codecRtpTimestampStep20ms(codec_);
}
}
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 (opusEnc) opus_encoder_destroy(opusEnc);
if (opusDec) opus_decoder_destroy(opusDec);
if (gsmEnc) gsm_destroy(gsmEnc);
if (gsmDec) gsm_destroy(gsmDec);
if (capFd >= 0) ::close(capFd);
if (playFd >= 0) ::close(playFd);
capPid_.store(-1);
playPid_.store(-1);
if (capPid > 1) {
::kill(capPid, SIGKILL);
::waitpid(capPid, nullptr, 0);
}
if (playPid > 1) {
::kill(playPid, SIGKILL);
::waitpid(playPid, nullptr, 0);
}
}
int sock_ = -1;
struct sockaddr_in remAddr_ {};
std::string activeRemoteIp_;
int activeRemotePort_ = 0;
SipCodecId codec_ = SipCodecId::Pcmu;
int payloadType_ = 0;
int dtmfPt_ = 101;
std::map<int, SipCodecId> rxPtMap_;
std::atomic<bool> running_{false};
std::atomic<pid_t> capPid_{-1};
std::atomic<pid_t> playPid_{-1};
std::thread worker_;
std::mutex dtmfMtx_;
std::string dtmfQueue_;
// ZRTP & SRTP state
mutable std::mutex zrtpMtx_;
bool zrtpEnabled_ = true;
bool peerHasZrtpSdp_ = false;
int txAudioFrames_ = 0;
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 directPreferredCodec = "AUTO";
std::string activeSipCallId;
std::string activePeerUri;
std::string activeTargetHost;
int activeTargetPort = 5060;
std::vector<std::string> activeProxyIps;
std::string activeFromDisplay = "Bananarchy";
std::string activeFromUser = "anonymous";
std::string activeFromDomain = "bananarchy.local";
bool activeCallZrtp = true;
std::string activePreferredCodec = "AUTO";
std::string activeFromHeader;
std::string activeToHeader;
std::string activeViaHeader;
std::string activeContactUri;
std::string activeRemoteContactUri;
std::vector<std::string> activeRouteSet;
std::string activeRemoteTag;
std::string activeLocalTag;
std::string activeBranch;
std::string lastInvitePacket;
std::string lastAckPacket;
int64_t lastInviteTxMs = 0;
int inviteRetransmitCount = 0;
bool gotProvisionalResponse = false;
int activeCseq = 1;
struct sockaddr_in activePeerSin {};
std::string remoteRtpIp;
int remoteRtpPort = 0;
SipCodecId remoteCodec = SipCodecId::Pcmu;
int remotePayloadType = 0;
int remoteDtmfPt = 101;
std::map<int, SipCodecId> remotePtMap;
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 sockaddr_in sin {};
sin.sin_family = AF_INET;
sin.sin_port = htons(static_cast<uint16_t>(port > 0 ? port : 5060));
if (::inet_pton(AF_INET, host.c_str(), &sin.sin_addr) == 1) {
return ::sendto(sipUdpFd, payload.data(), payload.size(), 0,
reinterpret_cast<const struct sockaddr*>(&sin),
sizeof(sin)) >= 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 regHost = acct.domain;
int regPort = acct.port > 0 ? acct.port : 5060;
std::vector<std::string> regIps;
resolveSipSrvAndA(acct.domain, regPort, regHost, regPort, regIps);
std::string sendTarget = !regIps.empty() ? regIps.front() : regHost;
std::string localIp = detectLocalIpForHost(sendTarget);
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.2\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(sendTarget, regPort, req.str());
};
auto buildLocalSdp = [&](const std::string& localIp,
const std::string& zrtpHashHex,
const std::string& preferredCodec,
const SipCodecId* answerCodec = nullptr,
int answerPt = -1,
int dtmfPt = 101) -> std::string {
std::vector<std::pair<int, SipCodecId>> mediaCodecs;
if (answerCodec && answerPt >= 0) {
mediaCodecs.push_back({answerPt, *answerCodec});
}
for (SipCodecId c : orderedCodecsForPreference(preferredCodec)) {
if (answerCodec && c == *answerCodec) continue;
int pt = codecDefaultPt(c);
if (answerPt == pt || dtmfPt == pt) continue;
mediaCodecs.push_back({pt, c});
}
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";
for (const auto& mc : mediaCodecs) {
sdp << " " << mc.first;
}
sdp << " " << dtmfPt << "\r\n";
for (const auto& mc : mediaCodecs) {
sdp << codecRtpmapLine(mc.first, mc.second);
}
sdp << "a=rtpmap:" << dtmfPt << " telephone-event/8000\r\n"
<< "a=fmtp:" << dtmfPt << " 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;
std::vector<std::string> proxyIps;
if (!resolveSipTarget(targetRaw, acctPtr, targetUri, destHost, destPort, &proxyIps)) {
neoui_show_toast("Enter user@host or add account", 2200);
return false;
}
std::string primaryIp = !proxyIps.empty() ? proxyIps.front() : destHost;
std::string localIp = detectLocalIpForHost(primaryIp);
if (!auth) {
activeAccountIdx = acctPtr ? acctIdx : -1;
activePeerUri = targetUri;
activeTargetHost = primaryIp;
activeTargetPort = destPort;
activeProxyIps = proxyIps;
activeFromDisplay = acctPtr ? acctPtr->label : "Bananarchy";
activeFromUser = acctPtr ? acctPtr->username : "anonymous";
activeFromDomain = acctPtr ? acctPtr->domain : "bananarchy.local";
activeCallZrtp = acctPtr ? acctPtr->zrtpEnabled : directZrtpEnabled;
activePreferredCodec = acctPtr ? acctPtr->preferredCodec : directPreferredCodec;
activeSipCallId = randomHexToken(8) + "@" + localIp;
activeLocalTag = randomHexToken(6);
activeRemoteTag.clear();
activeRemoteContactUri.clear();
activeRouteSet.clear();
lastAckPacket.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, activePreferredCodec);
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.2\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;
lastInvitePacket = req.str();
lastInviteTxMs = nowMs();
inviteRetransmitCount = 0;
gotProvisionalResponse = false;
callState = SipCallState::Outgoing;
callStartedMs = nowMs();
sendUdpPacket(activeTargetHost, activeTargetPort, lastInvitePacket);
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;
activePreferredCodec = (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size()))
? accounts[activeAccountIdx].preferredCodec
: directPreferredCodec;
std::string zrtpHelloHash = rtpSession.prepareZrtp(activeCallZrtp);
std::string sdp = buildLocalSdp(localIp, zrtpHelloHash, activePreferredCodec,
&remoteCodec, remotePayloadType, remoteDtmfPt);
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, remoteCodec,
remotePayloadType, remoteDtmfPt, remotePtMap, activeCallZrtp,
!remoteZrtpHash.empty());
sendPluginCommand("callscreen",
"ACTIVE sip:1 " + activePeerUri + " SIP/" +
codecShortName(remoteCodec));
};
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::string reqUri = (method == "BYE" && !activeRemoteContactUri.empty())
? activeRemoteContactUri
: activePeerUri;
std::ostringstream req;
req << method << " " << reqUri << " SIP/2.0\r\n"
<< "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort
<< ";rport;branch=" << br << "\r\n"
<< "Max-Forwards: 70\r\n";
if (method == "BYE") {
for (const auto& rt : activeRouteSet) {
req << "Route: " << rt << "\r\n";
}
}
req << "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 (activePeerSin.sin_port != 0) {
sendUdpPacket("", 5060, req.str(), &activePeerSin);
} else if (!activeTargetHost.empty()) {
sendUdpPacket(activeTargetHost, activeTargetPort, req.str());
}
appendSipHistory("OUT", activePeerUri, acctLbl, durSec);
}
lastInvitePacket.clear();
lastAckPacket.clear();
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) {
gotProvisionalResponse = true;
activePeerSin = fromSin;
size_t tagPos = toHdr.find(";tag=");
if (tagPos != std::string::npos) {
activeRemoteTag = trimStr(toHdr.substr(tagPos + 5));
}
std::string contactHdr = getSipHeaderValue(msg, "Contact", "m");
if (!contactHdr.empty()) {
std::string curi = extractSipUriFromHeader(contactHdr);
if (!curi.empty()) activeRemoteContactUri = curi;
}
std::vector<std::string> rrs = getSipHeaderValues(msg, "Record-Route");
if (!rrs.empty()) {
std::reverse(rrs.begin(), rrs.end());
activeRouteSet = std::move(rrs);
}
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 == 180 || statusCode == 183) &&
callState == SipCallState::Outgoing) {
if (msg.find("\r\n\r\n") != std::string::npos) {
parseSdpMedia(msg, activePreferredCodec, remoteRtpIp, remoteRtpPort,
remoteCodec, remotePayloadType, remoteDtmfPt,
remotePtMap, remoteZrtpHash);
if (!remoteRtpIp.empty() && remoteRtpPort > 0) {
rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort,
remoteCodec, remotePayloadType, remoteDtmfPt,
remotePtMap, activeCallZrtp,
!remoteZrtpHash.empty());
}
}
} else if (statusCode == 200 &&
(callState == SipCallState::Outgoing ||
callState == SipCallState::Active)) {
if (callState == SipCallState::Active && !lastAckPacket.empty()) {
sendUdpPacket("", 5060, lastAckPacket, &fromSin);
return;
}
parseSdpMedia(msg, activePreferredCodec, remoteRtpIp, remoteRtpPort,
remoteCodec, remotePayloadType, remoteDtmfPt,
remotePtMap, remoteZrtpHash);
std::string localIp = detectLocalIpForHost(activeTargetHost);
std::string ackUri = !activeRemoteContactUri.empty()
? activeRemoteContactUri
: activePeerUri;
std::ostringstream ack;
ack << "ACK " << ackUri << " SIP/2.0\r\n"
<< "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort
<< ";rport;branch=z9hG4bK" << randomHexToken(6) << "\r\n"
<< "Max-Forwards: 70\r\n";
for (const auto& rt : activeRouteSet) {
ack << "Route: " << rt << "\r\n";
}
ack << "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";
lastAckPacket = ack.str();
sendUdpPacket("", 5060, lastAckPacket, &fromSin);
callState = SipCallState::Active;
callStartedMs = nowMs();
rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort,
remoteCodec, remotePayloadType, remoteDtmfPt,
remotePtMap, activeCallZrtp,
!remoteZrtpHash.empty());
sendPluginCommand("callscreen",
"ACTIVE sip:1 " + activePeerUri + " SIP/" +
codecShortName(remoteCodec));
} 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);
std::string prefCodec = (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size()))
? accounts[activeAccountIdx].preferredCodec
: directPreferredCodec;
parseSdpMedia(msg, prefCodec, remoteRtpIp, remoteRtpPort, remoteCodec,
remotePayloadType, remoteDtmfPt, remotePtMap,
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");
std::string tagStr = std::string("SIP/") + codecShortName(remoteCodec);
if (!sendPluginCommand("callscreen", "INCOMING sip:1 " + caller + " " + tagStr)) {
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 (9 fields):
// 0=Label, 1=Username, 2=Password, 3=Domain, 4=Port, 5=Transport, 6=Codec, 7=ZRTP, 8=Enabled
constexpr int kNumEditFields = 9;
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) {
if (rtpSession.isZrtpSecure()) {
regBadge = std::string(rtpSession.activeCodecName()) + ":" +
rtpSession.getZrtpSas();
} else {
regBadge = rtpSession.activeCodecName();
}
} 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 + Codec + ZRTP indicator
std::string acctLine;
if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
const auto& a = accounts[activeAccountIdx];
acctLine = "Acct: " + a.label + " [" + a.preferredCodec +
(a.zrtpEnabled ? " ZRTP]" : "]");
} else {
acctLine = "Mode: Direct [" + directPreferredCodec +
(directZrtpEnabled ? " ZRTP]" : " RTP]");
}
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.preferredCodec + (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", "Codec", "ZRTP", "Active"
};
std::string vals[kNumEditFields] = {
editAcctDraft.label,
editAcctDraft.username,
editAcctDraft.password.empty() ? "" : "******",
editAcctDraft.domain,
std::to_string(editAcctDraft.port),
editAcctDraft.transport,
normalizePreferredCodec(editAcctDraft.preferredCodec),
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|Cycle Direct Codec|Toggle Direct ZRTP|Register All Now|Delete Selected|Clear History",
nullptr, menuSel, 7);
}
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 == "HANGUP" || cmd.rfind("HANGUP ", 0) == 0) {
hangupActiveSipCall(true);
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("CODEC ", 0) == 0 && cmd.size() > 6) {
std::string cName = normalizePreferredCodec(cmd.substr(6));
if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
accounts[activeAccountIdx].preferredCodec = cName;
saveSipAccounts(accounts);
} else {
directPreferredCodec = cName;
}
if (visible) render();
} 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/" +
rtpSession.activeCodecName() + ":" + sas);
sendPluginCommand("callscreen",
"NOTICE ZRTP Encrypted (" +
std::string(rtpSession.activeCodecName()) +
" SAS: " + sas + ")");
if (visible) {
neoui_show_toast(("ZRTP Secure SAS: " + sas).c_str(), 3000);
render();
}
}
}
// 2c. RFC 3261 Timer A INVITE retransmission + multi-proxy SRV/A failover
int64_t now = nowMs();
if (callState == SipCallState::Outgoing && !gotProvisionalResponse &&
!lastInvitePacket.empty() && now - lastInviteTxMs >= 500) {
if (inviteRetransmitCount < 8) {
++inviteRetransmitCount;
lastInviteTxMs = now;
if (!activeProxyIps.empty()) {
activeTargetHost = activeProxyIps[
static_cast<size_t>(inviteRetransmitCount) % activeProxyIps.size()];
}
sendUdpPacket(activeTargetHost, activeTargetPort, lastInvitePacket);
} else if (now - callStartedMs >= 10000) {
hangupActiveSipCall(true);
}
}
// 3. Periodic REGISTER keepalive for enabled accounts
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 + 6) % 7;
else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 7;
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) {
if (activeAccountIdx >= 0 &&
activeAccountIdx < static_cast<int>(accounts.size())) {
accounts[activeAccountIdx].preferredCodec =
cyclePreferredCodec(accounts[activeAccountIdx].preferredCodec);
saveSipAccounts(accounts);
neoui_show_toast(("Codec: " + accounts[activeAccountIdx].preferredCodec).c_str(), 1500);
} else {
directPreferredCodec = cyclePreferredCodec(directPreferredCodec);
neoui_show_toast(("Direct Codec: " + directPreferredCodec).c_str(), 1500);
}
} else if (menuSel == 3) {
directZrtpEnabled = !directZrtpEnabled;
neoui_show_toast(directZrtpEnabled ? "Direct ZRTP: ON" : "Direct ZRTP: OFF", 1500);
} else if (menuSel == 4) {
for (auto& a : accounts) {
if (a.enabled) sendSipRegister(a);
}
neoui_show_toast("REGISTER sent", 1500);
} else if (menuSel == 5 && 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 == 6) {
::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.preferredCodec = cyclePreferredCodec(editAcctDraft.preferredCodec);
} else if (editFieldIdx == 7) {
editAcctDraft.zrtpEnabled = !editAcctDraft.zrtpEnabled;
} else if (editFieldIdx == 8) {
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 || callState == SipCallState::Outgoing) {
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
};