diff --git a/AGENTS.md b/AGENTS.md index 13c2710..36f0854 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,13 +41,13 @@ PipeWire. The verified device/carrier combinations are in the README. | `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. | | `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the nine partitions below. | | `interfaces/Imsd-Util.cppm` | `imsd::util` — SIP tokens, IPv6 host/port formatting, the RFC 5952 §4 IPv6 text (`CanonicalIp6`/`CanonicalAddr`; an IPv4-mapped address spelled in hex stays hex, where §5 and `inet_ntop` write it dotted) and the comma-separated address-list parser (`ParseAddressList`), hex/base64, MD5 (RFC 1321), the fixed protected ports `PortUc`/`PortUs` (45061/45062). | -| `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching. Not a full RFC 3261 parser, deliberately. | +| `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching. Not a full RFC 3261 parser, deliberately. | | `interfaces/Imsd-Sdp.cppm` | `imsd::sdp` — SDP offer/answer: the AMR-WB + AMR + telephone-event offer (optional IR.92 preconditions; `OfferedTelephoneEventPt` names its telephone-event numbers), the parser the media plane needs (the codec, its payload type and mode, and the telephone-event payload type the m-line lists at that codec's clock), `BuildAnswer` for the terminating side, the `CODECS` override. | | `interfaces/Imsd-Sms.cppm` | `imsd::sms` — the short message codecs SMS over IP rides on (TS 24.341 carries the bytes a 2G/3G phone puts in an RP-DATA, in a SIP MESSAGE body): the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 (TS 23.038); the SM-TL PDUs (TS 23.040: SMS-SUBMIT built, one per segment with the concatenation header when the text needs more than one; SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed; the SMS-DELIVER-REPORT that acknowledges a delivery; the user-data header — concatenation, application ports — and the `Reassembler` of a concatenated message); the SM-RL messages (TS 24.011: RP-DATA, RP-ACK, RP-ERROR in both directions, the cause values); EF_SMSP (TS 31.102 §4.2.27), where the (U)SIM names the service centre, and qmicli's hex dump of it. Byte-level only: no SIP, no clock, no I/O. | | `interfaces/Imsd-Aka.cppm` | `imsd::aka` — USIM AKA glue: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response. | | `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two 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 kernel's pair (unknown on either side decides nothing). | -| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite, which calls every builder but `BuildInviteResponse` (`tests/Engine` checks the responses `CallMachine` builds with it). Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each `Via:` line echoed in order (the text layer reads long header names only, not RFC 3261 7.3.3's compact forms) and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. | -| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first `Via:` line and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | +| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite. Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. | +| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | | `interfaces/Imsd-Qmi.cppm` | `imsd::qmi` — the QMI WDS request bytes `imsd-pcscf` sends (Bind Mux Data Port, Set IP Family, Get Packet Service Status, Get Current Settings, Get Profile Settings), the message/TLV parser, the P-CSCF list readers (0x22 flag, 0x23 IPv4, 0x24 FQDN, 0x2E IPv6 — the last one libqmi does not model). | | `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control and messaging (`Gated`'s `Action` parameter names the action), shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. | | `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. | @@ -280,15 +280,31 @@ What the suites pin: - `Messages` — the outgoing SIP messages: the initial and the protected REGISTER, the reg-event SUBSCRIBE and the INVITEs byte-for-byte, their variants, the in-dialog requests, the ACKs, the CANCEL and - `BuildResponse200` by their lines, `BuildInviteResponse` not there - (`tests/Engine` checks the responses `CallMachine` builds with it); the + `BuildResponse200` by their lines, `BuildInviteResponse` by the lines of + one 180 and by a 486 without a Record-Route (`tests/Engine` checks the + responses `CallMachine` builds with it); the SMS over IP shapes (the `+g.3gpp.smsip` tag, the MESSAGE with an RP-DATA, the delivery report - with In-Reply-To, a 488) pinned against TS 24.341's clauses. + with In-Reply-To, a 488) pinned against TS 24.341's clauses; `BuildResponse`, + `BuildResponse200` and `BuildInviteResponse` on a request whose header + names come in compact form. - `Sip` — the text layer's edge cases (empty header values, line anchoring, keepalive discards, a header read that stops at the first empty line — a body line spelling a header name picks nothing, leading empty lines are - skipped), `ResponseOf`, refused finals with reason headers, + skipped), the twelve compact forms (each through `Header`, in lower and + in upper case, and through `Headers`; no other letter taken for a + header name the suite lists; `l:` through the framer and + `DatagramMessage`), `ViaResponsePort`'s reading of a Via row — `rport` by its name (in + another case, with white space around it, with a value; those letters + in a value, in a longer name or in a quoted string not; a quoted string + ended by its closing quote — not by a quoted pair in it, and by the + quote behind an escaped backslash —), and of a row that holds a list + the top value alone (its port, a later value's `rport` and port not + counted, its own `rport` counted, last before the comma too; a comma + in a quoted string no end of it, the comma behind the closing quote + its end) —, white space before the colon (RFC 3261 7.3.1's four + spellings), + `ResponseOf`, refused finals with reason headers, reginfo documents, `HeaderUri` and `Body`. A change that flips one of those tests is a behaviour change, not a cleanup. - `Sdp` — the offer's exact bytes, the parser (the telephone-event payload @@ -323,7 +339,8 @@ What the suites pin: call, without the negotiation, for a character that is no tone or for a string past `DtmfMaxTones`; the receive payload type: our offer's on a renumbered answer, the answer's when the audio took ours, the echoed - offer's on an incoming call) and + offer's on an incoming call; an incoming call from an INVITE, and an + outgoing call from responses, whose header names come in compact form) and `RegRecovery` (thresholds, backoffs, the throttle schedule, Retry-After, which waits a Dial may cut short, when the old registration counts as gone, the holds a restart takes over, a binding the @@ -342,6 +359,10 @@ What the suites pin: In-Reply-To for no message, an unusable TPDU acknowledged with an RP-ERROR, a body that is no RP message, a page-mode text 200'd and logged, a short message while SMS over IP is off refused with 480; + a delivered MESSAGE whose header names come in compact form — the 200 and + the delivery report of its long form, its retransmission key, the 480 + while SMS over IP is off — and a final in compact form taken by the + message in flight; a submit report before the MESSAGE's own final taken — the message sent and the late final nobody's; with two segments the second goes out under its own Call-ID — a text past 255 segments failed at once naming the fit, @@ -1561,15 +1582,15 @@ unmeasured. A MESSAGE outside a call's dialog whose `Content-Type` does not contain `application/vnd.3gpp.sms`, letter case ignored — a page-mode MESSAGE — is still answered 200 and logged with its body: the 200 is `BuildResponse`'s -now and the line names the content type (§7.8). Every header of a MESSAGE -is read by its long name, on one line with the colon straight after the -name: a compact form (RFC 3261 7.3.3) is not seen, so -a `c:` line is no `Content-Type`, an `i:` line no Call-ID and a `v:` line -no `Via`; nor is a name with white space before its colon, and of a value -folded onto further lines the first is read (7.3.1 allows both). +now and the line names the content type (§7.8). A header imsd reads is +found under its long name or, where it has one, its compact form (RFC +3261 7.3.3: a `c:` line is a `Content-Type`, an `i:` line a Call-ID, a +`v:` line a Via), with or without white space before the colon; of a +value folded onto further lines the first line is read (7.3.1 allows the +fold). - **A retransmitted MESSAGE** (the same Call-ID, CSeq and Via branch — the - value of the first `branch=` of its first `Via:` line; a MESSAGE with none + value of the first `branch=` of its first Via row; a MESSAGE with none or an empty one is never taken for a copy — within 32 s of our final: `RecentTransactions`, standing in for RFC 3261 17.2.2's server transaction) gets that final again and is not diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index 3fe5969..b31c72e 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -16,8 +16,8 @@ Covers: the unprotected + protected REGISTER and the refresh re-REGISTER 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 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 @@ -522,9 +522,8 @@ 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 // outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index 925cd3f..006c56b 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -7,9 +7,11 @@ 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. +loggable and testable verbatim. 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,52 @@ 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 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 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), so of a value folded onto further lines (7.3.1) + // the first line is read. + std::optional 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 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 LeadingDigits(std::string_view s) { std::size_t n = 0; @@ -223,13 +268,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 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; diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index c9052b3..3615e0c 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -10,7 +10,9 @@ // reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming // what was offered), a landline gateway's G.711-only and AMR-NB offers // ring and are answered at the offer's own payload types, ring timeout -> -// 480, BYE both ways. DTMF: the tones reach the media leg on an active +// 480, BYE both ways; an incoming call from an INVITE, and an outgoing +// call from responses, whose header names come in compact form (RFC 3261 +// 7.3.3). DTMF: the tones reach the media leg on an active // call that negotiated telephone-event, and are dropped — with the reason // — before the answer, after the call, without the negotiation or with a // character that is no tone. Then RegRecovery, the registration recovery policy: @@ -38,7 +40,8 @@ // report routed to the message in flight, 488 for one that is not ours, an // unusable TPDU acknowledged with an RP-ERROR, a body that is no RP // message, a page-mode text 200'd and logged, a short message while SMS -// over IP is off refused with 480), and the store's record codec +// over IP is off refused with 480, a delivered MESSAGE and a final whose +// header names come in compact form), and the store's record codec // (FormatStoredSms/ParseStoredSms: a full record round trip, defaults // for absent keys, a value that does not parse or a missing id refused) and order // (StoredSmsBefore: the arrival second, then within a run the sequence @@ -199,6 +202,20 @@ namespace { "Content-Length: {}\r\n\r\n{}", extraHeaders, sdp.size(), sdp); } + + // The same message with the header names that have a compact form + // written in it (RFC 3261 7.3.3: Via, From, To, Call-ID, Contact, + // Content-Type, Content-Length, Supported; Event, Session-Expires) — + // in the header section only, the start line and the body as they are. + std::string Compact(std::string_view msg) { + const std::size_t end = msg.find("\r\n\r\n"); + std::string head(msg.substr(0, end)); + for (auto [name, letter] : std::initializer_list>{ + {"\r\nVia:", "\r\nv:"}, {"\r\nFrom:", "\r\nf:"}, {"\r\nTo:", "\r\nt:"}, {"\r\nCall-ID:", "\r\ni:"}, {"\r\nContact:", "\r\nm:"}, + {"\r\nContent-Type:", "\r\nc:"}, {"\r\nContent-Length:", "\r\nl:"}, {"\r\nSupported:", "\r\nk:"}, {"\r\nEvent:", "\r\no:"}, {"\r\nSession-Expires:", "\r\nx:"}}) + for (std::size_t at = 0; (at = head.find(name, at)) != std::string::npos; at += letter.size()) head.replace(at, name.size(), letter); + return end == std::string_view::npos ? head : head + std::string(msg.substr(end)); + } } int main() { @@ -754,6 +771,56 @@ int main() { Check(t && t->reason == "local-hangup", "active hangup -> local-hangup"); } + // ---- an incoming call whose INVITE carries its header names in compact + // form (RFC 3261 7.3.3: "MUST accept both the long and short forms"): + // the same dialog as from the long names + { + const std::string invite = Compact(MtInvite()); + Check(!invite.contains("Via:") && !invite.contains("From:") && !invite.contains("\r\nTo:") && !invite.contains("Call-ID:") && !invite.contains("Contact:") && !invite.contains("Session-Expires:") && !invite.contains("Content-Type:") && !invite.contains("Content-Length:"), "the compact INVITE carries none of the eight long names"); + Check(invite.contains("\r\nv: SIP/2.0/UDP [2001:db8::9]:5060;branch=z9hG4bKscscf1\r\n") && invite.contains("\r\ni: mt-call-abc123\r\n") && invite.contains("\r\nx: 1800\r\n") && invite.ends_with("a=ptime:20\r\na=sendrecv\r\n"), "...their compact forms instead, the body untouched"); + imsd::util::Rng rng(33); + CallMachine m(c, rng, "ims-call-70", IncomingInvite{invite}, 50004); + Check(m.CallId() == "mt-call-abc123" && m.Number() == "+31612345678", "compact INVITE: the Call-ID from `i:`"); + auto ai = m.OnInvite(); + const Action* ringing = Responded(ai, "SIP/2.0 180 Ringing"); + Check(ringing && ringing->text.contains("\r\nVia: SIP/2.0/UDP [2001:db8::105]:5100;branch=z9hG4bKpcscf1\r\nVia: SIP/2.0/UDP [2001:db8::9]:5060;branch=z9hG4bKscscf1\r\n"), "compact INVITE: the 180 echoes both `v:` rows, in order, as Via"); + Check(ringing && ringing->text.contains("\r\nFrom: ;tag=caller1\r\n") && ringing->text.contains("\r\nTo: ;tag=") && ringing->text.contains("\r\nCall-ID: mt-call-abc123\r\n"), "compact INVITE: the 180 echoes the `f:`, the `t:` with our tag and the `i:`"); + auto aa = m.OnAccept(); + const Action* ok = Responded(aa, "SIP/2.0 200 OK"); + const Action* media = Find(aa, Action::Type::StartMedia); + Check(ok && ok->text.contains("Session-Expires: 1800;refresher=uac\r\n") && media && media->media.remotePort == 27864 && m.State() == CallState::Active, "compact INVITE: the 200 echoes the `x:` session timer, the offer is answered"); + // a refresh whose Session-Expires comes as `x:` + const std::string upd = Compact(std::format( + "UPDATE sip:me SIP/2.0\r\nVia: SIP/2.0/UDP [x]:1;branch=z9hG4bKu2\r\n" + "From: ;tag=caller1\r\n" + "To: ;tag=x\r\n" + "Min-SE: 90\r\nSession-Expires: 1800;refresher=uac\r\n" + "Call-ID: {}\r\nCSeq: 3 UPDATE\r\nContent-Length: 0\r\n\r\n", m.CallId())); + auto au = m.OnRequest(upd); + const Action* se200 = Responded(au, "SIP/2.0 200 OK"); + Check(upd.contains("\r\nx: 1800;refresher=uac\r\n") && se200 && se200->text.contains("Session-Expires: 1800;refresher=uac\r\n") && se200->text.contains("\r\nVia: SIP/2.0/UDP [x]:1;branch=z9hG4bKu2\r\n") && se200->text.contains(std::format("\r\nCall-ID: {}\r\n", m.CallId())), "compact UPDATE: the 200 echoes the `x:` timer and the `v:`, `i:` rows"); + // our BYE: to the caller's `m:` Contact, the `f:` From as its To, the `t:` To's URI as its From + auto ah = m.OnHangup(); + const Action* bye = Sent(ah, "BYE "); + Check(bye && bye->text.starts_with("BYE sip:origgw@[2001:db8::9]:5060 SIP/2.0\r\n") && bye->text.contains("\r\nTo: ;tag=caller1\r\n") && bye->text.contains("\r\nFrom: ;tag=") && bye->text.contains("\r\nCall-ID: mt-call-abc123\r\n"), "compact INVITE: our BYE goes to the `m:` Contact with the dialog the `f:`, `t:` and `i:` rows made"); + } + + // ---- an outgoing call whose responses carry compact names: the dialog + // from `t:` and `m:` + { + imsd::util::Rng rng(42); + CallMachine m(c, rng, "ims-call-71", "1233", 50004, false); + m.Start(); + const std::string r183 = Compact(R183(m.CallId())), r200 = Compact(R200(m.CallId())); + Check(!r183.contains("\r\nTo:") && !r183.contains("Contact:") && r183.contains("\r\nt: ;tag=remote7\r\n") && r200.contains("\r\nm: \r\n"), "the compact responses carry `t:` and `m:`"); + auto a183 = m.OnInviteResponse(r183); + const Action* prack = Sent(a183, "PRACK "); + Check(prack && prack->text.starts_with("PRACK sip:termgw@[2001:db8::9]:5060 SIP/2.0\r\n") && prack->text.contains("\r\nTo: ;tag=remote7\r\n"), "compact 183: the PRACK targets the `m:` Contact and carries the `t:` To"); + auto a200 = m.OnInviteResponse(r200); + const Action* ack = Sent(a200, "ACK "); + Check(ack && ack->text.starts_with("ACK sip:termgw@[2001:db8::9]:5060 SIP/2.0\r\n") && ack->text.contains("\r\nTo: ;tag=remote7\r\n") && Has(a200, Action::Type::StartMedia) && m.State() == CallState::Active, "compact 200: the ACK to the `m:` Contact with the `t:` To, the call active"); + } + // ---- media death after accept releases the call { imsd::util::Rng rng(35); @@ -1490,6 +1557,28 @@ int main() { const auto* repo = findSms(ro.actions, SmsAction::Type::SendClient); Check(repo && repo->text.starts_with("MESSAGE sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org SIP/2.0\r\n"), "inbound: with a From that names another, the report still goes to the P-Asserted-Identity"); } + // the same delivery with its header names in compact form (RFC 3261 7.3.3): `c:` is the content type, `i:` the Call-ID, `v:` the Via + { + const std::string longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"); + const std::string compact = Compact(longForm); + Check(!compact.contains("Content-Type:") && !compact.contains("Call-ID:") && !compact.contains("Via:") && compact.contains("\r\nc: application/vnd.3gpp.sms\r\n") && compact.contains("\r\ni: in-011107@net\r\n") && compact.contains("\r\nv: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn1\r\n") && compact.contains(std::format("\r\nl: {}\r\n", imsd::sip::Body(longForm).size())) && imsd::sip::Body(longForm).size() == 42 && imsd::sip::Body(compact) == imsd::sip::Body(longForm), "the compact MESSAGE carries `c:`, `i:`, `v:` and `l:`, the body of 42 bytes as it was"); + imsd::util::Rng rng(80), rngLong(80); + Reassembler re, reLong; + auto r = OnSmsMessage(c, rng, compact, re, nullptr, 50.0); + auto want = OnSmsMessage(c, rngLong, longForm, reLong, nullptr, 50.0); + const auto* rec = findSms(r.actions, SmsAction::Type::Received); + const auto* rep = findSms(r.actions, SmsAction::Type::SendClient); + const auto* wantRep = findSms(want.actions, SmsAction::Type::SendClient); + Check(r.response == want.response && r.response.starts_with("SIP/2.0 200 OK\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn1\r\n") && r.response.contains("\r\nCall-ID: in-011107@net\r\n"), "compact MESSAGE: the 200 of the long form, the `v:` and the `i:` echoed as Via and Call-ID"); + Check(rec && rec->received.text == "How are you?" && rep && wantRep && rep->text == wantRep->text && rep->text.contains("\r\nIn-Reply-To: in-011107@net\r\n"), "compact MESSAGE: taken for a short message, and its delivery report names the `i:` Call-ID in In-Reply-To"); + Check(RecentTransactions::Key(compact) == "in-011107@net|1 MESSAGE|z9hG4bKn1" && RecentTransactions::Key(compact) == RecentTransactions::Key(longForm), "compact MESSAGE: the retransmission key from `i:` and `v:`"); + // the final to a MESSAGE of ours, its Call-ID as `i:` + imsd::util::Rng rngOut(81); + SmsOutbound m(c, rngOut, "ims-sms-20", p); + const std::string callid(imsd::sip::Header(findSms(m.Start(0.0), SmsAction::Type::SendClient)->text, "Call-ID").value_or("")); + const std::string final202 = Compact(final(callid, 202, "Accepted")); + Check(final202.contains(std::format("\r\ni: {}\r\n", callid)) && !final202.contains("Call-ID:") && m.OwnsResponse(final202), "outbound: a final whose Call-ID comes as `i:` is the message in flight's"); + } // a Call-ID the delivery report cannot carry — a byte up to 0x20 in it (but an LF, which ends the line) or a DEL: no In-Reply-To, the message and its report as ever for (int b = 0; b <= 0x7F; b++) { if ((b > 0x20 && b != 0x7F) || b == 0x0A) continue; @@ -1735,6 +1824,8 @@ int main() { const std::string plain = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn3\r\nFrom: ;tag=1\r\nTo: \r\nCall-ID: t2@net\r\nCSeq: 1 MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: 2\r\n\r\nhi"; auto r2 = OnSmsMessage(off, rng, plain, re, nullptr, 9.0); Check(r2.response.starts_with("SIP/2.0 200 OK") && hasSms(r2.actions, SmsAction::Type::Log), "off: a page-mode text is still 200'd and logged"); + auto r3 = OnSmsMessage(off, rng, Compact(offered), re, nullptr, 9.5); + Check(r3.response.starts_with("SIP/2.0 480 Temporarily Unavailable\r\n") && r3.response.contains("\r\nCall-ID: in-011107@net\r\n") && !r3.rp, "off: a short message whose content type comes as `c:` is refused with 480 too"); } } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 519ed15..974507b 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -5,7 +5,8 @@ // 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: // the REGISTER Contact carries +sip.instance and the MMTEL ICSI feature tag @@ -501,6 +502,56 @@ int main() { "Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To"); 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: ;tag=N2\r\nTo: ;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: ;tag=had\r\n"), "a To that already carries a tag is echoed 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: ;tag=N1\r\n" + "t: \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: ;tag=N1\r\nTo: \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: \r\n" + "From: ;tag=N3\r\n" + "To: \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: \r\n" + "f: ;tag=N3\r\n" + "t: \r\n" + "i: call3@net\r\n" + "CSeq: 1 INVITE\r\n" + "l: 0\r\n\r\n"; + 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: \r\n" + "From: ;tag=N3\r\n" + "To: ;tag=T180\r\n" + "Call-ID: call3@net\r\n" + "CSeq: 1 INVITE\r\n" + "Contact: \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"); + 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: ;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"; diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 2844f07..77fc8b8 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -1,14 +1,15 @@ // 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, 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) —, a refused final's Retry-After and summary (RetryAfter, -// RefusalSummary), transaction matching (ResponseOf), our binding in a -// reg-event document (RegInfoContactState), and HeaderUri and Body. 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) —, +// a refused final's Retry-After and summary (RetryAfter, RefusalSummary), +// transaction matching (ResponseOf), our binding in a reg-event document +// (RegInfoContactState), and HeaderUri and Body. These pin the module's +// edge-case behavior; see the module header before "fixing" one. import std; import Imsd; @@ -69,6 +70,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 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(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{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: \r\ns: active\r\n\r\n", "Record-Route").has_value() && !Header("NOTIFY sip:a@b SIP/2.0\r\nr: \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{"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"); @@ -123,6 +181,18 @@ int main() { Check(fb.TryExtract() == msg, "no Content-Length -> body length 0"); Check(fb.Size() == 8, "trailing bytes stay buffered"); } + { + // 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 { @@ -163,6 +233,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: ;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\" ;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: ;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 = @@ -186,6 +264,25 @@ 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"); + 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) @@ -208,6 +305,10 @@ 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"); + 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"); } // ---- RetryAfter / RefusalSummary (what a refused final is logged as) @@ -253,6 +354,7 @@ 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"); } // ---- RegInfoContactState: our binding in a reg-event NOTIFY (RFC 3680)