Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
c3b7d01d43 |
|||
|
a65724a252 |
|||
|
6d05aaed0d |
|||
|
1eee41f0ed |
|||
|
0026213073 |
|||
|
3d702ec1f1 |
|||
|
e3b94a8415 |
|||
|
640d261248 |
|||
|
3b9c0fed98 |
|||
|
52d4b4f217 |
|||
|
83a9eb539d |
|||
|
d48c1017da |
|||
|
c93df591f1 |
|||
|
bc0e70a17f |
|||
|
0aea0dac7f |
|||
|
d3e495c333 |
|||
|
610d8e1300 |
|||
|
3754687b0d |
|||
|
460343e578 |
|||
|
ddb8798d85 |
|||
|
d3c1ba4a29 |
|||
|
ed2a009425 |
|||
|
6b0d6341d3 |
|||
|
2ec2426597 |
|||
|
d381805d66 |
|||
|
21ebfa2823 |
|||
|
d6d7ba100a |
|||
|
1fa4d77fcd |
|||
|
23892e8e81 |
|||
|
ef04b473a7 |
|||
|
710f884575 |
|||
|
9333621c66 |
|||
|
5f01b46909 |
|||
|
7cae603c0c |
|||
|
c81dd3d267 |
|||
|
78c702546a |
|||
|
1267fe1ada |
|||
|
5c1fca12b9 |
|||
|
ca825937bf |
|||
|
a63132deb8 |
20 changed files with 6181 additions and 722 deletions
20
README.md
20
README.md
|
|
@ -69,11 +69,11 @@ session and root may place, answer and end calls; an ssh login may not.
|
|||
|
||||
Off unless `SMS_OVER_IMS=1` is set in `/etc/imsd.env`. On, imsd sends texts
|
||||
over the IMS registration it already holds, through the SIM's service
|
||||
centre or the one `SMSC` names, and receives texts the network delivers over IMS;
|
||||
centre or the one `SMSC` names, and receives texts over IMS;
|
||||
its store for received texts is `/var/lib/imsd/sms`, and a text in it stays
|
||||
until a messaging app deletes it. Apps that read ModemManager, such as Spacebar and
|
||||
Chatty, do not see texts that arrive this way; `imsd-messages`, the app built
|
||||
for imsd's `net.catcrafts.IMS1.Messaging` interface, shows them. The details are
|
||||
Chatty, do not see texts that arrive this way; `imsd-messages` is the app built
|
||||
for imsd's `net.catcrafts.IMS1.Messaging` interface. The details are
|
||||
in AGENTS.md: the behaviour and the store in §7.9, the interface in §8.4,
|
||||
what was verified on which network in §5.
|
||||
|
||||
|
|
@ -90,11 +90,13 @@ Configuration is environment variables in `/etc/imsd.env`, none are required.
|
|||
| `DEV` | `qmapmux0.0` | ims-PDN netdev; the packaged service passes the real one via `/run/imsd.env` |
|
||||
| `LOCAL` | *(auto)* | UE address (compared in RFC 5952 form). The packaged service gets the PDN address ModemManager assigned, via `/run/imsd.env` from `ims-pdn-up.sh`; a manual run prefers a global IPv6 on `DEV` that is neither temporary nor `dynamic` (RA-derived), then any non-temporary one, then the first (the kernel's temporary SLAAC address is listed first, and a registration bound to it is lost when the kernel retires it) |
|
||||
| `USER_AGENT` | `imsd/<version>` | REGISTER User-Agent. Some networks fingerprint UAs; setting your device's stock build string reproduces the stock modem's registration exactly. Empty omits the header |
|
||||
| `ISIM` | `1` | `0` registers the names derived from the IMSI and answers the challenge in the USIM, as 1.2.2 did. By default a card that has an ISIM registers the identity the ISIM holds (its private identity, home domain and first public identity) and the ISIM is asked for the answer to the challenge; a card without one, or with one imsd cannot use, registers the derived names. The journal's `identity:` line says which. A registration that stands keeps the names it was made under, so a change of the setting shows after a reboot |
|
||||
| `STATE_FILE` | `/var/lib/imsd/imsreg.state` (root) / `$XDG_STATE_HOME/imsd/imsreg.state` | persisted registration context for warm resume |
|
||||
| `HOLDS_FILE` | `/run/imsd.holds` (root) / `$XDG_RUNTIME_DIR/imsd.holds` (`/tmp/imsd.holds` without a runtime dir) | the waits the network imposed (a `Retry-After`, the refusal schedule), where that schedule stands whether the old registration is gone (`old_gone`) and the refusal count (`refusals`: a resume refused without a Retry-After at a start with no fresh target is one, the restart's the second), kept across a restart of imsd for the PDN they were set on — not across a reboot; `/dev/null` switches the file off (only a regular file is ever removed; anything else is emptied). `imsd-handover.sh` honours it too |
|
||||
| `RESUME` | `auto` | `0` forces a fresh registration (ignores a warm SA) where there is a fresh target; with none the untried pair is removed and the bring-up ends as AGENTS §7.2 (the daemon's own bring-up) step 1 says |
|
||||
| `REFRESH_INTERVAL` | *(auto)* | keepalive re-REGISTER period in s; default = half the granted expiry, clamped to [120, 1800] |
|
||||
| `EALG` | `aes-cbc` | offered ESP cipher (`aes-cbc`, `des-ede3-cbc`, `null`). From the 401's `Security-Server` list imsd selects the highest-preference `ipsec-3gpp` mechanism that matches this offer (RFC 3329 §2.3.1) and takes the SPIs/ports from the entry carrying them (some cores list every mechanism they support and put the SPIs on the one they applied); when no entry matches, the P-CSCF's SPI-carrying entry is installed as listed (`hmac-md5-96`, an absent `ealg` = null) and the journal says so. The line, the selection and the SA parameters are logged at every fresh registration |
|
||||
| `CRLF_KEEPALIVE` | `0` | whole seconds between CRLF keepalives (RFC 5626 §4.4.1) on an idle TCP flow to the P-CSCF; `0` or an empty value sends none (until 1.2.3 imsd sent one every 30 s; AGENTS.md §13 has what that costs a phone). For a network that drops a flow it hears nothing on (AGENTS.md §7.2, the daemon's bring-up, step 5). Any other value that is no whole number of seconds is reported in the journal and sends none |
|
||||
| `EALG` | `aes-cbc,null` | the ESP ciphers offered, in order: a comma-separated list of `aes-cbc`, `null` (no encryption) and `des-ede3-cbc`; a name imsd cannot install is ignored with a journal line. From the 401's `Security-Server` list imsd selects the `ipsec-3gpp` mechanism the P-CSCF put the SPIs on when it is the only such entry and one of the offer, else the mechanism of the offer with the highest preference (the `q` of RFC 3329 §2.3.1), and takes the SPIs/ports from the entry carrying them (some cores list every mechanism they support and put the SPIs on the one they applied); when no entry matches, the P-CSCF's SPI-carrying entry is taken as listed (`hmac-md5-96`, an absent `ealg` = null) where imsd can install it, and the journal says so. The offer is logged at bring-up beside the SIP transport, the line, the selection and the SA parameters at every fresh registration |
|
||||
| `SIP_TRANSPORT` | `auto` | transport of the protected leg (the second REGISTER and everything after it): `tcp`, `udp`, or `auto` = TCP, falling back to a fresh registration over UDP when the P-CSCF leaves two TCP connects unanswered — but only on a phone that has never registered over TCP: once the state file records a TCP registration, a silent connect is treated as an outage, not a policy (delete the file or set `udp` to override, e.g. after a SIM change). The challenge (first REGISTER) is always UDP. Over UDP a REGISTER or INVITE larger than ~1.2 KB leaves as IPv6 fragments at the ims PDN's 1280-byte MTU (the journal says so once per flow); there are no SIP retransmission timers over UDP yet, so a lost datagram costs a timeout. The SAs, the listener and the firewall rule cover both transports |
|
||||
| `SMS_OVER_IMS` | `0` | `1` takes short messages over IMS (AGENTS.md §7.9): the REGISTER Contact advertises `+g.3gpp.smsip` and `net.catcrafts.IMS1.Messaging.Send` submits one; off, imsd does not advertise it and refuses `Send` (AGENTS.md §7.9 says how imsd answers a text the network sends anyway) |
|
||||
| `SMSC` | *(EF_SMSP)* | the service centre a submission is addressed to, in international form (`+31653131313`; spaces, dashes and dots dropped; a national or `00`-prefixed number, or a `*` or `#` in it, is refused at bring-up); unset, imsd reads the (U)SIM's EF_SMSP record 1. Without either, `Send` fails with the reason |
|
||||
|
|
@ -102,7 +104,7 @@ Configuration is environment variables in `/etc/imsd.env`, none are required.
|
|||
| `RTP_PORT` | `50004` | local RTP port advertised in SDP |
|
||||
| `PRECOND` | `0` | `1` offers SDP QoS preconditions |
|
||||
| `CODECS` | *(empty — defaults)* | comma-separated codec preference list over `AMR-WB`, `AMR` (or `AMR-NB`), `PCMA`, `PCMU`: restricts and orders both the codecs offered on an outgoing call and those accepted from an inbound offer (default: offer AMR-WB + AMR, accept all four in that order). A bench knob — a network whose gateway transcodes every caller up to AMR-WB otherwise never lets the narrowband path run |
|
||||
| `DUMP_SIP` | `0` | `1` writes raw REGISTER-200/SUBSCRIBE-200 dumps, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last incoming call's INVITE (`imsd-invite-in.raw`), the last outgoing INVITE (`imsd-invite-out.raw`), the last inbound MESSAGE outside a call's dialog (`imsd-message-in.raw`) and the last MESSAGE a submission started with (`imsd-message-out.raw`), mode 0600, for debugging — they contain your IMSI/MSISDN and addresses, and the two MESSAGE dumps the text of a short message. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers |
|
||||
| `DUMP_SIP` | `0` | `1` writes dumps of a fresh registration's REGISTER 200 and of the SUBSCRIBE 200s, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last incoming call's INVITE (`imsd-invite-in.raw`), the last outgoing INVITE (`imsd-invite-out.raw`), the last inbound MESSAGE outside a call's dialog (`imsd-message-in.raw`) and the last MESSAGE a submission started with (`imsd-message-out.raw`), mode 0600, for debugging; a received message is dumped as imsd reads it, its folded header lines joined — they contain your IMSI/MSISDN and addresses, and the two MESSAGE dumps the text of a short message. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers |
|
||||
| `DUMP_DIR`, `OUT_DIR` | state dir | where dumps / per-call media stats land |
|
||||
| `IMSD_MEDIA` | *(auto)* | path to `imsd-media` (default: next to `imsd`, else `/usr/libexec/imsd-media`) |
|
||||
| `IMSD_ENV` | `/etc/imsd.env` | the configuration file's path — a bench seam for manual runs of `ims-pdn-up.sh` (the packaged unit reads `/etc/imsd.env` through `EnvironmentFile=`). The file's existence changes nothing |
|
||||
|
|
@ -147,18 +149,18 @@ A new desktop needs a new translation daemon, not changes here.
|
|||
|
||||
A second interface on the same object, for short messages over IMS
|
||||
(`SMS_OVER_IMS=1`). Additive: the interface above is unchanged. Frozen as of
|
||||
1.2.0: what the table lists stays as it is, and a dictionary imsd gives may
|
||||
gain a key.
|
||||
1.2.0: its members and their signatures stay as they are, and a dictionary
|
||||
imsd gives may gain a key.
|
||||
|
||||
| Member | Signature |
|
||||
|---|---|
|
||||
| `Send(number, text, options)` | `ssa{sv} → s` (id); options: `status-report` (b, ask the SC to report delivery). Refused with `NotSupported` while SMS over IMS is off |
|
||||
| `GetStatus()` | `→ a{sv}`: `enabled` (b), `smsc` (s), `ppi` (s, the own number in the daemon's last status, e.g. `tel:+31612345678`), `operator` (s, the SIM's operator id in that status), `registered` (b), `subscribers` (u) |
|
||||
| `Subscribe()` | `→` nothing: the calling connection receives `Received` and `StateChanged` from now on (unicast, never broadcast: to subscribers, and a submission's `sent` / `failed` also to its `Send` caller); subscribe again when imsd's name reappears on the bus |
|
||||
| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries |
|
||||
| `List()` | `→ a(sa{sv})`: the stored messages, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries; `IOError` when a store that is there cannot be read |
|
||||
| `Delete(id)` | `s`: removes a stored message |
|
||||
| `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `to` (when the daemon held an own number at receipt: that number, e.g. `tel:+31612345678`), `operator` (the SIM's operator id at receipt), `class` (i, -1 none), `pid` (y), `dcs` (y), `segments` (i), `message-waiting` (b), `port-dst`/`port-src` (u, when addressed to a port), `data` (ay, 8-bit data), `pdu` (ay, the SMS-DELIVER as received; of a concatenated message, the segment that completed it)) |
|
||||
| `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once |
|
||||
| `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC; AGENTS.md §7.9 has what counts as accepted when a segment was sent twice), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once |
|
||||
|
||||
`Send`, `Subscribe`, `List` and `Delete` are gated by polkit's `net.catcrafts.IMS1.Messaging`.
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -2,17 +2,26 @@
|
|||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
/*
|
||||
Imsd:Aka — USIM AKA (3GPP TS 33.102) glue for IMS registration:
|
||||
Imsd:Aka — the card's side of an IMS registration: AKA (3GPP TS 33.102) and
|
||||
the identity to register:
|
||||
|
||||
* the AKAv1-MD5 HTTP-digest response (RFC 3310) the protected REGISTER
|
||||
carries in its Authorization header — MD5 over the binary RES;
|
||||
* the home-network identity (IMPI/IMPU/registration URI/realm) derived
|
||||
from IMSI + MCC/MNC;
|
||||
* text parsers for the SIM facts the daemon shell scrapes from qmicli
|
||||
(`--uim-get-card-status`: which slot holds a ready USIM and its AID) and
|
||||
ModemManager (`mmcli`: the primary SIM path, then IMSI + operator id);
|
||||
* the home-network identity (IMPI/IMPU/registration URI/realm): derived
|
||||
from IMSI + MCC/MNC (TS 23.003 13.2 to 13.4B, the names of a UE without
|
||||
an ISIM), and since 1.2.3 the one an ISIM holds (TS 24.229 5.1.1.1A) —
|
||||
the value an identity file carries (`ParseIsimValue`) and the check of
|
||||
the three before they stand in a REGISTER (`IsimIdentity`);
|
||||
* text parsers for the SIM facts in qmicli's output
|
||||
(`--uim-get-card-status`: which slot holds a ready USIM and its AID,
|
||||
and the ISIM application of a slot) and in
|
||||
ModemManager's (`mmcli`: the primary SIM path, then IMSI + operator id);
|
||||
* the ISO 7816 APDU for the AUTHENTICATE(AKA) command and the parser for
|
||||
its 0xDB success response (RES / CK / IK TLV).
|
||||
its 0xDB success response (RES / CK / IK TLV), the class byte of a
|
||||
command on a logical channel, the SELECT and the two READ commands the
|
||||
ISIM's files are read with, and a card's answer: its status word and,
|
||||
for an answer without data, the command it asks for next ('61 XX',
|
||||
'6C XX').
|
||||
|
||||
All pure std C++: the actual card I/O (open channel, transmit APDU) is the
|
||||
shell's job — this module only shapes the bytes and reads the answers back.
|
||||
|
|
@ -25,7 +34,9 @@ import :Util;
|
|||
|
||||
export namespace imsd::aka {
|
||||
|
||||
// The home-network identity a USIM registers under.
|
||||
// The home-network identity: the one derived from the IMSI
|
||||
// (MakeIdentity), whose shapes the comments below give, or the one an
|
||||
// ISIM holds (IsimIdentity).
|
||||
struct Identity {
|
||||
std::string imsi;
|
||||
std::string mcc;
|
||||
|
|
@ -75,24 +86,26 @@ export namespace imsd::aka {
|
|||
return imsd::util::Md5::HexDigest(std::format("{}:{}:{}:{}:{}:{}", ha1, nonce, nc, cnonce, qop, ha2));
|
||||
}
|
||||
|
||||
// Which USIM the modem should authenticate against.
|
||||
// The ready USIM of a card status: its slot and its AID.
|
||||
struct SimSelection {
|
||||
int slot = 0;
|
||||
std::string aid; // uppercase, colons stripped
|
||||
};
|
||||
|
||||
// Parse qmicli `--uim-get-card-status`: the first ready USIM application,
|
||||
// its slot number, and its Application ID (the hex line under
|
||||
// "Application ID:"). nullopt if no ready USIM is present. Mirrors the
|
||||
// Python detect_sim() scan exactly.
|
||||
std::optional<SimSelection> ParseCardStatus(std::string_view text) {
|
||||
int curSlot = 0;
|
||||
bool inUsim = false;
|
||||
bool ready = false;
|
||||
std::optional<SimSelection> out;
|
||||
std::size_t pos = 0;
|
||||
auto isAidLine = [](std::string_view s) {
|
||||
// trimmed line is HH(:HH)+ — two-or-more colon-separated hex pairs
|
||||
// The pieces of qmicli's card status both of its readers take.
|
||||
namespace detail {
|
||||
// A line without the blanks before it and the blanks or the CR
|
||||
// after it.
|
||||
inline std::string_view Trimmed(std::string_view t) {
|
||||
while (!t.empty() && (t.front() == ' ' || t.front() == '\t'))
|
||||
t.remove_prefix(1);
|
||||
while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r'))
|
||||
t.remove_suffix(1);
|
||||
return t;
|
||||
}
|
||||
// A trimmed line that is an Application ID: HH(:HH)+, two or more
|
||||
// colon-separated hex pairs.
|
||||
inline bool AidLine(std::string_view s) {
|
||||
std::size_t i = 0;
|
||||
int pairs = 0;
|
||||
auto hex = [](char c) {
|
||||
|
|
@ -108,36 +121,49 @@ export namespace imsd::aka {
|
|||
i++;
|
||||
}
|
||||
return pairs >= 2;
|
||||
};
|
||||
while (pos <= text.size()) {
|
||||
std::size_t nl = text.find('\n', pos);
|
||||
std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
|
||||
std::string_view t = line;
|
||||
while (!t.empty() && (t.front() == ' ' || t.front() == '\t'))
|
||||
t.remove_prefix(1);
|
||||
while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r'))
|
||||
t.remove_suffix(1);
|
||||
|
||||
if (t.starts_with("Slot [")) {
|
||||
}
|
||||
// Such a line's AID: uppercase, colons stripped.
|
||||
inline std::string AidOf(std::string_view t) {
|
||||
std::string aid;
|
||||
for (char c : t)
|
||||
if (c != ':') aid.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
|
||||
return aid;
|
||||
}
|
||||
// The N of a "Slot [N]:" line: 0 when what stands between the
|
||||
// brackets is no number, `fallback` for a line without the pair.
|
||||
inline int SlotOf(std::string_view t, int fallback) {
|
||||
std::size_t lb = t.find('[');
|
||||
std::size_t rb = t.find(']', lb);
|
||||
if (lb != std::string_view::npos && rb != std::string_view::npos) {
|
||||
if (lb == std::string_view::npos || rb == std::string_view::npos) return fallback;
|
||||
int v = 0;
|
||||
std::from_chars(t.data() + lb + 1, t.data() + rb, v);
|
||||
curSlot = v;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse qmicli `--uim-get-card-status`: the first ready USIM application,
|
||||
// its slot number, and its Application ID (the hex line under
|
||||
// "Application ID:"). nullopt if no ready USIM is present. Mirrors the
|
||||
// Python detect_sim() scan exactly.
|
||||
std::optional<SimSelection> ParseCardStatus(std::string_view text) {
|
||||
int curSlot = 0;
|
||||
bool inUsim = false;
|
||||
bool ready = false;
|
||||
std::optional<SimSelection> out;
|
||||
std::size_t pos = 0;
|
||||
while (pos <= text.size()) {
|
||||
std::size_t nl = text.find('\n', pos);
|
||||
std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos));
|
||||
|
||||
if (t.starts_with("Slot [")) {
|
||||
curSlot = detail::SlotOf(t, curSlot);
|
||||
inUsim = ready = false;
|
||||
} else if (t.contains("Application type") && t.contains("usim")) {
|
||||
inUsim = true;
|
||||
} else if (inUsim && t.contains("Application state") && t.contains("ready")) {
|
||||
ready = true;
|
||||
} else if (inUsim && isAidLine(t)) {
|
||||
if (ready && !out) {
|
||||
std::string aid;
|
||||
for (char c : t)
|
||||
if (c != ':') aid.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
|
||||
out = SimSelection{curSlot, aid};
|
||||
}
|
||||
} else if (inUsim && detail::AidLine(t)) {
|
||||
if (ready && !out) out = SimSelection{curSlot, detail::AidOf(t)};
|
||||
inUsim = false;
|
||||
}
|
||||
if (nl == std::string_view::npos) break;
|
||||
|
|
@ -146,6 +172,49 @@ export namespace imsd::aka {
|
|||
return out;
|
||||
}
|
||||
|
||||
// An ISIM application as the card status lists it.
|
||||
struct IsimApp {
|
||||
std::string aid; // uppercase, colons stripped
|
||||
std::string state; // the modem's word for it: detected, ready, …
|
||||
};
|
||||
|
||||
// The first ISIM application of the card in `slot`, from the same card
|
||||
// status, in whatever state the modem lists it: the Fairphone 6's modem
|
||||
// lists an ISIM as `detected` beside a `ready` USIM (the two cards
|
||||
// with an ISIM the probe read, AGENTS.md §13), and a logical channel
|
||||
// opened on each all the same. nullopt when the card in that slot lists
|
||||
// none — another
|
||||
// slot's ISIM belongs to another subscription.
|
||||
std::optional<IsimApp> ParseIsimApp(std::string_view text, int slot) {
|
||||
int curSlot = 0;
|
||||
bool inIsim = false;
|
||||
std::string state;
|
||||
std::size_t pos = 0;
|
||||
while (pos <= text.size()) {
|
||||
std::size_t nl = text.find('\n', pos);
|
||||
std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos));
|
||||
|
||||
if (t.starts_with("Slot [")) {
|
||||
curSlot = detail::SlotOf(t, curSlot);
|
||||
inIsim = false;
|
||||
} else if (t.contains("Application type")) {
|
||||
inIsim = t.contains("isim");
|
||||
state.clear();
|
||||
} else if (t.contains("Application state")) {
|
||||
// the word between the quotes: Application state: 'detected'
|
||||
std::size_t q1 = t.find('\'');
|
||||
std::size_t q2 = q1 == std::string_view::npos ? q1 : t.find('\'', q1 + 1);
|
||||
if (q2 != std::string_view::npos) state = t.substr(q1 + 1, q2 - q1 - 1);
|
||||
} else if (inIsim && detail::AidLine(t)) {
|
||||
if (curSlot == slot) return IsimApp{detail::AidOf(t), state};
|
||||
inIsim = false;
|
||||
}
|
||||
if (nl == std::string_view::npos) break;
|
||||
pos = nl + 1;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// "primary sim path: <path>" from `mmcli -m any`.
|
||||
std::optional<std::string> ParsePrimarySimPath(std::string_view text) {
|
||||
std::size_t at = text.find("primary sim path:");
|
||||
|
|
@ -214,8 +283,7 @@ export namespace imsd::aka {
|
|||
// "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=<mcc><mnc><tac:4hex><eci:7hex>"
|
||||
// (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit
|
||||
// TAC + 28-bit ECI; mmcli prints both hex fields zero-padded wider, so
|
||||
// take the low digits). The stock modem sends exactly this shape in
|
||||
// every REGISTER/INVITE — the TAS reads it to see which access the UE
|
||||
// take the low digits). The TAS reads it to see which access the UE
|
||||
// is reachable on. FDD is a constant: every KPN LTE band in use is FDD
|
||||
// and MM does not expose the duplex mode. nullopt when the fields are
|
||||
// missing or zero (no serving cell) — callers then omit the header
|
||||
|
|
@ -248,20 +316,191 @@ export namespace imsd::aka {
|
|||
|
||||
// ---- AUTHENTICATE(AKA) APDU (ISO 7816-4 over the qmicli UIM channel) ----
|
||||
|
||||
// The class byte of a command on a logical channel (ETSI TS 102 221
|
||||
// 10.1.1): '0X' with the channel in its two low bits for the standard
|
||||
// channels 0 to 3, '4X' with the channel less four in its low nibble for
|
||||
// the extended ones, 4 to 19. Before 1.2.3 the channel number itself was
|
||||
// the class byte, which is the first form only: a command for channel 4
|
||||
// went out as '04', channel 0 with a secure-messaging bit set.
|
||||
inline int ClassByte(int channel) {
|
||||
return channel < 4 ? channel & 0x03 : 0x40 | ((channel - 4) & 0x0F);
|
||||
}
|
||||
|
||||
// The command APDU (hex, no separators) for a 3G AKA authentication:
|
||||
// CLA=<channel byte> INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)]
|
||||
// `channel` is the logical-channel number qmicli returned; the CLA low
|
||||
// nibble carries it (Python: cla = "%02x" % ch).
|
||||
// CLA=<class byte> INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)]
|
||||
// `channel` is the logical-channel number qmicli returned.
|
||||
std::string BuildAkaApdu(int channel, std::span<const std::uint8_t> rand16, std::span<const std::uint8_t> autn16) {
|
||||
std::string data = std::format("10{}10{}", imsd::util::ToHex(rand16), imsd::util::ToHex(autn16));
|
||||
std::size_t lc = data.size() / 2;
|
||||
// CLA INS=88 P1=00 P2=81 Lc <data>
|
||||
return std::format("{:02x}880081{:02x}{}", channel, lc, data);
|
||||
return std::format("{:02x}880081{:02x}{}", ClassByte(channel), lc, data);
|
||||
}
|
||||
|
||||
// GET RESPONSE APDU for when the card answers 61xx (xx bytes available).
|
||||
std::string BuildGetResponseApdu(int channel, int le) {
|
||||
return std::format("{:02x}c00000{:02x}", channel, le & 0xFF);
|
||||
return std::format("{:02x}c00000{:02x}", ClassByte(channel), le & 0xFF);
|
||||
}
|
||||
|
||||
// ---- reading a file of the selected application -------------------------
|
||||
|
||||
// The ISIM's identity files (TS 31.103 4.2.2 to 4.2.4).
|
||||
constexpr std::uint16_t EfImpi = 0x6F02; // transparent: the private user identity
|
||||
constexpr std::uint16_t EfDomain = 0x6F03; // transparent: the home network domain name
|
||||
constexpr std::uint16_t EfImpu = 0x6F04; // linear fixed: the public user identities
|
||||
|
||||
// SELECT by file identifier under the application the channel was opened
|
||||
// on (TS 102 221 11.1.1.2: P1 '00', select by file id; P2 '04', return
|
||||
// the FCP template).
|
||||
std::string BuildSelectFileApdu(int channel, std::uint16_t fileId) {
|
||||
return std::format("{:02x}a4000402{:04x}", ClassByte(channel), fileId);
|
||||
}
|
||||
|
||||
// READ BINARY from the start of the selected transparent file (TS 102 221
|
||||
// 11.1.3), and READ RECORD of one record of the selected linear fixed
|
||||
// file by its number (11.1.5: P2 '04', absolute mode), both with Le '00':
|
||||
// a '6C XX' in answer names the length (7.3.1.1.5.1).
|
||||
std::string BuildReadBinaryApdu(int channel) {
|
||||
return std::format("{:02x}b0000000", ClassByte(channel));
|
||||
}
|
||||
std::string BuildReadRecordApdu(int channel, int record) {
|
||||
return std::format("{:02x}b2{:02x}0400", ClassByte(channel), record & 0xFF);
|
||||
}
|
||||
|
||||
// A card's answer to one command: the data and the status word.
|
||||
struct ApduAnswer {
|
||||
std::vector<std::uint8_t> data;
|
||||
std::uint8_t sw1 = 0;
|
||||
std::uint8_t sw2 = 0;
|
||||
// The normal endings (TS 102 221 10.2.1.1): '90 00'; '91 XX', from
|
||||
// a card that has a proactive command waiting for the terminal
|
||||
// (7.4.2.1); '92 XX', with a data transfer session going on.
|
||||
bool Ok() const { return (sw1 == 0x90 && sw2 == 0x00) || sw1 == 0x91 || sw1 == 0x92; }
|
||||
// The status word as the specifications write it: "6a82".
|
||||
std::string Status() const { return std::format("{:02x}{:02x}", sw1, sw2); }
|
||||
};
|
||||
|
||||
// The answer in the bytes qmicli prints for an exchange (the data, then
|
||||
// SW1 SW2); nullopt for fewer than the two status bytes.
|
||||
std::optional<ApduAnswer> ParseApduAnswer(std::span<const std::uint8_t> bytes) {
|
||||
if (bytes.size() < 2) return std::nullopt;
|
||||
ApduAnswer a;
|
||||
a.data.assign(bytes.begin(), bytes.end() - 2);
|
||||
a.sw1 = bytes[bytes.size() - 2];
|
||||
a.sw2 = bytes[bytes.size() - 1];
|
||||
return a;
|
||||
}
|
||||
|
||||
// The command to send after `answer` to get what `apdu` (hex) asked for,
|
||||
// when the card asks for one (TS 102 221 7.3.1.1.5, the procedure bytes
|
||||
// '61xx' and '6Cxx'): GET RESPONSE with the length a '61 XX' names, or,
|
||||
// for a '6C XX', the command again with that length in place of its
|
||||
// last byte — of a command that is a header and an Le, five bytes.
|
||||
// nullopt for any other answer, which is taken for the command's last:
|
||||
// data with a '61 XX' behind it, which offers more, among them.
|
||||
std::optional<std::string> ApduFollowUp(int channel, std::string_view apdu, const ApduAnswer& answer) {
|
||||
if (!answer.data.empty()) return std::nullopt;
|
||||
if (answer.sw1 == 0x61) return BuildGetResponseApdu(channel, answer.sw2);
|
||||
if (answer.sw1 == 0x6C && apdu.size() == 10) return std::format("{}{:02x}", apdu.substr(0, 8), answer.sw2);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Whether a SELECT's answer says the file is selected: a normal ending,
|
||||
// or '61 XX', the card offering the file's control parameters, which
|
||||
// nothing here needs.
|
||||
inline bool Selected(const ApduAnswer& answer) {
|
||||
return answer.Ok() || answer.sw1 == 0x61;
|
||||
}
|
||||
|
||||
// Whether a read's answer holds what was read: a normal ending, or
|
||||
// data under the warning '62 82', the file or the record having ended
|
||||
// before the Le bytes asked for (TS 102 221 10.2.1.3).
|
||||
inline bool HoldsRead(const ApduAnswer& answer) {
|
||||
return answer.Ok() || (answer.sw1 == 0x62 && answer.sw2 == 0x82 && !answer.data.empty());
|
||||
}
|
||||
|
||||
// The value of the data object with tag '80' that an ISIM identity file,
|
||||
// or a record of EF_IMPU, begins with (TS 31.103 4.2.2 to 4.2.4: the
|
||||
// NAI, the domain name, a URI), as text. The bytes after the object are
|
||||
// the file's padding and are not read, and 'FF' bytes at the end of its
|
||||
// length are taken for padding counted into it and cut: the probe that
|
||||
// read two reporters' cards cuts them (AGENTS.md §13), so its output
|
||||
// does not tell such a card from another. nullopt for anything else:
|
||||
// another first byte (an unused record is all 'FF'), a length in
|
||||
// another form than one byte, '81' and one or '82' and two, a length
|
||||
// that runs past the data, no value, or a value with a blank or a byte
|
||||
// that is not printable ASCII — the three are written into SIP header
|
||||
// fields.
|
||||
std::optional<std::string> ParseIsimValue(std::span<const std::uint8_t> data) {
|
||||
if (data.size() < 2 || data[0] != 0x80) return std::nullopt;
|
||||
std::size_t i = 1;
|
||||
std::size_t n = data[i++];
|
||||
if (n == 0x81) {
|
||||
if (i >= data.size()) return std::nullopt;
|
||||
n = data[i++];
|
||||
} else if (n == 0x82) {
|
||||
if (i + 1 >= data.size()) return std::nullopt;
|
||||
n = static_cast<std::size_t>(data[i]) << 8 | data[i + 1];
|
||||
i += 2;
|
||||
} else if (n >= 0x80) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (i + n > data.size()) return std::nullopt;
|
||||
while (n > 0 && data[i + n - 1] == 0xFF) n--;
|
||||
if (n == 0) return std::nullopt;
|
||||
std::string value;
|
||||
for (std::size_t k = 0; k < n; k++) {
|
||||
std::uint8_t c = data[i + k];
|
||||
if (c < 0x21 || c > 0x7E) return std::nullopt;
|
||||
value.push_back(static_cast<char>(c));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// The identity an ISIM holds in place of the derived one: `derived`
|
||||
// (which keeps its IMSI and operator) with the private identity, the
|
||||
// home domain and the public identity the card gave, and the
|
||||
// registration URI of that domain. nullopt when one of the three cannot
|
||||
// stand where imsd writes it: a private identity without an `@` between
|
||||
// two parts, a domain that is not labels of letters, digits and inner
|
||||
// hyphens, 63 characters a label and 253 in all at most, a
|
||||
// public identity that does not begin `sip:` and go on, a private or a
|
||||
// public identity of more than 255 characters, or one of the two with a
|
||||
// `"`, a `\`, a `<` or a `>` (the private identity is written into a
|
||||
// quoted string, the public one between angle brackets), a blank or a
|
||||
// byte outside printable ASCII.
|
||||
std::optional<Identity> IsimIdentity(Identity derived, std::string_view impi, std::string_view domain, std::string_view impu) {
|
||||
auto plain = [](std::string_view s) {
|
||||
if (s.empty() || s.size() > 255) return false;
|
||||
for (char ch : s) {
|
||||
auto c = static_cast<unsigned char>(ch);
|
||||
if (c < 0x21 || c > 0x7E || c == '"' || c == '\\' || c == '<' || c == '>') return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
auto host = [](std::string_view s) {
|
||||
if (s.empty() || s.size() > 253) return false;
|
||||
char prev = '.';
|
||||
std::size_t label = 0;
|
||||
for (char c : s) {
|
||||
bool alnum = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
|
||||
if (!alnum && c != '-' && c != '.') return false;
|
||||
if ((c == '.' || c == '-') && prev == '.') return false; // a label begins with a letter or a digit
|
||||
if (c == '.' && prev == '-') return false; // and ends with one
|
||||
label = c == '.' ? 0 : label + 1;
|
||||
if (label > 63) return false;
|
||||
prev = c;
|
||||
}
|
||||
return prev != '.' && prev != '-';
|
||||
};
|
||||
if (!plain(impi) || !plain(impu) || !host(domain)) return std::nullopt;
|
||||
std::size_t at = impi.find('@');
|
||||
if (at == 0 || at == std::string_view::npos || at + 1 == impi.size()) return std::nullopt;
|
||||
if (!impu.starts_with("sip:") || impu.size() == 4) return std::nullopt;
|
||||
derived.impi = impi;
|
||||
derived.domain = domain;
|
||||
derived.impu = impu;
|
||||
derived.regUri = std::format("sip:{}", domain);
|
||||
return derived;
|
||||
}
|
||||
|
||||
struct AkaResult {
|
||||
|
|
@ -293,4 +532,13 @@ export namespace imsd::aka {
|
|||
if (!take(r.res) || !take(r.ck) || !take(r.ik)) return std::nullopt;
|
||||
return r;
|
||||
}
|
||||
|
||||
// The same of an answer already parted into its data and its status
|
||||
// word (ParseApduAnswer).
|
||||
std::optional<AkaResult> ParseAkaResponse(const ApduAnswer& answer) {
|
||||
std::vector<std::uint8_t> resp = answer.data;
|
||||
resp.push_back(answer.sw1);
|
||||
resp.push_back(answer.sw2);
|
||||
return ParseAkaResponse(std::span<const std::uint8_t>(resp));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@
|
|||
|
||||
/*
|
||||
Imsd:Engine — the daemon's decisions as pure reducers: the call state
|
||||
machine (CallMachine), the registration recovery policy (RegRecovery,
|
||||
its own section below) and SMS over IP's (the last paragraph here).
|
||||
machine (CallMachine), the registration recovery policy (RegRecovery, its own section below), when the phone has
|
||||
to be awake for imsd (WakeAt, with the policy's WakeTime after a local wait) and SMS over IP's (the last paragraph here).
|
||||
|
||||
A CallMachine owns one call's SIP dialog, outgoing or incoming. It never
|
||||
touches a socket, a clock, or a subprocess: each event (the INVITE's
|
||||
|
|
@ -17,7 +17,8 @@ That keeps the whole call FSM — PRACK on reliable 18x, ACK of 2xx vs non-2xx
|
|||
finals, CANCEL/answer races, remote BYE, media-plane far-end-hangup, the
|
||||
emergency attempt chain (urn:service:sos first for a classified number, one
|
||||
fallback to a plain INVITE of the digits; a 380 Alternative Service upgrade
|
||||
the other way), the terminating (UAS) side: 100/180 on an inbound INVITE,
|
||||
the other way), an INVITE refused 422 sent again with the Min-SE the 422
|
||||
names (RFC 4028 7.3, 7.4), the terminating (UAS) side: 100/180 on an inbound INVITE,
|
||||
200-with-answer on Accept, 486 reject, the remote-CANCEL 200+487 pair — and
|
||||
DTMF, which reaches the media leg only on an active call whose SDP
|
||||
negotiated telephone-event, as the tones a keypad has —
|
||||
|
|
@ -30,12 +31,15 @@ local-hangup/remote-hangup/refused-or-busy/error).
|
|||
SMS over IP (TS 24.341) has its own reducers at the end: SmsOutbound, one
|
||||
short message of ours on its way to the service centre segment by segment
|
||||
(the MESSAGE with the RP-DATA, its final, the submit report that comes
|
||||
back in a MESSAGE of its own), and OnSmsMessage, what an inbound
|
||||
back in a MESSAGE of its own; a segment that gets no answer, or an
|
||||
RP-ERROR with cause 41, sent once more, TP-RD set), and OnSmsMessage, what an inbound
|
||||
MESSAGE outside a call's dialog leads to (the final for it, the message or
|
||||
status report it delivered, the delivery report to send), with
|
||||
RecentTransactions (a retransmitted request within 32 s gets its final
|
||||
again and is not handled again; one whose first Via line has no
|
||||
`branch=`, or an empty one, is never taken for a copy), and StatusReportBook with SameRecipient (a status
|
||||
`branch=`, or an empty one, is never taken for a copy), RecentSubmissions (the
|
||||
Call-IDs of the MESSAGEs our submissions went out in, an hour each: a submit
|
||||
report for one no longer in flight is answered 200, not 488), and StatusReportBook with SameRecipient (a status
|
||||
report's match to the message that asked for one, TP-MR and recipient, and
|
||||
its word for the whole message), SmsWordOrder (the order of a message's
|
||||
words) and the ids (RunToken, SentSmsId, ReceivedSmsId), and the received-message store's record codec
|
||||
|
|
@ -73,8 +77,8 @@ export namespace imsd::engine {
|
|||
// ---- registration recovery policy ---------------------------------
|
||||
//
|
||||
// What the daemon does when the registration stops working after
|
||||
// bring-up, as a pure reducer: the shell supplies the clock and the
|
||||
// network, this decides the next step and how long to wait for it. Two
|
||||
// bring-up, as a pure reducer: the shell supplies the clock, the network and (at a local wait) its kind, the
|
||||
// kernel's refusal or the modem's word; this decides the next step, how long to wait for it and when a sleeping phone is woken for it. Two
|
||||
// kinds of failure reach it. A REFUSAL: the network answered a refresh
|
||||
// with a final other than 200 — a 401, re-authentication, included — or
|
||||
// a fresh registration's protected REGISTER with a final other than 200
|
||||
|
|
@ -128,9 +132,9 @@ export namespace imsd::engine {
|
|||
// refused or throttled fresh attempt, a terminated binding's probation
|
||||
// or its refusal schedule), which nothing cuts short — a
|
||||
// restart of the process neither: the shell keeps the holds (Holds)
|
||||
// and hands them to the next one (Restore). The shell supplies the
|
||||
// clock and the network; this holds the deadlines and names the next
|
||||
// step (Next). Success resets everything.
|
||||
// and hands them to the next one (Restore). The shell supplies the clock, what the network answered or did not and,
|
||||
// at a local wait, its kind (the kernel's refusal, the modem's word); this holds the deadlines and each kind's count,
|
||||
// and names the next step (Next) and when a sleeping phone is woken for it (WakeTime). Success resets everything.
|
||||
struct RegRecovery {
|
||||
enum class Failure { Refused, Silent, Throttled };
|
||||
enum class Step { Reconnect, Fresh };
|
||||
|
|
@ -157,6 +161,21 @@ export namespace imsd::engine {
|
|||
// untouched. Dev phone 2026-09-24: four such refusals in 26 s read
|
||||
// as two silent cycles cost a fresh registration into the throttle.
|
||||
static constexpr double LocalRetry = 5;
|
||||
// That pace is for a phone that is awake. A sleeping phone is woken
|
||||
// for a look that follows such a wait after as long again as that
|
||||
// kind of wait has lasted, within these bounds: seldom in a
|
||||
// coverage gap of hours (counted from the modem's first word of no
|
||||
// service since the network last answered: a modem that alternates
|
||||
// at the edge of coverage shortens nothing), soon at first where
|
||||
// the kernel refuses a connect (counted from its first refusal
|
||||
// since the modem was last without service or the network last
|
||||
// answered, whichever came later: a 4-tuple it still holds clears
|
||||
// in awake seconds, TIME_WAIT's 60). A step that follows no
|
||||
// local wait is woken for at the policy's own time,
|
||||
// whatever went before.
|
||||
static constexpr double LocalWakeMin = 10;
|
||||
static constexpr double LocalWakeMax = 900;
|
||||
enum class Local { NoService, Kernel };
|
||||
|
||||
int refusals = 0;
|
||||
int silentCycles = 0;
|
||||
|
|
@ -167,10 +186,14 @@ export namespace imsd::engine {
|
|||
bool fresh = false; // the next registration attempt is a fresh one
|
||||
bool oldGone = false; // the old registration is gone: nothing to reconnect over
|
||||
bool terminated = false; // the network terminated our binding, and the policy has counted it
|
||||
// the deadlines, on the shell's clock
|
||||
// the deadlines and a local wait's state, on the shell's clock
|
||||
double backoffUntil = 0; // self-imposed: no step before this; a Dial clears it
|
||||
double holdUntil = 0; // the network's word for any attempt (a Retry-After on a refresh): nothing clears it
|
||||
double freshHoldUntil = 0; // no fresh attempt before this (the schedule after a refused or throttled fresh attempt, a fresh Retry-After, probation, rejected/unregistered)
|
||||
bool lastLocal = false; // the step that waits follows a local wait, not a counted failure
|
||||
double gapSince = 0; // the modem's first word of no service since the network last answered (0: none)
|
||||
double kernelSince = 0; // the kernel's first refusal of a connect since the modem was last without service or the network last answered (0: none)
|
||||
double localWakeAt = 0; // when a sleeping phone is woken for the look after a local wait
|
||||
|
||||
bool Fresh() const { return fresh; }
|
||||
bool Reconnectable() const { return !oldGone; }
|
||||
|
|
@ -210,7 +233,32 @@ export namespace imsd::engine {
|
|||
return {Step::Fresh, freshAt};
|
||||
}
|
||||
|
||||
void OnLocalRefusal(double now) { backoffUntil = now + LocalRetry; }
|
||||
void OnLocalRefusal(double now, Local kind = Local::Kernel) {
|
||||
backoffUntil = now + LocalRetry;
|
||||
lastLocal = true;
|
||||
double since;
|
||||
if (kind == Local::NoService) {
|
||||
if (gapSince == 0) gapSince = now;
|
||||
kernelSince = 0;
|
||||
since = gapSince;
|
||||
} else {
|
||||
if (kernelSince == 0) kernelSince = now;
|
||||
since = kernelSince;
|
||||
}
|
||||
localWakeAt = now + std::clamp(now - since, LocalWakeMin, LocalWakeMax);
|
||||
}
|
||||
bool LocalLook() const { return lastLocal; }
|
||||
// The network has answered (the shell's word: an answered TCP
|
||||
// connect of the resume or of a reconnect, a response to a
|
||||
// REGISTER): it is in reach, and both counts start over.
|
||||
void OnNetworkAnswered() { gapSince = 0; kernelSince = 0; }
|
||||
// When a sleeping phone is to be awake for the next step: the
|
||||
// step's own time, and after a local wait the slower look's, never
|
||||
// before the step's own (a hold the network set).
|
||||
double WakeTime(double now) const {
|
||||
double at = Next(now).at;
|
||||
return lastLocal ? std::max(at, localWakeAt) : at;
|
||||
}
|
||||
|
||||
// A refused keepalive refresh, or a failed reconnect + refresh
|
||||
// cycle; `status` is the refusal's. The backoff paces the next step;
|
||||
|
|
@ -220,6 +268,8 @@ export namespace imsd::engine {
|
|||
// registration is due says the old registration is gone (KPN drops
|
||||
// it the moment an initial REGISTER arrives, throttled or not).
|
||||
void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) {
|
||||
lastLocal = false; // a counted step waits now: woken for at its own time
|
||||
if (f == Failure::Refused) OnNetworkAnswered(); // silence is no answer: the gap's count stands
|
||||
if (retryAfter > 0) holdUntil = std::max(holdUntil, now + static_cast<double>(std::min(retryAfter, RetryAfterMax)));
|
||||
// A cycle over a registration already known gone — the network
|
||||
// terminated the binding while the cycle waited for its final —
|
||||
|
|
@ -243,6 +293,8 @@ export namespace imsd::engine {
|
|||
// it off 30 s → 10 min. A reconnect over the old SA meanwhile waits
|
||||
// at least the reconnect backoff.
|
||||
void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) {
|
||||
lastLocal = false;
|
||||
if (f != Failure::Silent) OnNetworkAnswered();
|
||||
freshAttempts++;
|
||||
fresh = true;
|
||||
if (saReplaced) oldGone = true;
|
||||
|
|
@ -268,6 +320,8 @@ export namespace imsd::engine {
|
|||
// reg-event dialog of the account carries it, a NOTIFY may be
|
||||
// retransmitted), and never shortens a hold already running.
|
||||
void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) {
|
||||
lastLocal = false;
|
||||
OnNetworkAnswered();
|
||||
bool reported = terminated;
|
||||
terminated = true;
|
||||
oldGone = true;
|
||||
|
|
@ -286,7 +340,7 @@ export namespace imsd::engine {
|
|||
|
||||
// The stored registration is not there to reconnect over (a resume
|
||||
// that failed at bring-up found its SAs unusable, or there are none).
|
||||
void OldGone() { oldGone = true; fresh = true; }
|
||||
void OldGone() { oldGone = true; fresh = true; lastLocal = false; }
|
||||
|
||||
// A user's Dial cuts the backoff short, never the network's word.
|
||||
void OnDial() { backoffUntil = 0; }
|
||||
|
|
@ -294,6 +348,24 @@ export namespace imsd::engine {
|
|||
void OnSuccess() { *this = RegRecovery{}; }
|
||||
};
|
||||
|
||||
// When the phone has to be awake for imsd, on the shell's clock (0:
|
||||
// never): what the shell arms its wake alarm from. A time that is not
|
||||
// later than now says the phone is to stay awake. The shell's loop arms the alarm for the time, and WakeHold
|
||||
// ahead where the time is nearer than that: under an alarm that near the kernel refuses a suspend that reaches
|
||||
// its check in time (the shell has the turns that arm it and what that takes). While imsd is busy with
|
||||
// what counts awake seconds in its waits (a call, a text in flight) that
|
||||
// is now. With a registration on a live flow it is the refresh's due
|
||||
// time, or the reg-event subscription's renewal where that comes first
|
||||
// (renewalDue 0: none is due). Without one it is the recovery policy's
|
||||
// word (RegRecovery::WakeTime) where the shell has a step to run, a dead
|
||||
// flow under a registration: a step that is due is now, whatever the
|
||||
// policy's clock value for "now". And none where nothing waits to be done.
|
||||
constexpr double WakeAt(double now, bool busy, bool liveFlow, double refreshDue, double renewalDue, bool recovering, double recoveryAt) {
|
||||
if (busy) return now;
|
||||
if (liveFlow) return renewalDue > 0 ? std::min(refreshDue, renewalDue) : refreshDue;
|
||||
return recovering ? std::max(recoveryAt, now) : 0;
|
||||
}
|
||||
|
||||
// Parsed SDP answer needed to bring up the media leg. `codec` is one of
|
||||
// imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play).
|
||||
// `dtmfPt` is the telephone-event payload type at the codec's clock
|
||||
|
|
@ -346,6 +418,10 @@ export namespace imsd::engine {
|
|||
// imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants.
|
||||
inline constexpr double InviteTimeout = 90.0;
|
||||
inline constexpr double Cancel487Timeout = 10.0;
|
||||
// How often an INVITE goes out again for a 422 under one Call-ID
|
||||
// (CallMachine::OnInviteResponse). RFC 4028 sets no number: this is
|
||||
// imsd's bound for a path that names a larger minimum every time.
|
||||
inline constexpr int MinSeAgainMax = 3;
|
||||
// How long an unanswered incoming call may ring before we 480 it — a
|
||||
// safety net behind the network's own CANCEL, so generous.
|
||||
inline constexpr double IncomingRingTimeout = 120.0;
|
||||
|
|
@ -417,11 +493,50 @@ export namespace imsd::engine {
|
|||
offer.codecs = codecs_;
|
||||
std::string sdp = imsd::sdp::BuildOffer(offer);
|
||||
std::vector<Action> a;
|
||||
a.push_back(Send(imsd::msg::BuildInvite(ctx_, d_, sdp, precond_)));
|
||||
inviteOut_ = imsd::msg::BuildInvite(ctx_, d_, sdp, precond_);
|
||||
a.push_back(Send(inviteOut_));
|
||||
a.push_back(Deadline(InviteTimeout));
|
||||
return a;
|
||||
}
|
||||
|
||||
// An outgoing call's current INVITE has been sent and has had no
|
||||
// response, not a 100 either, and no CANCEL has followed it.
|
||||
// The shell asks when it finds the client flow dead under a call: a
|
||||
// flow the network had forgotten is reset at the first bytes sent
|
||||
// on it, and those may be this INVITE.
|
||||
bool Unanswered() const {
|
||||
return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_;
|
||||
}
|
||||
// … and that INVITE has not gone out a second time over a reopened
|
||||
// flow.
|
||||
bool ResendDue() const { return Unanswered() && !resent_; }
|
||||
|
||||
// The shell reopened the flow under an INVITE whose resend is due:
|
||||
// the same INVITE again, byte for byte (the same branch: RFC 3261
|
||||
// 17.2.3 has a server that did receive the first match this one to
|
||||
// its transaction), and the setup deadline from now. Once per
|
||||
// INVITE: one that AgainWithMinSe sends has a resend of its own.
|
||||
std::vector<Action> OnFlowReopened() {
|
||||
std::vector<Action> a;
|
||||
if (!ResendDue()) return a;
|
||||
resent_ = true;
|
||||
a.push_back(LogAct(std::format("call {}: the INVITE again over the reopened flow", uni_)));
|
||||
a.push_back(Send(inviteOut_));
|
||||
a.push_back(Deadline(InviteTimeout));
|
||||
return a;
|
||||
}
|
||||
|
||||
// The flow under an unanswered INVITE is dead and stays so (it
|
||||
// could not be reopened, or died again after the resend): the call
|
||||
// ends here, an emergency call's first attempt too, with nothing to
|
||||
// send a CANCEL on and no flow for a fallback attempt.
|
||||
std::vector<Action> OnFlowLost() {
|
||||
std::vector<Action> a;
|
||||
if (!Unanswered()) return a;
|
||||
Append(a, Finish("error", "the client flow died before any response to the INVITE"));
|
||||
return a;
|
||||
}
|
||||
|
||||
// UAS: answer the inbound INVITE with 100 Trying + 180 Ringing (made
|
||||
// reliable only when the caller Requires 100rel) and arm the ring
|
||||
// timeout. An offer we cannot serve — no audio line, or none of the
|
||||
|
|
@ -488,14 +603,21 @@ export namespace imsd::engine {
|
|||
return a;
|
||||
}
|
||||
|
||||
// A response to our INVITE (the shell already matched Call-ID + CSeq).
|
||||
// A response to an INVITE of ours (the shell has matched the Call-ID
|
||||
// and the method).
|
||||
std::vector<Action> OnInviteResponse(std::string_view msg) {
|
||||
std::vector<Action> a;
|
||||
if (direction_ == Direction::Incoming)
|
||||
return a; // a UAS has no INVITE transaction of its own
|
||||
// An answer to an INVITE this call has since sent again under
|
||||
// its Call-ID (AgainWithMinSe) is the replaced transaction's:
|
||||
// the shell matches the Call-ID and the method, the sequence
|
||||
// number is told apart here.
|
||||
if (!imsd::sip::ResponseOf(msg, d_.callid, std::format("{} INVITE", d_.invCseq))) return a;
|
||||
AbsorbDialog(msg);
|
||||
auto st = imsd::sip::Status(msg);
|
||||
if (!st) return a;
|
||||
answered_ = true;
|
||||
int code = *st;
|
||||
if (code > 100 && code < 200) {
|
||||
if (state_ == CallState::Dialing) {
|
||||
|
|
@ -507,7 +629,7 @@ export namespace imsd::engine {
|
|||
if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) {
|
||||
pracked_.insert(std::string(*rseq));
|
||||
std::array<std::string, 1> extra = {
|
||||
std::format("RAck: {} 1 INVITE", *rseq)};
|
||||
std::format("RAck: {} {} INVITE", *rseq, d_.invCseq)};
|
||||
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra)));
|
||||
nextCseq_++;
|
||||
}
|
||||
|
|
@ -540,7 +662,24 @@ export namespace imsd::engine {
|
|||
}
|
||||
// non-2xx final
|
||||
a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or("")))));
|
||||
std::string fin = WithReason(std::format("INVITE final {}", code), msg);
|
||||
std::string fin = std::format("INVITE final {}", code);
|
||||
if (code == 422) {
|
||||
// Session Interval Too Small: by RFC 4028 6 it carries the
|
||||
// server's minimum in a Min-SE, and TS 24.229 5.1.2A.1.1 has
|
||||
// a UE retry an INVITE so refused by RFC 4028 7.4. Only an
|
||||
// INVITE that awaits its final (no CANCEL out, no answer
|
||||
// taken), not for a Min-SE no larger than the one the
|
||||
// refused INVITE carried, and not more than MinSeAgainMax
|
||||
// times under one Call-ID.
|
||||
const auto minSe = imsd::sip::MinSe(msg);
|
||||
fin += minSe ? std::format(", Min-SE {}", *minSe) : std::string(", no Min-SE read");
|
||||
const bool awaited = !cancelled_ && (state_ == CallState::Dialing || state_ == CallState::Ringing);
|
||||
if (minSe && awaited && *minSe > d_.minSe && minSeAgain_ < MinSeAgainMax) {
|
||||
Append(a, AgainWithMinSe(*minSe, WithReason(fin, msg)));
|
||||
return a;
|
||||
}
|
||||
}
|
||||
fin = WithReason(fin, msg);
|
||||
if (auto sos = FallbackTo(code, msg)) {
|
||||
Append(a, Retry(*sos, fin));
|
||||
return a;
|
||||
|
|
@ -758,6 +897,13 @@ export namespace imsd::engine {
|
|||
bool sosTried_ = false;
|
||||
bool plainTried_ = false;
|
||||
bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline
|
||||
// The current INVITE as sent, whether any response to it has come,
|
||||
// and whether it went out a second time over a reopened flow
|
||||
// (OnFlowReopened).
|
||||
std::string inviteOut_;
|
||||
bool answered_ = false;
|
||||
bool resent_ = false;
|
||||
int minSeAgain_ = 0; // INVITEs sent again for a 422 under this Call-ID
|
||||
std::set<std::string> pracked_;
|
||||
std::string answerSdp_;
|
||||
std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start
|
||||
|
|
@ -773,20 +919,65 @@ export namespace imsd::engine {
|
|||
d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local);
|
||||
d_.itag = rng_.Token(10);
|
||||
d_.invBranch = rng_.Token(20);
|
||||
nextCseq_ = 2;
|
||||
pracked_.clear();
|
||||
answerSdp_.clear();
|
||||
NewTransaction();
|
||||
cancelled_ = false;
|
||||
userCancelled_ = false;
|
||||
minSeAgain_ = 0;
|
||||
}
|
||||
|
||||
// What each INVITE of an outgoing call starts from, a dialog's first
|
||||
// (ResetDialog) and one sent again in it (AgainWithMinSe): the
|
||||
// requests within the dialog numbered after it, no 18x PRACKed, no
|
||||
// answer, no response to it and no resend of it.
|
||||
void NewTransaction() {
|
||||
nextCseq_ = d_.invCseq + 1;
|
||||
pracked_.clear();
|
||||
answerSdp_.clear();
|
||||
answered_ = false;
|
||||
resent_ = false;
|
||||
}
|
||||
|
||||
// The INVITE a 422 refused, again (RFC 4028 7.3, 7.4): a new
|
||||
// transaction of the same call. Its dialog keeps the request-URI,
|
||||
// the Call-ID and our tag, takes the next sequence number the
|
||||
// Call-ID has not carried (7.3 has "one higher than the previous":
|
||||
// the one after the refused INVITE's, or, which is ours, the one
|
||||
// after the last PRACK's where a PRACK followed that INVITE), a
|
||||
// branch of its own and `minSe` as its Min-SE. Its session interval
|
||||
// is the refused INVITE's, or `minSe` where that was smaller. What
|
||||
// the refused transaction left (the refusal's To tag, a route, a
|
||||
// target, and what NewTransaction clears) is not the new one's.
|
||||
// Whether it is sent is the caller's (OnInviteResponse).
|
||||
std::vector<Action> AgainWithMinSe(int minSe, std::string_view why) {
|
||||
imsd::msg::Dialog next;
|
||||
next.ruri = d_.ruri;
|
||||
next.callid = d_.callid;
|
||||
next.itag = d_.itag;
|
||||
next.invBranch = rng_.Token(20);
|
||||
next.invCseq = nextCseq_;
|
||||
next.minSe = minSe;
|
||||
next.sessionExpires = std::max(d_.sessionExpires, minSe);
|
||||
d_ = std::move(next);
|
||||
NewTransaction();
|
||||
minSeAgain_++;
|
||||
std::vector<Action> a;
|
||||
a.push_back(LogAct(std::format("call {}: {} — the INVITE again with Session-Expires {}", uni_, why, d_.sessionExpires)));
|
||||
if (state_ != CallState::Dialing) {
|
||||
state_ = CallState::Dialing;
|
||||
a.push_back(StateAct("outgoing"));
|
||||
}
|
||||
Append(a, Start());
|
||||
return a;
|
||||
}
|
||||
|
||||
// The emergency fallback chain — where the next attempt (if any)
|
||||
// points. `msg` may be empty (deadline paths).
|
||||
// - a sos INVITE that fails for any reason other than the user
|
||||
// hanging up is re-attempted as a plain INVITE of the dialled
|
||||
// digits: the pre-emergency-support behavior, so classification
|
||||
// can only improve on the status quo, never block a call the old
|
||||
// code would have placed.
|
||||
// - asked after a sos attempt, it answers the dialled digits as a
|
||||
// plain INVITE, unless the user hung up or the digits were tried
|
||||
// before that attempt (the 380's upgrade below): the
|
||||
// pre-emergency-support behavior, so classification can only improve
|
||||
// on the status quo, never block a call the old code would have placed.
|
||||
// An end of a sos attempt that does not ask here brings no fallback.
|
||||
// - a plain INVITE answered 380 Alternative Service whose body
|
||||
// names emergency (TS 24.229 5.1.6: the network classified a
|
||||
// number we didn't) is re-attempted as urn:service:sos. A 380
|
||||
|
|
@ -1041,15 +1232,76 @@ export namespace imsd::engine {
|
|||
std::map<std::uint8_t, std::shared_ptr<Message>> byMr_;
|
||||
};
|
||||
|
||||
// The waits (TS 24.011 10: TR1M; TS 24.341 5.3.1.1 NOTE 1 has it
|
||||
// exceed SIP timer F): a MESSAGE's final within 32 s
|
||||
// of the MESSAGE or of its latest provisional, which starts the wait
|
||||
// over; the submit report within 40 s of the final — a length TR1M may
|
||||
// have, though 6.3.1 sets TR1M when the RP-DATA is transferred.
|
||||
inline constexpr double SmsSendTimeout = 32.0;
|
||||
inline constexpr double SmsReportTimeout = 40.0;
|
||||
// What the bus hears: `sent` once every segment's submit report is
|
||||
// in, `failed` with the reason; a status report's word
|
||||
// The Call-IDs an In-Reply-To lists (RFC 3261 20.21: a callid, then
|
||||
// more after commas), each without the white space around it.
|
||||
std::vector<std::string_view> InReplyToCallIds(std::string_view inReplyTo) {
|
||||
std::vector<std::string_view> ids;
|
||||
for (auto part : std::views::split(inReplyTo, ','))
|
||||
ids.push_back(imsd::sip::Trim(std::string_view(part.begin(), part.end())));
|
||||
return ids;
|
||||
}
|
||||
|
||||
// An RP-ERROR's refusal in words: its RP cause and, when its submit
|
||||
// report carries one, the TP-FCS.
|
||||
std::string RpErrorWords(const imsd::sms::Rp& rp) {
|
||||
std::string words = std::format("RP cause {} ({})", rp.cause.value_or(0), imsd::sms::RpCauseText(rp.cause.value_or(0)));
|
||||
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, true); r && r->failureCause)
|
||||
words += std::format(", TP-FCS 0x{:02x} ({})", *r->failureCause, imsd::sms::FailureCauseText(*r->failureCause));
|
||||
return words;
|
||||
}
|
||||
|
||||
// The MESSAGEs our submissions went out in, by Call-ID. TS 24.341
|
||||
// 5.3.1.2 has a submit report answered 200 when its In-Reply-To
|
||||
// "indicates that the request corresponds to a short message submitted
|
||||
// by the SM-over-IP sender" and 488 when it does not, and its NOTE 3
|
||||
// has the sender store the Call-ID for that. The message in flight
|
||||
// knows the MESSAGEs of its segment in flight (SmsOutbound); this table
|
||||
// keeps every one for an hour after it went out, so a report that comes
|
||||
// once its message has ended — its waits run out, say — or once its
|
||||
// segment was followed by the next is still known for ours: answered 200 and logged with
|
||||
// the message's id. Nothing else follows from it: a message that has
|
||||
// ended has had its word on the bus, and `failed` is its last (§8.4);
|
||||
// one whose next segment is in flight goes on as it was. The table is
|
||||
// this run's.
|
||||
class RecentSubmissions {
|
||||
public:
|
||||
static constexpr double Keep = 3600.0;
|
||||
struct Entry { std::string id; std::size_t segment = 0, segments = 0; double at = 0; };
|
||||
|
||||
// the MESSAGE `callid` carried segment `segment` of `segments` of the message `id`
|
||||
void Sent(std::string_view callid, std::string_view id, std::size_t segment, std::size_t segments, double now) {
|
||||
Purge(now);
|
||||
byCallId_[std::string(callid)] = Entry{std::string(id), segment, segments, now};
|
||||
}
|
||||
// The MESSAGE of ours an In-Reply-To names — of the Call-IDs it lists, the first on record.
|
||||
std::optional<Entry> Named(std::string_view inReplyTo, double now) {
|
||||
Purge(now);
|
||||
for (std::string_view callid : InReplyToCallIds(inReplyTo))
|
||||
if (auto it = byCallId_.find(callid); it != byCallId_.end()) return it->second;
|
||||
return std::nullopt;
|
||||
}
|
||||
std::size_t Size() const { return byCallId_.size(); }
|
||||
|
||||
private:
|
||||
void Purge(double now) {
|
||||
std::erase_if(byCallId_, [&](const auto& e) { return now - e.second.at > Keep; });
|
||||
}
|
||||
std::map<std::string, Entry, std::less<>> byCallId_;
|
||||
};
|
||||
|
||||
// The waits. TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP sender's TR1M
|
||||
// set to a value greater than SIP timer F, and TS 24.229 table 7.7.1
|
||||
// recommends a UE on a 3GPP access a T1 of 2 s and a timer F of 64*T1.
|
||||
// So: a MESSAGE's final within 128 s of the MESSAGE — or of its latest
|
||||
// provisional, which starts the wait over here, as it did in 1.2.0;
|
||||
// RFC 3261's timer F does not start over —; the submit report within
|
||||
// 130 s of the final — past the 35 to 45 s TS 24.011 10.1 has for
|
||||
// TR1M, as the NOTE asks, and from the final, where 6.3.1 sets TR1M
|
||||
// when the RP-DATA is transferred.
|
||||
inline constexpr double SmsSendTimeout = 128.0;
|
||||
inline constexpr double SmsReportTimeout = 130.0;
|
||||
// What the bus hears: `sent` once the service centre has accepted
|
||||
// every segment, `failed` with the reason; a status report's word
|
||||
// after `sent` (StatusReportBook, SmsWordOrder, which also has the one
|
||||
// failure posted as `sent`).
|
||||
inline constexpr std::string_view SmsStateSent = "sent";
|
||||
|
|
@ -1108,14 +1360,43 @@ export namespace imsd::engine {
|
|||
std::optional<Word> held_;
|
||||
};
|
||||
|
||||
// A segment's MESSAGEs at most: the first and one repeat. TS 23.040
|
||||
// 9.2.3.6 has the MS repeat an SMS-SUBMIT that got no answer "in the
|
||||
// range 1 to 3" times and leaves the number to the implementation.
|
||||
inline constexpr std::size_t SmsAttempts = 2;
|
||||
|
||||
// One short message of ours on its way to the service centre, segment
|
||||
// by segment: the MESSAGE with the segment's RP-DATA, its final, the
|
||||
// submit report, then the next segment. RP-MR and TP-MR count up from
|
||||
// the values the shell hands over (TS 23.040 9.2.3.6, 9.2.3.24.1; the
|
||||
// shell keeps the counters across messages). No retransmission: an
|
||||
// unanswered MESSAGE or a report that never comes fails the message
|
||||
// (TS 23.040 9.2.3.6's automatic repeat with TP-RD is not done) and
|
||||
// the bus hears why.
|
||||
// shell keeps the counters across messages).
|
||||
//
|
||||
// A segment that gets no answer, or an RP-ERROR with cause 41, is sent
|
||||
// once more, as 9.2.3.6 has it: "In the case where no response or an
|
||||
// RP-ERROR with an appropriate cause value (see 3GPP TS 24.011 [13]) is
|
||||
// received in response to an SMS-SUBMIT, then the MS shall automatically
|
||||
// repeat the SMS-SUBMIT but must use the same TP-MR value and set the
|
||||
// TP-RD bit to 1". Here that is: the final's wait or the report's run
|
||||
// out; a final of 408 or 504 — no response in time, the server's own
|
||||
// (RFC 3261 21.4.9) or one it waited for (21.5.5), so what became of
|
||||
// the MESSAGE past it is as unknown as with no final; an RP-ERROR whose
|
||||
// cause invites another attempt at once (RpCauseIsTemporary). The
|
||||
// repeat is a MESSAGE of its own — its Call-ID, the next RP-MR — with
|
||||
// the same SMS-SUBMIT, TP-RD set. A service centre that has the first
|
||||
// "should discard" the repeat and answer it with an RP-ERROR whose
|
||||
// TP-FCS is the duplicate rejection (0xC5), or with an RP-ACK (9.2.3.6
|
||||
// again): either ends the segment as accepted — the rejection only
|
||||
// where no RP-ERROR has refused the first attempt by then — and so
|
||||
// does the first attempt's own RP-ACK when it comes after the repeat
|
||||
// went out; its RP-ERROR then leaves the segment to the repeat's
|
||||
// answer, and one that comes once that answer has ended the segment
|
||||
// changes nothing (OnSmsMessage logs it). Any
|
||||
// other refusal — a final that is neither of the two, an RP-ERROR with
|
||||
// another cause, a flow that is down — fails the message at once, and
|
||||
// so does whatever ends the repeat short of an acceptance; the reason
|
||||
// then names the first attempt's end as well. Not done of the clause's
|
||||
// repeat: it cannot be switched off, and a failed message is not kept
|
||||
// for the user to send again under its TP-MR.
|
||||
class SmsOutbound {
|
||||
public:
|
||||
struct Params {
|
||||
|
|
@ -1131,11 +1412,12 @@ export namespace imsd::engine {
|
|||
};
|
||||
enum class Phase { Idle, Sending, AwaitingReport, Done };
|
||||
|
||||
SmsOutbound(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string id, Params p)
|
||||
: ctx_(ctx), rng_(rng), id_(std::move(id)), p_(std::move(p)) {}
|
||||
// `submitted`: where each MESSAGE this message goes out in is put on record
|
||||
SmsOutbound(const imsd::msg::Context& ctx, imsd::util::Rng& rng, RecentSubmissions& submitted, std::string id, Params p)
|
||||
: ctx_(ctx), rng_(rng), submitted_(submitted), id_(std::move(id)), p_(std::move(p)), nextRpMr_(p_.rpMr) {}
|
||||
|
||||
const std::string& Id() const { return id_; }
|
||||
// the segment in flight's MESSAGE (empty before the first went out)
|
||||
// the MESSAGE in flight — the segment in flight's latest (empty before the first went out)
|
||||
const std::string& CallId() const { return callid_; }
|
||||
Phase State() const { return phase_; }
|
||||
bool Done() const { return phase_ == Phase::Done; }
|
||||
|
|
@ -1145,6 +1427,11 @@ export namespace imsd::engine {
|
|||
// later status report to this message
|
||||
const std::vector<std::uint8_t>& TpMrs() const { return tpMrs_; }
|
||||
std::size_t Segments() const { return tpdus_.size(); }
|
||||
// The RP-MR after the last this message used — every MESSAGE built
|
||||
// for it took the next one from `rpMr` on, one the flow could not
|
||||
// send as well: where the shell's counter goes on once the message
|
||||
// has ended.
|
||||
std::uint8_t NextRpMr() const { return nextRpMr_; }
|
||||
|
||||
// Builds the segments and sends the first. A destination that is
|
||||
// no number, or a text past 255 segments, fails the message at once.
|
||||
|
|
@ -1163,13 +1450,16 @@ export namespace imsd::engine {
|
|||
out.push_back(Fail("no service centre (none from SMSC= or EF_SMSP)"));
|
||||
return out;
|
||||
}
|
||||
s.rejectDuplicates = true; // each segment's repeat: the same SMS-SUBMIT with TP-RD set
|
||||
repeats_ = imsd::sms::BuildSubmits(s, p_.text, p_.concatRef);
|
||||
for (std::size_t i = 0; i < tpdus_.size(); i++) tpMrs_.push_back(static_cast<std::uint8_t>((p_.tpMr + i) & 0xFF));
|
||||
SendSegment(out, now);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The segment in flight's MESSAGE: its final is matched by Call-ID
|
||||
// and CSeq.
|
||||
// The MESSAGE in flight: its final is matched by Call-ID and CSeq.
|
||||
// The first attempt's final, come after the repeat went out, is
|
||||
// nobody's.
|
||||
bool OwnsResponse(std::string_view msg) const {
|
||||
return phase_ == Phase::Sending && imsd::sip::ResponseOf(msg, callid_, "1 MESSAGE");
|
||||
}
|
||||
|
|
@ -1182,8 +1472,13 @@ export namespace imsd::engine {
|
|||
return out;
|
||||
}
|
||||
if (status >= 300) {
|
||||
std::string why = std::format("segment {}/{} refused: {}", seg_ + 1, tpdus_.size(), imsd::sip::RefusalSummary(msg));
|
||||
if (status == 408 || status == 504) { // Request Timeout, Server Time-out: no word on the MESSAGE's fate
|
||||
EndAttempt(out, now, std::move(why));
|
||||
return out;
|
||||
}
|
||||
phase_ = Phase::Done;
|
||||
out.push_back(Fail(std::format("segment {}/{} refused: {}", seg_ + 1, tpdus_.size(), imsd::sip::RefusalSummary(msg))));
|
||||
out.push_back(Fail(std::move(why)));
|
||||
return out;
|
||||
}
|
||||
phase_ = Phase::AwaitingReport;
|
||||
|
|
@ -1192,57 +1487,79 @@ export namespace imsd::engine {
|
|||
return out;
|
||||
}
|
||||
|
||||
// Whether an RP-ACK/RP-ERROR the IP-SM-GW sent is this segment's:
|
||||
// In-Reply-To names our MESSAGE (TS 24.341 5.3.1.2), or — from an
|
||||
// IP-SM-GW that sends none — the RP-MR is the one in flight. A
|
||||
// report arriving before the MESSAGE's own final (the IP-SM-GW's
|
||||
// order is its own) is taken as well.
|
||||
bool OwnsReport(std::string_view inReplyTo, std::optional<std::uint8_t> rpMr) const {
|
||||
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return false;
|
||||
if (!inReplyTo.empty()) { // a list of Call-IDs (RFC 3261 20.21): ours among them
|
||||
for (auto part : std::views::split(inReplyTo, ','))
|
||||
if (imsd::sip::Trim(std::string_view(part.begin(), part.end())) == callid_) return true;
|
||||
return false;
|
||||
// Which of the segment in flight's MESSAGEs an RP-ACK/RP-ERROR the
|
||||
// IP-SM-GW sent answers — 0 the first, 1 its repeat — or none of
|
||||
// them: by In-Reply-To when the report has one (TS 24.341 5.3.1.2;
|
||||
// the later MESSAGE when it lists both), else — from an IP-SM-GW
|
||||
// that sends none — by RP-MR. A report arriving before the
|
||||
// MESSAGE's own final (the IP-SM-GW's order is its own) is taken as
|
||||
// well.
|
||||
std::optional<std::size_t> ReportAttempt(std::string_view inReplyTo, std::optional<std::uint8_t> rpMr) const {
|
||||
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return std::nullopt;
|
||||
const std::vector<std::string_view> named = InReplyToCallIds(inReplyTo); // a list of Call-IDs (RFC 3261 20.21): ours among them
|
||||
for (std::size_t k = attempts_.size(); k-- > 0;) {
|
||||
if (!inReplyTo.empty() ? std::ranges::contains(named, std::string_view(attempts_[k].callid)) : rpMr && *rpMr == attempts_[k].rpMr) return k;
|
||||
}
|
||||
return rpMr && *rpMr == CurrentRpMr();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// The submit report for the segment in flight: an RP-ACK moves to
|
||||
// the next segment, or ends the message as sent; an RP-ERROR fails
|
||||
// it with its cause. The shell answers the report's MESSAGE
|
||||
// itself.
|
||||
std::vector<SmsAction> OnReport(const imsd::sms::Rp& rp, double now) {
|
||||
// The submit report for the segment in flight, answering its
|
||||
// MESSAGE number `attempt` (ReportAttempt; none given: the one in
|
||||
// flight). An RP-ACK to either attempt moves to the next segment,
|
||||
// or ends the message as sent. An RP-ERROR to the first attempt,
|
||||
// come after its repeat went out, changes what is known of that
|
||||
// attempt and nothing else: the repeat's answer ends the segment.
|
||||
// An RP-ERROR to the attempt in flight: the duplicate rejection
|
||||
// (TP-FCS 0xC5) of a repeat whose first attempt no RP-ERROR has
|
||||
// refused so far is taken for that attempt accepted, whatever RP
|
||||
// cause comes with it — 9.2.3.6 has the service centre discard a
|
||||
// repeat of what it has —; a cause that
|
||||
// invites another attempt at once (RpCauseIsTemporary) ends the
|
||||
// attempt — the repeat follows, or the message has failed —; any
|
||||
// other fails the message with its cause. The shell answers the
|
||||
// report's MESSAGE itself.
|
||||
std::vector<SmsAction> OnReport(const imsd::sms::Rp& rp, double now, std::optional<std::size_t> attempt = std::nullopt) {
|
||||
std::vector<SmsAction> out;
|
||||
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return out;
|
||||
const std::size_t inFlight = attempts_.size() - 1;
|
||||
const std::size_t answered = std::min(attempt.value_or(inFlight), inFlight);
|
||||
const bool late = answered < inFlight; // the first attempt's report, after the repeat went out
|
||||
if (rp.type == imsd::sms::RpType::ErrorMt) {
|
||||
std::string why = std::format("segment {}/{} refused by the SC: {}", seg_ + 1, tpdus_.size(), RpErrorWords(rp));
|
||||
if (late) {
|
||||
out.push_back(LogAct(std::format("sms {}: {}, in the first attempt's report, which came after the repeat went out: the repeat's decides", id_, why)));
|
||||
firstRefused_ = true;
|
||||
firstWhy_ = why + ", in a report that came after the repeat went out";
|
||||
return out;
|
||||
}
|
||||
const auto report = imsd::sms::ParseSubmitReport(rp.tpdu, true);
|
||||
if (answered > 0 && !firstRefused_ && report && report->failureCause == imsd::sms::FcsDuplicateRejected) {
|
||||
out.push_back(LogAct(std::format("sms {}: segment {}/{}: the repeat was rejected as a duplicate ({}): the first attempt is taken for accepted", id_, seg_ + 1, tpdus_.size(), RpErrorWords(rp))));
|
||||
Accepted(out, now);
|
||||
return out;
|
||||
}
|
||||
if (imsd::sms::RpCauseIsTemporary(rp.cause.value_or(0))) {
|
||||
firstRefused_ = true;
|
||||
EndAttempt(out, now, std::move(why));
|
||||
return out;
|
||||
}
|
||||
phase_ = Phase::Done;
|
||||
std::string why = std::format("segment {}/{} refused by the SC: RP cause {} ({})", seg_ + 1, tpdus_.size(), rp.cause.value_or(0), imsd::sms::RpCauseText(rp.cause.value_or(0)));
|
||||
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, true); r && r->failureCause)
|
||||
why += std::format(", TP-FCS 0x{:02x} ({})", *r->failureCause, imsd::sms::FailureCauseText(*r->failureCause));
|
||||
out.push_back(Fail(why));
|
||||
out.push_back(Fail(std::move(why)));
|
||||
return out;
|
||||
}
|
||||
if (rp.type != imsd::sms::RpType::AckMt) return out;
|
||||
if (late) out.push_back(LogAct(std::format("sms {}: segment {}/{}: the first attempt's submit report came after the repeat went out: accepted", id_, seg_ + 1, tpdus_.size())));
|
||||
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, false); r && !r->scts.empty()) scts_ = r->scts;
|
||||
seg_++;
|
||||
if (seg_ < tpdus_.size()) { SendSegment(out, now); return out; }
|
||||
phase_ = Phase::Done;
|
||||
deadline_ = 0;
|
||||
out.push_back(StateAct(SmsStateSent, scts_.empty() ? std::format("{} segment(s) accepted by the SC", tpdus_.size()) : std::format("{} segment(s) accepted by the SC at {}", tpdus_.size(), scts_)));
|
||||
Accepted(out, now);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The wait ran out: no final to the MESSAGE, or no submit report.
|
||||
std::vector<SmsAction> OnDeadline() {
|
||||
std::vector<SmsAction> OnDeadline(double now) {
|
||||
std::vector<SmsAction> out;
|
||||
if (phase_ == Phase::Sending) {
|
||||
phase_ = Phase::Done;
|
||||
out.push_back(Fail(std::format("no answer to the MESSAGE of segment {}/{} within {:.0f} s", seg_ + 1, tpdus_.size(), SmsSendTimeout)));
|
||||
} else if (phase_ == Phase::AwaitingReport) {
|
||||
phase_ = Phase::Done;
|
||||
out.push_back(Fail(std::format("no submit report for segment {}/{} within {:.0f} s of the final", seg_ + 1, tpdus_.size(), SmsReportTimeout)));
|
||||
}
|
||||
deadline_ = 0;
|
||||
if (phase_ == Phase::Sending) EndAttempt(out, now, std::format("no answer to the MESSAGE of segment {}/{} within {:.0f} s", seg_ + 1, tpdus_.size(), SmsSendTimeout));
|
||||
else if (phase_ == Phase::AwaitingReport) EndAttempt(out, now, std::format("no submit report for segment {}/{} within {:.0f} s of the final", seg_ + 1, tpdus_.size(), SmsReportTimeout));
|
||||
else deadline_ = 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
|
|
@ -1250,25 +1567,62 @@ export namespace imsd::engine {
|
|||
std::vector<SmsAction> OnSendFailed() {
|
||||
std::vector<SmsAction> out;
|
||||
phase_ = Phase::Done;
|
||||
deadline_ = 0;
|
||||
out.push_back(Fail(std::format("segment {}/{} not sent: the flow to the P-CSCF is down", seg_ + 1, tpdus_.size())));
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::uint8_t CurrentRpMr() const { return static_cast<std::uint8_t>((p_.rpMr + seg_) & 0xFF); }
|
||||
// One MESSAGE the segment in flight went out in.
|
||||
struct Attempt { std::string callid; std::uint8_t rpMr = 0; };
|
||||
|
||||
// The segment in flight as a MESSAGE: the first attempt with the
|
||||
// SMS-SUBMIT as built, the repeat with TP-RD set in it, each under a
|
||||
// Call-ID of its own and the next RP-MR, so a report without
|
||||
// In-Reply-To still tells the two.
|
||||
void SendSegment(std::vector<SmsAction>& out, double now) {
|
||||
const bool repeat = !attempts_.empty();
|
||||
const std::vector<std::uint8_t>& tpdu = repeat ? repeats_[seg_] : tpdus_[seg_];
|
||||
callid_ = std::format("{}@{}", rng_.Token(16), ctx_.local);
|
||||
std::vector<std::uint8_t> rp = imsd::sms::BuildRpData(CurrentRpMr(), p_.scAddress, tpdus_[seg_]);
|
||||
attempts_.push_back({callid_, nextRpMr_++});
|
||||
submitted_.Sent(callid_, id_, seg_ + 1, tpdus_.size(), now);
|
||||
std::vector<std::uint8_t> rp = imsd::sms::BuildRpData(attempts_.back().rpMr, p_.scAddress, tpdu);
|
||||
out.push_back(SmsAction{SmsAction::Type::SendClient, imsd::msg::BuildMessageSms(ctx_, p_.scTarget, callid_, rng_.Token(8), rng_.Token(16), rp)});
|
||||
out.push_back(LogAct(std::format("sms {}: segment {}/{} to {} via {}: MESSAGE sent (RP-MR {}, TP-MR {}, {} bytes)", id_, seg_ + 1, tpdus_.size(), p_.number, p_.scTarget, CurrentRpMr(), tpMrs_[seg_], tpdus_[seg_].size())));
|
||||
out.push_back(LogAct(std::format("sms {}: segment {}/{} to {} via {}: MESSAGE sent{} (RP-MR {}, TP-MR {}{}, {} bytes)", id_, seg_ + 1, tpdus_.size(), p_.number, p_.scTarget, repeat ? " again" : "", attempts_.back().rpMr, tpMrs_[seg_], repeat ? " with TP-RD" : "", tpdu.size())));
|
||||
phase_ = Phase::Sending;
|
||||
deadline_ = now + SmsSendTimeout;
|
||||
}
|
||||
|
||||
// The attempt in flight ended without the service centre's word, or
|
||||
// with RP cause 41 or one read as it (RpCauseIsTemporary): the
|
||||
// repeat when the segment has had none, else the message has failed.
|
||||
void EndAttempt(std::vector<SmsAction>& out, double now, std::string why) {
|
||||
if (attempts_.size() >= SmsAttempts) {
|
||||
phase_ = Phase::Done;
|
||||
out.push_back(Fail(std::move(why)));
|
||||
return;
|
||||
}
|
||||
out.push_back(LogAct(std::format("sms {}: {}; sending the segment again, TP-RD set", id_, why)));
|
||||
firstWhy_ = std::move(why);
|
||||
SendSegment(out, now);
|
||||
}
|
||||
|
||||
// The service centre has the segment in flight: the next one, or
|
||||
// the message is sent.
|
||||
void Accepted(std::vector<SmsAction>& out, double now) {
|
||||
seg_++;
|
||||
attempts_.clear();
|
||||
firstRefused_ = false;
|
||||
if (seg_ < tpdus_.size()) { SendSegment(out, now); return; }
|
||||
phase_ = Phase::Done;
|
||||
deadline_ = 0;
|
||||
out.push_back(StateAct(SmsStateSent, scts_.empty() ? std::format("{} segment(s) accepted by the SC", tpdus_.size()) : std::format("{} segment(s) accepted by the SC at {}", tpdus_.size(), scts_)));
|
||||
}
|
||||
|
||||
// `failed` with the reason; of a segment that was sent again, how
|
||||
// the first attempt ended as well.
|
||||
SmsAction Fail(std::string why) {
|
||||
deadline_ = 0;
|
||||
if (attempts_.size() > 1) why += std::format("; the first attempt: {}", firstWhy_);
|
||||
return StateAct(SmsStateFailed, std::move(why));
|
||||
}
|
||||
SmsAction StateAct(std::string_view state, std::string reason) {
|
||||
|
|
@ -1282,12 +1636,18 @@ export namespace imsd::engine {
|
|||
|
||||
const imsd::msg::Context& ctx_;
|
||||
imsd::util::Rng& rng_;
|
||||
RecentSubmissions& submitted_;
|
||||
std::string id_;
|
||||
Params p_;
|
||||
std::vector<std::vector<std::uint8_t>> tpdus_;
|
||||
std::uint8_t nextRpMr_; // the RP-MR the next MESSAGE takes
|
||||
std::vector<std::vector<std::uint8_t>> tpdus_; // each segment's SMS-SUBMIT
|
||||
std::vector<std::vector<std::uint8_t>> repeats_; // the same with TP-RD set, for a segment's repeat
|
||||
std::vector<std::uint8_t> tpMrs_;
|
||||
std::size_t seg_ = 0;
|
||||
std::string callid_; // the segment in flight's MESSAGE
|
||||
std::vector<Attempt> attempts_; // the MESSAGEs the segment in flight went out in: the first, then its repeat
|
||||
std::string firstWhy_; // how the first attempt ended, once the segment was sent again
|
||||
bool firstRefused_ = false; // an RP-ERROR has answered an attempt of the segment in flight: where a repeat's duplicate rejection reads it, the first
|
||||
std::string callid_; // the MESSAGE in flight
|
||||
std::string scts_; // the SC's time stamp from the last RP-ACK's submit report
|
||||
Phase phase_ = Phase::Idle;
|
||||
double deadline_ = 0;
|
||||
|
|
@ -1470,7 +1830,10 @@ export namespace imsd::engine {
|
|||
// An inbound MESSAGE (TS 24.341 5.3.2.3, 5.3.1.2, 5.3.1.3). An RP-DATA
|
||||
// with an SMS-DELIVER is answered 200, handed to the reassembler and,
|
||||
// whole, to the bus, and acknowledged with an RP-ACK carrying the
|
||||
// SMS-DELIVER-REPORT in a MESSAGE to the IP-SM-GW; one with an
|
||||
// SMS-DELIVER-REPORT in a MESSAGE to the IP-SM-GW — but one of class 2,
|
||||
// which is for the (U)SIM, is refused with an RP-ERROR instead (cause
|
||||
// 111, TP-FCS 0xFF) and goes no further, unless it is a short message
|
||||
// type 0; one with an
|
||||
// SMS-STATUS-REPORT is acknowledged the same way and the report handed
|
||||
// over for the shell to match; one whose TPDU is unusable is
|
||||
// acknowledged with an RP-ERROR (cause 96, TP-FCS "TPDU not supported")
|
||||
|
|
@ -1478,8 +1841,9 @@ export namespace imsd::engine {
|
|||
// else its From; one that gives neither URI gets none, which is logged.
|
||||
// An RP-ACK/RP-ERROR is a submit report: the message in
|
||||
// flight (`outbound`) takes it and the MESSAGE is answered 200; one the
|
||||
// message in flight does not own is answered 488 when its In-Reply-To is
|
||||
// not empty, else 200 and logged. A MESSAGE whose Content-Type
|
||||
// message in flight does not own is answered 200 and logged when its
|
||||
// In-Reply-To names a MESSAGE of ours on record (`submitted`), 488 when
|
||||
// it names none, and 200 and logged when it has no In-Reply-To. A MESSAGE whose Content-Type
|
||||
// does not contain the SMS one, or whose body is no RP message, is
|
||||
// answered 200 and logged (the journal keeps what the 200 acknowledged). While SMS over IP is off (`ctx.smsOverIp`)
|
||||
// every MESSAGE whose Content-Type contains the SMS one is refused
|
||||
|
|
@ -1487,7 +1851,7 @@ export namespace imsd::engine {
|
|||
// and an RP-ACK would count a short message delivered to nobody, a failure lets the IP-SM-GW try the
|
||||
// modem's path (TS 24.341 5.3.3.4.2 NOTE 2) where the network gives the
|
||||
// modem one.
|
||||
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, double now) {
|
||||
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, RecentSubmissions& submitted, double now) {
|
||||
using imsd::sms::RpType;
|
||||
SmsInbound r;
|
||||
const std::string toTag = rng.Token(10); // the To tag for the finals we give this request (RFC 3261 8.2.6.2; BuildResponse adds it unless the To holds `tag=`)
|
||||
|
|
@ -1519,16 +1883,21 @@ export namespace imsd::engine {
|
|||
if (rp.type == RpType::AckMt || rp.type == RpType::ErrorMt) {
|
||||
std::string inReplyTo; // every In-Reply-To row: the rows are one list (RFC 3261 7.3.1)
|
||||
for (std::string_view row : imsd::sip::Headers(message, "In-Reply-To")) inReplyTo.append(inReplyTo.empty() ? "" : ",").append(row);
|
||||
if (outbound && outbound->OwnsReport(inReplyTo, rp.mr)) {
|
||||
r.actions = outbound->OnReport(rp, now);
|
||||
if (const auto attempt = outbound ? outbound->ReportAttempt(inReplyTo, rp.mr) : std::nullopt) {
|
||||
r.actions = outbound->OnReport(rp, now, *attempt);
|
||||
return r;
|
||||
}
|
||||
if (!inReplyTo.empty()) {
|
||||
r.response = imsd::msg::BuildResponse(ctx, message, 488, "Not Acceptable Here", toTag);
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: no MESSAGE of ours in flight; 488", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", inReplyTo)});
|
||||
if (auto ours = submitted.Named(inReplyTo, now)) {
|
||||
// a MESSAGE of ours that is no longer in flight: the 200 stands (TS 24.341 5.3.1.2), and the journal keeps what the report said
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: sms {}'s segment {}/{}, no longer in flight; 200", rp.type == RpType::AckMt ? "RP-ACK" : std::format("RP-ERROR, {}", RpErrorWords(rp)), inReplyTo, ours->id, ours->segment, ours->segments)});
|
||||
return r;
|
||||
}
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}, RP-MR {}) for no message in flight; 200", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", rp.mr)});
|
||||
r.response = imsd::msg::BuildResponse(ctx, message, 488, "Not Acceptable Here", toTag);
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: no MESSAGE of ours on record; 488", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", inReplyTo)});
|
||||
return r;
|
||||
}
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}, RP-MR {}) that no message in flight owns; 200", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", rp.mr)});
|
||||
return r;
|
||||
}
|
||||
// what is left is an RP-DATA: ParseRp gave one of the network's three
|
||||
|
|
@ -1565,6 +1934,24 @@ export namespace imsd::engine {
|
|||
const int total = concat ? d->ud.header.concat->total : 1;
|
||||
const int seq = concat ? d->ud.header.concat->seq : 1;
|
||||
std::string segment = concat ? std::format(", segment {}/{} of set {}", seq, total, d->ud.header.concat->ref) : std::string();
|
||||
if (d->coding.msgClass == 2 && d->pid != imsd::sms::PidShortMessageType0) {
|
||||
// Class 2 is (U)SIM-specific — a (U)SIM data download (TP-PID 0x7F, which TS
|
||||
// 23.040 9.2.3.9 has the ME pass to the (U)SIM), or a message for the card's
|
||||
// EF_SMS: TS 23.038 4 has the MS "ensure that the message has been transferred
|
||||
// to the SMS data field in the (U)SIM before sending an acknowledgement" and
|
||||
// return "protocol error, unspecified" when it "cannot be stored in the (U)SIM
|
||||
// and there is other short message storage available" (the clause excepts a
|
||||
// download for an MS supporting the (U)SIM Application Toolkit; imsd has none).
|
||||
// imsd has no way to the card for either, so an RP-ERROR with that cause is its
|
||||
// answer to both, each segment's on its own: not stored, not handed over — an
|
||||
// RP-ACK would say the card has it. A short message type 0 is no part of this,
|
||||
// whatever its class: 9.2.3.9 has it received "irrespective of whether there is
|
||||
// memory available in the (U)SIM or ME or not", and it goes the way of any
|
||||
// type 0 below (stored and handed over: AGENTS.md §7.9 has that departure).
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message from {} via {} at {}{}: class 2{} ({} bytes), which imsd cannot pass to the (U)SIM: refused", d->from.Number(), sc, d->scts, segment, d->pid == imsd::sms::PidSimDataDownload ? ", a (U)SIM data download" : "", rp.tpdu.size())});
|
||||
report(imsd::sms::BuildRpError(rp.mr, imsd::sms::RpCauseProtocolError, imsd::sms::DeliverReportError(imsd::sms::FcsUnspecified)), "delivery report RP-ERROR");
|
||||
return r;
|
||||
}
|
||||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message from {} via {} at {}{}: {} ({} bytes)", d->from.Number(), sc, d->scts, segment, d->ud.alphabet == imsd::sms::Alphabet::Octet ? "8-bit data" : "text", rp.tpdu.size())});
|
||||
if (auto whole = reassembler.Add(*d, now)) {
|
||||
SmsAction a{SmsAction::Type::Received};
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ rules select — the policies carrying imsd's fingerprint and the reqid-1/2
|
|||
transport-mode ESP states in their direction or on the UE's ims-PDN address,
|
||||
whoever installed them (§12); and `FileNamesAnotherPair`, whether a state
|
||||
file's spi_uc/spi_us name the pair the kernel holds (unknown on either side
|
||||
decides nothing).
|
||||
decides nothing). And `SaPaths` with `OnSaPath`: whether a packet runs on one
|
||||
of the two paths the outbound policies of an SA pair select (§12).
|
||||
|
||||
Pure std C++ (the shell runs the commands and captures the text). Command
|
||||
shapes and the parser are pinned by tests/Ipsec.
|
||||
|
|
@ -66,8 +67,8 @@ export namespace imsd::ipsec {
|
|||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Canonical ealg name: absent is the null cipher (RFC 3329 §2.2), "3des"
|
||||
// (imsd's EALG alias) is des-ede3-cbc. Used on both sides of the
|
||||
// Canonical ealg name: absent is the null cipher (RFC 3329 Appendix A),
|
||||
// "3des" (imsd's EALG alias) is des-ede3-cbc. Used on both sides of the
|
||||
// offer/answer comparison.
|
||||
std::string NormalizeEalg(std::string_view ealg) {
|
||||
if (ealg.empty()) return "null";
|
||||
|
|
@ -82,6 +83,40 @@ export namespace imsd::ipsec {
|
|||
return ealg == "null" || ealg == "aes-cbc" || ealg == "des-ede3-cbc";
|
||||
}
|
||||
|
||||
// The ESP ciphers offered in Security-Client when EALG names none, in
|
||||
// the order offered. The UE announces the IPsec algorithms it supports
|
||||
// (TS 24.229 5.1.1.2.2 d; TS 33.203 7.2), and of the ciphers it must
|
||||
// support (7.1 by TS 33.210 5.3.3: RFC 8221's NULL, AES-CBC and
|
||||
// AES-GCM) these are the two EncArgs can key. Whether the signalling is
|
||||
// encrypted is the P-CSCF's choice (TS 33.203 5.1.3); aes-cbc comes
|
||||
// first for a P-CSCF that goes by the UE's order.
|
||||
std::vector<std::string> DefaultEalgOffer() { return {"aes-cbc", "null"}; }
|
||||
|
||||
// An EALG setting ("aes-cbc, null") read as the ciphers to offer, in the
|
||||
// order written: case-insensitive, spaces and tabs ignored, "3des" for
|
||||
// des-ede3-cbc, a repeat dropped. An element that names no cipher
|
||||
// KnownEalg() has goes to `unknown`, in lower case without its spaces;
|
||||
// an empty element is passed over. A setting that names no cipher gives
|
||||
// DefaultEalgOffer().
|
||||
struct EalgSetting {
|
||||
std::vector<std::string> ciphers; // the offer
|
||||
std::vector<std::string> unknown; // the names passed over
|
||||
};
|
||||
EalgSetting ParseEalgOffer(std::string_view spec) {
|
||||
EalgSetting out;
|
||||
for (auto part : std::views::split(spec, ',')) {
|
||||
std::string n;
|
||||
for (char c : std::string_view(part))
|
||||
if (c != ' ' && c != '\t') n += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
if (n.empty()) continue; // not NormalizeEalg's absent-means-null: an empty element names nothing
|
||||
n = NormalizeEalg(n);
|
||||
std::vector<std::string>& to = KnownEalg(n) ? out.ciphers : out.unknown;
|
||||
if (std::ranges::find(to, n) == to.end()) to.push_back(n);
|
||||
}
|
||||
if (out.ciphers.empty()) out.ciphers = DefaultEalgOffer();
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
// ESP cipher argv triple for `ip xfrm state add ... <enc>`, matching
|
||||
// imscall.setup_sa: aes-cbc keyed with CK; 3DES uses CK||CK[:8] to
|
||||
|
|
@ -146,16 +181,47 @@ export namespace imsd::ipsec {
|
|||
return cmds;
|
||||
}
|
||||
|
||||
// The two paths the outbound policies of an SA pair select
|
||||
// (BuildSetupCommands: reqid 1 from the UE's protected client port to
|
||||
// the P-CSCF's server port, reqid 2 from its protected server port to the
|
||||
// P-CSCF's client port), between the pair's two addresses. The shell
|
||||
// keeps one of the pair it set up without an error or resumed; with no
|
||||
// ports, none.
|
||||
struct SaPaths {
|
||||
std::string local; // the UE's address the pair is on
|
||||
std::string pcscf; // the P-CSCF's
|
||||
int portPs = 0;
|
||||
int portPc = 0;
|
||||
};
|
||||
|
||||
// Whether a packet from [fromHost]:fromPort to [toHost]:toPort runs on
|
||||
// one of the two paths of `p`. Addresses are compared as
|
||||
// imsd::util::CanonicalAddr writes them (an IPv6 address in its RFC 5952
|
||||
// form).
|
||||
inline bool OnSaPath(const SaPaths& p, std::string_view fromHost, int fromPort, std::string_view toHost, int toPort) {
|
||||
const int theirs = fromPort == imsd::util::PortUc ? p.portPs : fromPort == imsd::util::PortUs ? p.portPc : 0;
|
||||
return theirs != 0 && toPort == theirs && imsd::util::CanonicalAddr(fromHost) == imsd::util::CanonicalAddr(p.local) &&
|
||||
imsd::util::CanonicalAddr(toHost) == imsd::util::CanonicalAddr(p.pcscf);
|
||||
}
|
||||
|
||||
// ---- Security-Server (RFC 3329 §2.2) -----------------------------------
|
||||
//
|
||||
// The P-CSCF answers the challenge with the mechanisms it supports, each
|
||||
// with a preference, plus the SPIs and ports it assigned to this
|
||||
// registration. The UE takes the highest-preference mechanism that is
|
||||
// in that list AND that it offered (RFC 3329 §2.3.1, TS 24.229
|
||||
// §5.1.1.5.1, TS 33.203 §7.2); imsd offers exactly one combination
|
||||
// (hmac-sha-1-96 + EALG). The SPIs/ports are per registration, not per
|
||||
// mechanism: they come from whichever entry carries them (O2 UK's
|
||||
// Mavenir core lists six entries and puts them on the one it applied).
|
||||
// registration. RFC 3329 §2.3.1 and TS 24.229 §5.1.1.5.1 have the UE
|
||||
// take the most preferred mechanism it supports; TS 33.203 §7.2 has it
|
||||
// take the first on the P-CSCF's list, the same entry where the list
|
||||
// runs from its highest q down or carries none. imsd looks among the
|
||||
// entries it offered: hmac-sha-1-96 with each cipher of its list (EALG,
|
||||
// DefaultEalgOffer). The SPIs/ports are per registration, not per
|
||||
// mechanism: they come from whichever entry carries them. O2 UK's
|
||||
// Mavenir core lists six entries, in rising q, and puts them on the one
|
||||
// it applied: the sha1 entry without a cipher for a null offer
|
||||
// (2026-09-17), the sha1 entry with aes-cbc, its highest q, for an
|
||||
// aes-cbc offer (2026-09-20). So an entry that alone carries them, when
|
||||
// it is one imsd offered, is taken before the highest q is looked at:
|
||||
// with more than one cipher offered the two can name different
|
||||
// algorithms, with one a different mod or prot.
|
||||
// imsd ≤ 0.3.5 took the first `ealg=` anywhere in the header and
|
||||
// installed 3DES against a P-CSCF expecting the null cipher: every
|
||||
// protected packet was undecryptable to it (alyx, 2026-09-17; journal/ims
|
||||
|
|
@ -255,15 +321,21 @@ export namespace imsd::ipsec {
|
|||
|
||||
// Parse a Security-Server value and select against our offer. Names,
|
||||
// parameter names and alg/ealg/prot/mod values are tokens
|
||||
// (case-insensitive) and come back lower-case. `selected` = the
|
||||
// highest-q ipsec-3gpp mechanism whose alg (absent = the offered one)
|
||||
// and ealg (absent = null) equal what we offered; when none matches,
|
||||
// the highest-q ipsec-3gpp entry carrying spi-s, else port-s, else the
|
||||
// first ipsec-3gpp entry, with offerMatched = false so the caller can
|
||||
// say so. `carrier` = selected when it carries spi-s, else the highest-q
|
||||
// ipsec-3gpp entry that does. nullopt when the value holds no ipsec-3gpp
|
||||
// mechanism at all.
|
||||
std::optional<SecurityServer> ParseSecurityServer(std::string_view value, std::string_view offeredAlg, std::string_view offeredEalg) {
|
||||
// (case-insensitive) and come back lower-case. An entry is one we
|
||||
// offered when it is ipsec-3gpp, its alg (absent = the offered one) is
|
||||
// the offered one and its ealg (absent = null) is among the offered
|
||||
// ciphers. `selected` = the ipsec-3gpp entry carrying spi-s when one
|
||||
// entry alone carries it and it is one we offered (the entry the P-CSCF
|
||||
// marked), else the highest-q entry we offered (ties: the earlier one);
|
||||
// when none matches, the highest-q ipsec-3gpp entry carrying spi-s, else
|
||||
// port-s, else the first ipsec-3gpp entry, with offerMatched = false so
|
||||
// the caller can say so. With one cipher offered the marked entry and
|
||||
// the highest-q offered one name the same algorithms; their mod and prot
|
||||
// can differ, and the marked entry's are the ones taken. `carrier` =
|
||||
// selected when it carries spi-s, else the highest-q ipsec-3gpp entry
|
||||
// that does. nullopt when the value holds no ipsec-3gpp mechanism at
|
||||
// all.
|
||||
std::optional<SecurityServer> ParseSecurityServer(std::string_view value, std::string_view offeredAlg, const std::vector<std::string>& offeredEalgs) {
|
||||
SecurityServer ss;
|
||||
for (std::string_view part : detail::SplitUnquoted(value, ',')) {
|
||||
part = detail::TrimWs(part);
|
||||
|
|
@ -294,13 +366,17 @@ export namespace imsd::ipsec {
|
|||
auto ipsec = [](const SecurityMechanism& m) { return m.name == "ipsec-3gpp"; };
|
||||
auto carries = [&](const SecurityMechanism& m) { return ipsec(m) && m.spiPs.has_value(); };
|
||||
std::string wantAlg = detail::Lower(offeredAlg);
|
||||
std::string wantEalg = NormalizeEalg(detail::Lower(offeredEalg));
|
||||
std::vector<std::string> wantEalgs;
|
||||
for (const std::string& e : offeredEalgs) wantEalgs.push_back(NormalizeEalg(detail::Lower(e)));
|
||||
auto offered = [&](const SecurityMechanism& m) {
|
||||
return ipsec(m) && (m.alg.empty() || m.alg == wantAlg) && NormalizeEalg(m.ealg) == wantEalg;
|
||||
return ipsec(m) && (m.alg.empty() || m.alg == wantAlg) && std::ranges::find(wantEalgs, NormalizeEalg(m.ealg)) != wantEalgs.end();
|
||||
};
|
||||
auto firstIpsec = std::ranges::find_if(ss.mechanisms, ipsec);
|
||||
if (firstIpsec == ss.mechanisms.end()) return std::nullopt;
|
||||
if (auto i = detail::Best(ss.mechanisms, offered)) { ss.selected = *i; ss.offerMatched = true; }
|
||||
std::optional<std::size_t> marked;
|
||||
if (std::ranges::count_if(ss.mechanisms, carries) == 1) marked = static_cast<std::size_t>(std::ranges::find_if(ss.mechanisms, carries) - ss.mechanisms.begin());
|
||||
if (marked && offered(ss.mechanisms[*marked])) { ss.selected = *marked; ss.offerMatched = true; }
|
||||
else if (auto i = detail::Best(ss.mechanisms, offered)) { ss.selected = *i; ss.offerMatched = true; }
|
||||
else if (auto i = detail::Best(ss.mechanisms, carries)) ss.selected = *i;
|
||||
else if (auto i = detail::Best(ss.mechanisms, [&](const SecurityMechanism& m) { return ipsec(m) && m.portPs.has_value(); })) ss.selected = *i;
|
||||
else ss.selected = static_cast<std::size_t>(firstIpsec - ss.mechanisms.begin());
|
||||
|
|
@ -312,7 +388,7 @@ export namespace imsd::ipsec {
|
|||
// What a warm SA in the kernel tells us — enough for a refresh re-REGISTER
|
||||
// to re-bind without re-authenticating.
|
||||
struct ExistingSa {
|
||||
std::string securityServer; // one-mechanism Security-Server value: the resume's Security-Verify when the state file holds no list for this pair
|
||||
std::string securityServer; // one-mechanism Security-Server value, its alg and ealg the pair's own: the resume's Security-Verify when the state file holds no list for this pair
|
||||
int portPs = 0;
|
||||
int portPc = 0;
|
||||
std::uint32_t spiUc = 0; // our inbound client SPI (a reregistration offers a different one)
|
||||
|
|
@ -384,6 +460,22 @@ export namespace imsd::ipsec {
|
|||
if (b.find("dir in") != std::string_view::npos) return ParseDec(TokenAfter(b, "dport ")) == port;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The sec-agree names of a state's algorithms, from the names `ip
|
||||
// xfrm state` prints on its `auth-trunc` and `enc` lines (the
|
||||
// kernel's for what KernelAuth and EncArgs install; the null cipher,
|
||||
// added as cipher_null, prints as ecb(cipher_null)). A state that
|
||||
// prints no such line, or another name, reads as hmac-sha-1-96 and
|
||||
// aes-cbc.
|
||||
inline std::string_view AlgOfState(std::string_view b) {
|
||||
return TokenAfter(b, "auth-trunc ") == "hmac(md5)" ? "hmac-md5-96" : "hmac-sha-1-96";
|
||||
}
|
||||
inline std::string_view EalgOfState(std::string_view b) {
|
||||
std::string_view enc = TokenAfter(b, "enc ");
|
||||
if (enc == "ecb(cipher_null)") return "null";
|
||||
if (enc == "cbc(des3_ede)") return "des-ede3-cbc";
|
||||
return "aes-cbc";
|
||||
}
|
||||
}
|
||||
|
||||
// Reconstruct SA facts from `ip xfrm state` + `ip xfrm policy` text.
|
||||
|
|
@ -391,6 +483,8 @@ export namespace imsd::ipsec {
|
|||
// state: (src==LOCAL,dst==P): reqid1->spiPs reqid2->spiPc
|
||||
// (src==P,dst==LOCAL): reqid1->spiUc reqid2->spiUs
|
||||
// policy: dir out, reqid1->portPs=dport, reqid2->portPc=dport
|
||||
// The state that gives spiPs also gives the algorithms the rebuilt
|
||||
// Security-Server entry names (detail::AlgOfState, EalgOfState).
|
||||
// Addresses are compared in RFC 5952 form on both sides (the kernel prints
|
||||
// that form; PCSCF=/LOCAL= arrive in any spelling), so the spelling in
|
||||
// /etc/imsd.env can no longer hide a registration's SAs.
|
||||
|
|
@ -403,13 +497,15 @@ export namespace imsd::ipsec {
|
|||
bool havePc = false;
|
||||
bool havePortPs = false;
|
||||
bool havePortPc = false;
|
||||
std::string_view alg;
|
||||
std::string_view ealg;
|
||||
for (std::string_view b : detail::SrcBlocks(stateText)) {
|
||||
const std::string src = imsd::util::CanonicalAddr(detail::TokenAfter(b, "src "));
|
||||
const std::string dst = imsd::util::CanonicalAddr(detail::TokenAfter(b, "dst "));
|
||||
auto spi = detail::ParseHex32(detail::TokenAfter(b, "spi "));
|
||||
auto reqid = detail::ParseDec(detail::TokenAfter(b, "reqid "));
|
||||
if (!spi || !reqid) continue;
|
||||
if (src == l && dst == p && *reqid == 1) { sa.spiPs = *spi; havePs = true; }
|
||||
if (src == l && dst == p && *reqid == 1) { sa.spiPs = *spi; havePs = true; alg = detail::AlgOfState(b); ealg = detail::EalgOfState(b); }
|
||||
if (src == l && dst == p && *reqid == 2) { sa.spiPc = *spi; havePc = true; }
|
||||
if (src == p && dst == l && *reqid == 1) sa.spiUc = *spi;
|
||||
if (src == p && dst == l && *reqid == 2) sa.spiUs = *spi;
|
||||
|
|
@ -430,7 +526,7 @@ export namespace imsd::ipsec {
|
|||
else if (*reqid == 2) { sa.portPc = *dport; havePortPc = true; }
|
||||
}
|
||||
if (!(havePs && havePc && havePortPs && havePortPc)) return std::nullopt;
|
||||
sa.securityServer = std::format("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; " "spi-c={}; spi-s={}; port-c={}; port-s={}", sa.spiPc, sa.spiPs, sa.portPc, sa.portPs);
|
||||
sa.securityServer = std::format("ipsec-3gpp; q=0.1; alg={}; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", alg, ealg, sa.spiPc, sa.spiPs, sa.portPc, sa.portPs);
|
||||
return sa;
|
||||
}
|
||||
|
||||
|
|
@ -438,7 +534,10 @@ export namespace imsd::ipsec {
|
|||
// file's list when the entry carrying its SPIs names the SA pair the
|
||||
// kernel holds (a file an attempt the process did not live to record
|
||||
// left behind names another pair), else the one-mechanism entry rebuilt
|
||||
// from the SA — for an empty or unparseable value too.
|
||||
// from the SA — for an empty or unparseable value too. The entry
|
||||
// carrying the SPIs is ParseSecurityServer's carrier under the offer
|
||||
// handed in: the offer decides only where several entries carry SPIs
|
||||
// of their own.
|
||||
struct ResumeSecurityVerify {
|
||||
enum class Source { Stored, NoneStored, OtherSa };
|
||||
Source source = Source::NoneStored;
|
||||
|
|
@ -446,12 +545,12 @@ export namespace imsd::ipsec {
|
|||
std::size_t mechanisms = 0; // of the stored list, when it is used
|
||||
std::optional<std::uint32_t> storedSpiPs; // the stored list's spi-s (OtherSa); nullopt = none parsed
|
||||
};
|
||||
ResumeSecurityVerify ChooseResumeSecurityVerify(std::string_view stored, const ExistingSa& sa, std::string_view offeredEalg) {
|
||||
ResumeSecurityVerify ChooseResumeSecurityVerify(std::string_view stored, const ExistingSa& sa, const std::vector<std::string>& offeredEalgs) {
|
||||
ResumeSecurityVerify r;
|
||||
r.value = sa.securityServer;
|
||||
if (stored.empty()) return r;
|
||||
r.source = ResumeSecurityVerify::Source::OtherSa;
|
||||
if (auto parsed = ParseSecurityServer(stored, "hmac-sha-1-96", offeredEalg)) {
|
||||
if (auto parsed = ParseSecurityServer(stored, "hmac-sha-1-96", offeredEalgs)) {
|
||||
const SecurityMechanism& c = parsed->Carrier();
|
||||
r.storedSpiPs = c.spiPs;
|
||||
if (c.spiPc == sa.spiPc && c.spiPs == sa.spiPs && c.portPc == sa.portPc && c.portPs == sa.portPs) {
|
||||
|
|
|
|||
|
|
@ -5,19 +5,23 @@
|
|||
Imsd:Messages — the SIP request/response text the engine puts on the wire.
|
||||
|
||||
Every VoLTE message the daemon sends is assembled here from an explicit
|
||||
context and the per-request variables (tags, branches, CSeq) so the builders
|
||||
context and the per-request variables so the builders
|
||||
are pure functions with no hidden state: the engine owns the dialog bookkeeping
|
||||
and the transport owns the socket, this module only formats bytes. That makes
|
||||
and the transport owns the socket (and takes the P-Access-Network-Info line
|
||||
out of an answer the server ports send on neither path of the SA pair on
|
||||
record), this module only formats bytes. That makes
|
||||
each message byte-pinnable — tests/Messages compares a REGISTER pair and an INVITE
|
||||
with strings cross-generated from the Python reference stack, header for header.
|
||||
with strings cross-generated from the Python reference stack, header for header
|
||||
but for the divergences that suite's header names.
|
||||
|
||||
Covers: the unprotected + protected REGISTER and the refresh re-REGISTER
|
||||
(sec-agree, Security-Client/Verify, AKAv1-MD5 Authorization); the INVITE with
|
||||
an AMR-WB SDP offer and IMS MMTEL feature tags; the in-dialog PRACK/BYE and
|
||||
2xx/non-2xx ACK; CANCEL (reusing the INVITE branch); the 200 OK that echoes
|
||||
an inbound request's dialog headers; the finals of the inbound MESSAGE
|
||||
path, each `Via:` line echoed and the To tagged unless it holds `tag=`
|
||||
(RFC 3261 8.2.6.2; long header names only); the UAS responses to an
|
||||
path, each Via row echoed and the To tagged unless it holds `tag=`
|
||||
(RFC 3261 8.2.6.2); the 400 to a request whose datagram ended before its
|
||||
body did (18.3); the UAS responses to an
|
||||
inbound INVITE (100/180/200
|
||||
and rejection finals); and the SIP MESSAGE that carries a short message's
|
||||
RP-DATA to the service centre, or its RP-ACK/RP-ERROR back to the IP-SM-GW
|
||||
|
|
@ -28,6 +32,7 @@ export module Imsd:Messages;
|
|||
import std;
|
||||
import :Util;
|
||||
import :Aka;
|
||||
import :Ipsec;
|
||||
import :Sip;
|
||||
|
||||
export namespace imsd::msg {
|
||||
|
|
@ -46,7 +51,9 @@ export namespace imsd::msg {
|
|||
// of every request we send over it. TCP unless the engine fell back
|
||||
// to, or was told to use, UDP.
|
||||
std::string transport = "TCP";
|
||||
std::string ealgOffer = "aes-cbc";
|
||||
// The ESP ciphers Security-Client offers, in order (canonical names:
|
||||
// imsd::ipsec::ParseEalgOffer).
|
||||
std::vector<std::string> ealgOffer = imsd::ipsec::DefaultEalgOffer();
|
||||
// RFC 7254 IMEI URN for +sip.instance (e.g. urn:gsma:imei:35999999-
|
||||
// 000000-1); empty omits the parameter.
|
||||
std::string instanceId;
|
||||
|
|
@ -72,7 +79,13 @@ export namespace imsd::msg {
|
|||
// P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli
|
||||
// location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header —
|
||||
// never fabricate one: the network reads it to learn which access
|
||||
// the UE is reachable on (stock sends it in every REGISTER/INVITE).
|
||||
// the UE is reachable on.
|
||||
// It rides in every request but the ACKs and the CANCEL and in every
|
||||
// response but a 100 Trying, a CANCEL's and BuildBadRequest's 400:
|
||||
// by TS 24.229 5.1.2A.1.1 and 5.1.2A.2 for a request within a
|
||||
// dialog and for the three kinds of response detail::AccessInfo
|
||||
// names (the 100 and the 400 are left out by imsd's choice), by RFC
|
||||
// 7315 5.7 for the ACKs and the CANCEL.
|
||||
std::string panInfo;
|
||||
// Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS
|
||||
// 24.341 5.3.2.2): the network then delivers terminating short
|
||||
|
|
@ -100,12 +113,18 @@ export namespace imsd::msg {
|
|||
return std::format("Via: SIP/2.0/{} {};branch=z9hG4bK{};rport", transport, imsd::util::HostPort(c.local, port), branch);
|
||||
}
|
||||
|
||||
// Security-Client value: the SPIs and protected ports offered for the SA
|
||||
// pairs this REGISTER may set up — the in-use ones on an initial
|
||||
// registration, new SPIs and a new client port on a reregistration
|
||||
// (TS 24.229 5.1.1.4.2 d; TS 33.203 7.4.0: the server port stays).
|
||||
// Security-Client value: one mechanism per offered cipher, each with the
|
||||
// SPIs and protected ports offered for the SA pairs this REGISTER may
|
||||
// set up — the in-use ones on an initial registration, new SPIs and a
|
||||
// new client port on a reregistration (TS 24.229 5.1.1.4.2 d; TS 33.203
|
||||
// 7.4.0: the server port stays). One pair of SPIs and one of ports for
|
||||
// the whole list (TS 33.203 7.2 NOTE 1, NOTE 2), the mechanisms
|
||||
// comma-separated in one header field (Annex H).
|
||||
inline std::string SecurityClient(const Context& c, std::uint32_t spiUc, std::uint32_t spiUs, int portUc, int portUs) {
|
||||
return std::format("Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", c.ealgOffer, spiUc, spiUs, portUc, portUs);
|
||||
std::string v;
|
||||
for (const std::string& ealg : c.ealgOffer)
|
||||
v += std::format("{}ipsec-3gpp; alg=hmac-sha-1-96; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", v.empty() ? "" : ", ", ealg, spiUc, spiUs, portUc, portUs);
|
||||
return std::format("Security-Client: {}", v);
|
||||
}
|
||||
inline std::string SecurityClient(const Context& c, std::uint32_t spiUc, std::uint32_t spiUs) {
|
||||
return SecurityClient(c, spiUc, spiUs, c.portUc, c.portUs);
|
||||
|
|
@ -213,6 +232,18 @@ export namespace imsd::msg {
|
|||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// The P-Access-Network-Info line of a response with status `code`
|
||||
// to `request`, where the serving cell is known: TS 24.229
|
||||
// 5.1.2A.1.1 and 5.1.2A.2 have a UE insert the header into every
|
||||
// response it sends within a dialog, to a request for a dialog and
|
||||
// to a standalone method, those to a CANCEL excepted. A 100 Trying
|
||||
// gets none, by imsd's choice: a stateful proxy never forwards it
|
||||
// (RFC 3261 21.1.1; AGENTS.md §7.6).
|
||||
inline void AccessInfo(std::vector<std::string>& l, const Context& c, std::string_view request, int code) {
|
||||
if (c.panInfo.empty() || code == 100 || request.starts_with("CANCEL ")) return;
|
||||
l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- REGISTER -------------------------------------------------------
|
||||
|
|
@ -322,7 +353,7 @@ export namespace imsd::msg {
|
|||
|
||||
// ---- call dialog ----------------------------------------------------
|
||||
|
||||
// The dialog identity + routing the engine accumulates for one call.
|
||||
// A dialog as the engine keeps it.
|
||||
// For an outgoing call itag is our From tag and dialogTo is learned from
|
||||
// the responses; for an incoming call itag is the To tag we mint,
|
||||
// dialogTo is the caller's From, and both feed BuildInDialog identically
|
||||
|
|
@ -337,11 +368,18 @@ export namespace imsd::msg {
|
|||
std::optional<std::string> remoteTarget; // remote Contact URI
|
||||
std::string localUri; // our URI in this dialog: the UAS takes the
|
||||
// INVITE's To URI; empty = CallerId(c) (UAC)
|
||||
int invCseq = 1; // our INVITE's sequence number: its CANCEL
|
||||
// and its ACK carry it, a PRACK's RAck
|
||||
// names it
|
||||
int sessionExpires = 1800; // the session interval our INVITE asks for
|
||||
// (RFC 4028 4), in seconds
|
||||
int minSe = 90; // the Min-SE our INVITE carries (RFC 4028 5)
|
||||
};
|
||||
|
||||
// The identity we sign our own requests with: the registered public
|
||||
// identity (P-Associated-URI sip: entry), else the tel: one, and the
|
||||
// IMSI-derived temporary IMPU only before either is learned. 3GPP allows
|
||||
// identity's own (an ISIM's first, or the IMSI-derived temporary IMPU)
|
||||
// only before either is learned. 3GPP allows
|
||||
// the temporary IMPU in REGISTER alone; a P-CSCF that does not overwrite
|
||||
// From shows it to the callee (Telia, 2026-09-01: the reporter's IMSI on
|
||||
// the far phone) and a strict one may reject the request.
|
||||
|
|
@ -370,7 +408,8 @@ export namespace imsd::msg {
|
|||
}
|
||||
|
||||
// INVITE with an AMR-WB SDP offer (passed in, built by Imsd:Sdp). MMTEL
|
||||
// ICSI feature tags + sec-agree + session timers, exactly as imsd._send_invite.
|
||||
// ICSI feature tags + sec-agree + session timers, as imsd._send_invite; the
|
||||
// sequence number, the session interval and its minimum are the dialog's.
|
||||
std::string BuildInvite(const Context& c, const Dialog& d, std::string_view sdp, bool precond) {
|
||||
std::string supported = precond ? "100rel, timer, precondition"
|
||||
: "100rel, timer";
|
||||
|
|
@ -382,7 +421,7 @@ export namespace imsd::msg {
|
|||
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
|
||||
std::format("To: <{}>", d.ruri),
|
||||
std::format("Call-ID: {}", d.callid),
|
||||
"CSeq: 1 INVITE",
|
||||
std::format("CSeq: {} INVITE", d.invCseq),
|
||||
std::format("Contact: <sip:{}@{}>;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)),
|
||||
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER",
|
||||
std::format("Supported: {}", supported),
|
||||
|
|
@ -394,8 +433,8 @@ export namespace imsd::msg {
|
|||
l.push_back(std::format("Security-Verify: {}", c.securityServer));
|
||||
l.push_back("Proxy-Require: sec-agree");
|
||||
l.push_back("Require: sec-agree");
|
||||
l.push_back("Session-Expires: 1800;refresher=uac");
|
||||
l.push_back("Min-SE: 90");
|
||||
l.push_back(std::format("Session-Expires: {};refresher=uac", d.sessionExpires));
|
||||
l.push_back(std::format("Min-SE: {}", d.minSe));
|
||||
l.push_back("Content-Type: application/sdp");
|
||||
l.push_back(std::format("Content-Length: {}", sdp.size()));
|
||||
l.push_back("");
|
||||
|
|
@ -404,6 +443,9 @@ export namespace imsd::msg {
|
|||
|
||||
// An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set.
|
||||
// `extra` lines go after CSeq; an optional body sets Content-Type/Length.
|
||||
// P-Access-Network-Info as in the INVITE (TS 24.229 5.1.2A.1.1,
|
||||
// 5.1.2A.2); the ACKs and the CANCEL, built below, carry none (RFC 7315
|
||||
// 5.7: the header appears in no ACK and no CANCEL).
|
||||
std::string BuildInDialog(const Context& c, const Dialog& d, std::string_view method, int cseq, std::string_view viaBranch, std::span<const std::string> extra = {}, std::string_view body = {}, std::string_view ctype = {}) {
|
||||
std::string target = d.remoteTarget.value_or(d.ruri);
|
||||
std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri));
|
||||
|
|
@ -419,6 +461,7 @@ export namespace imsd::msg {
|
|||
};
|
||||
for (const std::string& e : extra)
|
||||
l.push_back(e);
|
||||
if (!c.panInfo.empty()) l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo));
|
||||
if (!body.empty()) {
|
||||
l.push_back(std::format("Content-Type: {}", ctype));
|
||||
l.push_back(std::format("Content-Length: {}", body.size()));
|
||||
|
|
@ -442,7 +485,7 @@ export namespace imsd::msg {
|
|||
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
|
||||
std::format("To: {}", to),
|
||||
std::format("Call-ID: {}", d.callid),
|
||||
"CSeq: 1 ACK",
|
||||
std::format("CSeq: {} ACK", d.invCseq),
|
||||
"Content-Length: 0",
|
||||
};
|
||||
return std::format("{}\r\n", detail::Join(l));
|
||||
|
|
@ -459,7 +502,7 @@ export namespace imsd::msg {
|
|||
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
|
||||
std::format("To: {}", toHeader),
|
||||
std::format("Call-ID: {}", d.callid),
|
||||
"CSeq: 1 ACK",
|
||||
std::format("CSeq: {} ACK", d.invCseq),
|
||||
"Content-Length: 0",
|
||||
};
|
||||
return std::format("{}\r\n", detail::Join(l));
|
||||
|
|
@ -475,7 +518,7 @@ export namespace imsd::msg {
|
|||
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
|
||||
std::format("To: <{}>", d.ruri),
|
||||
std::format("Call-ID: {}", d.callid),
|
||||
"CSeq: 1 CANCEL",
|
||||
std::format("CSeq: {} CANCEL", d.invCseq),
|
||||
"Content-Length: 0",
|
||||
};
|
||||
return std::format("{}\r\n", detail::Join(l));
|
||||
|
|
@ -489,7 +532,8 @@ export namespace imsd::msg {
|
|||
// half by tagging To (all but 100 Trying, which is hop-by-hop and
|
||||
// tagless). 1xx/2xx carry our Contact (the dialog's remote target for the
|
||||
// caller) and Allow; `extra` appends headers (RSeq, Session-Expires...);
|
||||
// `sdp` turns a 200 into the answer.
|
||||
// P-Access-Network-Info follows them where the cell is known, in all
|
||||
// but a 100; `sdp` turns a 200 into the answer.
|
||||
std::string BuildInviteResponse(const Context& c, std::string_view invite, int code, std::string_view text, std::string_view toTag, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
|
||||
std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
|
||||
for (auto v : imsd::sip::Headers(invite, "Via"))
|
||||
|
|
@ -511,6 +555,7 @@ export namespace imsd::msg {
|
|||
}
|
||||
for (const std::string& e : extra)
|
||||
l.push_back(e);
|
||||
detail::AccessInfo(l, c, invite, code);
|
||||
if (sdp) {
|
||||
l.push_back("Content-Type: application/sdp");
|
||||
l.push_back(std::format("Content-Length: {}", sdp->size()));
|
||||
|
|
@ -522,14 +567,15 @@ export namespace imsd::msg {
|
|||
}
|
||||
|
||||
// The final for an inbound MESSAGE outside a call's dialog — the 200 to one we took, the 480 or
|
||||
// 488 to one we did not: each `Via:` line echoed in order (the response
|
||||
// travels the proxy chain back, RFC 3261 8.2.6.2; long header names only,
|
||||
// not the compact forms), From, To with
|
||||
// 488 to one we did not: each Via row echoed in order (RFC 3261
|
||||
// 8.2.6.2), From, To with
|
||||
// `toTag` added unless the request's To holds `tag=` (8.2.6.2 again),
|
||||
// Call-ID and CSeq; no body. The shell's answers to any other request
|
||||
// Call-ID and CSeq, then P-Access-Network-Info where the cell is known;
|
||||
// no body. The shell's answers to any other request
|
||||
// outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does
|
||||
// not handle) keep BuildResponse200's hop-by-hop shape, as before.
|
||||
std::string BuildResponse(const Context&, std::string_view request, int code, std::string_view text, std::string_view toTag) {
|
||||
// not handle) keep BuildResponse200's hop-by-hop shape, as before,
|
||||
// unless the request is cut short: BuildBadRequest's 400 has this one.
|
||||
std::string BuildResponse(const Context& c, std::string_view request, int code, std::string_view text, std::string_view toTag) {
|
||||
std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
|
||||
for (auto v : imsd::sip::Headers(request, "Via")) l.push_back(std::format("Via: {}", v));
|
||||
if (auto f = imsd::sip::Header(request, "From")) l.push_back(std::format("From: {}", *f));
|
||||
|
|
@ -539,19 +585,38 @@ export namespace imsd::msg {
|
|||
}
|
||||
if (auto ci = imsd::sip::Header(request, "Call-ID")) l.push_back(std::format("Call-ID: {}", *ci));
|
||||
if (auto cs = imsd::sip::Header(request, "CSeq")) l.push_back(std::format("CSeq: {}", *cs));
|
||||
detail::AccessInfo(l, c, request, code);
|
||||
l.push_back("Content-Length: 0");
|
||||
return std::format("{}\r\n", detail::Join(l));
|
||||
}
|
||||
|
||||
// The 400 to a request whose datagram ended before its body did (RFC
|
||||
// 3261 18.3), from the request's header section
|
||||
// (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd
|
||||
// keeps nothing of such a request, so the tag it adds to a To that holds
|
||||
// none is made from the request itself, "in a manner that will generate
|
||||
// the same tag for the same request consistently" (8.2.7), and from
|
||||
// `secret`, which the
|
||||
// caller draws once for the run: the randomness 19.3 asks of a tag. It
|
||||
// is the first sixteen hex digits of the MD5 of the secret and that
|
||||
// header section. The transport answers with it, without the
|
||||
// registration's context: it carries no P-Access-Network-Info.
|
||||
std::string BuildBadRequest(std::string_view head, std::string_view secret) {
|
||||
return BuildResponse({}, head, 400, "Bad Request", imsd::util::Md5::HexDigest(std::format("{}{}", secret, head)).substr(0, 16));
|
||||
}
|
||||
|
||||
// A 200 OK for an inbound request: echo Via/From/To/Call-ID/CSeq in order,
|
||||
// then either an SDP answer (with our Contact) or an empty body.
|
||||
// `extra` appends headers (Session-Expires echo for refreshes...).
|
||||
// `extra` appends headers (Session-Expires echo for refreshes...), and
|
||||
// P-Access-Network-Info follows them where the cell is known, unless
|
||||
// the request is a CANCEL.
|
||||
std::string BuildResponse200(const Context& c, std::string_view request, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
|
||||
std::vector<std::string> l = {"SIP/2.0 200 OK"};
|
||||
for (std::string_view h : {"Via", "From", "To", "Call-ID", "CSeq"})
|
||||
if (auto v = imsd::sip::Header(request, h)) l.push_back(std::format("{}: {}", h, *v));
|
||||
for (const auto& e : extra)
|
||||
l.push_back(e);
|
||||
detail::AccessInfo(l, c, request, 200);
|
||||
if (sdp) {
|
||||
l.push_back(std::format("Contact: <sip:{}@{}>", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)));
|
||||
l.push_back("Content-Type: application/sdp");
|
||||
|
|
|
|||
|
|
@ -6,10 +6,12 @@ Imsd:Sip — SIP message text layer + TCP framing.
|
|||
|
||||
Deliberately a text layer, not a full RFC 3261 parser: the engine works on
|
||||
whole messages as strings and pulls out exactly what it needs (headers,
|
||||
status codes, the granted registration lifetime), which keeps every message
|
||||
loggable and testable verbatim. Edge-case behavior (empty header values,
|
||||
line anchoring, keepalive discards) is pinned by tests/Sip — a change that
|
||||
flips one of those tests is a behavior change, not a cleanup.
|
||||
status codes, the granted registration lifetime, the interval a Min-SE
|
||||
names), which keeps every message loggable and testable as text. A header is asked for by its long name and
|
||||
found under that or its compact form (RFC 3261 7.3.3). Edge-case behavior
|
||||
(empty header values, line anchoring, white space before the colon,
|
||||
keepalive discards) is pinned by tests/Sip — a change that flips one of
|
||||
those tests is a behavior change, not a cleanup.
|
||||
|
||||
Pure std C++ (no GLib).
|
||||
*/
|
||||
|
|
@ -39,6 +41,19 @@ namespace imsd::sip {
|
|||
return s;
|
||||
}
|
||||
|
||||
// Where the piece of `s` that begins at `from` ends: at the first `sep`
|
||||
// outside a quoted string (RFC 3261 25.1: in one, a backslash takes the
|
||||
// next character with it), or at the end of `s`.
|
||||
constexpr std::size_t PieceEnd(std::string_view s, std::size_t from, char sep) {
|
||||
bool quoted = false;
|
||||
for (std::size_t i = from; i < s.size(); i++) {
|
||||
if (quoted && s[i] == '\\') i++;
|
||||
else if (s[i] == '"') quoted = !quoted;
|
||||
else if (!quoted && s[i] == sep) return i;
|
||||
}
|
||||
return s.size();
|
||||
}
|
||||
|
||||
// Iterate the \n-separated lines of the header section (any trailing CR
|
||||
// stays on the line and is stripped by Trim when a value is extracted).
|
||||
// The first empty line after a line of text ends the headers (RFC 3261
|
||||
|
|
@ -64,22 +79,53 @@ namespace imsd::sip {
|
|||
}
|
||||
}
|
||||
|
||||
// One "Name: value" match: name anchored at line start (case-insensitive,
|
||||
// per RFC 3261 header names), immediately followed by the colon — no
|
||||
// whitespace before it — and at least one character (even just the CR)
|
||||
// after it. A bare "Name:\r" line matches with value ""; a "Name:" that
|
||||
// ends the buffer does not match. Matching never crosses the line
|
||||
// boundary: an empty-valued header yields "", NOT the next line's
|
||||
// content (a regex-based implementation whose whitespace class eats the
|
||||
// CRLF gets that wrong — pinned by the "bare header" test).
|
||||
std::optional<std::string_view> MatchHeaderLine(std::string_view line, std::string_view name) {
|
||||
// The one-letter form a header name may be written in (RFC 3261 7.3.3:
|
||||
// "Implementations MUST accept both the long and short forms of each
|
||||
// header name"): the ten RFC 3261 defines (its section 20), and those
|
||||
// of the two extension headers imsd reads that have one — Event (RFC
|
||||
// 6665 7.3) and Session-Expires (RFC 4028 4). 0 for any other name:
|
||||
// whoever starts reading another extension header adds its form here.
|
||||
constexpr char CompactForm(std::string_view name) {
|
||||
constexpr std::pair<std::string_view, char> Forms[] = {
|
||||
{"Call-ID", 'i'}, {"Contact", 'm'}, {"Content-Encoding", 'e'}, {"Content-Length", 'l'},
|
||||
{"Content-Type", 'c'}, {"From", 'f'}, {"Subject", 's'}, {"Supported", 'k'}, {"To", 't'},
|
||||
{"Via", 'v'}, {"Event", 'o'}, {"Session-Expires", 'x'},
|
||||
};
|
||||
for (const auto& [longForm, letter] : Forms)
|
||||
if (name.size() == longForm.size() && IEqualsPrefix(name, longForm)) return letter;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The value of a line that begins with the field name `name`: the name
|
||||
// anchored at line start (case-insensitive, per RFC 3261 header names),
|
||||
// then spaces or tabs, or none, then the colon (RFC 3261 25.1's HCOLON:
|
||||
// "Subject : lunch" is 7.3.1's example) and at least one
|
||||
// character (even just the CR) after it. A bare "Name:\r" line matches
|
||||
// with value ""; a "Name:" that ends the buffer does not match.
|
||||
// Matching never crosses the line boundary: an empty-valued header
|
||||
// yields "", NOT the next line's content (a regex-based implementation
|
||||
// whose whitespace class eats the CRLF gets that wrong — pinned by the
|
||||
// "bare header" test). A value folded onto further lines (7.3.1) is
|
||||
// one line by the time a received message is read here: the framers
|
||||
// unfold its header section (Unfolded).
|
||||
std::optional<std::string_view> ValueOfField(std::string_view line, std::string_view name) {
|
||||
if (!IEqualsPrefix(line, name)) return std::nullopt;
|
||||
if (line.size() <= name.size() || line[name.size()] != ':') return std::nullopt;
|
||||
std::string_view rest = line.substr(name.size() + 1);
|
||||
std::size_t colon = name.size();
|
||||
while (colon < line.size() && (line[colon] == ' ' || line[colon] == '\t')) colon++;
|
||||
if (colon >= line.size() || line[colon] != ':') return std::nullopt;
|
||||
std::string_view rest = line.substr(colon + 1);
|
||||
if (rest.empty()) return std::nullopt;
|
||||
return Trim(rest);
|
||||
}
|
||||
|
||||
// One header line's match to `name`, the long form a reader asks by:
|
||||
// the line carries that name, or its compact form.
|
||||
std::optional<std::string_view> MatchHeaderLine(std::string_view line, std::string_view name) {
|
||||
if (auto v = ValueOfField(line, name)) return v;
|
||||
if (const char letter = CompactForm(name)) return ValueOfField(line, std::string_view(&letter, 1));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// First run of ASCII digits starting at `s`; nullopt if none.
|
||||
std::optional<long> LeadingDigits(std::string_view s) {
|
||||
std::size_t n = 0;
|
||||
|
|
@ -91,6 +137,35 @@ namespace imsd::sip {
|
|||
if (ec != std::errc{}) return std::nullopt;
|
||||
return v;
|
||||
}
|
||||
|
||||
// The length a Content-Length value names: the number its leading
|
||||
// digits spell (RFC 3261 25.1: 1*DIGIT), zeros before it aside; nullopt
|
||||
// where the value begins with no digit. Of a number of more than nine
|
||||
// digits the first nine are read — more than a datagram holds, and
|
||||
// enough that a stream waits for a body that does not come.
|
||||
std::optional<std::size_t> LengthOf(std::string_view v) {
|
||||
std::string_view digits = v.substr(0, v.find_first_not_of("0123456789"));
|
||||
if (digits.empty()) return std::nullopt;
|
||||
while (digits.starts_with('0')) digits.remove_prefix(1);
|
||||
std::size_t n = 0;
|
||||
for (char c : digits.substr(0, 9)) n = n * 10 + static_cast<std::size_t>(c - '0');
|
||||
return n;
|
||||
}
|
||||
|
||||
// A CSeq value as its sequence number and its method (RFC 3261 25.1:
|
||||
// 1*DIGIT LWS Method): the digits the trimmed value begins with, less
|
||||
// the zeros before the number, the spaces or tabs after them, then the
|
||||
// method to the value's end. nullopt where no space or tab follows the
|
||||
// digits.
|
||||
std::optional<std::pair<std::string_view, std::string_view>> CSeqParts(std::string_view v) {
|
||||
v = Trim(v);
|
||||
const std::size_t digits = v.find_first_not_of("0123456789");
|
||||
const std::size_t method = v.find_first_not_of(" \t", digits);
|
||||
if (method == digits) return std::nullopt;
|
||||
std::string_view number = v.substr(0, digits);
|
||||
while (number.starts_with('0')) number.remove_prefix(1);
|
||||
return std::pair{number, v.substr(method)};
|
||||
}
|
||||
}
|
||||
|
||||
export namespace imsd::sip {
|
||||
|
|
@ -118,6 +193,26 @@ export namespace imsd::sip {
|
|||
return out;
|
||||
}
|
||||
|
||||
// `msg` without its `name:` header lines: every line of the header
|
||||
// section on which Headers would find the name, long or compact
|
||||
// (MatchHeaderLine), is left out, and the other lines and the body stay
|
||||
// as they are. For P-Access-Network-Info as the builders write it, one
|
||||
// line with its value, that is the header whole.
|
||||
std::string WithoutHeader(std::string_view msg, std::string_view name) {
|
||||
std::string out;
|
||||
std::size_t kept = 0;
|
||||
ForEachLine(msg, [&](std::string_view line) {
|
||||
if (MatchHeaderLine(line, name)) {
|
||||
const auto at = static_cast<std::size_t>(line.data() - msg.data());
|
||||
out += msg.substr(kept, at - kept);
|
||||
kept = std::min(at + line.size() + 1, msg.size());
|
||||
}
|
||||
return true;
|
||||
});
|
||||
out += msg.substr(kept);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The 3-digit code of a "SIP/2.0 NNN ..." response start-line; nullopt
|
||||
// for requests / anything else. Only matches at the start of the message.
|
||||
std::optional<int> Status(std::string_view msg) {
|
||||
|
|
@ -133,9 +228,16 @@ export namespace imsd::sip {
|
|||
|
||||
// True for a response of the transaction (callid, cseq) — the reply a
|
||||
// wait for that request may judge. A request, another transaction's
|
||||
// response or anything else a socket delivers is not.
|
||||
// response or anything else a socket delivers is not. Two CSeqs are
|
||||
// equal "if the sequence number and the request method are identical"
|
||||
// (RFC 3261 20.16): they are compared so, whatever spaces or tabs part
|
||||
// the two and whatever zeros stand before the number.
|
||||
bool ResponseOf(std::string_view msg, std::string_view callid, std::string_view cseq) {
|
||||
return Status(msg).has_value() && Header(msg, "Call-ID") == callid && Header(msg, "CSeq") == cseq;
|
||||
if (!Status(msg).has_value() || Header(msg, "Call-ID") != callid) return false;
|
||||
const auto theirs = Header(msg, "CSeq");
|
||||
if (!theirs) return false;
|
||||
const auto a = CSeqParts(*theirs), b = CSeqParts(cseq);
|
||||
return a && b && *a == *b;
|
||||
}
|
||||
|
||||
// Retry-After of a response (RFC 3261 20.33), in seconds; nullopt when
|
||||
|
|
@ -146,6 +248,18 @@ export namespace imsd::sip {
|
|||
return LeadingDigits(*v);
|
||||
}
|
||||
|
||||
// The interval a message's Min-SE names (RFC 4028 5: delta-seconds,
|
||||
// then parameters), in seconds: the number its value's leading digits
|
||||
// spell, zeros before it aside. nullopt when the header is absent, its
|
||||
// value begins with no digit, or the number has more than nine digits.
|
||||
std::optional<int> MinSe(std::string_view msg) {
|
||||
auto v = Header(msg, "Min-SE");
|
||||
if (!v) return std::nullopt;
|
||||
const auto n = LeadingDigits(*v);
|
||||
if (!n || *n > 999'999'999) return std::nullopt;
|
||||
return static_cast<int>(*n);
|
||||
}
|
||||
|
||||
// A refused final for the journal: its status line, then the headers
|
||||
// that say who refused and for how long — Retry-After (RFC 3261 20.33),
|
||||
// Warning (20.43: the node's own words), Reason (RFC 3326), Server
|
||||
|
|
@ -223,13 +337,23 @@ export namespace imsd::sip {
|
|||
// the caller should reply to the request's source port instead
|
||||
// (nullopt). Also nullopt when the Via has no explicit port (5060 is
|
||||
// the default, but our P-CSCF flows always carry one). Handles
|
||||
// "[v6]:port" and "host:port" sent-by forms.
|
||||
// "[v6]:port" and "host:port" sent-by forms. rport (RFC 3581) is a
|
||||
// parameter by its name, in any case (7.3.1): not those letters in a
|
||||
// value or in a longer name. The top Via is the first value of the
|
||||
// first Via row: a row may hold a list (7.3.1), and what follows its
|
||||
// first comma outside a quoted string is another hop's.
|
||||
std::optional<int> ViaResponsePort(std::string_view msg) {
|
||||
auto via = Header(msg, "Via");
|
||||
if (!via) return std::nullopt;
|
||||
std::string_view v = *via;
|
||||
std::string_view v = via->substr(0, PieceEnd(*via, 0, ','));
|
||||
if (std::size_t sc = v.find(';'); sc != std::string_view::npos) {
|
||||
if (v.substr(sc).find("rport") != std::string_view::npos) return std::nullopt;
|
||||
for (std::size_t at = sc; at < v.size();) { // each parameter, from its semicolon to the next
|
||||
const std::size_t next = PieceEnd(v, at + 1, ';');
|
||||
std::string_view name = v.substr(at + 1, next - at - 1);
|
||||
name = Trim(name.substr(0, name.find('=')));
|
||||
if (name.size() == 5 && IEqualsPrefix(name, "rport")) return std::nullopt;
|
||||
at = next;
|
||||
}
|
||||
v = v.substr(0, sc);
|
||||
}
|
||||
std::size_t colon;
|
||||
|
|
@ -330,6 +454,29 @@ export namespace imsd::sip {
|
|||
return std::string(uri);
|
||||
}
|
||||
|
||||
// A header section with its folds taken out. RFC 3261 7.3.1: "Header
|
||||
// fields can be extended over multiple lines by preceding each extra
|
||||
// line with at least one SP or horizontal tab (HT). The line break and
|
||||
// the whitespace at the beginning of the next line are treated as a
|
||||
// single SP character." So a line break that a space or a tab follows
|
||||
// becomes, with that white space, one space; every other byte is kept.
|
||||
std::string Unfolded(std::string_view head) {
|
||||
std::string out;
|
||||
out.reserve(head.size());
|
||||
for (std::size_t i = 0; i < head.size();) {
|
||||
const std::string_view next = head.substr(i + 1);
|
||||
if (head[i] == '\n' && (next.starts_with(' ') || next.starts_with('\t'))) {
|
||||
if (out.ends_with('\r')) out.pop_back();
|
||||
out.push_back(' ');
|
||||
const std::size_t text = next.find_first_not_of(" \t");
|
||||
i = text == std::string_view::npos ? head.size() : i + 1 + text;
|
||||
} else {
|
||||
out.push_back(head[i++]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The body of a message: what follows the header terminator, empty
|
||||
// without one.
|
||||
std::string_view Body(std::string_view msg) {
|
||||
|
|
@ -340,25 +487,27 @@ export namespace imsd::sip {
|
|||
// SIP-over-TCP stream framing, transport-free: feed received bytes into
|
||||
// Append(), pull complete messages (headers + Content-Length body) out
|
||||
// of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are
|
||||
// discarded.
|
||||
// discarded. A message comes out with its header section unfolded
|
||||
// (Unfolded) and its body as it came.
|
||||
class FrameBuffer {
|
||||
public:
|
||||
void Append(std::string_view data) { buf_.append(data); }
|
||||
|
||||
// One complete SIP message off the front of the buffer, or nullopt
|
||||
// if more bytes are needed. Content-Length is located with the same
|
||||
// line-anchored matching rules as Header().
|
||||
// line-anchored matching rules as Header(), in the unfolded header
|
||||
// section.
|
||||
std::optional<std::string> TryExtract() {
|
||||
std::size_t keep = buf_.find_first_not_of("\r\n");
|
||||
buf_.erase(0, keep == std::string::npos ? buf_.size() : keep);
|
||||
std::size_t idx = buf_.find("\r\n\r\n");
|
||||
if (idx == std::string::npos) return std::nullopt;
|
||||
std::string_view head = std::string_view(buf_).substr(0, idx);
|
||||
std::string msg = Unfolded(std::string_view(buf_).substr(0, idx));
|
||||
long clen = 0;
|
||||
if (auto v = Header(head, "Content-Length")) clen = LeadingDigits(*v).value_or(0);
|
||||
if (auto v = Header(msg, "Content-Length")) clen = static_cast<long>(LengthOf(*v).value_or(0));
|
||||
std::size_t total = idx + 4 + static_cast<std::size_t>(clen);
|
||||
if (buf_.size() < total) return std::nullopt;
|
||||
std::string msg = buf_.substr(0, total);
|
||||
msg.append(buf_, idx, total - idx);
|
||||
buf_.erase(0, total);
|
||||
return msg;
|
||||
}
|
||||
|
|
@ -376,6 +525,8 @@ export namespace imsd::sip {
|
|||
// fit is a truncated datagram → nullopt with `problem` set; no
|
||||
// Content-Length means the body is the rest of the datagram. A datagram
|
||||
// without a header terminator is malformed → nullopt with `problem`.
|
||||
// The message comes out with its header section unfolded (Unfolded),
|
||||
// where the Content-Length is read, and its body as it came.
|
||||
std::optional<std::string> DatagramMessage(std::string_view d, std::string* problem = nullptr) {
|
||||
std::size_t start = d.find_first_not_of("\r\n");
|
||||
if (start == std::string_view::npos) return std::nullopt;
|
||||
|
|
@ -385,19 +536,52 @@ export namespace imsd::sip {
|
|||
if (problem) *problem = std::format("datagram without a header terminator ({} bytes)", d.size());
|
||||
return std::nullopt;
|
||||
}
|
||||
std::size_t bodyStart = idx + 4;
|
||||
std::size_t body = d.size() - bodyStart;
|
||||
if (auto v = Header(d.substr(0, idx), "Content-Length")) {
|
||||
std::size_t clen = 0; int digits = 0;
|
||||
for (char c : *v) { if (c < '0' || c > '9' || digits == 9) break; clen = clen * 10 + static_cast<std::size_t>(c - '0'); digits++; }
|
||||
if (digits) {
|
||||
std::size_t body = d.size() - (idx + 4);
|
||||
std::string msg = Unfolded(d.substr(0, idx));
|
||||
if (auto v = Header(msg, "Content-Length")) {
|
||||
if (const auto length = LengthOf(*v)) {
|
||||
const std::size_t clen = *length;
|
||||
if (clen > body) {
|
||||
if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body);
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::string(d.substr(0, bodyStart + clen));
|
||||
body = clen;
|
||||
}
|
||||
}
|
||||
return std::string(d);
|
||||
msg.append(d.substr(idx, 4 + body));
|
||||
return msg;
|
||||
}
|
||||
|
||||
// RFC 3261 18.3 of a datagram that ends before its message's body does:
|
||||
// "If the message is a response, it MUST be discarded. If the message
|
||||
// is a request, the element SHOULD generate a 400 (Bad Request)
|
||||
// response." The header section of such a request, unfolded (Unfolded),
|
||||
// with the empty line that ends it and no body — what the 400 is built
|
||||
// from — or nullopt for every other datagram: one whose body is all
|
||||
// there, by its Content-Length or for want of one; one without an end
|
||||
// of headers; one whose first line is no request's; an ACK or a CANCEL.
|
||||
// A request's first line ends with the SIP version (7.1: "Request-Line
|
||||
// = Method SP Request-URI SP SIP-Version CRLF") and a status line
|
||||
// begins with it (7.2), in whatever letter case ("The SIP-Version
|
||||
// string is case-insensitive"): a response is none, and neither are
|
||||
// bytes that are no SIP. imsd keeps nothing of a request it answers so,
|
||||
// and of an element that keeps nothing 8.2.7 says: "A stateless UAS
|
||||
// MUST ignore ACK requests." "A stateless UAS MUST ignore CANCEL
|
||||
// requests."
|
||||
std::optional<std::string> CutShortRequest(std::string_view d) {
|
||||
const std::size_t start = d.find_first_not_of("\r\n");
|
||||
if (start == std::string_view::npos) return std::nullopt;
|
||||
d.remove_prefix(start);
|
||||
const std::size_t idx = d.find("\r\n\r\n");
|
||||
if (idx == std::string_view::npos) return std::nullopt;
|
||||
std::string head = Unfolded(d.substr(0, idx));
|
||||
const auto length = Header(head, "Content-Length").and_then(LengthOf);
|
||||
if (!length || *length <= d.size() - (idx + 4)) return std::nullopt;
|
||||
const std::string_view line = std::string_view(head).substr(0, head.find("\r\n"));
|
||||
const std::string_view last = line.substr(line.rfind(' ') + 1); // of a line without a space, the line
|
||||
if (last.size() != 7 || !IEqualsPrefix(last, "SIP/2.0") || IEqualsPrefix(line, "SIP/")) return std::nullopt;
|
||||
if (line.starts_with("ACK ") || line.starts_with("CANCEL ")) return std::nullopt;
|
||||
head.append("\r\n\r\n");
|
||||
return head;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -408,6 +408,10 @@ export namespace imsd::sms {
|
|||
|
||||
constexpr std::uint8_t DcsGsm7 = 0x00;
|
||||
constexpr std::uint8_t DcsUcs2 = 0x08;
|
||||
// TP-PID "(U)SIM Data download" (TS 23.040 9.2.3.9): with a class 2 coding, a message for the card whole
|
||||
constexpr std::uint8_t PidSimDataDownload = 0x7F;
|
||||
// TP-PID "Short Message Type 0" (9.2.3.9): received whatever memory there is; no message for the card
|
||||
constexpr std::uint8_t PidShortMessageType0 = 0x40;
|
||||
|
||||
// ---- TS 23.040 9.2.3.24: the user-data header -------------------------
|
||||
|
||||
|
|
@ -688,6 +692,10 @@ export namespace imsd::sms {
|
|||
Bytes DeliverReportError(std::uint8_t fcs) { return {0x00, fcs, 0x00}; }
|
||||
constexpr std::uint8_t FcsUnspecified = 0xFF;
|
||||
constexpr std::uint8_t FcsTpduNotSupported = 0xB0;
|
||||
// "SM Rejected-Duplicate SM" (9.2.3.22): the cause 9.2.3.6 has the SC
|
||||
// give an SMS-SUBMIT with TP-RD set whose TP-MR is that of the one
|
||||
// before it
|
||||
constexpr std::uint8_t FcsDuplicateRejected = 0xC5;
|
||||
|
||||
// Segment capacities (9.2.3.24.1): a lone message, and one with the
|
||||
// 8-bit-reference concatenation header (six octets: UDHL + 00 03 r t s).
|
||||
|
|
@ -880,6 +888,25 @@ export namespace imsd::sms {
|
|||
default: return std::format("cause {}", cause & 0x7F);
|
||||
}
|
||||
}
|
||||
// Whether an RP-ERROR to a submission invites another attempt at once.
|
||||
// Of the causes table 8.4's part 1 lists for a mobile originating
|
||||
// transfer, Annex E-2 says so of one, 41 temporary failure: "the Mobile
|
||||
// Station may wish to try another short message transfer attempt
|
||||
// almost immediately" (of 38, network out of order, it says that
|
||||
// "immediately reattempting the short message transfer is not likely
|
||||
// to be successful"); and part 1 has every value it does not list
|
||||
// "treated as cause number 41". So: 41, and any value part 1 does not
|
||||
// list.
|
||||
constexpr bool RpCauseIsTemporary(std::uint8_t cause) {
|
||||
switch (cause & 0x7F) {
|
||||
// part 1's values but 41
|
||||
case 1: case 8: case 10: case 11: case 21: case 27: case 28: case 29: case 30: case 38: case 42: case 47:
|
||||
case 50: case 69: case 81: case 95: case 96: case 97: case 98: case 99: case 111: case 127:
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
constexpr std::uint8_t RpCauseMemoryCapacityExceeded = 22;
|
||||
constexpr std::uint8_t RpCauseInvalidMandatoryInformation = 96;
|
||||
constexpr std::uint8_t RpCauseProtocolError = 111;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
|
||||
/*
|
||||
Imsd:Util — small self-contained primitives the rest of the engine builds on:
|
||||
random SIP tokens, IPv6 detection + host/port formatting, the RFC 5952
|
||||
random SIP tokens, the whole seconds a setting names, IPv6 detection +
|
||||
host/port formatting, the RFC 5952
|
||||
canonical IPv6 text and the address-list parser, hex/base64 decoding, and MD5
|
||||
(RFC 1321). None of the standard library ships these last three, and
|
||||
the IMS AKAv1-MD5 digest (Imsd:Aka) needs MD5 over raw bytes plus base64 to
|
||||
|
|
@ -148,6 +149,18 @@ export namespace imsd::util {
|
|||
return out;
|
||||
}
|
||||
|
||||
// A setting that counts whole seconds (CRLF_KEEPALIVE=): decimal digits
|
||||
// and nothing else. nullopt for anything else — a sign, a unit, a
|
||||
// fraction, a blank, an empty value, a number too large for a long — so
|
||||
// the caller can say the setting was not understood rather than take it
|
||||
// for a number it is not.
|
||||
inline std::optional<long> WholeSeconds(std::string_view s) {
|
||||
if (s.empty() || !std::all_of(s.begin(), s.end(), [](char c) { return c >= '0' && c <= '9'; })) return std::nullopt;
|
||||
long v = 0;
|
||||
if (std::from_chars(s.data(), s.data() + s.size(), v).ec != std::errc{}) return std::nullopt;
|
||||
return v;
|
||||
}
|
||||
|
||||
// A random token of `n` chars over [a-z0-9] — SIP branch/tag/Call-ID
|
||||
// material (the Python rand()). The generator is a parameter so tests can
|
||||
// pin output; the default constructor seeds from random_device.
|
||||
|
|
|
|||
|
|
@ -501,6 +501,18 @@ log "wrote /run/imsd.env: DEV=$IFACE LOCAL=$ADDR PCSCF_DISCOVERED=$DISCOVERED PC
|
|||
# the P-CSCF's TCP SYNs to the protected server port never reached the
|
||||
# listener, so terminating delivery failed and MT calls fell back to CS.
|
||||
# 45061/45062 = imsd's protected client/server ports (kPortUc/kPortUs).
|
||||
#
|
||||
# The ESP packet itself passes the chain first, before the kernel
|
||||
# decapsulates it. With no rule for it, the chain lets it in only as an
|
||||
# answer to a packet of ours ("ct state established": the connection
|
||||
# tracker's entry for a protocol it has no tracker of its own for, 600 s by
|
||||
# default), and drops a request the network starts later than that after
|
||||
# our last packet. ESP that no SA of ours matches is dropped by the kernel
|
||||
# behind the rule, and what an SA decapsulates passes the chain again.
|
||||
#
|
||||
# Each of the two has its own check: a ruleset that carries the port rules
|
||||
# under their comment (fp6-img's 01_imsd.nft) can lack the ESP rule. What
|
||||
# is inserted here is gone when the ruleset is next loaded from its files.
|
||||
# Best-effort: never fail the unit over a missing/foreign firewall.
|
||||
if nft list table inet filter >/dev/null 2>&1; then
|
||||
if ! nft list chain inet filter input | grep -q imsd-protected-ports; then
|
||||
|
|
@ -509,5 +521,10 @@ if nft list table inet filter >/dev/null 2>&1; then
|
|||
log "nftables: opened protected ports 45061-45062 on qmapmux*" ||
|
||||
log "nftables: rule insert failed (continuing)"
|
||||
fi
|
||||
if ! nft list chain inet filter input | grep -q imsd-esp; then
|
||||
nft insert rule inet filter input iifname "qmapmux*" meta l4proto esp accept comment '"imsd-esp"' &&
|
||||
log "nftables: accepting ESP on qmapmux*" ||
|
||||
log "nftables: rule insert failed (continuing)"
|
||||
fi
|
||||
fi
|
||||
exit 0
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@
|
|||
// Imsd:Aka unit tests — the AKAv1-MD5 digest against a vector cross-computed
|
||||
// with the Python reference, identity assembly, the qmicli/mmcli text
|
||||
// parsers (fed real device output), and the AUTHENTICATE APDU build/parse.
|
||||
// Then the ISIM (since 1.2.3): the application of the slot in use out of a
|
||||
// card status, the commands its files are read with, a card's answer and
|
||||
// the command it asks for next, the value an identity file holds, and the
|
||||
// check of the three values before they are an identity.
|
||||
import std;
|
||||
import Imsd;
|
||||
|
||||
|
|
@ -36,6 +40,69 @@ namespace {
|
|||
"\t\t\tA0:00:00:00:87:10:02:FF:31:F0:04:89:0E:00:00:01\n"
|
||||
"\t\tPIN1 state: 'disabled'\n";
|
||||
|
||||
// A card with a USIM and an ISIM in one slot. The two applications,
|
||||
// their states and their AIDs are those the fp6 journal's probe read off
|
||||
// a reporter's card on 2026-11-23 (the modem lists the ISIM `detected`
|
||||
// beside the `ready` USIM); the lines are the ones qmicli prints for an
|
||||
// application, as in the fixture above: the probe prints its own listing
|
||||
// of a card, not qmicli's.
|
||||
constexpr std::string_view CardStatusIsim =
|
||||
"[qrtr://0] Successfully got card status\n"
|
||||
"Provisioning applications:\n"
|
||||
"\tPrimary GW: slot '1', application '1'\n"
|
||||
"Slot [1]:\n"
|
||||
"\tCard state: 'present'\n"
|
||||
"\tUPIN state: 'not-initialized'\n"
|
||||
"\tApplication [1]:\n"
|
||||
"\t\tApplication type: 'usim (2)'\n"
|
||||
"\t\tApplication state: 'ready'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n"
|
||||
"\t\tPIN1 state: 'disabled'\n"
|
||||
"\tApplication [2]:\n"
|
||||
"\t\tApplication type: 'isim (5)'\n"
|
||||
"\t\tApplication state: 'detected'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n"
|
||||
"\t\tPIN1 state: 'disabled'\n"
|
||||
"Slot [2]:\n"
|
||||
"\tCard state: 'absent'\n";
|
||||
|
||||
// The same two applications with the ISIM listed first, and a second
|
||||
// card in slot 2 that has an ISIM of its own (its AID the twelve bytes
|
||||
// of the other card with an ISIM the probe read, 2026-11-21) beside a USIM
|
||||
// that is not ready.
|
||||
constexpr std::string_view CardStatusIsimFirst =
|
||||
"Slot [1]:\n"
|
||||
"\tCard state: 'present'\n"
|
||||
"\tApplication [1]:\n"
|
||||
"\t\tApplication type: 'isim (5)'\n"
|
||||
"\t\tApplication state: 'detected'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n"
|
||||
"\tApplication [2]:\n"
|
||||
"\t\tApplication type: 'usim (2)'\n"
|
||||
"\t\tApplication state: 'ready'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n"
|
||||
"Slot [2]:\n"
|
||||
"\tCard state: 'present'\n"
|
||||
"\tApplication [1]:\n"
|
||||
"\t\tApplication type: 'usim (2)'\n"
|
||||
"\t\tApplication state: 'detected'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:02:FF:49:FF:05:89\n"
|
||||
"\tApplication [2]:\n"
|
||||
"\t\tApplication type: 'isim (5)'\n"
|
||||
"\t\tApplication state: 'ready'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\ta0:00:00:00:87:10:04:ff:49:ff:05:89\n"
|
||||
"\tApplication [3]:\n"
|
||||
"\t\tApplication type: 'isim (5)'\n"
|
||||
"\t\tApplication state: 'detected'\n"
|
||||
"\t\tApplication ID:\n"
|
||||
"\t\t\tA0:00:00:00:87:10:04:FF:49:FF:05:99\n";
|
||||
|
||||
constexpr std::string_view MmcliSim =
|
||||
" Properties | active: yes\n"
|
||||
" | imsi: 001010123456789\n"
|
||||
|
|
@ -72,6 +139,10 @@ int main() {
|
|||
Check(sel && sel->aid == "A0000000871002FF31F004890E000001", "AID uppercased, colons stripped");
|
||||
}
|
||||
Check(!ParseCardStatus("Slot [1]:\n\tCard state: 'absent'\n").has_value(), "no ready USIM -> nullopt");
|
||||
{
|
||||
auto odd = ParseCardStatus("Slot [2]:\n\tCard state: 'absent'\nSlot [x]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n");
|
||||
Check(odd && odd->slot == 0, "a slot line whose number does not parse is slot 0, not the slot before it");
|
||||
}
|
||||
|
||||
// ---- mmcli parsers
|
||||
Check(ParsePrimarySimPath(" SIM | primary sim path: /org/freedesktop/ModemManager1/SIM/0\n") == "/org/freedesktop/ModemManager1/SIM/0", "primary sim path");
|
||||
|
|
@ -98,6 +169,20 @@ int main() {
|
|||
Check(apdu == "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", "APDU byte-exact");
|
||||
Check(BuildGetResponseApdu(0x01, 0x2E) == "01c000002e", "GET RESPONSE APDU");
|
||||
}
|
||||
{
|
||||
// the class byte (TS 102 221 10.1.1, tables 10.3 and 10.4a): the
|
||||
// channel itself for 0 to 3, '4X' with the channel less four for 4
|
||||
// to 19
|
||||
Check(ClassByte(0) == 0x00 && ClassByte(1) == 0x01 && ClassByte(3) == 0x03, "class byte of a standard channel is the channel");
|
||||
Check(ClassByte(4) == 0x40, "class byte of channel 4 is 40");
|
||||
Check(ClassByte(5) == 0x41, "class byte of channel 5 is 41");
|
||||
Check(ClassByte(19) == 0x4F, "class byte of channel 19 is 4f");
|
||||
std::vector<std::uint8_t> rnd(16, 0x11), autn(16, 0x22);
|
||||
Check(BuildAkaApdu(3, rnd, autn).starts_with("0388008122"), "AUTHENTICATE on channel 3 starts 03");
|
||||
Check(BuildAkaApdu(4, rnd, autn).starts_with("4088008122"), "AUTHENTICATE on channel 4 starts 40, not 04");
|
||||
Check(BuildAkaApdu(4, rnd, autn).substr(2) == BuildAkaApdu(1, rnd, autn).substr(2), "the channel changes the class byte and nothing else");
|
||||
Check(BuildGetResponseApdu(7, 0x35) == "43c0000035", "GET RESPONSE on channel 7 starts 43");
|
||||
}
|
||||
{
|
||||
// DB | 08 RES | 10 CK | 10 IK | SW1 SW2(9000)
|
||||
std::vector<std::uint8_t> body = {0xDB, 0x08};
|
||||
|
|
@ -112,6 +197,13 @@ int main() {
|
|||
Check(r && r->res.size() == 8 && r->res[0] == 0xA0, "RES extracted");
|
||||
Check(r && r->ck.size() == 16 && r->ck[0] == 0xC0, "CK extracted");
|
||||
Check(r && r->ik.size() == 16 && r->ik[0] == 0xD0, "IK extracted");
|
||||
// the same answer parted into its data and its status word
|
||||
auto parted = ParseApduAnswer(body);
|
||||
auto r2 = parted ? ParseAkaResponse(*parted) : std::nullopt;
|
||||
Check(r2 && r2->res == r->res && r2->ck == r->ck && r2->ik == r->ik, "an ApduAnswer's AKA result is the raw answer's");
|
||||
std::vector<std::uint8_t> refused = {0x69, 0x82};
|
||||
auto no = ParseApduAnswer(refused);
|
||||
Check(no && !ParseAkaResponse(*no).has_value(), "a status word alone is no AKA result");
|
||||
}
|
||||
{
|
||||
// sync-failure tag (0xDC) or truncated body -> nullopt
|
||||
|
|
@ -123,8 +215,7 @@ int main() {
|
|||
{
|
||||
// P-Access-Network-Info from `mmcli --location-get` (real-device
|
||||
// output shape; TAC/CI zero-padded wider than the 4/7 hex digits
|
||||
// PANI uses). The mcc+mnc+TAC+ECI concatenation was validated
|
||||
// against a stock modem's on-wire PANI; values here are synthetic.
|
||||
// PANI uses). Values here are synthetic.
|
||||
constexpr std::string_view Loc =
|
||||
" --------------------------\n"
|
||||
" 3GPP | operator mcc: 001\n"
|
||||
|
|
@ -144,6 +235,212 @@ int main() {
|
|||
Check(!ParsePani(Zeros).has_value(), "PANI all-zero cell rejected");
|
||||
}
|
||||
|
||||
// ---- the ISIM application of the slot in use
|
||||
{
|
||||
auto sel = ParseCardStatus(CardStatusIsim);
|
||||
Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the ready USIM beside an ISIM is still the USIM read");
|
||||
auto isim = ParseIsimApp(CardStatusIsim, 1);
|
||||
Check(isim.has_value(), "the ISIM of slot 1 is found");
|
||||
Check(isim && isim->aid == "A0000000871004FFFFFFFF8903020000", "its AID, uppercase, colons stripped");
|
||||
Check(isim && isim->state == "detected", "its state is the modem's word, detected");
|
||||
Check(!ParseIsimApp(CardStatusIsim, 2).has_value(), "an absent card in the slot asked for: no ISIM");
|
||||
Check(!ParseIsimApp(CardStatus, 2).has_value(), "a card with a USIM only: no ISIM");
|
||||
Check(!ParseIsimApp(CardStatus, 1).has_value(), "a slot with no card: no ISIM");
|
||||
Check(!ParseIsimApp("", 1).has_value(), "no card status: no ISIM");
|
||||
}
|
||||
{
|
||||
auto sel = ParseCardStatus(CardStatusIsimFirst);
|
||||
Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the USIM listed after an ISIM is read");
|
||||
auto first = ParseIsimApp(CardStatusIsimFirst, 1);
|
||||
Check(first && first->aid == "A0000000871004FFFFFFFF8903020000" && first->state == "detected", "the ISIM listed before the USIM is found");
|
||||
// slot 2's ISIM is not slot 1's: each slot's reader gets its own card's
|
||||
auto other = ParseIsimApp(CardStatusIsimFirst, 2);
|
||||
Check(other && other->aid == "A0000000871004FF49FF0589", "the other slot's ISIM for the other slot: a twelve-byte AID, lower case made upper");
|
||||
Check(other && other->state == "ready", "its state, ready");
|
||||
Check(first && other && first->aid != other->aid, "slot 1 is not answered with slot 2's ISIM");
|
||||
Check(!ParseIsimApp(CardStatusIsimFirst, 3).has_value(), "a slot the status does not list: no ISIM");
|
||||
}
|
||||
{
|
||||
// an application of another type keeps its AID to itself, and an
|
||||
// ISIM whose state line is missing is found with no state
|
||||
auto none = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'csim (4)'\n\t\tApplication state: 'detected'\n\t\tApplication ID:\n\t\t\tA0:00:00:03:43:10:02:FF\n", 1);
|
||||
Check(!none.has_value(), "a CSIM is no ISIM");
|
||||
auto bare = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1);
|
||||
Check(bare && bare->aid == "A0000000871004FF" && bare->state.empty(), "an ISIM without a state line: found, the state empty");
|
||||
// the state of the application before it is not taken for the ISIM's
|
||||
auto after = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n\tApplication [2]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1);
|
||||
Check(after && after->state.empty(), "the USIM's state is not the ISIM's");
|
||||
}
|
||||
|
||||
// ---- the commands a file of the selected application is read with
|
||||
Check(EfImpi == 0x6F02 && EfDomain == 0x6F03 && EfImpu == 0x6F04, "the three identity files' identifiers (TS 31.103 4.2.2 to 4.2.4)");
|
||||
Check(BuildSelectFileApdu(1, EfImpi) == "01a40004026f02", "SELECT EF_IMPI on channel 1");
|
||||
Check(BuildSelectFileApdu(5, EfDomain) == "41a40004026f03", "SELECT EF_DOMAIN on channel 5: the extended class byte");
|
||||
Check(BuildSelectFileApdu(2, 0x00AD) == "02a400040200ad", "a file identifier below 1000 keeps its four digits");
|
||||
Check(BuildReadBinaryApdu(1) == "01b0000000", "READ BINARY from offset 0, Le 00");
|
||||
Check(BuildReadBinaryApdu(4) == "40b0000000", "READ BINARY on channel 4");
|
||||
Check(BuildReadRecordApdu(1, 1) == "01b2010400", "READ RECORD 1, absolute, Le 00");
|
||||
Check(BuildReadRecordApdu(6, 2) == "42b2020400", "READ RECORD 2 on channel 6");
|
||||
|
||||
// ---- a card's answer, and the command it asks for next
|
||||
{
|
||||
std::vector<std::uint8_t> offer = {0x61, 0x19};
|
||||
auto a = ParseApduAnswer(offer);
|
||||
Check(a && a->data.empty() && a->sw1 == 0x61 && a->sw2 == 0x19, "61 19: no data, the status word");
|
||||
Check(a && !a->Ok() && a->Status() == "6119", "61 19 is not 90 00; written 6119");
|
||||
Check(a && Selected(*a), "a SELECT answered 61 XX has selected the file");
|
||||
Check(a && ApduFollowUp(1, "01a40004026f02", *a) == "01c0000019", "61 19 asks for GET RESPONSE with Le 19");
|
||||
Check(a && ApduFollowUp(5, "41b0000000", *a) == "41c0000019", "GET RESPONSE on the command's channel");
|
||||
|
||||
std::vector<std::uint8_t> data = {0x80, 0x03, 'a', '.', 'b', 0x90, 0x00};
|
||||
auto d = ParseApduAnswer(data);
|
||||
Check(d && d->data.size() == 5 && d->data[0] == 0x80 && d->data[4] == 'b', "data before 90 00 is the answer's data");
|
||||
Check(d && d->Ok() && d->Status() == "9000" && Selected(*d), "90 00 is Ok");
|
||||
Check(d && !ApduFollowUp(1, "01b0000000", *d).has_value(), "90 00 with data asks for nothing");
|
||||
|
||||
std::vector<std::uint8_t> len = {0x6C, 0x23};
|
||||
auto l = ParseApduAnswer(len);
|
||||
Check(l && ApduFollowUp(1, "01b0000000", *l) == "01b0000023", "6C 23 to READ BINARY: the command again with Le 23");
|
||||
Check(l && ApduFollowUp(4, "40b2010400", *l) == "40b2010423", "6C 23 to READ RECORD: the command again with Le 23");
|
||||
Check(l && !ApduFollowUp(1, "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", *l).has_value(), "6C XX to a command that carries data: nothing to send again");
|
||||
Check(l && !Selected(*l), "6C XX is no selected file");
|
||||
|
||||
std::vector<std::uint8_t> missing = {0x6A, 0x82};
|
||||
auto m = ParseApduAnswer(missing);
|
||||
Check(m && m->Status() == "6a82" && !m->Ok() && !Selected(*m), "6A 82: file not found, nothing selected");
|
||||
Check(m && !ApduFollowUp(1, "01a40004026f09", *m).has_value(), "an error asks for nothing");
|
||||
|
||||
std::vector<std::uint8_t> more = {0x80, 0x01, 'a', 0x61, 0x05};
|
||||
auto w = ParseApduAnswer(more);
|
||||
Check(w && !ApduFollowUp(1, "01b0000000", *w).has_value(), "data with 61 XX is not followed");
|
||||
|
||||
std::vector<std::uint8_t> one = {0x90};
|
||||
Check(!ParseApduAnswer(one).has_value(), "one byte is no answer");
|
||||
Check(!ParseApduAnswer({}).has_value(), "no bytes is no answer");
|
||||
std::vector<std::uint8_t> sw = {0x90, 0x00};
|
||||
auto e = ParseApduAnswer(sw);
|
||||
Check(e && e->data.empty() && e->Ok(), "90 00 alone: Ok, no data");
|
||||
|
||||
// a card with a proactive command waiting ends a command 91 XX, one
|
||||
// with a data transfer session going on 92 XX
|
||||
std::vector<std::uint8_t> proactive = {0x80, 0x03, 'a', '.', 'b', 0x91, 0x0B};
|
||||
auto p = ParseApduAnswer(proactive);
|
||||
Check(p && p->Ok() && Selected(*p) && HoldsRead(*p) && p->data.size() == 5, "91 XX is a normal ending");
|
||||
std::vector<std::uint8_t> transfer = {0x80, 0x03, 'a', '.', 'b', 0x92, 0x10};
|
||||
auto x = ParseApduAnswer(transfer);
|
||||
Check(x && x->Ok() && Selected(*x) && HoldsRead(*x), "92 XX is a normal ending");
|
||||
std::vector<std::uint8_t> n9001 = {0x90, 0x01}, n9300 = {0x93, 0x00};
|
||||
Check(!ParseApduAnswer(n9001)->Ok(), "90 01 is no normal ending");
|
||||
Check(!ParseApduAnswer(n9300)->Ok(), "93 00 is no normal ending");
|
||||
|
||||
// a read may end 62 82 with all the file holds
|
||||
std::vector<std::uint8_t> eof = {0x80, 0x03, 'a', '.', 'b', 0x62, 0x82};
|
||||
auto f = ParseApduAnswer(eof);
|
||||
Check(f && !f->Ok() && HoldsRead(*f) && !Selected(*f), "data under 62 82 is what a read holds, and no normal ending");
|
||||
Check(d && HoldsRead(*d), "data under 90 00 is what a read holds");
|
||||
std::vector<std::uint8_t> bare6282 = {0x62, 0x82}, d6281 = {0x80, 0x01, 'a', 0x62, 0x81}, d6382 = {0x80, 0x01, 'a', 0x63, 0x82};
|
||||
Check(!HoldsRead(*ParseApduAnswer(bare6282)), "62 82 without data holds nothing");
|
||||
Check(!HoldsRead(*ParseApduAnswer(d6281)), "data under 62 81 is not taken");
|
||||
Check(!HoldsRead(*ParseApduAnswer(d6382)), "data under 63 82 is not taken");
|
||||
Check(m && !HoldsRead(*m), "6A 82 holds nothing");
|
||||
}
|
||||
|
||||
// ---- the value an ISIM identity file holds (the data object with tag 80)
|
||||
{
|
||||
auto bytes = [](std::initializer_list<std::uint8_t> head, std::string_view text, std::size_t pad) {
|
||||
std::vector<std::uint8_t> v(head);
|
||||
v.insert(v.end(), text.begin(), text.end());
|
||||
v.insert(v.end(), pad, 0xFF);
|
||||
return v;
|
||||
};
|
||||
Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 17)) == "ims.example.net", "the value of the object, the file's FF padding after it not read");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 0)) == "ims.example.net", "the value with nothing after it");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x81, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 81 form");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x82, 0x00, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 82 form");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x23}, "001010123456789@private.example.net", 29)) == "001010123456789@private.example.net", "a private identity");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x22}, "sip:001010123456789@ims.example.net", 30)) == "sip:001010123456789@ims.example.ne", "the length decides, not the bytes that follow");
|
||||
std::vector<std::uint8_t> unused(64, 0xFF);
|
||||
Check(!ParseIsimValue(unused).has_value(), "an unused record, all FF: no value");
|
||||
Check(!ParseIsimValue(bytes({0x81, 0x0F}, "ims.example.net", 0)).has_value(), "another tag: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x10}, "ims.example.net", 0)).has_value(), "a length past the data: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x00}, "", 4)).has_value(), "a length of zero: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x83, 0x00, 0x00, 0x0F}, "ims.example.net", 0)).has_value(), "a length form of three bytes: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x81}, "", 0)).has_value(), "an 81 form with no length byte: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x82, 0x00}, "", 0)).has_value(), "an 82 form cut short: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80}, "", 0)).has_value(), "the tag alone: no value");
|
||||
Check(!ParseIsimValue({}).has_value(), "no bytes: no value");
|
||||
Check(ParseIsimValue(bytes({0x80, 0x12}, "ims.example.net", 3)) == "ims.example.net", "FF at the end of the length are padding counted into it");
|
||||
std::vector<std::uint8_t> ffInside = {0x80, 0x05, 'a', '.', 0xFF, '.', 'b'};
|
||||
Check(!ParseIsimValue(ffInside).has_value(), "an FF before the value's end: no value");
|
||||
std::vector<std::uint8_t> ffOnly = {0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xFF};
|
||||
Check(!ParseIsimValue(ffOnly).has_value(), "a length of nothing but FF: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x0F}, "ims example.net", 0)).has_value(), "a blank in the value: no value");
|
||||
Check(!ParseIsimValue(bytes({0x80, 0x11}, "ims.example.net\r\n", 0)).has_value(), "a line break in the value: no value");
|
||||
std::vector<std::uint8_t> nul = {0x80, 0x03, 'a', 0x00, 'b'};
|
||||
Check(!ParseIsimValue(nul).has_value(), "a NUL in the value: no value");
|
||||
std::vector<std::uint8_t> utf8 = {0x80, 0x03, 'a', 0xC3, 0xA9};
|
||||
Check(!ParseIsimValue(utf8).has_value(), "a byte above ASCII in the value: no value");
|
||||
}
|
||||
|
||||
// ---- the identity an ISIM holds
|
||||
{
|
||||
const Identity derived = MakeIdentity("001010123456789", "001", "01");
|
||||
// names unlike the derived ones: a domain of the operator's own
|
||||
auto id = IsimIdentity(derived, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net");
|
||||
Check(id.has_value(), "an ISIM's three values make an identity");
|
||||
Check(id && id->impi == "001010123456789@private.example.net", "the private identity is the card's");
|
||||
Check(id && id->domain == "one.example.net", "the home domain is the card's");
|
||||
Check(id && id->impu == "sip:001010123456789@one.example.net", "the public identity is the card's");
|
||||
Check(id && id->regUri == "sip:one.example.net", "the registration URI is that domain's");
|
||||
Check(id && id->imsi == derived.imsi && id->mcc == derived.mcc && id->mnc == derived.mnc, "the IMSI and the operator stay");
|
||||
// an ISIM that holds the names the IMSI gives: the same identity
|
||||
auto same = IsimIdentity(derived, derived.impi, derived.domain, derived.impu);
|
||||
Check(same && same->impi == derived.impi && same->domain == derived.domain && same->impu == derived.impu && same->regUri == derived.regUri, "the derived names from an ISIM give the derived identity");
|
||||
// a public identity that is a number, a domain with a hyphen and digits
|
||||
Check(IsimIdentity(derived, "user@realm.example", "ims-1.example.net", "sip:+15555550100@ims-1.example.net").has_value(), "a number as the public identity, a hyphen in the domain");
|
||||
|
||||
auto no = [&](std::string_view impi, std::string_view domain, std::string_view impu) { return !IsimIdentity(derived, impi, domain, impu).has_value(); };
|
||||
const std::string_view P = "001010123456789@private.example.net", D = "one.example.net", U = "sip:001010123456789@one.example.net";
|
||||
Check(no("001010123456789", D, U), "a private identity without a realm is refused");
|
||||
Check(no("@private.example.net", D, U), "a private identity without a user is refused");
|
||||
Check(no("001010123456789@", D, U), "a private identity that ends at the @ is refused");
|
||||
Check(no("", D, U), "an empty private identity is refused");
|
||||
Check(no("0010101\"23456789@private.example.net", D, U), "a quote in the private identity is refused (it stands in a quoted string)");
|
||||
Check(no("001010123456789\\@private.example.net", D, U), "a backslash in the private identity is refused");
|
||||
Check(no("001010123456789@private.example.net\r\nVia: x", D, U), "a line break in the private identity is refused");
|
||||
Check(no("0010101 23456789@private.example.net", D, U), "a blank in the private identity is refused");
|
||||
Check(no(P, "", U), "an empty domain is refused");
|
||||
Check(no(P, "one.example.net>", U), "an angle bracket in the domain is refused");
|
||||
Check(no(P, "one_example.net", U), "an underscore in the domain is refused");
|
||||
Check(no(P, "one..example.net", U), "an empty label in the domain is refused");
|
||||
Check(no(P, ".one.example.net", U), "a domain that begins with a dot is refused");
|
||||
Check(no(P, "one.example.net.", U), "a domain that ends with a dot is refused");
|
||||
Check(no(P, "-one.example.net", U), "a label that begins with a hyphen is refused");
|
||||
Check(no(P, "one-.example.net", U), "a label that ends with a hyphen is refused");
|
||||
Check(no(P, "one.example.net-", U), "a domain that ends with a hyphen is refused");
|
||||
Check(no(P, "one.example.net:5060", U), "a port on the domain is refused");
|
||||
Check(no(P, "one.example.net;lr", U), "a parameter on the domain is refused");
|
||||
Check(no(P, "one.example.net\r\nRoute: <sip:x>", U), "a line break in the domain is refused");
|
||||
Check(no(P, D, "tel:+15555550100"), "a tel: public identity is refused");
|
||||
Check(no(P, D, "sip:"), "a public identity that is the scheme alone is refused");
|
||||
Check(no(P, D, "001010123456789@one.example.net"), "a public identity without a scheme is refused");
|
||||
Check(no(P, D, "sip:001010123456789@one.example.net>;tag=x"), "an angle bracket in the public identity is refused (it stands between two)");
|
||||
Check(no(P, D, "sip:001010123456789@one.example.net<sip:x@y"), "an opening angle bracket in the public identity is refused");
|
||||
Check(no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(63, 'd'), U), "a domain of 255 characters is refused");
|
||||
Check(!no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(61, 'd'), U), "a domain of 253 characters is taken");
|
||||
Check(no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(62, 'd'), U), "a domain of 254 characters is refused");
|
||||
Check(no(P, D, "sip:001010123456789@one.example.net\r\nTo: <sip:x>"), "a line break in the public identity is refused");
|
||||
Check(no(P, D, "sip:0010101 23456789@one.example.net"), "a blank in the public identity is refused");
|
||||
Check(no(P, D, "sip:us\xC3\xA9r@one.example.net"), "a byte above ASCII in the public identity is refused");
|
||||
Check(no(P, std::string(64, 'a') + ".example.net", U), "a label of 64 characters in the domain is refused");
|
||||
Check(!no(P, std::string(63, 'a') + ".example.net", U), "a label of 63 characters is taken");
|
||||
Check(no(std::string(300, 'a') + "@x.example", D, U), "a private identity of 300 characters is refused");
|
||||
Check(no(std::string(246, 'a') + "@x.example", D, U), "a private identity of 256 characters is refused");
|
||||
Check(!no(std::string(245, 'a') + "@x.example", D, U), "a private identity of 255 characters is taken");
|
||||
Check(no(P, D, "sip:" + std::string(252, 'a')), "a public identity of 256 characters is refused");
|
||||
Check(!no(P, D, "sip:" + std::string(251, 'a')), "a public identity of 255 characters is taken");
|
||||
}
|
||||
|
||||
if (Failures == 0) std::println("Aka: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -3,9 +3,13 @@
|
|||
|
||||
// Imsd:Ipsec unit tests — the `ip xfrm` setup command sequence (byte-exact
|
||||
// argv), the warm-SA reader, fed `ip xfrm state`/`policy` output in the
|
||||
// exact shape captured from a registered FP6 (addresses/keys synthetic), and
|
||||
// exact shape captured from a registered FP6 (addresses/keys synthetic) and,
|
||||
// for the entry it rebuilds, states in the shape a Linux 7.2 `ip xfrm state`
|
||||
// prints, with its line for each algorithm imsd installs, and
|
||||
// the Security-Server parser, fed the operator lines as captured (O2 UK's
|
||||
// six-mechanism Mavenir shape verbatim, KPN's single mechanism).
|
||||
// six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc
|
||||
// offer; KPN's single mechanism; Odido's), the EALG list, and the two
|
||||
// paths an SA pair's outbound policies select (OnSaPath).
|
||||
import std;
|
||||
import Imsd;
|
||||
|
||||
|
|
@ -77,6 +81,42 @@ int main() {
|
|||
Check(sa && sa->spiPc == 0x0526f2c1u, "spi_pc (UE->P reqid2)");
|
||||
Check(sa && sa->securityServer == "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; " "spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000", "reconstructed Security-Server value");
|
||||
}
|
||||
// the rebuilt entry names the pair's own algorithms: the state towards
|
||||
// the P-CSCF's server port as `ip xfrm state` prints it for each
|
||||
// algorithm imsd installs (the null cipher has no key: a trailing space)
|
||||
{
|
||||
constexpr std::string_view Sha1 = "\tauth-trunc hmac(sha1) 0x00112233445566778899aabbccddeeff 96\n";
|
||||
constexpr std::string_view Md5 = "\tauth-trunc hmac(md5) 0x00112233445566778899aabbccddeeff 96\n";
|
||||
constexpr std::string_view Aes = "\tenc cbc(aes) 0xffeeddccbbaa99887766554433221100\n";
|
||||
constexpr std::string_view Null = "\tenc ecb(cipher_null) \n";
|
||||
constexpr std::string_view Des3 = "\tenc cbc(des3_ede) 0xffeeddccbbaa99887766554433221100ffeeddccbbaa9988\n";
|
||||
// `first` is the reqid-1 state's two lines (the state that gives spi-s),
|
||||
// `second` the reqid-2 state's
|
||||
auto rebuilt = [](std::string_view first, std::string_view second, bool reqid1Listed1st = false) {
|
||||
auto block = [](std::string_view spi, int reqid, std::string_view lines) {
|
||||
return std::format(
|
||||
"src 2001:db8:1111:2222:3333:4444:5555:db43 dst 2001:db8::105\n"
|
||||
"\tproto esp spi {} reqid {} mode transport\n"
|
||||
"\treplay-window 0 \n"
|
||||
"{}"
|
||||
"\tanti-replay context: seq 0x0, oseq 0x0, bitmap 0x00000000\n"
|
||||
"\tsel src ::/0 dst ::/0 \n", spi, reqid, lines);
|
||||
};
|
||||
const std::string one = block("0x0526f2c0", 1, first);
|
||||
const std::string two = block("0x0526f2c1", 2, second);
|
||||
auto sa = ParseExistingSa(reqid1Listed1st ? one + two : two + one, Policy, "2001:db8::105", "2001:db8:1111:2222:3333:4444:5555:db43");
|
||||
return sa ? sa->securityServer : std::string();
|
||||
};
|
||||
auto entry = [](std::string_view alg, std::string_view ealg) { return std::format("ipsec-3gpp; q=0.1; alg={}; ealg={}; spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000", alg, ealg); };
|
||||
auto both = [](std::string_view a, std::string_view b) { return std::string(a) + std::string(b); };
|
||||
Check(rebuilt(both(Sha1, Aes), both(Sha1, Aes)) == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: a sha1 and aes-cbc pair");
|
||||
Check(rebuilt(both(Sha1, Null), both(Sha1, Null)) == entry("hmac-sha-1-96", "null"), "rebuilt entry: a null pair names ealg=null");
|
||||
Check(rebuilt(both(Sha1, Des3), both(Sha1, Des3)) == entry("hmac-sha-1-96", "des-ede3-cbc"), "rebuilt entry: a 3DES pair names des-ede3-cbc");
|
||||
Check(rebuilt(both(Md5, Aes), both(Md5, Aes)) == entry("hmac-md5-96", "aes-cbc"), "rebuilt entry: an md5 pair names hmac-md5-96");
|
||||
Check(rebuilt(both(Md5, Null), both(Sha1, Des3)) == entry("hmac-md5-96", "null") && rebuilt(both(Md5, Null), both(Sha1, Des3), true) == entry("hmac-md5-96", "null"), "rebuilt entry: the algorithms are those of the state that gives spi-s, listed first or last");
|
||||
Check(rebuilt("", both(Md5, Null)) == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: a state that prints no algorithm reads as sha1 and aes-cbc");
|
||||
Check(rebuilt("\tauth-trunc hmac(sha256) 0x00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff 96\n\tenc cbc(camellia) 0xffeeddccbbaa99887766554433221100\n", "") == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: names imsd does not install read as sha1 and aes-cbc");
|
||||
}
|
||||
// the environment's spelling must not matter: upper case, uncompressed,
|
||||
// bracketed — the kernel prints RFC 5952 form and both sides are
|
||||
// canonicalised before the compare
|
||||
|
|
@ -249,7 +289,7 @@ int main() {
|
|||
"ipsec-3gpp;q=0.98;alg=hmac-sha-1-96;mod=trans;ealg=aes-cbc";
|
||||
{
|
||||
// alyx's offer (EALG=null): the entry O2 marked is also the only one matching the offer
|
||||
auto ss = ParseSecurityServer(O2, "hmac-sha-1-96", "null");
|
||||
auto ss = ParseSecurityServer(O2, "hmac-sha-1-96", {"null"});
|
||||
Check(ss.has_value() && ss->mechanisms.size() == 6, "O2/null: six mechanisms");
|
||||
Check(ss && ss->selected == 3 && ss->carrier == 3 && ss->offerMatched, "O2/null: the fourth mechanism (sha1, no ealg, the SPIs) selected, offer matched");
|
||||
if (ss) {
|
||||
|
|
@ -263,44 +303,108 @@ int main() {
|
|||
Check(m.text == "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937015;port-c=6051;port-s=6060", "O2/null: selected text verbatim");
|
||||
Check(ss->mechanisms[1].ealg == "des-ede3-cbc" && !ss->mechanisms[1].spiPs, "O2/null: the 3DES entry is parsed but carries no SPIs");
|
||||
}
|
||||
// the default offer (EALG=aes-cbc): the spec picks sha1+aes (q=0.98); the SPIs stay with the marked entry
|
||||
auto sa = ParseSecurityServer(O2, "hmac-sha-1-96", "aes-cbc");
|
||||
// an offer of aes-cbc alone: sha1+aes (q=0.98) is the offered entry; the SPIs stay with the marked entry
|
||||
auto sa = ParseSecurityServer(O2, "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(sa && sa->selected == 5 && sa->offerMatched, "O2/aes: sha1+aes-cbc (q=0.98) selected for the aes offer");
|
||||
Check(sa && sa->carrier == 3 && sa->Carrier().spiPs == 133937015u && sa->Carrier().portPs == 6060, "O2/aes: SPIs/ports from the entry carrying them");
|
||||
Check(sa && sa->Selected().ealg == "aes-cbc" && sa->Selected().alg == "hmac-sha-1-96", "O2/aes: algorithms from the selected entry");
|
||||
// an offer O2 does not list (3des alias -> des-ede3-cbc): sha1+3des (q=0.96)
|
||||
auto s3 = ParseSecurityServer(O2, "hmac-sha-1-96", "3des");
|
||||
auto s3 = ParseSecurityServer(O2, "hmac-sha-1-96", {"3des"});
|
||||
Check(s3 && s3->selected == 4 && s3->offerMatched && s3->carrier == 3, "O2/3des: the alias matches des-ede3-cbc (q=0.96), SPIs from the marked entry");
|
||||
}
|
||||
// ---- KPN: one mechanism, spaces after the separators, explicit ealg
|
||||
{
|
||||
auto ss = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", "aes-cbc");
|
||||
auto ss = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(ss && ss->mechanisms.size() == 1 && ss->selected == 0 && ss->carrier == 0 && ss->offerMatched, "KPN: single mechanism selected, offer matched");
|
||||
Check(ss && ss->Selected().alg == "hmac-sha-1-96" && ss->Selected().ealg == "aes-cbc", "KPN: alg + ealg");
|
||||
Check(ss && ss->Selected().spiPc == 49889723u && ss->Selected().spiPs == 49889722u && ss->Selected().portPc == 33142 && ss->Selected().portPs == 6000, "KPN: SPIs + ports");
|
||||
Check(ss && ss->Selected().qMilli == 100, "KPN: q=0.1");
|
||||
auto nul = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", "null");
|
||||
auto nul = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", {"null"});
|
||||
Check(nul && nul->Selected().ealg == "null" && nul->offerMatched, "KPN: explicit ealg=null matches the null offer");
|
||||
// the P-CSCF answers a cipher we did not offer: still the only entry, installed as answered, flagged
|
||||
auto other = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", "aes-cbc");
|
||||
auto other = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(other && other->selected == 0 && other->carrier == 0 && !other->offerMatched, "single entry not matching the offer: selected via the spi-s fallback, offerMatched=false");
|
||||
// the fresh-SA throttle answer: spi-s present and zero
|
||||
auto thr = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=1; spi-s=0; port-c=33102; port-s=6000", "hmac-sha-1-96", "aes-cbc");
|
||||
auto thr = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=1; spi-s=0; port-c=33102; port-s=6000", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(thr && thr->Carrier().spiPs.has_value() && *thr->Carrier().spiPs == 0, "KPN throttle: spi-s=0 is present, not absent");
|
||||
// no SPIs anywhere: parsed, nothing to build from
|
||||
auto bare = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null;", "hmac-sha-1-96", "null");
|
||||
auto bare = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null;", "hmac-sha-1-96", {"null"});
|
||||
Check(bare && bare->mechanisms.size() == 1 && bare->offerMatched && !bare->Carrier().spiPs && !bare->Carrier().portPs, "no spi-s: absent, not zero");
|
||||
}
|
||||
// ---- the offer: EALG as a list, the default when it names nothing
|
||||
{
|
||||
using L = std::vector<std::string>;
|
||||
Check(DefaultEalgOffer() == L{"aes-cbc", "null"}, "default offer: aes-cbc, then null");
|
||||
Check(ParseEalgOffer("null").ciphers == L{"null"} && ParseEalgOffer("aes-cbc").ciphers == L{"aes-cbc"}, "EALG: one name is a list of one");
|
||||
Check(ParseEalgOffer("null,aes-cbc").ciphers == L{"null", "aes-cbc"}, "EALG: the order written is the order offered");
|
||||
Check(ParseEalgOffer(" AES-CBC ,\tNull ").ciphers == L{"aes-cbc", "null"}, "EALG: case, spaces and tabs ignored");
|
||||
Check(ParseEalgOffer("3des").ciphers == L{"des-ede3-cbc"} && ParseEalgOffer("des-ede3-cbc,3DES").ciphers == L{"des-ede3-cbc"}, "EALG: 3des is des-ede3-cbc, a repeat dropped");
|
||||
auto mixed = ParseEalgOffer("aes-gcm,null, HMAC-SHA-1-96,aes-gcm");
|
||||
Check(mixed.ciphers == L{"null"} && mixed.unknown == L{"aes-gcm", "hmac-sha-1-96"}, "EALG: a name imsd cannot install goes to unknown, once, in lower case without spaces");
|
||||
Check(ParseEalgOffer("").ciphers == DefaultEalgOffer() && ParseEalgOffer("").unknown.empty() && ParseEalgOffer(" , ,").ciphers == DefaultEalgOffer() && ParseEalgOffer(" , ,").unknown.empty(), "EALG: empty or blank elements name nothing: the default offer");
|
||||
Check(ParseEalgOffer("aes-gcm").ciphers == DefaultEalgOffer() && ParseEalgOffer("aes-gcm").unknown == L{"aes-gcm"}, "EALG: no known name -> the default offer, the name in unknown");
|
||||
Check(ParseEalgOffer("aes-cbc,").ciphers == L{"aes-cbc"} && ParseEalgOffer("aes-cbc,").unknown.empty(), "EALG: an empty element is no name, not the null cipher");
|
||||
}
|
||||
// ---- selection against more than one offered cipher
|
||||
{
|
||||
const std::vector<std::string> both = {"aes-cbc", "null"};
|
||||
// KPN's answer: one entry
|
||||
auto kpn = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", both);
|
||||
Check(kpn && kpn->selected == 0 && kpn->offerMatched && kpn->Selected().ealg == "aes-cbc", "both offered, KPN's aes-cbc entry: selected, offer matched");
|
||||
// Odido's answer to an offer of the null cipher (2026-07-13), verbatim
|
||||
auto odido = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=30890423; spi-s=30890422; port-c=32997; port-s=6000", "hmac-sha-1-96", both);
|
||||
Check(odido && odido->selected == 0 && odido->offerMatched && NormalizeEalg(odido->Selected().ealg) == "null" && odido->Carrier().spiPs == 30890422u, "both offered, Odido's null entry: selected, offer matched");
|
||||
// O2's list as it answered a null offer: the SPIs on sha1/null (q=0.94). With
|
||||
// both ciphers offered that marked entry is taken, not sha1/aes-cbc (q=0.98)
|
||||
auto o2null = ParseSecurityServer(O2, "hmac-sha-1-96", both);
|
||||
Check(o2null && o2null->selected == 3 && o2null->carrier == 3 && o2null->offerMatched, "both offered, O2's list marking sha1/null: the marked entry, not the higher-q sha1/aes-cbc");
|
||||
Check(o2null && NormalizeEalg(o2null->Selected().ealg) == "null" && o2null->Selected().alg == "hmac-sha-1-96", "both offered, O2 marking sha1/null: the selected entry is sha1 with the null cipher");
|
||||
// O2's list as it answered an aes-cbc offer (alyx report 14, 2026-09-20), verbatim: the SPIs on sha1/aes-cbc
|
||||
constexpr std::string_view O2Aes =
|
||||
"ipsec-3gpp;q=0.88;alg=hmac-md5-96;mod=trans,"
|
||||
"ipsec-3gpp;q=0.9;alg=hmac-md5-96;mod=trans;ealg=des-ede3-cbc,"
|
||||
"ipsec-3gpp;q=0.92;alg=hmac-md5-96;mod=trans;ealg=aes-cbc,"
|
||||
"ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans,"
|
||||
"ipsec-3gpp;q=0.96;alg=hmac-sha-1-96;mod=trans;ealg=des-ede3-cbc,"
|
||||
"ipsec-3gpp;q=0.98;alg=hmac-sha-1-96;mod=trans;ealg=aes-cbc;spi-c=53871876;spi-s=58749351;port-c=6058;port-s=6060";
|
||||
auto o2aes = ParseSecurityServer(O2Aes, "hmac-sha-1-96", both);
|
||||
Check(o2aes && o2aes->selected == 5 && o2aes->carrier == 5 && o2aes->offerMatched && o2aes->Selected().ealg == "aes-cbc", "both offered, O2's list marking sha1/aes-cbc: that entry");
|
||||
Check(ParseSecurityServer(O2Aes, "hmac-sha-1-96", {"aes-cbc"})->selected == 5 && ParseSecurityServer(O2Aes, "hmac-sha-1-96", {"null"})->selected == 3, "one cipher offered: the entry of that cipher, marked or not");
|
||||
// the marked entry is one we did not offer (md5): the highest-q offered entry, its SPIs
|
||||
auto md5marked = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc,ipsec-3gpp;q=0.4;alg=hmac-sha-1-96,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", both);
|
||||
Check(md5marked && md5marked->selected == 0 && md5marked->carrier == 2 && md5marked->offerMatched, "both offered, the marked entry not offered: the highest-q offered entry, SPIs from the marked one");
|
||||
// every entry carries the SPIs: nothing is marked — the highest q, without q the first
|
||||
auto listq = ParseSecurityServer("ipsec-3gpp;q=0.4;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", both);
|
||||
Check(listq && listq->selected == 1 && listq->carrier == 1 && listq->offerMatched, "both offered, both entries carry the SPIs: the highest q");
|
||||
auto listfirst = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", both);
|
||||
Check(listfirst && listfirst->selected == 0 && listfirst->offerMatched, "both offered, both entries carry the SPIs, no q: the first on the list");
|
||||
// neither offered cipher listed: the P-CSCF's entry, flagged
|
||||
auto neither = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=des-ede3-cbc; spi-c=1; spi-s=2; port-c=3; port-s=4", "hmac-sha-1-96", both);
|
||||
Check(neither && neither->selected == 0 && !neither->offerMatched, "both offered, a 3DES answer: taken via the spi-s fallback, offerMatched=false");
|
||||
// the marked entry over a higher-q offered one also under one offered cipher (same algorithms, the entry's own mod)
|
||||
auto onecipher = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;mod=tun,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;mod=trans;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(onecipher && onecipher->selected == 1 && onecipher->Selected().mod == "trans", "one cipher offered, two entries of it: the marked one");
|
||||
// the resume's choice under the same offer: O2's stored list, and a list whose two entries carry SPIs of their own
|
||||
ExistingSa sa;
|
||||
sa.spiPc = 129427852u; sa.spiPs = 133937015u; sa.portPc = 6051; sa.portPs = 6060;
|
||||
sa.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=129427852; spi-s=133937015; port-c=6051; port-s=6060";
|
||||
auto rsv = ChooseResumeSecurityVerify(O2, sa, both);
|
||||
Check(rsv.source == ResumeSecurityVerify::Source::Stored && rsv.value == O2 && rsv.mechanisms == 6, "resume, both offered: O2's stored list for the kernel's pair");
|
||||
constexpr std::string_view TwoPairs = "ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8";
|
||||
ExistingSa aesPair;
|
||||
aesPair.spiPc = 5; aesPair.spiPs = 6; aesPair.portPc = 7; aesPair.portPs = 8;
|
||||
Check(ChooseResumeSecurityVerify(TwoPairs, aesPair, {"aes-cbc"}).source == ResumeSecurityVerify::Source::Stored && ChooseResumeSecurityVerify(TwoPairs, aesPair, both).source == ResumeSecurityVerify::Source::OtherSa, "resume: the offer handed in decides which entry's SPIs are held against the kernel's pair");
|
||||
}
|
||||
// ---- the resume's Security-Verify: the stored list only for the SA pair the kernel holds
|
||||
{
|
||||
using Source = ResumeSecurityVerify::Source;
|
||||
ExistingSa sa;
|
||||
sa.spiPc = 129427852u; sa.spiPs = 133937015u; sa.portPc = 6051; sa.portPs = 6060;
|
||||
sa.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=129427852; spi-s=133937015; port-c=6051; port-s=6060";
|
||||
auto ok = ChooseResumeSecurityVerify(O2, sa, "null");
|
||||
auto ok = ChooseResumeSecurityVerify(O2, sa, {"null"});
|
||||
Check(ok.source == Source::Stored && ok.value == O2 && ok.mechanisms == 6, "resume: O2's six-entry list whose carrier is the kernel's pair -> the list verbatim, six mechanisms");
|
||||
auto okAes = ChooseResumeSecurityVerify(O2, sa, "aes-cbc");
|
||||
Check(okAes.source == Source::Stored && okAes.value == O2, "resume: the same under the aes offer (the carrier does not depend on the offer)");
|
||||
auto okAes = ChooseResumeSecurityVerify(O2, sa, {"aes-cbc"});
|
||||
Check(okAes.source == Source::Stored && okAes.value == O2, "resume: the same under the aes offer (O2's list has one carrier)");
|
||||
constexpr std::pair<std::string_view, std::string_view> off[] = {
|
||||
{"spi-c", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427853;spi-s=133937015;port-c=6051;port-s=6060"},
|
||||
{"spi-s", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937016;port-c=6051;port-s=6060"},
|
||||
|
|
@ -308,19 +412,19 @@ int main() {
|
|||
{"port-s", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937015;port-c=6051;port-s=6061"},
|
||||
};
|
||||
for (const auto& [field, text] : off) {
|
||||
auto r = ChooseResumeSecurityVerify(text, sa, "null");
|
||||
auto r = ChooseResumeSecurityVerify(text, sa, {"null"});
|
||||
Check(r.source == Source::OtherSa && r.value == sa.securityServer, std::format("resume: {} off by one -> the rebuilt entry", field));
|
||||
}
|
||||
auto offSpiS = ChooseResumeSecurityVerify(off[1].second, sa, "null");
|
||||
auto offSpiS = ChooseResumeSecurityVerify(off[1].second, sa, {"null"});
|
||||
Check(offSpiS.storedSpiPs && *offSpiS.storedSpiPs == 133937016u, "resume: the stored spi-s is reported for the log line");
|
||||
auto none = ChooseResumeSecurityVerify("", sa, "null");
|
||||
auto none = ChooseResumeSecurityVerify("", sa, {"null"});
|
||||
Check(none.source == Source::NoneStored && none.value == sa.securityServer, "resume: nothing stored -> the rebuilt entry");
|
||||
auto junk = ChooseResumeSecurityVerify("not a list", sa, "null");
|
||||
auto junk = ChooseResumeSecurityVerify("not a list", sa, {"null"});
|
||||
Check(junk.source == Source::OtherSa && junk.value == sa.securityServer && !junk.storedSpiPs, "resume: an unparseable value -> the rebuilt entry, no spi-s to report");
|
||||
ExistingSa kpn;
|
||||
kpn.spiPc = 49889723u; kpn.spiPs = 49889722u; kpn.portPc = 33142; kpn.portPs = 6000;
|
||||
kpn.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000";
|
||||
auto k = ChooseResumeSecurityVerify(kpn.securityServer, kpn, "aes-cbc");
|
||||
auto k = ChooseResumeSecurityVerify(kpn.securityServer, kpn, {"aes-cbc"});
|
||||
Check(k.source == Source::Stored && k.value == kpn.securityServer && k.mechanisms == 1, "resume: KPN's one-entry list for its pair -> the list, one mechanism");
|
||||
}
|
||||
// ---- a state file another attempt left behind: the file's UE SPIs against the kernel pair's
|
||||
|
|
@ -335,44 +439,60 @@ int main() {
|
|||
// ---- selection rules and syntax corners
|
||||
{
|
||||
// spec-shaped list: every entry carries the SPI set, md5 preferred by q — we offered sha1, so sha1 wins (audit A1)
|
||||
auto a1 = ParseSecurityServer("ipsec-3gpp;q=0.1;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14,ipsec-3gpp;q=0.2;alg=hmac-md5-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14", "hmac-sha-1-96", "aes-cbc");
|
||||
auto a1 = ParseSecurityServer("ipsec-3gpp;q=0.1;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14,ipsec-3gpp;q=0.2;alg=hmac-md5-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(a1 && a1->selected == 0 && a1->offerMatched && a1->Selected().alg == "hmac-sha-1-96", "every entry carries SPIs, md5 preferred: the offered sha1 is selected, not the highest q");
|
||||
// two sha1 entries with different ciphers, both carrying SPIs: the offered cipher wins over q (audit A3)
|
||||
auto a3 = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=des-ede3-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.8;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc");
|
||||
auto a3 = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=des-ede3-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.8;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(a3 && a3->selected == 1 && a3->Carrier().spiPs == 6u, "offered cipher wins over a higher-q cipher we did not offer");
|
||||
// two matching entries: the higher q
|
||||
auto two = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc");
|
||||
auto two = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(two && two->selected == 1 && two->Selected().spiPs == 6u, "two matching entries: highest q selected");
|
||||
// nothing matches the offer (md5-only list): fallback = the highest-q carrier, flagged
|
||||
auto md5 = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc");
|
||||
auto md5 = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(md5 && md5->selected == 1 && !md5->offerMatched && md5->carrier == 1, "no match: highest-q carrier, offerMatched=false");
|
||||
// no q at all, nothing matching: the first carrier
|
||||
auto noq = ParseSecurityServer("ipsec-3gpp;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc");
|
||||
auto noq = ParseSecurityServer("ipsec-3gpp;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(noq && noq->selected == 0 && !noq->offerMatched, "no q, no match: first carrier");
|
||||
// absent alg on the entry counts as the offered one
|
||||
auto noalg = ParseSecurityServer("ipsec-3gpp;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", "aes-cbc");
|
||||
auto noalg = ParseSecurityServer("ipsec-3gpp;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(noalg && noalg->offerMatched, "absent alg matches the offer");
|
||||
// only non-ipsec mechanisms: nothing for us
|
||||
Check(!ParseSecurityServer("tls;q=0.2,digest;d-alg=MD5", "hmac-sha-1-96", "aes-cbc").has_value(), "tls/digest only -> nullopt");
|
||||
Check(!ParseSecurityServer("tls;q=0.2,digest;d-alg=MD5", "hmac-sha-1-96", {"aes-cbc"}).has_value(), "tls/digest only -> nullopt");
|
||||
// a quoted comma must not split the list; tokens are case-insensitive
|
||||
auto q = ParseSecurityServer("digest;d-alg=MD5;d-qop=\"auth,auth-int\",IPSEC-3GPP; ALG=HMAC-SHA-1-96; EALG=AES-CBC; SPI-C=11; SPI-S=12; PORT-C=13; PORT-S=14", "HMAC-SHA-1-96", "AES-CBC");
|
||||
auto q = ParseSecurityServer("digest;d-alg=MD5;d-qop=\"auth,auth-int\",IPSEC-3GPP; ALG=HMAC-SHA-1-96; EALG=AES-CBC; SPI-C=11; SPI-S=12; PORT-C=13; PORT-S=14", "HMAC-SHA-1-96", {"AES-CBC"});
|
||||
Check(q && q->mechanisms.size() == 2 && q->mechanisms[0].name == "digest", "quoted comma stays inside the digest mechanism");
|
||||
Check(q && q->selected == 1 && q->offerMatched && q->Selected().name == "ipsec-3gpp" && q->Selected().alg == "hmac-sha-1-96" && q->Selected().ealg == "aes-cbc" && q->Selected().spiPs == 12u && q->Selected().portPs == 14, "case-insensitive names and values, lower-cased; offer compared case-insensitively");
|
||||
// prot/mod parsed for the caller to refuse
|
||||
auto tun = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;prot=ah;mod=tun;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", "aes-cbc");
|
||||
auto tun = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;prot=ah;mod=tun;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(tun && tun->Selected().prot == "ah" && tun->Selected().mod == "tun", "prot/mod parsed");
|
||||
// spi-s beyond 32 bits, a port beyond 16 bits or zero: absent, not garbage
|
||||
auto bad = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=4294967296;port-c=0;port-s=70000", "hmac-sha-1-96", "aes-cbc");
|
||||
auto bad = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=4294967296;port-c=0;port-s=70000", "hmac-sha-1-96", {"aes-cbc"});
|
||||
Check(bad && !bad->Selected().spiPs && !bad->Selected().portPs && !bad->Selected().portPc && bad->Selected().spiPc == 1u, "out-of-range spi-s/port-s and port 0 are absent");
|
||||
// q syntax
|
||||
auto q1 = ParseSecurityServer("ipsec-3gpp;q=1;spi-s=1", "hmac-sha-1-96", "null");
|
||||
auto q1 = ParseSecurityServer("ipsec-3gpp;q=1;spi-s=1", "hmac-sha-1-96", {"null"});
|
||||
Check(q1 && q1->Selected().qMilli == 1000, "q=1 -> 1000");
|
||||
auto qx = ParseSecurityServer("ipsec-3gpp;q=x;spi-s=1", "hmac-sha-1-96", "null");
|
||||
auto qx = ParseSecurityServer("ipsec-3gpp;q=x;spi-s=1", "hmac-sha-1-96", {"null"});
|
||||
Check(qx && !qx->Selected().qMilli, "q=x -> no q");
|
||||
Check(!ParseSecurityServer("", "hmac-sha-1-96", "null").has_value() && !ParseSecurityServer(" , ", "hmac-sha-1-96", "null").has_value(), "empty value -> nullopt");
|
||||
Check(!ParseSecurityServer("", "hmac-sha-1-96", {"null"}).has_value() && !ParseSecurityServer(" , ", "hmac-sha-1-96", {"null"}).has_value(), "empty value -> nullopt");
|
||||
Check(NormalizeEalg("") == "null" && NormalizeEalg("3des") == "des-ede3-cbc" && NormalizeEalg("aes-cbc") == "aes-cbc", "NormalizeEalg");
|
||||
}
|
||||
|
||||
// ---- OnSaPath: the two paths an SA pair's outbound policies select
|
||||
{
|
||||
const SaPaths p{"2001:db8::db43", "2001:db8::105", 6000, 33421};
|
||||
Check(OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: the client port to the P-CSCF's server port");
|
||||
Check(OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33421), "OnSaPath: the server port to the P-CSCF's client port");
|
||||
Check(!OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 33421) && !OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 6000), "OnSaPath: not the client port to its client port, nor the server port to its server port");
|
||||
Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33422), "OnSaPath: not another port of the P-CSCF");
|
||||
Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::106", 33421), "OnSaPath: not another host on the P-CSCF's port");
|
||||
Check(!OnSaPath(p, "2001:db8::db44", 45062, "2001:db8::105", 33421), "OnSaPath: not from another address of ours");
|
||||
Check(!OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 6000) && !OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 33421), "OnSaPath: not from a port that is neither protected port");
|
||||
Check(OnSaPath(p, "2001:DB8:0:0:0:0:0:DB43", 45061, "2001:0db8::0105", 6000) && OnSaPath(SaPaths{"2001:DB8:0:0:0:0:0:DB43", "2001:0db8::0105", 6000, 33421}, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: an IPv6 address in another spelling is the same address, the packet's or the record's");
|
||||
Check(!OnSaPath(SaPaths{}, "2001:db8::db43", 45061, "2001:db8::105", 6000) && !OnSaPath(SaPaths{}, "", 45061, "", 0), "OnSaPath: no pair on record, no path");
|
||||
const SaPaths four{"192.0.2.2", "192.0.2.1", 6000, 33421};
|
||||
Check(OnSaPath(four, "192.0.2.2", 45062, "192.0.2.1", 33421) && !OnSaPath(four, "192.0.2.2", 45062, "192.0.2.3", 33421), "OnSaPath: over IPv4 a path of the pair, and not another host on its port");
|
||||
}
|
||||
|
||||
if (Failures == 0) std::println("Ipsec: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@
|
|||
// compared byte-for-byte against a reference message cross-generated from the
|
||||
// Python VoLTE stack with pinned tags/branches/SPIs; their variants and the other
|
||||
// builders against a message written here or by their lines (BuildInviteResponse
|
||||
// is not called). A divergence here is a wire-format change, i.e. a
|
||||
// by the lines of one 180 and by its answers to an INVITE in long and in
|
||||
// compact form). A divergence here is a wire-format change, i.e. a
|
||||
// registration or call that the commercial IMS core may reject; these are the
|
||||
// hardest pins in the project. Two deliberate post-parity divergences:
|
||||
// hardest pins in the project. Three deliberate post-parity divergences:
|
||||
// the REGISTER Contact carries +sip.instance and the MMTEL ICSI feature tag
|
||||
// (the Python stack registered without them, which made the network divert
|
||||
// incoming calls to voicemail — see ContactFeatures in Imsd:Messages), and
|
||||
|
|
@ -15,7 +16,16 @@
|
|||
// TS 24.229 coding and what the stock modem sends on the wire; the Python
|
||||
// stack's plain-colon form is a different string under RFC 3841 matching
|
||||
// and left terminating access-domain selection routing incoming calls to
|
||||
// CS fallback (observed live 2026-07-20). Then the SMS over IP shapes: the
|
||||
// CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client
|
||||
// carries the default offer's two mechanisms, where the Python stack offered
|
||||
// one cipher. The two REGISTERs once more on an identity an ISIM holds: the
|
||||
// pinned ones with the card's names in place of the derived ones. The INVITE,
|
||||
// its CANCEL and its ACKs once more for a dialog with another sequence number,
|
||||
// session interval and Min-SE than the pinned 1, 1800 and 90. Which
|
||||
// messages carry P-Access-Network-Info where the cell is known, and that the
|
||||
// PRACK, the BYE and the responses that carry it carry none where it is not.
|
||||
// Then the
|
||||
// SMS over IP shapes: the
|
||||
// +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying
|
||||
// an RP-DATA to the service centre and the one carrying an RP-ACK to the
|
||||
// IP-SM-GW with In-Reply-To (TS 24.341 5.3.1.2, 5.3.2.4), and a final other
|
||||
|
|
@ -67,7 +77,7 @@ namespace {
|
|||
"Authorization: Digest username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\", nonce=\"\", response=\"\"\r\n"
|
||||
"Require: sec-agree\r\n"
|
||||
"Proxy-Require: sec-agree\r\n"
|
||||
"Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"
|
||||
"Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"
|
||||
"Supported: sec-agree, path\r\n"
|
||||
"Expires: 600000\r\n"
|
||||
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"
|
||||
|
|
@ -87,7 +97,7 @@ namespace {
|
|||
"Authorization: Digest username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\", nonce=\"NONCEXYZ\", qop=auth, nc=00000001, cnonce=\"CNONCE0123456789\", response=\"RESP0000\", algorithm=AKAv1-MD5\r\n"
|
||||
"Require: sec-agree\r\n"
|
||||
"Proxy-Require: sec-agree\r\n"
|
||||
"Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"
|
||||
"Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"
|
||||
"Security-Verify: ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000\r\n"
|
||||
"Supported: sec-agree, path\r\n"
|
||||
"Expires: 600000\r\n"
|
||||
|
|
@ -186,7 +196,8 @@ namespace {
|
|||
int main() {
|
||||
Context c = MakeCtx();
|
||||
|
||||
// ---- REGISTER (initial + protected), byte-exact vs Python
|
||||
// ---- REGISTER (initial + protected), byte-exact (the header of this
|
||||
// file has what differs from the Python stack's bytes)
|
||||
Eq(BuildRegisterInitial(c, "REGCALLID@2001:db8::db43", "FTAG5678",
|
||||
"REGBRANCH123456", 7449812u, 176466735u),
|
||||
Reg1, "unprotected REGISTER");
|
||||
|
|
@ -204,13 +215,34 @@ int main() {
|
|||
{
|
||||
std::string auth = AuthAka(c, "NONCEXYZ", "CNONCE0123456789", "RESP0000");
|
||||
std::string r3 = BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth, 45063);
|
||||
Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "refresh Security-Client: new SPIs, a new client port, the same server port");
|
||||
Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "refresh Security-Client: new SPIs, a new client port, the same server port, in both mechanisms");
|
||||
Check(r3.contains("\r\nCSeq: 3 REGISTER\r\n") && r3.contains("\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;") && r3.contains("@[2001:db8::db43]:45062>"), "refresh: CSeq+1, the server port in Via and Contact");
|
||||
Check(r3.contains(std::format("\r\n{}\r\n", auth)), "refresh carries the last challenge answer verbatim");
|
||||
std::string r3same = BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth);
|
||||
Check(r3same.contains("port-c=45061; port-s=45062\r\n"), "without a client port the in-use one is offered (the initial registration's second REGISTER)");
|
||||
}
|
||||
|
||||
// ---- the offer: one mechanism per offered cipher, in the list's order,
|
||||
// every one with the REGISTER's SPIs and ports
|
||||
{
|
||||
Check(c.ealgOffer == imsd::ipsec::DefaultEalgOffer(), "the default context offers the default list");
|
||||
Context one = c;
|
||||
one.ealgOffer = {"aes-cbc"};
|
||||
Check(BuildRegisterInitial(one, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u).contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "one cipher offered: one mechanism, the header as it was before the default offer had two");
|
||||
Context two = c;
|
||||
two.ealgOffer = {"aes-cbc", "null"};
|
||||
std::string r1 = BuildRegisterInitial(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u);
|
||||
Check(r1.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "two ciphers offered: two mechanisms in one Security-Client");
|
||||
std::string auth = AuthAka(two, "NONCEXYZ", "CNONCE0123456789", "RESP0000");
|
||||
std::string r2 = BuildRegisterProtected(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth);
|
||||
Check(r2.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "the protected REGISTER repeats the initial one's Security-Client (TS 33.203 Annex H)");
|
||||
std::string r3 = BuildRegisterProtected(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth, 45063);
|
||||
Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "a reregistration's new SPIs and client port in every mechanism");
|
||||
two.ealgOffer = {"null", "des-ede3-cbc"};
|
||||
std::string r4 = BuildRegisterInitial(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u);
|
||||
Check(r4.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=des-ede3-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "the list's order is the header's order");
|
||||
}
|
||||
|
||||
// ---- protected-leg transport follows Context.transport (SIP_TRANSPORT=udp,
|
||||
// or the auto fallback): every protected request's Via says UDP, the
|
||||
// challenge's Via stays UDP either way, and TCP is the untouched default.
|
||||
|
|
@ -226,6 +258,42 @@ int main() {
|
|||
Check(BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth).contains("\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;"), "default transport stays TCP");
|
||||
}
|
||||
|
||||
// ---- the REGISTERs of an identity an ISIM holds (imsd::aka::IsimIdentity):
|
||||
// every name is the card's — the Request-URI the home domain's, From and
|
||||
// To the public identity, the digest's username the private identity,
|
||||
// its realm the home domain; the rest of the message is the one pinned
|
||||
// above.
|
||||
{
|
||||
Context ci = c;
|
||||
ci.id = *imsd::aka::IsimIdentity(c.id, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net");
|
||||
std::string want1(Reg1);
|
||||
auto swap = [](std::string& s, std::string_view from, std::string_view to) {
|
||||
int n = 0;
|
||||
for (std::size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) { s.replace(at, from.size(), to); n++; }
|
||||
return n;
|
||||
};
|
||||
Check(swap(want1, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0") == 1, "the pinned REGISTER has one Request-URI");
|
||||
Check(swap(want1, "<sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>", "<sip:001010123456789@one.example.net>") == 2, "the pinned REGISTER has the public identity in From and To");
|
||||
Check(swap(want1, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"",
|
||||
"username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\"") == 1, "the pinned REGISTER has one digest");
|
||||
Check(!want1.contains("3gppnetwork.org"), "no derived name is left in the expected REGISTER");
|
||||
Eq(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u), want1, "unprotected REGISTER of an ISIM's identity");
|
||||
|
||||
std::string want2(Reg2);
|
||||
swap(want2, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0");
|
||||
swap(want2, "<sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>", "<sip:001010123456789@one.example.net>");
|
||||
swap(want2, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"",
|
||||
"username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\"");
|
||||
Check(!want2.contains("3gppnetwork.org"), "no derived name is left in the expected protected REGISTER");
|
||||
std::string auth = AuthAka(ci, "NONCEXYZ", "CNONCE0123456789", "RESP0000");
|
||||
Eq(BuildRegisterProtected(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth), want2, "protected REGISTER of an ISIM's identity");
|
||||
// the Contact keeps the binding's own user-part: the IMSI here, as in
|
||||
// the pinned message (an old state file's shape)
|
||||
Check(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u).contains("\r\nContact: <sip:001010123456789@[2001:db8::db43]:5060>"), "the Contact is not the public identity");
|
||||
// RuriFor with a home domain that is not a derived one
|
||||
Eq(RuriFor("+31612345678", ci.id.domain), "sip:+31612345678@one.example.net;user=phone", "RuriFor puts a number at the domain it is given, an ISIM's here");
|
||||
}
|
||||
|
||||
// ---- RuriFor variants
|
||||
Eq(RuriFor("1233", c.id.domain), "sip:1233;phone-context=ims.mnc001.mcc001.3gppnetwork.org@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri short code");
|
||||
Eq(RuriFor("+31612345678", c.id.domain), "sip:+31612345678@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri E.164");
|
||||
|
|
@ -358,11 +426,11 @@ int main() {
|
|||
Check(prack.contains("To: <sip:1233@x>;tag=remote99\r\n"), "PRACK To has remote tag");
|
||||
Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq");
|
||||
Check(prack.contains("RAck: 42 1 INVITE\r\n"), "PRACK RAck");
|
||||
Check(prack.ends_with("Content-Length: 0\r\n\r\n"), "PRACK empty body");
|
||||
Check(prack.ends_with("RAck: 42 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "PRACK: P-Access-Network-Info after its RAck, an empty body");
|
||||
|
||||
std::string bye = BuildInDialog(c, d, "BYE", 3, "byebranch");
|
||||
Check(bye.starts_with("BYE sip:termgw@2001:db8::9 SIP/2.0\r\n"), "BYE line");
|
||||
Check(bye.contains("CSeq: 3 BYE\r\n"), "BYE CSeq");
|
||||
Check(bye.ends_with("CSeq: 3 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "BYE: its CSeq, then P-Access-Network-Info");
|
||||
|
||||
std::string ack = BuildAck2xx(c, d, "ackbranch", "<ignored>");
|
||||
Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target");
|
||||
|
|
@ -373,6 +441,12 @@ int main() {
|
|||
Check(cancel.starts_with(std::format("CANCEL {} SIP/2.0\r\n", d.ruri)), "CANCEL request-URI = ruri");
|
||||
Check(cancel.contains("branch=z9hG4bKib;rport\r\n"), "CANCEL reuses INVITE branch");
|
||||
Check(cancel.contains("CSeq: 1 CANCEL\r\n"), "CANCEL CSeq copies INVITE");
|
||||
// RFC 7315 5.7: the header appears in no ACK and no CANCEL
|
||||
Check(!ack.contains("P-Access-Network-Info") && !cancel.contains("P-Access-Network-Info") && !BuildAckNon2xx(c, d, "<sip:x@y>;tag=z").contains("P-Access-Network-Info"), "neither ACK nor the CANCEL carries P-Access-Network-Info");
|
||||
// where the cell is not known the in-dialog requests carry none either
|
||||
Context n = MakeCtx();
|
||||
n.panInfo.clear();
|
||||
Check(BuildInDialog(n, d, "PRACK", 2, "prbranch", rack).ends_with("RAck: 42 1 INVITE\r\nContent-Length: 0\r\n\r\n") && BuildInDialog(n, d, "BYE", 3, "byebranch").ends_with("CSeq: 3 BYE\r\nContent-Length: 0\r\n\r\n"), "no cell known: PRACK and BYE without the header");
|
||||
}
|
||||
{
|
||||
// non-2xx ACK uses the INVITE branch + registration route + resp To
|
||||
|
|
@ -383,6 +457,20 @@ int main() {
|
|||
Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route");
|
||||
Check(ack.contains("To: <sip:x@y>;tag=z\r\n"), "non-2xx ACK echoes response To");
|
||||
}
|
||||
{
|
||||
// The INVITE's sequence number, session interval and Min-SE are the
|
||||
// dialog's (1, 1800 and 90 in the pinned INVITE above), and its CANCEL
|
||||
// and both ACKs carry the INVITE's number.
|
||||
Dialog d;
|
||||
d.ruri = "sip:x@y"; d.callid = "CID"; d.itag = "it"; d.invBranch = "ib9";
|
||||
d.invCseq = 2; d.sessionExpires = 3600; d.minSe = 2400;
|
||||
std::string inv = BuildInvite(c, d, "v=0\r\n", false);
|
||||
Check(inv.contains("\r\nCSeq: 2 INVITE\r\n"), "INVITE carries the dialog's sequence number");
|
||||
Check(inv.contains("\r\nSession-Expires: 3600;refresher=uac\r\nMin-SE: 2400\r\n"), "INVITE carries the dialog's session interval and Min-SE");
|
||||
Check(BuildCancel(c, d).contains("\r\nCSeq: 2 CANCEL\r\n"), "CANCEL copies the INVITE's number");
|
||||
Check(BuildAckNon2xx(c, d, "<sip:x@y>;tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "non-2xx ACK copies the INVITE's number");
|
||||
Check(BuildAck2xx(c, d, "ab", "<sip:x@y>;tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "2xx ACK copies the INVITE's number");
|
||||
}
|
||||
|
||||
// ---- 200 OK response echoes the request's dialog headers, in order
|
||||
{
|
||||
|
|
@ -399,12 +487,21 @@ int main() {
|
|||
Check(r.contains("Via: SIP/2.0/TCP [a::1]:45061;branch=z9hG4bKother\r\n"), "200 echoes Via");
|
||||
Check(r.contains("Call-ID: xyz@far\r\n"), "200 echoes Call-ID");
|
||||
Check(r.contains("CSeq: 7 BYE\r\n"), "200 echoes CSeq");
|
||||
Check(r.ends_with("Content-Length: 0\r\n\r\n"), "200 empty body");
|
||||
Check(r.ends_with("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "200 to a BYE: P-Access-Network-Info after the echoed five, an empty body");
|
||||
// with an SDP answer: our Contact + application/sdp appear
|
||||
std::string r2 = BuildResponse200(c, req, Sdp);
|
||||
Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type");
|
||||
Check(r2.contains("Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"), "200 w/ SDP includes our Contact");
|
||||
Check(r2.ends_with(Sdp), "200 w/ SDP body");
|
||||
Check(r2.contains("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContact: "), "200 w/ SDP: P-Access-Network-Info before our Contact");
|
||||
// TS 24.229 5.1.2A.1.1, 5.1.2A.2: "(except CANCEL responses)"
|
||||
std::string cancelReq = req;
|
||||
cancelReq.replace(0, 3, "CANCEL");
|
||||
cancelReq.replace(cancelReq.find("CSeq: 7 BYE"), 11, "CSeq: 7 CANCEL");
|
||||
Check(BuildResponse200(c, cancelReq).ends_with("CSeq: 7 CANCEL\r\nContent-Length: 0\r\n\r\n"), "200 to a CANCEL: no P-Access-Network-Info");
|
||||
Context n = MakeCtx();
|
||||
n.panInfo.clear();
|
||||
Check(BuildResponse200(n, req).ends_with("CSeq: 7 BYE\r\nContent-Length: 0\r\n\r\n") && !BuildResponse200(n, req, Sdp).contains("P-Access-Network-Info"), "no cell known: the 200 without the header");
|
||||
}
|
||||
|
||||
// ---- s53 oracle diff: UUID Contact user-part + User-Agent ------------
|
||||
|
|
@ -490,7 +587,9 @@ int main() {
|
|||
"Call-ID: in1@net\r\n"
|
||||
"CSeq: 9 MESSAGE\r\n"
|
||||
"Content-Length: 0\r\n\r\n";
|
||||
Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"),
|
||||
Context noCell = MakeCtx();
|
||||
noCell.panInfo.clear();
|
||||
Eq(BuildResponse(noCell, inbound, 488, "Not Acceptable Here", "T488"),
|
||||
"SIP/2.0 488 Not Acceptable Here\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
|
||||
|
|
@ -499,8 +598,125 @@ int main() {
|
|||
"Call-ID: in1@net\r\n"
|
||||
"CSeq: 9 MESSAGE\r\n"
|
||||
"Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To");
|
||||
Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"),
|
||||
"SIP/2.0 488 Not Acceptable Here\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
|
||||
"From: <sip:ipsmgw@ims>;tag=N1\r\n"
|
||||
"To: <sip:me@ims>;tag=T488\r\n"
|
||||
"Call-ID: in1@net\r\n"
|
||||
"CSeq: 9 MESSAGE\r\n"
|
||||
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"
|
||||
"Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after its CSeq");
|
||||
const std::string tagged = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet2\r\nFrom: <sip:ipsmgw@ims>;tag=N2\r\nTo: <sip:me@ims>;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n";
|
||||
Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: <sip:me@ims>;tag=had\r\n"), "a To that already carries a tag is echoed as it is");
|
||||
// the 400 to a request whose datagram ended before its body did (RFC 3261 18.3), built from what imsd::sip::CutShortRequest gives of it
|
||||
{
|
||||
std::string cut = inbound;
|
||||
cut.replace(cut.find("Content-Length: 0"), 17, "Content-Length: 12");
|
||||
const std::string head = imsd::sip::CutShortRequest(cut + "seven b").value_or("");
|
||||
Check(!head.empty(), "an inbound MESSAGE with seven body bytes of twelve is a request cut short");
|
||||
// the To tag below was made apart from imsd's MD5: Python's hashlib over the secret and the header section with its empty line, the first sixteen digits
|
||||
const std::string_view secret = "run-secret-of-16";
|
||||
Eq(BuildBadRequest(head, secret),
|
||||
"SIP/2.0 400 Bad Request\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
|
||||
"From: <sip:ipsmgw@ims>;tag=N1\r\n"
|
||||
"To: <sip:me@ims>;tag=d930d9cad06d5cba\r\n"
|
||||
"Call-ID: in1@net\r\n"
|
||||
"CSeq: 9 MESSAGE\r\n"
|
||||
"Content-Length: 0\r\n\r\n", "its 400 echoes every Via and tags To with sixteen hex digits of the MD5 of the secret and the header section");
|
||||
Eq(BuildBadRequest(imsd::sip::CutShortRequest(cut + "s").value_or(""), secret), BuildBadRequest(head, secret), "the same request cut short elsewhere draws the same 400, tag and all");
|
||||
Check(!BuildBadRequest(head, secret).contains("P-Access-Network-Info"), "the 400 is built without the registration's context: no P-Access-Network-Info");
|
||||
const auto toTag = [](std::string_view r) { const std::size_t at = r.find(";tag=", r.find("\r\nTo: ")); return r.substr(at, r.find("\r\n", at) - at); };
|
||||
const std::string r1 = BuildBadRequest(head, secret);
|
||||
std::string other = cut;
|
||||
other.replace(other.find("in1@net"), 7, "in2@net");
|
||||
const std::string r2 = BuildBadRequest(imsd::sip::CutShortRequest(other + "seven b").value_or(""), secret);
|
||||
Check(r2.contains("\r\nCall-ID: in2@net\r\n") && toTag(r2).size() == 5 + 16 && toTag(r2) != toTag(r1), "another request draws another tag, of sixteen digits too");
|
||||
const std::string r3 = BuildBadRequest(head, "another-secret-16");
|
||||
Check(toTag(r3).size() == 5 + 16 && toTag(r3) != toTag(r1), "and the same request under another secret draws another tag");
|
||||
std::string had = tagged;
|
||||
had.replace(had.find("Content-Length: 0"), 17, "Content-Length: 12");
|
||||
Check(BuildBadRequest(imsd::sip::CutShortRequest(had + "seven b").value_or(""), secret).contains("\r\nTo: <sip:me@ims>;tag=had\r\n"), "and the 400 echoes a To that already carries a tag as it is");
|
||||
}
|
||||
// a request whose header names come in compact form (RFC 3261 7.3.3): the finals echo them under the long names
|
||||
const std::string compact =
|
||||
"MESSAGE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n"
|
||||
"v: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"V: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
|
||||
"f: <sip:ipsmgw@ims>;tag=N1\r\n"
|
||||
"t: <sip:me@ims>\r\n"
|
||||
"i: in1@net\r\n"
|
||||
"CSeq: 9 MESSAGE\r\n"
|
||||
"l: 0\r\n\r\n";
|
||||
Eq(BuildResponse(c, compact, 488, "Not Acceptable Here", "T488"), BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"), "a 488 for a MESSAGE in compact form is the one for its long form");
|
||||
Eq(BuildResponse200(c, compact), BuildResponse200(c, inbound), "the hop-by-hop 200 for a request in compact form is the one for its long form");
|
||||
Check(BuildResponse200(c, compact).contains("\r\nFrom: <sip:ipsmgw@ims>;tag=N1\r\nTo: <sip:me@ims>\r\nCall-ID: in1@net\r\nCSeq: 9 MESSAGE\r\n"), "with its `f:`, `t:` and `i:` under the long names");
|
||||
// BuildInviteResponse reads the same names: an INVITE in compact form gets the responses of its long form
|
||||
const std::string invite =
|
||||
"INVITE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n"
|
||||
"Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n"
|
||||
"Record-Route: <sip:[2001:db8::105]:6000;lr>\r\n"
|
||||
"From: <sip:caller@ims>;tag=N3\r\n"
|
||||
"To: <sip:me@ims>\r\n"
|
||||
"Call-ID: call3@net\r\n"
|
||||
"CSeq: 1 INVITE\r\n"
|
||||
"Content-Length: 0\r\n\r\n";
|
||||
const std::string compactInvite =
|
||||
"INVITE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n"
|
||||
"v: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n"
|
||||
"V: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n"
|
||||
"Record-Route: <sip:[2001:db8::105]:6000;lr>\r\n"
|
||||
"f: <sip:caller@ims>;tag=N3\r\n"
|
||||
"t: <sip:me@ims>\r\n"
|
||||
"i: call3@net\r\n"
|
||||
"CSeq: 1 INVITE\r\n"
|
||||
"l: 0\r\n\r\n";
|
||||
Eq(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180"),
|
||||
"SIP/2.0 180 Ringing\r\n"
|
||||
"Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n"
|
||||
"Record-Route: <sip:[2001:db8::105]:6000;lr>\r\n"
|
||||
"From: <sip:caller@ims>;tag=N3\r\n"
|
||||
"To: <sip:me@ims>;tag=T180\r\n"
|
||||
"Call-ID: call3@net\r\n"
|
||||
"CSeq: 1 INVITE\r\n"
|
||||
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"
|
||||
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n"
|
||||
"Content-Length: 0\r\n\r\n", "a 180 for an INVITE echoes every Via and the Record-Route, tags To and carries our Contact and Allow");
|
||||
const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180");
|
||||
Eq(ringing,
|
||||
"SIP/2.0 180 Ringing\r\n"
|
||||
"Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n"
|
||||
"Record-Route: <sip:[2001:db8::105]:6000;lr>\r\n"
|
||||
"From: <sip:caller@ims>;tag=N3\r\n"
|
||||
"To: <sip:me@ims>;tag=T180\r\n"
|
||||
"Call-ID: call3@net\r\n"
|
||||
"CSeq: 1 INVITE\r\n"
|
||||
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"
|
||||
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n"
|
||||
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"
|
||||
"Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after them");
|
||||
{
|
||||
const std::array<std::string, 2> reliable = {"Require: 100rel", "RSeq: 1"};
|
||||
Check(BuildInviteResponse(c, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "a reliable 180: P-Access-Network-Info after its Require and RSeq");
|
||||
Check(BuildInviteResponse(c, invite, 100, "Trying", "unused").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "a 100 Trying carries none");
|
||||
Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "and a 486");
|
||||
Check(BuildInviteResponse(c, invite, 200, "OK", "T200", "v=0\r\n").ends_with("P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Type: application/sdp\r\nContent-Length: 5\r\n\r\nv=0\r\n"), "and a 200 with its answer, before the Content-Type");
|
||||
Check(!BuildInviteResponse(noCell, invite, 100, "Trying", "unused").contains("P-Access-Network-Info") && !BuildInviteResponse(noCell, invite, 200, "OK", "T200", "v=0\r\n").contains("P-Access-Network-Info"), "no cell known: a 100 and a 200 without the header");
|
||||
Check(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nContent-Length: 0\r\n\r\n") && BuildInviteResponse(noCell, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "no cell known: a reliable 180 and a 486 without it");
|
||||
// the exception is for a response to a CANCEL, not for one to a request that names the method
|
||||
std::string allowing = invite;
|
||||
allowing.insert(allowing.find("Content-Length:"), "Allow: INVITE, ACK, CANCEL, BYE\r\n");
|
||||
Check(BuildInviteResponse(c, allowing, 180, "Ringing", "T180") == ringing, "an INVITE whose Allow names CANCEL is answered like any other");
|
||||
}
|
||||
Eq(BuildInviteResponse(c, compactInvite, 180, "Ringing", "T180"), ringing, "a 180 for an INVITE in compact form is the one for its long form");
|
||||
Eq(BuildInviteResponse(c, compactInvite, 486, "Busy Here", "T486"), BuildInviteResponse(c, invite, 486, "Busy Here", "T486"), "and so is a 486");
|
||||
Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("\r\nTo: <sip:me@ims>;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route");
|
||||
{
|
||||
const std::string body = "hi\r\nVia: SIP/2.0/UDP 192.0.2.66;branch=z9hG4bKx";
|
||||
const std::string tail = "Content-Length: 0\r\n\r\n";
|
||||
|
|
@ -512,5 +728,5 @@ int main() {
|
|||
}
|
||||
|
||||
if (Failures == 0) std::println("Messages: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,5 +90,5 @@ int main() {
|
|||
}
|
||||
|
||||
if (Failures == 0) std::println("Qmi: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
|
|
@ -396,5 +396,5 @@ int main() {
|
|||
}
|
||||
|
||||
if (Failures == 0) std::println("Sdp: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,20 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Imsd:Sip unit tests — header access, status-line parsing, granted-expires
|
||||
// extraction, caller-identity extraction, and the TCP frame buffer (split
|
||||
// delivery, keepalive pongs, pipelined messages). These pin the module's
|
||||
// edge-case behavior; see the module header before "fixing" one.
|
||||
// Imsd:Sip unit tests — header access (compact forms and white space before
|
||||
// the colon among it), status-line parsing, granted-expires extraction,
|
||||
// caller-identity extraction, the port a Via names for the response
|
||||
// (ViaResponsePort), the two framers — the TCP frame buffer (split delivery,
|
||||
// keepalive pongs, pipelined messages) and a datagram's (DatagramMessage),
|
||||
// with the Content-Length they read and the unfolding of a folded header
|
||||
// section (Unfolded) —, a request whose datagram ends before its body does
|
||||
// (CutShortRequest), a refused final's Retry-After and summary (RetryAfter,
|
||||
// RefusalSummary), the interval a 422's Min-SE names (MinSe), transaction
|
||||
// matching (ResponseOf), our binding in a
|
||||
// reg-event document (RegInfoContactState), HeaderUri and Body, and a
|
||||
// message less every line on which one header is found (WithoutHeader).
|
||||
// These pin the module's edge-case behavior; see the module header before
|
||||
// "fixing" one.
|
||||
import std;
|
||||
import Imsd;
|
||||
|
||||
|
|
@ -65,6 +75,63 @@ int main() {
|
|||
Check(!Header(BodyVia, "X-Body").has_value(), "Header never reads the body");
|
||||
Check(Header("\r\n\r\nSIP/2.0 200 OK\r\nCall-ID: k\r\n\r\n", "Call-ID") == "k", "empty lines before the first line of text (a keepalive's CRLFs) are skipped");
|
||||
|
||||
// ---- compact forms (RFC 3261 7.3.3: "MUST accept both the long and short forms of each header name")
|
||||
{
|
||||
// RFC 3261's ten (section 20), then Event (RFC 6665 7.3) and Session-Expires (RFC 4028 4)
|
||||
const std::pair<std::string_view, char> forms[] = {
|
||||
{"Call-ID", 'i'}, {"Contact", 'm'}, {"Content-Encoding", 'e'}, {"Content-Length", 'l'}, {"Content-Type", 'c'}, {"From", 'f'},
|
||||
{"Subject", 's'}, {"Supported", 'k'}, {"To", 't'}, {"Via", 'v'}, {"Event", 'o'}, {"Session-Expires", 'x'},
|
||||
};
|
||||
// every letter against the header names below — those imsd reads, and the three of the RFC's ten it does not: the twelve pairs match, nothing else does
|
||||
{
|
||||
const std::string_view names[] = {"Call-ID", "CSeq", "To", "From", "Via", "Contact", "Record-Route", "P-Associated-URI", "Session-Expires", "Require", "P-Asserted-Identity", "Subscription-State", "Service-Route", "Security-Server", "RSeq", "Retry-After", "Reason", "Path", "In-Reply-To", "Expires", "Event", "Content-Type", "Content-Length", "Warning", "Server", "Content-Encoding", "Subject", "Supported"};
|
||||
int pairs = 0;
|
||||
bool onlyThose = true;
|
||||
for (char letter = 'a'; letter <= 'z'; letter++)
|
||||
for (std::string_view name : names) {
|
||||
const bool found = Header(std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: v\r\n\r\n", letter), name).has_value();
|
||||
const bool paired = std::ranges::any_of(forms, [&](const auto& form) { return form.first == name && form.second == letter; });
|
||||
if (found) pairs++;
|
||||
if (found != paired) onlyThose = false;
|
||||
}
|
||||
Check(pairs == 12 && onlyThose, "of the letters a to z against the header names listed, the twelve pairs are compact forms and no other letter is taken for a name");
|
||||
}
|
||||
for (const auto& [name, letter] : forms) {
|
||||
const std::string lower = std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: value-{}\r\n\r\n", letter, letter);
|
||||
const std::string upper = std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: value-{}\r\n\r\n", static_cast<char>(letter - 'a' + 'A'), letter);
|
||||
const std::string expect = std::format("value-{}", letter);
|
||||
Check(Header(lower, name) == expect, std::format("Header: `{}:` is read as {}", letter, name));
|
||||
Check(Header(upper, name) == expect, std::format("Header: the compact form of {} in upper case is read too", name));
|
||||
Check(Headers(lower, name) == std::vector<std::string_view>{expect}, std::format("Headers: `{}:` is a row of {}", letter, name));
|
||||
// no other name of the twelve takes that line
|
||||
for (const auto& [other, otherLetter] : forms)
|
||||
if (other != name) Check(!Header(lower, other).has_value(), std::format("Header: `{}:` is no {}", letter, other));
|
||||
}
|
||||
// a name with no compact form is found under its long form only
|
||||
Check(!Header("NOTIFY sip:a@b SIP/2.0\r\nr: <sip:x>\r\ns: active\r\n\r\n", "Record-Route").has_value() && !Header("NOTIFY sip:a@b SIP/2.0\r\nr: <sip:x>\r\ns: active\r\n\r\n", "Subscription-State").has_value(), "Header: a name that has no compact form is not found under a letter");
|
||||
// both forms in one message, in the order they stand (7.3.3: a name MAY appear in both forms)
|
||||
const std::string mixed = "MESSAGE sip:a@b SIP/2.0\r\nVia: one\r\nv: two\r\nV: three\r\nVia: four\r\ni: c1@h\r\n\r\n";
|
||||
Check(Headers(mixed, "Via") == std::vector<std::string_view>{"one", "two", "three", "four"} && Header(mixed, "Via") == "one" && Header(mixed, "Call-ID") == "c1@h", "Headers: long and compact rows of one name are one list, in order");
|
||||
// asked for in another case, the compact form is found all the same; a longer name that begins with a long form has none
|
||||
Check(Header(mixed, "call-id") == "c1@h" && Header(mixed, "CALL-ID") == "c1@h" && Headers(mixed, "VIA").size() == 4, "Header: the name asked for in lower or upper case finds its compact form");
|
||||
Check(!Header(mixed, "Via-Info").has_value() && !Header(mixed, "Call-ID-Extra").has_value(), "Header: a name that only begins with one that has a compact form has none");
|
||||
// a longer name that begins with the letter is not the compact form
|
||||
Check(!Header("MESSAGE sip:a@b SIP/2.0\r\nTimestamp: 54\r\nVersion: 1\r\n\r\n", "To").has_value() && !Header("MESSAGE sip:a@b SIP/2.0\r\nTimestamp: 54\r\nVersion: 1\r\n\r\n", "Via").has_value(), "Header: a name that only begins with a compact letter is not that header");
|
||||
}
|
||||
|
||||
// ---- white space before the colon (RFC 3261 7.3.1, 25.1 HCOLON)
|
||||
{
|
||||
// 7.3.1's four equivalent spellings
|
||||
for (std::string_view line : {"Subject: lunch", "Subject : lunch", "Subject :lunch", "Subject: lunch"})
|
||||
Check(Header(std::format("MESSAGE sip:a@b SIP/2.0\r\n{}\r\n\r\n", line), "Subject") == "lunch", std::format("Header: `{}` reads as lunch", line));
|
||||
Check(Header("MESSAGE sip:a@b SIP/2.0\r\nCall-ID\t: c2@h\r\ni \t : c3@h\r\n\r\n", "Call-ID") == "c2@h" && Headers("MESSAGE sip:a@b SIP/2.0\r\nCall-ID\t: c2@h\r\ni \t : c3@h\r\n\r\n", "Call-ID").size() == 2, "Header: a tab or spaces before the colon, after the long or the compact form");
|
||||
Check(!Header("MESSAGE sip:a@b SIP/2.0\r\nTo be: or not\r\nt x: y\r\n\r\n", "To").has_value(), "Header: a word between the name and the colon is another field name");
|
||||
Check(Header("X-Empty :\r\nX-Real: v\r\n\r\n", "X-Empty") == "" && !Header("X-Last :", "X-Last").has_value(), "a bare header with a space before its colon matches with an empty value; one that ends the buffer does not");
|
||||
// a name, or a name and white space, that ends the text is no header — also where a colon stands in the bytes right after the text
|
||||
Check(!Header("A: 1\r\nTo", "To").has_value() && !Header("A: 1\r\nTo \t", "To").has_value() && !Header("A: 1\r\nt", "To").has_value(), "a name that ends the text, with or without white space after it, is no header");
|
||||
Check(!Header(std::string_view("A: 1\r\nTo:v").substr(0, 8), "To").has_value() && !Header(std::string_view("A: 1\r\nTo \t:v").substr(0, 10), "To").has_value(), "nor is it where a colon follows in the bytes past the text's end");
|
||||
}
|
||||
|
||||
// ---- GrantedExpires
|
||||
Check(GrantedExpires(Resp200) == 600000, "GrantedExpires from Contact expires=");
|
||||
Check(GrantedExpires("SIP/2.0 200 OK\r\nExpires: 3600\r\n\r\n") == 3600, "GrantedExpires falls back to Expires");
|
||||
|
|
@ -119,6 +186,28 @@ int main() {
|
|||
Check(fb.TryExtract() == msg, "no Content-Length -> body length 0");
|
||||
Check(fb.Size() == 8, "trailing bytes stay buffered");
|
||||
}
|
||||
{
|
||||
// the Content-Length is read as a number: zeros before it do not count, and one too long to be a length is no zero
|
||||
const std::string head = "SIP/2.0 200 OK\r\nCall-ID: x\r\n";
|
||||
FrameBuffer fb;
|
||||
fb.Append(head + "Content-Length: 00000000005\r\n\r\nhello" + head + "Content-Length: 000\r\n\r\n" + head + "Content-Length: x\r\n\r\n");
|
||||
Check(fb.TryExtract() == head + "Content-Length: 00000000005\r\n\r\nhello", "a Content-Length of 5 written with ten zeros before it frames a body of five bytes");
|
||||
Check(fb.TryExtract() == head + "Content-Length: 000\r\n\r\n" && fb.TryExtract() == head + "Content-Length: x\r\n\r\n" && fb.Size() == 0, "zero in three digits is zero, and a value without a digit counts as none");
|
||||
fb.Append(head + "Content-Length: 18446744073709551616\r\n\r\nhello");
|
||||
Check(!fb.TryExtract().has_value() && fb.Size() > 0, "a Content-Length past any number that fits is not read as zero: the body is waited for");
|
||||
}
|
||||
{
|
||||
// the body's length under the compact name (RFC 3261 7.3.3), and with a space before the colon (7.3.1)
|
||||
const std::string compact = "MESSAGE sip:a@b SIP/2.0\r\ni: c1@h\r\nl: 5\r\n\r\nhello";
|
||||
const std::string spaced = "MESSAGE sip:a@b SIP/2.0\r\nCall-ID: c2@h\r\nContent-Length : 3\r\n\r\nabc";
|
||||
FrameBuffer fb;
|
||||
fb.Append(compact + spaced + Resp200);
|
||||
Check(fb.TryExtract() == compact, "`l: 5` frames a body of five bytes");
|
||||
Check(fb.TryExtract() == spaced, "`Content-Length : 3` frames a body of three");
|
||||
Check(fb.TryExtract() == Resp200 && !fb.TryExtract().has_value(), "the message after them starts where their bodies end");
|
||||
fb.Append(compact.substr(0, compact.size() - 2));
|
||||
Check(!fb.TryExtract().has_value(), "a body shorter than `l:` says is waited for");
|
||||
}
|
||||
|
||||
// ---- CallerId: P-Asserted-Identity preferred, From fallback
|
||||
{
|
||||
|
|
@ -159,6 +248,14 @@ int main() {
|
|||
Check(CallerId("INVITE sip:me SIP/2.0\r\nContent-Length: 0\r\n\r\n").empty(), "no identity headers -> empty");
|
||||
}
|
||||
|
||||
// ---- the readers above under compact names
|
||||
{
|
||||
Check(CallerId("INVITE sip:me SIP/2.0\r\nf: <sip:+31687654321@ims.example;user=phone>;tag=f\r\nl: 0\r\n\r\n") == "+31687654321", "CallerId: a From that comes as `f:`");
|
||||
Check(HeaderUri("MESSAGE sip:me SIP/2.0\r\nf: \"GW\" <sip:ipsmgw@ims.example>;tag=f\r\nl: 0\r\n\r\n", "From") == "sip:ipsmgw@ims.example", "HeaderUri: a From that comes as `f:`");
|
||||
Check(GrantedExpires("SIP/2.0 200 OK\r\nm: <sip:a@b>;expires=7200\r\n\r\n") == 7200, "GrantedExpires: a Contact that comes as `m:`");
|
||||
Check(ViaResponsePort("UPDATE sip:me SIP/2.0\r\nv: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKx\r\nl: 0\r\n\r\n") == 6000, "ViaResponsePort: a Via that comes as `v:`");
|
||||
}
|
||||
|
||||
// ---- ViaResponsePort: RFC 3261 18.2.2 UDP response routing
|
||||
{
|
||||
std::string upd =
|
||||
|
|
@ -182,6 +279,27 @@ int main() {
|
|||
"Content-Length: 0\r\n\r\n";
|
||||
Check(!ViaResponsePort(np).has_value(), "portless v6 sent-by -> nullopt");
|
||||
Check(!ViaResponsePort("UPDATE sip:me SIP/2.0\r\n\r\n").has_value(), "no Via -> nullopt");
|
||||
// rport is a parameter by its name (RFC 3581), in any case (RFC 3261 7.3.1)
|
||||
const std::string top = "SIP/2.0/UDP [2001:db8::105]:6000";
|
||||
auto row = [](std::string_view value) { return std::format("BYE sip:me SIP/2.0\r\nVia: {}\r\nContent-Length: 0\r\n\r\n", value); };
|
||||
Check(!ViaResponsePort(row(top + ";RPort;branch=z9hG4bKp")).has_value(), "rport in another case");
|
||||
Check(!ViaResponsePort(row(top + " ; rport ;branch=z9hG4bKp")).has_value(), "rport with white space around it");
|
||||
Check(!ViaResponsePort(row(top + ";rport=6001;branch=z9hG4bKp")).has_value(), "rport that came with a value");
|
||||
Check(ViaResponsePort(row(top + ";branch=z9hG4bKrport;xrport;rportx=1")) == 6000, "those letters in a value or in a longer name are no rport");
|
||||
Check(ViaResponsePort(row(top + ";x=\"a;rport;b\";branch=z9hG4bKp")) == 6000, "nor between semicolons in a quoted string");
|
||||
Check(!ViaResponsePort(row(top + ";x=\"a;b\";rport")).has_value(), "a quoted string ends at its closing quote");
|
||||
Check(ViaResponsePort(row(top + ";x=\"a\\\";rport;b\"")) == 6000, "and a quoted pair in it does not close it");
|
||||
Check(!ViaResponsePort(row(top + ";x=\"a\\\\\";rport")).has_value(), "the quote behind an escaped backslash does");
|
||||
// a row that holds a list (RFC 3261 7.3.1): the top value alone speaks
|
||||
const std::string next = "SIP/2.0/UDP [2001:db8::9]:5060";
|
||||
Check(ViaResponsePort(row(top + ";branch=z9hG4bKp, " + next + ";branch=z9hG4bKs;rport=5060")) == 6000, "a list on one line: the top value's port, a later value's rport not counted");
|
||||
auto folded = DatagramMessage(row(top + ";branch=z9hG4bKp,\r\n " + next + ";branch=z9hG4bKs;rport=5060"));
|
||||
Check(folded && ViaResponsePort(*folded) == 6000, "the same list folded after its comma, as the datagram framer hands it on");
|
||||
Check(!ViaResponsePort(row(top + ";rport;branch=z9hG4bKp, " + next + ";branch=z9hG4bKs")).has_value(), "the top value's own rport counts");
|
||||
Check(!ViaResponsePort(row(top + ";branch=z9hG4bKp;rport, " + next + ";branch=z9hG4bKs")).has_value(), "also where it stands last before the comma");
|
||||
Check(ViaResponsePort(row(top + ", " + next + ";branch=z9hG4bKs")) == 6000, "a top value without parameters: its own port, not the next value's");
|
||||
Check(!ViaResponsePort(row(top + ";x=\"a,b\";rport, " + next)).has_value(), "a comma in a quoted string does not end the top value");
|
||||
Check(ViaResponsePort(row(top + ";x=\"a,b\";branch=z9hG4bKp, " + next + ";rport=5060")) == 6000, "the comma behind that string's closing quote does");
|
||||
}
|
||||
|
||||
// ---- DatagramMessage (one UDP datagram = one message, RFC 3261 18.3)
|
||||
|
|
@ -204,6 +322,106 @@ int main() {
|
|||
Check(m3 && *m3 == hdr + "X-Note: Content-Length: 99\r\n\r\nv=0\n", "a header name inside a value does not match");
|
||||
auto m4 = DatagramMessage(hdr + "Content-Length: 99999999999999999999\r\n\r\nv=0\n", &why);
|
||||
Check(!m4.has_value(), "absurd Content-Length: discarded, no overflow");
|
||||
why.clear();
|
||||
Check(!DatagramMessage(hdr + "Content-Length: 18446744073709551616\r\n\r\nv=0\n", &why).has_value() && why.contains("truncated"), "nor is one that would wrap to zero: discarded as truncated");
|
||||
Check(DatagramMessage(hdr + "Content-Length: 00000000004\r\n\r\nv=0\nJUNK") == hdr + "Content-Length: 00000000004\r\n\r\nv=0\n", "a Content-Length of 4 written with ten zeros before it cuts the body at four bytes");
|
||||
Check(DatagramMessage(hdr + "Content-Length: x4\r\n\r\nv=0\nJUNK") == hdr + "Content-Length: x4\r\n\r\nv=0\nJUNK", "a Content-Length that begins with no digit: the body is the rest of the datagram");
|
||||
auto m5 = DatagramMessage(hdr + "l: 4\r\n\r\nv=0\nJUNK");
|
||||
Check(m5 && *m5 == hdr + "l: 4\r\n\r\nv=0\n", "`l:` that fits truncates the body like Content-Length");
|
||||
why.clear();
|
||||
Check(!DatagramMessage(hdr + "L : 40\r\n\r\nv=0\n", &why).has_value() && why.contains("truncated"), "`L :` larger than the datagram: discarded, problem set");
|
||||
}
|
||||
|
||||
// ---- CutShortRequest (a request whose datagram ends before its body does: the header section its 400 is built from, RFC 3261 18.3)
|
||||
{
|
||||
const std::string req = "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000;branch=z9hG4bK1\r\nCall-ID: c\r\nCSeq: 7 MESSAGE\r\n";
|
||||
Check(CutShortRequest(req + "Content-Length: 9\r\n\r\nhello") == req + "Content-Length: 9\r\n\r\n", "a request with five body bytes of nine: its header section and the empty line, no body");
|
||||
Check(CutShortRequest("\r\n\r\n" + req + "l: 6\r\n\r\nhello") == req + "l: 6\r\n\r\n", "line breaks before it are no part of it, and the length is found under its compact form");
|
||||
Check(CutShortRequest(req + "Content-Length: 0006\r\n\r\nhello").has_value(), "zeros before the length are no part of the number");
|
||||
Check(!CutShortRequest(req + "Content-Length: 5\r\n\r\nhello") && !CutShortRequest(req + "Content-Length: 4\r\n\r\nhello"), "a body that is all there, with or without bytes after it: none");
|
||||
Check(!CutShortRequest(req + "\r\nhello") && !CutShortRequest(req + "Content-Length: x9\r\n\r\nhello"), "no Content-Length, or one that begins with no digit: none (the body is the rest of the datagram)");
|
||||
Check(!CutShortRequest(req + "Content-Length: 9\r\n") && !CutShortRequest("\r\n\r\n") && !CutShortRequest(""), "no end of headers, line breaks alone, no bytes: none");
|
||||
Check(!CutShortRequest("SIP/2.0 200 OK\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("sip/2.0 200 OK\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "a response cut short: none (it is discarded), its version in upper or in lower case");
|
||||
Check(!CutShortRequest("SIP/2.0 200 SIP/2.0\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("sip/2.0 200 sip/2.0\r\nContent-Length: 9\r\n\r\nhello"), "nor is a status line a request's first line because its phrase ends like a version");
|
||||
Check(CutShortRequest("MESSAGE sip:a@example.net sip/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "a request whose version is in lower case is a request");
|
||||
Check(!CutShortRequest("MESSAGE sip:a@example.net SIP/2.01\r\nContent-Length: 9\r\n\r\nhello"), "a first line that ends in more than the version: none");
|
||||
Check(!CutShortRequest("MESSAGE sip:a@example.net SIP/3.0\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("MESSAGE sip:a@example.net bar1234\r\nContent-Length: 9\r\n\r\nhello"), "nor one that ends in another version, or in seven other bytes");
|
||||
Check(!CutShortRequest("l:9\r\n\r\n") && !CutShortRequest("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nhello"), "bytes that are no SIP, a Content-Length larger than what follows among them: none");
|
||||
Check(!CutShortRequest("ACK sip:a@example.net SIP/2.0\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "an ACK cut short: none");
|
||||
Check(!CutShortRequest("CANCEL sip:a@example.net SIP/2.0\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "a CANCEL cut short: none");
|
||||
Check(CutShortRequest("ACKNOWLEDGE sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value() && CutShortRequest("ack sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "a method that begins with ACK, or spells it in other letter case, is no ACK");
|
||||
Check(CutShortRequest("CANCELLED sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value() && CutShortRequest("cancel sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "nor is one that begins with CANCEL, or spells it in other letter case, a CANCEL");
|
||||
// the two agree on what is cut short: the same bytes skipped, the same length read, the same count of body bytes
|
||||
for (std::string_view tail : {"Content-Length: 9\r\n\r\nhello", "Content-Length: 5\r\n\r\nhello", "Content-Length: 4\r\n\r\nhello", "\r\nhello", "Content-Length: 9\r\n"}) {
|
||||
std::string why;
|
||||
const bool truncated = !DatagramMessage(req + std::string(tail), &why).has_value() && why.contains("truncated");
|
||||
Check(CutShortRequest(req + std::string(tail)).has_value() == truncated, std::format("a MESSAGE's header section comes exactly where DatagramMessage calls its datagram truncated ({:?})", tail));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Unfolded, and the framers that use it (RFC 3261 7.3.1: a line begun with a space or a tab goes on with the line before it)
|
||||
{
|
||||
Check(Unfolded("Subject: I know you're there,\r\n pick up the phone\r\n and talk to me!") == "Subject: I know you're there, pick up the phone and talk to me!", "7.3.1's own example: each line break and the white space after it are one space");
|
||||
Check(Unfolded("A: 1\r\n\t2") == "A: 1 2" && Unfolded("A: 1\r\n \t 2") == "A: 1 2", "a tab begins a continuation as a space does, and a run of them is one space");
|
||||
Check(Unfolded("A:\r\n 1") == "A: 1", "a value that begins on the next line");
|
||||
Check(Unfolded("A: 1 \r\n 2") == "A: 1 2", "white space before the line break is kept");
|
||||
Check(Unfolded("A: 1\n 2") == "A: 1 2", "a bare LF folds as a CRLF does");
|
||||
Check(Unfolded("A: 1\r\nB: 2\r\n") == "A: 1\r\nB: 2\r\n", "a line break that no white space follows is kept");
|
||||
Check(Unfolded("A: 1\r\n") == "A: 1\r\n" && Unfolded("A: 1\n") == "A: 1\n" && Unfolded("\n") == "\n" && Unfolded("").empty(), "a line break that ends the text is kept");
|
||||
Check(Unfolded("A: 1\r\n \r\n 2") == "A: 1 2", "a continuation line of white space alone");
|
||||
Check(Unfolded("A: 1\r 2") == "A: 1\r 2", "a CR alone is no line break");
|
||||
Check(Unfolded("A: 1\r\n ") == "A: 1 " && Unfolded("A: 1\r\n \t") == "A: 1 ", "white space after a line break that ends the text is that one space");
|
||||
Check(Unfolded("\n 1") == " 1" && Unfolded("\r\n\t1") == " 1", "a text that begins with a fold");
|
||||
// a 401 whose WWW-Authenticate goes over four lines, its nonce on the second
|
||||
const std::string folded401 =
|
||||
"SIP/2.0 401 Unauthorized\r\n"
|
||||
"Call-ID: f1@host\r\n"
|
||||
"CSeq: 1\r\n REGISTER\r\n"
|
||||
"WWW-Authenticate: Digest realm=\"ims.example\",\r\n"
|
||||
" nonce=\"bm9uY2U=\",\r\n"
|
||||
" algorithm=AKAv1-MD5,\r\n"
|
||||
" qop=\"auth\"\r\n"
|
||||
"Content-Length:\r\n"
|
||||
"\t5\r\n\r\n";
|
||||
const std::string body = "a\r\n b"; // a body line that begins with a space is no fold
|
||||
const std::string unfolded401 =
|
||||
"SIP/2.0 401 Unauthorized\r\n"
|
||||
"Call-ID: f1@host\r\n"
|
||||
"CSeq: 1 REGISTER\r\n"
|
||||
"WWW-Authenticate: Digest realm=\"ims.example\", nonce=\"bm9uY2U=\", algorithm=AKAv1-MD5, qop=\"auth\"\r\n"
|
||||
"Content-Length: 5\r\n\r\n";
|
||||
FrameBuffer fb;
|
||||
fb.Append(folded401 + body + Resp200);
|
||||
auto m = fb.TryExtract();
|
||||
Check(m == unfolded401 + body, "the stream framer hands a message out with its header section unfolded and its body as it came");
|
||||
Check(m && Header(*m, "WWW-Authenticate") == "Digest realm=\"ims.example\", nonce=\"bm9uY2U=\", algorithm=AKAv1-MD5, qop=\"auth\"", "a folded WWW-Authenticate is read whole");
|
||||
Check(m && ResponseOf(*m, "f1@host", "1 REGISTER"), "a CSeq folded between its number and its method is the transaction's");
|
||||
Check(fb.TryExtract() == Resp200 && !fb.TryExtract().has_value(), "a folded Content-Length frames the body: the next message starts after it");
|
||||
fb.Append(folded401 + body.substr(0, 3));
|
||||
Check(!fb.TryExtract().has_value(), "a body shorter than a folded Content-Length says is waited for");
|
||||
fb.Append(body.substr(3));
|
||||
Check(fb.TryExtract() == unfolded401 + body, "and taken once it is whole");
|
||||
std::string why;
|
||||
Check(DatagramMessage(folded401 + body + "JUNK", &why) == unfolded401 + body && why.empty(), "the datagram framer does the same, and cuts at a folded Content-Length");
|
||||
Check(!DatagramMessage(folded401 + "a\r\n ", &why).has_value() && why.contains("truncated"), "a datagram shorter than its folded Content-Length: discarded, problem set");
|
||||
Check(DatagramMessage("SIP/2.0 200 OK\r\nCall-ID:\r\n a\r\n\r\nv=0\r\n b") == "SIP/2.0 200 OK\r\nCall-ID: a\r\n\r\nv=0\r\n b", "no Content-Length: the header section unfolded, the rest of the datagram the body as it came");
|
||||
Check(CutShortRequest("MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP\r\n [2001:db8::2]:6000\r\nContent-Length:\r\n\t9\r\n\r\nhello") == "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000\r\nContent-Length: 9\r\n\r\n", "a request cut short of a folded Content-Length: its header section unfolded, for the 400");
|
||||
}
|
||||
|
||||
// ---- MinSe (the smallest session interval a 422 names, RFC 4028 5, 6)
|
||||
{
|
||||
auto r422 = [](std::string_view line) {
|
||||
return std::format("SIP/2.0 422 Session Interval Too Small\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\n{}Content-Length: 0\r\n\r\n", line);
|
||||
};
|
||||
Check(MinSe(r422("Min-SE: 3600\r\n")) == 3600, "Min-SE read");
|
||||
Check(MinSe(r422("min-se: 0090 ;x=1\r\n")) == 90, "Min-SE: any case of the name, spaces, zeros before the number, a parameter after it");
|
||||
Check(MinSe(r422("Min-SE: 999999999\r\n")) == 999999999, "Min-SE of nine digits read");
|
||||
Check(MinSe(r422("Min-SE: 0000000090\r\n")) == 90, "zeros before the number are no digits of it: ten characters, the number 90");
|
||||
Check(MinSe(r422("Min-SE: 0\r\n")) == 0, "Min-SE of zero read as zero");
|
||||
Check(!MinSe(r422("")), "no Min-SE header: none");
|
||||
Check(!MinSe(r422("Min-SE: soon\r\n")) && !MinSe(r422("Min-SE: -90\r\n")) && !MinSe(r422("Min-SE:\r\n")), "Min-SE that begins with no digit: none");
|
||||
Check(!MinSe(r422("Min-SE: 1000000000\r\n")) && !MinSe(r422("Min-SE: 99999999999999999999\r\n")), "Min-SE of more than nine digits: none");
|
||||
Check(!MinSe(r422("Session-Expires: 3600\r\n")), "a Session-Expires is no Min-SE");
|
||||
}
|
||||
|
||||
// ---- RetryAfter / RefusalSummary (what a refused final is logged as)
|
||||
|
|
@ -249,6 +467,26 @@ int main() {
|
|||
Check(ResponseOf(stale, "earlier@[2001:db8::db43]", "1 REGISTER"), "matched by Call-ID and CSeq");
|
||||
Check(!ResponseOf("NOTIFY sip:x SIP/2.0\r\nCall-ID: 12345@host\r\nCSeq: 2 REGISTER\r\n\r\n", "12345@host", "2 REGISTER"), "a request is never a response");
|
||||
Check(!ResponseOf("", "12345@host", "2 REGISTER"), "nothing is not it");
|
||||
Check(ResponseOf("SIP/2.0 202 Accepted\r\nv: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\ni: 12345@host\r\nCSeq: 1 MESSAGE\r\nl: 0\r\n\r\n", "12345@host", "1 MESSAGE"), "a final whose Call-ID comes as `i:` is the transaction's");
|
||||
// a provisional of the transaction is its response too: both REGISTER waits start over on one
|
||||
Check(ResponseOf("SIP/2.0 100 Trying\r\nCall-ID: 12345@host\r\nCSeq: 2 REGISTER\r\nContent-Length: 0\r\n\r\n", "12345@host", "2 REGISTER"), "the transaction's 100 Trying is its response");
|
||||
// the CSeq as its number and its method (RFC 3261 20.16: equal "if the sequence number and the request method are identical"; 25.1: 1*DIGIT LWS Method), whatever spaces or tabs part them
|
||||
auto finalWith = [](std::string_view cseq) { return std::format("SIP/2.0 202 Accepted\r\nCall-ID: 12345@host\r\nCSeq: {}\r\nContent-Length: 0\r\n\r\n", cseq); };
|
||||
Check(ResponseOf(finalWith("1 MESSAGE"), "12345@host", "1 MESSAGE"), "two spaces between the CSeq's number and its method: the transaction's");
|
||||
Check(ResponseOf(finalWith("1\tMESSAGE"), "12345@host", "1 MESSAGE"), "a tab between them: the transaction's");
|
||||
Check(ResponseOf(finalWith("1 \t MESSAGE"), "12345@host", "1 MESSAGE"), "spaces and a tab between them: the transaction's");
|
||||
Check(ResponseOf(finalWith("01 MESSAGE"), "12345@host", "1 MESSAGE") && ResponseOf(finalWith("1 MESSAGE"), "12345@host", "001 MESSAGE"), "zeros before the number do not make it another");
|
||||
Check(ResponseOf(finalWith("0 MESSAGE"), "12345@host", "00 MESSAGE") && !ResponseOf(finalWith("10 MESSAGE"), "12345@host", "1 MESSAGE"), "zero is zero however long, and a zero after the number counts");
|
||||
Check(ResponseOf(finalWith("1 MESSAGE"), "12345@host", " 1 MESSAGE "), "white space around the CSeq asked for is no part of it");
|
||||
Check(!ResponseOf(finalWith("11 MESSAGE"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1 MESSAGE"), "12345@host", "11 MESSAGE"), "another number that begins alike is not it");
|
||||
Check(!ResponseOf(finalWith("1 MESSAGES"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1 MESSAG"), "12345@host", "1 MESSAGE"), "another method that begins alike is not it");
|
||||
Check(!ResponseOf(finalWith("1 message"), "12345@host", "1 MESSAGE"), "a method is a case-sensitive token");
|
||||
Check(!ResponseOf(finalWith("1MESSAGE"), "12345@host", "1 MESSAGE"), "no white space between number and method: not a CSeq");
|
||||
Check(!ResponseOf(finalWith("1 "), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1"), "12345@host", "1 MESSAGE"), "a CSeq without a method is not it");
|
||||
Check(!ResponseOf(finalWith("MESSAGE"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith(" MESSAGE"), "12345@host", "1 MESSAGE"), "a CSeq without a number is not it");
|
||||
Check(!ResponseOf("SIP/2.0 202 Accepted\r\nCall-ID: 12345@host\r\nContent-Length: 0\r\n\r\n", "12345@host", "1 MESSAGE"), "a final without a CSeq is not it");
|
||||
Check(!ResponseOf(finalWith("1 MESSAGE"), "12345@host", "MESSAGE"), "asked with a CSeq of another shape: nothing is it");
|
||||
Check(!ResponseOf(finalWith("MESSAGE"), "12345@host", "MESSAGE") && !ResponseOf(finalWith("1MESSAGE"), "12345@host", "1MESSAGE"), "two CSeqs of another shape are no match, alike or not");
|
||||
}
|
||||
|
||||
// ---- RegInfoContactState: our binding in a reg-event NOTIFY (RFC 3680)
|
||||
|
|
@ -257,8 +495,8 @@ int main() {
|
|||
auto contact = [](std::string_view id, std::string_view state, std::string_view extra, std::string_view user) {
|
||||
return std::format(
|
||||
"\t\t<contact id=\"{}\" state=\"{}\"{}>\n"
|
||||
"\t\t\t<uri>sip:{}@[2a03:db8::1]:45062</uri>\n"
|
||||
"\t\t\t<unknown-param name=\"+sip.instance\">"<urn:gsma:imei:35901961-000000-0>" </unknown-param>\n"
|
||||
"\t\t\t<uri>sip:{}@[2001:db8::1]:45062</uri>\n"
|
||||
"\t\t\t<unknown-param name=\"+sip.instance\">"<urn:gsma:imei:35999999-000000-1>" </unknown-param>\n"
|
||||
"\t\t</contact>\n", id, state, extra, user);
|
||||
};
|
||||
auto reginfo = [](std::string_view contacts) {
|
||||
|
|
@ -333,6 +571,34 @@ int main() {
|
|||
Check(imsd::sip::Body("OPTIONS sip:x SIP/2.0\r\nCSeq: 1 OPTIONS\r\n").empty(), "Body: none without a terminator");
|
||||
}
|
||||
|
||||
// ---- WithoutHeader: a message less every line on which one header is
|
||||
// found
|
||||
{
|
||||
const std::string r =
|
||||
"SIP/2.0 200 OK\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"
|
||||
"Content-Type: text/plain\r\n"
|
||||
"Content-Length: 31\r\n"
|
||||
"\r\n"
|
||||
"P-Access-Network-Info: a body\r\n";
|
||||
const std::string bare =
|
||||
"SIP/2.0 200 OK\r\n"
|
||||
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
|
||||
"Content-Type: text/plain\r\n"
|
||||
"Content-Length: 31\r\n"
|
||||
"\r\n"
|
||||
"P-Access-Network-Info: a body\r\n";
|
||||
Check(WithoutHeader(r, "P-Access-Network-Info") == bare, "WithoutHeader: the header's line is gone, the other lines and a body line that spells its name stay");
|
||||
Check(WithoutHeader(bare, "P-Access-Network-Info") == bare, "WithoutHeader: a message without the header comes back as it is");
|
||||
Check(WithoutHeader(r, "p-access-network-info") == bare, "WithoutHeader: the name in another letter case");
|
||||
Check(WithoutHeader(r, "P-Access-Network") == r && WithoutHeader(r, "Access-Network-Info") == r, "WithoutHeader: a name that is only part of a header's name takes nothing");
|
||||
const std::string twice = "BYE sip:a@b SIP/2.0\r\nP-Access-Network-Info: one\r\nCSeq: 2 BYE\r\nP-Access-Network-Info: two\r\n\r\n";
|
||||
Check(WithoutHeader(twice, "P-Access-Network-Info") == "BYE sip:a@b SIP/2.0\r\nCSeq: 2 BYE\r\n\r\n", "WithoutHeader: every line of the name, the last before the empty line too");
|
||||
Check(WithoutHeader("SIP/2.0 200 OK\r\nVia: x\r\nP-Access-Network-Info: v", "P-Access-Network-Info") == "SIP/2.0 200 OK\r\nVia: x\r\n", "WithoutHeader: a last line without its line end");
|
||||
Check(WithoutHeader("SIP/2.0 200 OK\r\nv: x\r\nTo: y\r\nVia: z\r\n\r\n", "Via") == "SIP/2.0 200 OK\r\nTo: y\r\n\r\n", "WithoutHeader: a header under its compact form goes as under its long one");
|
||||
}
|
||||
|
||||
if (Failures == 0) std::println("Sip: all tests passed");
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@
|
|||
// you?" PDU and vectors cross-generated by the fp6 journal's Python
|
||||
// reference: a header with fill bits, a 16-bit concatenation reference, a
|
||||
// class-0 message, port-addressed 8-bit data, an alphanumeric sender, a
|
||||
// negative time zone), SMS-STATUS-REPORT and SMS-SUBMIT-REPORT, the
|
||||
// RP-DATA / RP-ACK / RP-ERROR messages both ways, EF_SMSP with the KPN
|
||||
// negative time zone), SMS-STATUS-REPORT and SMS-SUBMIT-REPORT (the
|
||||
// duplicate rejection's TP-FCS among its causes), the
|
||||
// RP-DATA / RP-ACK / RP-ERROR messages both ways, which RP causes of a
|
||||
// submission invite a repeat, EF_SMSP with the KPN
|
||||
// SIM's record, qmicli's hex dump, and the reassembly of a concatenated
|
||||
// message.
|
||||
import std;
|
||||
|
|
@ -136,6 +138,12 @@ namespace {
|
|||
Check(to.size() == 1, "SUBMIT with a status report requested: one segment");
|
||||
if (!to.empty()) Eq(to[0], "31010A9113163254760000A902C834", "SMS-SUBMIT: status report requested, TP-VP A9, an even number of digits");
|
||||
|
||||
Submit r = o;
|
||||
r.rejectDuplicates = true;
|
||||
auto tr = BuildSubmits(r, "Hi", 0);
|
||||
Check(tr.size() == 1, "SUBMIT with TP-RD: one segment");
|
||||
if (!tr.empty()) Eq(tr[0], "35010A9113163254760000A902C834", "SMS-SUBMIT with TP-RD: bit 2 of the first octet set, the rest as without it");
|
||||
|
||||
Submit c{"+31612345678", 10};
|
||||
std::string longText(153, 'A');
|
||||
longText += std::string(8, 'B');
|
||||
|
|
@ -145,6 +153,12 @@ namespace {
|
|||
Eq(tc[0], "410A0B911316325476F80000A00500032A020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683", "segment 1/2: UDHI, the concatenation header, 153 septets after one fill bit, TP-MR 10");
|
||||
Eq(tc[1], "410B0B911316325476F800000F0500032A02028442A15028140A01", "segment 2/2: TP-MR 11, 8 septets");
|
||||
}
|
||||
auto tw = BuildSubmits(c, Rep("ü", 70) + "❤", 0x2A);
|
||||
Check(tw.size() == 2, "71 UCS-2 characters: two segments");
|
||||
if (tw.size() == 2) {
|
||||
Eq(tw[0], "410A0B911316325476F800088C0500032A0201" + Rep("00FC", 67), "UCS-2 segment 1/2: TP-MR 10, the header and 67 characters in 140 octets");
|
||||
Eq(tw[1], "410B0B911316325476F800080E0500032A020200FC00FC00FC2764", "UCS-2 segment 2/2: TP-MR 11, the header and four characters");
|
||||
}
|
||||
Check(BuildSubmits(c, std::string(160, 'A'), 1).size() == 1, "160 characters fit one message");
|
||||
Check(BuildSubmits(c, std::string(161, 'A'), 1).size() == 2, "161 characters need two");
|
||||
Check(BuildSubmits(c, Rep("ü", 70) + "❤", 1).size() == 2, "71 UCS-2 characters need two");
|
||||
|
|
@ -293,6 +307,8 @@ namespace {
|
|||
Check(udhi && udhi->failureCause == 0xC3, "TP-UDHI (bit 6) is no unused bit: the cause as sent");
|
||||
EqS(ScTimeStamp(Hex("621AF12205A0A0")), "2026-01-10T22:50:00+00:00", "SCTS: a semi-octet that is no digit reads as 0, in the zone too (9.2.3.11)");
|
||||
EqS(FailureCauseText(0xC3), "invalid SME address", "TP-FCS C3");
|
||||
Check(FcsDuplicateRejected == 0xC5, "TP-FCS C5 is the duplicate rejection (9.2.3.22)");
|
||||
EqS(FailureCauseText(FcsDuplicateRejected), "duplicate short message rejected", "TP-FCS C5 in words");
|
||||
Eq(DeliverReportAck(), "0000", "SMS-DELIVER-REPORT for RP-ACK");
|
||||
Eq(DeliverReportError(0xFF), "00FF00", "SMS-DELIVER-REPORT for RP-ERROR");
|
||||
}
|
||||
|
|
@ -317,6 +333,15 @@ namespace {
|
|||
auto errMt = ParseRp(Hex("052A011C410A01C30062016122050080"));
|
||||
Check(errMt && errMt->type == RpType::ErrorMt && errMt->cause == 28 && !errMt->diagnostic && errMt->tpdu.size() == 10, "RP-ERROR network to MS with a submit report");
|
||||
EqS(RpCauseText(28), "unidentified subscriber", "RP cause 28");
|
||||
// a submission's RP-ERROR invites another attempt at once for cause 41 (TS 24.011 Annex E-2) and for a value table 8.4's part 1 does not list (treated as 41)
|
||||
{
|
||||
const std::set<int> listed{1, 8, 10, 11, 21, 27, 28, 29, 30, 38, 41, 42, 47, 50, 69, 81, 95, 96, 97, 98, 99, 111, 127};
|
||||
bool asTabled = true;
|
||||
for (int cause = 0; cause < 128; cause++)
|
||||
if (RpCauseIsTemporary(static_cast<std::uint8_t>(cause)) != (cause == 41 || !listed.contains(cause))) asTabled = false;
|
||||
Check(asTabled && listed.size() == 23, "RpCauseIsTemporary over the 128 cause values: 41, and whatever part 1's 23 do not list");
|
||||
Check(RpCauseIsTemporary(41) && RpCauseIsTemporary(0x80 | 41) && !RpCauseIsTemporary(28) && !RpCauseIsTemporary(0x80 | 28) && RpCauseIsTemporary(2) && !RpCauseIsTemporary(11), "RpCauseIsTemporary: the extension bit is no part of the value; an unlisted 2 invites a repeat, the reserved 11 is listed");
|
||||
}
|
||||
auto diag = ParseRp(Hex("0507022611"));
|
||||
Check(diag && diag->cause == 38 && diag->diagnostic == 0x11 && diag->tpdu.empty(), "RP-ERROR with a diagnostic octet");
|
||||
Check(!ParseRp(Hex("05")), "one byte: nothing");
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
// Imsd:Util unit tests — MD5 against the RFC 1321 test suite, base64/hex
|
||||
// decoding, host/port formatting, the RFC 5952 canonical IPv6 text and the
|
||||
// address-list parser, and the deterministic-seed RNG. MD5 and
|
||||
// address-list parser, a setting's count of seconds, and the deterministic-seed RNG. MD5 and
|
||||
// base64 are our own (the standard library ships neither) and the AKAv1-MD5
|
||||
// digest depends on them exactly, so these are pinned hard.
|
||||
import std;
|
||||
|
|
@ -136,6 +136,16 @@ int main() {
|
|||
Check(ParseAddressList("2001:db8::1").size() == 1, "list: single entry, no rejected sink");
|
||||
}
|
||||
|
||||
// ---- WholeSeconds: a setting that counts seconds (CRLF_KEEPALIVE=)
|
||||
{
|
||||
Check(WholeSeconds("30") == 30, "seconds: 30");
|
||||
Check(WholeSeconds("0") == 0, "seconds: 0");
|
||||
Check(WholeSeconds("0840") == 840, "seconds: leading zero");
|
||||
Check(WholeSeconds("9876543210") == 9876543210L, "seconds: every digit, past an int");
|
||||
for (std::string_view s : {"", " 30", "30 ", "30s", "-30", "+30", "30.5", "0x1e", "1e2", "nan", "inf", "thirty", "99999999999999999999"})
|
||||
Check(!WholeSeconds(s), std::format("seconds: '{}' is no count of seconds", s));
|
||||
}
|
||||
|
||||
if (Failures == 0) std::println("Util: all tests passed");
|
||||
return Failures;
|
||||
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue