Compare commits

..
12 changed files with 198 additions and 2169 deletions

883
AGENTS.md

File diff suppressed because it is too large Load diff

View file

@ -44,7 +44,6 @@ its subscriber set on the main thread too.
#include <signal.h> #include <signal.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/timerfd.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
@ -56,7 +55,7 @@ import ImsdBus;
namespace { namespace {
// ---- static config (env-overridable, same knobs as imsd.py) --------------- // ---- static config (env-overridable, same knobs as imsd.py) ---------------
constexpr const char* Version = "1.2.7"; constexpr const char* Version = "1.2.4";
constexpr const char* BusName = "net.catcrafts.IMS1"; constexpr const char* BusName = "net.catcrafts.IMS1";
constexpr const char* ObjPath = "/net/catcrafts/IMS1"; constexpr const char* ObjPath = "/net/catcrafts/IMS1";
constexpr const char* Iface = "net.catcrafts.IMS1"; constexpr const char* Iface = "net.catcrafts.IMS1";
@ -435,30 +434,6 @@ int PortOf(const sockaddr_storage& ss) {
return ss.ss_family == AF_INET6 ? ntohs(reinterpret_cast<const sockaddr_in6*>(&ss)->sin6_port) : ntohs(reinterpret_cast<const sockaddr_in*>(&ss)->sin_port); return ss.ss_family == AF_INET6 ? ntohs(reinterpret_cast<const sockaddr_in6*>(&ss)->sin6_port) : ntohs(reinterpret_cast<const sockaddr_in*>(&ss)->sin_port);
} }
// The host a socket address names, as text.
std::string HostOf(const sockaddr_storage& ss) {
char buf[INET6_ADDRSTRLEN] = {};
if (ss.ss_family == AF_INET6) inet_ntop(AF_INET6, &reinterpret_cast<const sockaddr_in6*>(&ss)->sin6_addr, buf, sizeof buf);
else inet_ntop(AF_INET, &reinterpret_cast<const sockaddr_in*>(&ss)->sin_addr, buf, sizeof buf);
return buf;
}
// Whether two socket addresses name the same host and port: for IPv6 the
// scope too (a link-local address is a host of one link). One that names
// none is the same as nothing, another such one included.
bool SameEnd(const sockaddr_storage& a, const sockaddr_storage& b) {
if (a.ss_family == AF_UNSPEC || a.ss_family != b.ss_family || PortOf(a) != PortOf(b) || HostOf(a) != HostOf(b)) return false;
return a.ss_family != AF_INET6 ||
reinterpret_cast<const sockaddr_in6*>(&a)->sin6_scope_id == reinterpret_cast<const sockaddr_in6*>(&b)->sin6_scope_id;
}
// A socket's own name (getsockname); all zeros where that fails.
sockaddr_storage NameOf(int fd) {
sockaddr_storage ss{}; socklen_t l = sizeof ss;
if (getsockname(fd, reinterpret_cast<sockaddr*>(&ss), &l) != 0) ss = {};
return ss;
}
// ---- SIP over the protected TCP flow -------------------------------------- // ---- SIP over the protected TCP flow --------------------------------------
enum class Transport { Tcp, Udp }; enum class Transport { Tcp, Udp };
constexpr std::string_view TransportName(Transport t) { return t == Transport::Udp ? "UDP" : "TCP"; } constexpr std::string_view TransportName(Transport t) { return t == Transport::Udp ? "UDP" : "TCP"; }
@ -507,17 +482,11 @@ public:
// datagram socket to the same peer — the kernel then delivers that peer's // datagram socket to the same peer — the kernel then delivers that peer's
// datagrams here in preference to the unconnected ServerPorts socket on // datagrams here in preference to the unconnected ServerPorts socket on
// the same port. A UDP connect() cannot be refused by the peer, so it is // the same port. A UDP connect() cannot be refused by the peer, so it is
// one attempt. `tick` is called before every try and then before every // one attempt.
// second of a try's wait for its answer and of the pause before the bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0) {
// next try: what the caller must do at least that often while this
// thread waits (the wake alarm, under a registration step and under
// the connect for a call's resend).
bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0,
const std::function<void()>& tick = {}) {
transport_ = t; transport_ = t;
lastConnectLocal_ = false; lastConnectLocal_ = false;
int fam = Is6(local) ? AF_INET6 : AF_INET; int fam = Is6(local) ? AF_INET6 : AF_INET;
if (tick) tick();
if (t == Transport::Udp) { if (t == Transport::Udp) {
int fd = socket(fam, SOCK_DGRAM, 0); int fd = socket(fam, SOCK_DGRAM, 0);
if (fd < 0) return SocketFailed(); if (fd < 0) return SocketFailed();
@ -538,7 +507,6 @@ public:
} }
int silent = 0; int silent = 0;
for (int attempt = 0; attempt < tries; attempt++) { for (int attempt = 0; attempt < tries; attempt++) {
if (tick && attempt > 0) tick();
int fd = socket(fam, SOCK_STREAM, 0); int fd = socket(fam, SOCK_STREAM, 0);
if (fd < 0) return SocketFailed(); if (fd < 0) return SocketFailed();
int one = 1; int one = 1;
@ -559,7 +527,7 @@ public:
int err = localRefusal ? errno : 0; int err = localRefusal ? errno : 0;
if (rc < 0 && errno == EINPROGRESS) { if (rc < 0 && errno == EINPROGRESS) {
pollfd p{fd, POLLOUT, 0}; pollfd p{fd, POLLOUT, 0};
if (PollTicked(p, 12000, tick) > 0) { if (poll(&p, 1, 12000) > 0) {
socklen_t el = sizeof err; socklen_t el = sizeof err;
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el); getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el);
connected = (err == 0); connected = (err == 0);
@ -586,24 +554,10 @@ public:
return false; return false;
} }
Log(std::format("connect failed; retry in 10s ({}) [{}/{}]", why, attempt + 1, tries)); Log(std::format("connect failed; retry in 10s ({}) [{}/{}]", why, attempt + 1, tries));
for (int s = 0; s < 10; s++) { sleep(10);
if (tick) tick();
sleep(1);
}
} }
return false; return false;
} }
// poll(2) on one descriptor for `ms`, in pieces of a second with `tick`
// called before each where there is one. Answers as poll does.
static int PollTicked(pollfd& p, int ms, const std::function<void()>& tick) {
if (!tick) return poll(&p, 1, ms);
for (;;) {
tick();
int piece = std::min(ms, 1000);
int r = poll(&p, 1, piece);
if (r != 0 || (ms -= piece) <= 0) return r;
}
}
// socket() failing is ours, not the network's: logged, and a local // socket() failing is ours, not the network's: logged, and a local
// refusal like a connect() the kernel turns down. // refusal like a connect() the kernel turns down.
bool SocketFailed() { bool SocketFailed() {
@ -646,10 +600,7 @@ public:
if (send(fd_, "\r\n\r\n", 4, MSG_NOSIGNAL) <= 0) alive_ = false; if (send(fd_, "\r\n\r\n", 4, MSG_NOSIGNAL) <= 0) alive_ = false;
} }
// The next whole message on the flow, within `timeoutSec`. With a std::optional<std::string> RecvMsg(double timeoutSec) {
// `tick` the wait for the socket is PollTicked's (Connect has what the
// tick is for).
std::optional<std::string> RecvMsg(double timeoutSec, const std::function<void()>& tick = {}) {
auto deadline = std::chrono::steady_clock::now() + auto deadline = std::chrono::steady_clock::now() +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(timeoutSec)); std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(timeoutSec));
for (;;) { for (;;) {
@ -658,7 +609,7 @@ public:
if (now >= deadline) return std::nullopt; if (now >= deadline) return std::nullopt;
int ms = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count()); int ms = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count());
pollfd p{fd_, POLLIN, 0}; pollfd p{fd_, POLLIN, 0};
int r = PollTicked(p, ms, tick); int r = poll(&p, 1, ms);
if (r <= 0) { if (r == 0) return std::nullopt; if (errno == EINTR) continue; return std::nullopt; } if (r <= 0) { if (r == 0) return std::nullopt; if (errno == EINTR) continue; return std::nullopt; }
std::optional<std::string> m; std::optional<std::string> m;
if (!ReadOnce(m)) return std::nullopt; if (!ReadOnce(m)) return std::nullopt;
@ -753,15 +704,6 @@ struct Inbound {
class ServerPorts { class ServerPorts {
public: public:
// Whether a packet from `own` to `peer` runs on a path of the SA pair:
// the shell answers, from its record of the pair (Engine::InsideSa).
// These ports take a request from any source (AGENTS.md §12); an
// answer they send that runs on neither path goes without
// P-Access-Network-Info, which names the serving cell (RFC 7315 4.4.2:
// a UA inserts it into what "is going to be securely sent" to its
// proxy).
void SetInsideSa(std::function<bool(const sockaddr_storage&, const sockaddr_storage&)> f) { insideSa_ = std::move(f); }
void Open(const std::string& local) { void Open(const std::string& local) {
int fam = Is6(local) ? AF_INET6 : AF_INET; int fam = Is6(local) ? AF_INET6 : AF_INET;
for (int port : {PortUc, PortUs}) { for (int port : {PortUc, PortUs}) {
@ -786,7 +728,7 @@ public:
if (bind(us, reinterpret_cast<sockaddr*>(&a), l) == 0) { if (bind(us, reinterpret_cast<sockaddr*>(&a), l) == 0) {
fcntl(us, F_SETFL, O_NONBLOCK); fcntl(us, F_SETFL, O_NONBLOCK);
udp_.push_back(us); udp_.push_back(us);
(port == PortUc ? udpUc_ : udpUs_) = us; if (port == PortUc) udpUc_ = us;
} else { close(us); } } else { close(us); }
} }
Log(std::format("listening on protected port {} (TCP+UDP)", port)); Log(std::format("listening on protected port {} (TCP+UDP)", port));
@ -797,11 +739,10 @@ public:
std::vector<Inbound> out; std::vector<Inbound> out;
for (int ls : listeners_) { for (int ls : listeners_) {
for (;;) { for (;;) {
sockaddr_storage peer{}; socklen_t pl = sizeof peer; int c = accept(ls, nullptr, nullptr);
int c = accept(ls, reinterpret_cast<sockaddr*>(&peer), &pl);
if (c < 0) break; if (c < 0) break;
fcntl(c, F_SETFL, O_NONBLOCK); fcntl(c, F_SETFL, O_NONBLOCK);
conns_.push_back({c, {}, PortOf(NameOf(c)), peer}); conns_.push_back({c, {}});
} }
} }
for (int us : udp_) { for (int us : udp_) {
@ -861,15 +802,8 @@ public:
htons(static_cast<uint16_t>(*vp)); htons(static_cast<uint16_t>(*vp));
if (udpUc_ >= 0) rs = udpUc_; if (udpUc_ >= 0) rs = udpUc_;
} }
// The closure keeps which of the two ports the answer auto reply = [rs, s, sll](const std::string& r) mutable {
// leaves by, not the socket's descriptor: CloseAll closes sendto(rs, r.data(), r.size(), 0, reinterpret_cast<sockaddr*>(&s), sll);
// that, and the kernel gives a closed descriptor's number
// out again.
auto reply = [this, uc = rs == udpUc_, s, sll](const std::string& r) mutable {
const int from = uc ? udpUc_ : udpUs_;
if (from < 0) return;
const std::string o = Leaving(r, NameOf(from), s);
sendto(from, o.data(), o.size(), 0, reinterpret_cast<sockaddr*>(&s), sll);
}; };
if (cutShort) { if (cutShort) {
Log(std::format("UDP: {} on server socket {} — answered 400", why, us == udpUc_ ? PortUc : PortUs)); Log(std::format("UDP: {} on server socket {} — answered 400", why, us == udpUc_ ? PortUc : PortUs));
@ -891,19 +825,9 @@ public:
} }
while (auto m = it->fb.TryExtract()) { while (auto m = it->fb.TryExtract()) {
if (!imsd::sip::Status(*m).has_value()) { if (!imsd::sip::Status(*m).has_value()) {
// What is sent through this closure is written to the int fd = it->fd;
// newest connection held from this request's peer to the out.push_back({*m, [fd](const std::string& r) {
// port the request came in on, and is not sent where none (void)!write(fd, r.data(), r.size());
// is held. The closure keeps the port and the peer, not
// the descriptor: Poll closes that when the peer has ended
// the connection, and the kernel gives a closed
// descriptor's number out again, to a pipe, a file or the
// connection of whoever connects next.
out.push_back({*m, [this, port = it->port, peer = it->peer](const std::string& r) {
const Conn* c = Find(port, peer);
if (!c) { Gone(port, peer); return; }
const std::string o = Leaving(r, NameOf(c->fd), c->peer);
(void)!write(c->fd, o.data(), o.size());
}}); }});
} }
} }
@ -917,46 +841,11 @@ public:
for (int f : udp_) close(f); for (int f : udp_) close(f);
for (auto& c : conns_) close(c.fd); for (auto& c : conns_) close(c.fd);
listeners_.clear(); udp_.clear(); conns_.clear(); listeners_.clear(); udp_.clear(); conns_.clear();
udpUc_ = udpUs_ = -1; udpUc_ = -1;
} }
private: private:
// An accepted connection: the port of ours it came in on and the peer struct Conn { int fd; imsd::sip::FrameBuffer fb; };
// accept named. int udpUc_ = -1;
struct Conn { int fd; imsd::sip::FrameBuffer fb; int port; sockaddr_storage peer; };
// The connection held from `peer` to our port `port`: the newest, where
// an older one that ended in an error stands until Poll reads its end;
// none where none is held.
const Conn* Find(int port, const sockaddr_storage& peer) const {
const Conn* found = nullptr;
for (const Conn& c : conns_)
if (c.port == port && SameEnd(c.peer, peer)) found = &c;
return found;
}
// `r` as it leaves from `own` to `peer` (SetInsideSa).
std::string Leaving(const std::string& r, const sockaddr_storage& own, const sockaddr_storage& peer) {
if (insideSa_ && insideSa_(own, peer)) return r;
std::string bare = imsd::sip::WithoutHeader(r, "P-Access-Network-Info");
if (bare.size() != r.size() && !saidOutside_) {
saidOutside_ = true;
Log(std::format("an answer from port {} to {} is on neither path of the SA pair on record: it goes without P-Access-Network-Info, as every such answer does (said once)", PortOf(own),
imsd::util::HostPort(HostOf(peer), PortOf(peer))));
}
return bare;
}
// An answer with no connection to go out on.
void Gone(int port, const sockaddr_storage& peer) {
if (!saidClosed_) Log(std::format("an answer from port {} to {} is not sent: no connection from that peer to that port is held (said once)", port,
imsd::util::HostPort(HostOf(peer), PortOf(peer))));
saidClosed_ = true;
}
std::function<bool(const sockaddr_storage&, const sockaddr_storage&)> insideSa_;
bool saidOutside_ = false;
bool saidClosed_ = false;
int udpUc_ = -1, udpUs_ = -1;
std::vector<int> listeners_, udp_; std::vector<int> listeners_, udp_;
std::vector<Conn> conns_; std::vector<Conn> conns_;
}; };
@ -1122,7 +1011,7 @@ struct StatusSnapshot {
// engine -> main-loop event // engine -> main-loop event
struct Event { struct Event {
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState, Work } type; enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type;
CallInfo info; // Added CallInfo info; // Added
std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id) std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id)
StatusSnapshot status; // Registration/Status StatusSnapshot status; // Registration/Status
@ -1131,7 +1020,6 @@ struct Event {
std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds) std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds)
std::string to; // SmsReceived: the subscriber it arrived for (the own number the daemon held then) std::string to; // SmsReceived: the subscriber it arrived for (the own number the daemon held then)
std::string simOperator; // SmsReceived: the operator id of the SIM it arrived under std::string simOperator; // SmsReceived: the operator id of the SIM it arrived under
bool on = false; // Work: a registration step or a text's sending wants the work's lock (true: at its begin, after its wait for a hold) or no longer does (at its end, for such a wait)
}; };
GDBusConnection* DbusConn = nullptr; GDBusConnection* DbusConn = nullptr;
@ -1508,90 +1396,11 @@ GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt
return g_variant_builder_end(&b); return g_variant_builder_end(&b);
} }
// ---- logind's inhibitor for sleep (main thread only) -----------------------
// Nothing of imsd runs while the phone is suspended: a suspend under a
// call stops this daemon and the call's media leg for as long as the
// phone sleeps. So imsd takes logind's block inhibitor for sleep while
// the calls table holds a call: from the call's addition (an incoming
// call's ringing; for a Dial after the recovery's try on a dead flow and
// the PANI refresh) to its removal. Under it logind refused a plain
// `systemctl suspend` on the dev phone; a request can tell it to ignore
// inhibitors (`systemctl suspend -i`).
// Where it was asked for during a suspend's operation logind refused this lock (systemd 262 on the
// dev phone: refused in a suspend's hooks before and after the sleep and
// to a call 0.1 to 0.3 s after the resume, given once logind had logged
// the operation's "finished"). So a lock that is wanted and not held is
// asked for again when logind sends PrepareForSleep with false; one
// wanted before the bus connection is there, when it comes.
// Where logind gives no lock at all (the session bus of --session has no
// logind) calls go on without one. The journal says so once until a
// call's lock is next given.
// A second lock is asked for, in the way the call's is, while the engine has work in flight that waits for
// the network: a step of the registration (Engine::Step) or a text being
// sent. A suspend under one would leave it where it stood until something
// wakes the phone: a text's waits count awake seconds. It is asked for where it is wanted and not
// held, released when nothing wants it any more, and the journal has no line for any of that.
struct SleepLock {
const char* why; // logind's "why": what the lock is held for
bool told; // its taking, its release and a refusal go to the journal
bool want = false;
int fd = -1; // the inhibitor's file descriptor (-1: not held)
};
SleepLock CallLock{"a call", true};
SleepLock WorkLock{"a registration step or a text in flight", false};
int WorksInFlight = 0; // the engine's Work events, true less false: what wants the work's lock now (a step that waits out a hold is not in it)
bool NoSleepLockTold = false; // the journal has a refusal's line since a call's lock was last given
void HoldSleepOff(SleepLock& lock, bool want) {
lock.want = want;
if (want == (lock.fd >= 0)) return;
if (!want) {
close(lock.fd);
lock.fd = -1;
if (lock.told) Log("sleep is no longer held off (no call)");
return;
}
if (!DbusConn) return;
GError* err = nullptr;
GUnixFDList* fds = nullptr;
GVariant* r = g_dbus_connection_call_with_unix_fd_list_sync(
DbusConn, "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit",
g_variant_new("(ssss)", "sleep", "imsd", lock.why, "block"), G_VARIANT_TYPE("(h)"),
G_DBUS_CALL_FLAGS_NONE, 2000, nullptr, &fds, nullptr, &err);
if (r) {
gint32 handle = -1;
g_variant_get(r, "(h)", &handle);
g_variant_unref(r);
if (fds && handle >= 0) lock.fd = g_unix_fd_list_get(fds, handle, nullptr);
}
if (fds) g_object_unref(fds);
if (lock.fd >= 0) {
if (lock.told) {
Log("sleep is held off while the call lasts (logind's inhibitor)");
NoSleepLockTold = false;
}
} else if (lock.told && !NoSleepLockTold) {
Log(std::format("no sleep inhibitor from logind ({}): asked again when it says a sleep is over", err ? err->message : "no file descriptor in its answer"));
NoSleepLockTold = true;
}
g_clear_error(&err);
}
// logind's PrepareForSleep: at one with false, a lock that is wanted and
// not held is asked for.
void OnPrepareForSleep(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer) {
if (!g_variant_is_of_type(params, G_VARIANT_TYPE("(b)"))) return;
gboolean entering = TRUE;
g_variant_get(params, "(b)", &entering);
if (entering) return;
HoldSleepOff(CallLock, CallLock.want);
HoldSleepOff(WorkLock, WorkLock.want);
}
gboolean OnIdleEvent(gpointer data) { gboolean OnIdleEvent(gpointer data) {
std::unique_ptr<Event> ev(static_cast<Event*>(data)); std::unique_ptr<Event> ev(static_cast<Event*>(data));
switch (ev->type) { switch (ev->type) {
case Event::Type::Added: { case Event::Type::Added: {
Calls[ev->info.uni] = ev->info; Calls[ev->info.uni] = ev->info;
HoldSleepOff(CallLock, true);
EmitSignal("CallAdded", g_variant_new("(s@a{sv})", ev->info.uni.c_str(), CallVariant(ev->info))); EmitSignal("CallAdded", g_variant_new("(s@a{sv})", ev->info.uni.c_str(), CallVariant(ev->info)));
break; break;
} }
@ -1607,7 +1416,6 @@ gboolean OnIdleEvent(gpointer data) {
} }
case Event::Type::Deleted: case Event::Type::Deleted:
Calls.erase(ev->uni); Calls.erase(ev->uni);
HoldSleepOff(CallLock, !Calls.empty());
EmitSignal("CallDeleted", g_variant_new("(s)", ev->uni.c_str())); EmitSignal("CallDeleted", g_variant_new("(s)", ev->uni.c_str()));
break; break;
case Event::Type::Registration: case Event::Type::Registration:
@ -1628,10 +1436,6 @@ gboolean OnIdleEvent(gpointer data) {
Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text)); Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text));
g_main_loop_quit(MainLoop); g_main_loop_quit(MainLoop);
break; break;
case Event::Type::Work:
WorksInFlight = std::max(0, WorksInFlight + (ev->on ? 1 : -1));
HoldSleepOff(WorkLock, WorksInFlight > 0);
break;
case Event::Type::SmsReceived: case Event::Type::SmsReceived:
for (const std::string& to : Subscribers) for (const std::string& to : Subscribers)
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at, ev->to, ev->simOperator))); EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at, ev->to, ev->simOperator)));
@ -1809,7 +1613,6 @@ public:
} }
for (;;) { for (;;) {
try { try {
Step step(*this);
BringUp(); BringUp();
break; break;
} catch (const Stopping&) { } catch (const Stopping&) {
@ -1842,7 +1645,6 @@ public:
return; return;
} }
} }
server_.SetInsideSa([this](const sockaddr_storage& own, const sockaddr_storage& peer) { return InsideSa(own, peer); });
try { server_.Open(local_); } try { server_.Open(local_); }
catch (...) { Log("server ports unavailable; remote hangup/incoming not seen"); } catch (...) { Log("server ports unavailable; remote hangup/incoming not seen"); }
OnRegistered(); OnRegistered();
@ -1884,7 +1686,6 @@ public:
Execute(call_->OnDeadline()); Execute(call_->OnDeadline());
MaybeDropCall(); MaybeDropCall();
} }
ArmWake(WakeDue());
if (auto msg = sip_.RecvMsg(0.3)) OnFlowMessage(*msg); if (auto msg = sip_.RecvMsg(0.3)) OnFlowMessage(*msg);
} }
// shutdown: release an active call, keep the SA/registration for resume // shutdown: release an active call, keep the SA/registration for resume
@ -1946,19 +1747,11 @@ private:
// after it, not before. False when the engine is stopping. // after it, not before. False when the engine is stopping.
bool WaitForPolicy() { bool WaitForPolicy() {
bool waited = false; bool waited = false;
// No lock under this wait, which can be an hour: nothing is waited
// for from the network, and the alarm ends a sleep at its end. For a
// step it is called from (the bring-up's) the lock is asked for again after.
const int paused = !quit_.load() && recovery_.Next(Boot()).at > Boot() ? steps_ : 0;
for (int i = 0; i < paused; i++) PostWork(false);
while (!quit_.load() && recovery_.Next(Boot()).at > Boot()) { while (!quit_.load() && recovery_.Next(Boot()).at > Boot()) {
waited = true; waited = true;
if (auto cmd = PopCmd()) { HandleCmd(*cmd); MaybeDropCall(); continue; } if (auto cmd = PopCmd()) { HandleCmd(*cmd); MaybeDropCall(); continue; }
ArmWake(recovery_.Next(Boot()).at); // a wait the phone sleeps under ends with the phone awake
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
for (int i = 0; i < paused; i++) PostWork(true);
if (waited) netAlarm_(); // the wait's alarm has fired where the phone slept under it
if (waited && !quit_.load()) RefreshPani(); if (waited && !quit_.load()) RefreshPani();
return !quit_.load(); return !quit_.load();
} }
@ -2042,10 +1835,9 @@ private:
bool subPending_ = false; // SUBSCRIBE sent, no final yet bool subPending_ = false; // SUBSCRIBE sent, no final yet
double subSentAt_ = 0; double subSentAt_ = 0;
double subRetryAt_ = 0; // a failed/ended subscription is renewed at this time (0: none due) double subRetryAt_ = 0; // a failed/ended subscription is renewed at this time (0: none due)
double subRenewAt_ = 0; // the live subscription is subscribed anew at this time on the boot clock, ahead of its granted expiry (0: none) double subRenewAt_ = 0; // the live subscription is subscribed anew at this time, ahead of its granted expiry (0: none)
double subRetryDelay_ = 60; // 60 s doubling to 10 min between failed SUBSCRIBEs double subRetryDelay_ = 60; // 60 s doubling to 10 min between failed SUBSCRIBEs
int portPs_ = 0; // P-CSCF protected server port (reconnect target) int portPs_ = 0; // P-CSCF protected server port (reconnect target)
imsd::ipsec::SaPaths saPaths_; // the SA pair this run set up without an error or resumed, until it takes that pair out of the kernel: what InsideSa judges by
imsd::engine::RegRecovery recovery_; // what to do when the registration stops working imsd::engine::RegRecovery recovery_; // what to do when the registration stops working
bool saReplaced_ = false; // the running fresh attempt got past the SA setup (the old registration's SAs are gone) bool saReplaced_ = false; // the running fresh attempt got past the SA setup (the old registration's SAs are gone)
@ -2065,10 +1857,8 @@ private:
std::function<void(const std::string&)> callReply_; std::function<void(const std::string&)> callReply_;
// timers // timers
double lastRefresh_ = 0; // on the boot clock (Boot): the registration's lifetime runs at the network while the phone sleeps double lastRefresh_ = 0;
double lastKa_ = 0; // on the steady clock (Mono) double lastKa_ = 0;
int wakeFd_ = -1; // the wake alarm, a timer on CLOCK_BOOTTIME_ALARM (-2: the kernel gave none)
double wakeAt_ = 0; // the boot-clock time it was last armed for, fired or not (0: not armed)
std::atomic<bool> quit_{false}; std::atomic<bool> quit_{false};
bool devMode_ = false; bool devMode_ = false;
@ -2104,133 +1894,6 @@ private:
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
} }
// The refresh's interval: half the granted lifetime (of 3600 s where none
// was granted), within 120-1800 s (REFRESH_INTERVAL= sets it).
double RefreshInterval() const {
if (const char* o = std::getenv("REFRESH_INTERVAL")) return std::atof(o);
long exp = reg_.expiry ? reg_.expiry : 3600;
return std::max(120.0, std::min(exp * 0.5, 1800.0));
}
// The wake alarm. The registration's lifetime runs at the network while
// the phone sleeps, and the steady clock does not: a refresh counted in
// awake seconds comes too late for a phone that sleeps most of the time
// (the dev phone, 2026-11-19: asleep for most of a registration's two hours, no refresh, the
// binding expired). So the refresh is due on the boot clock, and a timer
// on CLOCK_BOOTTIME_ALARM, armed by the loop for the time WakeDue names (ArmWake's other callers arm their own), makes the
// kernel wake a sleeping phone then (its RTC's alarm; CAP_WAKE_ALARM,
// which the system service has). The descriptor is never read: the
// waking is the whole of it, and the loop's own clock checks act once
// the phone is awake. Where the kernel gives no such timer the journal
// says so once and the daemon runs without: awake, nothing differs.
void ArmWake(double at) {
if (wakeTrace_) TraceWake(at);
if (wakeFd_ == -2 || at == wakeAt_) return;
if (wakeFd_ < 0) {
// the timer can be had without an RTC behind it, and then
// neither wakes the phone nor makes the kernel refuse a suspend:
// the clock's resolution is what the kernel answers only with one
timespec res{};
if (clock_getres(CLOCK_BOOTTIME_ALARM, &res) != 0) {
Log("no wake alarm (no RTC that can wake the phone): a sleeping phone is not woken for the registration's refresh");
wakeFd_ = -2;
return;
}
wakeFd_ = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_CLOEXEC);
if (wakeFd_ < 0) {
Log(std::format("no wake alarm ({}): a sleeping phone is not woken for the registration's refresh", std::strerror(errno)));
wakeFd_ = -2;
return;
}
Log("wake alarm: a sleeping phone is woken when the registration's refresh is due");
}
itimerspec its{}; // all zero disarms
if (at > 0) {
its.it_value.tv_sec = static_cast<time_t>(at);
its.it_value.tv_nsec = static_cast<long>((at - std::floor(at)) * 1e9);
}
if (timerfd_settime(wakeFd_, TFD_TIMER_ABSTIME, &its, nullptr) < 0) {
Log(std::format("wake alarm not set: {}", std::strerror(errno)));
return;
}
wakeAt_ = at;
}
// What the loop arms the alarm for at the end of a turn that took no
// command off the queue (one that took a command handles it and goes
// straight to the next turn). A time that has come (a call, a text in
// flight; a step that is due, which the next turn runs) is armed
// WakeHold ahead at every such turn: the kernel refuses a suspend
// that finds an alarm less than two seconds ahead at its check (alarmtimer_suspend),
// whoever asks for it. For a step that follows a local wait (no
// packet service, a connect the kernel refused) the policy names the
// slower look's time: with no call and no text in flight nothing is
// held then.
static constexpr double WakeHold = 1.9;
// WAKE_TRACE=1, a test seam: a line whenever the time the alarm is
// armed for changes (by the second), with or without a timer to arm (a
// bench has none). A time under two seconds ahead is "held", said once
// while it lasts.
const bool wakeTrace_ = EnvOr("WAKE_TRACE", "0") == "1";
std::string wakeTraced_;
void TraceWake(double at) {
double ahead = at - Boot();
std::string s = at <= 0 ? "none" : ahead < 2 ? "held under 2 s ahead" : std::format("{:.0f} s on the boot clock", at);
if (s == wakeTraced_) return;
wakeTraced_ = s;
Log(at > 0 && ahead >= 2 ? std::format("wake trace: {} ({:.0f} s ahead)", s, ahead) : std::format("wake trace: {}", s));
}
double WakeDue() const {
bool recovering = portPs_ != 0 && !reg_.callid.empty(); // MaybeReconnect's own condition
bool renewal = registered_ && !subCallid_.empty() && !subPending_; // MaybeResubscribe's own, with the live flow
double now = Boot();
double at = imsd::engine::WakeAt(now, call_.has_value() || smsOut_.has_value(), !reg_.callid.empty() && sip_.Alive(),
lastRefresh_ + RefreshInterval(), renewal ? subRenewAt_ : 0,
recovering, recovering ? recovery_.WakeTime(now) : 0);
return at > 0 && at < now + WakeHold ? now + WakeHold : at;
}
// A step of the registration that exchanges with the network: the
// refresh, a reconnect, a fresh registration, the bring-up. The main
// thread asks for logind's sleep lock while one runs (WorkLock, which a
// text in flight wants as well; held where logind gives it), so that the step's waits run their
// awake seconds in one piece; not while the bring-up waits out a hold
// (WaitForPolicy). For a sleep that begins under a step all the same
// (logind refused such a lock on the dev phone where a suspend's operation was already running; a suspend
// told to ignore inhibitors) the alarm stands at most WakeNet ahead
// while the step waits for the network: set as it begins, and anew
// before every second of a connect's wait, of the pause before the next
// try and of a wait for a REGISTER's answer. It fires once, and a wait
// can outlast the sleep it ended: set every second, it stands again
// within a second of that wake, for the sleep that may follow. Where there is an alarm the
// sleep ends there, a lock logind had refused is asked for at its end (one held is kept), and the step goes
// on. A wait for a helper program (mmcli, qmicli, ip) has the alarm
// that stood when it began, once. After the step
// the loop's own arming takes over again (WakeDue).
static constexpr double WakeNet = 30;
struct Step {
explicit Step(Engine& engine) : e(engine) { e.steps_++; e.PostWork(true); e.netAlarm_(); }
~Step() { e.steps_--; e.PostWork(false); }
Step(const Step&) = delete;
Step& operator=(const Step&) = delete;
Engine& e;
};
int steps_ = 0; // the steps under way: what a hold's wait pauses (WaitForPolicy)
bool noServiceTold_ = false; // the journal has the line of the coverage gap that runs
// What a step sets the alarm to as it begins and before every second of
// its waits for the network: WakeNet ahead, also where a call or a text
// is in flight (the loop's WakeHold needs setting anew within two
// seconds, which a helper program's wait does not give: under a step
// the sleep is bounded, not refused).
const std::function<void()> netAlarm_ = [this] { ArmWake(Boot() + WakeNet); };
// The connect for a call's resend is no step: no helper program runs
// under it, and the loop arms again at the end of the turn it runs in.
// It keeps the loop's hold through its wait, set anew every second.
const std::function<void()> holdAlarm_ = [this] { ArmWake(Boot() + WakeHold); };
void PostWork(bool on) {
auto ev = std::make_unique<Event>();
ev->type = Event::Type::Work; ev->on = on;
PostEvent(std::move(ev));
}
std::optional<Cmd> PopCmd() { std::optional<Cmd> PopCmd() {
std::scoped_lock g(cmdLock_); std::scoped_lock g(cmdLock_);
if (cmds_.empty()) return std::nullopt; if (cmds_.empty()) return std::nullopt;
@ -2247,14 +1910,6 @@ private:
return "/usr/libexec/imsd-media"; return "/usr/libexec/imsd-media";
} }
// Whether a packet from `own` to `peer` runs on one of the two paths of
// the SA pair on record (imsd::ipsec::OnSaPath). The record is the
// shell's own: of the pair it set up without an error or read back from
// the kernel's tables at a resume. It does not ask the kernel again.
bool InsideSa(const sockaddr_storage& own, const sockaddr_storage& peer) const {
return imsd::ipsec::OnSaPath(saPaths_, HostOf(own), PortOf(own), HostOf(peer), PortOf(peer));
}
// Refresh P-Access-Network-Info from the live serving cell (mmcli 3GPP // Refresh P-Access-Network-Info from the live serving cell (mmcli 3GPP
// location). Serving cell changes as the phone moves, so this runs // location). Serving cell changes as the phone moves, so this runs
// before every REGISTER/INVITE-carrying step; on failure the previous // before every REGISTER/INVITE-carrying step; on failure the previous
@ -2390,7 +2045,7 @@ private:
// P-CSCF and nothing is configured, a fact until a boot or a // P-CSCF and nothing is configured, a fact until a boot or a
// start. A discovery that FAILED (the reader did not answer) is // start. A discovery that FAILED (the reader did not answer) is
// no fact: the fatal, and the restart runs it again. // no fact: the fatal, and the restart runs it again.
if (outcome == ResumeOutcome::Dead) { recovery_.OldGone(); RemoveDeadPair(pdnLocal_); saPaths_ = {}; } if (outcome == ResumeOutcome::Dead) { recovery_.OldGone(); RemoveDeadPair(pdnLocal_); }
KeepHolds(); KeepHolds();
if (outcome == ResumeOutcome::Failed || DiscoveryFailed()) throw std::runtime_error(std::string(NoFreshPcscf)); if (outcome == ResumeOutcome::Failed || DiscoveryFailed()) throw std::runtime_error(std::string(NoFreshPcscf));
RequestIdle(std::string(NoPcscfIdleText)); throw Stopping{}; RequestIdle(std::string(NoPcscfIdleText)); throw Stopping{};
@ -2536,15 +2191,13 @@ private:
Log(std::format("RESUME via existing SA (cseq {})", ps->cseq.value_or(1))); Log(std::format("RESUME via existing SA (cseq {})", ps->cseq.value_or(1)));
portPs_ = sa->portPs; portPs_ = sa->portPs;
saPaths_ = {local_, pcscf_, sa->portPs, sa->portPc};
SetTransport(t); SetTransport(t);
// Local refusals (TIME_WAIT after a restart) keep retrying; two // Local refusals (TIME_WAIT after a restart) keep retrying; two
// silences mean the flow is not coming back — fresh instead. // silences mean the flow is not coming back — fresh instead.
if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2, netAlarm_)) { if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2)) {
Log(std::format("resume connect failed; {}", ResumeFailedNext())); Log(std::format("resume connect failed; {}", ResumeFailedNext()));
return ResumeOutcome::Failed; return ResumeOutcome::Failed;
} }
if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered();
reg_.callid = *ps->callid; reg_.callid = *ps->callid;
reg_.ftag = ps->ftag.value_or(""); reg_.ftag = ps->ftag.value_or("");
// The refresh must carry the SAME Contact URI as the stored binding; // The refresh must carry the SAME Contact URI as the stored binding;
@ -2704,19 +2357,16 @@ private:
sp.ealg = ealg; sp.ealg = ealg;
// imsd's previous pair out first, each entry by its key — not `ip xfrm … // imsd's previous pair out first, each entry by its key — not `ip xfrm …
// flush`: another IPsec user's entries (a policy-based VPN's) stay (§12) // flush`: another IPsec user's entries (a policy-based VPN's) stay (§12)
saPaths_ = {};
{ {
auto state = RunCapture({"ip", "xfrm", "state"}); auto state = RunCapture({"ip", "xfrm", "state"});
auto policy = RunCapture({"ip", "xfrm", "policy"}); auto policy = RunCapture({"ip", "xfrm", "policy"});
RunOwnXfrmDeletes(imsd::ipsec::OwnXfrmDeleteCommands(state.out, policy.out, local_)); RunOwnXfrmDeletes(imsd::ipsec::OwnXfrmDeleteCommands(state.out, policy.out, local_));
} }
saReplaced_ = true; // from here on the old registration's SAs are gone saReplaced_ = true; // from here on the old registration's SAs are gone
bool installed = true;
for (auto& cmd : imsd::ipsec::BuildSetupCommands(sp)) { for (auto& cmd : imsd::ipsec::BuildSetupCommands(sp)) {
int rc = RunCmd(cmd); int rc = RunCmd(cmd);
if (rc != 0) { Log(std::format("{} -> rc {}", RedactKeys(cmd), rc)); installed = false; } if (rc != 0) Log(std::format("{} -> rc {}", RedactKeys(cmd), rc));
} }
if (installed) saPaths_ = {local_, pcscf_, portPs, portPc};
ctx_.securityServer = ss_; ctx_.securityServer = ss_;
portPs_ = portPs; portPs_ = portPs;
@ -2738,7 +2388,7 @@ private:
} }
} }
bool autoTcp = (sipPolicy_ == "auto" && transport_ == Transport::Tcp && !tcpKnownGood); bool autoTcp = (sipPolicy_ == "auto" && transport_ == Transport::Tcp && !tcpKnownGood);
if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0, netAlarm_)) { if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0)) {
if (autoTcp) { if (autoTcp) {
// Two unanswered TCP connects: treat the P-CSCF as UDP-only // Two unanswered TCP connects: treat the P-CSCF as UDP-only
// and register again over UDP — a new challenge and a new SA // and register again over UDP — a new challenge and a new SA
@ -2807,8 +2457,7 @@ private:
double deadline = Mono() + 12.0; double deadline = Mono() + 12.0;
for (;;) { for (;;) {
double left = deadline - Mono(); double left = deadline - Mono();
// the alarm is set anew before every second of the wait (Step) auto m = left > 0 ? sip_.RecvMsg(left) : std::nullopt;
auto m = left > 0 ? sip_.RecvMsg(left, netAlarm_) : std::nullopt;
if (!m) throw std::runtime_error(std::format("no reply to {}", what)); if (!m) throw std::runtime_error(std::format("no reply to {}", what));
auto st = imsd::sip::Status(*m); auto st = imsd::sip::Status(*m);
if (!st) { if (!st) {
@ -2821,7 +2470,6 @@ private:
if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what)); if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
continue; continue;
} }
recovery_.OnNetworkAnswered(); // a response to our REGISTER, whatever it says: the network is in reach
if (*st >= 200) return *m; if (*st >= 200) return *m;
Log(std::format("{} -> {} (provisional); waiting for the final", what, *st)); Log(std::format("{} -> {} (provisional); waiting for the final", what, *st));
deadline = Mono() + 12.0; deadline = Mono() + 12.0;
@ -2843,9 +2491,6 @@ private:
for (;;) { for (;;) {
double left = deadline - Mono(); double left = deadline - Mono();
if (left <= 0) break; if (left <= 0) break;
// in pieces of a second, the alarm set anew before each (Step)
netAlarm_();
left = std::min(left, 1.0);
long sec = static_cast<long>(left); long sec = static_cast<long>(left);
long usec = static_cast<long>((left - static_cast<double>(sec)) * 1e6); long usec = static_cast<long>((left - static_cast<double>(sec)) * 1e6);
if (sec == 0 && usec == 0) usec = 1000; if (sec == 0 && usec == 0) usec = 1000;
@ -2853,14 +2498,7 @@ private:
setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
sockaddr_storage src; socklen_t sl = sizeof src; sockaddr_storage src; socklen_t sl = sizeof src;
ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast<sockaddr*>(&src), &sl); ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast<sockaddr*>(&src), &sl);
if (n < 0) { if (n < 0) break;
// a piece is over, or the receive was interrupted (EINTR: by
// a suspend's freeze, after which the kernel takes a poll up
// again but not a datagram receive under a timeout; by a stop and a
// continue; by a signal handled here): the deadline is looked at above
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue;
break;
}
const int sp = PortOf(src); const int sp = PortOf(src);
std::string why; std::string why;
auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast<std::size_t>(n)), &why); auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast<std::size_t>(n)), &why);
@ -2875,7 +2513,6 @@ private:
continue; continue;
} }
int st = *imsd::sip::Status(m); int st = *imsd::sip::Status(m);
recovery_.OnNetworkAnswered();
if (st >= 200) { close(us); return m; } if (st >= 200) { close(us); return m; }
Log(std::format("unprotected REGISTER -> {} (provisional); waiting for the final", st)); Log(std::format("unprotected REGISTER -> {} (provisional); waiting for the final", st));
deadline = Mono() + 8.0; deadline = Mono() + 8.0;
@ -2907,15 +2544,6 @@ private:
do spiUs = rng_.UInt(0x10000, 0xFFFFFFF); while (spiUs == reg_.spiUc || spiUs == reg_.spiUs || spiUs == spiUc); do spiUs = rng_.UInt(0x10000, 0xFFFFFFF); while (spiUs == reg_.spiUc || spiUs == reg_.spiUs || spiUs == spiUc);
std::string reg = imsd::msg::BuildRegisterProtected(ctx_, callid, ftag, rng_.Token(16), cseq, spiUc, spiUs, auth, PortUcNext); std::string reg = imsd::msg::BuildRegisterProtected(ctx_, callid, ftag, rng_.Token(16), cseq, spiUc, spiUs, auth, PortUcNext);
if (!sip_.Send(reg)) throw std::runtime_error("send re-REGISTER failed"); if (!sip_.Send(reg)) throw std::runtime_error("send re-REGISTER failed");
// Sent, the number is used, whatever comes back: the next REGISTER
// on this Call-ID carries a higher one (RFC 3261 10.2), where a
// registrar that took this one and whose answer did not arrive
// refuses the same number (10.3 step 7; KPN answered 482 Loop
// Detected where, by 1.2.4's code, two re-REGISTERs carried an
// unanswered refresh's: the dev phone, 2026-11-25). After a restart
// too: the state file has the number before the answer is waited for.
reg_.cseq = cseq;
PersistState(reg_, route_, ppi_, ctx_.aor, ctx_.transport, pcscf_);
std::string m = AwaitFinal(callid, cseq, "re-REGISTER"); std::string m = AwaitFinal(callid, cseq, "re-REGISTER");
auto st = imsd::sip::Status(m); auto st = imsd::sip::Status(m);
if (st == 200) return {m, cseq}; if (st == 200) return {m, cseq};
@ -2975,7 +2603,8 @@ private:
// 7.1.2) and the IMS AKA context of an ISIM (TS 31.103 7.1.2), and both // 7.1.2) and the IMS AKA context of an ISIM (TS 31.103 7.1.2), and both
// answer RES, CK and IK under tag DB. // answer RES, CK and IK under tag DB.
// An ISIM that gives no result is not the end of the attempt: the same // An ISIM that gives no result is not the end of the attempt: the same
// card's USIM is asked, where 1.2.2 sent every challenge. // card's USIM is asked, where 1.2.2 sent every challenge —
// no AKA in a real ISIM has run on this code (AGENTS.md §5).
std::optional<imsd::aka::AkaResult> Authenticate(std::span<const std::uint8_t> rand16, std::span<const std::uint8_t> autn16) { std::optional<imsd::aka::AkaResult> Authenticate(std::span<const std::uint8_t> rand16, std::span<const std::uint8_t> autn16) {
std::string what; std::string what;
auto result = AkaIn(reg_.aid, rand16, autn16, what); auto result = AkaIn(reg_.aid, rand16, autn16, what);
@ -3007,8 +2636,11 @@ private:
void MaybeRefresh() { void MaybeRefresh() {
if (call_ || reg_.callid.empty()) return; if (call_ || reg_.callid.empty()) return;
if (!sip_.Alive()) return; // MaybeReconnect owns dead-flow recovery if (!sip_.Alive()) return; // MaybeReconnect owns dead-flow recovery
if (Boot() - lastRefresh_ < RefreshInterval()) return; long exp = reg_.expiry ? reg_.expiry : 3600;
Step step(*this); double interval;
if (const char* o = std::getenv("REFRESH_INTERVAL")) interval = std::atof(o);
else interval = std::max(120.0, std::min(exp * 0.5, 1800.0));
if (Mono() - lastRefresh_ < interval) return;
try { try {
RefreshPani(); RefreshPani();
auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1);
@ -3035,7 +2667,7 @@ private:
Log(std::format("keepalive re-REGISTER failed: {}", e.what())); Log(std::format("keepalive re-REGISTER failed: {}", e.what()));
CloseFlowAfterWait(); CloseFlowAfterWait();
} }
lastRefresh_ = Boot(); lastRefresh_ = Mono();
lastKa_ = Mono(); lastKa_ = Mono();
} }
@ -3057,9 +2689,8 @@ private:
} }
// A client flow found dead under an outgoing call whose INVITE has had // A client flow found dead under an outgoing call whose INVITE has had
// no response and no CANCEL (CallMachine::Unanswered) is reopened, once // no response and no CANCEL (CallMachine::Unanswered) is reopened once
// for each INVITE the call sends, and that INVITE sent again: a flow the // per attempt and the INVITE sent again: a flow the network had
// network had
// forgotten is reset at the first bytes sent on it, and those may be a // forgotten is reset at the first bytes sent on it, and those may be a
// call's. No REGISTER goes first: the registration and its SAs stand // call's. No REGISTER goes first: the registration and its SAs stand
// (not where the network has ended the binding: RegRecovery's // (not where the network has ended the binding: RegRecovery's
@ -3075,7 +2706,7 @@ private:
if (recovery_.Reconnectable() && call_->ResendDue()) { if (recovery_.Reconnectable() && call_->ResendDue()) {
Log(std::format("call {}: the client flow died before any response to the INVITE; reopening it", call_->Uni())); Log(std::format("call {}: the client flow died before any response to the INVITE; reopening it", call_->Uni()));
sip_.Abort(); sip_.Abort();
ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1, 0, holdAlarm_) && Execute(call_->OnFlowReopened()); ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1) && Execute(call_->OnFlowReopened());
} }
if (!ok && call_ && !call_->Terminated()) Execute(call_->OnFlowLost()); if (!ok && call_ && !call_->Terminated()) Execute(call_->OnFlowLost());
MaybeDropCall(); MaybeDropCall();
@ -3124,48 +2755,15 @@ private:
// refuses while the old one is live, and drops it for. // refuses while the old one is live, and drops it for.
void CoverageGap(std::string_view what) { void CoverageGap(std::string_view what) {
if (registered_) { registered_ = false; EmitStatus(true); } if (registered_) { registered_ = false; EmitStatus(true); }
recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService); recovery_.OnLocalRefusal(Boot());
Log(std::format("{} while the modem reports no packet service: not counted; {}", what, NextStep())); Log(std::format("{} while the modem reports no packet service: not counted; {}", what, NextStep()));
} }
// While the modem reports no packet service the recovery tries nothing
// (this is its look before a reconnect cycle and before a fresh
// registration of its own; a bring-up does not ask): a reconnect would wait for answers that cannot come (over TCP
// two connects of 12 s, over UDP the re-REGISTER's 12 s), and a fresh registration its first REGISTER's 8 s, with the sleep
// lock held. The policy looks again LocalRetry on while the phone is
// awake, and wakes a sleeping one for a look at its slower pace
// (RegRecovery::WakeTime). One line where the modem is found without
// service, and again after a look that found it with. The modem's word
// does not start the gap's count over: only the network's answer does
// (RegRecovery::OnNetworkAnswered: the shell's calls and the policy's
// own). The look asks ModemManager, which can take its time: the alarm
// stands under it. A dead flow's socket that is still open does not
// outlive the look: left open through the wait a TCP one is readable at every
// turn of the loop (its end of file, its error), which would then spin
// instead of waiting, and a Dial's INVITE would be written into it.
// Abort, as at a call's reopen: a TCP FIN sent into a gap would hold the
// address pair against the reconnect after it, as a step's own close after an unanswered wait does (CloseFlowAfterWait). (A recovery step runs
// on a dead flow only: MaybeReconnect.)
bool NoService(std::string_view what) {
netAlarm_();
if (PacketServiceUp()) { noServiceTold_ = false; return false; }
sip_.Abort();
if (registered_) { registered_ = false; EmitStatus(true); }
recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService);
if (!noServiceTold_) {
Log(std::format("the modem reports no packet service: {} waits until it has it again", what));
noServiceTold_ = true;
}
return true;
}
void ReconnectCycle() { void ReconnectCycle() {
using F = imsd::engine::RegRecovery::Failure; using F = imsd::engine::RegRecovery::Failure;
if (NoService("the reconnect")) return;
Log("client flow dead; reconnecting"); Log("client flow dead; reconnecting");
Step step(*this);
sip_.Close(); sip_.Close();
if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2, 0, netAlarm_)) { if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2)) {
if (AddressGone()) return; if (AddressGone()) return;
if (sip_.LastConnectLocal()) { if (sip_.LastConnectLocal()) {
if (registered_) { registered_ = false; EmitStatus(true); } if (registered_) { registered_ = false; EmitStatus(true); }
@ -3176,10 +2774,6 @@ private:
RecoveryFailed(F::Silent, 0, "P-CSCF silent"); RecoveryFailed(F::Silent, 0, "P-CSCF silent");
return; return;
} }
// a TCP connect the P-CSCF answered: the network is in reach (a
// UDP "connect" says nothing of it; there a REGISTER's response
// does, in AwaitFinal)
if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered();
try { try {
RefreshPani(); RefreshPani();
auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1);
@ -3228,9 +2822,7 @@ private:
// nothing is retried until the next fresh attempt. // nothing is retried until the next fresh attempt.
void FreshRecover() { void FreshRecover() {
using F = imsd::engine::RegRecovery::Failure; using F = imsd::engine::RegRecovery::Failure;
if (NoService("the fresh registration")) return;
Log(std::format("registering fresh (recovery attempt {})", recovery_.freshAttempts + 1)); Log(std::format("registering fresh (recovery attempt {})", recovery_.freshAttempts + 1));
Step step(*this);
sip_.Close(); sip_.Close();
saReplaced_ = false; // this attempt's, whatever fails first saReplaced_ = false; // this attempt's, whatever fails first
// the subscription dialog is the registration's and goes with the // the subscription dialog is the registration's and goes with the
@ -3366,7 +2958,7 @@ private:
bool was = registered_; bool was = registered_;
registered_ = true; registered_ = true;
EmitStatus(!was); EmitStatus(!was);
lastRefresh_ = Boot(); lastKa_ = Mono(); lastRefresh_ = Mono(); lastKa_ = Mono();
// a refresh or a reconnect opens no subscription dialog while imsd // a refresh or a reconnect opens no subscription dialog while imsd
// holds one for the registration or has a retry scheduled; a fresh // holds one for the registration or has a retry scheduled; a fresh
// registration (or a start) has none yet, and a fresh attempt drops // registration (or a start) has none yet, and a fresh attempt drops
@ -3430,7 +3022,7 @@ private:
ScheduleResubscribe(0); ScheduleResubscribe(0);
} }
if (call_ || !registered_ || !sip_.Alive()) return; if (call_ || !registered_ || !sip_.Alive()) return;
if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Boot() >= subRenewAt_) { if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Mono() >= subRenewAt_) {
// the granted lifetime is running out: a new dialog (the S-CSCF // the granted lifetime is running out: a new dialog (the S-CSCF
// closes the previous one — KPN with noresource), on the same // closes the previous one — KPN with noresource), on the same
// registration // registration
@ -3448,8 +3040,8 @@ private:
// end, or halfway through a shorter grant. // end, or halfway through a shorter grant.
void ArmSubscriptionRenewal(long expires) { void ArmSubscriptionRenewal(long expires) {
double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0; double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0;
subRenewAt_ = Boot() + std::max(ahead, 30.0); subRenewAt_ = Mono() + std::max(ahead, 30.0);
Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Boot())); Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Mono()));
} }
// The network's view of our binding (RFC 3680 reginfo), read from any // The network's view of our binding (RFC 3680 reginfo), read from any
@ -3644,7 +3236,6 @@ private:
const bool wantsReport = p.statusReport; const bool wantsReport = p.statusReport;
const std::string destination = p.number; const std::string destination = p.number;
smsOut_.emplace(ctx_, rng_, smsSubmitted_, id, std::move(p)); smsOut_.emplace(ctx_, rng_, smsSubmitted_, id, std::move(p));
PostWork(true); // the work's lock while it is in flight: its waits count awake seconds
auto actions = smsOut_->Start(Mono()); auto actions = smsOut_->Start(Mono());
// on record from the start — the SC may deliver segment 1 and report on // on record from the start — the SC may deliver segment 1 and report on
// it while segment 2 is still in flight — and only for a message that // it while segment 2 is still in flight — and only for a message that
@ -3668,7 +3259,6 @@ private:
void EndSms() { void EndSms() {
rpMr_ = smsOut_->NextRpMr(); rpMr_ = smsOut_->NextRpMr();
smsOut_.reset(); smsOut_.reset();
PostWork(false);
} }
// The message in flight ended: the next queued message starts (its // The message in flight ended: the next queued message starts (its
@ -4258,11 +3848,6 @@ const GDBusInterfaceVTable MessagingVtable = { imsd::bus::Gated<HandleMessagingM
void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) { void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) {
DbusConn = conn; DbusConn = conn;
g_dbus_connection_signal_subscribe(conn, "org.freedesktop.login1", "org.freedesktop.login1.Manager", "PrepareForSleep",
"/org/freedesktop/login1", nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnPrepareForSleep, nullptr, nullptr);
// the engine began before the bus was there: what it has asked for by now
HoldSleepOff(CallLock, CallLock.want);
HoldSleepOff(WorkLock, WorkLock.want);
GError* err = nullptr; GError* err = nullptr;
GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, &err); GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, &err);
if (!node) { Log(std::format("introspection XML: {}", err ? err->message : "?")); if (err) g_error_free(err); return; } if (!node) { Log(std::format("introspection XML: {}", err ? err->message : "?")); if (err) g_error_free(err); return; }

View file

@ -283,7 +283,8 @@ export namespace imsd::aka {
// "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=<mcc><mnc><tac:4hex><eci:7hex>" // "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=<mcc><mnc><tac:4hex><eci:7hex>"
// (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit // (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit
// TAC + 28-bit ECI; mmcli prints both hex fields zero-padded wider, so // TAC + 28-bit ECI; mmcli prints both hex fields zero-padded wider, so
// take the low digits). The TAS reads it to see which access the UE // take the low digits). The stock modem sends exactly this shape in
// every REGISTER/INVITE — the TAS reads it to see which access the UE
// is reachable on. FDD is a constant: every KPN LTE band in use is FDD // is reachable on. FDD is a constant: every KPN LTE band in use is FDD
// and MM does not expose the duplex mode. nullopt when the fields are // and MM does not expose the duplex mode. nullopt when the fields are
// missing or zero (no serving cell) — callers then omit the header // missing or zero (no serving cell) — callers then omit the header

View file

@ -3,8 +3,8 @@
/* /*
Imsd:Engine — the daemon's decisions as pure reducers: the call state Imsd:Engine — the daemon's decisions as pure reducers: the call state
machine (CallMachine), the registration recovery policy (RegRecovery, its own section below), when the phone has machine (CallMachine), the registration recovery policy (RegRecovery,
to be awake for imsd (WakeAt, with the policy's WakeTime after a local wait) and SMS over IP's (the last paragraph here). 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 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 touches a socket, a clock, or a subprocess: each event (the INVITE's
@ -17,8 +17,7 @@ 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 finals, CANCEL/answer races, remote BYE, media-plane far-end-hangup, the
emergency attempt chain (urn:service:sos first for a classified number, one 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 fallback to a plain INVITE of the digits; a 380 Alternative Service upgrade
the other way), an INVITE refused 422 sent again with the Min-SE the 422 the other way), the terminating (UAS) side: 100/180 on an inbound INVITE,
names (RFC 4028 7.3, 7.4), the terminating (UAS) side: 100/180 on an inbound INVITE,
200-with-answer on Accept, 486 reject, the remote-CANCEL 200+487 pair — and 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 DTMF, which reaches the media leg only on an active call whose SDP
negotiated telephone-event, as the tones a keypad has — negotiated telephone-event, as the tones a keypad has —
@ -77,8 +76,8 @@ export namespace imsd::engine {
// ---- registration recovery policy --------------------------------- // ---- registration recovery policy ---------------------------------
// //
// What the daemon does when the registration stops working after // What the daemon does when the registration stops working after
// bring-up, as a pure reducer: the shell supplies the clock, the network and (at a local wait) its kind, the // bring-up, as a pure reducer: the shell supplies the clock and the
// kernel's refusal or the modem's word; this decides the next step, how long to wait for it and when a sleeping phone is woken for it. Two // 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 // kinds of failure reach it. A REFUSAL: the network answered a refresh
// with a final other than 200 — a 401, re-authentication, included — or // with a final other than 200 — a 401, re-authentication, included — or
// a fresh registration's protected REGISTER with a final other than 200 // a fresh registration's protected REGISTER with a final other than 200
@ -132,9 +131,9 @@ export namespace imsd::engine {
// refused or throttled fresh attempt, a terminated binding's probation // refused or throttled fresh attempt, a terminated binding's probation
// or its refusal schedule), which nothing cuts short — a // or its refusal schedule), which nothing cuts short — a
// restart of the process neither: the shell keeps the holds (Holds) // restart of the process neither: the shell keeps the holds (Holds)
// and hands them to the next one (Restore). The shell supplies the clock, what the network answered or did not and, // and hands them to the next one (Restore). The shell supplies the
// at a local wait, its kind (the kernel's refusal, the modem's word); this holds the deadlines and each kind's count, // clock and the network; this holds the deadlines and names the next
// and names the next step (Next) and when a sleeping phone is woken for it (WakeTime). Success resets everything. // step (Next). Success resets everything.
struct RegRecovery { struct RegRecovery {
enum class Failure { Refused, Silent, Throttled }; enum class Failure { Refused, Silent, Throttled };
enum class Step { Reconnect, Fresh }; enum class Step { Reconnect, Fresh };
@ -161,21 +160,6 @@ export namespace imsd::engine {
// untouched. Dev phone 2026-09-24: four such refusals in 26 s read // untouched. Dev phone 2026-09-24: four such refusals in 26 s read
// as two silent cycles cost a fresh registration into the throttle. // as two silent cycles cost a fresh registration into the throttle.
static constexpr double LocalRetry = 5; static constexpr double LocalRetry = 5;
// That pace is for a phone that is awake. A sleeping phone is woken
// for a look that follows such a wait after as long again as that
// kind of wait has lasted, within these bounds: seldom in a
// coverage gap of hours (counted from the modem's first word of no
// service since the network last answered: a modem that alternates
// at the edge of coverage shortens nothing), soon at first where
// the kernel refuses a connect (counted from its first refusal
// since the modem was last without service or the network last
// answered, whichever came later: a 4-tuple it still holds clears
// in awake seconds, TIME_WAIT's 60). A step that follows no
// local wait is woken for at the policy's own time,
// whatever went before.
static constexpr double LocalWakeMin = 10;
static constexpr double LocalWakeMax = 900;
enum class Local { NoService, Kernel };
int refusals = 0; int refusals = 0;
int silentCycles = 0; int silentCycles = 0;
@ -186,14 +170,10 @@ export namespace imsd::engine {
bool fresh = false; // the next registration attempt is a fresh one bool fresh = false; // the next registration attempt is a fresh one
bool oldGone = false; // the old registration is gone: nothing to reconnect over 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 bool terminated = false; // the network terminated our binding, and the policy has counted it
// the deadlines and a local wait's state, on the shell's clock // the deadlines, on the shell's clock
double backoffUntil = 0; // self-imposed: no step before this; a Dial clears it 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 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) 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 lastLocal = false; // the step that waits follows a local wait, not a counted failure
double gapSince = 0; // the modem's first word of no service since the network last answered (0: none)
double kernelSince = 0; // the kernel's first refusal of a connect since the modem was last without service or the network last answered (0: none)
double localWakeAt = 0; // when a sleeping phone is woken for the look after a local wait
bool Fresh() const { return fresh; } bool Fresh() const { return fresh; }
bool Reconnectable() const { return !oldGone; } bool Reconnectable() const { return !oldGone; }
@ -233,32 +213,7 @@ export namespace imsd::engine {
return {Step::Fresh, freshAt}; return {Step::Fresh, freshAt};
} }
void OnLocalRefusal(double now, Local kind = Local::Kernel) { void OnLocalRefusal(double now) { backoffUntil = now + LocalRetry; }
backoffUntil = now + LocalRetry;
lastLocal = true;
double since;
if (kind == Local::NoService) {
if (gapSince == 0) gapSince = now;
kernelSince = 0;
since = gapSince;
} else {
if (kernelSince == 0) kernelSince = now;
since = kernelSince;
}
localWakeAt = now + std::clamp(now - since, LocalWakeMin, LocalWakeMax);
}
bool LocalLook() const { return lastLocal; }
// The network has answered (the shell's word: an answered TCP
// connect of the resume or of a reconnect, a response to a
// REGISTER): it is in reach, and both counts start over.
void OnNetworkAnswered() { gapSince = 0; kernelSince = 0; }
// When a sleeping phone is to be awake for the next step: the
// step's own time, and after a local wait the slower look's, never
// before the step's own (a hold the network set).
double WakeTime(double now) const {
double at = Next(now).at;
return lastLocal ? std::max(at, localWakeAt) : at;
}
// A refused keepalive refresh, or a failed reconnect + refresh // A refused keepalive refresh, or a failed reconnect + refresh
// cycle; `status` is the refusal's. The backoff paces the next step; // cycle; `status` is the refusal's. The backoff paces the next step;
@ -268,8 +223,6 @@ export namespace imsd::engine {
// registration is due says the old registration is gone (KPN drops // registration is due says the old registration is gone (KPN drops
// it the moment an initial REGISTER arrives, throttled or not). // it the moment an initial REGISTER arrives, throttled or not).
void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) { void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) {
lastLocal = false; // a counted step waits now: woken for at its own time
if (f == Failure::Refused) OnNetworkAnswered(); // silence is no answer: the gap's count stands
if (retryAfter > 0) holdUntil = std::max(holdUntil, now + static_cast<double>(std::min(retryAfter, RetryAfterMax))); 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 // A cycle over a registration already known gone — the network
// terminated the binding while the cycle waited for its final — // terminated the binding while the cycle waited for its final —
@ -293,8 +246,6 @@ export namespace imsd::engine {
// it off 30 s → 10 min. A reconnect over the old SA meanwhile waits // it off 30 s → 10 min. A reconnect over the old SA meanwhile waits
// at least the reconnect backoff. // at least the reconnect backoff.
void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) { void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) {
lastLocal = false;
if (f != Failure::Silent) OnNetworkAnswered();
freshAttempts++; freshAttempts++;
fresh = true; fresh = true;
if (saReplaced) oldGone = true; if (saReplaced) oldGone = true;
@ -320,8 +271,6 @@ export namespace imsd::engine {
// reg-event dialog of the account carries it, a NOTIFY may be // reg-event dialog of the account carries it, a NOTIFY may be
// retransmitted), and never shortens a hold already running. // retransmitted), and never shortens a hold already running.
void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) { void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) {
lastLocal = false;
OnNetworkAnswered();
bool reported = terminated; bool reported = terminated;
terminated = true; terminated = true;
oldGone = true; oldGone = true;
@ -340,7 +289,7 @@ export namespace imsd::engine {
// The stored registration is not there to reconnect over (a resume // The stored registration is not there to reconnect over (a resume
// that failed at bring-up found its SAs unusable, or there are none). // that failed at bring-up found its SAs unusable, or there are none).
void OldGone() { oldGone = true; fresh = true; lastLocal = false; } void OldGone() { oldGone = true; fresh = true; }
// A user's Dial cuts the backoff short, never the network's word. // A user's Dial cuts the backoff short, never the network's word.
void OnDial() { backoffUntil = 0; } void OnDial() { backoffUntil = 0; }
@ -348,24 +297,6 @@ export namespace imsd::engine {
void OnSuccess() { *this = RegRecovery{}; } void OnSuccess() { *this = RegRecovery{}; }
}; };
// When the phone has to be awake for imsd, on the shell's clock (0:
// never): what the shell arms its wake alarm from. A time that is not
// later than now says the phone is to stay awake. The shell's loop arms the alarm for the time, and WakeHold
// ahead where the time is nearer than that: under an alarm that near the kernel refuses a suspend that reaches
// its check in time (the shell has the turns that arm it and what that takes). While imsd is busy with
// what counts awake seconds in its waits (a call, a text in flight) that
// is now. With a registration on a live flow it is the refresh's due
// time, or the reg-event subscription's renewal where that comes first
// (renewalDue 0: none is due). Without one it is the recovery policy's
// word (RegRecovery::WakeTime) where the shell has a step to run, a dead
// flow under a registration: a step that is due is now, whatever the
// policy's clock value for "now". And none where nothing waits to be done.
constexpr double WakeAt(double now, bool busy, bool liveFlow, double refreshDue, double renewalDue, bool recovering, double recoveryAt) {
if (busy) return now;
if (liveFlow) return renewalDue > 0 ? std::min(refreshDue, renewalDue) : refreshDue;
return recovering ? std::max(recoveryAt, now) : 0;
}
// Parsed SDP answer needed to bring up the media leg. `codec` is one of // 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). // imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play).
// `dtmfPt` is the telephone-event payload type at the codec's clock // `dtmfPt` is the telephone-event payload type at the codec's clock
@ -418,10 +349,6 @@ export namespace imsd::engine {
// imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants. // imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants.
inline constexpr double InviteTimeout = 90.0; inline constexpr double InviteTimeout = 90.0;
inline constexpr double Cancel487Timeout = 10.0; inline constexpr double Cancel487Timeout = 10.0;
// How often an INVITE goes out again for a 422 under one Call-ID
// (CallMachine::OnInviteResponse). RFC 4028 sets no number: this is
// imsd's bound for a path that names a larger minimum every time.
inline constexpr int MinSeAgainMax = 3;
// How long an unanswered incoming call may ring before we 480 it — a // How long an unanswered incoming call may ring before we 480 it — a
// safety net behind the network's own CANCEL, so generous. // safety net behind the network's own CANCEL, so generous.
inline constexpr double IncomingRingTimeout = 120.0; inline constexpr double IncomingRingTimeout = 120.0;
@ -499,23 +426,22 @@ export namespace imsd::engine {
return a; return a;
} }
// An outgoing call's current INVITE has been sent and has had no // The current outgoing attempt has sent its INVITE and has had no
// response, not a 100 either, and no CANCEL has followed it. // 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 // 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 // flow the network had forgotten is reset at the first bytes sent
// on it, and those may be this INVITE. // on it, and those may be this INVITE.
bool Unanswered() const { bool Unanswered() const {
return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_; return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_;
} }
// … and that INVITE has not gone out a second time over a reopened // … and the attempt has not been sent again yet.
// flow.
bool ResendDue() const { return Unanswered() && !resent_; } bool ResendDue() const { return Unanswered() && !resent_; }
// The shell reopened the flow under an INVITE whose resend is due: // The shell reopened the flow under an attempt whose resend is due:
// the same INVITE again, byte for byte (the same branch: RFC 3261 // 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 // 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 // its transaction), and the setup deadline from now. Once per
// INVITE: one that AgainWithMinSe sends has a resend of its own. // attempt.
std::vector<Action> OnFlowReopened() { std::vector<Action> OnFlowReopened() {
std::vector<Action> a; std::vector<Action> a;
if (!ResendDue()) return a; if (!ResendDue()) return a;
@ -526,7 +452,7 @@ export namespace imsd::engine {
return a; return a;
} }
// The flow under an unanswered INVITE is dead and stays so (it // The flow under an unanswered attempt is dead and stays so (it
// could not be reopened, or died again after the resend): the call // could not be reopened, or died again after the resend): the call
// ends here, an emergency call's first attempt too, with nothing to // ends here, an emergency call's first attempt too, with nothing to
// send a CANCEL on and no flow for a fallback attempt. // send a CANCEL on and no flow for a fallback attempt.
@ -603,17 +529,11 @@ export namespace imsd::engine {
return a; return a;
} }
// A response to an INVITE of ours (the shell has matched the Call-ID // A response to our INVITE (the shell already matched Call-ID + CSeq).
// and the method).
std::vector<Action> OnInviteResponse(std::string_view msg) { std::vector<Action> OnInviteResponse(std::string_view msg) {
std::vector<Action> a; std::vector<Action> a;
if (direction_ == Direction::Incoming) if (direction_ == Direction::Incoming)
return a; // a UAS has no INVITE transaction of its own return a; // a UAS has no INVITE transaction of its own
// An answer to an INVITE this call has since sent again under
// its Call-ID (AgainWithMinSe) is the replaced transaction's:
// the shell matches the Call-ID and the method, the sequence
// number is told apart here.
if (!imsd::sip::ResponseOf(msg, d_.callid, std::format("{} INVITE", d_.invCseq))) return a;
AbsorbDialog(msg); AbsorbDialog(msg);
auto st = imsd::sip::Status(msg); auto st = imsd::sip::Status(msg);
if (!st) return a; if (!st) return a;
@ -629,7 +549,7 @@ export namespace imsd::engine {
if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) { if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) {
pracked_.insert(std::string(*rseq)); pracked_.insert(std::string(*rseq));
std::array<std::string, 1> extra = { std::array<std::string, 1> extra = {
std::format("RAck: {} {} INVITE", *rseq, d_.invCseq)}; std::format("RAck: {} 1 INVITE", *rseq)};
a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra))); a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra)));
nextCseq_++; nextCseq_++;
} }
@ -662,24 +582,7 @@ export namespace imsd::engine {
} }
// non-2xx final // non-2xx final
a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or(""))))); a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or("")))));
std::string fin = std::format("INVITE final {}", code); std::string fin = WithReason(std::format("INVITE final {}", code), msg);
if (code == 422) {
// Session Interval Too Small: by RFC 4028 6 it carries the
// server's minimum in a Min-SE, and TS 24.229 5.1.2A.1.1 has
// a UE retry an INVITE so refused by RFC 4028 7.4. Only an
// INVITE that awaits its final (no CANCEL out, no answer
// taken), not for a Min-SE no larger than the one the
// refused INVITE carried, and not more than MinSeAgainMax
// times under one Call-ID.
const auto minSe = imsd::sip::MinSe(msg);
fin += minSe ? std::format(", Min-SE {}", *minSe) : std::string(", no Min-SE read");
const bool awaited = !cancelled_ && (state_ == CallState::Dialing || state_ == CallState::Ringing);
if (minSe && awaited && *minSe > d_.minSe && minSeAgain_ < MinSeAgainMax) {
Append(a, AgainWithMinSe(*minSe, WithReason(fin, msg)));
return a;
}
}
fin = WithReason(fin, msg);
if (auto sos = FallbackTo(code, msg)) { if (auto sos = FallbackTo(code, msg)) {
Append(a, Retry(*sos, fin)); Append(a, Retry(*sos, fin));
return a; return a;
@ -897,13 +800,12 @@ export namespace imsd::engine {
bool sosTried_ = false; bool sosTried_ = false;
bool plainTried_ = false; bool plainTried_ = false;
bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline
// The current INVITE as sent, whether any response to it has come, // The current outgoing attempt's INVITE as sent, whether any response
// and whether it went out a second time over a reopened flow // to it has come, and whether it went out a second time over a
// (OnFlowReopened). // reopened flow (OnFlowReopened).
std::string inviteOut_; std::string inviteOut_;
bool answered_ = false; bool answered_ = false;
bool resent_ = false; bool resent_ = false;
int minSeAgain_ = 0; // INVITEs sent again for a 422 under this Call-ID
std::set<std::string> pracked_; std::set<std::string> pracked_;
std::string answerSdp_; std::string answerSdp_;
std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start
@ -919,65 +821,23 @@ export namespace imsd::engine {
d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local); d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local);
d_.itag = rng_.Token(10); d_.itag = rng_.Token(10);
d_.invBranch = rng_.Token(20); d_.invBranch = rng_.Token(20);
NewTransaction(); nextCseq_ = 2;
cancelled_ = false;
userCancelled_ = false;
minSeAgain_ = 0;
}
// What each INVITE of an outgoing call starts from, a dialog's first
// (ResetDialog) and one sent again in it (AgainWithMinSe): the
// requests within the dialog numbered after it, no 18x PRACKed, no
// answer, no response to it and no resend of it.
void NewTransaction() {
nextCseq_ = d_.invCseq + 1;
pracked_.clear(); pracked_.clear();
answerSdp_.clear(); answerSdp_.clear();
cancelled_ = false;
userCancelled_ = false;
answered_ = false; answered_ = false;
resent_ = false; resent_ = false;
} }
// The INVITE a 422 refused, again (RFC 4028 7.3, 7.4): a new
// transaction of the same call. Its dialog keeps the request-URI,
// the Call-ID and our tag, takes the next sequence number the
// Call-ID has not carried (7.3 has "one higher than the previous":
// the one after the refused INVITE's, or, which is ours, the one
// after the last PRACK's where a PRACK followed that INVITE), a
// branch of its own and `minSe` as its Min-SE. Its session interval
// is the refused INVITE's, or `minSe` where that was smaller. What
// the refused transaction left (the refusal's To tag, a route, a
// target, and what NewTransaction clears) is not the new one's.
// Whether it is sent is the caller's (OnInviteResponse).
std::vector<Action> AgainWithMinSe(int minSe, std::string_view why) {
imsd::msg::Dialog next;
next.ruri = d_.ruri;
next.callid = d_.callid;
next.itag = d_.itag;
next.invBranch = rng_.Token(20);
next.invCseq = nextCseq_;
next.minSe = minSe;
next.sessionExpires = std::max(d_.sessionExpires, minSe);
d_ = std::move(next);
NewTransaction();
minSeAgain_++;
std::vector<Action> a;
a.push_back(LogAct(std::format("call {}: {} — the INVITE again with Session-Expires {}", uni_, why, d_.sessionExpires)));
if (state_ != CallState::Dialing) {
state_ = CallState::Dialing;
a.push_back(StateAct("outgoing"));
}
Append(a, Start());
return a;
}
// The emergency fallback chain — where the next attempt (if any) // The emergency fallback chain — where the next attempt (if any)
// points. `msg` may be empty (deadline paths). // points. `msg` may be empty (deadline paths).
// - asked after a sos attempt, it answers the dialled digits as a // - a sos INVITE that fails for any reason other than the user
// plain INVITE, unless the user hung up or the digits were tried // hanging up, its own send failing at the Dial (Fail) or the
// before that attempt (the 380's upgrade below): 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 // pre-emergency-support behavior, so classification can only improve
// on the status quo, never block a call the old code would have placed. // on the status quo, never block a call the old code would have placed.
// An end of a sos attempt that does not ask here brings no fallback.
// - a plain INVITE answered 380 Alternative Service whose body // - a plain INVITE answered 380 Alternative Service whose body
// names emergency (TS 24.229 5.1.6: the network classified a // 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 // number we didn't) is re-attempted as urn:service:sos. A 380

View file

@ -25,8 +25,7 @@ rules select — the policies carrying imsd's fingerprint and the reqid-1/2
transport-mode ESP states in their direction or on the UE's ims-PDN address, transport-mode ESP states in their direction or on the UE's ims-PDN address,
whoever installed them (§12); and `FileNamesAnotherPair`, whether a state whoever installed them (§12); and `FileNamesAnotherPair`, whether a state
file's spi_uc/spi_us name the pair the kernel holds (unknown on either side file's spi_uc/spi_us name the pair the kernel holds (unknown on either side
decides nothing). And `SaPaths` with `OnSaPath`: whether a packet runs on one decides nothing).
of the two paths the outbound policies of an SA pair select (§12).
Pure std C++ (the shell runs the commands and captures the text). Command Pure std C++ (the shell runs the commands and captures the text). Command
shapes and the parser are pinned by tests/Ipsec. shapes and the parser are pinned by tests/Ipsec.
@ -181,29 +180,6 @@ export namespace imsd::ipsec {
return cmds; return cmds;
} }
// The two paths the outbound policies of an SA pair select
// (BuildSetupCommands: reqid 1 from the UE's protected client port to
// the P-CSCF's server port, reqid 2 from its protected server port to the
// P-CSCF's client port), between the pair's two addresses. The shell
// keeps one of the pair it set up without an error or resumed; with no
// ports, none.
struct SaPaths {
std::string local; // the UE's address the pair is on
std::string pcscf; // the P-CSCF's
int portPs = 0;
int portPc = 0;
};
// Whether a packet from [fromHost]:fromPort to [toHost]:toPort runs on
// one of the two paths of `p`. Addresses are compared as
// imsd::util::CanonicalAddr writes them (an IPv6 address in its RFC 5952
// form).
inline bool OnSaPath(const SaPaths& p, std::string_view fromHost, int fromPort, std::string_view toHost, int toPort) {
const int theirs = fromPort == imsd::util::PortUc ? p.portPs : fromPort == imsd::util::PortUs ? p.portPc : 0;
return theirs != 0 && toPort == theirs && imsd::util::CanonicalAddr(fromHost) == imsd::util::CanonicalAddr(p.local) &&
imsd::util::CanonicalAddr(toHost) == imsd::util::CanonicalAddr(p.pcscf);
}
// ---- Security-Server (RFC 3329 §2.2) ----------------------------------- // ---- Security-Server (RFC 3329 §2.2) -----------------------------------
// //
// The P-CSCF answers the challenge with the mechanisms it supports, each // The P-CSCF answers the challenge with the mechanisms it supports, each

View file

@ -5,11 +5,9 @@
Imsd:Messages — the SIP request/response text the engine puts on the wire. Imsd:Messages — the SIP request/response text the engine puts on the wire.
Every VoLTE message the daemon sends is assembled here from an explicit Every VoLTE message the daemon sends is assembled here from an explicit
context and the per-request variables so the builders context and the per-request variables (tags, branches, CSeq) so the builders
are pure functions with no hidden state: the engine owns the dialog bookkeeping are pure functions with no hidden state: the engine owns the dialog bookkeeping
and the transport owns the socket (and takes the P-Access-Network-Info line and the transport owns the socket, this module only formats bytes. That makes
out of an answer the server ports send on neither path of the SA pair on
record), this module only formats bytes. That makes
each message byte-pinnable — tests/Messages compares a REGISTER pair and an INVITE each message byte-pinnable — tests/Messages compares a REGISTER pair and an INVITE
with strings cross-generated from the Python reference stack, header for header with strings cross-generated from the Python reference stack, header for header
but for the divergences that suite's header names. but for the divergences that suite's header names.
@ -79,13 +77,7 @@ export namespace imsd::msg {
// P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli // P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli
// location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header — // location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header —
// never fabricate one: the network reads it to learn which access // never fabricate one: the network reads it to learn which access
// the UE is reachable on. // the UE is reachable on (stock sends it in every REGISTER/INVITE).
// It rides in every request but the ACKs and the CANCEL and in every
// response but a 100 Trying, a CANCEL's and BuildBadRequest's 400:
// by TS 24.229 5.1.2A.1.1 and 5.1.2A.2 for a request within a
// dialog and for the three kinds of response detail::AccessInfo
// names (the 100 and the 400 are left out by imsd's choice), by RFC
// 7315 5.7 for the ACKs and the CANCEL.
std::string panInfo; std::string panInfo;
// Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS // Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS
// 24.341 5.3.2.2): the network then delivers terminating short // 24.341 5.3.2.2): the network then delivers terminating short
@ -232,18 +224,6 @@ export namespace imsd::msg {
} }
return s; return s;
} }
// The P-Access-Network-Info line of a response with status `code`
// to `request`, where the serving cell is known: TS 24.229
// 5.1.2A.1.1 and 5.1.2A.2 have a UE insert the header into every
// response it sends within a dialog, to a request for a dialog and
// to a standalone method, those to a CANCEL excepted. A 100 Trying
// gets none, by imsd's choice: a stateful proxy never forwards it
// (RFC 3261 21.1.1; AGENTS.md §7.6).
inline void AccessInfo(std::vector<std::string>& l, const Context& c, std::string_view request, int code) {
if (c.panInfo.empty() || code == 100 || request.starts_with("CANCEL ")) return;
l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo));
}
} }
// ---- REGISTER ------------------------------------------------------- // ---- REGISTER -------------------------------------------------------
@ -353,7 +333,7 @@ export namespace imsd::msg {
// ---- call dialog ---------------------------------------------------- // ---- call dialog ----------------------------------------------------
// A dialog as the engine keeps it. // The dialog identity + routing the engine accumulates for one call.
// For an outgoing call itag is our From tag and dialogTo is learned from // For an outgoing call itag is our From tag and dialogTo is learned from
// the responses; for an incoming call itag is the To tag we mint, // the responses; for an incoming call itag is the To tag we mint,
// dialogTo is the caller's From, and both feed BuildInDialog identically // dialogTo is the caller's From, and both feed BuildInDialog identically
@ -368,12 +348,6 @@ export namespace imsd::msg {
std::optional<std::string> remoteTarget; // remote Contact URI std::optional<std::string> remoteTarget; // remote Contact URI
std::string localUri; // our URI in this dialog: the UAS takes the std::string localUri; // our URI in this dialog: the UAS takes the
// INVITE's To URI; empty = CallerId(c) (UAC) // INVITE's To URI; empty = CallerId(c) (UAC)
int invCseq = 1; // our INVITE's sequence number: its CANCEL
// and its ACK carry it, a PRACK's RAck
// names it
int sessionExpires = 1800; // the session interval our INVITE asks for
// (RFC 4028 4), in seconds
int minSe = 90; // the Min-SE our INVITE carries (RFC 4028 5)
}; };
// The identity we sign our own requests with: the registered public // The identity we sign our own requests with: the registered public
@ -408,8 +382,7 @@ export namespace imsd::msg {
} }
// INVITE with an AMR-WB SDP offer (passed in, built by Imsd:Sdp). MMTEL // INVITE with an AMR-WB SDP offer (passed in, built by Imsd:Sdp). MMTEL
// ICSI feature tags + sec-agree + session timers, as imsd._send_invite; the // ICSI feature tags + sec-agree + session timers, exactly as imsd._send_invite.
// sequence number, the session interval and its minimum are the dialog's.
std::string BuildInvite(const Context& c, const Dialog& d, std::string_view sdp, bool precond) { std::string BuildInvite(const Context& c, const Dialog& d, std::string_view sdp, bool precond) {
std::string supported = precond ? "100rel, timer, precondition" std::string supported = precond ? "100rel, timer, precondition"
: "100rel, timer"; : "100rel, timer";
@ -421,7 +394,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: <{}>", d.ruri), std::format("To: <{}>", d.ruri),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
std::format("CSeq: {} INVITE", d.invCseq), "CSeq: 1 INVITE",
std::format("Contact: <sip:{}@{}>;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)), std::format("Contact: <sip:{}@{}>;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)),
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER", "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER",
std::format("Supported: {}", supported), std::format("Supported: {}", supported),
@ -433,8 +406,8 @@ export namespace imsd::msg {
l.push_back(std::format("Security-Verify: {}", c.securityServer)); l.push_back(std::format("Security-Verify: {}", c.securityServer));
l.push_back("Proxy-Require: sec-agree"); l.push_back("Proxy-Require: sec-agree");
l.push_back("Require: sec-agree"); l.push_back("Require: sec-agree");
l.push_back(std::format("Session-Expires: {};refresher=uac", d.sessionExpires)); l.push_back("Session-Expires: 1800;refresher=uac");
l.push_back(std::format("Min-SE: {}", d.minSe)); l.push_back("Min-SE: 90");
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");
l.push_back(std::format("Content-Length: {}", sdp.size())); l.push_back(std::format("Content-Length: {}", sdp.size()));
l.push_back(""); l.push_back("");
@ -443,9 +416,6 @@ export namespace imsd::msg {
// An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set. // An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set.
// `extra` lines go after CSeq; an optional body sets Content-Type/Length. // `extra` lines go after CSeq; an optional body sets Content-Type/Length.
// P-Access-Network-Info as in the INVITE (TS 24.229 5.1.2A.1.1,
// 5.1.2A.2); the ACKs and the CANCEL, built below, carry none (RFC 7315
// 5.7: the header appears in no ACK and no CANCEL).
std::string BuildInDialog(const Context& c, const Dialog& d, std::string_view method, int cseq, std::string_view viaBranch, std::span<const std::string> extra = {}, std::string_view body = {}, std::string_view ctype = {}) { std::string BuildInDialog(const Context& c, const Dialog& d, std::string_view method, int cseq, std::string_view viaBranch, std::span<const std::string> extra = {}, std::string_view body = {}, std::string_view ctype = {}) {
std::string target = d.remoteTarget.value_or(d.ruri); std::string target = d.remoteTarget.value_or(d.ruri);
std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri)); std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri));
@ -461,7 +431,6 @@ export namespace imsd::msg {
}; };
for (const std::string& e : extra) for (const std::string& e : extra)
l.push_back(e); l.push_back(e);
if (!c.panInfo.empty()) l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo));
if (!body.empty()) { if (!body.empty()) {
l.push_back(std::format("Content-Type: {}", ctype)); l.push_back(std::format("Content-Type: {}", ctype));
l.push_back(std::format("Content-Length: {}", body.size())); l.push_back(std::format("Content-Length: {}", body.size()));
@ -485,7 +454,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: {}", to), std::format("To: {}", to),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
std::format("CSeq: {} ACK", d.invCseq), "CSeq: 1 ACK",
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -502,7 +471,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: {}", toHeader), std::format("To: {}", toHeader),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
std::format("CSeq: {} ACK", d.invCseq), "CSeq: 1 ACK",
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -518,7 +487,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: <{}>", d.ruri), std::format("To: <{}>", d.ruri),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
std::format("CSeq: {} CANCEL", d.invCseq), "CSeq: 1 CANCEL",
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -532,8 +501,7 @@ export namespace imsd::msg {
// half by tagging To (all but 100 Trying, which is hop-by-hop and // half by tagging To (all but 100 Trying, which is hop-by-hop and
// tagless). 1xx/2xx carry our Contact (the dialog's remote target for the // tagless). 1xx/2xx carry our Contact (the dialog's remote target for the
// caller) and Allow; `extra` appends headers (RSeq, Session-Expires...); // caller) and Allow; `extra` appends headers (RSeq, Session-Expires...);
// P-Access-Network-Info follows them where the cell is known, in all // `sdp` turns a 200 into the answer.
// but a 100; `sdp` turns a 200 into the answer.
std::string BuildInviteResponse(const Context& c, std::string_view invite, int code, std::string_view text, std::string_view toTag, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) { std::string BuildInviteResponse(const Context& c, std::string_view invite, int code, std::string_view text, std::string_view toTag, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)}; std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
for (auto v : imsd::sip::Headers(invite, "Via")) for (auto v : imsd::sip::Headers(invite, "Via"))
@ -555,7 +523,6 @@ export namespace imsd::msg {
} }
for (const std::string& e : extra) for (const std::string& e : extra)
l.push_back(e); l.push_back(e);
detail::AccessInfo(l, c, invite, code);
if (sdp) { if (sdp) {
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");
l.push_back(std::format("Content-Length: {}", sdp->size())); l.push_back(std::format("Content-Length: {}", sdp->size()));
@ -570,12 +537,10 @@ export namespace imsd::msg {
// 488 to one we did not: each Via row echoed in order (RFC 3261 // 488 to one we did not: each Via row echoed in order (RFC 3261
// 8.2.6.2), From, To with // 8.2.6.2), From, To with
// `toTag` added unless the request's To holds `tag=` (8.2.6.2 again), // `toTag` added unless the request's To holds `tag=` (8.2.6.2 again),
// Call-ID and CSeq, then P-Access-Network-Info where the cell is known; // Call-ID and CSeq; no body. The shell's answers to any other request
// no body. The shell's answers to any other request
// outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does // outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does
// not handle) keep BuildResponse200's hop-by-hop shape, as before, // not handle) keep BuildResponse200's hop-by-hop shape, as before.
// unless the request is cut short: BuildBadRequest's 400 has this one. std::string BuildResponse(const Context&, std::string_view request, int code, std::string_view text, std::string_view toTag) {
std::string BuildResponse(const Context& c, std::string_view request, int code, std::string_view text, std::string_view toTag) {
std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)}; std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
for (auto v : imsd::sip::Headers(request, "Via")) l.push_back(std::format("Via: {}", v)); for (auto v : imsd::sip::Headers(request, "Via")) l.push_back(std::format("Via: {}", v));
if (auto f = imsd::sip::Header(request, "From")) l.push_back(std::format("From: {}", *f)); if (auto f = imsd::sip::Header(request, "From")) l.push_back(std::format("From: {}", *f));
@ -585,7 +550,6 @@ export namespace imsd::msg {
} }
if (auto ci = imsd::sip::Header(request, "Call-ID")) l.push_back(std::format("Call-ID: {}", *ci)); if (auto ci = imsd::sip::Header(request, "Call-ID")) l.push_back(std::format("Call-ID: {}", *ci));
if (auto cs = imsd::sip::Header(request, "CSeq")) l.push_back(std::format("CSeq: {}", *cs)); if (auto cs = imsd::sip::Header(request, "CSeq")) l.push_back(std::format("CSeq: {}", *cs));
detail::AccessInfo(l, c, request, code);
l.push_back("Content-Length: 0"); l.push_back("Content-Length: 0");
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
} }
@ -593,30 +557,25 @@ export namespace imsd::msg {
// The 400 to a request whose datagram ended before its body did (RFC // The 400 to a request whose datagram ended before its body did (RFC
// 3261 18.3), from the request's header section // 3261 18.3), from the request's header section
// (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd // (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd
// keeps nothing of such a request, so the tag it adds to a To that holds // keeps nothing of such a request, so the To tag is made from the
// none is made from the request itself, "in a manner that will generate // request itself, "in a manner that will generate the same tag for the
// the same tag for the same request consistently" (8.2.7), and from // same request consistently" (8.2.7), and from `secret`, which the
// `secret`, which the
// caller draws once for the run: the randomness 19.3 asks of a tag. It // caller draws once for the run: the randomness 19.3 asks of a tag. It
// is the first sixteen hex digits of the MD5 of the secret and that // is the first sixteen hex digits of the MD5 of the secret and that
// header section. The transport answers with it, without the // header section.
// registration's context: it carries no P-Access-Network-Info.
std::string BuildBadRequest(std::string_view head, std::string_view secret) { std::string BuildBadRequest(std::string_view head, std::string_view secret) {
return BuildResponse({}, head, 400, "Bad Request", imsd::util::Md5::HexDigest(std::format("{}{}", secret, head)).substr(0, 16)); return BuildResponse({}, head, 400, "Bad Request", imsd::util::Md5::HexDigest(std::format("{}{}", secret, head)).substr(0, 16));
} }
// A 200 OK for an inbound request: echo Via/From/To/Call-ID/CSeq in order, // A 200 OK for an inbound request: echo Via/From/To/Call-ID/CSeq in order,
// then either an SDP answer (with our Contact) or an empty body. // then either an SDP answer (with our Contact) or an empty body.
// `extra` appends headers (Session-Expires echo for refreshes...), and // `extra` appends headers (Session-Expires echo for refreshes...).
// P-Access-Network-Info follows them where the cell is known, unless
// the request is a CANCEL.
std::string BuildResponse200(const Context& c, std::string_view request, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) { std::string BuildResponse200(const Context& c, std::string_view request, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
std::vector<std::string> l = {"SIP/2.0 200 OK"}; std::vector<std::string> l = {"SIP/2.0 200 OK"};
for (std::string_view h : {"Via", "From", "To", "Call-ID", "CSeq"}) for (std::string_view h : {"Via", "From", "To", "Call-ID", "CSeq"})
if (auto v = imsd::sip::Header(request, h)) l.push_back(std::format("{}: {}", h, *v)); if (auto v = imsd::sip::Header(request, h)) l.push_back(std::format("{}: {}", h, *v));
for (const auto& e : extra) for (const auto& e : extra)
l.push_back(e); l.push_back(e);
detail::AccessInfo(l, c, request, 200);
if (sdp) { if (sdp) {
l.push_back(std::format("Contact: <sip:{}@{}>", ContactUser(c), imsd::util::HostPort(c.local, c.portUs))); l.push_back(std::format("Contact: <sip:{}@{}>", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)));
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");

View file

@ -6,8 +6,8 @@ Imsd:Sip — SIP message text layer + TCP framing.
Deliberately a text layer, not a full RFC 3261 parser: the engine works on Deliberately a text layer, not a full RFC 3261 parser: the engine works on
whole messages as strings and pulls out exactly what it needs (headers, whole messages as strings and pulls out exactly what it needs (headers,
status codes, the granted registration lifetime, the interval a Min-SE status codes, the granted registration lifetime), which keeps every message
names), which keeps every message loggable and testable as text. A header is asked for by its long name and loggable and testable as text. A header is asked for by its long name and
found under that or its compact form (RFC 3261 7.3.3). Edge-case behavior found under that or its compact form (RFC 3261 7.3.3). Edge-case behavior
(empty header values, line anchoring, white space before the colon, (empty header values, line anchoring, white space before the colon,
keepalive discards) is pinned by tests/Sip — a change that flips one of keepalive discards) is pinned by tests/Sip — a change that flips one of
@ -193,26 +193,6 @@ export namespace imsd::sip {
return out; return out;
} }
// `msg` without its `name:` header lines: every line of the header
// section on which Headers would find the name, long or compact
// (MatchHeaderLine), is left out, and the other lines and the body stay
// as they are. For P-Access-Network-Info as the builders write it, one
// line with its value, that is the header whole.
std::string WithoutHeader(std::string_view msg, std::string_view name) {
std::string out;
std::size_t kept = 0;
ForEachLine(msg, [&](std::string_view line) {
if (MatchHeaderLine(line, name)) {
const auto at = static_cast<std::size_t>(line.data() - msg.data());
out += msg.substr(kept, at - kept);
kept = std::min(at + line.size() + 1, msg.size());
}
return true;
});
out += msg.substr(kept);
return out;
}
// The 3-digit code of a "SIP/2.0 NNN ..." response start-line; nullopt // The 3-digit code of a "SIP/2.0 NNN ..." response start-line; nullopt
// for requests / anything else. Only matches at the start of the message. // for requests / anything else. Only matches at the start of the message.
std::optional<int> Status(std::string_view msg) { std::optional<int> Status(std::string_view msg) {
@ -248,18 +228,6 @@ export namespace imsd::sip {
return LeadingDigits(*v); return LeadingDigits(*v);
} }
// The interval a message's Min-SE names (RFC 4028 5: delta-seconds,
// then parameters), in seconds: the number its value's leading digits
// spell, zeros before it aside. nullopt when the header is absent, its
// value begins with no digit, or the number has more than nine digits.
std::optional<int> MinSe(std::string_view msg) {
auto v = Header(msg, "Min-SE");
if (!v) return std::nullopt;
const auto n = LeadingDigits(*v);
if (!n || *n > 999'999'999) return std::nullopt;
return static_cast<int>(*n);
}
// A refused final for the journal: its status line, then the headers // A refused final for the journal: its status line, then the headers
// that say who refused and for how long — Retry-After (RFC 3261 20.33), // that say who refused and for how long — Retry-After (RFC 3261 20.33),
// Warning (20.43: the node's own words), Reason (RFC 3326), Server // Warning (20.43: the node's own words), Reason (RFC 3326), Server

View file

@ -215,7 +215,8 @@ int main() {
{ {
// P-Access-Network-Info from `mmcli --location-get` (real-device // P-Access-Network-Info from `mmcli --location-get` (real-device
// output shape; TAC/CI zero-padded wider than the 4/7 hex digits // output shape; TAC/CI zero-padded wider than the 4/7 hex digits
// PANI uses). Values here are synthetic. // PANI uses). The mcc+mnc+TAC+ECI concatenation was validated
// against a stock modem's on-wire PANI; values here are synthetic.
constexpr std::string_view Loc = constexpr std::string_view Loc =
" --------------------------\n" " --------------------------\n"
" 3GPP | operator mcc: 001\n" " 3GPP | operator mcc: 001\n"

View file

@ -4,9 +4,7 @@
// Imsd:Engine unit tests — the call state machine driven through recorded // Imsd:Engine unit tests — the call state machine driven through recorded
// network dialogs. Outgoing: reliable-18x PRACK, 2xx ACK + media start, // network dialogs. Outgoing: reliable-18x PRACK, 2xx ACK + media start,
// media-plane far-end hangup, local hang-up (CANCEL before answer, BYE // media-plane far-end hangup, local hang-up (CANCEL before answer, BYE
// after), the CANCEL/answer race, busy/error finals, and an INVITE refused // after), the CANCEL/answer race, and busy/error finals. Incoming: 100+180
// 422 sent again with the Min-SE the refusal names (the same call, the next
// sequence number; when it is not sent again). Incoming: 100+180
// on the INVITE (reliable when the caller requires 100rel), Accept -> 200 // on the INVITE (reliable when the caller requires 100rel), Accept -> 200
// with the SDP answer at the offer's payload types + media, ACK silence, // with the SDP answer at the offer's payload types + media, ACK silence,
// reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming // reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming
@ -14,11 +12,7 @@
// ring and are answered at the offer's own payload types, ring timeout -> // ring and are answered at the offer's own payload types, ring timeout ->
// 480, BYE both ways; an incoming call from an INVITE, and an outgoing // 480, BYE both ways; an incoming call from an INVITE, and an outgoing
// call from responses, whose header names come in compact form (RFC 3261 // call from responses, whose header names come in compact form (RFC 3261
// 7.3.3); which of a call's messages carry P-Access-Network-Info where // 7.3.3). DTMF: the tones reach the media leg on an active
// the cell is known (its 180, its 200s but the one to a CANCEL, a 486
// and a 487, PRACK and BYE) and which do not (the 100 Trying, the 200 to
// a CANCEL, the ACKs, the CANCEL). DTMF: the tones reach the media leg
// on an active
// call that negotiated telephone-event, and are dropped — with the reason // call that negotiated telephone-event, and are dropped — with the reason
// — before the answer, after the call, without the negotiation or with a // — before the answer, after the call, without the negotiation or with a
// character that is no tone. Then RegRecovery, the registration recovery policy: // character that is no tone. Then RegRecovery, the registration recovery policy:
@ -26,9 +20,7 @@
// fresh backoffs, the throttle schedule, Retry-After, which waits a Dial // fresh backoffs, the throttle schedule, Retry-After, which waits a Dial
// may cut short, when the old registration counts as gone, the holds a // may cut short, when the old registration counts as gone, the holds a
// restart takes over (Holds/Restore), and a binding the network terminated // restart takes over (Holds/Restore), and a binding the network terminated
// (OnBindingTerminated). Then WakeAt, when the phone has to be awake for // (OnBindingTerminated). Then SMS over IP: the status-report book
// imsd, and the policy's wake after a local wait (WakeTime). Then SMS
// over IP: the status-report book
// (StatusReportBook with SameRecipient — a word for the whole message: a two-segment // (StatusReportBook with SameRecipient — a word for the whole message: a two-segment
// message delivered with its last segment, a permanent failure the last // message delivered with its last segment, a permanent failure the last
// word, pending kept, another recipient no match, a reused TP-MR, a // word, pending kept, another recipient no match, a reused TP-MR, a
@ -102,9 +94,8 @@ namespace {
return nullptr; return nullptr;
} }
// Build a response with the machine's own Call-ID and its INVITE's first // Build a response with the machine's own Call-ID (so dialog matching in a
// sequence number: the shell matches the Call-ID and the method, the // real shell would hold; the reducer itself doesn't re-check).
// reducer the transaction (Cseq below gives a response another number).
std::string R183(std::string_view callid) { std::string R183(std::string_view callid) {
return std::format( return std::format(
"SIP/2.0 183 Session Progress\r\n" "SIP/2.0 183 Session Progress\r\n"
@ -161,30 +152,6 @@ namespace {
code, text, callid); code, text, callid);
} }
// A 422 to the INVITE numbered `cseq`; `minSe` is its Min-SE header's
// value, empty for a 422 without the header.
std::string R422(std::string_view callid, int cseq, std::string_view minSe) {
return std::format(
"SIP/2.0 422 Session Interval Too Small\r\n"
"Via: SIP/2.0/TCP [2001:db8::db43]:45061;branch=z9hG4bKx\r\n"
"From: <sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>;tag=it\r\n"
"To: <sip:1233@ims>;tag=refused1\r\n"
"Call-ID: {}\r\nCSeq: {} INVITE\r\n{}Content-Length: 0\r\n\r\n",
callid, cseq, minSe.empty() ? std::string() : std::format("Min-SE: {}\r\n", minSe));
}
// One of the responses above as an answer to the INVITE numbered `n`.
std::string Cseq(std::string msg, int n) {
const std::string_view one = "CSeq: 1 INVITE\r\n";
msg.replace(msg.find(one), one.size(), std::format("CSeq: {} INVITE\r\n", n));
return msg;
}
// The Log action whose text holds `part`.
const Action* Logged(const std::vector<Action>& a, std::string_view part) {
for (const auto& x : a)
if (x.type == Action::Type::Log && x.text.contains(part)) return &x;
return nullptr;
}
// First SendResponse whose text starts with `prefix`. // First SendResponse whose text starts with `prefix`.
const Action* Responded(const std::vector<Action>& a, std::string_view prefix) { const Action* Responded(const std::vector<Action>& a, std::string_view prefix) {
for (const auto& x : a) for (const auto& x : a)
@ -504,7 +471,7 @@ int main() {
} }
// ---- the client flow dies before any response to the INVITE: the shell // ---- the client flow dies before any response to the INVITE: the shell
// reopens it and the same INVITE goes out again, once per INVITE // reopens it and the same INVITE goes out again, once per attempt
{ {
imsd::util::Rng rng(16); imsd::util::Rng rng(16);
CallMachine m(c, rng, "ims-call-6b", "1233", 50004, false); CallMachine m(c, rng, "ims-call-6b", "1233", 50004, false);
@ -518,7 +485,7 @@ int main() {
const Action* dl = Find(again, Action::Type::SetDeadline); const Action* dl = Find(again, Action::Type::SetDeadline);
Check(dl && dl->seconds == imsd::engine::InviteTimeout, "the resend arms the setup deadline anew"); Check(dl && dl->seconds == imsd::engine::InviteTimeout, "the resend arms the setup deadline anew");
Check(m.State() == CallState::Dialing && !m.Terminated(), "still dialing after the resend"); Check(m.State() == CallState::Dialing && !m.Terminated(), "still dialing after the resend");
Check(m.Unanswered() && !m.ResendDue(), "one resend per INVITE"); Check(m.Unanswered() && !m.ResendDue(), "one resend per attempt");
Check(m.OnFlowReopened().empty(), "a second reopen sends nothing"); Check(m.OnFlowReopened().empty(), "a second reopen sends nothing");
auto lost = m.OnFlowLost(); auto lost = m.OnFlowLost();
const Action* t = Find(lost, Action::Type::State); const Action* t = Find(lost, Action::Type::State);
@ -921,67 +888,6 @@ int main() {
Check(m.Terminated(), "terminated"); Check(m.Terminated(), "terminated");
} }
// ---- P-Access-Network-Info through a call's life, where the cell is
// known: in the 180, the 200s but a CANCEL's, a 486 and a 487, and
// in PRACK and BYE; in no 100 Trying, no ACK and no CANCEL
{
Context k = MakeCtx();
k.panInfo = "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0";
const auto with = [](const Action* a) { return a && a->text.contains("\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"); };
const auto without = [](const Action* a) { return a && !a->text.contains("P-Access-Network-Info"); };
const auto inDialog = [](std::string_view method, std::string_view callid, std::string_view extra = "") {
return std::format(
"{} sip:001010123456789@[2001:db8::db43]:45061 SIP/2.0\r\n"
"Via: SIP/2.0/UDP [2001:db8::105]:5100;branch=z9hG4bKpcscf9\r\n"
"From: <sip:+31612345678@ims;user=phone>;tag=caller1\r\n"
"To: <sip:+31611111111@ims;user=phone>;tag=ours\r\n"
"Call-ID: {}\r\nCSeq: 2 {}\r\n{}Content-Length: 0\r\n\r\n", method, callid, method, extra);
};
{
// an incoming call its caller cancels
imsd::util::Rng rng(71);
CallMachine m(k, rng, "ims-call-80", IncomingInvite{MtInvite("Require: 100rel\r\n")}, 50004);
auto ai = m.OnInvite();
Check(with(Responded(ai, "SIP/2.0 180 Ringing")) && without(Responded(ai, "SIP/2.0 100 Trying")), "a cell known: the 180 to an incoming INVITE carries P-Access-Network-Info, its 100 Trying does not");
Check(with(Responded(m.OnRequest(inDialog("PRACK", m.CallId(), "RAck: 1 1 INVITE\r\n")), "SIP/2.0 200 OK")), "... and the 200 to the PRACK of that 180");
auto ac = m.OnRequest(inDialog("CANCEL", m.CallId()));
Check(without(Responded(ac, "SIP/2.0 200 OK")) && with(Responded(ac, "SIP/2.0 487 Request Terminated")), "... the 200 to a CANCEL does not, the INVITE's 487 does");
}
{
// an incoming call answered, then refreshed and ended from the far side
imsd::util::Rng rng(72);
CallMachine m(k, rng, "ims-call-81", IncomingInvite{MtInvite()}, 50004);
m.OnInvite();
Check(with(Responded(m.OnAccept(), "SIP/2.0 200 OK")), "... the 200 that answers the call");
Check(with(Responded(m.OnRequest(inDialog("UPDATE", m.CallId(), "Session-Expires: 1800;refresher=uac\r\n")), "SIP/2.0 200 OK")), "... the 200 to a session refresh");
Check(with(Responded(m.OnRequest(inDialog("BYE", m.CallId())), "SIP/2.0 200 OK")), "... and the 200 to the far side's BYE");
}
{
// an incoming call refused, and one answered and ended here
imsd::util::Rng rng(73);
CallMachine m(k, rng, "ims-call-82", IncomingInvite{MtInvite()}, 50004);
m.OnInvite();
Check(with(Responded(m.OnHangup(), "SIP/2.0 486 Busy Here")), "... a 486");
CallMachine n(k, rng, "ims-call-83", IncomingInvite{MtInvite()}, 50004);
n.OnInvite();
n.OnAccept();
Check(with(Sent(n.OnHangup(), "BYE ")), "... our BYE on a call that came in");
}
{
// a call we place: its PRACK and its BYE carry it, its ACKs and its CANCEL do not
imsd::util::Rng rng(74);
CallMachine m(k, rng, "ims-call-84", "1233", 50004, false);
m.Start();
Check(with(Sent(m.OnInviteResponse(R183(m.CallId())), "PRACK ")), "... the PRACK of a call we place");
Check(without(Sent(m.OnInviteResponse(R200(m.CallId())), "ACK ")), "... not the ACK of its 200");
Check(with(Sent(m.OnHangup(), "BYE ")), "... its BYE");
CallMachine n(k, rng, "ims-call-85", "1233", 50004, false);
n.Start();
Check(without(Sent(n.OnHangup(), "CANCEL ")), "... not a CANCEL");
Check(without(Sent(n.OnInviteResponse(Final(n.CallId(), 487, "Request Terminated")), "ACK ")), "... and not the ACK of a refusal");
}
}
// ================= emergency (stage 1) ================================ // ================= emergency (stage 1) ================================
// ---- emergency dial: the INVITE targets the sos URN over the normal // ---- emergency dial: the INVITE targets the sos URN over the normal
@ -1061,248 +967,6 @@ int main() {
Check(m.Terminated(), "terminated when the chain is exhausted"); Check(m.Terminated(), "terminated when the chain is exhausted");
} }
// ---- a 422 that names a larger Min-SE: the INVITE again in the same
// call (RFC 4028 7.3, 7.4; TS 24.229 5.1.2A.1.1), then answered
{
imsd::util::Rng rng(61);
CallMachine m(c, rng, "ims-call-40", "1233", 50004, false);
auto start = m.Start();
const Action* inv1 = Sent(start, "INVITE ");
Check(inv1 && inv1->text.contains("\r\nCSeq: 1 INVITE\r\n") && inv1->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 90\r\n"), "the first INVITE asks for 1800 s with a Min-SE of 90");
const std::string id = m.CallId();
m.OnInviteResponse(Final(id, 100, "Trying"));
auto a = m.OnInviteResponse(R422(id, 1, "3600"));
const Action* ack = Sent(a, "ACK ");
Check(ack && ack->text.contains("\r\nCSeq: 1 ACK\r\n") && ack->text.contains("\r\nTo: <sip:1233@ims>;tag=refused1\r\n"), "the 422 is ACKed in its own transaction, with its To");
Check(ack && inv1 && imsd::sip::Header(ack->text, "Via") == imsd::sip::Header(inv1->text, "Via"), "... over the refused INVITE's branch");
const Action* inv2 = Sent(a, "INVITE ");
Check(inv2 && m.CallId() == id && inv2->text.contains(std::format("\r\nCall-ID: {}\r\n", id)), "the INVITE goes out again under the same Call-ID");
Check(inv2 && inv2->text.contains("\r\nCSeq: 2 INVITE\r\n"), "... with the next sequence number");
Check(inv2 && inv1 && inv2->text.substr(0, inv2->text.find("\r\n")) == inv1->text.substr(0, inv1->text.find("\r\n")), "... the same request line");
Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "From") == imsd::sip::Header(inv1->text, "From"), "... the same From and tag");
Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "To") == imsd::sip::Header(inv1->text, "To"), "... the same To");
Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "Via") != imsd::sip::Header(inv1->text, "Via"), "... a branch of its own");
Check(inv2 && inv2->text.contains("\r\nSession-Expires: 3600;refresher=uac\r\nMin-SE: 3600\r\n"), "... the 422's Min-SE as its Min-SE and as its session interval");
const Action* log = Find(a, Action::Type::Log);
Check(log && log->text == "call ims-call-40: INVITE final 422, Min-SE 3600 — the INVITE again with Session-Expires 3600", "the journal names the minimum and the interval sent");
Check(Has(a, Action::Type::SetDeadline) && !Has(a, Action::Type::State) && m.State() == CallState::Dialing && !m.Terminated(), "the call goes on dialing, its timeout armed again, no state announced");
Check(m.Unanswered() && m.ResendDue(), "the INVITE sent again has had no response and has a resend of its own");
// an answer of the replaced transaction is not this one's
Check(m.OnInviteResponse(R422(id, 1, "7200")).empty() && m.OnInviteResponse(R200(id)).empty() && m.OnInviteResponse(R183(id)).empty() && m.State() == CallState::Dialing && m.Unanswered(), "an answer with the replaced INVITE's number is dropped");
// the second INVITE's own answers
auto a183 = m.OnInviteResponse(Cseq(R183(id), 2));
const Action* prack = Sent(a183, "PRACK ");
Check(prack && prack->text.contains("RAck: 1 2 INVITE\r\n") && prack->text.contains("CSeq: 3 PRACK\r\n"), "the PRACK names the second INVITE and takes the number after it");
Check(prack && prack->text.contains("\r\nTo: <sip:1233@ims>;tag=remote7\r\n"), "... in the dialog the second INVITE's 183 made");
auto a200 = m.OnInviteResponse(Cseq(R200(id), 2));
const Action* ack2 = Sent(a200, "ACK ");
Check(ack2 && ack2->text.contains("\r\nCSeq: 2 ACK\r\n") && Has(a200, Action::Type::StartMedia) && m.State() == CallState::Active, "the second INVITE's 200 is ACKed with its number and the call is active");
}
// ---- the flow dies under the INVITE sent again: the shell reopens it
// and that INVITE goes out once more, byte for byte; a flow that
// dies again ends the call
{
imsd::util::Rng rng(79);
CallMachine m(c, rng, "ims-call-53", "1233", 50004, false);
auto start = m.Start();
const Action* inv1 = Sent(start, "INVITE ");
auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600"));
const Action* inv2 = Sent(a, "INVITE ");
auto again = m.OnFlowReopened();
const Action* resent = Sent(again, "INVITE ");
Check(inv1 && inv2 && resent && resent->text == inv2->text && resent->text != inv1->text, "the INVITE sent again for a 422 is the one resent over a reopened flow, byte for byte");
Check(m.Unanswered() && !m.ResendDue() && m.OnFlowReopened().empty(), "... once");
auto lost = m.OnFlowLost();
const Action* t = Find(lost, Action::Type::State);
Check(t && t->reason == "error" && m.Terminated() && Sent(lost, "INVITE ") == nullptr, "... and a flow that dies again ends its call with error");
}
// ---- a hang-up while the INVITE sent again awaits its final cancels
// that INVITE
{
imsd::util::Rng rng(80);
CallMachine m(c, rng, "ims-call-54", "1233", 50004, false);
m.Start();
const std::string id = m.CallId();
auto a = m.OnInviteResponse(R422(id, 1, "3600"));
const Action* inv2 = Sent(a, "INVITE ");
auto h = m.OnHangup();
const Action* cancel = Sent(h, "CANCEL ");
Check(inv2 && cancel && cancel->text.contains("\r\nCSeq: 2 CANCEL\r\n") && imsd::sip::Header(cancel->text, "Via") == imsd::sip::Header(inv2->text, "Via"), "a hang-up after the INVITE was sent again: a CANCEL with the second INVITE's number and branch");
auto e = m.OnInviteResponse(Cseq(Final(id, 487, "Request Terminated"), 2));
const Action* t = Find(e, Action::Type::State);
Check(Sent(e, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "local-hangup", "... and its 487 ends the call as a hang-up");
}
// ---- what the refused transaction left is not the second INVITE's: a
// 183 before the 422 (the ringing state, a PRACKed RSeq, an early
// answer), the refusal's Record-Route and Contact, a resend used
{
auto refused = [&](CallMachine& m) {
m.Start();
m.OnFlowReopened(); // the first INVITE's one resend
m.OnInviteResponse(R183(m.CallId())); // ringing; RSeq 1 PRACKed; an answer on port 6004
std::string r = R422(m.CallId(), 1, "3600");
r.replace(r.find("Content-Length"), 0, "Record-Route: <sip:[2001:db8::bad]:6000;lr>\r\nContact: <sip:refuser@[2001:db8::bad]:5060>\r\nReason: Q.850;cause=31\r\n");
return m.OnInviteResponse(r);
};
imsd::util::Rng rng(74);
CallMachine m(c, rng, "ims-call-48", "1233", 50004, false);
auto a = refused(m);
const std::string id = m.CallId();
const Action* st = Find(a, Action::Type::State);
Check(Sent(a, "INVITE ") != nullptr && m.State() == CallState::Dialing && st && st->state == "dialing" && st->reason == "outgoing", "a 422 after a 183: the INVITE again, and the call announced as dialing again");
Check(Logged(a, "call ims-call-48: INVITE final 422, Min-SE 3600, Reason: Q.850;cause=31 — the INVITE again with Session-Expires 3600") != nullptr, "the refusal's Reason is in the line of the INVITE sent again");
Check(m.Unanswered() && m.ResendDue(), "the second INVITE has a resend of its own although the first used one");
const Action* inv = Sent(a, "INVITE ");
Check(inv && inv->text.contains("\r\nCSeq: 3 INVITE\r\n"), "after a PRACK numbered 2 the second INVITE takes 3");
auto b183 = m.OnInviteResponse(Cseq(R183(id), 3));
const Action* prack = Sent(b183, "PRACK ");
Check(prack && prack->text.contains("RAck: 1 3 INVITE\r\n") && prack->text.contains("CSeq: 4 PRACK\r\n"), "the second INVITE's 183 is PRACKed although the first's had the same RSeq");
Check(prack && prack->text.starts_with("PRACK sip:termgw@[2001:db8::9]:5060 SIP/2.0"), "... to that 183's Contact");
// a 200 that brings no route, no Contact and no answer finds none left over
imsd::util::Rng rng2(75);
CallMachine n(c, rng2, "ims-call-49", "1233", 50004, false);
refused(n);
auto a200 = n.OnInviteResponse(Cseq(Final(n.CallId(), 200, "OK"), 3));
const Action* ack = Sent(a200, "ACK ");
Check(ack && ack->text.starts_with("ACK sip:1233;") && !ack->text.contains("2001:db8::bad") && !ack->text.contains("termgw"), "the ACK of a 200 without a Contact or a Record-Route goes to the request-URI: not to the refusal's Contact or the first 183's, not over the refusal's Record-Route");
const Action* media = Find(a200, Action::Type::StartMedia);
Check(media && media->media.remotePort != 6004 && media->media.remoteIp.empty(), "the first INVITE's early answer is not the second's");
}
// ---- a Min-SE below the interval asked for: sent again with that
// Min-SE, the interval kept
{
imsd::util::Rng rng(62);
CallMachine m(c, rng, "ims-call-41", "1233", 50004, false);
m.Start();
auto a = m.OnInviteResponse(R422(m.CallId(), 1, "900;x=y"));
const Action* inv2 = Sent(a, "INVITE ");
Check(inv2 && inv2->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 900\r\n"), "a smaller Min-SE is carried and the interval of 1800 kept");
Check(Logged(a, "INVITE final 422, Min-SE 900 — the INVITE again with Session-Expires 1800") != nullptr, "... and the journal says so");
}
// ---- a 422 the INVITE is not sent again for: the call ends, and the
// journal has what the refusal named
{
// the Min-SE the refused INVITE carried, named again
imsd::util::Rng rng(63);
CallMachine m(c, rng, "ims-call-42", "1233", 50004, false);
m.Start();
const std::string id = m.CallId();
m.OnInviteResponse(R422(id, 1, "3600"));
auto a = m.OnInviteResponse(R422(id, 2, "3600"));
const Action* ack = Sent(a, "ACK ");
Check(ack && ack->text.contains("\r\nCSeq: 2 ACK\r\n"), "the second 422 is ACKed with the second INVITE's number");
const Action* t = Find(a, Action::Type::State);
Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "error", "a 422 that names the Min-SE just sent ends the call");
Check(Logged(a, "call ims-call-42 ended: error — INVITE final 422, Min-SE 3600") != nullptr, "... with the minimum in the journal");
// none, one that begins with no digit, one of ten digits, the default, zero
int n = 0;
for (std::string_view v : {"", "soon", "1000000000", "90", "0"}) {
imsd::util::Rng r2(64 + n);
CallMachine k(c, r2, "ims-call-43", "1233", 50004, false);
k.Start();
auto b = k.OnInviteResponse(R422(k.CallId(), 1, v));
const std::string what = v.empty() ? std::string("a 422 without a Min-SE") : std::format("a 422 with Min-SE '{}'", v);
Check(Sent(b, "ACK ") != nullptr && Sent(b, "INVITE ") == nullptr && k.Terminated(), what + " ends the call");
const bool read = v == "90" || v == "0";
Check(Logged(b, read ? std::format("INVITE final 422, Min-SE {}", v) : std::string("INVITE final 422, no Min-SE read")) != nullptr, what + ": the journal has what was read");
n++;
}
// a Reason on the refusal follows the Min-SE part
imsd::util::Rng r3(70);
CallMachine q(c, r3, "ims-call-44", "1233", 50004, false);
q.Start();
std::string r = R422(q.CallId(), 1, "");
r.replace(r.find("Content-Length"), 0, "Reason: Q.850;cause=31\r\n");
Check(Logged(q.OnInviteResponse(r), "INVITE final 422, no Min-SE read, Reason: Q.850;cause=31") != nullptr, "a 422's Reason is kept in the journal line");
}
// ---- a network that names a larger minimum each time: three INVITEs
// sent again, then the call ends (MinSeAgainMax)
{
imsd::util::Rng rng(71);
CallMachine m(c, rng, "ims-call-45", "1233", 50004, false);
m.Start();
const std::string id = m.CallId();
int sent = 0;
for (int i = 1; i <= 3; i++) {
auto a = m.OnInviteResponse(R422(id, i, std::to_string(3600 * i)));
const Action* inv = Sent(a, "INVITE ");
if (inv && inv->text.contains(std::format("\r\nCSeq: {} INVITE\r\n", i + 1)) && inv->text.contains(std::format("\r\nSession-Expires: {};refresher=uac\r\nMin-SE: {}\r\n", 3600 * i, 3600 * i))) sent++;
}
Check(sent == 3 && !m.Terminated(), "three larger minimums in a row: the INVITE again each time, numbered 2, 3 and 4");
auto last = m.OnInviteResponse(R422(id, 4, "14400"));
Check(Sent(last, "INVITE ") == nullptr && m.Terminated() && Logged(last, "INVITE final 422, Min-SE 14400") != nullptr, "the fourth ends the call");
}
// ---- a 422 after the answer: no INVITE again; the call ends
{
imsd::util::Rng rng(77);
CallMachine m(c, rng, "ims-call-51", "1233", 50004, false);
m.Start();
m.OnInviteResponse(R200(m.CallId()));
auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600"));
const Action* t = Find(a, Action::Type::State);
Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "error" && Has(a, Action::Type::StopMedia), "a 422 after the answer: no INVITE again; the call ends and its media stops");
}
// ---- a 486 that carries a Min-SE is no 422: not sent again
{
imsd::util::Rng rng(78);
CallMachine m(c, rng, "ims-call-52", "1233", 50004, false);
m.Start();
std::string busy = Final(m.CallId(), 486, "Busy Here");
busy.replace(busy.find("Content-Length"), 0, "Min-SE: 3600\r\n");
auto a = m.OnInviteResponse(busy);
Check(Sent(a, "INVITE ") == nullptr && Logged(a, "call ims-call-52 ended: refused-or-busy — INVITE final 486") != nullptr && Logged(a, "Min-SE") == nullptr, "a 486 that carries a Min-SE is no 422: no INVITE again, no Min-SE in its line");
}
// ---- a 422 after the call was cancelled ends it as a hang-up
{
imsd::util::Rng rng(72);
CallMachine m(c, rng, "ims-call-46", "1233", 50004, false);
m.Start();
m.OnHangup();
auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600"));
const Action* t = Find(a, Action::Type::State);
Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "local-hangup", "a 422 that crosses the user's CANCEL: no INVITE again, a local hang-up");
}
// ---- an emergency call: the 422 is answered on the same attempt; a 422
// the INVITE is not sent again for falls back like any other final
{
imsd::util::Rng rng(73);
CallMachine m(c, rng, "ims-call-47", "112", 50004, false, true);
m.Start();
const std::string id = m.CallId();
auto a = m.OnInviteResponse(R422(id, 1, "3600"));
const Action* sos2 = Sent(a, "INVITE ");
Check(sos2 && sos2->text.starts_with("INVITE urn:service:sos ") && sos2->text.contains("\r\nCSeq: 2 INVITE\r\n") && sos2->text.contains("\r\nMin-SE: 3600\r\n") && m.CallId() == id, "the emergency INVITE again with the Min-SE, still to urn:service:sos");
auto b = m.OnInviteResponse(R422(id, 2, "3600"));
const Action* plain = Sent(b, "INVITE ");
Check(plain && plain->text.starts_with("INVITE sip:112;phone-context=") && m.CallId() != id && plain->text.contains("\r\nCSeq: 1 INVITE\r\n") && plain->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 90\r\n"), "a 422 that ends the emergency attempt falls back to the digits: a new dialog, numbered and timed afresh");
auto c2 = m.OnInviteResponse(R422(m.CallId(), 1, "3600"));
const Action* plain2 = Sent(c2, "INVITE ");
Check(plain2 && plain2->text.starts_with("INVITE sip:112;phone-context=") && plain2->text.contains("\r\nCSeq: 2 INVITE\r\n") && plain2->text.contains("\r\nMin-SE: 3600\r\n"), "... and the fallback's own 422 is answered in its turn");
}
{
// the count of INVITEs sent again is the Call-ID's: after an emergency
// attempt that used all three, the fallback's starts at none
imsd::util::Rng rng(76);
CallMachine m(c, rng, "ims-call-50", "112", 50004, false, true);
m.Start();
const std::string id = m.CallId();
for (int i = 1; i <= 3; i++) m.OnInviteResponse(R422(id, i, std::to_string(3600 * i)));
auto b = m.OnInviteResponse(R422(id, 4, "14400"));
Check(m.CallId() != id && Sent(b, "INVITE ") != nullptr && Sent(b, "INVITE ")->text.starts_with("INVITE sip:112;phone-context="), "the fourth 422 of the emergency attempt: the fallback");
auto d = m.OnInviteResponse(R422(m.CallId(), 1, "3600"));
Check(Sent(d, "INVITE ") != nullptr && Sent(d, "INVITE ")->text.contains("\r\nCSeq: 2 INVITE\r\n") && !m.Terminated(), "the fallback's first 422 is answered: its count starts at none");
}
// ---- user hangup during the sos attempt kills the chain: 487 ends it // ---- user hangup during the sos attempt kills the chain: 487 ends it
{ {
imsd::util::Rng rng(47); imsd::util::Rng rng(47);
@ -1732,129 +1396,6 @@ int main() {
} }
} }
// ---- WakeAt: when the phone has to be awake for imsd (the shell arms
// its wake alarm from it). The clock is ours: seconds.
{
Check(WakeAt(1000, true, true, 2800, 0, true, 1005) == 1000, "busy (a call, a text in flight): now, the phone is to stay awake");
Check(WakeAt(1000, true, false, 0, 0, false, 0) == 1000, "…also where no registration stands (an emergency call)");
Check(WakeAt(1000, false, true, 2800, 0, false, 0) == 2800, "a registration on a live flow: the refresh's due time");
Check(WakeAt(1000, false, true, 2800, 0, true, 1005) == 2800, "…whatever the recovery policy names meanwhile");
Check(WakeAt(1000, false, true, 990, 0, false, 0) == 990, "a refresh that is due: its time, which has come");
Check(WakeAt(1000, false, true, 2800, 1300, false, 0) == 1300, "the reg-event subscription's renewal where it comes before the refresh");
Check(WakeAt(1000, false, true, 2800, 600400, false, 0) == 2800, "…and the refresh where the renewal is far off");
Check(WakeAt(1000, false, false, 2800, 1300, true, 1005) == 1005, "a dead flow under a registration: the recovery's next step");
Check(WakeAt(1000, false, false, 2800, 0, true, 0) == 1000, "a step the policy says is due now (its 0): now, not no alarm");
Check(WakeAt(1000, false, false, 2800, 0, true, 400) == 1000, "…and one whose time has passed");
Check(WakeAt(1000, false, false, 2800, 0, false, 1005) == 0, "no flow and nothing to recover: no alarm");
RegRecovery w;
w.OldGone(); w.OnFreshFailure(1000, RegRecovery::Failure::Throttled);
Check(WakeAt(1000, false, false, 0, 0, true, w.WakeTime(1000)) == 1000 + 21 * 60, "a throttled fresh registration: the alarm at the schedule's end, 21 min on");
}
// ---- RegRecovery: the wake after a local wait. Awake, the next look is
// LocalRetry on; a sleeping phone is woken for it after as long again as
// that kind of wait has lasted (no packet service: since the modem's
// first such word since the network last answered; a connect the kernel
// refused: since its first refusal since the modem was last without
// service or the network last answered, whichever came later), within
// LocalWakeMin and Max. A counted step is woken for at the policy's own
// time.
{
using L = RegRecovery::Local;
using F = RegRecovery::Failure;
RegRecovery g;
Check(!g.LocalLook() && g.WakeTime(1000) == 0, "nothing waits: the step's own time (due now)");
{
RegRecovery o;
o.OnLocalRefusal(1000, L::NoService); o.OnLocalRefusal(1600, L::NoService);
Check(o.WakeTime(1600) == 1600 + 600, "600 s into a gap: the slower look, 600 s on");
o.OldGone();
Check(!o.LocalLook() && o.WakeTime(1600) == o.Next(1600).at, "the old registration written off meanwhile: a verdict, the wake at the policy's own time");
}
g.OnLocalRefusal(1000, L::NoService);
Check(g.LocalLook() && g.Next(1000).at == 1000 + RegRecovery::LocalRetry, "a local wait: looked at again LocalRetry on");
Check(g.WakeTime(1000) == 1000 + 10, "…a sleeping phone woken for it 10 s on, the floor (LocalWakeMin)");
g.OnLocalRefusal(1005, L::NoService); g.OnLocalRefusal(1010, L::NoService);
Check(g.WakeTime(1010) == 1010 + RegRecovery::LocalWakeMin, "looks while awake push the wake on, the floor standing");
g.OnLocalRefusal(1012, L::NoService);
Check(g.WakeTime(1012) == 1012 + 12, "12 s into the gap: woken after 12 s more");
g.OnLocalRefusal(1200, L::NoService);
Check(g.WakeTime(1200) == 1200 + 200, "200 s into the gap: woken after 200 s more");
g.OnLocalRefusal(4000, L::NoService);
Check(g.WakeTime(4000) == 4000 + 900, "a long gap: every 15 min, the ceiling (LocalWakeMax)");
Check(g.Next(4000).at == 4000 + RegRecovery::LocalRetry, "…the awake pace as it was");
// the modem has service again and the kernel refuses the connect (the old flow's 4-tuple): looked at soon
g.OnLocalRefusal(4100, L::Kernel);
Check(g.WakeTime(4100) == 4100 + RegRecovery::LocalWakeMin, "the first connect the kernel refuses after the gap: woken LocalWakeMin on");
g.OnLocalRefusal(4130, L::Kernel);
Check(g.WakeTime(4130) == 4130 + 30, "…30 s of such refusals: 30 s more");
// the modem's word alternates: the gap's pace does not start over, the kernel's does at each return
g.OnLocalRefusal(4200, L::NoService);
Check(g.WakeTime(4200) == 4200 + RegRecovery::LocalWakeMax, "no service again: the gap's count goes on from its first word, at the ceiling by now");
g.OnLocalRefusal(5000, L::Kernel);
Check(g.WakeTime(5000) == 5000 + RegRecovery::LocalWakeMin, "the kernel's refusal after it: counted from this one, not from before the gap");
g.OnLocalRefusal(5100, L::NoService);
Check(g.WakeTime(5100) == 5100 + RegRecovery::LocalWakeMax, "…and no service again: the gap's pace still");
// a counted step is woken for at its own time, and the gap's count stands through a silent one
RegRecovery a = g; a.OnReconnectFailure(5110, F::Silent);
Check(!a.LocalLook() && a.WakeTime(5110) == a.Next(5110).at && a.Next(5110).at == 5110 + RegRecovery::ReconnectDelayMin, "a silent cycle: the policy's own time, not the gap's pace");
a.OnLocalRefusal(5200, L::NoService);
Check(a.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMax, "…no service after it: the gap's pace goes on where it was");
RegRecovery b = g; b.OnFreshFailure(5110, F::Silent);
Check(!b.LocalLook() && b.WakeTime(5110) == b.Next(5110).at, "a silent fresh attempt: the policy's own time");
b.OnLocalRefusal(5200, L::NoService);
Check(b.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMax, "…and the gap's pace after it");
// the network's answer starts both counts over
RegRecovery r = g; r.OnReconnectFailure(5110, F::Refused);
Check(!r.LocalLook() && r.WakeTime(5110) == r.Next(5110).at, "a refusal: the policy's own time");
r.OnLocalRefusal(5300, L::NoService);
Check(r.WakeTime(5300) == 5300 + RegRecovery::LocalWakeMin, "…and a gap after the network's answer starts at the floor");
RegRecovery th = g; th.OnFreshFailure(5110, F::Throttled); th.OldGone(); th.OnLocalRefusal(5300, L::NoService);
Check(th.Next(5300).at == 5110 + 21 * 60 && th.WakeTime(5300) == 5110 + 21 * 60, "a throttle with the old registration written off: the look after it woken for at the schedule's end, which is later than the look's floor");
RegRecovery tr = g; tr.OnFreshFailure(5110, F::Throttled); tr.OnLocalRefusal(5300, L::NoService);
Check(tr.WakeTime(5300) == 5300 + 10, "a throttle is the network's answer too: a gap after it starts at the floor");
RegRecovery tf = g; tf.OnFreshFailure(5110, F::Refused); tf.OnLocalRefusal(5300, L::NoService);
Check(tf.WakeTime(5300) == 5300 + 10, "…and so is a refused fresh attempt");
RegRecovery c = g; c.OnBindingTerminated(5110, "expired");
Check(!c.LocalLook(), "a terminated binding: a counted step");
c.OnLocalRefusal(5300, L::NoService);
Check(c.WakeTime(5300) == 5300 + 10, "…and the network's word: a gap after it starts at the floor");
RegRecovery d = g; d.OnSuccess();
Check(!d.LocalLook() && d.WakeTime(5110) == 0, "a success: everything over");
d.OnLocalRefusal(5200, L::NoService);
Check(d.WakeTime(5200) == 5200 + 10, "…the gap's count too: a gap after it starts at the floor");
RegRecovery kq; kq.OnLocalRefusal(2000, L::Kernel); kq.OnLocalRefusal(2400, L::Kernel);
Check(kq.WakeTime(2400) == 2400 + 400, "400 s of the kernel's refusals: 400 s more");
RegRecovery n = kq; n.OnNetworkAnswered(); n.OnLocalRefusal(2410, L::Kernel);
Check(n.WakeTime(2410) == 2410 + RegRecovery::LocalWakeMin, "an answered connect, then the kernel's refusal: the floor again");
RegRecovery n2 = kq; n2.OnLocalRefusal(2410, L::Kernel);
Check(n2.WakeTime(2410) == 2410 + 410, "…where without the answer the count had gone on");
// …and the kernel's count at each of the policy's own: 800 s of refusals would be woken for 800 s on
RegRecovery kr = kq; kr.OnReconnectFailure(2405, F::Refused); kr.OnLocalRefusal(2800, L::Kernel);
Check(kr.WakeTime(2800) == 2800 + 10, "a refused reconnect starts the kernel's count over too");
RegRecovery kt = kq; kt.OnFreshFailure(2405, F::Throttled); kt.OnLocalRefusal(2800, L::Kernel);
Check(kt.WakeTime(2800) == 2800 + 10, "…a throttled fresh attempt");
RegRecovery kf = kq; kf.OnFreshFailure(2405, F::Refused); kf.OnLocalRefusal(2800, L::Kernel);
Check(kf.WakeTime(2800) == 2800 + 10, "…a refused one");
RegRecovery kc = kq; kc.OnBindingTerminated(2405, "expired"); kc.OnLocalRefusal(2800, L::Kernel);
Check(kc.WakeTime(2800) == 2800 + 10, "…a terminated binding");
RegRecovery ks = kq; ks.OnSuccess(); ks.OnLocalRefusal(2800, L::Kernel);
Check(ks.WakeTime(2800) == 2800 + 10, "…and a success");
RegRecovery kn = kq; kn.OnReconnectFailure(2405, F::Silent); kn.OnLocalRefusal(2800, L::Kernel);
Check(kn.WakeTime(2800) == 2800 + 800, "…and not a silent cycle: 800 s of refusals, 800 s more");
RegRecovery kb = kq; kb.OnFreshFailure(2405, F::Silent); kb.OnLocalRefusal(2800, L::Kernel);
Check(kb.WakeTime(2800) == 2800 + 800, "…nor a silent fresh attempt");
RegRecovery gq = g; gq.OnNetworkAnswered(); gq.OnLocalRefusal(5200, L::NoService);
Check(gq.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMin, "an answer, then a gap: the floor, where without it the gap's count was at its ceiling");
// a hold the network set outlasts the look's pace
RegRecovery h; h.OnReconnectFailure(1000, F::Refused, 600); h.OnLocalRefusal(1100, L::NoService);
Check(h.Next(1100).at == 1600 && h.WakeTime(1100) == 1600, "a hold that outlasts the look's pace: woken for at the hold's end, not 10 s on");
RegRecovery k; k.OnLocalRefusal(1000);
Check(k.WakeTime(1000) == 1000 + RegRecovery::LocalWakeMin, "a refusal with no kind named and no gap before it: the floor");
RegRecovery kd; kd.OnLocalRefusal(1000, L::NoService); kd.OnLocalRefusal(1600);
Check(kd.WakeTime(1600) == 1600 + 10, "…and it is the kernel's (the default kind): 600 s into a gap its own count starts, at the floor");
}
// ---- SMS over IP: SmsOutbound and OnSmsMessage (TS 24.341) ---------- // ---- SMS over IP: SmsOutbound and OnSmsMessage (TS 24.341) ----------
{ {
using namespace imsd::sms; using namespace imsd::sms;

View file

@ -8,8 +8,7 @@
// prints, with its line for each algorithm imsd installs, and // prints, with its line for each algorithm imsd installs, and
// the Security-Server parser, fed the operator lines as captured (O2 UK's // the Security-Server parser, fed the operator lines as captured (O2 UK's
// six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc // six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc
// offer; KPN's single mechanism; Odido's), the EALG list, and the two // offer; KPN's single mechanism; Odido's), and the EALG list.
// paths an SA pair's outbound policies select (OnSaPath).
import std; import std;
import Imsd; import Imsd;
@ -477,22 +476,6 @@ int main() {
Check(NormalizeEalg("") == "null" && NormalizeEalg("3des") == "des-ede3-cbc" && NormalizeEalg("aes-cbc") == "aes-cbc", "NormalizeEalg"); Check(NormalizeEalg("") == "null" && NormalizeEalg("3des") == "des-ede3-cbc" && NormalizeEalg("aes-cbc") == "aes-cbc", "NormalizeEalg");
} }
// ---- OnSaPath: the two paths an SA pair's outbound policies select
{
const SaPaths p{"2001:db8::db43", "2001:db8::105", 6000, 33421};
Check(OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: the client port to the P-CSCF's server port");
Check(OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33421), "OnSaPath: the server port to the P-CSCF's client port");
Check(!OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 33421) && !OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 6000), "OnSaPath: not the client port to its client port, nor the server port to its server port");
Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33422), "OnSaPath: not another port of the P-CSCF");
Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::106", 33421), "OnSaPath: not another host on the P-CSCF's port");
Check(!OnSaPath(p, "2001:db8::db44", 45062, "2001:db8::105", 33421), "OnSaPath: not from another address of ours");
Check(!OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 6000) && !OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 33421), "OnSaPath: not from a port that is neither protected port");
Check(OnSaPath(p, "2001:DB8:0:0:0:0:0:DB43", 45061, "2001:0db8::0105", 6000) && OnSaPath(SaPaths{"2001:DB8:0:0:0:0:0:DB43", "2001:0db8::0105", 6000, 33421}, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: an IPv6 address in another spelling is the same address, the packet's or the record's");
Check(!OnSaPath(SaPaths{}, "2001:db8::db43", 45061, "2001:db8::105", 6000) && !OnSaPath(SaPaths{}, "", 45061, "", 0), "OnSaPath: no pair on record, no path");
const SaPaths four{"192.0.2.2", "192.0.2.1", 6000, 33421};
Check(OnSaPath(four, "192.0.2.2", 45062, "192.0.2.1", 33421) && !OnSaPath(four, "192.0.2.2", 45062, "192.0.2.3", 33421), "OnSaPath: over IPv4 a path of the pair, and not another host on its port");
}
if (Failures == 0) std::println("Ipsec: all tests passed"); if (Failures == 0) std::println("Ipsec: all tests passed");
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits
} }

View file

@ -19,12 +19,7 @@
// CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client // CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client
// carries the default offer's two mechanisms, where the Python stack offered // carries the default offer's two mechanisms, where the Python stack offered
// one cipher. The two REGISTERs once more on an identity an ISIM holds: the // one cipher. The two REGISTERs once more on an identity an ISIM holds: the
// pinned ones with the card's names in place of the derived ones. The INVITE, // pinned ones with the card's names in place of the derived ones. Then the
// its CANCEL and its ACKs once more for a dialog with another sequence number,
// session interval and Min-SE than the pinned 1, 1800 and 90. Which
// messages carry P-Access-Network-Info where the cell is known, and that the
// PRACK, the BYE and the responses that carry it carry none where it is not.
// Then the
// SMS over IP shapes: the // SMS over IP shapes: the
// +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying // +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying
// an RP-DATA to the service centre and the one carrying an RP-ACK to the // an RP-DATA to the service centre and the one carrying an RP-ACK to the
@ -426,11 +421,11 @@ int main() {
Check(prack.contains("To: <sip:1233@x>;tag=remote99\r\n"), "PRACK To has remote tag"); Check(prack.contains("To: <sip:1233@x>;tag=remote99\r\n"), "PRACK To has remote tag");
Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq"); Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq");
Check(prack.contains("RAck: 42 1 INVITE\r\n"), "PRACK RAck"); Check(prack.contains("RAck: 42 1 INVITE\r\n"), "PRACK RAck");
Check(prack.ends_with("RAck: 42 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "PRACK: P-Access-Network-Info after its RAck, an empty body"); Check(prack.ends_with("Content-Length: 0\r\n\r\n"), "PRACK empty body");
std::string bye = BuildInDialog(c, d, "BYE", 3, "byebranch"); std::string bye = BuildInDialog(c, d, "BYE", 3, "byebranch");
Check(bye.starts_with("BYE sip:termgw@2001:db8::9 SIP/2.0\r\n"), "BYE line"); Check(bye.starts_with("BYE sip:termgw@2001:db8::9 SIP/2.0\r\n"), "BYE line");
Check(bye.ends_with("CSeq: 3 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "BYE: its CSeq, then P-Access-Network-Info"); Check(bye.contains("CSeq: 3 BYE\r\n"), "BYE CSeq");
std::string ack = BuildAck2xx(c, d, "ackbranch", "<ignored>"); std::string ack = BuildAck2xx(c, d, "ackbranch", "<ignored>");
Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target"); Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target");
@ -441,12 +436,6 @@ int main() {
Check(cancel.starts_with(std::format("CANCEL {} SIP/2.0\r\n", d.ruri)), "CANCEL request-URI = ruri"); Check(cancel.starts_with(std::format("CANCEL {} SIP/2.0\r\n", d.ruri)), "CANCEL request-URI = ruri");
Check(cancel.contains("branch=z9hG4bKib;rport\r\n"), "CANCEL reuses INVITE branch"); Check(cancel.contains("branch=z9hG4bKib;rport\r\n"), "CANCEL reuses INVITE branch");
Check(cancel.contains("CSeq: 1 CANCEL\r\n"), "CANCEL CSeq copies INVITE"); Check(cancel.contains("CSeq: 1 CANCEL\r\n"), "CANCEL CSeq copies INVITE");
// RFC 7315 5.7: the header appears in no ACK and no CANCEL
Check(!ack.contains("P-Access-Network-Info") && !cancel.contains("P-Access-Network-Info") && !BuildAckNon2xx(c, d, "<sip:x@y>;tag=z").contains("P-Access-Network-Info"), "neither ACK nor the CANCEL carries P-Access-Network-Info");
// where the cell is not known the in-dialog requests carry none either
Context n = MakeCtx();
n.panInfo.clear();
Check(BuildInDialog(n, d, "PRACK", 2, "prbranch", rack).ends_with("RAck: 42 1 INVITE\r\nContent-Length: 0\r\n\r\n") && BuildInDialog(n, d, "BYE", 3, "byebranch").ends_with("CSeq: 3 BYE\r\nContent-Length: 0\r\n\r\n"), "no cell known: PRACK and BYE without the header");
} }
{ {
// non-2xx ACK uses the INVITE branch + registration route + resp To // non-2xx ACK uses the INVITE branch + registration route + resp To
@ -457,20 +446,6 @@ int main() {
Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route"); Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route");
Check(ack.contains("To: <sip:x@y>;tag=z\r\n"), "non-2xx ACK echoes response To"); Check(ack.contains("To: <sip:x@y>;tag=z\r\n"), "non-2xx ACK echoes response To");
} }
{
// The INVITE's sequence number, session interval and Min-SE are the
// dialog's (1, 1800 and 90 in the pinned INVITE above), and its CANCEL
// and both ACKs carry the INVITE's number.
Dialog d;
d.ruri = "sip:x@y"; d.callid = "CID"; d.itag = "it"; d.invBranch = "ib9";
d.invCseq = 2; d.sessionExpires = 3600; d.minSe = 2400;
std::string inv = BuildInvite(c, d, "v=0\r\n", false);
Check(inv.contains("\r\nCSeq: 2 INVITE\r\n"), "INVITE carries the dialog's sequence number");
Check(inv.contains("\r\nSession-Expires: 3600;refresher=uac\r\nMin-SE: 2400\r\n"), "INVITE carries the dialog's session interval and Min-SE");
Check(BuildCancel(c, d).contains("\r\nCSeq: 2 CANCEL\r\n"), "CANCEL copies the INVITE's number");
Check(BuildAckNon2xx(c, d, "<sip:x@y>;tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "non-2xx ACK copies the INVITE's number");
Check(BuildAck2xx(c, d, "ab", "<sip:x@y>;tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "2xx ACK copies the INVITE's number");
}
// ---- 200 OK response echoes the request's dialog headers, in order // ---- 200 OK response echoes the request's dialog headers, in order
{ {
@ -487,21 +462,12 @@ int main() {
Check(r.contains("Via: SIP/2.0/TCP [a::1]:45061;branch=z9hG4bKother\r\n"), "200 echoes Via"); Check(r.contains("Via: SIP/2.0/TCP [a::1]:45061;branch=z9hG4bKother\r\n"), "200 echoes Via");
Check(r.contains("Call-ID: xyz@far\r\n"), "200 echoes Call-ID"); Check(r.contains("Call-ID: xyz@far\r\n"), "200 echoes Call-ID");
Check(r.contains("CSeq: 7 BYE\r\n"), "200 echoes CSeq"); Check(r.contains("CSeq: 7 BYE\r\n"), "200 echoes CSeq");
Check(r.ends_with("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "200 to a BYE: P-Access-Network-Info after the echoed five, an empty body"); Check(r.ends_with("Content-Length: 0\r\n\r\n"), "200 empty body");
// with an SDP answer: our Contact + application/sdp appear // with an SDP answer: our Contact + application/sdp appear
std::string r2 = BuildResponse200(c, req, Sdp); std::string r2 = BuildResponse200(c, req, Sdp);
Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type"); Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type");
Check(r2.contains("Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"), "200 w/ SDP includes our Contact"); Check(r2.contains("Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"), "200 w/ SDP includes our Contact");
Check(r2.ends_with(Sdp), "200 w/ SDP body"); Check(r2.ends_with(Sdp), "200 w/ SDP body");
Check(r2.contains("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContact: "), "200 w/ SDP: P-Access-Network-Info before our Contact");
// TS 24.229 5.1.2A.1.1, 5.1.2A.2: "(except CANCEL responses)"
std::string cancelReq = req;
cancelReq.replace(0, 3, "CANCEL");
cancelReq.replace(cancelReq.find("CSeq: 7 BYE"), 11, "CSeq: 7 CANCEL");
Check(BuildResponse200(c, cancelReq).ends_with("CSeq: 7 CANCEL\r\nContent-Length: 0\r\n\r\n"), "200 to a CANCEL: no P-Access-Network-Info");
Context n = MakeCtx();
n.panInfo.clear();
Check(BuildResponse200(n, req).ends_with("CSeq: 7 BYE\r\nContent-Length: 0\r\n\r\n") && !BuildResponse200(n, req, Sdp).contains("P-Access-Network-Info"), "no cell known: the 200 without the header");
} }
// ---- s53 oracle diff: UUID Contact user-part + User-Agent ------------ // ---- s53 oracle diff: UUID Contact user-part + User-Agent ------------
@ -587,17 +553,6 @@ int main() {
"Call-ID: in1@net\r\n" "Call-ID: in1@net\r\n"
"CSeq: 9 MESSAGE\r\n" "CSeq: 9 MESSAGE\r\n"
"Content-Length: 0\r\n\r\n"; "Content-Length: 0\r\n\r\n";
Context noCell = MakeCtx();
noCell.panInfo.clear();
Eq(BuildResponse(noCell, inbound, 488, "Not Acceptable Here", "T488"),
"SIP/2.0 488 Not Acceptable Here\r\n"
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
"From: <sip:ipsmgw@ims>;tag=N1\r\n"
"To: <sip:me@ims>;tag=T488\r\n"
"Call-ID: in1@net\r\n"
"CSeq: 9 MESSAGE\r\n"
"Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To");
Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"), Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"),
"SIP/2.0 488 Not Acceptable Here\r\n" "SIP/2.0 488 Not Acceptable Here\r\n"
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n" "Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
@ -606,8 +561,7 @@ int main() {
"To: <sip:me@ims>;tag=T488\r\n" "To: <sip:me@ims>;tag=T488\r\n"
"Call-ID: in1@net\r\n" "Call-ID: in1@net\r\n"
"CSeq: 9 MESSAGE\r\n" "CSeq: 9 MESSAGE\r\n"
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" "Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To");
"Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after its CSeq");
const std::string tagged = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet2\r\nFrom: <sip:ipsmgw@ims>;tag=N2\r\nTo: <sip:me@ims>;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n"; const std::string tagged = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet2\r\nFrom: <sip:ipsmgw@ims>;tag=N2\r\nTo: <sip:me@ims>;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n";
Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: <sip:me@ims>;tag=had\r\n"), "a To that already carries a tag is echoed as it is"); Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: <sip:me@ims>;tag=had\r\n"), "a To that already carries a tag is echoed as it is");
// the 400 to a request whose datagram ended before its body did (RFC 3261 18.3), built from what imsd::sip::CutShortRequest gives of it // the 400 to a request whose datagram ended before its body did (RFC 3261 18.3), built from what imsd::sip::CutShortRequest gives of it
@ -628,7 +582,6 @@ int main() {
"CSeq: 9 MESSAGE\r\n" "CSeq: 9 MESSAGE\r\n"
"Content-Length: 0\r\n\r\n", "its 400 echoes every Via and tags To with sixteen hex digits of the MD5 of the secret and the header section"); "Content-Length: 0\r\n\r\n", "its 400 echoes every Via and tags To with sixteen hex digits of the MD5 of the secret and the header section");
Eq(BuildBadRequest(imsd::sip::CutShortRequest(cut + "s").value_or(""), secret), BuildBadRequest(head, secret), "the same request cut short elsewhere draws the same 400, tag and all"); Eq(BuildBadRequest(imsd::sip::CutShortRequest(cut + "s").value_or(""), secret), BuildBadRequest(head, secret), "the same request cut short elsewhere draws the same 400, tag and all");
Check(!BuildBadRequest(head, secret).contains("P-Access-Network-Info"), "the 400 is built without the registration's context: no P-Access-Network-Info");
const auto toTag = [](std::string_view r) { const std::size_t at = r.find(";tag=", r.find("\r\nTo: ")); return r.substr(at, r.find("\r\n", at) - at); }; const auto toTag = [](std::string_view r) { const std::size_t at = r.find(";tag=", r.find("\r\nTo: ")); return r.substr(at, r.find("\r\n", at) - at); };
const std::string r1 = BuildBadRequest(head, secret); const std::string r1 = BuildBadRequest(head, secret);
std::string other = cut; std::string other = cut;
@ -675,18 +628,6 @@ int main() {
"i: call3@net\r\n" "i: call3@net\r\n"
"CSeq: 1 INVITE\r\n" "CSeq: 1 INVITE\r\n"
"l: 0\r\n\r\n"; "l: 0\r\n\r\n";
Eq(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180"),
"SIP/2.0 180 Ringing\r\n"
"Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n"
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n"
"Record-Route: <sip:[2001:db8::105]:6000;lr>\r\n"
"From: <sip:caller@ims>;tag=N3\r\n"
"To: <sip:me@ims>;tag=T180\r\n"
"Call-ID: call3@net\r\n"
"CSeq: 1 INVITE\r\n"
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n"
"Content-Length: 0\r\n\r\n", "a 180 for an INVITE echoes every Via and the Record-Route, tags To and carries our Contact and Allow");
const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180"); const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180");
Eq(ringing, Eq(ringing,
"SIP/2.0 180 Ringing\r\n" "SIP/2.0 180 Ringing\r\n"
@ -699,21 +640,7 @@ int main() {
"CSeq: 1 INVITE\r\n" "CSeq: 1 INVITE\r\n"
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n" "Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n" "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n"
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" "Content-Length: 0\r\n\r\n", "a 180 for an INVITE echoes every Via and the Record-Route, tags To and carries our Contact and Allow");
"Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after them");
{
const std::array<std::string, 2> reliable = {"Require: 100rel", "RSeq: 1"};
Check(BuildInviteResponse(c, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "a reliable 180: P-Access-Network-Info after its Require and RSeq");
Check(BuildInviteResponse(c, invite, 100, "Trying", "unused").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "a 100 Trying carries none");
Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "and a 486");
Check(BuildInviteResponse(c, invite, 200, "OK", "T200", "v=0\r\n").ends_with("P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Type: application/sdp\r\nContent-Length: 5\r\n\r\nv=0\r\n"), "and a 200 with its answer, before the Content-Type");
Check(!BuildInviteResponse(noCell, invite, 100, "Trying", "unused").contains("P-Access-Network-Info") && !BuildInviteResponse(noCell, invite, 200, "OK", "T200", "v=0\r\n").contains("P-Access-Network-Info"), "no cell known: a 100 and a 200 without the header");
Check(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nContent-Length: 0\r\n\r\n") && BuildInviteResponse(noCell, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "no cell known: a reliable 180 and a 486 without it");
// the exception is for a response to a CANCEL, not for one to a request that names the method
std::string allowing = invite;
allowing.insert(allowing.find("Content-Length:"), "Allow: INVITE, ACK, CANCEL, BYE\r\n");
Check(BuildInviteResponse(c, allowing, 180, "Ringing", "T180") == ringing, "an INVITE whose Allow names CANCEL is answered like any other");
}
Eq(BuildInviteResponse(c, compactInvite, 180, "Ringing", "T180"), ringing, "a 180 for an INVITE in compact form is the one for its long form"); Eq(BuildInviteResponse(c, compactInvite, 180, "Ringing", "T180"), ringing, "a 180 for an INVITE in compact form is the one for its long form");
Eq(BuildInviteResponse(c, compactInvite, 486, "Busy Here", "T486"), BuildInviteResponse(c, invite, 486, "Busy Here", "T486"), "and so is a 486"); Eq(BuildInviteResponse(c, compactInvite, 486, "Busy Here", "T486"), BuildInviteResponse(c, invite, 486, "Busy Here", "T486"), "and so is a 486");
Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("\r\nTo: <sip:me@ims>;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route"); Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("\r\nTo: <sip:me@ims>;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route");

View file

@ -9,12 +9,9 @@
// with the Content-Length they read and the unfolding of a folded header // with the Content-Length they read and the unfolding of a folded header
// section (Unfolded) —, a request whose datagram ends before its body does // section (Unfolded) —, a request whose datagram ends before its body does
// (CutShortRequest), a refused final's Retry-After and summary (RetryAfter, // (CutShortRequest), a refused final's Retry-After and summary (RetryAfter,
// RefusalSummary), the interval a 422's Min-SE names (MinSe), transaction // RefusalSummary), transaction matching (ResponseOf), our binding in a
// matching (ResponseOf), our binding in a // reg-event document (RegInfoContactState), and HeaderUri and Body. These pin
// reg-event document (RegInfoContactState), HeaderUri and Body, and a // the module's edge-case behavior; see the module header before "fixing" one.
// message less every line on which one header is found (WithoutHeader).
// These pin the module's edge-case behavior; see the module header before
// "fixing" one.
import std; import std;
import Imsd; import Imsd;
@ -408,22 +405,6 @@ int main() {
Check(CutShortRequest("MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP\r\n [2001:db8::2]:6000\r\nContent-Length:\r\n\t9\r\n\r\nhello") == "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000\r\nContent-Length: 9\r\n\r\n", "a request cut short of a folded Content-Length: its header section unfolded, for the 400"); Check(CutShortRequest("MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP\r\n [2001:db8::2]:6000\r\nContent-Length:\r\n\t9\r\n\r\nhello") == "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000\r\nContent-Length: 9\r\n\r\n", "a request cut short of a folded Content-Length: its header section unfolded, for the 400");
} }
// ---- MinSe (the smallest session interval a 422 names, RFC 4028 5, 6)
{
auto r422 = [](std::string_view line) {
return std::format("SIP/2.0 422 Session Interval Too Small\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\n{}Content-Length: 0\r\n\r\n", line);
};
Check(MinSe(r422("Min-SE: 3600\r\n")) == 3600, "Min-SE read");
Check(MinSe(r422("min-se: 0090 ;x=1\r\n")) == 90, "Min-SE: any case of the name, spaces, zeros before the number, a parameter after it");
Check(MinSe(r422("Min-SE: 999999999\r\n")) == 999999999, "Min-SE of nine digits read");
Check(MinSe(r422("Min-SE: 0000000090\r\n")) == 90, "zeros before the number are no digits of it: ten characters, the number 90");
Check(MinSe(r422("Min-SE: 0\r\n")) == 0, "Min-SE of zero read as zero");
Check(!MinSe(r422("")), "no Min-SE header: none");
Check(!MinSe(r422("Min-SE: soon\r\n")) && !MinSe(r422("Min-SE: -90\r\n")) && !MinSe(r422("Min-SE:\r\n")), "Min-SE that begins with no digit: none");
Check(!MinSe(r422("Min-SE: 1000000000\r\n")) && !MinSe(r422("Min-SE: 99999999999999999999\r\n")), "Min-SE of more than nine digits: none");
Check(!MinSe(r422("Session-Expires: 3600\r\n")), "a Session-Expires is no Min-SE");
}
// ---- RetryAfter / RefusalSummary (what a refused final is logged as) // ---- RetryAfter / RefusalSummary (what a refused final is logged as)
{ {
std::string r503 = std::string r503 =
@ -571,34 +552,6 @@ int main() {
Check(imsd::sip::Body("OPTIONS sip:x SIP/2.0\r\nCSeq: 1 OPTIONS\r\n").empty(), "Body: none without a terminator"); Check(imsd::sip::Body("OPTIONS sip:x SIP/2.0\r\nCSeq: 1 OPTIONS\r\n").empty(), "Body: none without a terminator");
} }
// ---- WithoutHeader: a message less every line on which one header is
// found
{
const std::string r =
"SIP/2.0 200 OK\r\n"
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
"P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 31\r\n"
"\r\n"
"P-Access-Network-Info: a body\r\n";
const std::string bare =
"SIP/2.0 200 OK\r\n"
"Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 31\r\n"
"\r\n"
"P-Access-Network-Info: a body\r\n";
Check(WithoutHeader(r, "P-Access-Network-Info") == bare, "WithoutHeader: the header's line is gone, the other lines and a body line that spells its name stay");
Check(WithoutHeader(bare, "P-Access-Network-Info") == bare, "WithoutHeader: a message without the header comes back as it is");
Check(WithoutHeader(r, "p-access-network-info") == bare, "WithoutHeader: the name in another letter case");
Check(WithoutHeader(r, "P-Access-Network") == r && WithoutHeader(r, "Access-Network-Info") == r, "WithoutHeader: a name that is only part of a header's name takes nothing");
const std::string twice = "BYE sip:a@b SIP/2.0\r\nP-Access-Network-Info: one\r\nCSeq: 2 BYE\r\nP-Access-Network-Info: two\r\n\r\n";
Check(WithoutHeader(twice, "P-Access-Network-Info") == "BYE sip:a@b SIP/2.0\r\nCSeq: 2 BYE\r\n\r\n", "WithoutHeader: every line of the name, the last before the empty line too");
Check(WithoutHeader("SIP/2.0 200 OK\r\nVia: x\r\nP-Access-Network-Info: v", "P-Access-Network-Info") == "SIP/2.0 200 OK\r\nVia: x\r\n", "WithoutHeader: a last line without its line end");
Check(WithoutHeader("SIP/2.0 200 OK\r\nv: x\r\nTo: y\r\nVia: z\r\n\r\n", "Via") == "SIP/2.0 200 OK\r\nTo: y\r\n\r\n", "WithoutHeader: a header under its compact form goes as under its long one");
}
if (Failures == 0) std::println("Sip: all tests passed"); if (Failures == 0) std::println("Sip: all tests passed");
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that
} }