diff --git a/CHANGELOG.md b/CHANGELOG.md index cca880d..bf99fca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Release versions follow the `
` format (where `2026` is `a`, ### New features and improvements - **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xkopher`)**: - - **SIP VoIP client (`sip.so` / `xsip`)**: implemented an RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History` tabs) with Digest MD5 authentication, background standby `REGISTER` keepalive, incoming `INVITE` standby wakeup and call handling integrated with `xcallscreen` (`[SIP]`), bidirectional G.711 (`PCMU`/`PCMA` 8 kHz) RTP audio streaming, and RFC 2833 DTMF tones. + - **SIP VoIP client (`sip.so` / `xsip`)**: implemented an RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History` tabs) supporting both account-registered calling (with alphanumeric username/password multi-tap entry, Digest MD5 authentication, and background standby `REGISTER` keepalive) and direct accountless P2P SIP URI calling (`user@host[:port]` or `sip:user@host[:port]`), RFC 6189 **ZRTP** media-path key agreement (`DH3k` 3072-bit / `DH2k` 2048-bit Diffie-Hellman, `H0..H3` SHA-256 hash chain, Castagnoli CRC-32C framing, `a=zrtp-hash` SDP signaling, and 4-character Base32 `SAS` verification code) with RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`/`32`) encrypted voice media, incoming `INVITE` standby wakeup and call handling integrated with `xcallscreen` (`[SIP]` / `[ZRTP:]`), bidirectional G.711 (`PCMU`/`PCMA` 8 kHz) RTP/SRTP audio streaming, and RFC 2833 DTMF tones. - **Email client (`email.so` / `xemail` / `xmail`)**: implemented a multi-account `IMAP4rev1`, `POP3`, and `SMTP` client (`Inbox`, `Compose`, `Accounts` tabs) supporting implicit TLS (`993`/`995`/`465`), `STARTTLS` (`143`/`110`/`587`), and plain TCP, SASL `PLAIN`/`LOGIN` authentication, RFC 2047 encoded-word header decoding, Base64/Quoted-Printable MIME body decoding, HTML tag stripping, offline inbox cache (`~/.local/share/sxmo/email/`), full-screen reader, and message composer/reply. - **IRCv3 client (`irc.so` / `xirc`)**: implemented a multi-server IRC client (`Buffers`, `Chat`, `Servers` tabs) with OpenSSL TLS, IRCv3 capability negotiation (`CAP LS 302`: `sasl`, `server-time`, `message-tags`, `multi-prefix`, `away-notify`, `account-notify`, `chghost`, `cap-notify`), `SASL PLAIN` authentication, slash commands (`/join`, `/part`, `/msg`, `/nick`, `/me`, `/topic`, `/raw`, `/quit`), and a resident background mode (`BG_STAY`) that keeps sockets connected when the window is closed and vibrates on nick highlights or private messages. - **Tox / Trifa P2P messenger and audio call client (`tox.so` / `xtox`)**: built an encrypted P2P messenger and voice call client (`Friends`, `Chat`, `My Tox ID` tabs) on `c-toxcore` (`libtoxcore.so.2`), featuring persistent profile storage (`~/.local/share/sxmo/tox/profile.tox`), non-blocking IPv4 DHT + TCP relay bootstrap, friend request handling, persistent chat logs, and standby incoming `ToxAV` 48 kHz Opus voice calls integrated with `xcallscreen` (`[TOX]`). diff --git a/MANUAL.md b/MANUAL.md index deccb34..56de517 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -230,10 +230,10 @@ All twenty-three phone applications are compiled as shared-object plugins (`/usr 16. **SIP VoIP client (`sip.so` / `xsip`)**: - **Open**: select **SIP VoIP** from the System or Applications menu, or run `xsip`. - **Three tabs (`1:Dialer`, `2:Accounts`, `3:History` — switch with `Left`/`Right`)**: - - **`1:Dialer`**: enter a SIP URI (`user@domain`) or extension (`1001`) using multi-tap input (`*` cycles input mode) or select a recent peer with `Up`/`Down`, and press **Call (green)** or **Center `OK`** to place an outgoing SIP call. - - **`2:Accounts`**: add or edit SIP accounts (`~/.config/sxmo/sip_accounts.tsv`: Label, Username, Password, Domain, Port, UDP/TCP/TLS transport, Enabled). Enabled accounts maintain RFC 3261 `REGISTER` keepalives with Digest MD5 authentication in the background even when `xsip` is closed. + - **`1:Dialer`**: enter a SIP URI (`user@host[:port]` or `sip:user@host[:port]`) or account extension (`1001`) using multi-tap alphanumeric input (`*` or `#` cycles `[abc]` / `[ABC]` / `[123]` / `[Sym]` / `[Abc]`) or select a recent peer with `Up`/`Down`, and press **Call (green)** or **Center `OK`** to place an outgoing SIP call. Outbound calls work both with a registered SIP account and directly without any configured account (`Direct URI` mode, selectable via `Menu -> Switch Account` when accounts are also present). + - **`2:Accounts`**: add or edit SIP accounts (`~/.config/sxmo/sip_accounts.tsv`: Label, alphanumeric Username, Password, Domain, Port, UDP/TCP/TLS transport, ZRTP toggle, Enabled). Enabled accounts maintain RFC 3261 `REGISTER` keepalives with Digest MD5 authentication in the background even when `xsip` is closed. - **`3:History`**: browse incoming, outgoing, and missed SIP calls (`~/.local/share/sxmo/sip_history.tsv`) and press **Call (green)** or **Center `OK`** to redial. - - **CallScreen (`xcallscreen`) and RTP audio integration**: incoming `INVITE` requests wake the phone, trigger the ringtone/vibrator, and open `xcallscreen` with a `[SIP]` badge; answering streams bidirectional 8 kHz G.711 (`PCMU`/`PCMA`) RTP audio and RFC 2833 DTMF tones. + - **ZRTP / SRTP encryption and CallScreen (`xcallscreen`) integration**: supports RFC 6189 **ZRTP** (`DH3k` 3072-bit / `DH2k` 2048-bit Diffie-Hellman key agreement with `a=zrtp-hash` SDP signaling and persistent 96-bit `ZID`) and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`/`32`) encrypted voice media (`ON` by default per account and for direct accountless calls via `Menu -> Toggle Direct ZRTP`). Incoming `INVITE` requests wake the phone, trigger the ringtone/vibrator, and open `xcallscreen` with a `[SIP]` badge; once ZRTP completes its handshake, the 4-character Short Authentication String (`SAS`) is displayed in both `xsip` (`ZRTP SECURE | SAS: `) and `xcallscreen` (`[ZRTP:]`) while streaming bidirectional 8 kHz G.711 (`PCMU`/`PCMA`) RTP/SRTP audio and RFC 2833 DTMF tones. 17. **Email client (`email.so` / `xemail` / `xmail`)**: - **Open**: select **Email** from the System or Applications menu, or run `xemail` / `xmail`. diff --git a/README.md b/README.md index 7c7102a..20ee8d7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs - **Networks and Bluetooth manager (`xnetworks`) with OBEX file transfer (`bananarchy-bt-obex`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing, with built-in Bluetooth OBEX Object Push file reception (`~/Downloads` status and receiver toggle in the `Bluetooth` tab) and **Send via Bluetooth** in `xfiles`. - **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), Bluetooth file sharing, music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, **Send via Bluetooth** OBEX file push to paired/discovered devices, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), image viewer, and dedicated monophonic ringtone viewer (`RingtoneView` for Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` with graphical piano-roll pitch contour, note sequence viewer, live audio preview, and one-key assignment as call ringtone or notification/SMS sound — plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio, tracker, or monophonic melody file as call ringtone or notification/SMS sound), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, `NRT`, `RTTTL`, `RTX`, `EMY`, `IMY`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. - **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xkopher`)**: - - **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) with Digest MD5 authentication, standby `REGISTER` keepalive, incoming `INVITE` ringing and call handling integrated with `xcallscreen`, bidirectional G.711 (`PCMU`/`PCMA` 8 kHz) RTP audio, and RFC 2833 DTMF. + - **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) supporting both account-registered calling (with Digest MD5 authentication and standby `REGISTER` keepalive) and direct accountless P2P SIP URI calling (`user@host[:port]` or `sip:user@host[:port]`), RFC 6189 **ZRTP** media-path Diffie-Hellman (`DH3k`/`DH2k`) key agreement and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`) voice encryption with a 4-character `SAS` verification code, incoming `INVITE` ringing and call handling integrated with `xcallscreen` (`[SIP]` / `[ZRTP:]`), bidirectional G.711 (`PCMU`/`PCMA` 8 kHz) RTP/SRTP audio, and RFC 2833 DTMF. - **Email client (`xemail` / `xmail` / `email.so`)**: multi-account `IMAP4rev1`, `POP3`, and `SMTP` client (`Inbox`, `Compose`, `Accounts`) supporting implicit TLS, `STARTTLS`, and plain TCP, SASL `PLAIN`/`LOGIN`, MIME RFC 2047/Base64/Quoted-Printable decoding, offline inbox cache, full-screen message reader, and composer. - **IRCv3 client (`xirc` / `irc.so`)**: multi-server IRC client (`Buffers`, `Chat`, `Servers`) with OpenSSL TLS, IRCv3 capability negotiation (`CAP LS 302`: `sasl`, `server-time`, `message-tags`, `multi-prefix`, `away-notify`, `account-notify`, `chghost`, `cap-notify`), `SASL PLAIN` authentication, slash commands, and resident background mode with highlight vibration alerts. - **Tox / Trifa P2P messenger and audio call client (`xtox` / `tox.so`)**: encrypted P2P messenger (`Friends`, `Chat`, `My Tox ID`) built on `c-toxcore` (`libtoxcore.so.2`) with DHT + TCP relay bootstrap, friend requests, persistent message history, and `ToxAV` 48 kHz Opus voice calls integrated with `xcallscreen`. diff --git a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so index a4120ca..0d22876 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so and b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/email.so b/overlay/rootfs/usr/lib/dwm/plugins/email.so index 81b03e4..996f56a 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/email.so and b/overlay/rootfs/usr/lib/dwm/plugins/email.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/irc.so b/overlay/rootfs/usr/lib/dwm/plugins/irc.so index 5593165..0f1c531 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/irc.so and b/overlay/rootfs/usr/lib/dwm/plugins/irc.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/sip.so b/overlay/rootfs/usr/lib/dwm/plugins/sip.so index 7ddb54b..76e3137 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/sip.so and b/overlay/rootfs/usr/lib/dwm/plugins/sip.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so index a4120ca..0d22876 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so index 81b03e4..996f56a 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/email.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so index 5593165..0f1c531 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so index 7ddb54b..76e3137 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so differ diff --git a/src/dwm-plugins/callscreen_plugin.cpp b/src/dwm-plugins/callscreen_plugin.cpp index 674c58e..9e475cb 100644 --- a/src/dwm-plugins/callscreen_plugin.cpp +++ b/src/dwm-plugins/callscreen_plugin.cpp @@ -437,6 +437,7 @@ int callscreen_run_main(int argc, char** argv) { std::string callNumber; std::string contactName; int activeSimSlot = 0; + std::string sipZrtpSas; DualSimInfo simInfo = queryDualSimInfo(); std::string endReason = "CALL ENDED"; std::string statusNotice; @@ -769,7 +770,7 @@ int callscreen_run_main(int argc, char** argv) { std::string simTag; if (activeSimSlot == 3 || callId.rfind("sip:", 0) == 0) { - simTag = " [SIP]"; + simTag = sipZrtpSas.empty() ? " [SIP]" : (" [ZRTP:" + sipZrtpSas + "]"); } else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) { simTag = " [TOX]"; } else if (activeSimSlot == 1 || activeSimSlot == 2) { @@ -1676,8 +1677,15 @@ int callscreen_run_main(int argc, char** argv) { render(); return; } + if (line.rfind("NOTICE ", 0) == 0) { + statusNotice = trimStr(line.substr(7)); + statusNoticeUntilMs = nowMs() + 12000; + render(); + return; + } if (line == "ENDED" || line.rfind("ENDED ", 0) == 0) { std::string reason = (line.size() > 6) ? trimStr(line.substr(6)) : "CALL ENDED"; + sipZrtpSas.clear(); if (callState != CallState::Idle) { transitionToEnded(reason); } else { @@ -1717,10 +1725,17 @@ int callscreen_run_main(int argc, char** argv) { } auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) { - if (tagStr == "SIP" || cidStr.rfind("sip:", 0) == 0) { + if (tagStr == "SIP" || tagStr.rfind("SIP:", 0) == 0 || + cidStr.rfind("sip:", 0) == 0) { activeSimSlot = 3; + if (tagStr.rfind("SIP:", 0) == 0 && tagStr.size() > 4) { + sipZrtpSas = tagStr.substr(4); + } else if (tagStr == "SIP") { + sipZrtpSas.clear(); + } return; } + sipZrtpSas.clear(); if (tagStr == "TOX" || cidStr.rfind("tox:", 0) == 0) { activeSimSlot = 4; return; diff --git a/src/dwm-plugins/email_plugin.cpp b/src/dwm-plugins/email_plugin.cpp index e09fe26..8ac479d 100644 --- a/src/dwm-plugins/email_plugin.cpp +++ b/src/dwm-plugins/email_plugin.cpp @@ -591,23 +591,42 @@ int email_run_main(int argc, char** argv) { auto syncInputBuffer = [&]() { if (editModalOpen) { - if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str()); - else if (editFieldIdx == 1) neoui_input_reset(editDraft.address.c_str()); - else if (editFieldIdx == 2) neoui_input_reset(editDraft.username.c_str()); - else if (editFieldIdx == 3) neoui_input_reset(editDraft.password.c_str()); - else if (editFieldIdx == 5) neoui_input_reset(editDraft.inHost.c_str()); - else if (editFieldIdx == 6) { + if (editFieldIdx == 0) { + neoui_input_set_mode(NEO_INPUT_ABC_TITLE); + neoui_input_reset(editDraft.label.c_str()); + } else if (editFieldIdx == 1) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.address.c_str()); + } else if (editFieldIdx == 2) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.username.c_str()); + } else if (editFieldIdx == 3) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.password.c_str()); + } else if (editFieldIdx == 5) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.inHost.c_str()); + } else if (editFieldIdx == 6) { neoui_input_set_mode(NEO_INPUT_123); neoui_input_reset(std::to_string(editDraft.inPort).c_str()); - } else if (editFieldIdx == 8) neoui_input_reset(editDraft.smtpHost.c_str()); - else if (editFieldIdx == 9) { + } else if (editFieldIdx == 8) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.smtpHost.c_str()); + } else if (editFieldIdx == 9) { neoui_input_set_mode(NEO_INPUT_123); neoui_input_reset(std::to_string(editDraft.smtpPort).c_str()); } } else if (activeTab == 1) { - if (composeField == 0) neoui_input_reset(composeTo.c_str()); - else if (composeField == 1) neoui_input_reset(composeSubject.c_str()); - else neoui_input_reset(composeBody.c_str()); + if (composeField == 0) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(composeTo.c_str()); + } else if (composeField == 1) { + neoui_input_set_mode(NEO_INPUT_ABC_TITLE); + neoui_input_reset(composeSubject.c_str()); + } else { + neoui_input_set_mode(NEO_INPUT_ABC_TITLE); + neoui_input_reset(composeBody.c_str()); + } } }; @@ -937,14 +956,30 @@ int email_run_main(int argc, char** argv) { else if (editDraft.smtpSecurity == "STARTTLS") editDraft.smtpSecurity = "PLAIN"; else editDraft.smtpSecurity = "TLS"; } - } else if (k == NEO_KEY_STAR) { + } else if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) { neoui_input_cycle_mode(); + } else if (k == NEO_KEY_RIGHT && neoui_input_is_tap_active()) { + neoui_input_commit_tap(); + applyInputBuffer(); } else if (k == NEO_KEY_BACK) { neoui_input_backspace(); applyInputBuffer(); } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { neoui_input_feed_key(k); applyInputBuffer(); + } else { + int ks = neoui_event_keysym(); + if (ks >= 0x20 && ks <= 0x7e && + editFieldIdx != 4 && editFieldIdx != 7 && editFieldIdx != 10) { + neoui_input_commit_tap(); + if ((editFieldIdx != 6 && editFieldIdx != 9) || + (ks >= '0' && ks <= '9')) { + std::string cur = neoui_input_get_text(); + cur.push_back(static_cast(ks)); + neoui_input_set_text(cur.c_str()); + applyInputBuffer(); + } + } } render(); } else if (readingMsg) { diff --git a/src/dwm-plugins/irc_plugin.cpp b/src/dwm-plugins/irc_plugin.cpp index 9e33e96..f547acf 100644 --- a/src/dwm-plugins/irc_plugin.cpp +++ b/src/dwm-plugins/irc_plugin.cpp @@ -560,18 +560,32 @@ int irc_run_main(int argc, char** argv) { auto syncEditInput = [&]() { if (!editModalOpen) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); neoui_input_reset(chatInput.c_str()); return; } - if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str()); - else if (editFieldIdx == 1) neoui_input_reset(editDraft.host.c_str()); - else if (editFieldIdx == 2) { + if (editFieldIdx == 0) { + neoui_input_set_mode(NEO_INPUT_ABC_TITLE); + neoui_input_reset(editDraft.label.c_str()); + } else if (editFieldIdx == 1) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.host.c_str()); + } else if (editFieldIdx == 2) { neoui_input_set_mode(NEO_INPUT_123); neoui_input_reset(std::to_string(editDraft.port).c_str()); - } else if (editFieldIdx == 4) neoui_input_reset(editDraft.nick.c_str()); - else if (editFieldIdx == 5) neoui_input_reset(editDraft.saslUser.c_str()); - else if (editFieldIdx == 6) neoui_input_reset(editDraft.saslPass.c_str()); - else if (editFieldIdx == 7) neoui_input_reset(editDraft.autoJoin.c_str()); + } else if (editFieldIdx == 4) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.nick.c_str()); + } else if (editFieldIdx == 5) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.saslUser.c_str()); + } else if (editFieldIdx == 6) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.saslPass.c_str()); + } else if (editFieldIdx == 7) { + neoui_input_set_mode(NEO_INPUT_ABC_LOWER); + neoui_input_reset(editDraft.autoJoin.c_str()); + } }; auto applyEditInput = [&]() { @@ -895,14 +909,28 @@ int irc_run_main(int argc, char** argv) { } else if (editFieldIdx == 8) { editDraft.keepInBackground = !editDraft.keepInBackground; } - } else if (k == NEO_KEY_STAR) { + } else if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) { neoui_input_cycle_mode(); + } else if (k == NEO_KEY_RIGHT && neoui_input_is_tap_active()) { + neoui_input_commit_tap(); + applyEditInput(); } else if (k == NEO_KEY_BACK) { neoui_input_backspace(); applyEditInput(); } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { neoui_input_feed_key(k); applyEditInput(); + } else { + int ks = neoui_event_keysym(); + if (ks >= 0x20 && ks <= 0x7e && editFieldIdx != 3 && editFieldIdx != 8) { + neoui_input_commit_tap(); + if (editFieldIdx != 2 || (ks >= '0' && ks <= '9')) { + std::string cur = neoui_input_get_text(); + cur.push_back(static_cast(ks)); + neoui_input_set_text(cur.c_str()); + applyEditInput(); + } + } } render(); } else { diff --git a/src/dwm-plugins/sip_plugin.cpp b/src/dwm-plugins/sip_plugin.cpp index 28fcc38..53fa2de 100644 --- a/src/dwm-plugins/sip_plugin.cpp +++ b/src/dwm-plugins/sip_plugin.cpp @@ -2,14 +2,23 @@ // SIP VoIP DWM Plugin (sip.so / xsip) for Bananarchy (240x320) // Features: // - Preloaded standby SIP User Agent daemon with background REGISTER keepalive +// - Direct peer-to-peer / URI outbound calling without a SIP account // - Digest MD5 authentication (RFC 2617 / RFC 3261) for REGISTER and INVITE // - Incoming call standby wakeup and full CallScreen (callscreen.so) integration // - Bidirectional G.711 (PCMU/PCMA 8 kHz) RTP audio + RFC 2833 DTMF +// - RFC 6189 ZRTP media key agreement (DH3k/DH2k + B32 SAS) + RFC 3711 SRTP // - NeoUI 3-tab interface: Dialer, Accounts, and Call History #include "../sxmo-dwm/dwm_plugin.h" #include "net_tls.h" +#include +#include +#include +#include +#include +#include + #include #include #include @@ -81,6 +90,220 @@ int16_t alawToLinear(uint8_t aval) { return static_cast((aval & 0x80) ? t : -t); } +// --------------------------------------------------------------------------- +// RFC 6189 ZRTP & RFC 3711 SRTP Cryptographic Helpers +// --------------------------------------------------------------------------- + +// RFC 3526 Group 15 (3072-bit MODP Group for ZRTP "DH3k") +constexpr const char* kDh3kPrimeHex = + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; + +// RFC 3526 Group 14 (2048-bit MODP Group for ZRTP "DH2k") +constexpr const char* kDh2kPrimeHex = + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; + +// Castagnoli CRC-32C (polynomial 0x1EDC6F41, reversed 0x82F63B78) per RFC 6189 Section 5 +uint32_t zrtpCrc32c(const uint8_t* data, size_t len) { + uint32_t crc = 0xFFFFFFFFu; + for (size_t i = 0; i < len; ++i) { + crc ^= data[i]; + for (int b = 0; b < 8; ++b) { + if (crc & 1u) { + crc = (crc >> 1) ^ 0x82F63B78u; + } else { + crc >>= 1; + } + } + } + return ~crc; +} + +void sha256Bytes(const uint8_t* data, size_t len, uint8_t out[32]) { + SHA256(data, len, out); +} + +std::string bytesToHexLower(const uint8_t* data, size_t len) { + static const char kHex[] = "0123456789abcdef"; + std::string s; + s.reserve(len * 2); + for (size_t i = 0; i < len; ++i) { + s.push_back(kHex[(data[i] >> 4) & 0x0f]); + s.push_back(kHex[data[i] & 0x0f]); + } + return s; +} + +void hmacSha256(const uint8_t* key, size_t keyLen, + const uint8_t* data, size_t dataLen, + uint8_t out[32]) { + unsigned int outLen = 32; + HMAC(EVP_sha256(), key, static_cast(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(keyLen), data, dataLen, out, &outLen); +} + +// RFC 6189 Section 4.5.1 KDF(KI, Label, Context, L) +std::vector zrtpKdf(const uint8_t ki[32], const std::string& label, + const std::vector& context, + uint32_t numBits) { + std::vector 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((numBits >> 24) & 0xff)); + input.push_back(static_cast((numBits >> 16) & 0xff)); + input.push_back(static_cast((numBits >> 8) & 0xff)); + input.push_back(static_cast(numBits & 0xff)); + + uint8_t digest[32]; + hmacSha256(ki, 32, input.data(), input.size(), digest); + size_t outBytes = (numBits + 7) / 8; + return std::vector(digest, digest + std::min(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 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(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 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(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((ssrc >> 24) & 0xff); + ivOut[5] ^= static_cast((ssrc >> 16) & 0xff); + ivOut[6] ^= static_cast((ssrc >> 8) & 0xff); + ivOut[7] ^= static_cast(ssrc & 0xff); + ivOut[8] ^= static_cast((pktIndex >> 40) & 0xff); + ivOut[9] ^= static_cast((pktIndex >> 32) & 0xff); + ivOut[10] ^= static_cast((pktIndex >> 24) & 0xff); + ivOut[11] ^= static_cast((pktIndex >> 16) & 0xff); + ivOut[12] ^= static_cast((pktIndex >> 8) & 0xff); + ivOut[13] ^= static_cast(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(zidOut), 12); + if (in.gcount() == 12) return; + } + if (RAND_bytes(zidOut, 12) != 1) { + for (int i = 0; i < 12; ++i) { + zidOut[i] = static_cast((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(zidOut), 12); + } +} + struct SipAccount { bool enabled = true; std::string label = "SIP Account"; @@ -90,6 +313,7 @@ struct SipAccount { std::string domain; int port = 5060; std::string transport = "UDP"; // UDP, TCP, TLS + bool zrtpEnabled = true; // Runtime state std::string regStatus = "OFF"; @@ -153,6 +377,10 @@ std::vector loadSipAccounts() { if (cols.size() >= 8 && !cols[7].empty()) { a.transport = cols[7]; } + if (cols.size() >= 9 && !cols[8].empty()) { + a.zrtpEnabled = (cols[8] != "0" && toLowerStr(cols[8]) != "false" && + toLowerStr(cols[8]) != "off"); + } a.regStatus = a.enabled ? "IDLE" : "OFF"; a.callId = randomHexToken(8) + "@" + a.domain; a.fromTag = randomHexToken(6); @@ -175,7 +403,8 @@ void saveSipAccounts(const std::vector& list) { << a.password << "\t" << a.domain << "\t" << a.port << "\t" - << a.transport << "\n"; + << a.transport << "\t" + << (a.zrtpEnabled ? "1" : "0") << "\n"; } } @@ -223,11 +452,12 @@ void appendSipHistory(const std::string& dir, const std::string& peer, } std::string detectLocalIpForHost(const std::string& remoteHost) { + std::string target = remoteHost.empty() ? "8.8.8.8" : remoteHost; struct addrinfo hints {}; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; struct addrinfo* res = nullptr; - if (::getaddrinfo(remoteHost.c_str(), "5060", &hints, &res) == 0 && res) { + if (::getaddrinfo(target.c_str(), "5060", &hints, &res) == 0 && res) { int s = ::socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (s >= 0) { if (::connect(s, res->ai_addr, res->ai_addrlen) == 0) { @@ -249,6 +479,75 @@ std::string detectLocalIpForHost(const std::string& remoteHost) { return "127.0.0.1"; } +// Parse a dial string ("user@host:port", "sip:user@host", "192.168.1.50:5060", "1001") +bool resolveSipTarget(const std::string& rawInput, + const SipAccount* acct, + std::string& outTargetUri, + std::string& outHost, + int& outPort) { + std::string s = trimStr(rawInput); + if (s.empty()) return false; + if (s.front() == '<' && s.back() == '>' && s.size() > 2) { + s = trimStr(s.substr(1, s.size() - 2)); + } + if (toLowerStr(s).rfind("sip:", 0) == 0) { + s = s.substr(4); + } else if (toLowerStr(s).rfind("sips:", 0) == 0) { + s = s.substr(5); + } + // Strip any URI parameters (;transport=...) + size_t semi = s.find(';'); + if (semi != std::string::npos) { + s = s.substr(0, semi); + } + if (s.empty()) return false; + + std::string userPart; + std::string hostPortPart; + size_t atPos = s.find('@'); + if (atPos != std::string::npos) { + userPart = s.substr(0, atPos); + hostPortPart = s.substr(atPos + 1); + } else if (acct && !acct->domain.empty()) { + userPart = s; + hostPortPart = acct->domain; + outHost = acct->domain; + outPort = acct->port > 0 ? acct->port : 5060; + outTargetUri = "sip:" + userPart + "@" + acct->domain; + return true; + } else { + // Direct host/IP without user part (e.g. "192.168.1.10" or "192.168.1.10:5060") + if (s.find('.') == std::string::npos && s.find(':') == std::string::npos && + toLowerStr(s) != "localhost") { + return false; + } + userPart = "user"; + hostPortPart = s; + } + + outPort = (acct && acct->port > 0 && acct->domain == hostPortPart) ? acct->port : 5060; + outHost = hostPortPart; + size_t colonPos = hostPortPart.rfind(':'); + if (colonPos != std::string::npos) { + outHost = hostPortPart.substr(0, colonPos); + int p = std::atoi(hostPortPart.substr(colonPos + 1).c_str()); + if (p > 0 && p <= 65535) { + outPort = p; + } + } + if (outHost.empty()) return false; + if (userPart.empty()) userPart = "user"; + + if (acct && !acct->domain.empty() && acct->enabled && + toLowerStr(outHost) == toLowerStr(acct->domain)) { + outTargetUri = "sip:" + userPart + "@" + outHost; + outPort = acct->port > 0 ? acct->port : outPort; + } else { + outTargetUri = "sip:" + userPart + "@" + hostPortPart; + } + return true; +} + DigestChallenge parseDigestChallenge(const std::string& sipMsg) { DigestChallenge ch; std::istringstream iss(sipMsg); @@ -348,7 +647,8 @@ std::string getSipHeaderValue(const std::string& msg, const std::string& hdrName } void parseSdpMedia(const std::string& msg, std::string& outIp, int& outPort, - int& outPayloadType) { + int& outPayloadType, std::string& outPeerZrtpHash) { + outPeerZrtpHash.clear(); size_t bodyPos = msg.find("\r\n\r\n"); if (bodyPos == std::string::npos) return; std::istringstream iss(msg.substr(bodyPos + 4)); @@ -368,16 +668,44 @@ void parseSdpMedia(const std::string& msg, std::string& outIp, int& outPort, break; } } + } else if (line.rfind("a=zrtp-hash:", 0) == 0) { + std::istringstream zss(line.substr(12)); + std::string ver, hashHex; + zss >> ver >> hashHex; + if (!hashHex.empty()) { + outPeerZrtpHash = hashHex; + } } } } +// --------------------------------------------------------------------------- +// RTP + RFC 6189 ZRTP + RFC 3711 SRTP Session Engine +// --------------------------------------------------------------------------- + class RtpAudioSession { public: ~RtpAudioSession() { stop(); } + std::string prepareZrtp(bool enableZrtp) { + std::lock_guard lk(zrtpMtx_); + zrtpEnabled_ = enableZrtp; + srtpActive_.store(false); + zrtpSecure_.store(false); + zrtpNotified_.store(false); + zrtpSas_.clear(); + zrtpState_ = ZrtpState::Discovery; + if (!enableZrtp) { + return ""; + } + initZrtpMaterialLocked(); + uint8_t h[32]; + sha256Bytes(localHelloMsg_.data(), localHelloMsg_.size(), h); + return bytesToHexLower(h, 32); + } + bool start(int localPort, const std::string& remoteIp, int remotePort, - int payloadType) { + int payloadType, bool enableZrtp) { stop(); if (remoteIp.empty() || remotePort <= 0) return false; @@ -414,6 +742,14 @@ class RtpAudioSession { } } + { + std::lock_guard lk(zrtpMtx_); + zrtpEnabled_ = enableZrtp; + if (enableZrtp && localHelloMsg_.empty()) { + initZrtpMaterialLocked(); + } + } + sock_ = sock; remAddr_ = remAddr; payloadType_ = (payloadType == 8) ? 8 : 0; @@ -431,6 +767,10 @@ class RtpAudioSession { ::close(sock_); sock_ = -1; } + std::lock_guard lk(zrtpMtx_); + localHelloMsg_.clear(); + srtpActive_.store(false); + zrtpSecure_.store(false); } void queueDtmf(char digit) { @@ -438,7 +778,617 @@ class RtpAudioSession { dtmfQueue_.push_back(digit); } + bool isZrtpSecure() const { return zrtpSecure_.load(); } + + bool consumeZrtpNotification(std::string& outSas) { + if (!zrtpSecure_.load() || zrtpNotified_.load()) return false; + std::lock_guard lk(zrtpMtx_); + if (zrtpSas_.empty()) return false; + outSas = zrtpSas_; + zrtpNotified_.store(true); + return true; + } + + std::string getZrtpSas() const { + std::lock_guard 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((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((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(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& 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(21 + pubBytes / 4); + size_t totalBytes = words * 4; + outMsg.assign(totalBytes, 0); + outMsg[0] = 0x50; + outMsg[1] = 0x5a; + outMsg[2] = static_cast((words >> 8) & 0xff); + outMsg[3] = static_cast(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(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 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(peerPvLen), nullptr); + BIGNUM* x = BN_bin2bn(dhPrivBytes_.data(), + static_cast(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 dhResult(peerPvLen, 0); + BN_bn2binpad(shared, dhResult.data(), static_cast(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& helloR = weAreInitiator ? peerHelloMsg_ : localHelloMsg_; + const std::vector& commitMsg = weAreInitiator ? localCommitMsg_ : peerCommitMsg_; + const std::vector& dhPart1 = weAreInitiator ? peerDhPart1Msg_ : localDhPart1Msg_; + const std::vector& dhPart2 = weAreInitiator ? localDhPart2Msg_ : peerDhPart2Msg_; + + std::vector 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 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 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 sasBytes = zrtpKdf(s0, "SAS", kdfContext, 32); + static const char kZrtpBase32[] = "ybndrfg8ejkmcpqxot1uwisza345h769"; + uint32_t sas20 = ((static_cast(sasBytes[0]) << 16) | + (static_cast(sasBytes[1]) << 8) | + static_cast(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 srtpKeyI = zrtpKdf(s0, "Initiator SRTP master key", kdfContext, 128); + std::vector srtpSaltI = zrtpKdf(s0, "Initiator SRTP master salt", kdfContext, 112); + std::vector srtpKeyR = zrtpKdf(s0, "Responder SRTP master key", kdfContext, 128); + std::vector srtpSaltR = zrtpKdf(s0, "Responder SRTP master salt", kdfContext, 112); + + std::vector hmacKeyI = zrtpKdf(s0, "Initiator HMAC key", kdfContext, 256); + std::vector hmacKeyR = zrtpKdf(s0, "Responder HMAC key", kdfContext, 256); + std::vector zrtpKeyI = zrtpKdf(s0, "Initiator ZRTP key", kdfContext, 128); + std::vector 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& 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(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 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 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(&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(msg + 4), 8); + + std::lock_guard 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(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 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 lk(zrtpMtx_); + if (!zrtpEnabled_ || zrtpState_ == ZrtpState::Secure) return; + if (now - lastZrtpTxMs_ < 180) return; + lastZrtpTxMs_ = now; + + if (zrtpState_ == ZrtpState::Discovery) { + if (helloSendCount_ < 25 && !localHelloMsg_.empty()) { + ++helloSendCount_; + sendZrtpMessageLocked(localSsrc, localHelloMsg_.data(), localHelloMsg_.size()); + } + } else if (zrtpState_ == ZrtpState::CommitSent && !localCommitMsg_.empty()) { + sendZrtpMessageLocked(localSsrc, localCommitMsg_.data(), localCommitMsg_.size()); + } else if (zrtpState_ == ZrtpState::WaitDHPart2 && !localDhPart1Msg_.empty()) { + sendZrtpMessageLocked(localSsrc, localDhPart1Msg_.data(), localDhPart1Msg_.size()); + } else if (zrtpState_ == ZrtpState::WaitConfirm1 && !localDhPart2Msg_.empty()) { + sendZrtpMessageLocked(localSsrc, localDhPart2Msg_.data(), localDhPart2Msg_.size()); + } else if (zrtpState_ == ZrtpState::WaitConfirm2 && !localConfirm1Msg_.empty()) { + sendZrtpMessageLocked(localSsrc, localConfirm1Msg_.data(), localConfirm1Msg_.size()); + } + } + + size_t protectRtpPacket(uint8_t* pkt, size_t clearLen, uint16_t seq, uint32_t ssrc) { + if (!srtpActive_.load() || clearLen < 12) return clearLen; + std::lock_guard 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(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(txSrtp_.tagBytes)); + return clearLen + static_cast(txSrtp_.tagBytes); + } + + bool unprotectRtpPacket(uint8_t* pkt, size_t& ioLen, size_t hdrLen) { + if (!srtpActive_.load()) return true; + std::lock_guard lk(zrtpMtx_); + size_t tagBytes = static_cast(rxSrtp_.tagBytes); + if (ioLen <= hdrLen + tagBytes) return false; + size_t encRtpLen = ioLen - tagBytes; + + uint16_t seq = (static_cast(pkt[2]) << 8) | pkt[3]; + uint32_t ssrc = (static_cast(pkt[8]) << 24) | + (static_cast(pkt[9]) << 16) | + (static_cast(pkt[10]) << 8) | + static_cast(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 authBuf(pkt, pkt + encRtpLen); + uint32_t netRoc = htonl(estRoc); + authBuf.insert(authBuf.end(), reinterpret_cast(&netRoc), + reinterpret_cast(&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(estRoc) << 16) | seq; + uint8_t iv[16]; + rxSrtp_.computePacketIv(ssrc, pktIdx, iv); + aes128CtrCrypt(rxSrtp_.cipherKey, iv, pkt + hdrLen, encRtpLen - hdrLen); + ioLen = encRtpLen; + return true; + } + void runLoop() { FILE* capFp = ::popen("arecord -q -f S16_LE -r 8000 -c 1 -t raw 2>/dev/null", "r"); FILE* playFp = ::popen("aplay -q -f S16_LE -r 8000 -c 1 -t raw 2>/dev/null", "w"); @@ -454,16 +1404,30 @@ class RtpAudioSession { int64_t nextTxMs = nowMs() + 20; while (running_.load()) { - // 1. Receive incoming RTP packets and play to speaker/earpiece + // 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(n); + + // Demultiplex RFC 6189 ZRTP packet (0x10 0x00 ... "ZRTP") + if (pktLen >= 16 && (rxPkt[0] & 0xf0) == 0x10 && + rxPkt[4] == 'Z' && rxPkt[5] == 'R' && + rxPkt[6] == 'T' && rxPkt[7] == 'P') { + handleZrtpPacket(ssrc, rxPkt, pktLen); + continue; + } + + if ((rxPkt[0] & 0xc0) != 0x80) continue; uint8_t pt = rxPkt[1] & 0x7f; size_t hdrLen = 12 + (rxPkt[0] & 0x0f) * 4; - if (n <= static_cast(hdrLen)) continue; + if (pktLen <= hdrLen) continue; + if (!unprotectRtpPacket(rxPkt, pktLen, hdrLen)) { + continue; + } const uint8_t* payload = rxPkt + hdrLen; - size_t payLen = static_cast(n) - hdrLen; + size_t payLen = pktLen - hdrLen; if (playFp && (pt == 0 || pt == 8)) { int16_t pcmOut[640]; size_t samples = std::min(payLen, 640); @@ -476,8 +1440,10 @@ class RtpAudioSession { } } - // 2. Transmit 20ms (160 samples) audio frame or RFC 2833 DTMF event + // 2. Transmit 20ms (160 samples) audio frame or RFC 2833 DTMF event + ZRTP tick int64_t now = nowMs(); + periodicZrtpTick(ssrc, now); + if (now >= nextTxMs) { nextTxMs = now + 20; char dtmfCh = '\0'; @@ -494,10 +1460,11 @@ class RtpAudioSession { else if (dtmfCh == '*') evCode = 10; else if (dtmfCh == '#') evCode = 11; for (int p = 0; p < 3; ++p) { - uint8_t pkt[16]; + uint8_t pkt[16 + 16]; + uint16_t curSeq = seq++; pkt[0] = 0x80; pkt[1] = static_cast((p == 0 ? 0x80 : 0x00) | 101); - uint16_t netSeq = htons(seq++); + uint16_t netSeq = htons(curSeq); uint32_t netTs = htonl(ts); uint32_t netSsrc = htonl(ssrc); std::memcpy(pkt + 2, &netSeq, 2); @@ -507,7 +1474,8 @@ class RtpAudioSession { pkt[13] = static_cast((p == 2 ? 0x80 : 0x00) | 10); uint16_t dur = htons(static_cast((p + 1) * 160)); std::memcpy(pkt + 14, &dur, 2); - ::sendto(sock_, pkt, sizeof(pkt), 0, + size_t sendLen = protectRtpPacket(pkt, 16, curSeq, ssrc); + ::sendto(sock_, pkt, sendLen, 0, reinterpret_cast(&remAddr_), sizeof(remAddr_)); } @@ -518,10 +1486,11 @@ class RtpAudioSession { ssize_t r = ::read(capFd, pcmIn, sizeof(pcmIn)); (void)r; } - uint8_t pkt[12 + 160]; + uint8_t pkt[12 + 160 + 16]; + uint16_t curSeq = seq++; pkt[0] = 0x80; pkt[1] = static_cast(payloadType_ & 0x7f); - uint16_t netSeq = htons(seq++); + uint16_t netSeq = htons(curSeq); uint32_t netTs = htonl(ts); uint32_t netSsrc = htonl(ssrc); std::memcpy(pkt + 2, &netSeq, 2); @@ -531,7 +1500,8 @@ class RtpAudioSession { pkt[12 + i] = (payloadType_ == 8) ? linearToAlaw(pcmIn[i]) : linearToUlaw(pcmIn[i]); } - ::sendto(sock_, pkt, sizeof(pkt), 0, + size_t sendLen = protectRtpPacket(pkt, 12 + 160, curSeq, ssrc); + ::sendto(sock_, pkt, sendLen, 0, reinterpret_cast(&remAddr_), sizeof(remAddr_)); ts += 160; @@ -554,6 +1524,54 @@ class RtpAudioSession { std::thread worker_; std::mutex dtmfMtx_; std::string dtmfQueue_; + + // ZRTP & SRTP state + mutable std::mutex zrtpMtx_; + bool zrtpEnabled_ = true; + std::atomic srtpActive_{false}; + std::atomic zrtpSecure_{false}; + std::atomic 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 dhPrivBytes_; + std::vector localDhPub_; + std::vector localHelloMsg_; + std::vector localCommitMsg_; + std::vector localDhPart1Msg_; + std::vector localDhPart2Msg_; + std::vector localConfirm1Msg_; + std::vector localConfirm2Msg_; + std::vector peerHelloMsg_; + std::vector peerCommitMsg_; + std::vector peerDhPart1Msg_; + std::vector 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) { @@ -620,9 +1638,18 @@ int sip_run_main(int argc, char** argv) { enum class SipCallState { Idle = 0, Incoming = 1, Outgoing = 2, Active = 3 }; SipCallState callState = SipCallState::Idle; - int activeAccountIdx = 0; + // activeAccountIdx: -1 = Direct (No Account), 0..N-1 = configured account + int activeAccountIdx = accounts.empty() ? -1 : 0; + bool directZrtpEnabled = true; + std::string activeSipCallId; std::string activePeerUri; + std::string activeTargetHost; + int activeTargetPort = 5060; + std::string activeFromDisplay = "Bananarchy"; + std::string activeFromUser = "user"; + std::string activeFromDomain = "127.0.0.1"; + bool activeCallZrtp = true; std::string activeFromHeader; std::string activeToHeader; std::string activeViaHeader; @@ -635,6 +1662,7 @@ int sip_run_main(int argc, char** argv) { std::string remoteRtpIp; int remoteRtpPort = 0; int remotePayloadType = 0; + std::string remoteZrtpHash; int localRtpPort = 16400 + (::getpid() % 1000) * 2; int64_t callStartedMs = 0; RtpAudioSession rtpSession; @@ -683,7 +1711,7 @@ int sip_run_main(int argc, char** argv) { << "Contact: \r\n" << "Expires: 300\r\n" - << "User-Agent: Bananarchy-XSip/1.0\r\n"; + << "User-Agent: Bananarchy-XSip/1.1\r\n"; if (auth && auth->valid) { req << buildDigestAuthHeader(*auth, acct, "REGISTER", uri); } @@ -694,11 +1722,12 @@ int sip_run_main(int argc, char** argv) { sendUdpPacket(acct.domain, acct.port, req.str()); }; - auto buildLocalSdp = [&](const std::string& localIp) -> std::string { + auto buildLocalSdp = [&](const std::string& localIp, + const std::string& zrtpHashHex) -> std::string { std::ostringstream sdp; uint32_t sessId = static_cast(::time(nullptr)); sdp << "v=0\r\n" - << "o=" << (accounts.empty() ? "user" : accounts[0].username) << " " + << "o=" << activeFromUser << " " << sessId << " " << sessId << " IN IP4 " << localIp << "\r\n" << "s=Bananarchy SIP Call\r\n" << "c=IN IP4 " << localIp << "\r\n" @@ -708,58 +1737,71 @@ int sip_run_main(int argc, char** argv) { << "a=rtpmap:8 PCMA/8000\r\n" << "a=rtpmap:101 telephone-event/8000\r\n" << "a=fmtp:101 0-15\r\n" - << "a=ptime:20\r\n" - << "a=sendrecv\r\n"; + << "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 { - if (acctIdx < 0 || acctIdx >= static_cast(accounts.size())) { - return false; - } - SipAccount& acct = accounts[acctIdx]; - if (acct.domain.empty() || acct.username.empty()) return false; - - std::string targetUri = trimStr(targetRaw); - if (targetUri.rfind("sip:", 0) != 0) { - if (targetUri.find('@') == std::string::npos) { - targetUri = "sip:" + targetUri + "@" + acct.domain; - } else { - targetUri = "sip:" + targetUri; + const SipAccount* acctPtr = nullptr; + if (acctIdx >= 0 && acctIdx < static_cast(accounts.size())) { + const SipAccount& cand = accounts[acctIdx]; + if (!cand.domain.empty() && !cand.username.empty() && cand.enabled) { + acctPtr = &cand; } } - std::string localIp = detectLocalIpForHost(acct.domain); + std::string targetUri; + std::string destHost; + int destPort = 5060; + if (!resolveSipTarget(targetRaw, acctPtr, targetUri, destHost, destPort)) { + neoui_show_toast("Enter user@host or add account", 2200); + return false; + } + + std::string localIp = detectLocalIpForHost(destHost); if (!auth) { - activeAccountIdx = acctIdx; + activeAccountIdx = acctPtr ? acctIdx : -1; activePeerUri = targetUri; + activeTargetHost = destHost; + activeTargetPort = destPort; + activeFromDisplay = acctPtr ? acctPtr->label : "Bananarchy"; + activeFromUser = acctPtr ? acctPtr->username : "user"; + activeFromDomain = acctPtr ? acctPtr->domain + : (localIp + ":" + std::to_string(localSipPort)); + activeCallZrtp = acctPtr ? acctPtr->zrtpEnabled : directZrtpEnabled; activeSipCallId = randomHexToken(8) + "@" + localIp; activeLocalTag = randomHexToken(6); activeRemoteTag.clear(); + std::memset(&activePeerSin, 0, sizeof(activePeerSin)); activeCseq = 1; } else { ++activeCseq; } activeBranch = "z9hG4bK" + randomHexToken(6); - std::string sdp = buildLocalSdp(localIp); + std::string zrtpHelloHash = rtpSession.prepareZrtp(activeCallZrtp); + std::string sdp = buildLocalSdp(localIp, zrtpHelloHash); std::ostringstream req; req << "INVITE " << targetUri << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";rport;branch=" << activeBranch << "\r\n" << "Max-Forwards: 70\r\n" - << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "From: \"" << activeFromDisplay << "\" ;tag=" << activeLocalTag << "\r\n" << "To: <" << targetUri << ">\r\n" << "Call-ID: " << activeSipCallId << "\r\n" << "CSeq: " << activeCseq << " INVITE\r\n" - << "Contact: \r\n" << "Allow: INVITE, ACK, CANCEL, BYE, OPTIONS, INFO\r\n" - << "User-Agent: Bananarchy-XSip/1.0\r\n"; - if (auth && auth->valid) { - req << buildDigestAuthHeader(*auth, acct, "INVITE", targetUri); + << "User-Agent: Bananarchy-XSip/1.1\r\n"; + if (auth && auth->valid && acctPtr) { + req << buildDigestAuthHeader(*auth, *acctPtr, "INVITE", targetUri); } req << "Content-Type: application/sdp\r\n" << "Content-Length: " << sdp.size() << "\r\n\r\n" @@ -767,7 +1809,7 @@ int sip_run_main(int argc, char** argv) { callState = SipCallState::Outgoing; callStartedMs = nowMs(); - sendUdpPacket(acct.domain, acct.port, req.str()); + sendUdpPacket(activeTargetHost, activeTargetPort, req.str()); if (!auth) { sendPluginCommand("callscreen", "OUTGOING sip:1 " + targetUri + " SIP"); } @@ -776,12 +1818,19 @@ int sip_run_main(int argc, char** argv) { auto acceptActiveSipCall = [&]() { if (callState != SipCallState::Incoming) return; - std::string host = (activeAccountIdx >= 0 && - activeAccountIdx < static_cast(accounts.size())) - ? accounts[activeAccountIdx].domain - : "8.8.8.8"; + std::string host = !activeTargetHost.empty() + ? activeTargetHost + : ((activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) + ? accounts[activeAccountIdx].domain + : "8.8.8.8"); std::string localIp = detectLocalIpForHost(host); - std::string sdp = buildLocalSdp(localIp); + activeCallZrtp = (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) + ? accounts[activeAccountIdx].zrtpEnabled + : directZrtpEnabled; + std::string zrtpHelloHash = rtpSession.prepareZrtp(activeCallZrtp); + std::string sdp = buildLocalSdp(localIp, zrtpHelloHash); std::ostringstream resp; resp << "SIP/2.0 200 OK\r\n" << "Via: " << activeViaHeader << "\r\n" @@ -789,7 +1838,8 @@ int sip_run_main(int argc, char** argv) { << "To: " << activeToHeader << ";tag=" << activeLocalTag << "\r\n" << "Call-ID: " << activeSipCallId << "\r\n" << "CSeq: " << std::max(1, activeCseq) << " INVITE\r\n" - << "Contact: \r\n" + << "Contact: \r\n" << "Content-Type: application/sdp\r\n" << "Content-Length: " << sdp.size() << "\r\n\r\n" << sdp; @@ -801,7 +1851,8 @@ int sip_run_main(int argc, char** argv) { "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); callState = SipCallState::Active; callStartedMs = nowMs(); - rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort, remotePayloadType); + rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort, remotePayloadType, + activeCallZrtp); sendPluginCommand("callscreen", "ACTIVE sip:1 " + activePeerUri + " SIP"); }; @@ -815,7 +1866,7 @@ int sip_run_main(int argc, char** argv) { std::string acctLbl = (activeAccountIdx >= 0 && activeAccountIdx < static_cast(accounts.size())) ? accounts[activeAccountIdx].label - : "SIP"; + : "Direct SIP"; int durSec = (callState == SipCallState::Active && callStartedMs > 0) ? static_cast((nowMs() - callStartedMs) / 1000) : 0; @@ -835,27 +1886,27 @@ int sip_run_main(int argc, char** argv) { appendSipHistory("MISSED", activePeerUri, acctLbl, 0); } else if (callState == SipCallState::Outgoing || callState == SipCallState::Active) { - if (activeAccountIdx >= 0 && - activeAccountIdx < static_cast(accounts.size())) { - SipAccount& acct = accounts[activeAccountIdx]; - std::string localIp = detectLocalIpForHost(acct.domain); - std::string method = (callState == SipCallState::Outgoing) ? "CANCEL" : "BYE"; - int seqNum = (method == "CANCEL") ? activeCseq : ++activeCseq; - std::string br = (method == "CANCEL") ? activeBranch - : ("z9hG4bK" + randomHexToken(6)); - std::ostringstream req; - req << method << " " << activePeerUri << " SIP/2.0\r\n" - << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort - << ";rport;branch=" << br << "\r\n" - << "Max-Forwards: 70\r\n" - << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" - << "To: <" << activePeerUri << ">" - << (activeRemoteTag.empty() ? "" : (";tag=" + activeRemoteTag)) << "\r\n" - << "Call-ID: " << activeSipCallId << "\r\n" - << "CSeq: " << seqNum << " " << method << "\r\n" - << "Content-Length: 0\r\n\r\n"; - sendUdpPacket(acct.domain, acct.port, req.str()); + std::string localIp = detectLocalIpForHost(activeTargetHost); + std::string method = (callState == SipCallState::Outgoing) ? "CANCEL" : "BYE"; + int seqNum = (method == "CANCEL") ? activeCseq : ++activeCseq; + std::string br = (method == "CANCEL") ? activeBranch + : ("z9hG4bK" + randomHexToken(6)); + std::ostringstream req; + req << method << " " << activePeerUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=" << br << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << activeFromDisplay << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: <" << activePeerUri << ">" + << (activeRemoteTag.empty() ? "" : (";tag=" + activeRemoteTag)) << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << seqNum << " " << method << "\r\n" + << "Content-Length: 0\r\n\r\n"; + if (!activeTargetHost.empty()) { + sendUdpPacket(activeTargetHost, activeTargetPort, req.str()); + } else { + sendUdpPacket("", 5060, req.str(), &activePeerSin); } appendSipHistory("OUT", activePeerUri, acctLbl, durSec); } @@ -906,56 +1957,57 @@ int sip_run_main(int argc, char** argv) { // Match active INVITE response if (callIdHdr == activeSipCallId && cseqHdr.find("INVITE") != std::string::npos) { + activePeerSin = fromSin; size_t tagPos = toHdr.find(";tag="); if (tagPos != std::string::npos) { activeRemoteTag = trimStr(toHdr.substr(tagPos + 5)); } if (statusCode == 401 || statusCode == 407) { DigestChallenge ch = parseDigestChallenge(msg); - if (ch.valid) { - // Send ACK for 401/407 then authenticated INVITE - if (activeAccountIdx >= 0 && - activeAccountIdx < static_cast(accounts.size())) { - SipAccount& acct = accounts[activeAccountIdx]; - std::string localIp = detectLocalIpForHost(acct.domain); - std::ostringstream ack; - ack << "ACK " << activePeerUri << " SIP/2.0\r\n" - << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort - << ";rport;branch=" << activeBranch << "\r\n" - << "Max-Forwards: 70\r\n" - << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" - << "To: " << toHdr << "\r\n" - << "Call-ID: " << activeSipCallId << "\r\n" - << "CSeq: " << activeCseq << " ACK\r\n" - << "Content-Length: 0\r\n\r\n"; - sendUdpPacket(acct.domain, acct.port, ack.str()); - sendSipInvite(activeAccountIdx, activePeerUri, &ch); - } - } - } else if (statusCode == 200 && callState == SipCallState::Outgoing) { - parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType); - if (activeAccountIdx >= 0 && + if (ch.valid && activeAccountIdx >= 0 && activeAccountIdx < static_cast(accounts.size())) { - SipAccount& acct = accounts[activeAccountIdx]; - std::string localIp = detectLocalIpForHost(acct.domain); + // 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=z9hG4bK" << randomHexToken(6) << "\r\n" + << ";rport;branch=" << activeBranch << "\r\n" << "Max-Forwards: 70\r\n" - << "From: \"" << acct.label << "\" ;tag=" << activeLocalTag << "\r\n" + << "From: \"" << activeFromDisplay << "\" ;tag=" << activeLocalTag << "\r\n" << "To: " << toHdr << "\r\n" << "Call-ID: " << activeSipCallId << "\r\n" << "CSeq: " << activeCseq << " ACK\r\n" << "Content-Length: 0\r\n\r\n"; - sendUdpPacket(acct.domain, acct.port, ack.str()); + sendUdpPacket(activeTargetHost, activeTargetPort, ack.str(), &fromSin); + sendSipInvite(activeAccountIdx, activePeerUri, &ch); + } else { + hangupActiveSipCall(true); + } + } else if (statusCode == 200 && callState == SipCallState::Outgoing) { + parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType, + remoteZrtpHash); + std::string localIp = detectLocalIpForHost(activeTargetHost); + std::ostringstream ack; + ack << "ACK " << activePeerUri << " SIP/2.0\r\n" + << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort + << ";rport;branch=z9hG4bK" << randomHexToken(6) << "\r\n" + << "Max-Forwards: 70\r\n" + << "From: \"" << activeFromDisplay << "\" ;tag=" << activeLocalTag << "\r\n" + << "To: " << toHdr << "\r\n" + << "Call-ID: " << activeSipCallId << "\r\n" + << "CSeq: " << activeCseq << " ACK\r\n" + << "Content-Length: 0\r\n\r\n"; + if (!activeTargetHost.empty()) { + sendUdpPacket(activeTargetHost, activeTargetPort, ack.str()); + } else { + sendUdpPacket("", 5060, ack.str(), &fromSin); } callState = SipCallState::Active; callStartedMs = nowMs(); rtpSession.start(localRtpPort, remoteRtpIp, remoteRtpPort, - remotePayloadType); + remotePayloadType, activeCallZrtp); sendPluginCommand("callscreen", "ACTIVE sip:1 " + activePeerUri + " SIP"); } else if (statusCode >= 400 && callState != SipCallState::Idle) { hangupActiveSipCall(true); @@ -1002,7 +2054,13 @@ int sip_run_main(int argc, char** argv) { activeLocalTag = randomHexToken(6); activeCseq = std::max(1, std::atoi(cseqHdr.c_str())); activePeerSin = fromSin; - parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType); + char peerIpBuf[INET_ADDRSTRLEN] = {0}; + if (::inet_ntop(AF_INET, &fromSin.sin_addr, peerIpBuf, sizeof(peerIpBuf))) { + activeTargetHost = peerIpBuf; + } + activeTargetPort = ntohs(fromSin.sin_port); + parseSdpMedia(msg, remoteRtpIp, remoteRtpPort, remotePayloadType, + remoteZrtpHash); // Extract clean caller URI from From header std::string caller = fromHdr; @@ -1058,7 +2116,7 @@ int sip_run_main(int argc, char** argv) { std::string acctLbl = (activeAccountIdx >= 0 && activeAccountIdx < static_cast(accounts.size())) ? accounts[activeAccountIdx].label - : "SIP"; + : "Direct SIP"; int durSec = (callState == SipCallState::Active && callStartedMs > 0) ? static_cast((nowMs() - callStartedMs) / 1000) : 0; @@ -1082,23 +2140,38 @@ int sip_run_main(int argc, char** argv) { bool menuOpen = false; int menuSel = 0; - // Account editor modal state + // Account editor modal state (8 fields): + // 0=Label, 1=Username, 2=Password, 3=Domain, 4=Port, 5=Transport, 6=ZRTP, 7=Enabled + constexpr int kNumEditFields = 8; bool editModalOpen = false; int editAcctIdx = -1; - int editFieldIdx = 0; // 0=Label, 1=Username, 2=Password, 3=Domain, 4=Port, 5=Transport, 6=Enabled + int editFieldIdx = 0; SipAccount editAcctDraft; auto syncInputBufferForFocus = [&]() { if (editModalOpen) { - if (editFieldIdx == 0) neoui_input_reset(editAcctDraft.label.c_str()); - else if (editFieldIdx == 1) neoui_input_reset(editAcctDraft.username.c_str()); - else if (editFieldIdx == 2) neoui_input_reset(editAcctDraft.password.c_str()); - else if (editFieldIdx == 3) neoui_input_reset(editAcctDraft.domain.c_str()); - else if (editFieldIdx == 4) { + 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()); } }; @@ -1106,13 +2179,18 @@ int sip_run_main(int argc, char** argv) { auto applyInputBufferToFocus = [&]() { std::string txt = neoui_input_get_text(); if (editModalOpen) { - if (editFieldIdx == 0) editAcctDraft.label = txt; - else if (editFieldIdx == 1) { + 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 (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; } @@ -1123,11 +2201,18 @@ int sip_run_main(int argc, char** argv) { neo.bindAsActiveContext(); neoui_begin_frame(); - std::string regBadge = "NO ACCT"; - for (const auto& a : accounts) { - if (a.enabled) { - regBadge = a.regStatus; - if (a.regStatus == "ONLINE") break; + std::string regBadge = "DIRECT"; + if (callState == SipCallState::Active && rtpSession.isZrtpSecure()) { + regBadge = "ZRTP:" + rtpSession.getZrtpSas(); + } else if (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(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()); @@ -1137,18 +2222,25 @@ int sip_run_main(int argc, char** argv) { constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; if (activeTab == 0) { - // Active account indicator - std::string acctLine = "Account: None (Add in Accounts tab)"; - if (!accounts.empty()) { - int idx = std::clamp(activeAccountIdx, 0, static_cast(accounts.size()) - 1); - acctLine = "Acct: " + accounts[idx].label + " [" + accounts[idx].regStatus + "]"; + // Active account / Direct mode + ZRTP indicator + std::string acctLine; + if (activeAccountIdx >= 0 && + activeAccountIdx < static_cast(accounts.size())) { + const auto& a = accounts[activeAccountIdx]; + acctLine = "Acct: " + a.label + " [" + a.regStatus + + (a.zrtpEnabled ? " ZRTP]" : "]"); + } else { + acctLine = std::string("Mode: Direct URI [") + + (directZrtpEnabled ? "ZRTP ON]" : "ZRTP OFF]"); } neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 2, 18, acctLine.c_str(), 224); + std::string dialLbl = std::string("SIP URI / Ext ") + + neoui_input_mode_badge() + " (*/# mode):"; neoui_draw_input_box(6, kBodyY + 22, 228, 38, 1, - "SIP URI / Extension (* mode):", dialInput.c_str(), - "user@domain or 1001", 0); + 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, @@ -1176,15 +2268,17 @@ int sip_run_main(int argc, char** argv) { } } neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 22, 240, 22, - "[Call/OK] Dial [*] Input Mode"); + "[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 + 60, + 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_YELLOW, 0, kBodyY + 88, + 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(accounts.size()) - 1); @@ -1193,7 +2287,8 @@ int sip_run_main(int argc, char** argv) { for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast(accounts.size()); ++i) { int idx = scrollOffset + i; const auto& a = accounts[idx]; - std::string sub = a.username + "@" + a.domain + ":" + std::to_string(a.port); + std::string sub = a.username + "@" + a.domain + + (a.zrtpEnabled ? " [ZRTP]" : ""); int col = (a.regStatus == "ONLINE") ? NEO_TEXT_GREEN : (a.enabled ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED); neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, @@ -1233,35 +2328,41 @@ int sip_run_main(int argc, char** argv) { } 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, - editAcctIdx < 0 ? "Add SIP Account" : "Edit SIP Account"); - const char* labels[7] = { - "Label", "Username", "Password", "Domain", "Port", "Transport", "Enabled" + modalTitle.c_str()); + const char* labels[kNumEditFields] = { + "Label", "User", "Pass", "Domain", "Port", "Proto", "ZRTP", "Active" }; - std::string vals[7] = { + std::string vals[kNumEditFields] = { editAcctDraft.label, editAcctDraft.username, editAcctDraft.password.empty() ? "" : "******", editAcctDraft.domain, std::to_string(editAcctDraft.port), editAcctDraft.transport, + editAcctDraft.zrtpEnabled ? "ON (SRTP)" : "OFF", editAcctDraft.enabled ? "ON" : "OFF" }; - int startIdx = std::max(0, std::min(editFieldIdx - 2, 3)); - for (int i = 0; i < 4 && (startIdx + i) < 7; ++i) { + 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 rowTxt = std::string(labels[f]) + ": " + - (f == editFieldIdx && f <= 4 ? neoui_input_get_text() : vals[f]); + 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", "TOGGLE", "Cancel"); + 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|Register All Now|Switch Account|Delete Selected|Clear History", - nullptr, menuSel, 5); + "Add SIP Account|Switch Account / Direct|Toggle Direct ZRTP|Register All Now|Delete Selected|Clear History", + nullptr, menuSel, 6); } neoui_end_frame(); @@ -1327,15 +2428,30 @@ int sip_run_main(int argc, char** argv) { "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); } else if (cmd.rfind("CALL_DTMF ", 0) == 0 && cmd.size() >= 11) { rtpSession.queueDtmf(cmd[10]); + } else if (cmd.rfind("DIAL ", 0) == 0 && cmd.size() > 5) { + dialInput = trimStr(cmd.substr(5)); + activeTab = 0; + openWindow(); + sendSipInvite(activeAccountIdx, dialInput); + if (visible) render(); } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { + bool autoCall = false; if (cmd.size() > 5) { std::string arg = trimStr(cmd.substr(5)); if (arg.rfind("dial ", 0) == 0) { dialInput = trimStr(arg.substr(5)); activeTab = 0; + } else if (arg.rfind("call ", 0) == 0) { + dialInput = trimStr(arg.substr(5)); + activeTab = 0; + autoCall = true; } } openWindow(); + if (autoCall && !dialInput.empty()) { + sendSipInvite(activeAccountIdx, dialInput); + if (visible) render(); + } } } @@ -1355,6 +2471,21 @@ int sip_run_main(int argc, char** argv) { } } + // 2b. Check if ZRTP completed handshake on active call + if (callState == SipCallState::Active) { + std::string sas; + if (rtpSession.consumeZrtpNotification(sas)) { + sendPluginCommand("callscreen", + "ACTIVE sip:1 " + activePeerUri + " SIP:" + sas); + sendPluginCommand("callscreen", + "NOTICE ZRTP Encrypted (SAS: " + sas + ")"); + if (visible) { + neoui_show_toast(("ZRTP Secure SAS: " + sas).c_str(), 3000); + render(); + } + } + } + // 3. Periodic REGISTER keepalive for enabled accounts int64_t now = nowMs(); bool anyEnabled = false; @@ -1383,11 +2514,13 @@ int sip_run_main(int argc, char** argv) { 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(accounts.size()) - 1; sendSipRegister(accounts.back()); } else if (editAcctIdx < static_cast(accounts.size())) { accounts[editAcctIdx] = editAcctDraft; @@ -1420,9 +2553,10 @@ int sip_run_main(int argc, char** argv) { } } 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 + 4) % 5; - else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5; + if (k == NEO_KEY_UP) menuSel = (menuSel + 5) % 6; + else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 6; else if (k == NEO_KEY_OK) { menuOpen = false; if (menuSel == 0) { @@ -1432,17 +2566,32 @@ int sip_run_main(int argc, char** argv) { 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(accounts.size())) { + ++activeAccountIdx; + } else { + activeAccountIdx = -1; + } + } else if (menuSel == 2) { + directZrtpEnabled = !directZrtpEnabled; + neoui_show_toast(directZrtpEnabled ? "Direct ZRTP: ON" : "Direct ZRTP: OFF", 1500); + } else if (menuSel == 3) { for (auto& a : accounts) { if (a.enabled) sendSipRegister(a); } neoui_show_toast("REGISTER sent", 1500); - } else if (menuSel == 2 && !accounts.empty()) { - activeAccountIdx = (activeAccountIdx + 1) % static_cast(accounts.size()); - } else if (menuSel == 3 && activeTab == 1 && + } else if (menuSel == 4 && activeTab == 1 && selectedRow >= 0 && selectedRow < static_cast(accounts.size())) { accounts.erase(accounts.begin() + selectedRow); + if (activeAccountIdx >= static_cast(accounts.size())) { + activeAccountIdx = static_cast(accounts.size()) - 1; + } saveSipAccounts(accounts); - } else if (menuSel == 4) { + } else if (menuSel == 5) { ::unlink(getSipHistoryPath().c_str()); history.clear(); } @@ -1452,64 +2601,98 @@ int sip_run_main(int argc, char** argv) { render(); } else if (editModalOpen) { if (k == NEO_KEY_UP) { + neoui_input_commit_tap(); applyInputBufferToFocus(); - editFieldIdx = (editFieldIdx + 6) % 7; + editFieldIdx = (editFieldIdx + kNumEditFields - 1) % kNumEditFields; syncInputBufferForFocus(); } else if (k == NEO_KEY_DOWN) { + neoui_input_commit_tap(); applyInputBufferToFocus(); - editFieldIdx = (editFieldIdx + 1) % 7; + 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 == 5) { + if (editFieldIdx <= 4) { + if (neoui_input_is_tap_active()) { + neoui_input_commit_tap(); + applyInputBufferToFocus(); + } else { + applyInputBufferToFocus(); + editFieldIdx = (editFieldIdx + 1) % kNumEditFields; + syncInputBufferForFocus(); + } + } else if (editFieldIdx == 5) { if (editAcctDraft.transport == "UDP") editAcctDraft.transport = "TCP"; else if (editAcctDraft.transport == "TCP") editAcctDraft.transport = "TLS"; else editAcctDraft.transport = "UDP"; } else if (editFieldIdx == 6) { + editAcctDraft.zrtpEnabled = !editAcctDraft.zrtpEnabled; + } else if (editFieldIdx == 7) { editAcctDraft.enabled = !editAcctDraft.enabled; } - } else if (k == NEO_KEY_STAR) { - neoui_input_cycle_mode(); + } 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) { + } 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(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) { - applyInputBufferToFocus(); - activeTab = (activeTab + 1) % 3; - selectedRow = 0; - scrollOffset = 0; - syncInputBufferForFocus(); + 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(history.size())) { target = history[selectedRow].peerUri; } - if (accounts.empty()) { - neoui_show_toast("Add a SIP account first", 2000); - } else if (!target.empty()) { - sendSipInvite(std::clamp(activeAccountIdx, 0, - static_cast(accounts.size()) - 1), - target); + if (!target.empty()) { + sendSipInvite(activeAccountIdx, target); + } else { + neoui_show_toast("Enter SIP URI (user@host)", 1800); } } else if (activeTab == 1) { if (accounts.empty()) { @@ -1524,14 +2707,11 @@ int sip_run_main(int argc, char** argv) { editModalOpen = true; syncInputBufferForFocus(); } else if (activeTab == 2 && selectedRow >= 0 && - selectedRow < static_cast(history.size()) && - !accounts.empty()) { - sendSipInvite(std::clamp(activeAccountIdx, 0, - static_cast(accounts.size()) - 1), - history[selectedRow].peerUri); + selectedRow < static_cast(history.size())) { + sendSipInvite(activeAccountIdx, history[selectedRow].peerUri); } } else if (activeTab == 0) { - if (k == NEO_KEY_STAR) { + if (k == NEO_KEY_STAR || k == NEO_KEY_HASH) { neoui_input_cycle_mode(); } else if (k == NEO_KEY_BACK) { if (!dialInput.empty()) { @@ -1541,9 +2721,14 @@ int sip_run_main(int argc, char** argv) { closeWindow(); break; } - } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { + } 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(ks)); + neoui_input_set_text(cur.c_str()); + applyInputBufferToFocus(); } } else if (k == NEO_KEY_END || k == NEO_KEY_BACK) { closeWindow(); @@ -1569,7 +2754,9 @@ int sip_run_main(int argc, char** argv) { if (sipUdpFd >= 0) pfds[nfds++] = { sipUdpFd, POLLIN, 0 }; int timeoutMs = -1; - if (visible) { + if (callState == SipCallState::Active) { + timeoutMs = 150; + } else if (visible) { timeoutMs = neoui_input_is_tap_active() ? 150 : 1000; } else if (anyEnabled) { timeoutMs = 15000; @@ -1597,7 +2784,7 @@ int sip_plugin_init(const DwmHostApi* host) { extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { DWM_PLUGIN_API_VERSION, "sip", - "SIP VoIP client with standby registration and CallScreen integration", + "SIP VoIP client with ZRTP/SRTP, direct URI calling, and CallScreen integration", sip_plugin_init, nullptr, nullptr,