imsd/interfaces/Imsd-Sip.cppm

524 lines
26 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
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
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
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).
*/
export module Imsd:Sip;
import std;
namespace imsd::sip {
constexpr char AsciiLower(char c) {
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c - 'A' + 'a') : c;
}
constexpr bool IEqualsPrefix(std::string_view text, std::string_view prefix) {
if (text.size() < prefix.size()) return false;
for (std::size_t i = 0; i < prefix.size(); i++)
if (AsciiLower(text[i]) != AsciiLower(prefix[i])) return false;
return true;
}
// spaces, tabs, CR, LF off both ends
constexpr std::string_view Trim(std::string_view s) {
while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\r' || s.front() == '\n'))
s.remove_prefix(1);
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n'))
s.remove_suffix(1);
return s;
}
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
// 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
// 7): a body line that spells a header name — a text someone typed, or
// UCS-2 bytes that happen to — is never read as one. Empty lines before
// the first line of text (a keepalive's CRLFs ahead of a message) are
// skipped.
template <typename F>
void ForEachLine(std::string_view msg, F&& f) {
std::size_t pos = 0;
bool started = false;
while (pos <= msg.size()) {
std::size_t nl = msg.find('\n', pos);
std::string_view line = msg.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
const bool blank = line.empty() || line == "\r";
if (blank && started) return;
if (!blank) {
started = true;
if (!f(line)) return;
}
if (nl == std::string_view::npos) return;
pos = nl + 1;
}
}
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
// The one-letter form a header name may be written in (RFC 3261 7.3.3:
// "Implementations MUST accept both the long and short forms of each
// header name"): the ten RFC 3261 defines (its section 20), and those
// of the two extension headers imsd reads that have one — Event (RFC
// 6665 7.3) and Session-Expires (RFC 4028 4). 0 for any other name:
// whoever starts reading another extension header adds its form here.
constexpr char CompactForm(std::string_view name) {
constexpr std::pair<std::string_view, char> Forms[] = {
{"Call-ID", 'i'}, {"Contact", 'm'}, {"Content-Encoding", 'e'}, {"Content-Length", 'l'},
{"Content-Type", 'c'}, {"From", 'f'}, {"Subject", 's'}, {"Supported", 'k'}, {"To", 't'},
{"Via", 'v'}, {"Event", 'o'}, {"Session-Expires", 'x'},
};
for (const auto& [longForm, letter] : Forms)
if (name.size() == longForm.size() && IEqualsPrefix(name, longForm)) return letter;
return 0;
}
// The value of a line that begins with the field name `name`: the name
// anchored at line start (case-insensitive, per RFC 3261 header names),
// then spaces or tabs, or none, then the colon (RFC 3261 25.1's HCOLON:
// "Subject : lunch" is 7.3.1's example) and at least one
// character (even just the CR) after it. A bare "Name:\r" line matches
// with value ""; a "Name:" that ends the buffer does not match.
// Matching never crosses the line boundary: an empty-valued header
// yields "", NOT the next line's content (a regex-based implementation
// whose whitespace class eats the CRLF gets that wrong — pinned by the
// "bare header" test), so of a value folded onto further lines (7.3.1)
// the first line is read.
std::optional<std::string_view> ValueOfField(std::string_view line, std::string_view name) {
if (!IEqualsPrefix(line, name)) return std::nullopt;
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
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);
}
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
// One header line's match to `name`, the long form a reader asks by:
// the line carries that name, or its compact form.
std::optional<std::string_view> MatchHeaderLine(std::string_view line, std::string_view name) {
if (auto v = ValueOfField(line, name)) return v;
if (const char letter = CompactForm(name)) return ValueOfField(line, std::string_view(&letter, 1));
return std::nullopt;
}
// First run of ASCII digits starting at `s`; nullopt if none.
std::optional<long> LeadingDigits(std::string_view s) {
std::size_t n = 0;
while (n < s.size() && s[n] >= '0' && s[n] <= '9')
n++;
if (n == 0) return std::nullopt;
long v = 0;
auto [_, ec] = std::from_chars(s.data(), s.data() + n, v);
if (ec != std::errc{}) return std::nullopt;
return v;
}
// The length a Content-Length value names: the number its leading
// digits spell (RFC 3261 25.1: 1*DIGIT), zeros before it aside; nullopt
// where the value begins with no digit. Of a number of more than nine
// digits the first nine are read — more than a datagram holds, and
// enough that a stream waits for a body that does not come.
std::optional<std::size_t> LengthOf(std::string_view v) {
std::string_view digits = v.substr(0, v.find_first_not_of("0123456789"));
if (digits.empty()) return std::nullopt;
while (digits.starts_with('0')) digits.remove_prefix(1);
std::size_t n = 0;
for (char c : digits.substr(0, 9)) n = n * 10 + static_cast<std::size_t>(c - '0');
return n;
}
// A CSeq value as its sequence number and its method (RFC 3261 25.1:
// 1*DIGIT LWS Method): the digits the trimmed value begins with, less
// the zeros before the number, the spaces or tabs after them, then the
// method to the value's end. nullopt where no space or tab follows the
// digits.
std::optional<std::pair<std::string_view, std::string_view>> CSeqParts(std::string_view v) {
v = Trim(v);
const std::size_t digits = v.find_first_not_of("0123456789");
const std::size_t method = v.find_first_not_of(" \t", digits);
if (method == digits) return std::nullopt;
std::string_view number = v.substr(0, digits);
while (number.starts_with('0')) number.remove_prefix(1);
return std::pair{number, v.substr(method)};
}
}
export namespace imsd::sip {
// Value of the first `name:` header, trimmed; nullopt if absent.
std::optional<std::string_view> Header(std::string_view msg, std::string_view name) {
std::optional<std::string_view> out;
ForEachLine(msg, [&](std::string_view line) {
if (auto v = MatchHeaderLine(line, name)) {
out = *v;
return false;
}
return true;
});
return out;
}
// Every `name:` header value, in order.
std::vector<std::string_view> Headers(std::string_view msg, std::string_view name) {
std::vector<std::string_view> out;
ForEachLine(msg, [&](std::string_view line) {
if (auto v = MatchHeaderLine(line, name)) out.push_back(*v);
return true;
});
return out;
}
// The 3-digit code of a "SIP/2.0 NNN ..." response start-line; nullopt
// for requests / anything else. Only matches at the start of the message.
std::optional<int> Status(std::string_view msg) {
constexpr std::string_view Prefix = "SIP/2.0 ";
if (!msg.starts_with(Prefix) || msg.size() < Prefix.size() + 3) return std::nullopt;
std::string_view d = msg.substr(Prefix.size(), 3);
for (char c : d)
if (c < '0' || c > '9') return std::nullopt;
int v = 0;
std::from_chars(d.data(), d.data() + 3, v);
return v;
}
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers A refused final was logged as its bare status code ("re-REGISTER failed 503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as "expected 401", without even the code — so a field journal could not say which node refused or what it said. O2 UK answered a phone's 30-minute refresh with 503 twenty-one times over seventy minutes and then refused a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24); the journal holds nothing but the numbers. Log the status line with the headers that carry the reason — Retry-After, Warning, Reason, Server — for a REGISTER's refused final (initial, protected, refresh) and for a refused SUBSCRIBE the run loop reads, and dump the refused message under DUMP_SIP as its own fail dump next to the 200s. To tell a REGISTER's final from what else arrives, the final is now matched by Call-ID and CSeq, and a request that arrives on the client flow while one is awaited is dispatched: a refresh no longer reads such a request as a failed REGISTER. An INVITE among those requests is a call like any other, announced on the bus: a Dial whose reconnect it arrived under meets the call-in-progress rule again before it places its own, and when a resume, a refresh or a reconnect fails the call that arrived under it ends with the flow it came in on (486 while the flow still carries one, and the bus told). The unprotected REGISTER's reply is matched the same way on the init port. Tested on the dev phone (KPN) in builds of this series; not every path has run there.
2026-09-24 18:51:03 +02:00
// True for a response of the transaction (callid, cseq) — the reply a
// wait for that request may judge. A request, another transaction's
// response or anything else a socket delivers is not. Two CSeqs are
// equal "if the sequence number and the request method are identical"
// (RFC 3261 20.16): they are compared so, whatever spaces or tabs part
// the two and whatever zeros stand before the number.
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers A refused final was logged as its bare status code ("re-REGISTER failed 503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as "expected 401", without even the code — so a field journal could not say which node refused or what it said. O2 UK answered a phone's 30-minute refresh with 503 twenty-one times over seventy minutes and then refused a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24); the journal holds nothing but the numbers. Log the status line with the headers that carry the reason — Retry-After, Warning, Reason, Server — for a REGISTER's refused final (initial, protected, refresh) and for a refused SUBSCRIBE the run loop reads, and dump the refused message under DUMP_SIP as its own fail dump next to the 200s. To tell a REGISTER's final from what else arrives, the final is now matched by Call-ID and CSeq, and a request that arrives on the client flow while one is awaited is dispatched: a refresh no longer reads such a request as a failed REGISTER. An INVITE among those requests is a call like any other, announced on the bus: a Dial whose reconnect it arrived under meets the call-in-progress rule again before it places its own, and when a resume, a refresh or a reconnect fails the call that arrived under it ends with the flow it came in on (486 while the flow still carries one, and the bus told). The unprotected REGISTER's reply is matched the same way on the init port. Tested on the dev phone (KPN) in builds of this series; not every path has run there.
2026-09-24 18:51:03 +02:00
bool ResponseOf(std::string_view msg, std::string_view callid, std::string_view cseq) {
if (!Status(msg).has_value() || Header(msg, "Call-ID") != callid) return false;
const auto theirs = Header(msg, "CSeq");
if (!theirs) return false;
const auto a = CSeqParts(*theirs), b = CSeqParts(cseq);
return a && b && *a == *b;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers A refused final was logged as its bare status code ("re-REGISTER failed 503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as "expected 401", without even the code — so a field journal could not say which node refused or what it said. O2 UK answered a phone's 30-minute refresh with 503 twenty-one times over seventy minutes and then refused a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24); the journal holds nothing but the numbers. Log the status line with the headers that carry the reason — Retry-After, Warning, Reason, Server — for a REGISTER's refused final (initial, protected, refresh) and for a refused SUBSCRIBE the run loop reads, and dump the refused message under DUMP_SIP as its own fail dump next to the 200s. To tell a REGISTER's final from what else arrives, the final is now matched by Call-ID and CSeq, and a request that arrives on the client flow while one is awaited is dispatched: a refresh no longer reads such a request as a failed REGISTER. An INVITE among those requests is a call like any other, announced on the bus: a Dial whose reconnect it arrived under meets the call-in-progress rule again before it places its own, and when a resume, a refresh or a reconnect fails the call that arrived under it ends with the flow it came in on (486 while the flow still carries one, and the bus told). The unprotected REGISTER's reply is matched the same way on the init port. Tested on the dev phone (KPN) in builds of this series; not every path has run there.
2026-09-24 18:51:03 +02:00
}
// Retry-After of a response (RFC 3261 20.33), in seconds; nullopt when
// absent or not a number.
std::optional<long> RetryAfter(std::string_view msg) {
auto v = Header(msg, "Retry-After");
if (!v) return std::nullopt;
return LeadingDigits(*v);
}
// A refused final for the journal: its status line, then the headers
// that say who refused and for how long — Retry-After (RFC 3261 20.33),
// Warning (20.43: the node's own words), Reason (RFC 3326), Server
// (20.35). "503 Service Unavailable; Retry-After: 60; Warning: 399
// pcscf1.example \"...\"". A bare status code says neither which node
// nor why: O2 UK answered a refresh 503 twenty-one times and a
// subscription 500 (alyx, 2026-09-24) and the journal could not tell
// the P-CSCF from the S-CSCF (ims ledger F17).
std::string RefusalSummary(std::string_view msg) {
std::string_view line = msg.substr(0, msg.find_first_of("\r\n"));
if (line.starts_with("SIP/2.0 ")) line.remove_prefix(8);
std::string s(Trim(line));
for (std::string_view name : {"Retry-After", "Warning", "Reason", "Server"})
for (std::string_view v : Headers(msg, name))
s += std::format("; {}: {}", name, v);
return s;
}
engine: keep the reg-event subscription alive and act on a terminated binding The reg-event subscription is the network's own account of our binding (TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every refresh and reconnect and otherwise never looked back: a refused SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended subscription got nothing until the next refresh's new dialog, and a NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and showed our contact active, the flow died eight seconds after the 200 and no connect over the SA succeeded after that; the 500 was logged and nothing was done about it. Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup or probation (RFC 6665 4.1.3; after any other reason, or none, the next refresh subscribes anew), and subscribe anew ahead of the lifetime the S-CSCF granted. A refresh or a reconnect opens no dialog while imsd holds one for the registration or has a retry scheduled. Read the reginfo for our own contact and act on its state: a NOTIFY that terminates our binding schedules a fresh registration — at once for deactivated or expired, after the network's retry-after (up to an hour) for probation, on imsd's own refusal schedule (21 min, growing to 60) for rejected or unregistered (RFC 3680). A hold already running stands, and a REGISTER wait a call kept open that still gets its 200 after such a NOTIFY leaves that registration standing. The parser is in Imsd:Sip and pinned by tests/Sip with the O2 document shapes; the policy is RegRecovery's (OnBindingTerminated, added here with its tests in tests/Engine). Tested on the dev phone (KPN) in builds of this series; not every path has run there.
2026-10-03 19:36:23 +02:00
// Our binding in a reg-event NOTIFY body (RFC 3680 reginfo): the
// <contact> whose <uri> carries `user` as its SIP user part, across every
// <registration> of the implicit set (the sip: and the tel: identity
// list the same contact). Active anywhere = Active; otherwise the first
// terminated occurrence's event and retry-after attribute; NotListed
// when no contact of ours is in the document — a partial update about
// other bindings, or a previous registration's binding (the contact our
// own fresh registration deactivated, O2 UK 2026-09-24).
struct RegInfoContact {
enum class State { NotListed, Active, Terminated };
State state = State::NotListed;
std::string event; // terminated: deactivated | probation | rejected | unregistered | expired | …
long retryAfter = 0; // terminated: the retry-after attribute (probation), seconds
};
RegInfoContact RegInfoContactState(std::string_view reginfo, std::string_view user) {
constexpr std::size_t npos = std::string_view::npos;
RegInfoContact out;
std::string needle = std::format(":{}@", user); // sip:<user>@… / sips:<user>@…
std::size_t pos = 0;
while ((pos = reginfo.find("<contact", pos)) != npos) {
std::size_t tagEnd = reginfo.find('>', pos);
if (tagEnd == npos) break;
std::string_view tag = reginfo.substr(pos, tagEnd - pos);
std::size_t end = reginfo.find("</contact>", tagEnd);
std::string_view body = reginfo.substr(tagEnd + 1, end == npos ? npos : end - tagEnd - 1);
pos = end == npos ? reginfo.size() : end + 10;
std::size_t u = body.find("<uri>");
if (u == npos) continue;
std::size_t ue = body.find("</uri>", u);
std::string_view uri = Trim(body.substr(u + 5, ue == npos ? npos : ue - u - 5));
if (!uri.contains(needle)) continue;
auto attr = [&](std::string_view name) -> std::string_view {
std::string key = std::format(" {}=\"", name);
std::size_t a = tag.find(key);
if (a == npos) return {};
std::size_t b = tag.find('"', a + key.size());
return tag.substr(a + key.size(), b == npos ? npos : b - a - key.size());
};
std::string_view state = attr("state");
if (state == "active") {
out.state = RegInfoContact::State::Active;
out.event.clear();
out.retryAfter = 0;
return out;
}
if (state == "terminated" && out.state == RegInfoContact::State::NotListed) {
out.state = RegInfoContact::State::Terminated;
out.event = std::string(attr("event"));
out.retryAfter = LeadingDigits(attr("retry-after")).value_or(0);
}
}
return out;
}
// Where a UDP response to this request must go (RFC 3261 18.2.2): the
// top Via's sent-by port — unless the Via carries rport, in which case
// 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
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
// "[v6]:port" and "host:port" sent-by forms. rport (RFC 3581) is a
// parameter by its name, in any case (7.3.1): not those letters in a
// value or in a longer name. The top Via is the first value of the
// first Via row: a row may hold a list (7.3.1), and what follows its
// first comma outside a quoted string is another hop's.
std::optional<int> ViaResponsePort(std::string_view msg) {
auto via = Header(msg, "Via");
if (!via) return std::nullopt;
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
std::string_view v = via->substr(0, PieceEnd(*via, 0, ','));
if (std::size_t sc = v.find(';'); sc != std::string_view::npos) {
sip: a header is found under its compact form, and with white space before the colon RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
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;
if (std::size_t br = v.rfind(']'); br != std::string_view::npos)
colon = v.find(':', br); // v6: port only after the ]
else
colon = v.rfind(':'); // v4/hostname (transport token
// has no colon of its own)
if (colon == std::string_view::npos) return std::nullopt;
if (auto p = LeadingDigits(Trim(v.substr(colon + 1))))
if (*p > 0 && *p < 65536) return static_cast<int>(*p);
return std::nullopt;
}
// Registration lifetime granted by a REGISTER 200 OK: the Contact
// header's expires= parameter (the registrar's answer for our binding),
// else the Expires header; nullopt if absent. "expires=" is searched
// anywhere in each Contact value, not parameter-parsed.
std::optional<long> GrantedExpires(std::string_view msg) {
for (std::string_view contact : Headers(msg, "Contact")) {
std::size_t at = contact.find("expires=");
if (at != std::string_view::npos)
if (auto v = LeadingDigits(contact.substr(at + 8))) return v;
}
if (auto e = Header(msg, "Expires")) {
std::string_view v = *e;
if (!v.empty() && v.find_first_not_of("0123456789") == std::string_view::npos) return LeadingDigits(v);
}
return std::nullopt;
}
// Caller identity of an inbound request: the number/user of the first
// P-Asserted-Identity (the network-asserted identity, RFC 3325), falling
// back to From. Understands "<tel:+31612345678>", "<sip:+31612345678@
// host;user=phone>" (user part) and bare values; returns "" if neither
// header yields one. Anonymous callers come out as "anonymous".
std::string CallerId(std::string_view msg) {
auto extract = [](std::string_view v) -> std::optional<std::string> {
std::string_view uri = v;
std::size_t lt = v.find('<');
if (lt != std::string_view::npos) {
std::size_t gt = v.find('>', lt);
if (gt != std::string_view::npos) uri = v.substr(lt + 1, gt - lt - 1);
} else {
std::size_t semi = v.find(';');
if (semi != std::string_view::npos) uri = v.substr(0, semi);
uri = Trim(uri);
}
if (uri.starts_with("tel:")) {
std::string_view n = uri.substr(4);
std::size_t semi = n.find(';');
if (semi != std::string_view::npos) n = n.substr(0, semi);
return std::string(n);
}
if (uri.starts_with("sip:") || uri.starts_with("sips:")) {
std::string_view n = uri.substr(uri.find(':') + 1);
std::size_t end = n.find_first_of("@;");
if (end == std::string_view::npos) return std::nullopt;
return std::string(n.substr(0, end));
}
return std::nullopt;
};
for (std::string_view h : Headers(msg, "P-Asserted-Identity"))
if (auto n = extract(h)) return *n;
if (auto f = Header(msg, "From"))
if (auto n = extract(*f)) return *n;
return "";
}
sip, engine: the SMS over IP transactions as reducers TS 24.341 has a submission travel as a MESSAGE with the RP-DATA, answered with a final and then with the submit report in a MESSAGE of the IP-SM-GW's own, and a delivery arrive as a MESSAGE with the RP-DATA to be answered and acknowledged with an RP-ACK in a MESSAGE of ours. Two pure reducers carry that, in the shape CallMachine has: SmsOutbound takes one message of ours segment by segment — the MESSAGE, its final (a 32 s wait, which a provisional starts over), the RP-ACK or RP-ERROR matched by In-Reply-To, else by RP-MR (within 40 s of the final, a length TR1M may have), then the next segment with the next RP-MR and TP-MR — and ends it as sent or failed, its State action carrying the reason; OnSmsMessage turns an inbound MESSAGE into its final, the message or status report it carried and the delivery report to send, 488 for a submit report In-Reply-To no MESSAGE of ours in flight — one that is not ours (5.3.1.2), or ours once the message has ended (its report's wait run out, judged by the reducer's caller; a failure; sent) or its segment was superseded by the next, which gets the same answer — an RP-ERROR for a TPDU that is unusable (a delivery or a status report that does not parse, or one of the submit-report type), and a 200 with a log line for what it makes nothing of: a MESSAGE whose Content-Type does not contain the SMS one, a body that is no RP message, a submit report without In-Reply-To for no message in flight. Imsd:Sip gains HeaderUri, the URI of a header's first element, a quoted display name before it passed over (none when that URI holds an ASCII control character, a space, `<`, `>` or `"`: it goes into a request line), and Body, moved out of CallMachine (its four call sites and the shell's NOTIFY/MESSAGE branch follow). No retransmission (TS 23.040 9.2.3.6's repeat with TP-RD is not done): an unanswered MESSAGE or a report that never comes fails the message. RecentTransactions, the reducer, keys a request by Call-ID, CSeq and Via branch — the value of the first `branch=` of its first Via line; a request with none or an empty one is not remembered — and gives back the final remembered for it within 32 s (TimerJ, on every transport) — what a caller needs to answer a retransmitted request again and not handle it again (RFC 3261 17.2.2); without it a repeated RP-DATA would be handled again: a second delivery report where the first got one and, of a text in one segment, a second Received. Every final OnSmsMessage gives an inbound MESSAGE — the 200, the 488 — goes through BuildResponse: each Via: line echoed, the To echoed with a tag minted for the request unless it holds `tag=` (RFC 3261 8.2.6.2). tests/Engine drives both reducers through the dialogs above and the retransmission table; tests/Sip pins the two helpers. OnSmsMessage's header reads — the delivery report's target (P-Asserted-Identity, else From) among them — go through the text layer, which ends at the header section: a body line may spell a header name (a text, or UCS-2 bytes that do) and must pick nothing. Pinned with an 8-bit SMS-DELIVER whose data spells a P-Asserted-Identity line. A UCS-2 surrogate pair a sender split across two segments comes out whole in the Received action OnSmsMessage returns (the codec decodes a set from its joined units); pinned. Pinned as well: a submit report that arrives before the MESSAGE's own final is taken (the message sent, or the next segment out under its own Call-ID, and the late final nobody's), a text past 255 segments fails at once naming the fit, and a delivery with no P-Asserted-Identity and no From URI is handed over with no delivery report to send. A submit report whose In-Reply-To lists Call-IDs (RFC 3261 20.21) is ours when ours is among them, and a delivered MESSAGE's Call-ID with an ASCII control character or a space in it is not written into the delivery report's In-Reply-To.
2026-10-16 23:20:56 +02:00
// The URI of the party a header names — of the first element of the
// first `name:` header's value: what stands in its angle brackets, a
// quoted display name before them passed over, or a bare URI up to its
// first parameter or the next element —
// the Request-URI of a request to that party (the IP-SM-GW of a
// delivered short message, TS 24.341 5.3.2.4: its P-Asserted-Identity).
// nullopt when the header is absent or that element gives no URI — a
// URI with an ASCII control character, a space, `<`, `>` or `"` in it
// is none: it would stand in a request line as it is.
std::optional<std::string> HeaderUri(std::string_view msg, std::string_view name) {
auto v = Header(msg, name);
if (!v) return std::nullopt;
std::string_view uri = *v;
std::size_t at = 0;
if (uri.starts_with('"')) // a quoted display name: its `<`, `,` and `;` are not the value's
for (at = 1; at < uri.size() && uri[at] != '"'; at++)
if (uri[at] == '\\') at++;
const std::size_t stop = uri.find_first_of("<,;", at);
if (stop != std::string_view::npos && uri[stop] == '<') {
const std::size_t gt = uri.find('>', stop);
if (gt == std::string_view::npos) return std::nullopt;
uri = uri.substr(stop + 1, gt - stop - 1);
} else {
uri = Trim(uri.substr(0, stop)); // a bare URI; a value that begins with a quote is none below
}
if (uri.empty() || !uri.contains(':')) return std::nullopt;
for (unsigned char c : uri)
if (c <= 0x20 || c == 0x7F || c == '<' || c == '>' || c == '"') return std::nullopt;
return std::string(uri);
}
// The body of a message: what follows the header terminator, empty
// without one.
std::string_view Body(std::string_view msg) {
std::size_t at = msg.find("\r\n\r\n");
return at == std::string_view::npos ? std::string_view{} : msg.substr(at + 4);
}
// SIP-over-TCP stream framing, transport-free: feed received bytes into
// Append(), pull complete messages (headers + Content-Length body) out
// of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are
// discarded.
class FrameBuffer {
public:
void Append(std::string_view data) { buf_.append(data); }
// One complete SIP message off the front of the buffer, or nullopt
// if more bytes are needed. Content-Length is located with the same
// line-anchored matching rules as Header().
std::optional<std::string> TryExtract() {
std::size_t keep = buf_.find_first_not_of("\r\n");
buf_.erase(0, keep == std::string::npos ? buf_.size() : keep);
std::size_t idx = buf_.find("\r\n\r\n");
if (idx == std::string::npos) return std::nullopt;
std::string_view head = std::string_view(buf_).substr(0, idx);
long clen = 0;
if (auto v = Header(head, "Content-Length")) clen = static_cast<long>(LengthOf(*v).value_or(0));
std::size_t total = idx + 4 + static_cast<std::size_t>(clen);
if (buf_.size() < total) return std::nullopt;
std::string msg = buf_.substr(0, total);
buf_.erase(0, total);
return msg;
}
std::size_t Size() const { return buf_.size(); }
private:
std::string buf_;
};
sip: UDP for the protected leg, TCP first with a fallback imsd's protected leg (the second REGISTER and everything after it) was TCP only. A P-CSCF that never answers the TCP connect on its protected server port (O2 UK: the SYNs leave ESP-protected, nothing comes back) left the unit looping with no way forward, although the SAs, the listener sockets and the firewall rule already covered UDP. The client flow now carries a transport. UDP binds the same protected client port and connect()s the datagram socket to the P-CSCF's protected server port, so the kernel delivers that peer's datagrams to it ahead of the unconnected listener on the same port. One datagram is one message (RFC 3261 18.3: a Content-Length that fits truncates, one that does not fit discards the datagram, none means the rest of the datagram); a receive error is logged and marks the flow dead; a message over the single-packet ESP budget at the ims PDN's MTU is logged once per flow, since the kernel fragments it and a P-CSCF may drop the fragments. Every protected request's Via follows the transport; the challenge stays UDP. SIP_TRANSPORT selects the policy: auto (default) registers over TCP and, after two unanswered connects, registers again over UDP (new challenge, new SA pair) - but only on a phone whose state file does not record a successful TCP registration, so an outage on a TCP carrier never becomes a second initial REGISTER; a phone whose last registration was UDP goes straight to UDP. tcp and udp force one. A connect refused locally (EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow) keeps retrying and is not counted as silence; SO_ERROR results are logged by name. The registration's transport is persisted so a warm resume reconnects the same way, and the resume gives up after two silences. Two things the change exposed and fixes: an engine-fatal event exited 0 ("exiting for systemd restart" with Restart=on-failure never firing), and a fresh registration refused with the P-CSCF's fresh-SA throttle (Security-Server spi-s=0) must not be retried by a 120-s restart loop, since every attempt re-arms the ~20-min window - it is now waited out in-process, growing on repeats, with D-Bus commands still served. A resume the network refuses falls through to a fresh registration. A retransmitted 200 OK to our INVITE is ACKed again and no longer starts a second media leg. Verified on KPN: resume over TCP after a binary swap, MT and MO calls with media both ways, the throttle deferral and its self-recovery, the UDP client path up to KPN dropping the datagram. The UDP success path is a field test; SIP retransmission timers over UDP are not in this change.
2026-09-17 14:58:46 +02:00
// The SIP message carried by one UDP datagram (RFC 3261 18.3): a
// datagram is never accumulated with the next. Leading CRLFs (an RFC
// 5626 keepalive pong) are not a message → nullopt, no problem. A
// Content-Length that fits truncates the body to it; one that does not
// fit is a truncated datagram → nullopt with `problem` set; no
// Content-Length means the body is the rest of the datagram. A datagram
// without a header terminator is malformed → nullopt with `problem`.
std::optional<std::string> DatagramMessage(std::string_view d, std::string* problem = nullptr) {
std::size_t start = d.find_first_not_of("\r\n");
if (start == std::string_view::npos) return std::nullopt;
d.remove_prefix(start);
std::size_t idx = d.find("\r\n\r\n");
if (idx == std::string_view::npos) {
if (problem) *problem = std::format("datagram without a header terminator ({} bytes)", d.size());
return std::nullopt;
}
std::size_t bodyStart = idx + 4;
std::size_t body = d.size() - bodyStart;
if (auto v = Header(d.substr(0, idx), "Content-Length")) {
if (const auto length = LengthOf(*v)) {
const std::size_t clen = *length;
sip: UDP for the protected leg, TCP first with a fallback imsd's protected leg (the second REGISTER and everything after it) was TCP only. A P-CSCF that never answers the TCP connect on its protected server port (O2 UK: the SYNs leave ESP-protected, nothing comes back) left the unit looping with no way forward, although the SAs, the listener sockets and the firewall rule already covered UDP. The client flow now carries a transport. UDP binds the same protected client port and connect()s the datagram socket to the P-CSCF's protected server port, so the kernel delivers that peer's datagrams to it ahead of the unconnected listener on the same port. One datagram is one message (RFC 3261 18.3: a Content-Length that fits truncates, one that does not fit discards the datagram, none means the rest of the datagram); a receive error is logged and marks the flow dead; a message over the single-packet ESP budget at the ims PDN's MTU is logged once per flow, since the kernel fragments it and a P-CSCF may drop the fragments. Every protected request's Via follows the transport; the challenge stays UDP. SIP_TRANSPORT selects the policy: auto (default) registers over TCP and, after two unanswered connects, registers again over UDP (new challenge, new SA pair) - but only on a phone whose state file does not record a successful TCP registration, so an outage on a TCP carrier never becomes a second initial REGISTER; a phone whose last registration was UDP goes straight to UDP. tcp and udp force one. A connect refused locally (EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow) keeps retrying and is not counted as silence; SO_ERROR results are logged by name. The registration's transport is persisted so a warm resume reconnects the same way, and the resume gives up after two silences. Two things the change exposed and fixes: an engine-fatal event exited 0 ("exiting for systemd restart" with Restart=on-failure never firing), and a fresh registration refused with the P-CSCF's fresh-SA throttle (Security-Server spi-s=0) must not be retried by a 120-s restart loop, since every attempt re-arms the ~20-min window - it is now waited out in-process, growing on repeats, with D-Bus commands still served. A resume the network refuses falls through to a fresh registration. A retransmitted 200 OK to our INVITE is ACKed again and no longer starts a second media leg. Verified on KPN: resume over TCP after a binary swap, MT and MO calls with media both ways, the throttle deferral and its self-recovery, the UDP client path up to KPN dropping the datagram. The UDP success path is a field test; SIP retransmission timers over UDP are not in this change.
2026-09-17 14:58:46 +02:00
if (clen > body) {
if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body);
return std::nullopt;
}
return std::string(d.substr(0, bodyStart + clen));
}
}
return std::string(d);
}
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 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.
2026-11-22 17:35:11 +01:00
// 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<std::string> CutShortRequest(std::string_view d) {
const std::size_t start = d.find_first_not_of("\r\n");
if (start == std::string_view::npos) return std::nullopt;
d.remove_prefix(start);
const std::size_t idx = d.find("\r\n\r\n");
if (idx == std::string_view::npos) return std::nullopt;
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";
}
}