From 7cae603c0cfba5624ff70fe77fb04970c52e2fe0 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH] sip, messages, imsd: the client flow answers a request datagram cut short of the Content-Length it reads with a 400, unless an ACK or a CANCEL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 3261 18.3 on 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 client flow's datagram read ignored either, where the Content-Length it read said more bytes than came, with one line, `UDP: datagram truncated (…) — ignored`. CutShortRequest gives the header section of a request whose datagram has fewer body bytes than the Content-Length read from it says, and BuildBadRequest the 400 for it, in the shape of BuildResponse's finals: every Via row echoed, the To tagged unless it holds a tag. The client flow sends that 400 and its line ends `— answered 400`. Such a request is known by its first line, which ends with the SIP version where a status line begins with it (7.1, 7.2), in upper or in lower case: a response cut short so, bytes that are no SIP cut short so and a datagram without an end of headers are ignored as before. imsd keeps nothing of a request it answers so, and follows 8.2.7 for an element that answers without state: a To tag it adds is made from the request's header section and a secret drawn once for the run, "in a manner that will generate the same tag for the same request consistently", and an ACK or a CANCEL cut short so gets no answer. The server ports and the init port hand a datagram on as it came, as before this commit. Tested by tests/Sip (CutShortRequest: the header section of a request cut short, with line breaks before it, under a compact Content-Length and with its version in lower case; nothing for a body that is all there, no Content-Length, no end of headers, a response in either letter case, bytes that are no SIP, an ACK, a CANCEL) and by tests/Messages (the 400 by its lines, its tag against Python's hashlib; the same request, the same 400; another request or another secret, another tag). On the workstation's loopback, SipFlow built around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture, cut-short, at this commit and at the one before): a MESSAGE with five body bytes of nine draws the 400, and the same one when it is sent again, where the commit before ignored it; a response cut short the same way, in upper and in lower case, an ACK, a CANCEL, bytes that are no SIP and a request without an end of headers draw nothing at either commit; the MESSAGE with its Content-Length folded is handed on at either commit, a folded value being read by its first line; a whole request sent after them is returned by the flow. --- AGENTS.md | 45 +++++++++++++++++++++++++++++++---- implementations/main.cpp | 20 ++++++++++++++-- interfaces/Imsd-Messages.cppm | 13 ++++++++++ interfaces/Imsd-Sip.cppm | 31 ++++++++++++++++++++++++ tests/Messages/main.cpp | 30 +++++++++++++++++++++++ tests/Sip/main.cpp | 36 ++++++++++++++++++++++++---- 6 files changed, 164 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 23f6b4f..d860264 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,12 +41,12 @@ 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; 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 (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number). 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 (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. 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. 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-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); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, 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`. | @@ -287,13 +287,25 @@ What the suites pin: `+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; `BuildResponse`, `BuildResponse200` and `BuildInviteResponse` on a request whose header - names come in compact form. + names come in compact form; `BuildBadRequest` by the lines of one 400 + (every Via row echoed; the To tag sixteen hex digits of the MD5 of a + secret and the header section, the expected one from Python's hashlib; + the same request, the same 400; another request, another tag; another + secret, another tag; a To's own tag kept). - `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), the Content-Length the two framers read (zeros before its number no part of it; a number past any that fits not read as zero; a - value that begins with no digit read as none), the twelve compact forms (each through `Header`, in lower and + value that begins with no digit read as none), `CutShortRequest` (the + header section of a request with fewer body bytes than the + Content-Length read from it says, its version in upper or in lower case; none for a + body that is all there, for no Content-Length, no end of headers, a + response in either letter case, a status line whose phrase ends like a + version, a first line that ends in another version, in seven other + bytes or in more than the version, bytes that are no SIP, an ACK or a + CANCEL; for a MESSAGE, a header section exactly where + `DatagramMessage` calls the datagram truncated), 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 @@ -685,6 +697,18 @@ Rules: `checks.log`: a text sent to the own number over the bus, delivered back and listed); no capture holds a `Received` with them; the store's round trip with each is in `tests/Engine`. +- A request cut short of its Content-Length on the client flow ran on the + workstation's loopback (2026-11-22, the fp6 journal's + `2026-11-20-issues-2-5` capture, `cut-short`: `SipFlow` built around a + bench `main`, a peer on ::1 sending datagrams to the flow): a MESSAGE + with five body bytes of nine, its Content-Length on one line, drew a + 400 with its Via, From, Call-ID and CSeq echoed and its To tagged, and + the same 400 when it was sent again; a response, an ACK and a CANCEL + cut short the same way, and a request without an end of headers, were + ignored with their lines and drew nothing; a whole request sent after + them was returned by the flow; at the commit before, the cut-short + request was ignored as they were. Not in that bench: a 400 the flow + cannot send. - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, @@ -1594,7 +1618,18 @@ 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). +fold). A request that reaches the client flow in a datagram with fewer body +bytes than the Content-Length read from it says is answered 400 (RFC 3261 18.3: the element "SHOULD generate a 400 (Bad +Request) response"; the journal has `UDP: datagram truncated (…) — +answered 400`). Such a request is known by its first line, which ends with +the SIP version where a status line begins with it (7.1, 7.2), whatever +the version's letter case: a datagram cut short so that begins with a +status line, or with no line of SIP, is ignored, its line ending `— +ignored`. imsd keeps nothing of a request it answers so: a To tag +it adds is made from the request and a secret of the run, the same for the +same request (`BuildBadRequest`), and an ACK or a CANCEL cut short so draws +nothing — what RFC 3261 8.2.7 has an element do that answers without +state. - **A retransmitted MESSAGE** (the same Call-ID, CSeq and Via branch — the value of the first `branch=` of its first Via row; a MESSAGE with none diff --git a/implementations/main.cpp b/implementations/main.cpp index 2901c34..2c64d82 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -370,6 +370,14 @@ struct RefusedError : std::runtime_error { // 1280-byte MTU (40 IPv6 + 8 ESP + 16 IV + 8 UDP + padding + 12 ICV). constexpr std::size_t UdpSinglePacketBudget = 1190; +// The secret in the To tag of a 400 to a request cut short +// (imsd::msg::BuildBadRequest): drawn at the first such request, the same +// until imsd stops. +const std::string& BadRequestSecret() { + static const std::string secret = imsd::util::Rng().Token(16); + return secret; +} + class SipFlow { public: // TCP: connect up to `tries` times (12-s timeout each, 10 s apart). An @@ -527,9 +535,17 @@ public: alive_ = false; return std::nullopt; } if (n == 0) continue; + const std::string_view d(buf, static_cast(n)); std::string why; - if (auto m = imsd::sip::DatagramMessage(std::string_view(buf, static_cast(n)), &why)) return m; - if (!why.empty()) Log(std::format("UDP: {} — ignored", why)); + if (auto m = imsd::sip::DatagramMessage(d, &why)) return m; + if (!why.empty()) { + // A request cut short of its Content-Length is answered 400 + // (RFC 3261 18.3; CutShortRequest says which); whatever else + // DatagramMessage refuses is ignored. + const auto head = imsd::sip::CutShortRequest(d); + Log(std::format("UDP: {} — {}", why, head ? "answered 400" : "ignored")); + if (head && !Send(imsd::msg::BuildBadRequest(*head, BadRequestSecret()))) return std::nullopt; + } continue; } // EOF/RST is not a timeout: mark the flow dead so the engine's diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index b31c72e..5bf0c23 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -542,6 +542,19 @@ export namespace imsd::msg { 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 To tag 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. + 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...). diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index f0d97c6..0779cf8 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -490,4 +490,35 @@ export namespace imsd::sip { } return std::string(d); } + + // 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, 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 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; + const std::string_view head = 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 = 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; + return std::string(head) + "\r\n\r\n"; + } } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 974507b..e8f6c6f 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -502,6 +502,36 @@ 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"); + // 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: ;tag=N1\r\n" + "To: ;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"); + 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: ;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" diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 6c45f4f..2db5339 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -6,10 +6,11 @@ // 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 —, 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 +// with the Content-Length they read —, a request whose datagram ends before +// its body does (CutShortRequest), 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; @@ -326,6 +327,33 @@ int main() { 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)); + } + } + // ---- RetryAfter / RefusalSummary (what a refused final is logged as) { std::string r503 =