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.
This commit is contained in:
Jorijn van der Graaf 2026-10-16 23:20:56 +02:00
commit 4de5f0be45
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
6 changed files with 917 additions and 23 deletions

View file

@ -4,8 +4,8 @@
// lint-disable-file fixed-width-types
/*
Imsd:Engine — the daemon's decisions as pure reducers: the call state
machine (CallMachine) and the registration recovery policy (RegRecovery,
its own section below).
machine (CallMachine), the registration recovery policy (RegRecovery,
its own section below) and SMS over IP's (the last paragraph here).
A CallMachine owns one call's SIP dialog, outgoing or incoming. It never
touches a socket, a clock, or a subprocess: each event (the INVITE's
@ -26,7 +26,17 @@ unit-testable against recorded network dialogs with no I/O (tests/Engine).
State/reason strings are the frozen D-Bus vocabulary the dialer maps on
(dialing/ringing/incoming/active/terminated; outgoing/incoming/accepted/
local-hangup/remote-hangup/refused-or-busy/error). Pure std C++.
local-hangup/remote-hangup/refused-or-busy/error).
SMS over IP (TS 24.341) has its own reducers at the end: SmsOutbound, one
short message of ours on its way to the service centre segment by segment
(the MESSAGE with the RP-DATA, its final, the submit report that comes
back in a MESSAGE of its own), and OnSmsMessage, what an inbound
MESSAGE outside a call's dialog leads to (the final for it, the message or
status report it delivered, the delivery report to send), with
RecentTransactions (a retransmitted request within 32 s gets its final
again and is not handled again; one whose first Via line has no
`branch=`, or an empty one, is never taken for a copy). Pure std C++.
*/
export module Imsd:Engine;
@ -34,6 +44,7 @@ import std;
import :Util;
import :Sip;
import :Sdp;
import :Sms;
import :Messages;
export namespace imsd::engine {
@ -375,7 +386,7 @@ export namespace imsd::engine {
auto rr = imsd::sip::Headers(invite_, "Record-Route");
for (std::size_t i = rr.size(); i-- > 0;)
d_.recordRoute.emplace_back(rr[i]);
answerSdp_ = std::string(Body(invite_)); // the caller's offer
answerSdp_ = std::string(imsd::sip::Body(invite_)); // the caller's offer
nextCseq_ = 0; // our first in-dialog request gets CSeq 1
}
@ -544,7 +555,7 @@ export namespace imsd::engine {
std::string_view method = Method(msg);
if (method == "ACK")
return a; // ACK is never responded to (RFC 3261 17.1.1.2)
std::string_view body = Body(msg);
std::string_view body = imsd::sip::Body(msg);
if (body.contains("m=audio")) answerSdp_ = std::string(body);
if (direction_ == Direction::Incoming && state_ == CallState::Incoming) {
if (method == "CANCEL") {
@ -782,7 +793,7 @@ export namespace imsd::engine {
std::optional<bool> FallbackTo(int code, std::string_view msg) const {
if (userCancelled_) return std::nullopt;
if (attemptSos_) return plainTried_ ? std::nullopt : std::optional(false);
if (code == 380 && !sosTried_ && Body(msg).contains("emergency")) return true;
if (code == 380 && !sosTried_ && imsd::sip::Body(msg).contains("emergency")) return true;
return std::nullopt;
}
@ -799,11 +810,6 @@ export namespace imsd::engine {
return a;
}
static 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);
}
static std::string_view Method(std::string_view msg) {
std::size_t sp = msg.find(' ');
return sp == std::string_view::npos ? msg : msg.substr(0, sp);
@ -827,7 +833,7 @@ export namespace imsd::engine {
d_.recordRoute.emplace_back(v);
}
if (auto ct = imsd::sip::Header(msg, "Contact")) d_.remoteTarget = AngleUri(*ct);
std::string_view body = Body(msg);
std::string_view body = imsd::sip::Body(msg);
if (body.contains("m=audio")) answerSdp_ = std::string(body);
}
@ -905,4 +911,429 @@ export namespace imsd::engine {
into.push_back(std::move(m));
}
};
// ---- SMS over IP (TS 24.341) -----------------------------------------
//
// A short message rides a SIP MESSAGE with an RP message of TS 24.011
// as its body. Submitting one (5.3.1.2): a MESSAGE with the RP-DATA to
// the service centre's PSI, answered with a final (after a 2xx the
// submit report is awaited), then the submit report — an RP-ACK or RP-ERROR
// — in a MESSAGE of its own, In-Reply-To naming ours, which
// we answer 200. Receiving one (5.3.2.3, 5.3.2.4): a MESSAGE with the
// RP-DATA, which we answer 200 at once, then our delivery report — an RP-ACK
// with the SMS-DELIVER-REPORT — in a MESSAGE of our own to the
// IP-SM-GW (the delivered MESSAGE's P-Asserted-Identity), In-Reply-To
// naming it (a Call-ID with an ASCII control character or a space in
// it is not written). The same bytes as over NAS; the SIP legs are the
// reducers' here, the sockets and the clock the shell's.
// A short message the network delivered, as the bus reports it.
struct SmsReceived {
std::string from; // the sender: a number ("+316…", a short code) or an alphanumeric name
std::string text; // the text, UTF-8 (empty for 8-bit data)
std::vector<std::uint8_t> data; // 8-bit data (an application-port message)
std::string scts; // the service centre's time stamp (ScTimeStamp's text)
std::string sc; // the service centre (RP-Originator Address)
std::optional<int> msgClass; // 0: a flash message; 2: meant for the (U)SIM
std::optional<std::uint16_t> portDst; // application port addressing
std::optional<std::uint16_t> portSrc;
bool messageWaiting = false; // a message-waiting indication group, of any type, set or cleared (`dcs` has which)
std::uint8_t pid = 0;
std::uint8_t dcs = 0;
int segments = 1; // the segments a concatenated message came in
std::vector<std::uint8_t> tpdu; // the SMS-DELIVER as received — of a concatenated message, the segment that completed the set (the last to arrive)
};
struct SmsAction {
enum class Type {
SendClient, // send `text` on the client flow (a MESSAGE of ours)
SendResponse, // answer the inbound MESSAGE being handled with `text`
Received, // hand `received` to the bus
StatusReport, // `report`: the SC's word on a message we sent (matched by TP-MR by the shell)
State, // emit StateChanged(id, `state`, `reason`) for a message of ours
Log,
};
Type type;
std::string text;
std::string id, state, reason;
SmsReceived received;
imsd::sms::StatusReport report;
};
// The waits (TS 24.011 10: TR1M; TS 24.341 5.3.1.1 NOTE 1 has it
// exceed SIP timer F): a MESSAGE's final within 32 s
// of the MESSAGE or of its latest provisional, which starts the wait
// over; the submit report within 40 s of the final — a length TR1M may
// have, though 6.3.1 sets TR1M when the RP-DATA is transferred.
inline constexpr double SmsSendTimeout = 32.0;
inline constexpr double SmsReportTimeout = 40.0;
// What the bus hears: `sent` once every segment's submit report is
// in, `failed` with the reason otherwise.
inline constexpr std::string_view SmsStateSent = "sent";
inline constexpr std::string_view SmsStateFailed = "failed";
// One short message of ours on its way to the service centre, segment
// by segment: the MESSAGE with the segment's RP-DATA, its final, the
// submit report, then the next segment. RP-MR and TP-MR count up from
// the values the shell hands over (TS 23.040 9.2.3.6, 9.2.3.24.1; the
// shell keeps the counters across messages). No retransmission: an
// unanswered MESSAGE or a report that never comes fails the message
// (TS 23.040 9.2.3.6's automatic repeat with TP-RD is not done) and
// the bus hears why.
class SmsOutbound {
public:
struct Params {
std::string number; // the destination as typed
std::string text;
std::string scTarget; // the SC's PSI as a SIP URI (the Request-URI and To)
std::vector<std::uint8_t> scAddress; // the SC as the RP-DATA's destination: [octets][toa][digits]
std::uint8_t tpMr = 0; // the first segment's TP-MR
std::uint8_t rpMr = 0; // the first segment's RP-MR
std::uint8_t concatRef = 0; // the concatenation reference when the text needs segments
std::optional<std::uint8_t> validity; // TP-VP, relative (EF_SMSP's)
bool statusReport = false; // ask the SC for a status report (TP-SRR)
};
enum class Phase { Idle, Sending, AwaitingReport, Done };
SmsOutbound(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string id, Params p)
: ctx_(ctx), rng_(rng), id_(std::move(id)), p_(std::move(p)) {}
const std::string& Id() const { return id_; }
Phase State() const { return phase_; }
bool Done() const { return phase_ == Phase::Done; }
// the engine's clock reading at which OnDeadline is due (0: none)
double Deadline() const { return deadline_; }
// the TP-MRs the segments went out with, for the shell to match a
// later status report to this message
const std::vector<std::uint8_t>& TpMrs() const { return tpMrs_; }
std::size_t Segments() const { return tpdus_.size(); }
// Builds the segments and sends the first. A destination that is
// no number, or a text past 255 segments, fails the message at once.
std::vector<SmsAction> Start(double now) {
std::vector<SmsAction> out;
imsd::sms::Submit s{p_.number, p_.tpMr, p_.validity, p_.statusReport};
tpdus_ = imsd::sms::BuildSubmits(s, p_.text, p_.concatRef);
if (tpdus_.empty()) {
phase_ = Phase::Done;
out.push_back(Fail(imsd::sms::Address::ForNumber(p_.number) ? "the text does not fit 255 segments" : std::format("'{}' is not a number", p_.number)));
return out;
}
if (p_.scAddress.empty() || p_.scTarget.empty()) {
phase_ = Phase::Done;
tpdus_.clear();
out.push_back(Fail("no service centre (none from SMSC= or EF_SMSP)"));
return out;
}
for (std::size_t i = 0; i < tpdus_.size(); i++) tpMrs_.push_back(static_cast<std::uint8_t>((p_.tpMr + i) & 0xFF));
SendSegment(out, now);
return out;
}
// The segment in flight's MESSAGE: its final is matched by Call-ID
// and CSeq.
bool OwnsResponse(std::string_view msg) const {
return phase_ == Phase::Sending && imsd::sip::ResponseOf(msg, callid_, "1 MESSAGE");
}
std::vector<SmsAction> OnResponse(std::string_view msg, int status, double now) {
std::vector<SmsAction> out;
if (phase_ != Phase::Sending) return out;
if (status < 200) {
deadline_ = now + SmsSendTimeout;
return out;
}
if (status >= 300) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("segment {}/{} refused: {}", seg_ + 1, tpdus_.size(), imsd::sip::RefusalSummary(msg))));
return out;
}
phase_ = Phase::AwaitingReport;
deadline_ = now + SmsReportTimeout;
out.push_back(LogAct(std::format("sms {}: segment {}/{} -> {}; awaiting the submit report", id_, seg_ + 1, tpdus_.size(), status)));
return out;
}
// Whether an RP-ACK/RP-ERROR the IP-SM-GW sent is this segment's:
// In-Reply-To names our MESSAGE (TS 24.341 5.3.1.2), or — from an
// IP-SM-GW that sends none — the RP-MR is the one in flight. A
// report arriving before the MESSAGE's own final (the IP-SM-GW's
// order is its own) is taken as well.
bool OwnsReport(std::string_view inReplyTo, std::optional<std::uint8_t> rpMr) const {
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return false;
if (!inReplyTo.empty()) { // a list of Call-IDs (RFC 3261 20.21): ours among them
for (auto part : std::views::split(inReplyTo, ','))
if (imsd::sip::Trim(std::string_view(part.begin(), part.end())) == callid_) return true;
return false;
}
return rpMr && *rpMr == CurrentRpMr();
}
// The submit report for the segment in flight: an RP-ACK moves to
// the next segment, or ends the message as sent; an RP-ERROR fails
// it with its cause. The shell answers the report's MESSAGE
// itself.
std::vector<SmsAction> OnReport(const imsd::sms::Rp& rp, double now) {
std::vector<SmsAction> out;
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return out;
if (rp.type == imsd::sms::RpType::ErrorMt) {
phase_ = Phase::Done;
std::string why = std::format("segment {}/{} refused by the SC: RP cause {} ({})", seg_ + 1, tpdus_.size(), rp.cause.value_or(0), imsd::sms::RpCauseText(rp.cause.value_or(0)));
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, true); r && r->failureCause)
why += std::format(", TP-FCS 0x{:02x} ({})", *r->failureCause, imsd::sms::FailureCauseText(*r->failureCause));
out.push_back(Fail(why));
return out;
}
if (rp.type != imsd::sms::RpType::AckMt) return out;
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, false); r && !r->scts.empty()) scts_ = r->scts;
seg_++;
if (seg_ < tpdus_.size()) { SendSegment(out, now); return out; }
phase_ = Phase::Done;
deadline_ = 0;
out.push_back(StateAct(SmsStateSent, scts_.empty() ? std::format("{} segment(s) accepted by the SC", tpdus_.size()) : std::format("{} segment(s) accepted by the SC at {}", tpdus_.size(), scts_)));
return out;
}
// The wait ran out: no final to the MESSAGE, or no submit report.
std::vector<SmsAction> OnDeadline() {
std::vector<SmsAction> out;
if (phase_ == Phase::Sending) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("no answer to the MESSAGE of segment {}/{} within {:.0f} s", seg_ + 1, tpdus_.size(), SmsSendTimeout)));
} else if (phase_ == Phase::AwaitingReport) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("no submit report for segment {}/{} within {:.0f} s of the final", seg_ + 1, tpdus_.size(), SmsReportTimeout)));
}
deadline_ = 0;
return out;
}
// The MESSAGE could not be sent (the flow is down).
std::vector<SmsAction> OnSendFailed() {
std::vector<SmsAction> out;
phase_ = Phase::Done;
deadline_ = 0;
out.push_back(Fail(std::format("segment {}/{} not sent: the flow to the P-CSCF is down", seg_ + 1, tpdus_.size())));
return out;
}
private:
std::uint8_t CurrentRpMr() const { return static_cast<std::uint8_t>((p_.rpMr + seg_) & 0xFF); }
void SendSegment(std::vector<SmsAction>& out, double now) {
callid_ = std::format("{}@{}", rng_.Token(16), ctx_.local);
std::vector<std::uint8_t> rp = imsd::sms::BuildRpData(CurrentRpMr(), p_.scAddress, tpdus_[seg_]);
out.push_back(SmsAction{SmsAction::Type::SendClient, imsd::msg::BuildMessageSms(ctx_, p_.scTarget, callid_, rng_.Token(8), rng_.Token(16), rp)});
out.push_back(LogAct(std::format("sms {}: segment {}/{} to {} via {}: MESSAGE sent (RP-MR {}, TP-MR {}, {} bytes)", id_, seg_ + 1, tpdus_.size(), p_.number, p_.scTarget, CurrentRpMr(), tpMrs_[seg_], tpdus_[seg_].size())));
phase_ = Phase::Sending;
deadline_ = now + SmsSendTimeout;
}
SmsAction Fail(std::string why) {
deadline_ = 0;
return StateAct(SmsStateFailed, std::move(why));
}
SmsAction StateAct(std::string_view state, std::string reason) {
SmsAction a{SmsAction::Type::State};
a.id = id_;
a.state = std::string(state);
a.reason = std::move(reason);
return a;
}
static SmsAction LogAct(std::string text) { return SmsAction{SmsAction::Type::Log, std::move(text)}; }
const imsd::msg::Context& ctx_;
imsd::util::Rng& rng_;
std::string id_;
Params p_;
std::vector<std::vector<std::uint8_t>> tpdus_;
std::vector<std::uint8_t> tpMrs_;
std::size_t seg_ = 0;
std::string callid_; // the segment in flight's MESSAGE
std::string scts_; // the SC's time stamp from the last RP-ACK's submit report
Phase phase_ = Phase::Idle;
double deadline_ = 0;
};
// ---- retransmitted requests (RFC 3261 17.2.2) ------------------------
// A request whose Via branch (the value of the first `branch=` of its
// first Via line), Call-ID and CSeq match one we already answered is
// taken for a retransmission — a key of imsd's own, where 17.2.3 matches
// by branch, sent-by and method: the server transaction gives the same
// final again and does nothing else, for 32 s after the final (Timer J
// on an unreliable transport; here on every transport). Used for
// MESSAGE (TS 24.341): a delivery came twice within a second (KPN,
// 2026-10-17 01:23) and the copy became a second text and a second
// delivery report; one of the two was refused with 488.
class RecentTransactions {
public:
static constexpr double TimerJ = 32.0;
// "<Call-ID>|<CSeq>|<branch>" of a request, the branch what follows the
// first `branch=` of its first Via line up to a `;`, a `,` or white
// space; empty when that is nothing (then nothing is remembered or matched).
static std::string Key(std::string_view request) {
auto via = imsd::sip::Header(request, "Via");
if (!via) return {};
const std::size_t b = via->find("branch=");
if (b == std::string_view::npos) return {};
std::string_view branch = via->substr(b + 7);
branch = branch.substr(0, branch.find_first_of(";, \t"));
if (branch.empty()) return {};
return std::format("{}|{}|{}", imsd::sip::Header(request, "Call-ID").value_or(""), imsd::sip::Header(request, "CSeq").value_or(""), branch);
}
// The final we gave this request before, when it is a retransmission.
std::optional<std::string> Repeat(std::string_view key, double now) {
Purge(now);
if (key.empty()) return std::nullopt;
auto it = seen_.find(std::string(key));
if (it == seen_.end()) return std::nullopt;
return it->second.response;
}
void Remember(std::string key, std::string response, double now) {
if (key.empty()) return;
seen_[std::move(key)] = Entry{std::move(response), now};
}
void Purge(double now) {
for (auto it = seen_.begin(); it != seen_.end();) {
if (now - it->second.at > TimerJ) it = seen_.erase(it);
else ++it;
}
}
std::size_t Size() const { return seen_.size(); }
private:
struct Entry { std::string response; double at; };
std::map<std::string, Entry> seen_;
};
// What an inbound MESSAGE leads to.
struct SmsInbound {
std::string response; // the final for it (always set)
std::vector<SmsAction> actions; // what it delivered, and the delivery report to send
std::string reportCallId; // the delivery report MESSAGE's Call-ID (empty: none sent)
std::optional<imsd::sms::Rp> rp; // the RP message it carried
};
// An inbound MESSAGE (TS 24.341 5.3.2.3, 5.3.1.2, 5.3.1.3). An RP-DATA
// with an SMS-DELIVER is answered 200, handed to the reassembler and,
// whole, to the bus, and acknowledged with an RP-ACK carrying the
// SMS-DELIVER-REPORT in a MESSAGE to the IP-SM-GW; one with an
// SMS-STATUS-REPORT is acknowledged the same way and the report handed
// over for the shell to match; one whose TPDU is unusable is
// acknowledged with an RP-ERROR (cause 96, TP-FCS "TPDU not supported")
// and logged — each report to the delivered MESSAGE's P-Asserted-Identity,
// else its From; one that gives neither URI gets none, which is logged.
// An RP-ACK/RP-ERROR is a submit report: the message in
// flight (`outbound`) takes it and the MESSAGE is answered 200; one the
// message in flight does not own is answered 488 when its In-Reply-To is
// not empty, else 200 and logged. A MESSAGE whose Content-Type
// does not contain the SMS one, or whose body is no RP message, is
// answered 200 and logged (the journal keeps what the 200 acknowledged).
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, double now) {
using imsd::sms::RpType;
SmsInbound r;
const std::string toTag = rng.Token(10); // the To tag for the finals we give this request (RFC 3261 8.2.6.2; BuildResponse adds it unless the To holds `tag=`)
r.response = imsd::msg::BuildResponse(ctx, message, 200, "OK", toTag);
std::string_view body = imsd::sip::Body(message);
std::string ctype(imsd::sip::Header(message, "Content-Type").value_or(""));
for (char& c : ctype) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
// the delivery report's In-Reply-To: a Call-ID with an ASCII control
// character or a space in it is not written into a request of ours
std::string callid(imsd::sip::Header(message, "Call-ID").value_or(""));
if (std::ranges::any_of(callid, [](unsigned char c) { return c <= 0x20 || c == 0x7F; })) callid.clear();
const std::string from = imsd::sip::CallerId(message);
if (!ctype.contains(imsd::msg::SmsContentType)) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("MESSAGE from {} ({}, {} bytes):\n{}", from, ctype.empty() ? "no content type" : ctype, body.size(), body)});
return r;
}
std::span<const std::uint8_t> bytes(reinterpret_cast<const std::uint8_t*>(body.data()), body.size()); // lint-disable-line no-char-pointer
r.rp = imsd::sms::ParseRp(bytes, true);
if (!r.rp) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("MESSAGE from {} with {} bytes that are no RP message: {}", from, body.size(), imsd::util::ToHex(bytes))});
return r;
}
const imsd::sms::Rp& rp = *r.rp;
if (rp.type == RpType::AckMt || rp.type == RpType::ErrorMt) {
std::string inReplyTo; // every In-Reply-To row: the rows are one list (RFC 3261 7.3.1)
for (std::string_view row : imsd::sip::Headers(message, "In-Reply-To")) inReplyTo.append(inReplyTo.empty() ? "" : ",").append(row);
if (outbound && outbound->OwnsReport(inReplyTo, rp.mr)) {
r.actions = outbound->OnReport(rp, now);
return r;
}
if (!inReplyTo.empty()) {
r.response = imsd::msg::BuildResponse(ctx, message, 488, "Not Acceptable Here", toTag);
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: no MESSAGE of ours in flight; 488", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", inReplyTo)});
return r;
}
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}, RP-MR {}) for no message in flight; 200", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", rp.mr)});
return r;
}
// what is left is an RP-DATA: ParseRp gave one of the network's three
// types, and the two reports have returned above
// the delivery report goes where the delivered MESSAGE came from:
// its P-Asserted-Identity (5.3.2.4 NOTE 1), else its From
std::string gateway = imsd::sip::HeaderUri(message, "P-Asserted-Identity").value_or(imsd::sip::HeaderUri(message, "From").value_or(""));
auto report = [&](std::vector<std::uint8_t> body, std::string_view what) {
if (gateway.empty()) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("no P-Asserted-Identity or From URI on the delivered MESSAGE: no {} sent", what)});
return;
}
r.reportCallId = std::format("{}@{}", rng.Token(16), ctx.local);
r.actions.push_back(SmsAction{SmsAction::Type::SendClient, imsd::msg::BuildMessageSms(ctx, gateway, r.reportCallId, rng.Token(8), rng.Token(16), body, callid)});
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("{} (RP-MR {}) -> {}", what, rp.mr, gateway)});
};
const std::string sc = rp.sc ? rp.sc->Number() : std::string();
switch (imsd::sms::KindOfTpdu(rp.tpdu)) {
case imsd::sms::TpduKind::StatusReport: {
auto sr = imsd::sms::ParseStatusReport(rp.tpdu);
if (!sr) break;
SmsAction a{SmsAction::Type::StatusReport};
a.report = *sr;
r.actions.push_back(a);
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("status report from {}: TP-MR {} to {}: {} (discharged {})", sc, sr->mr, sr->recipient.Number(), imsd::sms::StatusText(sr->status), sr->dischargeTime)});
report(imsd::sms::BuildRpAck(rp.mr, imsd::sms::DeliverReportAck()), "delivery report RP-ACK");
return r;
}
case imsd::sms::TpduKind::Deliver:
case imsd::sms::TpduKind::Reserved: {
auto d = imsd::sms::ParseDeliver(rp.tpdu);
if (!d) break;
const bool concat = d->ud.header.concat.has_value();
const int total = concat ? d->ud.header.concat->total : 1;
const int seq = concat ? d->ud.header.concat->seq : 1;
std::string segment = concat ? std::format(", segment {}/{} of set {}", seq, total, d->ud.header.concat->ref) : std::string();
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message from {} via {} at {}{}: {} ({} bytes)", d->from.Number(), sc, d->scts, segment, d->ud.alphabet == imsd::sms::Alphabet::Octet ? "8-bit data" : "text", rp.tpdu.size())});
if (auto whole = reassembler.Add(*d, now)) {
SmsAction a{SmsAction::Type::Received};
a.received.from = whole->from.Number();
a.received.text = whole->ud.text;
a.received.data = whole->ud.data;
a.received.scts = whole->scts;
a.received.sc = sc;
a.received.msgClass = whole->coding.msgClass;
a.received.portDst = whole->ud.header.portDst;
a.received.portSrc = whole->ud.header.portSrc;
a.received.messageWaiting = whole->coding.messageWaiting;
a.received.pid = whole->pid;
a.received.dcs = whole->dcs;
a.received.segments = total;
a.received.tpdu = rp.tpdu;
r.actions.push_back(std::move(a));
}
report(imsd::sms::BuildRpAck(rp.mr, imsd::sms::DeliverReportAck()), "delivery report RP-ACK");
return r;
}
case imsd::sms::TpduKind::SubmitReport:
break;
}
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("RP-DATA from {} whose TPDU is unusable ({} bytes: {}): RP-ERROR", sc, rp.tpdu.size(), imsd::util::ToHex(rp.tpdu))});
report(imsd::sms::BuildRpError(rp.mr, imsd::sms::RpCauseInvalidMandatoryInformation, imsd::sms::DeliverReportError(imsd::sms::FcsTpduNotSupported)), "delivery report RP-ERROR");
return r;
}
}

View file

@ -300,6 +300,44 @@ export namespace imsd::sip {
return "";
}
// 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