diff --git a/AGENTS.md b/AGENTS.md index 08e16b1..63e58cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,7 +50,7 @@ PipeWire. The verified device/carrier combinations are in the README. | `interfaces/Imsd-Aka.cppm` | `imsd::aka` — the card's side of a registration: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. | | `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the ESP ciphers offered (`ParseEalgOffer`, `DefaultEalgOffer`), the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two 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, whoever installed them (§12), and `FileNamesAnotherPair`, whether a state file's `spi_uc`/`spi_us` name the kernel's pair (unknown on either side decides nothing). | | `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite. Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. | -| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, since 1.2.1 a segment that gets no answer, or an RP-ERROR with cause 41, sent once more with TP-RD set — TS 23.040 9.2.3.6 —, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again) and, since 1.2.1, `RecentSubmissions` (the Call-IDs of the MESSAGEs our submissions went out in, an hour each, by which a submit report for one that is no longer in flight is known for ours — TS 24.341 5.3.1.2); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | +| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, since 1.2.1 a segment that gets no answer, or an RP-ERROR with cause 41, sent once more with TP-RD set — TS 23.040 9.2.3.6 —, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again) and, since 1.2.1, `RecentSubmissions` (the Call-IDs of the MESSAGEs our submissions went out in, an hour each, by which a submit report for one that is no longer in flight is known for ours — TS 24.341 5.3.1.2); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. Since 1.2.5 also `WakeAt`: when the phone has to be awake for imsd (§7.10). | | `interfaces/Imsd-Qmi.cppm` | `imsd::qmi` — the QMI WDS request bytes `imsd-pcscf` sends (Bind Mux Data Port, Set IP Family, Get Packet Service Status, Get Current Settings, Get Profile Settings), the message/TLV parser, the P-CSCF list readers (0x22 flag, 0x23 IPv4, 0x24 FQDN, 0x2E IPv6 — the last one libqmi does not model). | | `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control and messaging (`Gated`'s `Action` parameter names the action), shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. | | `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. | @@ -121,8 +121,14 @@ the second refusal, the count travelling in the holds (`Reconnectable()` and `Fresh()`, decided once after both catch arms) — and taken out of the kernel, §7.2 step 1), the `OnLink` read that writes the old registration off when its address has left the netdev (`FreshRecover` after a failed move, -`AddressGone`), and `PacketServiceUp`'s read of -ModemManager before a silent cycle is counted; the no-target reads and +`AddressGone`), `PacketServiceUp`'s read of +ModemManager before a silent cycle is counted and, since 1.2.5, before +every reconnect cycle and every fresh registration of the recovery +(`NoService`; a bring-up's registrations and the connect for a call's +resend do not ask), and the shell's word that the network has answered, +which starts a coverage gap's counts over (`OnNetworkAnswered`: an +answered TCP connect of the resume or of a reconnect, a response to a +REGISTER); the no-target reads and reactions (1.0.0): the kernel text behind `SaPeer`, the holds' `old_gone` and the script's `PCSCF_DISCOVERY=` — whether a pair is resumable (`SaPeer` finds one and the holds' `old_gone` does not write it off: `!peer || @@ -169,7 +175,12 @@ old registration may be reconnected over) ran against a stand-in network on the workstation and on the dev phone (§5). The sleep inhibitor for a call (1.2.5, §7.6) is all in the shell (`HoldSleepOff` and its callers); what of it ran against a stand-in logind on the workstation and what on -the dev phone is in §5. SMS over IP +the dev phone is in §5. The registration through a +sleep (1.2.5, §7.10) is the shell's but for when the phone has to be +awake (`WakeAt`) and the policy's wake after a local wait +(`RegRecovery::WakeTime`), which are `Imsd:Engine`'s, with tests; §7.10 +has what the shell does for it, and §5 what of that ran against +stand-ins on the workstation and what on the dev phone. SMS over IP (1.2.0, §7.9) keeps in the shell, among others, the service centre's source (`SMSC=` over EF_SMSP, `LoadSmsParameters`), the three counters (TP-MR, RP-MR, the concatenation reference), their @@ -442,7 +453,24 @@ What the suites pin: `RegRecovery` (thresholds, backoffs, the throttle schedule, Retry-After, which waits a Dial may cut short, when the old registration counts as gone, the holds a restart takes over, a binding the - network terminated); and SMS over IP (TS 24.341): `SmsOutbound` through a + network terminated; the look after a local wait: 5 s after the + refusal is reported, and the time a sleeping phone is to be woken for + it, 10 s to 15 min by value, counted for no packet service from the + modem's first such word since the network's last answer and for the + kernel's refusals (the kind of a refusal that names none) from the + first since the modem was last without service or the network last + answered, where what starts a count over is the shell's word of an + answer, a refused reconnect, a refused or throttled fresh attempt or + a terminated binding, and not a silent cycle or attempt (a success + starts everything over); a step that + follows no local wait, and a + registration written off meanwhile, at the policy's own time) and + `WakeAt` (when the phone has to be awake for imsd: now while a call + or a text is in flight; with a registration on a live flow the + refresh's due time or the subscription's renewal, whichever comes + first; with a dead flow under a registration the recovery's word, + a due step as now; never where nothing waits); + and SMS over IP (TS 24.341): `SmsOutbound` through a submission — the MESSAGE with the RP-DATA to the SC's PSI, its 202, the RP-ACK ending it as sent with the SC's time stamp; a refused final; an RP-ERROR with its cause and TP-FCS; the final's wait and the report's @@ -530,12 +558,17 @@ Rules: named here. The known gaps: the reg-event subscription schedule (the arming and KPN's `noresource` closure have run on hardware, the 60 s retry only on a - pre-fix build that renewed that closure; the retry on this code, the - renewal firing, Timer F, the doubling, a SUBSCRIBE `Retry-After`, the + pre-fix build that renewed that closure, and the renewal firing on + the workstation, with the boot clock set ahead, 1.2.5's record below; + the retry on this code, Timer F, the doubling, a SUBSCRIBE + `Retry-After`, the renew arm and the back-off's survival across a refresh have run nowhere — §3, §7.4); a `Dial` bringing a recovery step forward (imsd-ofonod refuses the `Dial` itself and imsd-dialerd forwards - it) is pinned in `tests/Engine` only; + it) has run on the workstation in a coverage gap, where the step it + brought forward was the look at the modem (1.2.5's record below); one + that brings a reconnect, or a fresh attempt that is due, forward is + pinned in `tests/Engine` only; the escalation by one refused refresh that carries a `Retry-After` — the escalation to a fresh registration is pinned in `tests/Engine` only; a resume echoing a multi-mechanism Security-Server list on the wire (the @@ -622,11 +655,17 @@ Rules: error, a bind() refused while the address is still on the link — which no bench reaches without fault injection (§3); a coverage gap on the air (no bench stages a radio gap without an RF shield) — the packet-service - read's rule has run through a fake `mmcli` only (2026-10-03: `searching` - and `detached` not counted, `connecting` with `unknown` counted), its - other states, ModemManager not answering and its second site (a refresh - unanswered over a reconnected flow) not at all, and `tests/Engine` pin - nothing of it; the REGISTER wait's diverting arms — a response to + read's rule has run through a fake `mmcli` (2026-10-03: `searching` + and `detached` not counted, `connecting` with `unknown` counted; the + bench of 1.2.5's record below: `searching` with `detached`, + `registered` with `attached`) and against the dev phone's own + ModemManager (2026-10-03: `connected` with `attached`, two silent + cycles counted); the read that follows a refresh unanswered over a + reconnected flow has found no packet service on no run (`refresh + unanswered while the modem reports no packet service`); and + `tests/Engine` + pin what the policy does with the modem's word, nothing + of the read; the REGISTER wait's diverting arms — a response to another transaction ignored, a provisional restarting the wait, a request (an INVITE among them) dispatched and answered under the wait; an incoming call answered from a session's @@ -1146,10 +1185,112 @@ Rules: removal (a Dial refused under a call that has no lock); a second refusal before a lock is given, which prints no line; an answer of logind's without a descriptor; a `PrepareForSleep` whose argument is - not one boolean; the lock wanted where it is held, which asks nothing - (a suspend told to ignore inhibitors under it; a Dial refused under - a call that has it); a desktop's own - request for a suspend under the lock. + not one boolean; a Dial refused under a call that has its lock, which + asks nothing, and what logind signals after a suspend told to ignore + inhibitors under a call (the next entry has such a suspend; its run's + log has the lock listed before and after it, and no line of logind's + for the signal); a desktop's own request for a suspend under the lock. +- The registration through a sleep (§7.10) is shell code but for + `WakeAt` and the recovery policy's wake after a local wait, which + `tests/Engine` pins. On the workstation + (`bench/bench-sleep.sh` of the capture above) the bench's sleep is a + preloaded `clock_gettime` under which the boot clock runs ahead of the + steady clock by the seconds a file names: with the boot clock 50 s + ahead a refresh set for 60 s went out 20 s into the registration, and + 1.2.4's did not; with it 599500 s ahead the reg-event subscription was + renewed, and 1.2.4's was not; with no jump the refresh came at its + awake time and not before. The second lock was taken and released + around a refresh, asked for again at the stand-in logind's + `PrepareForSleep(false)` where that had refused it at a refresh's + start, and held from a text's sending to its `failed` where the + stand-in network answered no MESSAGE (256 s). In a gap of 40 s + (the stand-in modem without packet service, no SYN let through, the + flow closed by the network) no connect was tried and no lock taken, + the modem was asked every 5 s, the daemon's own processor time + stayed under a second (an earlier build, which kept the dead flow's + socket through the gap, used 33.9 s of it), and the reconnect came + 3 to 5 s after the gap's end; a `Dial` inside such a gap ended at + once, with nothing reopened under it, and the reconnect then came + 0.5 to 1.5 s after the gap's end. In a gap of 70 s that let no + segment through, the daemon had no socket of the old flow at the + gap's end, and the reconnect came 3 to 5 s after it, 0.5 to 1.5 s + where a `Dial` had been tried inside the gap. A + daemon started inside a hold of 60 s held no lock for + it. With `WAKE_TRACE=1`, a test seam, the daemon writes a line + whenever the time the alarm is armed for changes (by the second; one + line for a run of times less than two seconds ahead), with a timer + or without: in a gap + that a refresh ran into, with the boot clock put 1000 s ahead inside + it, the alarm named 900 s ahead; after the gap's end, where the old + flow's socket had two connects refused, it named no more than 30 s + ahead, and the reconnect came 15 to 16 s after the gap's end; and + where the stand-in modem reported service twice inside such a gap, + the alarm named 900 s ahead again after each. Where the modem still + reported service when the refresh failed, where the network stayed + silent for 80 s after the modem's return (two silent cycles, then a + fresh registration) and over UDP, the alarm named no more than 30 s + ahead from the modem's return to the recovery. While a step waited + for the network (a refresh's 12 s without a reply, a connect's 12 s + without an answer and the 10 s before the next try, a fresh + registration's two waits with the stand-in network holding its + answers back) the alarm was named a new time every second, and + through the connect for a call's resend it was named no time 2 s or + more ahead. Stopped 1.5 s into a fresh registration's wait for its + first 401 and continued 2 s later (a stop and a continue end a + datagram receive under a timeout as a suspend's freeze does, §13), + the daemon + registered when the stand-in's held-back 401 came, five runs of five; + an earlier build and 1.2.4 gave the wait up at the continue, five of + five each. The bench's + namespace gives no `CAP_WAKE_ALARM`: every life of this daemon there + says `no wake + alarm (Operation not permitted)` and runs on. The alarm is the dev + phone's (KPN, a 7.3 kernel, this commit's code under the next + commit's version string, `phone/` there, 2026-11-28), with + `REFRESH_INTERVAL=120` and deep suspends asked of logind: every + refresh that fell due under a sleep went out within 3 s of its due + time, after a resume whose first interrupt was the RTC's alarm + (1.2.4, in three sleeps of that script as it was on 2026-11-25, on + the same kernel build, sent no refresh in seven minutes); seven + recovery steps that fell due under a sleep ran 1.5 to 3 s after + their time (an earlier build, 2026-11-25); under a call a suspend + told to ignore inhibitors was refused by the kernel (`alarmtimer`, + -16), twice, systemd-sleep having tried its second state; and under + a refresh whose REGISTER the phone itself dropped, such a suspend a + second into the wait was ended by imsd's alarm (the RTC's the first + interrupt, 30.6 s in), after which imsd's timer, zero at the test's + first look, read 29 to 30 s ahead at each of its 32 looks from 0.2 s + later to the wait's end, which the test saw about 10 s after that + first look (an earlier build, which set the alarm once + for the wait, read zero at every reading until the wait had ended; + in another run, with two more such suspends in that wait, it slept + to the test's own alarm of 75 s both times). The re-registration + after that refresh came 71 s after its `no reply`, the kernel + refusing nine connects over a minute first (the old flow's socket, + §7.10). Not run: a + suspend under a fresh registration's first wait with the daemon on a + phone (the receive's `EINTR` at a resume was seen there with a test + program, §13); an alarm clock with no RTC behind it (`no RTC that + can wake the phone`), and a `timerfd_settime` that fails (`wake + alarm not set`); the alarm's disarming and `wake trace: none`, + which nothing reaches once the loop runs; a second suspend told to + ignore + inhibitors under one wait with this daemon on a phone (the dev + phone is not to be suspended within ten seconds of a resume: the + earlier build's run with three did so, and its wifi firmware + crashed; and the wait the test stages, an unanswered refresh's + 12 s, is over at about that time); the 1.9 s through a connect for + a call's resend that waits (the bench's is answered at once); a + fresh registration's look at the modem finding no packet service + (the reconnect's has run); a bring-up the network defers or refuses, + and a stop during a bring-up's hold; the work's lock asked for at + the bus connection's coming (no record tells that request from the + step's own); a coverage gap on a + phone, and the wake for its slower look; on a phone, a sleep longer + than a refresh interval of 1800 s; the alarm at most 30 s ahead + through a step's wait while a text is in flight, which is read from + the code; + the reg-event subscription's renewal on a network. - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, @@ -1230,8 +1371,8 @@ the status snapshot live (main thread only). The Messaging interface's `List` and `Delete` read and unlink the received-message store there while the engine thread writes it — safe through the `.tmp` + `link(2)` publish (§7.9). On the same bus imsd is a client of logind's -(`org.freedesktop.login1`): the main thread takes its sleep inhibitor -there and listens for its `PrepareForSleep` (§7.6). +(`org.freedesktop.login1`): the main thread takes its sleep inhibitors +there and listens for its `PrepareForSleep` (§7.6, §7.10). Per answered call imsd forks `imsd-media` (`IMSD_MEDIA`, default next to the `imsd` binary, else `/usr/libexec/imsd-media`) with the addresses, ports and @@ -1400,8 +1541,12 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): with `ip xfrm`, the protected REGISTER over the negotiated transport (§10.1, `SIP_TRANSPORT`), `REGISTERED (fresh)`. Then the reg-event SUBSCRIBE (§7.4). -5. A keepalive re-REGISTER refresh at half the granted lifetime, within - 120–1800 s (`REFRESH_INTERVAL`), only while idle. Besides it an idle +5. A keepalive re-REGISTER refresh at half the granted lifetime (of + 3600 s where none was granted), within + 120–1800 s (`REFRESH_INTERVAL`), only while idle; the time runs + through a suspend, and a sleeping phone is woken for it where imsd + has its wake alarm (§7.10). + Besides it an idle phone whose registration stands sends what its reg-event subscription needs (§7.4). The CRLF keepalive (RFC 5626 4.4.1) imsd sent every 30 s until 1.2.3 is off unless `CRLF_KEEPALIVE` names an interval in whole @@ -1654,7 +1799,9 @@ configuration file's path — the bench's seam too). ### 7.4 Registration recovery (`RegRecovery`, `Imsd-Engine.cppm`) What the daemon does when the registration stops working after bring-up, as -a pure reducer the shell feeds with the clock and the network's answers. Two +a pure reducer the shell feeds with the clock, the network's answers and its +local waits (a connect the kernel refused, the modem without packet +service). Two kinds of failure reach it: a **refusal** (the network answered a refresh with a final other than 200 — a 401, re-authentication, included — or a fresh registration's REGISTER with a final other than the expected one: from 300 @@ -1673,6 +1820,7 @@ The policy, with its constants: |---|---| | Reconnect | Through the existing SA, then refresh. Back-off 5 s → 5 min (`ReconnectDelayMin`/`Max`). | | Escalate to a fresh registration | After one refused refresh whose `Retry-After` is at least a second (the network's considered answer; a `Retry-After` of 0 or one that does not parse counts as none; O2 2026-10-08: the refresh refused 503 with Retry-After 414 s, the refresh after that wait 503 with Retry-After 772 s) or a 401 (re-authentication, which imsd answers with a fresh registration rather than over temporary SAs), after two refused refreshes without one (`RefusalsBeforeFresh`), or two reconnect cycles that end without an answer (`SilentCyclesBeforeFresh`) while the modem reports packet service (`PacketServiceUp`: ModemManager's registration and packet-service state, as `ims-pdn-up.sh` reads them). A cycle that fails during a coverage gap is the phone's silence, not the network's: not counted, retried on the local-refusal pace, so a radio gap across a refresh does not escalate into a fresh registration, which KPN refuses while the registration is live and drops it for (§13). New Call-ID, new challenge, new SA pair (`registering fresh (recovery attempt N)`; with no fresh target the daemon restarts instead, §7.2 step 3). | +| No packet service | While the modem reports none (`PacketServiceUp`) the recovery tries no reconnect and no fresh attempt and holds no sleep off (§7.10; a bring-up does not ask the modem): the modem is asked again 5 s after each look while the phone is awake and no call is up (`LocalRetry`, the pause after a connect the kernel refuses locally as well), and where imsd has its wake alarm a sleeping phone is woken for the next look after as long again as that kind of wait has lasted, within 10 s and 15 min (`LocalWakeMin`/`Max`): where the modem has no service, since its first such word since the network last answered (an answered TCP connect of the resume or of a reconnect, a response to a REGISTER, a terminated binding, a success); where the kernel refuses the connect, since its first refusal since the modem was last without service or the network last answered, whichever came later. A report of service from the modem starts neither count over. A step that follows no local wait (the rows above and below) is woken for at its own time. A `Dial` on the dead flow meanwhile ends at once: nothing is reopened under it (§7.10). | | A refused or throttled fresh attempt | Waits on the **throttle schedule**: 21 min, growing ×1.5 to 60 (`ThrottleMinutesMin`/`Max`). KPN refuses a fresh SA pair on an address whose registration is live (§13), and drops that registration the moment an initial REGISTER arrives. | | A silent fresh attempt | Backs off 30 s → 10 min (`FreshDelayMin`/`Max`). | | `Retry-After` | Always wins over a shorter wait, honoured up to an hour (`RetryAfterMax`, the schedule's longest wait); a longer one is cut to an hour and the refusal heard again then. On a refused fresh attempt it replaces the schedule's wait, shorter or longer, never below 30 s (`FreshDelayMin`). | @@ -1719,11 +1867,16 @@ even after the holds run out, so a restart does not start it over at 21 min. When nothing is held the file is removed — when it is a regular file; `/dev/null` switches the knob off and anything that is not a regular file is emptied, never unlinked. The recovery policy's waits and the holds are -measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts; the -keepalive refresh gate, the CRLF keepalive (where `CRLF_KEEPALIVE` sets one), the reg-event retry and -renewal timers and the times SMS over IP measures (§7.9: its two waits, -the 30-minute age-out, the retransmission table's 32 s, the submissions -table's hour) run on the steady clock and count awake seconds only. +measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts, and +so are the keepalive refresh's gate and the reg-event subscription's +renewal ahead of its granted lifetime's end (§7.10; awake seconds in +the releases up to 1.2.4); the CRLF keepalive (where `CRLF_KEEPALIVE` +sets one), the reg-event subscription's Timer F, its retries (after a +refusal, an unanswered SUBSCRIBE, a send that failed) and its renewal +after the S-CSCF has ended it, and the times SMS over IP measures +(§7.9: its two waits, the 30-minute age-out, the retransmission table's +32 s, the submissions table's hour) run on the steady clock and count +awake seconds only. The **reg-event subscription** (RFC 3680; the network's own view of the binding) is one live dialog per registration, subscribed anew ahead of the @@ -1889,7 +2042,9 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t sends `PrepareForSleep` with false, and one wanted before the bus connection was there when the connection comes. Where logind gives none at all (`--session`: the session bus - has no logind) calls go on without one. + has no logind) calls go on without one. For a suspend that is told to + ignore inhibitors there is the wake alarm: what it holds under a call + and what it does not is in §7.10. - Emergency: a number `IsEmergency` classifies (112, 911, plus `EMERGENCY_NUMBERS`; SIM `EF_ECC` is not read yet) is tried as `urn:service:sos` first, with one fallback to a plain INVITE of the digits; @@ -2094,6 +2249,19 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: (§7.6): where no lock was held, no such line; `no sleep inhibitor from logind (…): asked again when it says a sleep is over` where logind gave none, once until a call's lock is next given. +- `wake alarm: a sleeping phone is woken when the registration's refresh + is due` when the alarm is first armed, `no wake alarm (…): a sleeping + phone is not woken for the registration's refresh` where the kernel + gives no such timer (its error) or has no RTC behind it (`no RTC that + can wake the phone`), `wake alarm not set: …` where setting it fails + (§7.10). +- `the modem reports no packet service: the reconnect waits until it has + it again` (or `the fresh registration waits …`) where a recovery step + finds the modem without packet service: once, and again after a look + that found it with service (§7.10). A cycle that was tried and went + unanswered, the modem then reporting none, has the line it had: `… + while the modem reports no packet service: not counted; next: …` + (§7.4). `wake trace: …` only with `WAKE_TRACE=1`, a test seam (§5). - `media pt=N octet=true|false -> [X]:P, telephone-event pt N|none` at a call's media start (`… pt N (theirs M)` when `DTMF_RX_PT` differs from the one we send with); `call X: DTMF '…' -> media leg (telephone-event pt @@ -2586,6 +2754,140 @@ do that answers without state. — its flatpak on the `flatpak.catcrafts.net` remote accompanies this release. +### 7.10 A phone that sleeps + +Nothing of imsd runs while the phone is suspended. What it has to do at +a certain time the phone has to be awake for, and what it waits for +must not be cut off by a suspend. This is what sees to that. + +- **The refresh, and the subscription's renewal ahead of its expiry, run + on the boot clock.** + The network counts + a registration's lifetime while the phone sleeps. The refresh (§7.2 + step 5) is due on `CLOCK_BOOTTIME`, as the recovery policy's waits are + (§7.4), and so is the renewal of the reg-event subscription ahead of + its granted lifetime's end. In the releases up to 1.2.4 both counted + awake seconds, and a registration lapsed on a phone that slept most + of its two hours (§13). +- **A wake alarm.** A timer on `CLOCK_BOOTTIME_ALARM` (the kernel's alarm + timer, which sets the RTC's alarm for a suspend; it takes + `CAP_WAKE_ALARM`, which the service has) is armed at the end of every + turn of the loop that takes no command off the queue (a turn that + takes one handles it and goes straight to the next turn) for the time + `WakeAt` names (`Imsd:Engine`): now while a call or a text is in + flight (the hold of the next entry); else, with a + registration on a live flow the refresh's due time, or the reg-event + subscription's renewal where that comes first; with a dead flow under + a registration the recovery policy's word (`RegRecovery::WakeTime`: its + next step, and the slower look after a local wait, below); and none + where nothing waits to be done. A bring-up's wait for the policy arms + the policy's time itself. The timer 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, or has no RTC behind it, + the journal says so once, and nothing wakes the phone for imsd. A + resume by itself sends nothing: a refresh that is not due does not go + out. +- **Work in flight has a lock and the alarm.** Beside the call's lock + (§7.6) the main thread asks for a second block inhibitor of + logind's, in the way it asks for the call's + (its reason `a registration step or a text in flight`), while a step + of the + registration exchanges with the network (the refresh, a reconnect, a + fresh registration, the bring-up: `Engine::Step`) and while a text is + being sent, whose two waits count awake seconds (§7.9); not while a + bring-up waits out a hold the network set, which can be an hour + (§7.4). For a suspend that begins all the same (logind refused such + a lock where a suspend's operation was already running, §13; a request + can tell it to ignore inhibitors) there is the alarm. Under a call + and under a text in + flight, and where a step is due that the next turn runs (but for the + look after a local wait, below, which has its own slower time), it + is set 1.9 s ahead at every such turn, and the kernel refuses a + suspend under an alarm less than two seconds ahead (§13); that holds + where there is + an alarm and while the loop turns or a call's resend waits for its + connect, not through a turn that takes longer otherwise (a media leg + being stopped, a helper program) and not through a registration + step; and the suspend has to come to the kernel's check before the + alarm set last has fired, after its sync and its freeze of the + processes (§13). A step keeps the + alarm at most 30 s ahead while it waits for + the network, whatever else is in flight: where imsd has its wake + alarm, a sleep that begins under such a wait ends there, and the + step goes on (this section's last paragraph has what is left). The + alarm fires once + (§13), and a wait can outlast the sleep it ended, so it is set anew + before every second of a wait for the network (a connect's answer, + the pause before the next try, a REGISTER's answer): where the wait + goes on after a wake, it stands again within a second. One of those + waits, for the fresh registration's first answer, is a receive with a + timeout, which a suspend's freeze ends with `EINTR` (§13): it is + taken up again for the rest of its time. A wait for a helper program + keeps the alarm that stood when it began. +- **A coverage gap costs little sleep.** While the modem reports no + packet service the recovery tries no reconnect and no fresh + registration, and no lock is taken for one: either would wait for + answers that cannot come. A dead flow's socket that is still open at + that look is closed there without the FIN's exchange (`Abort`): over + TCP, + left open it is readable at every turn of the loop, which would + spin instead of waiting, and closed with a FIN it would hold the + address pair against the reconnect after the gap, as the socket of + a flow does that a step closed after a wait without an answer (the + kernel's refusals, below). (The refresh that + runs into the gap waits its 12 s under the lock, once. A bring-up + does not ask the modem: one that meets a gap makes its attempts + under the lock. A `Dial` that finds the flow dead in the gap ends + at once: the recovery's immediate try for it tries nothing either, + and the INVITE fails on a flow that is gone.) Awake and with no call + up, the modem is + asked again every 5 s; a sleeping phone is woken for the next look + after as long again as the modem has been without service, 10 s at + the least and 15 min at the most (§7.4's table). That time is + counted from the modem's first word of no service since the network + last answered (§7.4's table has what counts as its answer): the + modem's word for its + service starts no count over, and where it alternates at the edge + of coverage an attempt made on it costs its wait under the lock + (a TCP reconnect's 34 s where nothing answers) while the looks keep + their pace. Every + step that follows no local wait is woken for at the policy's own + time (§7.4's table): a reconnect cycle the network was silent to is + no local wait where the modem has service, a fresh attempt it was + silent to never is. + The kernel refuses a connect locally for as long as the + old flow's socket holds the address pair, which clears in awake + seconds (TIME_WAIT's 60, an unanswered FIN's retransmissions): two + tries 10 s apart under the lock at each look. That is the other + local wait: awake and with no call up, the next look comes 5 s after + each; a sleeping phone is woken for it after as long again as the + kernel's refusals have lasted, 10 s at the least and 15 min at the + most, counted from its first refusal since the + modem's last word of no service or the network's last answer, + whichever came later. The slower look does not know + the registration's lifetime: a gap that ends shortly before the + lifetime does can cost the registration. + +What of the registration's schedule and of the texts' times still +counts awake seconds is in §7.4's paragraph on the clocks; a step's own +waits for the network (a connect's answer, the pause before the next +try, a REGISTER's answer) count them too, under the step's lock. +Nothing holds a sleep off under the bring-up script, which runs before +the daemon (§7.3), nor in the wait before a restart after a failure: a +phone suspended there does not register until it is awake again. And +from the +moment the alarm has woken the phone to the step it woke it for, the +loop's next turn (up to a second where a bring-up waited out a hold), +there is neither alarm nor lock: a desktop that asked for a suspend +again within that time would have the phone sleep through the step +until something else woke it. For up to a second after the alarm has +ended a sleep under a step's wait it is not set again yet either +(where the freeze has ended the receive of the fresh registration's +first wait with time left, §13, it is set at once), and a helper +program the step goes on to from a wait in that second has none until +the step's next wait for the network: a suspend told to ignore +inhibitors that began there would not be ended by imsd. + ## 8. D-Bus ABI and desktop integration ### 8.1 `net.catcrafts.IMS1` (frozen) @@ -2854,7 +3156,8 @@ line, having a fresh target decides what a refused or failed resume leads to — the fresh registration (a refusal without a Retry-After is not counted) or, with none, the pair kept for the restart, removed, or the idle (§7.2 step 1) — and a comma-separated `PCSCF=` stops the bring-up before the -resume. +resume. `WAKE_TRACE=1` is a test seam of the wake alarm's (§5, §7.8), no +configuration, and in none of the README's tables. ### 10.2 imsd-media (per call, set through imsd's environment) @@ -3144,11 +3447,12 @@ the related code. packet on the ims netdev: the modem ended none of six sleeps in one and one of seven in the other, for a file-system request that no packet had preceded (2026-11-24). What an idle phone with a standing - registration still sends is the refresh, once in 1800 awake seconds on - KPN (three packets out, the dormancy report 11 to 13 s and the request - 102 to 104 s after them), and what its reg-event subscription needs - (§7.4): on KPN a renewal once in 599400 awake seconds (the grant of - 600000 s less 600). Awake and idle + registration still sends is the refresh, once in 1800 s on KPN, awake or, + where imsd has its wake alarm, asleep (§7.10; three packets out, the + dormancy report 11 to 13 s and + the request 102 to 104 s after them), and what its reg-event + subscription needs (§7.4): on KPN a renewal once in 599400 s (the grant + of 600000 s less 600). Awake and idle on a 100-mA USB port the dev phone's battery lost 140 mA under 1.2.3's ping and 59 mA without it (its own counter over one window of 40 min and one of 33; 2026-11-24). @@ -3158,6 +3462,55 @@ the related code. between). Where a network's P-CSCF closes or forgets a flow it hears nothing on, `CRLF_KEEPALIVE` is that network's setting (§7.2 step 5 has what imsd does without it). +- **A registration counted in awake seconds lapsed on a phone that + slept most of its two hours** (the dev phone, KPN, imsd 1.1.0, + 2026-11-19; the fp6 + journal's power lane, `2026-11-19-wake-tests`): registered at 09:15:48 + with a lifetime of 7200 s, the phone in a loop of suspends from 09:26 + to 11:22, no refresh + went out; the network's NOTIFY that the binding had expired woke the + phone at 11:16:37, the fresh registration met the throttle above, and + the phone registered again at 11:37:38. +- **The kernel refuses a suspend under an alarm timer less than two + seconds ahead** (`alarmtimer_suspend`, `kernel/time/alarmtimer.c`, + read at v7.3: -EBUSY, and a wakeup event of two seconds, where an + RTC stands behind the alarm timer; without one it lets the suspend + pass). The check is in the suspend's device phase, after the kernel + has synced and frozen the processes: an alarm that has fired by then + is off the queue and refuses nothing. On the dev + phone (2026-11-25 and 2026-11-28), `systemctl suspend -i` under a call + or a text in flight: logind let it through, the kernel refused it, + systemd-sleep tried the next state of its list and was refused again, + and the phone did not suspend; each refused attempt has its line in + the kernel's log, `alarmtimer alarmtimer.0.auto: PM: failed to + suspend: error -16` (six of six in the boot of 2026-11-28 13:22). +- **A timer on an alarm clock made with `timerfd_create` and set with no + interval fires once** + (read at v7.3: `alarmtimer_fired`, `kernel/time/alarmtimer.c`, takes + the alarm off the kernel's queue and restarts nothing; + `timerfd_alarmproc`, `fs/timerfd.c`, marks the timer expired, counts + a tick and wakes whoever waits on the descriptor; an interval would + be applied only when the timer is next accessed, by a read or by + `timerfd_gettime`). imsd sets no interval and neither reads nor + queries its timer: after it has fired there is no alarm of imsd's + until the next `timerfd_settime`, which is why a wait sets it every + second (§7.10). +- **A suspend's freeze ends a datagram receive that has a timeout with + `EINTR`** + (read at v7.3: `freeze_task`, `kernel/freezer.c`, wakes a user thread + that it cannot freeze where it sleeps as a pending signal would; a + datagram receive sleeps interruptibly and not freezably and leaves + with `sock_intr_errno`, `net/core/datagram.c` and + `include/net/sock.h`, which under a finite `SO_RCVTIMEO` is `-EINTR`, + and that the kernel does not take up again as it does an interrupted + `poll`). On the dev phone (2026-11-28) a test program's `recvfrom` + under a timeout returned `EINTR` at the resume from a suspend, in + pieces of a second and in one long wait alike (the fp6 journal's + `2026-11-25-through-sleep` capture, `evidence/recv-eintr/`). A stop + and a continue (`SIGSTOP`, `SIGCONT`) end such a receive the same + way, which is how the bench stages it (§5). The daemon's wait for a + fresh registration's first answer is such a receive + (`AwaitInitialFinal`). - **logind refused a block inhibitor for sleep where it was asked for during a suspend's operation** (systemd 262.2, the dev phone, 2026-11-25 and 2026-11-28): `Inhibit` diff --git a/implementations/main.cpp b/implementations/main.cpp index c83b791..cd893af 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -44,6 +44,7 @@ its subscriber set on the main thread too. #include #include #include +#include #include #include #include @@ -482,11 +483,17 @@ public: // datagram socket to the same peer — the kernel then delivers that peer's // 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 - // one attempt. - bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0) { + // one attempt. `tick` is called before every try and then before every + // second of a try's wait for its answer and of the pause before the + // 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& tick = {}) { transport_ = t; lastConnectLocal_ = false; int fam = Is6(local) ? AF_INET6 : AF_INET; + if (tick) tick(); if (t == Transport::Udp) { int fd = socket(fam, SOCK_DGRAM, 0); if (fd < 0) return SocketFailed(); @@ -507,6 +514,7 @@ public: } int silent = 0; for (int attempt = 0; attempt < tries; attempt++) { + if (tick && attempt > 0) tick(); int fd = socket(fam, SOCK_STREAM, 0); if (fd < 0) return SocketFailed(); int one = 1; @@ -527,7 +535,7 @@ public: int err = localRefusal ? errno : 0; if (rc < 0 && errno == EINPROGRESS) { pollfd p{fd, POLLOUT, 0}; - if (poll(&p, 1, 12000) > 0) { + if (PollTicked(p, 12000, tick) > 0) { socklen_t el = sizeof err; getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el); connected = (err == 0); @@ -554,10 +562,24 @@ public: return false; } Log(std::format("connect failed; retry in 10s ({}) [{}/{}]", why, attempt + 1, tries)); - sleep(10); + for (int s = 0; s < 10; s++) { + if (tick) tick(); + sleep(1); + } } 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& 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 // refusal like a connect() the kernel turns down. bool SocketFailed() { @@ -600,7 +622,10 @@ public: if (send(fd_, "\r\n\r\n", 4, MSG_NOSIGNAL) <= 0) alive_ = false; } - std::optional RecvMsg(double timeoutSec) { + // The next whole message on the flow, within `timeoutSec`. With a + // `tick` the wait for the socket is PollTicked's (Connect has what the + // tick is for). + std::optional RecvMsg(double timeoutSec, const std::function& tick = {}) { auto deadline = std::chrono::steady_clock::now() + std::chrono::duration_cast(std::chrono::duration(timeoutSec)); for (;;) { @@ -609,7 +634,7 @@ public: if (now >= deadline) return std::nullopt; int ms = static_cast(std::chrono::duration_cast(deadline - now).count()); pollfd p{fd_, POLLIN, 0}; - int r = poll(&p, 1, ms); + int r = PollTicked(p, ms, tick); if (r <= 0) { if (r == 0) return std::nullopt; if (errno == EINTR) continue; return std::nullopt; } std::optional m; if (!ReadOnce(m)) return std::nullopt; @@ -1011,7 +1036,7 @@ struct StatusSnapshot { // engine -> main-loop event struct Event { - enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type; + enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState, Work } type; CallInfo info; // Added std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id) StatusSnapshot status; // Registration/Status @@ -1020,6 +1045,7 @@ struct Event { 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 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; @@ -1414,6 +1440,11 @@ GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt // 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 @@ -1421,6 +1452,8 @@ struct SleepLock { 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; @@ -1464,6 +1497,7 @@ void OnPrepareForSleep(GDBusConnection*, const gchar*, const gchar*, const gchar g_variant_get(params, "(b)", &entering); if (entering) return; HoldSleepOff(CallLock, CallLock.want); + HoldSleepOff(WorkLock, WorkLock.want); } gboolean OnIdleEvent(gpointer data) { @@ -1508,6 +1542,10 @@ gboolean OnIdleEvent(gpointer data) { Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text)); g_main_loop_quit(MainLoop); break; + case Event::Type::Work: + WorksInFlight = std::max(0, WorksInFlight + (ev->on ? 1 : -1)); + HoldSleepOff(WorkLock, WorksInFlight > 0); + break; case Event::Type::SmsReceived: 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))); @@ -1685,6 +1723,7 @@ public: } for (;;) { try { + Step step(*this); BringUp(); break; } catch (const Stopping&) { @@ -1758,6 +1797,7 @@ public: Execute(call_->OnDeadline()); MaybeDropCall(); } + ArmWake(WakeDue()); if (auto msg = sip_.RecvMsg(0.3)) OnFlowMessage(*msg); } // shutdown: release an active call, keep the SA/registration for resume @@ -1819,11 +1859,19 @@ private: // after it, not before. False when the engine is stopping. bool WaitForPolicy() { 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()) { waited = true; 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)); } + 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(); return !quit_.load(); } @@ -1907,7 +1955,7 @@ private: bool subPending_ = false; // SUBSCRIBE sent, no final yet double subSentAt_ = 0; 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, ahead of its granted expiry (0: none) + double subRenewAt_ = 0; // the live subscription is subscribed anew at this time on the boot clock, ahead of its granted expiry (0: none) double subRetryDelay_ = 60; // 60 s doubling to 10 min between failed SUBSCRIBEs int portPs_ = 0; // P-CSCF protected server port (reconnect target) imsd::engine::RegRecovery recovery_; // what to do when the registration stops working @@ -1929,8 +1977,10 @@ private: std::function callReply_; // timers - double lastRefresh_ = 0; - double lastKa_ = 0; + double lastRefresh_ = 0; // on the boot clock (Boot): the registration's lifetime runs at the network while the phone sleeps + double lastKa_ = 0; // on the steady clock (Mono) + 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 quit_{false}; bool devMode_ = false; @@ -1966,6 +2016,133 @@ private: return std::chrono::duration(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(at); + its.it_value.tv_nsec = static_cast((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 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 holdAlarm_ = [this] { ArmWake(Boot() + WakeHold); }; + void PostWork(bool on) { + auto ev = std::make_unique(); + ev->type = Event::Type::Work; ev->on = on; + PostEvent(std::move(ev)); + } + std::optional PopCmd() { std::scoped_lock g(cmdLock_); if (cmds_.empty()) return std::nullopt; @@ -2266,10 +2443,11 @@ private: SetTransport(t); // Local refusals (TIME_WAIT after a restart) keep retrying; two // silences mean the flow is not coming back — fresh instead. - if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2)) { + if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2, netAlarm_)) { Log(std::format("resume connect failed; {}", ResumeFailedNext())); return ResumeOutcome::Failed; } + if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered(); reg_.callid = *ps->callid; reg_.ftag = ps->ftag.value_or(""); // The refresh must carry the SAME Contact URI as the stored binding; @@ -2460,7 +2638,7 @@ private: } } bool autoTcp = (sipPolicy_ == "auto" && transport_ == Transport::Tcp && !tcpKnownGood); - if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0)) { + if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0, netAlarm_)) { if (autoTcp) { // Two unanswered TCP connects: treat the P-CSCF as UDP-only // and register again over UDP — a new challenge and a new SA @@ -2529,7 +2707,8 @@ private: double deadline = Mono() + 12.0; for (;;) { double left = deadline - Mono(); - auto m = left > 0 ? sip_.RecvMsg(left) : std::nullopt; + // the alarm is set anew before every second of the wait (Step) + auto m = left > 0 ? sip_.RecvMsg(left, netAlarm_) : std::nullopt; if (!m) throw std::runtime_error(std::format("no reply to {}", what)); auto st = imsd::sip::Status(*m); if (!st) { @@ -2542,6 +2721,7 @@ private: if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what)); continue; } + recovery_.OnNetworkAnswered(); // a response to our REGISTER, whatever it says: the network is in reach if (*st >= 200) return *m; Log(std::format("{} -> {} (provisional); waiting for the final", what, *st)); deadline = Mono() + 12.0; @@ -2563,6 +2743,9 @@ private: for (;;) { double left = deadline - Mono(); 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(left); long usec = static_cast((left - static_cast(sec)) * 1e6); if (sec == 0 && usec == 0) usec = 1000; @@ -2570,7 +2753,14 @@ private: setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); sockaddr_storage src; socklen_t sl = sizeof src; ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast(&src), &sl); - if (n < 0) break; + if (n < 0) { + // 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); std::string why; auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast(n)), &why); @@ -2585,6 +2775,7 @@ private: continue; } int st = *imsd::sip::Status(m); + recovery_.OnNetworkAnswered(); if (st >= 200) { close(us); return m; } Log(std::format("unprotected REGISTER -> {} (provisional); waiting for the final", st)); deadline = Mono() + 8.0; @@ -2717,11 +2908,8 @@ private: void MaybeRefresh() { if (call_ || reg_.callid.empty()) return; if (!sip_.Alive()) return; // MaybeReconnect owns dead-flow recovery - long exp = reg_.expiry ? reg_.expiry : 3600; - 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; + if (Boot() - lastRefresh_ < RefreshInterval()) return; + Step step(*this); try { RefreshPani(); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); @@ -2748,7 +2936,7 @@ private: Log(std::format("keepalive re-REGISTER failed: {}", e.what())); CloseFlowAfterWait(); } - lastRefresh_ = Mono(); + lastRefresh_ = Boot(); lastKa_ = Mono(); } @@ -2787,7 +2975,7 @@ private: if (recovery_.Reconnectable() && call_->ResendDue()) { Log(std::format("call {}: the client flow died before any response to the INVITE; reopening it", call_->Uni())); sip_.Abort(); - ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1) && Execute(call_->OnFlowReopened()); + ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1, 0, holdAlarm_) && Execute(call_->OnFlowReopened()); } if (!ok && call_ && !call_->Terminated()) Execute(call_->OnFlowLost()); MaybeDropCall(); @@ -2836,15 +3024,48 @@ private: // refuses while the old one is live, and drops it for. void CoverageGap(std::string_view what) { if (registered_) { registered_ = false; EmitStatus(true); } - recovery_.OnLocalRefusal(Boot()); + recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService); 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() { using F = imsd::engine::RegRecovery::Failure; + if (NoService("the reconnect")) return; Log("client flow dead; reconnecting"); + Step step(*this); sip_.Close(); - if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2)) { + if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2, 0, netAlarm_)) { if (AddressGone()) return; if (sip_.LastConnectLocal()) { if (registered_) { registered_ = false; EmitStatus(true); } @@ -2855,6 +3076,10 @@ private: RecoveryFailed(F::Silent, 0, "P-CSCF silent"); 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 { RefreshPani(); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); @@ -2903,7 +3128,9 @@ private: // nothing is retried until the next fresh attempt. void FreshRecover() { using F = imsd::engine::RegRecovery::Failure; + if (NoService("the fresh registration")) return; Log(std::format("registering fresh (recovery attempt {})", recovery_.freshAttempts + 1)); + Step step(*this); sip_.Close(); saReplaced_ = false; // this attempt's, whatever fails first // the subscription dialog is the registration's and goes with the @@ -3039,7 +3266,7 @@ private: bool was = registered_; registered_ = true; EmitStatus(!was); - lastRefresh_ = Mono(); lastKa_ = Mono(); + lastRefresh_ = Boot(); lastKa_ = Mono(); // a refresh or a reconnect opens no subscription dialog while imsd // holds one for the registration or has a retry scheduled; a fresh // registration (or a start) has none yet, and a fresh attempt drops @@ -3103,7 +3330,7 @@ private: ScheduleResubscribe(0); } if (call_ || !registered_ || !sip_.Alive()) return; - if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Mono() >= subRenewAt_) { + if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Boot() >= subRenewAt_) { // the granted lifetime is running out: a new dialog (the S-CSCF // closes the previous one — KPN with noresource), on the same // registration @@ -3121,8 +3348,8 @@ private: // end, or halfway through a shorter grant. void ArmSubscriptionRenewal(long expires) { double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0; - subRenewAt_ = Mono() + std::max(ahead, 30.0); - Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Mono())); + subRenewAt_ = Boot() + std::max(ahead, 30.0); + Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Boot())); } // The network's view of our binding (RFC 3680 reginfo), read from any @@ -3317,6 +3544,7 @@ private: const bool wantsReport = p.statusReport; const std::string destination = p.number; 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()); // 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 @@ -3340,6 +3568,7 @@ private: void EndSms() { rpMr_ = smsOut_->NextRpMr(); smsOut_.reset(); + PostWork(false); } // The message in flight ended: the next queued message starts (its @@ -3933,6 +4162,7 @@ void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) { "/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; 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; } diff --git a/interfaces/Imsd-Engine.cppm b/interfaces/Imsd-Engine.cppm index 607b7bc..17ff177 100644 --- a/interfaces/Imsd-Engine.cppm +++ b/interfaces/Imsd-Engine.cppm @@ -3,8 +3,8 @@ /* Imsd:Engine — the daemon's decisions as pure reducers: the call state -machine (CallMachine), the registration recovery policy (RegRecovery, -its own section below) and SMS over IP's (the last paragraph here). +machine (CallMachine), the registration recovery policy (RegRecovery, its own section below), when the phone has +to be awake for imsd (WakeAt, with the policy's WakeTime after a local wait) and SMS over IP's (the last paragraph here). A CallMachine owns one call's SIP dialog, outgoing or incoming. It never touches a socket, a clock, or a subprocess: each event (the INVITE's @@ -76,8 +76,8 @@ export namespace imsd::engine { // ---- registration recovery policy --------------------------------- // // What the daemon does when the registration stops working after - // bring-up, as a pure reducer: the shell supplies the clock and the - // network, this decides the next step and how long to wait for it. Two + // bring-up, as a pure reducer: the shell supplies the clock, the network and (at a local wait) its kind, 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 // kinds of failure reach it. A REFUSAL: the network answered a refresh // with a final other than 200 — a 401, re-authentication, included — or // a fresh registration's protected REGISTER with a final other than 200 @@ -131,9 +131,9 @@ export namespace imsd::engine { // refused or throttled fresh attempt, a terminated binding's probation // or its refusal schedule), which nothing cuts short — a // restart of the process neither: the shell keeps the holds (Holds) - // and hands them to the next one (Restore). The shell supplies the - // clock and the network; this holds the deadlines and names the next - // step (Next). Success resets everything. + // and hands them to the next one (Restore). The shell supplies the clock, what the network answered or did not and, + // at a local wait, its kind (the kernel's refusal, the modem's word); this holds the deadlines and each kind's count, + // and names the next step (Next) and when a sleeping phone is woken for it (WakeTime). Success resets everything. struct RegRecovery { enum class Failure { Refused, Silent, Throttled }; enum class Step { Reconnect, Fresh }; @@ -160,6 +160,21 @@ export namespace imsd::engine { // untouched. Dev phone 2026-09-24: four such refusals in 26 s read // as two silent cycles cost a fresh registration into the throttle. static constexpr double LocalRetry = 5; + // 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 silentCycles = 0; @@ -170,10 +185,14 @@ export namespace imsd::engine { bool fresh = false; // the next registration attempt is a fresh one bool oldGone = false; // the old registration is gone: nothing to reconnect over bool terminated = false; // the network terminated our binding, and the policy has counted it - // the deadlines, on the shell's clock + // the deadlines and a local wait's state, on the shell's clock double backoffUntil = 0; // self-imposed: no step before this; a Dial clears it double holdUntil = 0; // the network's word for any attempt (a Retry-After on a refresh): nothing clears it double freshHoldUntil = 0; // no fresh attempt before this (the schedule after a refused or throttled fresh attempt, a fresh Retry-After, probation, rejected/unregistered) + bool 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 Reconnectable() const { return !oldGone; } @@ -213,7 +232,32 @@ export namespace imsd::engine { return {Step::Fresh, freshAt}; } - void OnLocalRefusal(double now) { backoffUntil = now + LocalRetry; } + void OnLocalRefusal(double now, Local kind = Local::Kernel) { + 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 // cycle; `status` is the refusal's. The backoff paces the next step; @@ -223,6 +267,8 @@ export namespace imsd::engine { // registration is due says the old registration is gone (KPN drops // it the moment an initial REGISTER arrives, throttled or not). void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) { + 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(std::min(retryAfter, RetryAfterMax))); // A cycle over a registration already known gone — the network // terminated the binding while the cycle waited for its final — @@ -246,6 +292,8 @@ export namespace imsd::engine { // it off 30 s → 10 min. A reconnect over the old SA meanwhile waits // at least the reconnect backoff. void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) { + lastLocal = false; + if (f != Failure::Silent) OnNetworkAnswered(); freshAttempts++; fresh = true; if (saReplaced) oldGone = true; @@ -271,6 +319,8 @@ export namespace imsd::engine { // reg-event dialog of the account carries it, a NOTIFY may be // retransmitted), and never shortens a hold already running. void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) { + lastLocal = false; + OnNetworkAnswered(); bool reported = terminated; terminated = true; oldGone = true; @@ -289,7 +339,7 @@ export namespace imsd::engine { // The stored registration is not there to reconnect over (a resume // that failed at bring-up found its SAs unusable, or there are none). - void OldGone() { oldGone = true; fresh = true; } + void OldGone() { oldGone = true; fresh = true; lastLocal = false; } // A user's Dial cuts the backoff short, never the network's word. void OnDial() { backoffUntil = 0; } @@ -297,6 +347,24 @@ export namespace imsd::engine { 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 // imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play). // `dtmfPt` is the telephone-event payload type at the codec's clock diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index 4d1ab5f..1ee15da 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -20,7 +20,9 @@ // fresh backoffs, the throttle schedule, Retry-After, which waits a Dial // may cut short, when the old registration counts as gone, the holds a // restart takes over (Holds/Restore), and a binding the network terminated -// (OnBindingTerminated). Then SMS over IP: the status-report book +// (OnBindingTerminated). Then WakeAt, when the phone has to be awake for +// 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 // message delivered with its last segment, a permanent failure the last // word, pending kept, another recipient no match, a reused TP-MR, a @@ -1396,6 +1398,129 @@ 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) ---------- { using namespace imsd::sms;