sip: a received message's header section is unfolded where it is framed

RFC 3261 7.3.1 lets a header value go on over further lines, each begun
with a space or a tab: "The line break and the whitespace at the
beginning of the next line are treated as a single SP character." The
text layer read a header from one line, so of a folded value it had the
first line only. Networks fold: KPN's 401 to the unprotected REGISTER
of 2026-07-18 and Odido's of 2026-07-13 had the WWW-Authenticate over
four lines (AGENTS.md §13; imsd finds a 401's nonce by a search of the
whole message, on a continuation line as on any other). A
Security-Server folded the same way would be read by its first line
alone, without the SPIs and ports on the further lines, and the
bring-up deferred; a short message whose Content-Type stands on a
continuation line would be taken for a page-mode text, answered 200
and never shown; a folded Content-Length on a connection would frame
no body, and the body's bytes begin the next message.

Unfolded takes the folds out of a header section, and the two framers
— FrameBuffer::TryExtract for a stream, DatagramMessage for a datagram
— hand a message on with its header section unfolded and its body as
it came; the Content-Length that frames the body is read from the
unfolded section. CutShortRequest reads its Content-Length so too, and
the header section it gives for the 400 is unfolded. Every socket imsd
reads SIP from goes through one of the two framers, so each reader of
a header still reads one line. A DUMP_SIP dump of a received message
holds it as framed.

Jorijn's decision of 2026-11-21 ("Unfold now").

Tested by tests/Sip — Unfolded on 7.3.1's own example, a tab, a bare LF,
a value begun on the next line and a line break that nothing follows;
both framers on a 401 whose WWW-Authenticate goes over four lines and
whose Content-Length is folded; CutShortRequest on a request cut short
of a folded Content-Length; ViaResponsePort on a Via list folded after
its comma, through the datagram framer — and by tests/Engine, a
delivered MESSAGE whose Content-Type came folded. On the workstation's
loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, init-port,
server-ports and cut-short, at this commit and at the one before): a
stand-in's 401 with its Security-Server over three lines gives the whole
value, where the commit before deferred the bring-up for want of SPIs; a
request with its Content-Type and Content-Length on continuation lines
comes out of the server ports unfolded and framed by that length, as a
datagram and over a connection; a request cut short of a folded
Content-Length, its Via on a continuation line, is answered 400 with its
Via whole, on a server port and on the client flow, where the commit
before did not read the folded length and handed the request on as it
came; a request on a server port whose Via row is a list folded after
its comma, `rport` on its lower value, is answered from the client-port
socket, the way to the port its top value names, as at the commit
before. On the dev phone the binary of this range's last commit
registered fresh on KPN after a reboot; the 401 was not dumped, so
whether it came folded that time is not on record. A MESSAGE the phone
sent to its own protected server port, its Via row a list folded after
its comma with `rport` on the lower value, was answered from the
client-port socket (the capture's phone-form6, fresh-check.log and
inject-bench.log).
This commit is contained in:
Jorijn van der Graaf 2026-11-22 17:35:12 +01:00
commit 9333621c66
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
6 changed files with 178 additions and 47 deletions

View file

@ -41,7 +41,7 @@ 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=`. | | `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.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-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), `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-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; `Unfolded`, by which the framers hand a message on with its folded header lines — 7.3.1 — joined; `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-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-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-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. |
@ -298,7 +298,7 @@ What the suites pin:
skipped), the Content-Length the two framers read (zeros before its 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 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), `CutShortRequest` (the value that begins with no digit read as none), `CutShortRequest` (the
header section of a request with fewer body bytes than the header section, unfolded, 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 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 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 response in either letter case, a status line whose phrase ends like a
@ -317,7 +317,12 @@ What the suites pin:
counted, its own `rport` counted, last before the comma too; a comma 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 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 its end) —, white space before the colon (RFC 3261 7.3.1's four
spellings), spellings), `Unfolded` (7.3.1's own example, a tab, a bare LF, a value
begun on the next line, a line break that nothing follows kept) and both
framers on a 401 whose WWW-Authenticate goes over four lines — the
header section unfolded, a folded Content-Length framing the body, the
body as it came —, and `ViaResponsePort` on a Via list folded after its
comma, as the datagram framer hands it on,
`ResponseOf` (the transaction's own 100 Trying; a final whose CSeq parts `ResponseOf` (the transaction's own 100 Trying; a final whose CSeq parts
its number and its method by two spaces, by a tab or by both, or has its number and its method by two spaces, by a tab or by both, or has
zeros before its number: the zeros before its number: the
@ -381,7 +386,8 @@ What the suites pin:
a delivered MESSAGE whose header names come in compact form — the 200 and 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 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 while SMS over IP is off — and a final in compact form taken by the
message in flight; message in flight; a delivered MESSAGE whose Content-Type came folded,
taken for a short message once the datagram framer has unfolded it;
a submit report before the MESSAGE's own final taken — the message sent 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 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, its own Call-ID — a text past 255 segments failed at once naming the fit,
@ -738,6 +744,24 @@ Rules:
text by a packet counter, none over TCP: `checks.log`); a MESSAGE the text by a packet counter, none over TCP: `checks.log`); a MESSAGE the
phone sent to its own server port with a Content-Length larger than phone sent to its own server port with a Content-Length larger than
its body was answered 400 (`inject-bench.log`). its body was answered 400 (`inject-bench.log`).
The unfolding ran in the same benches: the stand-in's 401 with its
WWW-Authenticate over four lines and its Security-Server over three
gave the Security-Server whole (at the commit before, its first line,
and the bring-up deferred: `Security-Server carries no
spi-c/spi-s/port-c/port-s`); a request whose Content-Type and
Content-Length stood on continuation lines came out of the server
ports unfolded and framed by that length, as a datagram and over a
connection (at the commit before, the datagram kept the bytes after
its body); a request cut short of a folded Content-Length, its Via on a continuation
line, was answered 400 with its Via whole, on a server port and, in
`cut-short`, on the client flow (at the commit before, its folded
length was not read and it was handed on as it came); a request on a
server port whose Via row held a list folded after its comma, `rport`
on its lower value, was answered by the way to the port its top value
names, as at the commit before. On the
phone the 401 of the fresh registration came from KPN, whose 401 of
2026-07-18 had its WWW-Authenticate over four lines (§13; the fresh one was not
dumped).
- `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims - `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` 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, on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture,
@ -1645,9 +1669,10 @@ still answered 200 and logged with its body: the 200 is `BuildResponse`'s
now and the line names the content type (§7.8). A header imsd reads is 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 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 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 `v:` line a Via), with or without white space before the colon, and a
value folded onto further lines the first line is read (7.3.1 allows the value folded onto further lines (7.3.1) whole: a received message's
fold). A datagram on a server port or on the init port is header section is unfolded where it is framed (`Unfolded`), each line
break in it that a space or a tab follows becoming, with the white space after it, one space. A datagram on a server port or on the init port is
framed as one on the client flow is (RFC 3261 18.3): bytes past the framed as one on the client flow is (RFC 3261 18.3): bytes past the
Content-Length read from it are discarded, and one that has no end of headers is Content-Length read from it are discarded, and one that has no end of headers is
ignored with a line (`UDP: … on server socket <port> — ignored`, `UDP: … ignored with a line (`UDP: … on server socket <port> — ignored`, `UDP: …
@ -2383,3 +2408,10 @@ the related code.
01:17:41–45, 28–36 min after their SC time stamps; what held them is 01:17:41–45, 28–36 min after their SC time stamps; what held them is
unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo
(`<unknown-param name="+g.3gpp.smsip"/>`) on both AORs. (`<unknown-param name="+g.3gpp.smsip"/>`) on both AORs.
- **A folded `WWW-Authenticate`** — the 401 to the unprotected REGISTER
came with its `WWW-Authenticate` over four lines on KPN (2026-07-18)
and on Odido (2026-07-13), the nonce on the second (RFC 3261 7.3.1; one
401 of each: the fp6 journal's `2026-11-20-issues-2-5` capture,
`folded-401`); the `Security-Server` of both was one line. imsd finds the nonce by a search
of the whole message, and unfolds every received message where it is
framed (§7.9).

View file

@ -102,7 +102,7 @@ Configuration is environment variables in `/etc/imsd.env`, none are required.
| `RTP_PORT` | `50004` | local RTP port advertised in SDP | | `RTP_PORT` | `50004` | local RTP port advertised in SDP |
| `PRECOND` | `0` | `1` offers SDP QoS preconditions | | `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 | | `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 | | `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_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 | | `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 |

View file

@ -810,10 +810,12 @@ void PersistState(const RegState& r, const std::string& route, const std::string
} }
} }
// Raw dump of a received message for offline diffing against the stock-modem // A dump of a SIP message for offline reading (the README's DUMP_SIP row
// oracle (rung-5b registration-parity work). One file per message kind, // lists the dumps): one imsd received, as its framer hands it on — bytes
// overwritten on every registration cycle. The dumps carry the subscriber's // past its body gone, its folded header lines joined — or one of its own,
// IMSI/MSISDN and addresses, so they are opt-in (DUMP_SIP=1) and mode 0600. // dumped before the send is tried. One file per kind, overwritten by the
// next dump of its kind. The dumps carry the subscriber's IMSI/MSISDN and
// addresses, so they are opt-in (DUMP_SIP=1) and mode 0600.
void DumpRaw(std::string_view name, std::string_view msg) { void DumpRaw(std::string_view name, std::string_view msg) {
if (EnvOr("DUMP_SIP", "0") != "1") return; if (EnvOr("DUMP_SIP", "0") != "1") return;
std::string path = std::format("{}/{}", EnvOr("DUMP_DIR", StateDir()), name); std::string path = std::format("{}/{}", EnvOr("DUMP_DIR", StateDir()), name);

View file

@ -7,7 +7,7 @@ Imsd:Sip — SIP message text layer + TCP framing.
Deliberately a text layer, not a full RFC 3261 parser: the engine works on 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, whole messages as strings and pulls out exactly what it needs (headers,
status codes, the granted registration lifetime), which keeps every message status codes, the granted registration lifetime), which keeps every message
loggable and testable verbatim. A header is asked for by its long name and 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 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, (empty header values, line anchoring, white space before the colon,
keepalive discards) is pinned by tests/Sip — a change that flips one of keepalive discards) is pinned by tests/Sip — a change that flips one of
@ -105,8 +105,9 @@ namespace imsd::sip {
// Matching never crosses the line boundary: an empty-valued header // Matching never crosses the line boundary: an empty-valued header
// yields "", NOT the next line's content (a regex-based implementation // yields "", NOT the next line's content (a regex-based implementation
// whose whitespace class eats the CRLF gets that wrong — pinned by the // 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) // "bare header" test). A value folded onto further lines (7.3.1) is
// the first line is read. // 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) { std::optional<std::string_view> ValueOfField(std::string_view line, std::string_view name) {
if (!IEqualsPrefix(line, name)) return std::nullopt; if (!IEqualsPrefix(line, name)) return std::nullopt;
std::size_t colon = name.size(); std::size_t colon = name.size();
@ -421,6 +422,29 @@ export namespace imsd::sip {
return std::string(uri); 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 // The body of a message: what follows the header terminator, empty
// without one. // without one.
std::string_view Body(std::string_view msg) { std::string_view Body(std::string_view msg) {
@ -431,25 +455,27 @@ export namespace imsd::sip {
// SIP-over-TCP stream framing, transport-free: feed received bytes into // SIP-over-TCP stream framing, transport-free: feed received bytes into
// Append(), pull complete messages (headers + Content-Length body) out // Append(), pull complete messages (headers + Content-Length body) out
// of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are // 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 { class FrameBuffer {
public: public:
void Append(std::string_view data) { buf_.append(data); } void Append(std::string_view data) { buf_.append(data); }
// One complete SIP message off the front of the buffer, or nullopt // One complete SIP message off the front of the buffer, or nullopt
// if more bytes are needed. Content-Length is located with the same // 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::optional<std::string> TryExtract() {
std::size_t keep = buf_.find_first_not_of("\r\n"); std::size_t keep = buf_.find_first_not_of("\r\n");
buf_.erase(0, keep == std::string::npos ? buf_.size() : keep); buf_.erase(0, keep == std::string::npos ? buf_.size() : keep);
std::size_t idx = buf_.find("\r\n\r\n"); std::size_t idx = buf_.find("\r\n\r\n");
if (idx == std::string::npos) return std::nullopt; 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; long clen = 0;
if (auto v = Header(head, "Content-Length")) clen = static_cast<long>(LengthOf(*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); std::size_t total = idx + 4 + static_cast<std::size_t>(clen);
if (buf_.size() < total) return std::nullopt; if (buf_.size() < total) return std::nullopt;
std::string msg = buf_.substr(0, total); msg.append(buf_, idx, total - idx);
buf_.erase(0, total); buf_.erase(0, total);
return msg; return msg;
} }
@ -467,6 +493,8 @@ export namespace imsd::sip {
// fit is a truncated datagram → nullopt with `problem` set; no // fit is a truncated datagram → nullopt with `problem` set; no
// Content-Length means the body is the rest of the datagram. A datagram // Content-Length means the body is the rest of the datagram. A datagram
// without a header terminator is malformed → nullopt with `problem`. // 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::optional<std::string> DatagramMessage(std::string_view d, std::string* problem = nullptr) {
std::size_t start = d.find_first_not_of("\r\n"); std::size_t start = d.find_first_not_of("\r\n");
if (start == std::string_view::npos) return std::nullopt; if (start == std::string_view::npos) return std::nullopt;
@ -476,49 +504,52 @@ export namespace imsd::sip {
if (problem) *problem = std::format("datagram without a header terminator ({} bytes)", d.size()); if (problem) *problem = std::format("datagram without a header terminator ({} bytes)", d.size());
return std::nullopt; return std::nullopt;
} }
std::size_t bodyStart = idx + 4; std::size_t body = d.size() - (idx + 4);
std::size_t body = d.size() - bodyStart; std::string msg = Unfolded(d.substr(0, idx));
if (auto v = Header(d.substr(0, idx), "Content-Length")) { if (auto v = Header(msg, "Content-Length")) {
if (const auto length = LengthOf(*v)) { if (const auto length = LengthOf(*v)) {
const std::size_t clen = *length; const std::size_t clen = *length;
if (clen > body) { if (clen > body) {
if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body); if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body);
return std::nullopt; 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: // 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 // "If the message is a response, it MUST be discarded. If the message
// is a request, the element SHOULD generate a 400 (Bad Request) // is a request, the element SHOULD generate a 400 (Bad Request)
// response." The header section of such a request, with the empty line // response." The header section of such a request, unfolded (Unfolded),
// that ends it and no body — what the 400 is built from — or nullopt // with the empty line that ends it and no body — what the 400 is built
// for every other datagram: one whose body is all there, by its // from — or nullopt for every other datagram: one whose body is all
// Content-Length or for want of one; one without an end of headers; // there, by its Content-Length or for want of one; one without an end
// one whose first line is no request's; an ACK or a CANCEL. A request's // of headers; one whose first line is no request's; an ACK or a CANCEL.
// first line ends with the SIP version (7.1: "Request-Line = Method SP // A request's first line ends with the SIP version (7.1: "Request-Line
// Request-URI SP SIP-Version CRLF") and a status line begins with it // = Method SP Request-URI SP SIP-Version CRLF") and a status line
// (7.2), in whatever letter case ("The SIP-Version string is // begins with it (7.2), in whatever letter case ("The SIP-Version
// case-insensitive"): a response is none, and neither are bytes that // string is case-insensitive"): a response is none, and neither are
// are no SIP. imsd keeps nothing of a request it answers so, and of an // bytes that are no SIP. imsd keeps nothing of a request it answers so,
// element that keeps nothing 8.2.7 says: "A stateless UAS MUST ignore // and of an element that keeps nothing 8.2.7 says: "A stateless UAS
// ACK requests." "A stateless UAS MUST ignore CANCEL requests." // MUST ignore ACK requests." "A stateless UAS MUST ignore CANCEL
// requests."
std::optional<std::string> CutShortRequest(std::string_view d) { std::optional<std::string> CutShortRequest(std::string_view d) {
const std::size_t start = d.find_first_not_of("\r\n"); const std::size_t start = d.find_first_not_of("\r\n");
if (start == std::string_view::npos) return std::nullopt; if (start == std::string_view::npos) return std::nullopt;
d.remove_prefix(start); d.remove_prefix(start);
const std::size_t idx = d.find("\r\n\r\n"); const std::size_t idx = d.find("\r\n\r\n");
if (idx == std::string_view::npos) return std::nullopt; if (idx == std::string_view::npos) return std::nullopt;
const std::string_view head = d.substr(0, idx); std::string head = Unfolded(d.substr(0, idx));
const auto length = Header(head, "Content-Length").and_then(LengthOf); const auto length = Header(head, "Content-Length").and_then(LengthOf);
if (!length || *length <= d.size() - (idx + 4)) return std::nullopt; 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 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 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 (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; if (line.starts_with("ACK ") || line.starts_with("CANCEL ")) return std::nullopt;
return std::string(head) + "\r\n\r\n"; head.append("\r\n\r\n");
return head;
} }
} }

View file

@ -41,7 +41,8 @@
// unusable TPDU acknowledged with an RP-ERROR, a body that is no RP // 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 // message, a page-mode text 200'd and logged, a short message while SMS
// over IP is off refused with 480, a delivered MESSAGE and a final whose // 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 // header names come in compact form, a delivered MESSAGE whose
// Content-Type came folded), and the store's record codec
// (FormatStoredSms/ParseStoredSms: a full record round trip, defaults // (FormatStoredSms/ParseStoredSms: a full record round trip, defaults
// for absent keys, a value that does not parse or a missing id refused) and order // 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 // (StoredSmsBefore: the arrival second, then within a run the sequence
@ -1557,6 +1558,20 @@ int main() {
const auto* repo = findSms(ro.actions, SmsAction::Type::SendClient); 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"); 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 Content-Type folded onto a second line (RFC 3261 7.3.1), as a framer hands it on
{
const std::string longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");
std::string folded = longForm;
folded.replace(folded.find("Content-Type: "), 14, "Content-Type:\r\n\t");
const auto framed = imsd::sip::DatagramMessage(folded);
Check(folded.contains("\r\nContent-Type:\r\n\tapplication/vnd.3gpp.sms\r\n") && framed == longForm, "folded MESSAGE: the datagram framer hands the long form's message on");
imsd::util::Rng rng(80), rngLong(80);
Reassembler re, reLong;
auto r = OnSmsMessage(c, rng, framed.value_or(""), re, nullptr, 50.0);
auto want = OnSmsMessage(c, rngLong, longForm, reLong, nullptr, 50.0);
const auto* rec = findSms(r.actions, SmsAction::Type::Received);
Check(rec && rec->received.text == "How are you?" && r.response == want.response && hasSms(r.actions, SmsAction::Type::SendClient), "folded MESSAGE: taken for a short message, answered and reported on as its long form");
}
// 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 // 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 longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");

View file

@ -6,12 +6,12 @@
// caller-identity extraction, the port a Via names for the response // caller-identity extraction, the port a Via names for the response
// (ViaResponsePort), the two framers — the TCP frame buffer (split delivery, // (ViaResponsePort), the two framers — the TCP frame buffer (split delivery,
// keepalive pongs, pipelined messages) and a datagram's (DatagramMessage), // keepalive pongs, pipelined messages) and a datagram's (DatagramMessage),
// with the Content-Length they read —, a request whose datagram ends before // with the Content-Length they read and the unfolding of a folded header
// its body does (CutShortRequest), a refused final's Retry-After and summary // section (Unfolded) —, a request whose datagram ends before its body does
// (RetryAfter, RefusalSummary), transaction matching (ResponseOf), our // (CutShortRequest), a refused final's Retry-After and summary (RetryAfter,
// binding in a reg-event document (RegInfoContactState), and HeaderUri and // RefusalSummary), transaction matching (ResponseOf), our binding in a
// Body. These pin the module's edge-case behavior; see the module header // reg-event document (RegInfoContactState), and HeaderUri and Body. These pin
// before "fixing" one. // the module's edge-case behavior; see the module header before "fixing" one.
import std; import std;
import Imsd; import Imsd;
@ -290,6 +290,8 @@ int main() {
// a row that holds a list (RFC 3261 7.3.1): the top value alone speaks // 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"; 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 + ";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 + ";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 + ";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 + ", " + next + ";branch=z9hG4bKs")) == 6000, "a top value without parameters: its own port, not the next value's");
@ -354,6 +356,55 @@ int main() {
} }
} }
// ---- 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");
}
// ---- RetryAfter / RefusalSummary (what a refused final is logged as) // ---- RetryAfter / RefusalSummary (what a refused final is logged as)
{ {
std::string r503 = std::string r503 =