A flow that is dead in a way imsd has not seen yet, the peer having dropped the connection's state, shows itself at the next bytes sent on it, where the peer answers them with a reset. Where those bytes were an outgoing call's INVITE, imsd read the reset, marked the flow dead and did nothing more for the call: no reconnect runs while a call is up, so the attempt stayed in `dialing` until its setup deadline, 90 s, sent a CANCEL that could not go out and was given up 10 s later, where a call that is no emergency call ends (`setup deadline expired`); the flow was reconnected only once the call was gone. Against a stand-in network that forgets a flow after 20 s of silence, 1.2.3's call ended 100 s after the Dial. The engine's loop now takes such a call up (MaybeResendInvite). When the client flow is found dead under an outgoing attempt whose INVITE has had no response, a 100 included, and no CANCEL, the dead socket is closed without a FIN's exchange, the flow is reopened with one connect and the same INVITE is sent again, the setup deadline running from then. Once per attempt: an emergency call's fallback attempt has a resend of its own. The INVITE is the first one byte for byte, its branch included, so a server that did receive the first matches the second to its transaction (RFC 3261 17.2.3). No REGISTER goes first: the registration and its SAs stand, and TS 33.203 7.1 has a UE with no TCP connection towards the P-CSCF set one up before it sends a request. Where a reg-event NOTIFY has ended the binding nothing is reopened. Where nothing is reopened, the connect fails (one that gets no answer, after 12 s) or the flow dies again before a response, the call ends with `error`, an emergency call's first attempt too: there is no flow for its fallback. The recovery policy takes the flow up once the call is gone, as before. The close without a FIN's exchange is for a flow the peer closed: closed the usual way, such a socket stays in the kernel's table until the peer has acknowledged imsd's own FIN, and a connect from its port before that is refused. A reset goes out in the FIN's place there; after a reset or the kernel's own giving up the socket is closed already and nothing is sent; and the reopen runs on a flow already found dead only. The recovery's reconnect closes the usual way, as before, and connects once more 10 s after such a refusal (one is in a user's log on O2, 2026-09-24, in the second the flow was found dead). Not changed: under a call, a flow that died with no reset and no close reaching the phone is found dead only when the kernel gives up on unacknowledged bytes, 924.6 s or more after them by its default tcp_retries2, so an attempt whose own INVITE is the first such bytes gets no response and is cancelled at its setup deadline, as before; a flow found dead after a response to the INVITE is not reopened, as before; a Dial whose INVITE cannot be sent ends its call at once, as before. Tested: tests/Engine (which attempt is sent again, the same bytes, once per attempt, the deadline anew, the call's end where the flow is lost); the daemon of this commit and 1.2.3's on the workstation against a stand-in network (the fp6 journal's 2026-11-24-crlf-keepalive capture, bench-dial.sh): a flow the network forgot, reopened and the INVITE answered 486 as on a live flow, where 1.2.3's call ended after 100 s; a flow the network closed at the INVITE, with the acknowledgement of the daemon's close kept back; one that died on the daemon's side at the kernel's retransmission limit; a network that takes no new connection, one that resets the second INVITE's flow too and one that has ended the binding, where the call ended within a second; UDP. And on the dev phone on KPN, the binary of the range's tip: a call to voicemail answered and hung up, and one whose flow was made to die under the INVITE before the INVITE left the phone: reopened from the same port, the INVITE again 2.1 s after the death was found, answered 0.2 s later. By a call, no P-CSCF that had dropped a flow's state has been met, and none that had received the first INVITE before the flow died.
1843 lines
103 KiB
C++
1843 lines
103 KiB
C++
// SPDX-License-Identifier: GPL-3.0-only
|
||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||
|
||
/*
|
||
Imsd:Engine — the daemon's decisions as pure reducers: the call state
|
||
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
|
||
responses, an in-dialog request from the network, an accept/hang-up command,
|
||
the media leg exiting, a setup timeout) is a method that mutates the dialog
|
||
state and returns a list of Actions for the daemon shell to carry out — send
|
||
this on the client flow, answer the request on the channel it came in on,
|
||
start/stop the media leg, emit this D-Bus state change, arm this deadline.
|
||
That keeps the whole call FSM — PRACK on reliable 18x, ACK of 2xx vs non-2xx
|
||
finals, CANCEL/answer races, remote BYE, media-plane far-end-hangup, the
|
||
emergency attempt chain (urn:service:sos first for a classified number, one
|
||
fallback to a plain INVITE of the digits; a 380 Alternative Service upgrade
|
||
the other way), the terminating (UAS) side: 100/180 on an inbound INVITE,
|
||
200-with-answer on Accept, 486 reject, the remote-CANCEL 200+487 pair — and
|
||
DTMF, which reaches the media leg only on an active call whose SDP
|
||
negotiated telephone-event, as the tones a keypad has —
|
||
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).
|
||
|
||
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; a segment that gets no answer, or an
|
||
RP-ERROR with cause 41, sent once more, TP-RD set), 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), RecentSubmissions (the
|
||
Call-IDs of the MESSAGEs our submissions went out in, an hour each: a submit
|
||
report for one no longer in flight is answered 200, not 488), and StatusReportBook with SameRecipient (a status
|
||
report's match to the message that asked for one, TP-MR and recipient, and
|
||
its word for the whole message), SmsWordOrder (the order of a message's
|
||
words) and the ids (RunToken, SentSmsId, ReceivedSmsId), and the received-message store's record codec
|
||
(FormatStoredSms/ParseStoredSms) and order (StoredSmsBefore). Pure std C++.
|
||
*/
|
||
|
||
export module Imsd:Engine;
|
||
import std;
|
||
import :Util;
|
||
import :Sip;
|
||
import :Sdp;
|
||
import :Sms;
|
||
import :Messages;
|
||
|
||
export namespace imsd::engine {
|
||
|
||
enum class CallState { Dialing, Ringing, Incoming, Active, Terminated };
|
||
enum class Direction { Outgoing, Incoming };
|
||
|
||
inline std::string_view StateStr(CallState s) {
|
||
switch (s) {
|
||
case CallState::Dialing: return "dialing";
|
||
case CallState::Ringing: return "ringing";
|
||
case CallState::Incoming: return "incoming";
|
||
case CallState::Active: return "active";
|
||
case CallState::Terminated: return "terminated";
|
||
}
|
||
return "terminated";
|
||
}
|
||
|
||
inline std::string_view DirectionStr(Direction d) {
|
||
return d == Direction::Incoming ? "incoming" : "outgoing";
|
||
}
|
||
|
||
// ---- registration recovery policy ---------------------------------
|
||
//
|
||
// What the daemon does when the registration stops working after
|
||
// bring-up, as a pure reducer: the shell supplies the clock and the
|
||
// network, this decides the next step and how long to wait for it. Two
|
||
// kinds of failure reach it. A REFUSAL: the network answered a refresh
|
||
// with a final other than 200 — a 401, re-authentication, included — or
|
||
// a fresh registration's protected REGISTER with a final other than 200
|
||
// (the unprotected one's 401 is its challenge). SILENCE: the
|
||
// flow died and reconnecting through the SA, or the refresh over it,
|
||
// got no answer. Neither is retried for long on the same registration.
|
||
// TS 24.229 5.1.1.4.1 has the UE perform an initial registration after
|
||
// a 408, 500, 504 or 403 on a re-REGISTER (5.1.1.2.1: not before a
|
||
// Retry-After has passed), and RFC 5626 has it register again when its
|
||
// flow cannot be recovered. imsd does so after any refusal: the 503s
|
||
// below are not in that list. Before this reducer the daemon looped
|
||
// reconnect + re-REGISTER on the same Call-ID and SA forever — O2 UK,
|
||
// 2026-09-24: 21 × 503 over 70 min, then 33 unanswered reconnect
|
||
// cycles over 2 h 39 min, each ended only by a manual restart whose
|
||
// fresh registration the network accepted within two seconds (ims
|
||
// ledger F16).
|
||
//
|
||
// Pacing. Reconnect cycles back off 5 s → 5 min. A refusal without a
|
||
// Retry-After of at least a second (none, 0, unparsable) escalates to
|
||
// a fresh registration after two (one 503 may be a momentary hiccup a
|
||
// retried refresh clears); one with such a Retry-After escalates at
|
||
// once — it is the network's considered answer (O2 2026-10-08: the
|
||
// refresh after the first wait was refused again, 414 s then 772 s) —
|
||
// and so does a 401, the network asking to re-authenticate, which imsd
|
||
// answers with a fresh registration (TS 24.229 5.1.1.5.1's temporary
|
||
// SAs on the proposed client port are not implemented). Silence
|
||
// escalates after two reconnect cycles
|
||
// that end without an answer — a TCP connect series whose last attempt
|
||
// was not a local refusal, a bind() the kernel refused, or a refresh
|
||
// that fails short of a refusal: unanswered, a failed send (the resume
|
||
// at start gives up after two unanswered
|
||
// connects).
|
||
// A fresh registration is the expensive step: an AKA run, a
|
||
// new SA pair, and on KPN a refusal (spi-s=0) while the registration on
|
||
// the address is live, which costs that registration. So a refused or
|
||
// throttled fresh attempt
|
||
// waits on the throttle schedule (21 min, growing ×1.5 to 60) and a
|
||
// silent one backs off 30 s → 10 min. Retry-After (RFC 3261 20.33)
|
||
// always wins over a shorter wait. A 403 is a refusal like the others:
|
||
// never hammered (the schedule), never abandoned (a SIM that is
|
||
// unbarred registers within the hour); once a fresh registration is
|
||
// due it also says the old registration is gone (KPN drops it the
|
||
// moment an initial REGISTER arrives, throttled or not), as does a
|
||
// fresh attempt that got past the SA setup, a binding the network
|
||
// terminated, and a bring-up resume that failed while a fresh
|
||
// registration follows (OldGone; with no fresh target a resumable pair
|
||
// is kept for the restart, §7.2 step 1) — no reconnect over the old SA
|
||
// from then on. Every wait
|
||
// is either the self-imposed backoff, which a user's Dial cuts short,
|
||
// or the network's own word (a Retry-After, the schedule after a
|
||
// refused or throttled fresh attempt, a terminated binding's probation
|
||
// or its refusal schedule), which nothing cuts short — a
|
||
// restart of the process neither: the shell keeps the holds (Holds)
|
||
// and hands them to the next one (Restore). The shell supplies the
|
||
// clock and the network; this holds the deadlines and names the next
|
||
// step (Next). Success resets everything.
|
||
struct RegRecovery {
|
||
enum class Failure { Refused, Silent, Throttled };
|
||
enum class Step { Reconnect, Fresh };
|
||
// What comes next: the step, and the earliest time it may run (the
|
||
// shell's clock; at <= now means now).
|
||
struct Plan { Step step; double at; };
|
||
|
||
static constexpr int RefusalsBeforeFresh = 2;
|
||
static constexpr int SilentCyclesBeforeFresh = 2;
|
||
static constexpr double ReconnectDelayMin = 5;
|
||
static constexpr double ReconnectDelayMax = 300;
|
||
static constexpr double FreshDelayMin = 30;
|
||
static constexpr double FreshDelayMax = 600;
|
||
static constexpr int ThrottleMinutesMin = 21;
|
||
static constexpr int ThrottleMinutesMax = 60;
|
||
// The network's word is honoured up to the schedule's own longest
|
||
// wait: a Retry-After beyond an hour is cut to it, and the refusal
|
||
// heard again then — one REGISTER an hour at most, never a day
|
||
// unregistered on one answer.
|
||
static constexpr long RetryAfterMax = ThrottleMinutesMax * 60;
|
||
// A connect refused locally — our own 4-tuple still in TIME_WAIT
|
||
// (up to 60 s after we closed it), no route yet — is not the
|
||
// network's answer: retried soon, never counted, the backoff
|
||
// untouched. Dev phone 2026-09-24: four such refusals in 26 s read
|
||
// as two silent cycles cost a fresh registration into the throttle.
|
||
static constexpr double LocalRetry = 5;
|
||
|
||
int refusals = 0;
|
||
int silentCycles = 0;
|
||
int freshAttempts = 0;
|
||
double reconnectDelay = ReconnectDelayMin;
|
||
double freshDelay = FreshDelayMin;
|
||
int throttleMinutes = ThrottleMinutesMin;
|
||
bool fresh = false; // the next registration attempt is a fresh one
|
||
bool oldGone = false; // the old registration is gone: nothing to reconnect over
|
||
bool terminated = false; // the network terminated our binding, and the policy has counted it
|
||
// the deadlines, on the shell's clock
|
||
double backoffUntil = 0; // self-imposed: no step before this; a Dial clears it
|
||
double holdUntil = 0; // the network's word for any attempt (a Retry-After on a refresh): nothing clears it
|
||
double freshHoldUntil = 0; // no fresh attempt before this (the schedule after a refused or throttled fresh attempt, a fresh Retry-After, probation, rejected/unregistered)
|
||
|
||
bool Fresh() const { return fresh; }
|
||
bool Reconnectable() const { return !oldGone; }
|
||
|
||
// The network's holds as seconds still to run, and where the
|
||
// schedule stands: what a restart of the process must not forget.
|
||
struct Held {
|
||
double hold = 0;
|
||
double freshHold = 0;
|
||
int throttleMinutes = ThrottleMinutesMin;
|
||
bool oldGone = false; // the old registration is gone: the next process has nothing to reconnect over
|
||
int refusals = 0; // refused reconnects counted so far (RefusalsBeforeFresh): a restart's refusal is the next one, not the first
|
||
// a schedule that has advanced is kept too, until a success resets it, and so are the gone verdict and the count
|
||
bool Any() const { return hold > 0 || freshHold > 0 || throttleMinutes > ThrottleMinutesMin || oldGone || refusals > 0; }
|
||
};
|
||
Held Holds(double now) const { return {std::max(0.0, holdUntil - now), std::max(0.0, freshHoldUntil - now), throttleMinutes, oldGone, refusals}; }
|
||
// A restarted process takes them over; nothing here shortens a
|
||
// hold it already has, or lengthens one past RetryAfterMax.
|
||
void Restore(double now, const Held& h) {
|
||
if (h.hold > 0) holdUntil = std::max(holdUntil, now + std::min(h.hold, static_cast<double>(RetryAfterMax)));
|
||
if (h.freshHold > 0) freshHoldUntil = std::max(freshHoldUntil, now + std::min(h.freshHold, static_cast<double>(RetryAfterMax)));
|
||
throttleMinutes = std::clamp(std::max(throttleMinutes, h.throttleMinutes), ThrottleMinutesMin, ThrottleMinutesMax);
|
||
refusals = std::max(refusals, h.refusals);
|
||
if (h.oldGone) OldGone(); // no reconnect over SAs the network has written off
|
||
}
|
||
|
||
// The next step and when. Not escalated: a reconnect after the
|
||
// backoff and any hold. Escalated: the fresh attempt once the
|
||
// backoff, any hold and the fresh hold have passed — and while a
|
||
// fresh hold still runs, a reconnect over the old SA meanwhile, the
|
||
// cheap thing, unless that registration is gone.
|
||
Plan Next(double now) const {
|
||
double any = std::max(backoffUntil, holdUntil);
|
||
double freshAt = std::max(any, freshHoldUntil);
|
||
if (!fresh) return {Step::Reconnect, any};
|
||
if (!oldGone && freshHoldUntil > any && now < freshHoldUntil) return {Step::Reconnect, any};
|
||
return {Step::Fresh, freshAt};
|
||
}
|
||
|
||
void OnLocalRefusal(double now) { backoffUntil = now + LocalRetry; }
|
||
|
||
// A refused keepalive refresh, or a failed reconnect + refresh
|
||
// cycle; `status` is the refusal's. The backoff paces the next step;
|
||
// a Retry-After of at least a second holds every attempt for its own
|
||
// length (up to RetryAfterMax), whichever is longer, and makes the
|
||
// next step the fresh registration, as does a 401. A 403 once a fresh
|
||
// registration is due says the old registration is gone (KPN drops
|
||
// it the moment an initial REGISTER arrives, throttled or not).
|
||
void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) {
|
||
if (retryAfter > 0) holdUntil = std::max(holdUntil, now + static_cast<double>(std::min(retryAfter, RetryAfterMax)));
|
||
// A cycle over a registration already known gone — the network
|
||
// terminated the binding while the cycle waited for its final —
|
||
// fails by definition: not a silent cycle, not a refusal, and no
|
||
// backoff before the fresh registration that verdict scheduled.
|
||
if (oldGone) return;
|
||
if (f == Failure::Refused) refusals++;
|
||
else silentCycles++;
|
||
if (refusals >= RefusalsBeforeFresh || silentCycles >= SilentCyclesBeforeFresh) fresh = true;
|
||
if (f == Failure::Refused && (retryAfter > 0 || status == 401)) fresh = true;
|
||
if (status == 403 && fresh) oldGone = true;
|
||
backoffUntil = now + reconnectDelay;
|
||
reconnectDelay = std::min(reconnectDelay * 2, ReconnectDelayMax);
|
||
}
|
||
|
||
// A failed fresh registration; `saReplaced`: it got past the SA
|
||
// setup, so the old registration's SAs went with it. Refusals and
|
||
// throttles hold the next fresh attempt on the schedule (a Retry-After
|
||
// replaces it, never below the short backoff's floor nor above
|
||
// RetryAfterMax); silence backs
|
||
// it off 30 s → 10 min. A reconnect over the old SA meanwhile waits
|
||
// at least the reconnect backoff.
|
||
void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) {
|
||
freshAttempts++;
|
||
fresh = true;
|
||
if (saReplaced) oldGone = true;
|
||
backoffUntil = std::max(backoffUntil, now + reconnectDelay);
|
||
if (f == Failure::Silent) {
|
||
backoffUntil = std::max(backoffUntil, now + freshDelay);
|
||
freshDelay = std::min(freshDelay * 2, FreshDelayMax);
|
||
return;
|
||
}
|
||
double wait = throttleMinutes * 60.0;
|
||
throttleMinutes = std::min(throttleMinutes * 3 / 2, ThrottleMinutesMax);
|
||
if (retryAfter > 0) wait = std::max(static_cast<double>(std::min(retryAfter, RetryAfterMax)), FreshDelayMin);
|
||
freshHoldUntil = now + wait;
|
||
}
|
||
|
||
// The network terminated our binding (a reg-event NOTIFY, RFC
|
||
// 3680): the old registration is gone. deactivated and expired
|
||
// mean a fresh registration now; probation after the network's
|
||
// retry-after (up to RetryAfterMax); rejected and unregistered on the
|
||
// refusal schedule —
|
||
// the network's word is neither hammered nor taken as final. One
|
||
// termination counts once, however often it is reported (every
|
||
// reg-event dialog of the account carries it, a NOTIFY may be
|
||
// retransmitted), and never shortens a hold already running.
|
||
void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) {
|
||
bool reported = terminated;
|
||
terminated = true;
|
||
oldGone = true;
|
||
fresh = true;
|
||
if (event == "probation") {
|
||
freshHoldUntil = std::max(freshHoldUntil, now + static_cast<double>(std::clamp(retryAfter, 1L, RetryAfterMax)));
|
||
} else if (reported) {
|
||
return;
|
||
} else if (event == "rejected" || event == "unregistered") {
|
||
freshHoldUntil = std::max(freshHoldUntil, now + throttleMinutes * 60.0);
|
||
throttleMinutes = std::min(throttleMinutes * 3 / 2, ThrottleMinutesMax);
|
||
} else {
|
||
backoffUntil = 0;
|
||
}
|
||
}
|
||
|
||
// The stored registration is not there to reconnect over (a resume
|
||
// that failed at bring-up found its SAs unusable, or there are none).
|
||
void OldGone() { oldGone = true; fresh = true; }
|
||
|
||
// A user's Dial cuts the backoff short, never the network's word.
|
||
void OnDial() { backoffUntil = 0; }
|
||
|
||
void OnSuccess() { *this = RegRecovery{}; }
|
||
};
|
||
|
||
// Parsed SDP answer needed to bring up the media leg. `codec` is one of
|
||
// imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play).
|
||
// `dtmfPt` is the telephone-event payload type at the codec's clock
|
||
// (RFC 4733) the leg sends with — the peer's SDP's; nullopt = none
|
||
// negotiated, no DTMF on this call. `dtmfRxPt` is a second number the
|
||
// leg takes events at: our own SDP's at that clock — our offer's
|
||
// number on a call we placed (an answerer sends with the offer's
|
||
// numbers, RFC 3264 §6.1, and may renumber ours in the answer), the
|
||
// offer's we echoed on a call we answered; the answer's telephone-event
|
||
// number instead when the answer gave the audio our offer's number,
|
||
// which is then the leg's audio number. The leg takes events at
|
||
// either number, never at the audio's.
|
||
struct MediaLeg {
|
||
std::string remoteIp;
|
||
int remotePort = 0;
|
||
int payloadType = -1;
|
||
bool octetAlign = false;
|
||
std::string codec = "AMR-WB";
|
||
std::optional<int> dtmfPt;
|
||
std::optional<int> dtmfRxPt;
|
||
bool Valid() const { return !remoteIp.empty() && remotePort > 0 && payloadType >= 0; }
|
||
};
|
||
|
||
struct Action {
|
||
enum class Type {
|
||
SendClient, // send `text` on the client TCP flow
|
||
SendResponse, // answer the just-handled inbound request on its origin channel
|
||
StartMedia, // bring up the media leg described by `media`
|
||
StopMedia, // tear the media leg down
|
||
SendDtmf, // hand `text` (the tones) to the running media leg
|
||
State, // emit CallStateChanged(uni, `state`, `reason`)
|
||
Deleted, // emit CallDeleted(uni); drop this machine
|
||
SetDeadline, // arm a setup timer for `seconds`; fire calls OnDeadline()
|
||
Log,
|
||
};
|
||
Type type;
|
||
std::string text;
|
||
std::string state;
|
||
std::string reason;
|
||
MediaLeg media;
|
||
double seconds = 0;
|
||
};
|
||
|
||
// The most tones one SendDtmf may carry (a keypad sends one; a dialer's
|
||
// string is a short sequence): the leg's `dtmf <tones>\n` line stays
|
||
// within one atomic pipe write, POSIX's 512-byte PIPE_BUF floor.
|
||
inline constexpr std::size_t DtmfMaxTones = 128;
|
||
|
||
// ring/answer budget, and how long to wait for a 487 after CANCEL — the
|
||
// imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants.
|
||
inline constexpr double InviteTimeout = 90.0;
|
||
inline constexpr double Cancel487Timeout = 10.0;
|
||
// How long an unanswered incoming call may ring before we 480 it — a
|
||
// safety net behind the network's own CANCEL, so generous.
|
||
inline constexpr double IncomingRingTimeout = 120.0;
|
||
|
||
// Constructor tag: this machine is the UAS of the given inbound INVITE.
|
||
struct IncomingInvite {
|
||
std::string_view invite;
|
||
};
|
||
|
||
class CallMachine {
|
||
public:
|
||
// `emergency`: the shell classified the dialled string as an
|
||
// emergency number — the first attempt targets urn:service:sos.
|
||
// `codecs`: the daemon's CODECS override — the codecs offered on an
|
||
// outgoing call and accepted from an inbound offer, in preference
|
||
// order; empty = the sdp module's defaults.
|
||
CallMachine(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string uni, std::string number, int rtpPort, bool precond, bool emergency = false,
|
||
std::vector<std::string> codecs = {})
|
||
: ctx_(ctx), rng_(rng), uni_(std::move(uni)), number_(std::move(number)),
|
||
rtpPort_(rtpPort), precond_(precond), codecs_(std::move(codecs)), attemptSos_(emergency) {
|
||
ResetDialog();
|
||
}
|
||
|
||
CallMachine(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string uni, IncomingInvite in, int rtpPort,
|
||
std::vector<std::string> codecs = {})
|
||
: ctx_(ctx), rng_(rng), uni_(std::move(uni)), rtpPort_(rtpPort),
|
||
precond_(false), codecs_(std::move(codecs)), direction_(Direction::Incoming),
|
||
state_(CallState::Incoming), reason_("incoming"),
|
||
invite_(in.invite) {
|
||
number_ = imsd::sip::CallerId(invite_);
|
||
d_.callid = std::string(imsd::sip::Header(invite_, "Call-ID").value_or(""));
|
||
d_.itag = rng_.Token(10); // the To tag we mint = our dialog tag
|
||
d_.invBranch = rng_.Token(20); // unused as UAS; kept initialized
|
||
if (auto from = imsd::sip::Header(invite_, "From")) d_.dialogTo = std::string(*from);
|
||
if (auto to = imsd::sip::Header(invite_, "To")) d_.localUri = AngleUri(*to).value_or("");
|
||
if (auto ct = imsd::sip::Header(invite_, "Contact")) d_.remoteTarget = AngleUri(*ct);
|
||
d_.ruri = d_.remoteTarget.value_or("");
|
||
// The UAS route set is the Record-Route in RECEIVED order
|
||
// (RFC 3261 12.1.1); DialogRoute() reverses for the UAC case, so
|
||
// store it reversed here to cancel that out.
|
||
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(imsd::sip::Body(invite_)); // the caller's offer
|
||
nextCseq_ = 0; // our first in-dialog request gets CSeq 1
|
||
}
|
||
|
||
const std::string& Uni() const { return uni_; }
|
||
const std::string& Number() const { return number_; }
|
||
const std::string& CallId() const { return d_.callid; }
|
||
CallState State() const { return state_; }
|
||
std::string_view StateStr() const { return engine::StateStr(state_); }
|
||
Direction Dir() const { return direction_; }
|
||
std::string_view DirectionStr() const { return engine::DirectionStr(direction_); }
|
||
const std::string& Reason() const { return reason_; }
|
||
bool Terminated() const { return state_ == CallState::Terminated; }
|
||
|
||
// Build + queue the INVITE for the current attempt and arm the ring
|
||
// timeout.
|
||
std::vector<Action> Start() {
|
||
if (attemptSos_) sosTried_ = true;
|
||
else
|
||
plainTried_ = true;
|
||
imsd::sdp::Offer offer;
|
||
offer.local = ctx_.local;
|
||
offer.rtpPort = rtpPort_;
|
||
offer.sessionId = rng_.UInt(1000000, 9999999);
|
||
offer.precond = precond_;
|
||
offer.codecs = codecs_;
|
||
std::string sdp = imsd::sdp::BuildOffer(offer);
|
||
std::vector<Action> a;
|
||
inviteOut_ = imsd::msg::BuildInvite(ctx_, d_, sdp, precond_);
|
||
a.push_back(Send(inviteOut_));
|
||
a.push_back(Deadline(InviteTimeout));
|
||
return a;
|
||
}
|
||
|
||
// The current outgoing attempt has sent its INVITE and has had no
|
||
// response to it, not a 100 either, and no CANCEL has followed it.
|
||
// The shell asks when it finds the client flow dead under a call: a
|
||
// flow the network had forgotten is reset at the first bytes sent
|
||
// on it, and those may be this INVITE.
|
||
bool Unanswered() const {
|
||
return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_;
|
||
}
|
||
// … and the attempt has not been sent again yet.
|
||
bool ResendDue() const { return Unanswered() && !resent_; }
|
||
|
||
// The shell reopened the flow under an attempt whose resend is due:
|
||
// the same INVITE again, byte for byte (the same branch: RFC 3261
|
||
// 17.2.3 has a server that did receive the first match this one to
|
||
// its transaction), and the setup deadline from now. Once per
|
||
// attempt.
|
||
std::vector<Action> OnFlowReopened() {
|
||
std::vector<Action> a;
|
||
if (!ResendDue()) return a;
|
||
resent_ = true;
|
||
a.push_back(LogAct(std::format("call {}: the INVITE again over the reopened flow", uni_)));
|
||
a.push_back(Send(inviteOut_));
|
||
a.push_back(Deadline(InviteTimeout));
|
||
return a;
|
||
}
|
||
|
||
// The flow under an unanswered attempt is dead and stays so (it
|
||
// could not be reopened, or died again after the resend): the call
|
||
// ends here, an emergency call's first attempt too, with nothing to
|
||
// send a CANCEL on and no flow for a fallback attempt.
|
||
std::vector<Action> OnFlowLost() {
|
||
std::vector<Action> a;
|
||
if (!Unanswered()) return a;
|
||
Append(a, Finish("error", "the client flow died before any response to the INVITE"));
|
||
return a;
|
||
}
|
||
|
||
// UAS: answer the inbound INVITE with 100 Trying + 180 Ringing (made
|
||
// reliable only when the caller Requires 100rel) and arm the ring
|
||
// timeout. An offer we cannot serve — no audio line, or none of the
|
||
// codecs imsd-media plays (AMR-WB, AMR, PCMA, PCMU; the CODECS
|
||
// override narrows that set) — is refused with 488 up front, before
|
||
// the UI ever rings; the log line names
|
||
// what WAS offered, so a field journal answers "which codec did the
|
||
// gateway want" without a raw SIP dump.
|
||
std::vector<Action> OnInvite() {
|
||
std::vector<Action> a;
|
||
if (direction_ != Direction::Incoming || state_ != CallState::Incoming) return a;
|
||
MediaLeg leg = ParseAnswer();
|
||
if (!leg.Valid() || leg.codec.empty()) {
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 488, "Not Acceptable Here", d_.itag)));
|
||
std::string why = !leg.Valid() ? "no usable audio line"
|
||
: std::format("no playable codec, offered: {}", imsd::sdp::OfferedCodecs(answerSdp_));
|
||
Append(a, Finish("error", std::format("incoming offer unusable ({}); 488 sent", why)));
|
||
return a;
|
||
}
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 100, "Trying", d_.itag)));
|
||
std::string require(imsd::sip::Header(invite_, "Require").value_or(""));
|
||
if (require.contains("precondition")) a.push_back(LogAct("caller requires preconditions; answering without them"));
|
||
std::vector<std::string> extra;
|
||
if (require.contains("100rel")) {
|
||
extra.push_back("Require: 100rel");
|
||
extra.push_back("RSeq: 1");
|
||
}
|
||
last180_ = imsd::msg::BuildInviteResponse(ctx_, invite_, 180, "Ringing", d_.itag, std::nullopt, extra);
|
||
a.push_back(Respond(last180_));
|
||
a.push_back(Deadline(IncomingRingTimeout));
|
||
return a;
|
||
}
|
||
|
||
// UAS: the user answered. 200 OK with the SDP answer (the offer's own
|
||
// payload types, RFC 3264), media up, active. The caller's ACK needs
|
||
// no action when it arrives (OnRequest ignores ACK).
|
||
std::vector<Action> OnAccept() {
|
||
std::vector<Action> a;
|
||
if (direction_ != Direction::Incoming || state_ != CallState::Incoming) return a;
|
||
MediaLeg leg = ParseAnswer();
|
||
imsd::sdp::AnswerSpec spec;
|
||
spec.local = ctx_.local;
|
||
spec.rtpPort = rtpPort_;
|
||
spec.sessionId = rng_.UInt(1000000, 9999999);
|
||
spec.payloadType = leg.payloadType;
|
||
spec.octetAlign = leg.octetAlign;
|
||
spec.codec = leg.codec;
|
||
spec.dtmfPt = leg.dtmfPt;
|
||
localSdp_ = imsd::sdp::BuildAnswer(spec);
|
||
// session timers: echo the caller's Session-Expires; with no
|
||
// refresher stated, make the caller (uac) the refresher — its
|
||
// re-INVITE/UPDATE refreshes get 200d by OnRequest.
|
||
std::vector<std::string> extra;
|
||
if (auto se = imsd::sip::Header(invite_, "Session-Expires")) {
|
||
std::string v(*se);
|
||
if (!v.contains("refresher=")) v += ";refresher=uac";
|
||
extra.push_back(std::format("Session-Expires: {}", v));
|
||
extra.push_back("Require: timer");
|
||
}
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 200, "OK", d_.itag, localSdp_, extra)));
|
||
a.push_back(StartMediaAct(leg));
|
||
state_ = CallState::Active;
|
||
a.push_back(StateAct("accepted"));
|
||
return a;
|
||
}
|
||
|
||
// A response to our INVITE (the shell already matched Call-ID + CSeq).
|
||
std::vector<Action> OnInviteResponse(std::string_view msg) {
|
||
std::vector<Action> a;
|
||
if (direction_ == Direction::Incoming)
|
||
return a; // a UAS has no INVITE transaction of its own
|
||
AbsorbDialog(msg);
|
||
auto st = imsd::sip::Status(msg);
|
||
if (!st) return a;
|
||
answered_ = true;
|
||
int code = *st;
|
||
if (code > 100 && code < 200) {
|
||
if (state_ == CallState::Dialing) {
|
||
state_ = CallState::Ringing;
|
||
a.push_back(StateAct("outgoing"));
|
||
}
|
||
auto rseq = imsd::sip::Header(msg, "RSeq");
|
||
std::string require = std::string(imsd::sip::Header(msg, "Require").value_or(""));
|
||
if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) {
|
||
pracked_.insert(std::string(*rseq));
|
||
std::array<std::string, 1> extra = {
|
||
std::format("RAck: {} 1 INVITE", *rseq)};
|
||
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra)));
|
||
nextCseq_++;
|
||
}
|
||
return a;
|
||
}
|
||
if (code < 200)
|
||
return a; // 1xx other than 100<code<200 (only 100): nothing
|
||
if (code == 200) {
|
||
a.push_back(Send(imsd::msg::BuildAck2xx(ctx_, d_, rng_.Token(20), std::string(imsd::sip::Header(msg, "To").value_or("")))));
|
||
// A 2xx retransmission (RFC 3261 13.3.1.4: the UAS repeats
|
||
// it until our ACK arrives) is ACKed again and nothing else —
|
||
// media is already running, or the call is already over.
|
||
if (state_ != CallState::Ringing && state_ != CallState::Dialing) return a;
|
||
if (cancelled_ && userCancelled_) {
|
||
// answered in the user's CANCEL race — we no longer want it
|
||
nextCseq_++;
|
||
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "BYE", nextCseq_, rng_.Token(20))));
|
||
Append(a, Finish("local-hangup", "answered during our CANCEL; BYE sent"));
|
||
return a;
|
||
}
|
||
// An answer racing a DEADLINE-initiated CANCEL is still
|
||
// wanted — the user never hung up. Matters most when the sos
|
||
// attempt is answered at the wire just as the timeout fires:
|
||
// BYEing an answering PSAP is the worst possible outcome.
|
||
MediaLeg leg = ParseAnswer();
|
||
a.push_back(StartMediaAct(leg));
|
||
state_ = CallState::Active;
|
||
a.push_back(StateAct("accepted"));
|
||
return a;
|
||
}
|
||
// non-2xx final
|
||
a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or("")))));
|
||
std::string fin = WithReason(std::format("INVITE final {}", code), msg);
|
||
if (auto sos = FallbackTo(code, msg)) {
|
||
Append(a, Retry(*sos, fin));
|
||
return a;
|
||
}
|
||
if (cancelled_ || code == 487) Append(a, Finish("local-hangup", fin));
|
||
else if (code == 486 || code == 480 || code == 603) Append(a, Finish("refused-or-busy", fin));
|
||
else
|
||
Append(a, Finish("error", fin));
|
||
return a;
|
||
}
|
||
|
||
// An in-dialog request from the network (the shell matched Call-ID).
|
||
std::vector<Action> OnRequest(std::string_view msg) {
|
||
std::vector<Action> a;
|
||
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 = imsd::sip::Body(msg);
|
||
if (body.contains("m=audio")) answerSdp_ = std::string(body);
|
||
if (direction_ == Direction::Incoming && state_ == CallState::Incoming) {
|
||
if (method == "CANCEL") {
|
||
// the caller gave up: 200 the CANCEL transaction, 487 the
|
||
// INVITE transaction (RFC 3261 9.2), done.
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg)));
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 487, "Request Terminated", d_.itag)));
|
||
Append(a, Finish("remote-hangup", WithReason("CANCEL before answer", msg)));
|
||
} else if (method == "INVITE") {
|
||
// retransmitted INVITE (our provisional got lost): repeat it
|
||
a.push_back(Respond(last180_));
|
||
} else {
|
||
// PRACK of our reliable 180, or anything else: 200 echo
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg)));
|
||
}
|
||
return a;
|
||
}
|
||
if (method == "UPDATE" || method == "INVITE") {
|
||
std::optional<std::string> ans;
|
||
if (direction_ == Direction::Incoming) {
|
||
// session-refresh: re-state the answer we gave if the
|
||
// refresh carries an offer; a bodyless refresh gets a
|
||
// bodyless 200 (RFC 3311/4028)
|
||
if (body.contains("m=audio")) ans = localSdp_;
|
||
} else {
|
||
imsd::sdp::Offer offer;
|
||
offer.local = ctx_.local;
|
||
offer.rtpPort = rtpPort_;
|
||
offer.sessionId = rng_.UInt(1000000, 9999999);
|
||
offer.precond = precond_;
|
||
offer.currRemote = "sendrecv";
|
||
offer.codecs = codecs_;
|
||
ans = imsd::sdp::BuildOffer(offer);
|
||
}
|
||
// RFC 4028 §9: a 2xx to a refresh MUST echo Session-Expires,
|
||
// or the refresher treats the session as unrefreshed. KPN's
|
||
// B2BUA audits ~55 s into every call with such an UPDATE and
|
||
// releases ("PT: Session timer expired") on a bare 200.
|
||
std::vector<std::string> extra;
|
||
if (auto se = imsd::sip::Header(msg, "Session-Expires")) {
|
||
std::string v(*se);
|
||
if (!v.contains("refresher=")) v += ";refresher=uac";
|
||
extra.push_back(std::format("Session-Expires: {}", v));
|
||
extra.push_back("Require: timer");
|
||
}
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg, ans ? std::optional<std::string_view>(*ans) : std::nullopt, extra)));
|
||
} else if (method == "BYE") {
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg)));
|
||
Append(a, Finish("remote-hangup", WithReason("remote BYE", msg)));
|
||
} else if (method == "CANCEL") {
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg)));
|
||
Append(a, Finish("remote-hangup", WithReason("remote CANCEL", msg)));
|
||
} else {
|
||
a.push_back(Respond(imsd::msg::BuildResponse200(ctx_, msg)));
|
||
}
|
||
return a;
|
||
}
|
||
|
||
std::vector<Action> OnHangup() {
|
||
std::vector<Action> a;
|
||
if (direction_ == Direction::Incoming && state_ == CallState::Incoming) {
|
||
// reject the unanswered call
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 486, "Busy Here", d_.itag)));
|
||
Append(a, Finish("local-hangup", "rejected (486 sent)"));
|
||
return a;
|
||
}
|
||
if (state_ == CallState::Active) {
|
||
nextCseq_++;
|
||
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "BYE", nextCseq_, rng_.Token(20))));
|
||
Append(a, Finish("local-hangup", "HangUp; BYE sent"));
|
||
} else if (state_ == CallState::Dialing || state_ == CallState::Ringing) {
|
||
// even when a deadline already CANCELled: the user's intent
|
||
// also kills the emergency fallback chain
|
||
userCancelled_ = true;
|
||
if (!cancelled_) {
|
||
a.push_back(Send(imsd::msg::BuildCancel(ctx_, d_)));
|
||
cancelled_ = true;
|
||
a.push_back(Deadline(Cancel487Timeout));
|
||
}
|
||
}
|
||
return a;
|
||
}
|
||
|
||
// The user pressed keys: the tones go to the media leg as RFC 4733
|
||
// events on an active call whose SDP negotiated telephone-event at
|
||
// the codec's clock; otherwise they are dropped with a line that
|
||
// says why — there is no second method (no SIP INFO).
|
||
// Upper and lower case letters are one event; anything but 0-9, *,
|
||
// # and A-D drops the whole string rather than sending part of
|
||
// what was pressed, and so does a string past DtmfMaxTones — a
|
||
// keypad sends one key, a dialer's string a short sequence; the
|
||
// bound keeps the leg's control line within one atomic pipe write
|
||
// (PIPE_BUF), so a line is sent whole or not at all.
|
||
std::vector<Action> OnDtmf(std::string_view tones) {
|
||
std::vector<Action> a;
|
||
if (tones.size() > DtmfMaxTones) {
|
||
a.push_back(LogAct(std::format("call {}: DTMF of {} tones dropped: more than {}", uni_, tones.size(), DtmfMaxTones)));
|
||
return a;
|
||
}
|
||
std::string sent;
|
||
for (char c : tones) {
|
||
const char u = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
||
if (!((u >= '0' && u <= '9') || u == '*' || u == '#' || (u >= 'A' && u <= 'D'))) {
|
||
a.push_back(LogAct(std::format("call {}: DTMF '{}' dropped: '{}' is not a tone", uni_, tones, c)));
|
||
return a;
|
||
}
|
||
sent += u;
|
||
}
|
||
if (sent.empty()) return a;
|
||
if (state_ != CallState::Active) {
|
||
a.push_back(LogAct(std::format("call {}: DTMF '{}' dropped: the call is {}", uni_, sent, engine::StateStr(state_))));
|
||
return a;
|
||
}
|
||
if (!dtmfPt_) {
|
||
a.push_back(LogAct(std::format("call {}: DTMF '{}' dropped: no telephone-event negotiated for this call", uni_, sent)));
|
||
return a;
|
||
}
|
||
a.push_back(LogAct(std::format("call {}: DTMF '{}' -> media leg (telephone-event pt {})", uni_, sent, *dtmfPt_)));
|
||
a.push_back(Action{Action::Type::SendDtmf, sent});
|
||
return a;
|
||
}
|
||
|
||
// The shell is abandoning this machine (an emergency dial preempts
|
||
// it while it waits on a CANCEL's 487): terminate bookkeeping only —
|
||
// the CANCEL already sent stands, and the late final for this
|
||
// Call-ID is ignored by dispatch.
|
||
std::vector<Action> Abandon(std::string_view detail) {
|
||
return Finish("local-hangup", detail);
|
||
}
|
||
|
||
// The media subprocess exited. code 3 = the downlink RTP dried up
|
||
// (far-end hangup); anything else = the leg died. Either way, if the
|
||
// call was up we release it network-side and tear down.
|
||
std::vector<Action> OnMediaExit(int code) {
|
||
std::vector<Action> a;
|
||
if (state_ != CallState::Active) return a;
|
||
nextCseq_++;
|
||
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "BYE", nextCseq_, rng_.Token(20))));
|
||
Append(a, Finish("remote-hangup", code == 3 ? "far-end hangup (downlink RTP stopped); BYE sent" : std::format("media leg died (code {}); BYE sent", code)));
|
||
return a;
|
||
}
|
||
|
||
// A setup deadline fired (never armed once Active).
|
||
std::vector<Action> OnDeadline() {
|
||
std::vector<Action> a;
|
||
if (state_ == CallState::Active) return a;
|
||
if (direction_ == Direction::Incoming) {
|
||
if (state_ == CallState::Incoming) {
|
||
// rang unanswered past the safety net; the missed call
|
||
// reads as remote-hangup, like a network CANCEL would
|
||
a.push_back(Respond(imsd::msg::BuildInviteResponse(ctx_, invite_, 480, "Temporarily Unavailable", d_.itag)));
|
||
Append(a, Finish("remote-hangup", "rang unanswered past the deadline (480 sent)"));
|
||
}
|
||
return a;
|
||
}
|
||
if (!cancelled_ && (state_ == CallState::Dialing || state_ == CallState::Ringing)) {
|
||
a.push_back(Send(imsd::msg::BuildCancel(ctx_, d_)));
|
||
cancelled_ = true;
|
||
a.push_back(Deadline(Cancel487Timeout));
|
||
} else if (auto sos = FallbackTo(0, {})) {
|
||
// the 487 never came; an abandoned sos attempt still gets
|
||
// its digits fallback rather than dying silently
|
||
Append(a, Retry(*sos, "no final after CANCEL"));
|
||
} else {
|
||
Append(a, Finish("error", "setup deadline expired"));
|
||
}
|
||
return a;
|
||
}
|
||
|
||
// The shell couldn't send (socket error) — collapse the call.
|
||
std::vector<Action> Fail(std::string_view reason) {
|
||
std::vector<Action> a;
|
||
Append(a, Finish(reason, "client-flow send failed"));
|
||
return a;
|
||
}
|
||
|
||
private:
|
||
const imsd::msg::Context& ctx_;
|
||
imsd::util::Rng& rng_;
|
||
std::string uni_, number_;
|
||
int rtpPort_;
|
||
bool precond_;
|
||
std::vector<std::string> codecs_; // CODECS override; empty = defaults
|
||
Direction direction_ = Direction::Outgoing;
|
||
CallState state_ = CallState::Dialing;
|
||
std::string reason_ = "outgoing";
|
||
std::string invite_; // incoming only: the inbound INVITE verbatim
|
||
std::string last180_; // incoming only: our provisional, for retransmits
|
||
std::string localSdp_; // incoming only: the SDP answer we sent
|
||
imsd::msg::Dialog d_;
|
||
int nextCseq_ = 2;
|
||
bool cancelled_ = false;
|
||
// The emergency attempt chain (outgoing only). attemptSos_ is what
|
||
// the CURRENT attempt targets; the tried flags bound the chain to
|
||
// one step in each direction, never a loop.
|
||
bool attemptSos_ = false;
|
||
bool sosTried_ = false;
|
||
bool plainTried_ = false;
|
||
bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline
|
||
// The current outgoing attempt's INVITE as sent, whether any response
|
||
// to it has come, and whether it went out a second time over a
|
||
// reopened flow (OnFlowReopened).
|
||
std::string inviteOut_;
|
||
bool answered_ = false;
|
||
bool resent_ = false;
|
||
std::set<std::string> pracked_;
|
||
std::string answerSdp_;
|
||
std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start
|
||
|
||
// Fresh dialog identity for the current attempt. A fallback INVITE
|
||
// after a final response is a new transaction AND a clean new dialog
|
||
// attempt (fresh Call-ID) — the shell's dispatch then ignores late
|
||
// responses to the abandoned attempt by Call-ID mismatch.
|
||
void ResetDialog() {
|
||
d_ = {};
|
||
d_.ruri = attemptSos_ ? std::string(imsd::msg::SosUrn)
|
||
: imsd::msg::RuriFor(number_, ctx_.id.domain);
|
||
d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local);
|
||
d_.itag = rng_.Token(10);
|
||
d_.invBranch = rng_.Token(20);
|
||
nextCseq_ = 2;
|
||
pracked_.clear();
|
||
answerSdp_.clear();
|
||
cancelled_ = false;
|
||
userCancelled_ = false;
|
||
answered_ = false;
|
||
resent_ = false;
|
||
}
|
||
|
||
// The emergency fallback chain — where the next attempt (if any)
|
||
// points. `msg` may be empty (deadline paths).
|
||
// - a sos INVITE that fails for any reason other than the user
|
||
// hanging up, its own send failing at the Dial (Fail) or the
|
||
// client flow lost under it (OnFlowLost: there is nothing to send
|
||
// on) is re-attempted as a plain INVITE of the dialled digits: the
|
||
// pre-emergency-support behavior, so classification can only improve
|
||
// on the status quo, never block a call the old code would have placed.
|
||
// - a plain INVITE answered 380 Alternative Service whose body
|
||
// names emergency (TS 24.229 5.1.6: the network classified a
|
||
// number we didn't) is re-attempted as urn:service:sos. A 380
|
||
// without that indication terminates as an error: promoting an
|
||
// arbitrary redirect would put a non-emergency call through to a
|
||
// PSAP.
|
||
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_ && imsd::sip::Body(msg).contains("emergency")) return true;
|
||
return std::nullopt;
|
||
}
|
||
|
||
// Switch the attempt and send its INVITE. Same uni: the dialer keeps
|
||
// seeing one continuous call, back in "dialing".
|
||
std::vector<Action> Retry(bool sos, std::string_view why) {
|
||
attemptSos_ = sos;
|
||
ResetDialog();
|
||
state_ = CallState::Dialing;
|
||
std::vector<Action> a;
|
||
a.push_back(LogAct(std::format("call {}: {} — retrying as {}", uni_, why, sos ? "emergency (urn:service:sos)" : "plain INVITE of the digits")));
|
||
a.push_back(StateAct("outgoing"));
|
||
Append(a, Start());
|
||
return a;
|
||
}
|
||
|
||
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);
|
||
}
|
||
static std::optional<std::string> AngleUri(std::string_view v) {
|
||
std::size_t lt = v.find('<');
|
||
if (lt == std::string_view::npos) return std::string(v);
|
||
std::size_t gt = v.find('>', lt);
|
||
if (gt == std::string_view::npos) return std::string(v);
|
||
return std::string(v.substr(lt + 1, gt - lt - 1));
|
||
}
|
||
|
||
// Fold a response's dialog-establishing headers into the dialog.
|
||
void AbsorbDialog(std::string_view msg) {
|
||
if (auto to = imsd::sip::Header(msg, "To"))
|
||
if (to->contains("tag=")) d_.dialogTo = std::string(*to);
|
||
auto rr = imsd::sip::Headers(msg, "Record-Route");
|
||
if (!rr.empty()) {
|
||
d_.recordRoute.clear();
|
||
for (auto v : rr)
|
||
d_.recordRoute.emplace_back(v);
|
||
}
|
||
if (auto ct = imsd::sip::Header(msg, "Contact")) d_.remoteTarget = AngleUri(*ct);
|
||
std::string_view body = imsd::sip::Body(msg);
|
||
if (body.contains("m=audio")) answerSdp_ = std::string(body);
|
||
}
|
||
|
||
MediaLeg ParseAnswer() const {
|
||
imsd::sdp::Answer ans = imsd::sdp::ParseAnswer(answerSdp_, codecs_);
|
||
MediaLeg leg;
|
||
leg.remoteIp = ans.ip;
|
||
leg.remotePort = ans.port < 0 ? 0 : ans.port;
|
||
leg.payloadType = ans.payloadType;
|
||
leg.octetAlign = ans.octetAlign;
|
||
leg.codec = ans.codec;
|
||
leg.dtmfPt = ans.dtmfPt;
|
||
// the second number the leg takes events at: our offer's on a call
|
||
// we placed — the answer's instead when the answer gave the audio
|
||
// that very number, which is then the leg's audio number
|
||
const int offered = imsd::sdp::OfferedTelephoneEventPt(imsd::sdp::CodecRate(leg.codec));
|
||
leg.dtmfRxPt = !leg.dtmfPt ? std::nullopt
|
||
: std::optional<int>(direction_ == Direction::Outgoing && offered != leg.payloadType ? offered : *leg.dtmfPt);
|
||
return leg;
|
||
}
|
||
|
||
// Terminate: state change, media teardown, deletion — in that order,
|
||
// so the UI leaves the call page before the (slow) media teardown.
|
||
// One journald line per teardown — who ended the call and why
|
||
// (the s59 60-second-drop hunt ran blind for lack of exactly
|
||
// this; the network's Reason header named the cause all along).
|
||
// `detail` carries the SIP-level cause when the caller knows it.
|
||
std::vector<Action> Finish(std::string_view reason, std::string_view detail = "") {
|
||
state_ = CallState::Terminated;
|
||
reason_ = std::string(reason);
|
||
std::vector<Action> a;
|
||
a.push_back(LogAct(detail.empty() ? std::format("call {} ended: {}", uni_, reason) : std::format("call {} ended: {} — {}", uni_, reason, detail)));
|
||
a.push_back(StateAct(reason));
|
||
a.push_back(Action{Action::Type::StopMedia});
|
||
a.push_back(Action{Action::Type::Deleted});
|
||
return a;
|
||
}
|
||
|
||
// "remote BYE, Reason: SIP;cause=503;text=..." — the peer's own
|
||
// stated cause, when it sent one.
|
||
static std::string WithReason(std::string_view what, std::string_view msg) {
|
||
auto r = imsd::sip::Header(msg, "Reason");
|
||
return r ? std::format("{}, Reason: {}", what, *r) : std::string(what);
|
||
}
|
||
|
||
Action Send(std::string text) {
|
||
return Action{Action::Type::SendClient, std::move(text)};
|
||
}
|
||
Action Respond(std::string text) {
|
||
return Action{Action::Type::SendResponse, std::move(text)};
|
||
}
|
||
Action StateAct(std::string_view reason) {
|
||
reason_ = std::string(reason);
|
||
Action a{Action::Type::State};
|
||
a.state = std::string(engine::StateStr(state_));
|
||
a.reason = reason_;
|
||
return a;
|
||
}
|
||
Action StartMediaAct(const MediaLeg& leg) {
|
||
dtmfPt_ = leg.dtmfPt;
|
||
Action a{Action::Type::StartMedia};
|
||
a.media = leg;
|
||
return a;
|
||
}
|
||
Action Deadline(double s) {
|
||
Action a{Action::Type::SetDeadline};
|
||
a.seconds = s;
|
||
return a;
|
||
}
|
||
Action LogAct(std::string text) {
|
||
return Action{Action::Type::Log, std::move(text)};
|
||
}
|
||
static void Append(std::vector<Action>& into, std::vector<Action> more) {
|
||
for (auto& m : more)
|
||
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 (the shell hands it to StatusReportBook)
|
||
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;
|
||
};
|
||
|
||
// Whether a status report's TP-Recipient-Address names the number a
|
||
// message was sent to. A status report may give a number dialled
|
||
// nationally in its international form (0612… as 31612…), so
|
||
// the digits are compared after a trunk 0: equal, or the shorter — at
|
||
// least seven digits, a short code must be equal — the longer's suffix.
|
||
// With the TP-MR that is match enough; separators and a '+' are ignored.
|
||
bool SameRecipient(std::string_view dialled, std::string_view reported) {
|
||
auto digits = [](std::string_view v) {
|
||
std::string d;
|
||
for (char c : v) if (std::isdigit(static_cast<unsigned char>(c))) d.push_back(c);
|
||
if (d.starts_with('0')) d.erase(0, 1);
|
||
return d;
|
||
};
|
||
const std::string a = digits(dialled), b = digits(reported);
|
||
if (a.empty() || b.empty()) return false;
|
||
if (a == b) return true;
|
||
const std::string& shorter = a.size() < b.size() ? a : b;
|
||
const std::string& longer = a.size() < b.size() ? b : a;
|
||
return shorter.size() >= 7 && longer.ends_with(shorter);
|
||
}
|
||
|
||
// The messages that asked for a status report, by the TP-MR of each
|
||
// segment (TS 23.040 9.2.3.6: a report names one SMS-SUBMIT). A message
|
||
// gets a word for the whole, by TP-ST as StatusAsRead gives it (a
|
||
// reserved value is a failure): Failed at the first report in which the
|
||
// service centre has stopped trying (0x40 and up; the message is
|
||
// forgotten), Delivered when the last of its segments is (below 0x20),
|
||
// Pending while the service centre is still trying one (0x20–0x3F); a
|
||
// segment delivered with others outstanding is SegmentDelivered, for
|
||
// the log. A report that names no
|
||
// message — an unknown TP-MR, or another recipient (SameRecipient) — is
|
||
// NoMessage. A TP-MR reused before its word came (256 segments later)
|
||
// forgets the older message whole.
|
||
class StatusReportBook {
|
||
public:
|
||
enum class Word { NoMessage, SegmentDelivered, Delivered, Pending, Failed };
|
||
struct Outcome { Word word = Word::NoMessage; std::string id; std::size_t outstanding = 0; };
|
||
|
||
void Sent(std::string_view id, std::string_view destination, std::span<const std::uint8_t> tpMrs) {
|
||
if (tpMrs.empty()) return;
|
||
for (std::uint8_t mr : tpMrs) Forget(mr);
|
||
auto m = std::make_shared<Message>();
|
||
m->id = id; m->destination = destination;
|
||
for (std::uint8_t mr : tpMrs) { m->outstanding.insert(mr); byMr_[mr] = m; }
|
||
}
|
||
Outcome Report(std::uint8_t mr, std::string_view recipient, std::uint8_t status) {
|
||
auto it = byMr_.find(mr);
|
||
if (it == byMr_.end() || !SameRecipient(it->second->destination, recipient)) return {};
|
||
auto m = it->second;
|
||
const std::uint8_t st = imsd::sms::StatusAsRead(status);
|
||
if (st >= 0x20 && st < 0x40) return {Word::Pending, m->id, m->outstanding.size()};
|
||
if (st >= 0x40) { Forget(mr); return {Word::Failed, m->id, 0}; }
|
||
m->outstanding.erase(mr);
|
||
byMr_.erase(it);
|
||
return {m->outstanding.empty() ? Word::Delivered : Word::SegmentDelivered, m->id, m->outstanding.size()};
|
||
}
|
||
std::size_t Size() const { return byMr_.size(); }
|
||
|
||
// the message `id`, every TP-MR of it: its submission failed, so a
|
||
// report on a part that went says nothing about the message
|
||
void ForgetMessage(std::string_view id) {
|
||
for (const auto& [mr, m] : byMr_)
|
||
if (m->id == id) { Forget(mr); return; }
|
||
}
|
||
|
||
private:
|
||
struct Message { std::string id, destination; std::set<std::uint8_t> outstanding; };
|
||
// the message holding this TP-MR, every TP-MR of it
|
||
void Forget(std::uint8_t mr) {
|
||
auto it = byMr_.find(mr);
|
||
if (it == byMr_.end()) return;
|
||
auto m = it->second;
|
||
for (std::uint8_t x : m->outstanding) byMr_.erase(x);
|
||
m->outstanding.clear();
|
||
}
|
||
std::map<std::uint8_t, std::shared_ptr<Message>> byMr_;
|
||
};
|
||
|
||
// The Call-IDs an In-Reply-To lists (RFC 3261 20.21: a callid, then
|
||
// more after commas), each without the white space around it.
|
||
std::vector<std::string_view> InReplyToCallIds(std::string_view inReplyTo) {
|
||
std::vector<std::string_view> ids;
|
||
for (auto part : std::views::split(inReplyTo, ','))
|
||
ids.push_back(imsd::sip::Trim(std::string_view(part.begin(), part.end())));
|
||
return ids;
|
||
}
|
||
|
||
// An RP-ERROR's refusal in words: its RP cause and, when its submit
|
||
// report carries one, the TP-FCS.
|
||
std::string RpErrorWords(const imsd::sms::Rp& rp) {
|
||
std::string words = std::format("RP cause {} ({})", 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)
|
||
words += std::format(", TP-FCS 0x{:02x} ({})", *r->failureCause, imsd::sms::FailureCauseText(*r->failureCause));
|
||
return words;
|
||
}
|
||
|
||
// The MESSAGEs our submissions went out in, by Call-ID. TS 24.341
|
||
// 5.3.1.2 has a submit report answered 200 when its In-Reply-To
|
||
// "indicates that the request corresponds to a short message submitted
|
||
// by the SM-over-IP sender" and 488 when it does not, and its NOTE 3
|
||
// has the sender store the Call-ID for that. The message in flight
|
||
// knows the MESSAGEs of its segment in flight (SmsOutbound); this table
|
||
// keeps every one for an hour after it went out, so a report that comes
|
||
// once its message has ended — its waits run out, say — or once its
|
||
// segment was followed by the next is still known for ours: answered 200 and logged with
|
||
// the message's id. Nothing else follows from it: a message that has
|
||
// ended has had its word on the bus, and `failed` is its last (§8.4);
|
||
// one whose next segment is in flight goes on as it was. The table is
|
||
// this run's.
|
||
class RecentSubmissions {
|
||
public:
|
||
static constexpr double Keep = 3600.0;
|
||
struct Entry { std::string id; std::size_t segment = 0, segments = 0; double at = 0; };
|
||
|
||
// the MESSAGE `callid` carried segment `segment` of `segments` of the message `id`
|
||
void Sent(std::string_view callid, std::string_view id, std::size_t segment, std::size_t segments, double now) {
|
||
Purge(now);
|
||
byCallId_[std::string(callid)] = Entry{std::string(id), segment, segments, now};
|
||
}
|
||
// The MESSAGE of ours an In-Reply-To names — of the Call-IDs it lists, the first on record.
|
||
std::optional<Entry> Named(std::string_view inReplyTo, double now) {
|
||
Purge(now);
|
||
for (std::string_view callid : InReplyToCallIds(inReplyTo))
|
||
if (auto it = byCallId_.find(callid); it != byCallId_.end()) return it->second;
|
||
return std::nullopt;
|
||
}
|
||
std::size_t Size() const { return byCallId_.size(); }
|
||
|
||
private:
|
||
void Purge(double now) {
|
||
std::erase_if(byCallId_, [&](const auto& e) { return now - e.second.at > Keep; });
|
||
}
|
||
std::map<std::string, Entry, std::less<>> byCallId_;
|
||
};
|
||
|
||
// The waits. TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP sender's TR1M
|
||
// set to a value greater than SIP timer F, and TS 24.229 table 7.7.1
|
||
// recommends a UE on a 3GPP access a T1 of 2 s and a timer F of 64*T1.
|
||
// So: a MESSAGE's final within 128 s of the MESSAGE — or of its latest
|
||
// provisional, which starts the wait over here, as it did in 1.2.0;
|
||
// RFC 3261's timer F does not start over —; the submit report within
|
||
// 130 s of the final — past the 35 to 45 s TS 24.011 10.1 has for
|
||
// TR1M, as the NOTE asks, and from the final, where 6.3.1 sets TR1M
|
||
// when the RP-DATA is transferred.
|
||
inline constexpr double SmsSendTimeout = 128.0;
|
||
inline constexpr double SmsReportTimeout = 130.0;
|
||
// What the bus hears: `sent` once the service centre has accepted
|
||
// every segment, `failed` with the reason; a status report's word
|
||
// after `sent` (StatusReportBook, SmsWordOrder, which also has the one
|
||
// failure posted as `sent`).
|
||
inline constexpr std::string_view SmsStateSent = "sent";
|
||
inline constexpr std::string_view SmsStateFailed = "failed";
|
||
inline constexpr std::string_view SmsStateDelivered = "delivered";
|
||
inline constexpr std::string_view SmsStateDeliveryPending = "delivery-pending";
|
||
inline constexpr std::string_view SmsStateDeliveryFailed = "delivery-failed";
|
||
|
||
// The order of one message's words (§8.4): the submission's first —
|
||
// `sent`, or `failed`, after which nothing follows — and a status
|
||
// report's only after `sent`. The SC can deliver and report segment 1
|
||
// while segment 2 is still on its way, so a report's word on the message
|
||
// in flight is held until the submission ends (the latest word, one per
|
||
// message). A submission that fails after the SC reported every segment
|
||
// delivered — its last submit report lost or late — ends as `sent` and
|
||
// then `delivered`, not `failed`; one that fails otherwise drops the held
|
||
// word and has the message's TP-MRs forgotten (`forget`), so a later
|
||
// report on a part that went matches nothing. One message is in flight
|
||
// at a time (the shell's queue), so one held word suffices.
|
||
class SmsWordOrder {
|
||
public:
|
||
struct Word { std::string id, state, reason; };
|
||
struct Ended { std::vector<Word> post; bool forget = false; };
|
||
|
||
// a report's word on `id`: posted now, or held while `id`'s submission is in flight
|
||
std::vector<Word> Report(std::string_view id, std::string_view state, std::string_view reason, bool inFlight) {
|
||
Word w{std::string(id), std::string(state), std::string(reason)};
|
||
if (!inFlight) return {std::move(w)};
|
||
held_ = std::move(w);
|
||
return {};
|
||
}
|
||
|
||
// the submission's word on `id`: the words to post, in order, and whether its TP-MRs are to be forgotten
|
||
Ended Submission(std::string_view id, std::string_view state, std::string_view reason) {
|
||
Ended e;
|
||
std::optional<Word> held;
|
||
if (held_ && held_->id == id) held = std::exchange(held_, std::nullopt);
|
||
if (state == SmsStateFailed) {
|
||
if (held && held->state == SmsStateDelivered) {
|
||
e.post.push_back({std::string(id), std::string(SmsStateSent), std::format("every segment reported delivered by the SC; {}", reason)});
|
||
e.post.push_back(std::move(*held));
|
||
return e;
|
||
}
|
||
e.forget = true;
|
||
e.post.push_back({std::string(id), std::string(state), std::string(reason)});
|
||
return e;
|
||
}
|
||
e.post.push_back({std::string(id), std::string(state), std::string(reason)});
|
||
if (held) e.post.push_back(std::move(*held));
|
||
return e;
|
||
}
|
||
|
||
bool Holding() const { return held_.has_value(); }
|
||
|
||
private:
|
||
std::optional<Word> held_;
|
||
};
|
||
|
||
// A segment's MESSAGEs at most: the first and one repeat. TS 23.040
|
||
// 9.2.3.6 has the MS repeat an SMS-SUBMIT that got no answer "in the
|
||
// range 1 to 3" times and leaves the number to the implementation.
|
||
inline constexpr std::size_t SmsAttempts = 2;
|
||
|
||
// 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).
|
||
//
|
||
// A segment that gets no answer, or an RP-ERROR with cause 41, is sent
|
||
// once more, as 9.2.3.6 has it: "In the case where no response or an
|
||
// RP-ERROR with an appropriate cause value (see 3GPP TS 24.011 [13]) is
|
||
// received in response to an SMS-SUBMIT, then the MS shall automatically
|
||
// repeat the SMS-SUBMIT but must use the same TP-MR value and set the
|
||
// TP-RD bit to 1". Here that is: the final's wait or the report's run
|
||
// out; a final of 408 or 504 — no response in time, the server's own
|
||
// (RFC 3261 21.4.9) or one it waited for (21.5.5), so what became of
|
||
// the MESSAGE past it is as unknown as with no final; an RP-ERROR whose
|
||
// cause invites another attempt at once (RpCauseIsTemporary). The
|
||
// repeat is a MESSAGE of its own — its Call-ID, the next RP-MR — with
|
||
// the same SMS-SUBMIT, TP-RD set. A service centre that has the first
|
||
// "should discard" the repeat and answer it with an RP-ERROR whose
|
||
// TP-FCS is the duplicate rejection (0xC5), or with an RP-ACK (9.2.3.6
|
||
// again): either ends the segment as accepted — the rejection only
|
||
// where no RP-ERROR has refused the first attempt by then — and so
|
||
// does the first attempt's own RP-ACK when it comes after the repeat
|
||
// went out; its RP-ERROR then leaves the segment to the repeat's
|
||
// answer, and one that comes once that answer has ended the segment
|
||
// changes nothing (OnSmsMessage logs it). Any
|
||
// other refusal — a final that is neither of the two, an RP-ERROR with
|
||
// another cause, a flow that is down — fails the message at once, and
|
||
// so does whatever ends the repeat short of an acceptance; the reason
|
||
// then names the first attempt's end as well. Not done of the clause's
|
||
// repeat: it cannot be switched off, and a failed message is not kept
|
||
// for the user to send again under its TP-MR.
|
||
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 };
|
||
|
||
// `submitted`: where each MESSAGE this message goes out in is put on record
|
||
SmsOutbound(const imsd::msg::Context& ctx, imsd::util::Rng& rng, RecentSubmissions& submitted, std::string id, Params p)
|
||
: ctx_(ctx), rng_(rng), submitted_(submitted), id_(std::move(id)), p_(std::move(p)), nextRpMr_(p_.rpMr) {}
|
||
|
||
const std::string& Id() const { return id_; }
|
||
// the MESSAGE in flight — the segment in flight's latest (empty before the first went out)
|
||
const std::string& CallId() const { return callid_; }
|
||
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(); }
|
||
// The RP-MR after the last this message used — every MESSAGE built
|
||
// for it took the next one from `rpMr` on, one the flow could not
|
||
// send as well: where the shell's counter goes on once the message
|
||
// has ended.
|
||
std::uint8_t NextRpMr() const { return nextRpMr_; }
|
||
|
||
// 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;
|
||
}
|
||
s.rejectDuplicates = true; // each segment's repeat: the same SMS-SUBMIT with TP-RD set
|
||
repeats_ = imsd::sms::BuildSubmits(s, p_.text, p_.concatRef);
|
||
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 MESSAGE in flight: its final is matched by Call-ID and CSeq.
|
||
// The first attempt's final, come after the repeat went out, is
|
||
// nobody's.
|
||
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) {
|
||
std::string why = std::format("segment {}/{} refused: {}", seg_ + 1, tpdus_.size(), imsd::sip::RefusalSummary(msg));
|
||
if (status == 408 || status == 504) { // Request Timeout, Server Time-out: no word on the MESSAGE's fate
|
||
EndAttempt(out, now, std::move(why));
|
||
return out;
|
||
}
|
||
phase_ = Phase::Done;
|
||
out.push_back(Fail(std::move(why)));
|
||
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;
|
||
}
|
||
|
||
// Which of the segment in flight's MESSAGEs an RP-ACK/RP-ERROR the
|
||
// IP-SM-GW sent answers — 0 the first, 1 its repeat — or none of
|
||
// them: by In-Reply-To when the report has one (TS 24.341 5.3.1.2;
|
||
// the later MESSAGE when it lists both), else — from an IP-SM-GW
|
||
// that sends none — by RP-MR. A report arriving before the
|
||
// MESSAGE's own final (the IP-SM-GW's order is its own) is taken as
|
||
// well.
|
||
std::optional<std::size_t> ReportAttempt(std::string_view inReplyTo, std::optional<std::uint8_t> rpMr) const {
|
||
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return std::nullopt;
|
||
const std::vector<std::string_view> named = InReplyToCallIds(inReplyTo); // a list of Call-IDs (RFC 3261 20.21): ours among them
|
||
for (std::size_t k = attempts_.size(); k-- > 0;) {
|
||
if (!inReplyTo.empty() ? std::ranges::contains(named, std::string_view(attempts_[k].callid)) : rpMr && *rpMr == attempts_[k].rpMr) return k;
|
||
}
|
||
return std::nullopt;
|
||
}
|
||
|
||
// The submit report for the segment in flight, answering its
|
||
// MESSAGE number `attempt` (ReportAttempt; none given: the one in
|
||
// flight). An RP-ACK to either attempt moves to the next segment,
|
||
// or ends the message as sent. An RP-ERROR to the first attempt,
|
||
// come after its repeat went out, changes what is known of that
|
||
// attempt and nothing else: the repeat's answer ends the segment.
|
||
// An RP-ERROR to the attempt in flight: the duplicate rejection
|
||
// (TP-FCS 0xC5) of a repeat whose first attempt no RP-ERROR has
|
||
// refused so far is taken for that attempt accepted, whatever RP
|
||
// cause comes with it — 9.2.3.6 has the service centre discard a
|
||
// repeat of what it has —; a cause that
|
||
// invites another attempt at once (RpCauseIsTemporary) ends the
|
||
// attempt — the repeat follows, or the message has failed —; any
|
||
// other fails the message with its cause. The shell answers the
|
||
// report's MESSAGE itself.
|
||
std::vector<SmsAction> OnReport(const imsd::sms::Rp& rp, double now, std::optional<std::size_t> attempt = std::nullopt) {
|
||
std::vector<SmsAction> out;
|
||
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return out;
|
||
const std::size_t inFlight = attempts_.size() - 1;
|
||
const std::size_t answered = std::min(attempt.value_or(inFlight), inFlight);
|
||
const bool late = answered < inFlight; // the first attempt's report, after the repeat went out
|
||
if (rp.type == imsd::sms::RpType::ErrorMt) {
|
||
std::string why = std::format("segment {}/{} refused by the SC: {}", seg_ + 1, tpdus_.size(), RpErrorWords(rp));
|
||
if (late) {
|
||
out.push_back(LogAct(std::format("sms {}: {}, in the first attempt's report, which came after the repeat went out: the repeat's decides", id_, why)));
|
||
firstRefused_ = true;
|
||
firstWhy_ = why + ", in a report that came after the repeat went out";
|
||
return out;
|
||
}
|
||
const auto report = imsd::sms::ParseSubmitReport(rp.tpdu, true);
|
||
if (answered > 0 && !firstRefused_ && report && report->failureCause == imsd::sms::FcsDuplicateRejected) {
|
||
out.push_back(LogAct(std::format("sms {}: segment {}/{}: the repeat was rejected as a duplicate ({}): the first attempt is taken for accepted", id_, seg_ + 1, tpdus_.size(), RpErrorWords(rp))));
|
||
Accepted(out, now);
|
||
return out;
|
||
}
|
||
if (imsd::sms::RpCauseIsTemporary(rp.cause.value_or(0))) {
|
||
firstRefused_ = true;
|
||
EndAttempt(out, now, std::move(why));
|
||
return out;
|
||
}
|
||
phase_ = Phase::Done;
|
||
out.push_back(Fail(std::move(why)));
|
||
return out;
|
||
}
|
||
if (rp.type != imsd::sms::RpType::AckMt) return out;
|
||
if (late) out.push_back(LogAct(std::format("sms {}: segment {}/{}: the first attempt's submit report came after the repeat went out: accepted", id_, seg_ + 1, tpdus_.size())));
|
||
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, false); r && !r->scts.empty()) scts_ = r->scts;
|
||
Accepted(out, now);
|
||
return out;
|
||
}
|
||
|
||
// The wait ran out: no final to the MESSAGE, or no submit report.
|
||
std::vector<SmsAction> OnDeadline(double now) {
|
||
std::vector<SmsAction> out;
|
||
if (phase_ == Phase::Sending) EndAttempt(out, now, std::format("no answer to the MESSAGE of segment {}/{} within {:.0f} s", seg_ + 1, tpdus_.size(), SmsSendTimeout));
|
||
else if (phase_ == Phase::AwaitingReport) EndAttempt(out, now, std::format("no submit report for segment {}/{} within {:.0f} s of the final", seg_ + 1, tpdus_.size(), SmsReportTimeout));
|
||
else 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;
|
||
out.push_back(Fail(std::format("segment {}/{} not sent: the flow to the P-CSCF is down", seg_ + 1, tpdus_.size())));
|
||
return out;
|
||
}
|
||
|
||
private:
|
||
// One MESSAGE the segment in flight went out in.
|
||
struct Attempt { std::string callid; std::uint8_t rpMr = 0; };
|
||
|
||
// The segment in flight as a MESSAGE: the first attempt with the
|
||
// SMS-SUBMIT as built, the repeat with TP-RD set in it, each under a
|
||
// Call-ID of its own and the next RP-MR, so a report without
|
||
// In-Reply-To still tells the two.
|
||
void SendSegment(std::vector<SmsAction>& out, double now) {
|
||
const bool repeat = !attempts_.empty();
|
||
const std::vector<std::uint8_t>& tpdu = repeat ? repeats_[seg_] : tpdus_[seg_];
|
||
callid_ = std::format("{}@{}", rng_.Token(16), ctx_.local);
|
||
attempts_.push_back({callid_, nextRpMr_++});
|
||
submitted_.Sent(callid_, id_, seg_ + 1, tpdus_.size(), now);
|
||
std::vector<std::uint8_t> rp = imsd::sms::BuildRpData(attempts_.back().rpMr, p_.scAddress, tpdu);
|
||
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, repeat ? " again" : "", attempts_.back().rpMr, tpMrs_[seg_], repeat ? " with TP-RD" : "", tpdu.size())));
|
||
phase_ = Phase::Sending;
|
||
deadline_ = now + SmsSendTimeout;
|
||
}
|
||
|
||
// The attempt in flight ended without the service centre's word, or
|
||
// with RP cause 41 or one read as it (RpCauseIsTemporary): the
|
||
// repeat when the segment has had none, else the message has failed.
|
||
void EndAttempt(std::vector<SmsAction>& out, double now, std::string why) {
|
||
if (attempts_.size() >= SmsAttempts) {
|
||
phase_ = Phase::Done;
|
||
out.push_back(Fail(std::move(why)));
|
||
return;
|
||
}
|
||
out.push_back(LogAct(std::format("sms {}: {}; sending the segment again, TP-RD set", id_, why)));
|
||
firstWhy_ = std::move(why);
|
||
SendSegment(out, now);
|
||
}
|
||
|
||
// The service centre has the segment in flight: the next one, or
|
||
// the message is sent.
|
||
void Accepted(std::vector<SmsAction>& out, double now) {
|
||
seg_++;
|
||
attempts_.clear();
|
||
firstRefused_ = false;
|
||
if (seg_ < tpdus_.size()) { SendSegment(out, now); return; }
|
||
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_)));
|
||
}
|
||
|
||
// `failed` with the reason; of a segment that was sent again, how
|
||
// the first attempt ended as well.
|
||
SmsAction Fail(std::string why) {
|
||
deadline_ = 0;
|
||
if (attempts_.size() > 1) why += std::format("; the first attempt: {}", firstWhy_);
|
||
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_;
|
||
RecentSubmissions& submitted_;
|
||
std::string id_;
|
||
Params p_;
|
||
std::uint8_t nextRpMr_; // the RP-MR the next MESSAGE takes
|
||
std::vector<std::vector<std::uint8_t>> tpdus_; // each segment's SMS-SUBMIT
|
||
std::vector<std::vector<std::uint8_t>> repeats_; // the same with TP-RD set, for a segment's repeat
|
||
std::vector<std::uint8_t> tpMrs_;
|
||
std::size_t seg_ = 0;
|
||
std::vector<Attempt> attempts_; // the MESSAGEs the segment in flight went out in: the first, then its repeat
|
||
std::string firstWhy_; // how the first attempt ended, once the segment was sent again
|
||
bool firstRefused_ = false; // an RP-ERROR has answered an attempt of the segment in flight: where a repeat's duplicate rejection reads it, the first
|
||
std::string callid_; // the MESSAGE in flight
|
||
std::string scts_; // the SC's time stamp from the last RP-ACK's submit report
|
||
Phase phase_ = Phase::Idle;
|
||
double deadline_ = 0;
|
||
};
|
||
|
||
// The ids of the Messaging interface (§8.4): the run's token — eight hex
|
||
// digits drawn once at the daemon's start — then a second, then a
|
||
// counter. The token is what tells one run's ids from another's: the
|
||
// wall clock reads 1970 until the first time sync, so a second alone
|
||
// repeats across runs, and a client that deleted the daemon's copy of a
|
||
// text freed its name.
|
||
std::string RunToken(std::uint32_t bits) { return std::format("{:08x}", bits); }
|
||
|
||
std::string SentSmsId(std::string_view run, std::int64_t start, std::uint64_t n) { return std::format("ims-sms-{}-{}-{}", run, start, n); }
|
||
|
||
std::string ReceivedSmsId(std::string_view run, std::int64_t at, std::uint64_t n) { return std::format("ims-sms-in-{}-{}-{}", run, at, n); }
|
||
|
||
// ---- the store of received messages (§7.9) ---------------------------
|
||
|
||
// A received message as the daemon keeps it until an app takes it
|
||
// (`List`/`Delete` on the Messaging interface, §8.4): its id, when it
|
||
// arrived (epoch seconds), the message, the subscriber it arrived
|
||
// for and the SIM's operator then. One record per file,
|
||
// key=value lines; the sender, the text, the data and the PDU as hex
|
||
// (a sender or a text may hold any character). Absent keys read as
|
||
// their defaults; a record without an id, or with a number or hex
|
||
// value that does not parse, is no record.
|
||
struct StoredSms {
|
||
std::string id;
|
||
std::int64_t receivedAt = 0;
|
||
SmsReceived sms;
|
||
std::string to; // the own number the daemon held at receipt (from a tel: P-Associated-URI); "" while it held none
|
||
std::string simOperator; // the SIM's operator id at receipt (MCC then MNC); "" when none was read
|
||
};
|
||
|
||
std::string FormatStoredSms(const StoredSms& r) {
|
||
auto hex = [](std::string_view s) { return imsd::util::ToHex(std::span<const std::uint8_t>(reinterpret_cast<const std::uint8_t*>(s.data()), s.size())); };
|
||
std::string out;
|
||
out += std::format("id={}\n", r.id);
|
||
out += std::format("received={}\n", r.receivedAt);
|
||
if (!r.to.empty()) out += std::format("to={}\n", r.to);
|
||
if (!r.simOperator.empty()) out += std::format("operator={}\n", r.simOperator);
|
||
out += std::format("from={}\n", hex(r.sms.from));
|
||
out += std::format("sc={}\n", r.sms.sc);
|
||
out += std::format("timestamp={}\n", r.sms.scts);
|
||
out += std::format("class={}\n", r.sms.msgClass.value_or(-1));
|
||
out += std::format("pid={}\n", r.sms.pid);
|
||
out += std::format("dcs={}\n", r.sms.dcs);
|
||
out += std::format("segments={}\n", r.sms.segments);
|
||
out += std::format("message-waiting={}\n", r.sms.messageWaiting ? 1 : 0);
|
||
if (r.sms.portDst) out += std::format("port-dst={}\n", *r.sms.portDst);
|
||
if (r.sms.portSrc) out += std::format("port-src={}\n", *r.sms.portSrc);
|
||
out += std::format("text={}\n", hex(r.sms.text));
|
||
out += std::format("data={}\n", imsd::util::ToHex(r.sms.data));
|
||
out += std::format("pdu={}\n", imsd::util::ToHex(r.sms.tpdu));
|
||
return out;
|
||
}
|
||
|
||
// The store's order, oldest first: by the arrival second, then — two
|
||
// texts of one run in one second share the id's prefix — by the sequence
|
||
// number, which the shorter id carries the smaller of (as text, -10
|
||
// would sort before -9).
|
||
bool StoredSmsBefore(const StoredSms& a, const StoredSms& b) {
|
||
if (a.receivedAt != b.receivedAt) return a.receivedAt < b.receivedAt;
|
||
if (a.id.size() != b.id.size()) return a.id.size() < b.id.size();
|
||
return a.id < b.id;
|
||
}
|
||
|
||
std::optional<StoredSms> ParseStoredSms(std::string_view text) {
|
||
StoredSms r;
|
||
bool ok = true;
|
||
auto bytesOf = [&](std::string_view v) -> std::vector<std::uint8_t> {
|
||
if (v.empty()) return {};
|
||
auto b = imsd::util::FromHex(v);
|
||
if (!b) { ok = false; return {}; }
|
||
return *b;
|
||
};
|
||
auto stringOf = [&](std::string_view v) { auto b = bytesOf(v); return std::string(b.begin(), b.end()); };
|
||
auto intOf = [&](std::string_view v) -> std::int64_t {
|
||
std::int64_t n = 0;
|
||
auto [p, ec] = std::from_chars(v.data(), v.data() + v.size(), n);
|
||
if (ec != std::errc() || p != v.data() + v.size()) ok = false;
|
||
return n;
|
||
};
|
||
for (std::size_t pos = 0; pos < text.size();) {
|
||
const std::size_t nl = text.find('\n', pos);
|
||
std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
|
||
pos = nl == std::string_view::npos ? text.size() : nl + 1;
|
||
const std::size_t eq = line.find('=');
|
||
if (eq == std::string_view::npos) continue;
|
||
std::string_view k = line.substr(0, eq);
|
||
std::string_view v = line.substr(eq + 1);
|
||
if (k == "id") r.id = std::string(v);
|
||
else if (k == "received") r.receivedAt = intOf(v);
|
||
else if (k == "to") r.to = std::string(v);
|
||
else if (k == "operator") r.simOperator = std::string(v);
|
||
else if (k == "from") r.sms.from = stringOf(v);
|
||
else if (k == "sc") r.sms.sc = std::string(v);
|
||
else if (k == "timestamp") r.sms.scts = std::string(v);
|
||
else if (k == "class") { const std::int64_t c = intOf(v); if (c >= 0) r.sms.msgClass = static_cast<int>(c); }
|
||
else if (k == "pid") r.sms.pid = static_cast<std::uint8_t>(intOf(v));
|
||
else if (k == "dcs") r.sms.dcs = static_cast<std::uint8_t>(intOf(v));
|
||
else if (k == "segments") r.sms.segments = static_cast<int>(intOf(v));
|
||
else if (k == "message-waiting") r.sms.messageWaiting = intOf(v) != 0;
|
||
else if (k == "port-dst") r.sms.portDst = static_cast<std::uint16_t>(intOf(v));
|
||
else if (k == "port-src") r.sms.portSrc = static_cast<std::uint16_t>(intOf(v));
|
||
else if (k == "text") r.sms.text = stringOf(v);
|
||
else if (k == "data") r.sms.data = bytesOf(v);
|
||
else if (k == "pdu") r.sms.tpdu = bytesOf(v);
|
||
}
|
||
if (!ok || r.id.empty()) return std::nullopt;
|
||
return r;
|
||
}
|
||
|
||
// ---- 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 — but one of class 2,
|
||
// which is for the (U)SIM, is refused with an RP-ERROR instead (cause
|
||
// 111, TP-FCS 0xFF) and goes no further, unless it is a short message
|
||
// type 0; 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 200 and logged when its
|
||
// In-Reply-To names a MESSAGE of ours on record (`submitted`), 488 when
|
||
// it names none, and 200 and logged when it has no In-Reply-To. 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). While SMS over IP is off (`ctx.smsOverIp`)
|
||
// every MESSAGE whose Content-Type contains the SMS one is refused
|
||
// with 480 Temporarily Unavailable instead, its body not parsed: a 200
|
||
// and an RP-ACK would count a short message delivered to nobody, a failure lets the IP-SM-GW try the
|
||
// modem's path (TS 24.341 5.3.3.4.2 NOTE 2) where the network gives the
|
||
// modem one.
|
||
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, RecentSubmissions& submitted, 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;
|
||
}
|
||
if (!ctx.smsOverIp) {
|
||
r.response = imsd::msg::BuildResponse(ctx, message, 480, "Temporarily Unavailable", toTag);
|
||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message over IP from {} ({} bytes) while SMS_OVER_IMS is off: 480", from, body.size())});
|
||
return r;
|
||
}
|
||
std::span<const std::uint8_t> bytes(reinterpret_cast<const std::uint8_t*>(body.data()), body.size());
|
||
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 (const auto attempt = outbound ? outbound->ReportAttempt(inReplyTo, rp.mr) : std::nullopt) {
|
||
r.actions = outbound->OnReport(rp, now, *attempt);
|
||
return r;
|
||
}
|
||
if (!inReplyTo.empty()) {
|
||
if (auto ours = submitted.Named(inReplyTo, now)) {
|
||
// a MESSAGE of ours that is no longer in flight: the 200 stands (TS 24.341 5.3.1.2), and the journal keeps what the report said
|
||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: sms {}'s segment {}/{}, no longer in flight; 200", rp.type == RpType::AckMt ? "RP-ACK" : std::format("RP-ERROR, {}", RpErrorWords(rp)), inReplyTo, ours->id, ours->segment, ours->segments)});
|
||
return r;
|
||
}
|
||
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 on record; 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 {}) that no message in flight owns; 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();
|
||
if (d->coding.msgClass == 2 && d->pid != imsd::sms::PidShortMessageType0) {
|
||
// Class 2 is (U)SIM-specific — a (U)SIM data download (TP-PID 0x7F, which TS
|
||
// 23.040 9.2.3.9 has the ME pass to the (U)SIM), or a message for the card's
|
||
// EF_SMS: TS 23.038 4 has the MS "ensure that the message has been transferred
|
||
// to the SMS data field in the (U)SIM before sending an acknowledgement" and
|
||
// return "protocol error, unspecified" when it "cannot be stored in the (U)SIM
|
||
// and there is other short message storage available" (the clause excepts a
|
||
// download for an MS supporting the (U)SIM Application Toolkit; imsd has none).
|
||
// imsd has no way to the card for either, so an RP-ERROR with that cause is its
|
||
// answer to both, each segment's on its own: not stored, not handed over — an
|
||
// RP-ACK would say the card has it. A short message type 0 is no part of this,
|
||
// whatever its class: 9.2.3.9 has it received "irrespective of whether there is
|
||
// memory available in the (U)SIM or ME or not", and it goes the way of any
|
||
// type 0 below (stored and handed over: AGENTS.md §7.9 has that departure).
|
||
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message from {} via {} at {}{}: class 2{} ({} bytes), which imsd cannot pass to the (U)SIM: refused", d->from.Number(), sc, d->scts, segment, d->pid == imsd::sms::PidSimDataDownload ? ", a (U)SIM data download" : "", rp.tpdu.size())});
|
||
report(imsd::sms::BuildRpError(rp.mr, imsd::sms::RpCauseProtocolError, imsd::sms::DeliverReportError(imsd::sms::FcsUnspecified)), "delivery report RP-ERROR");
|
||
return r;
|
||
}
|
||
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;
|
||
}
|
||
}
|