imsd-messages/interfaces/ImsdMessages-Sync.cppm

632 lines
31 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
/*
ImsdMessages:Sync — the app's side of imsd's Messaging interface, as pure
logic over an abstract transport.
imsd keeps a received text it could store until the app deletes it: the
app lists at start and after every Received, imports what it lacks, then
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
deletes imsd's copy; the --send errand leaves that to the instance that
owns the user's store. The signals are unicast to subscribers, so Subscribe
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
goes first, every time net.catcrafts.IMS1 appears on the bus (imsd's
restart empties its list). A Send answers with an id at once; the outcome
is a StateChanged for that id. All of it runs on one thread (the GLib main
loop in the app, the test's thread here); the transport answers through
callbacks, never from inside the call.
*/
export module ImsdMessages:Sync;
import std;
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
import :Number;
import :Model;
import :Store;
export namespace ImsdMessages {
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
struct BusError {
enum class Kind : std::uint8_t { NoOwner, AccessDenied, NotSupported, NotFound, InvalidArgs, Timeout, Other };
Kind kind = Kind::Other;
std::string message;
};
// GetStatus's dictionary (imsd AGENTS.md §8.4), the subscriber's own
// number in it (`ppi`, a tel: URI as the frozen interface gives it; ""
// when the network gave none) and the SIM's operator (`operator`: its
// MCC, then its MNC). No count of the store: GetStatus
// is open to every local account, and a count would tell them when a
// text arrived (imsd 2.0.0); List is the gated way.
struct Status {
bool enabled = false;
std::string smsc;
std::string ownNumber;
std::string simOperator;
bool registered = false;
std::uint32_t subscribers = 0;
};
using Done = std::function<void(std::optional<BusError>)>;
using StatusResult = std::expected<Status, BusError>;
using ListResult = std::expected<std::vector<ReceivedMessage>, BusError>;
using SendResult = std::expected<std::string, BusError>;
// What Sync needs from the bus. The GDBus client implements it; the
// tests a fake that answers when told to. A Send is answered by imsd,
// or by the bus once imsd has left it, never by a clock of the
// transport's own: Sync fails the row at an error and Retry sends the
// text again, and imsd sends what it was asked once its polkit prompt
// lets the call through, however late.
struct ImsdTransport {
virtual ~ImsdTransport() = default;
virtual void Subscribe(Done done) = 0;
virtual void GetStatus(std::function<void(StatusResult)> done) = 0;
virtual void List(std::function<void(ListResult)> done) = 0;
virtual void Delete(std::string id, Done done) = 0;
virtual void Send(std::string number, std::string text, bool statusReport, std::function<void(SendResult)> done) = 0;
};
// What the bus delivers; Sync implements it.
struct ImsdEvents {
virtual ~ImsdEvents() = default;
virtual void OnImsdAppeared() = 0;
virtual void OnImsdVanished() = 0;
virtual void OnReceived(const ReceivedMessage& message) = 0;
virtual void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) = 0;
virtual void OnRegistrationChanged(bool registered) = 0;
Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name The GLib side of the app. Variant reads imsd's Received dictionary by key and type as its SmsVariant writes it (`to`, the number the text arrived for, a tel: URI read like the status's `ppi`; `operator`, the SIM it arrived under), the GetStatus one with the subscriber's own number and the SIM's operator in it (`ppi`, a tel: URI as the frozen interface gives it; `operator`), and maps a GError to the core's error kinds off GDBus's own mapping. Client is the Sync logic's transport: asynchronous calls with their continuations as user data — every reply guarded where it is delivered (OnCallDone), as are the signal handlers and the name watch's callbacks: a throw is a fault the events hear, not the end of the process — the calls behind imsd's polkit gate allow interaction: Subscribe, List and Delete wait two minutes; Send has no bound of the client's, since imsd sends the text once its prompt lets the call through, however late, and a Send given up on would be failed by Sync and be sent all the same; GetStatus ten seconds — (one call: the Messaging status carries the own number, imsd reading both from one snapshot; AGENTS.md §1 names both interfaces), the Messaging and RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose appeared callback is where Sync subscribes. Notifier shows one desktop notification per conversation and replaces it as more texts arrive: one Notify at a time per conversation, since the id to replace comes with the answer; its default action asks the app for that conversation; the body is escaped when the server renders markup (GetCapabilities, asked once; Plasma and GNOME do), so a text's '<' or '&' shows as typed. Instance owns net.catcrafts.ImsdMessages and serves org.freedesktop.Application there, the Desktop Entry Specification's interface of a running application: Activate, Open and ActivateAction, each with its platform data — sent empty and not read: nothing in the app can use an activation token yet — and one action, quit, any other refused (the object registered before the name is asked for, so a launch that forwards the moment the name is granted finds it; Own tells a name another instance holds from a request that failed or was refused, and keeps the error's words); it forwards a call to the owner. project.cpp computes the gio flags once for the bus library, the executable and the Decode test. Tested: tests/Decode (every key of imsd's Received dictionary, one with ten of them, GetStatus, the own number, the SIM's operator, the error kinds, the markup escape, the parameters of the instance's three calls).
2026-10-17 23:45:29 +02:00
virtual void OnFault(std::string_view what) {} // a callback threw (a read, an allocation; the store catches its writes): logged, not fatal
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
};
// What Sync tells the UI and the notifier. A call can come from inside
// one of Sync's own — OnStatus from the store's word on a write (Send's
// Add, Retry's, OnStateChanged's), OnMessageChanged from Send — so a
// listener acting on one must not take the call it is inside as
// returned (the --send errand latches before it calls Send). Sync calls
// it through GuardedListener: a throw out of a handler is caught and
// told once, so no handler can stop Sync's own sequence.
struct SyncListener {
virtual ~SyncListener() = default;
virtual void OnStatus(const AppStatus&) {} // the banner's inputs changed
virtual void OnImported(const Message&) {} // a received text entered the store
virtual void OnUnstored(const Message&) {} // a signalled text the store refused: Sync holds it, and it may be nowhere else
virtual void OnMessageChanged(const Message&) {} // a message's state changed
virtual void OnLog(std::string_view) {}
};
// The listener as Sync calls it: a throw out of the app's handler (a
// logging failure, a bad_alloc) is caught here, so no step of Sync's
// own sequence is skipped by a word it could not deliver — the fault is
// told to the listener once, through the same guard, and a word that
// fails twice is dropped.
class GuardedListener : public SyncListener {
public:
explicit GuardedListener(SyncListener& inner) : inner(inner) {}
void OnStatus(const AppStatus& s) override { Guard([&] { inner.OnStatus(s); }); }
void OnImported(const Message& m) override { Guard([&] { inner.OnImported(m); }); }
void OnUnstored(const Message& m) override { Guard([&] { inner.OnUnstored(m); }); }
void OnMessageChanged(const Message& m) override { Guard([&] { inner.OnMessageChanged(m); }); }
void OnLog(std::string_view line) override { Guard([&] { inner.OnLog(line); }); }
private:
template <class F> void Guard(F&& call) {
std::string what;
try {
call();
return;
} catch (const std::exception& e) {
what = e.what();
} catch (...) {
what = "an exception";
}
if (telling) return; // the word of the fault threw too: dropped
telling = true;
OnLog(std::format("a listener threw: {}", what));
telling = false;
}
SyncListener& inner;
bool telling = false;
};
class Sync : public ImsdEvents {
public:
// `countryCode` overrides the code taken from the subscriber's own
// number (imsd's ppi), else from imsd's service centre number ("" for
// none).
Sync(MessageStore& store, ImsdTransport& bus, SyncListener& inner, std::string countryCode = "")
: store(store), bus(bus), listener(inner), countryOverride(std::move(countryCode)) {
known = store.ImsdIds();
for (const Message& m : store.All()) {
// A message still pending from an earlier run may have had
// imsd's answer while the app was not running: it is failed,
// the user can retry, and an answer that still comes applies
// where the row has imsd's id (one whose Send had no reply
// yet has none: its word is only logged).
if (m.direction == Direction::Outgoing && m.state == MessageState::Pending) store.SetState(m.id, MessageState::Failed, "the app stopped before imsd confirmed it");
}
// The store's word on its writes: refused — the disk full — texts
// wait (in imsd; one imsd could not store itself, here: Import),
// the banner says so, the 30 s Refresh lists again meanwhile; a
// send still goes, its own write a try, and a write that gets
// room clears it and lists the texts imsd holds at once (the
// Refresh, armed while the store refused, stops with the flag
// once no text is held). The flag is the store's (Refused), read
// here after the sweep above — a refusal during it shows too —
// and again after imsd's vanish resets the status.
store.onWriteState = [this](bool refused, std::string_view why) {
this->listener.OnLog(refused ? std::format("the store refused a write: {} — texts wait until there is room", why) : std::string("the store writes again"));
this->status.storeFailed = refused;
this->listener.OnStatus(this->status);
if (!refused) this->FetchList();
};
status.storeFailed = store.Refused();
if (status.storeFailed) listener.OnStatus(status);
}
// The store's slot is this Sync's: given back (a later Sync on the
// store takes it next).
~Sync() override { store.onWriteState = nullptr; }
const AppStatus& Current() const noexcept { return status; }
// The conversation on screen: a text for it is stored read and the
// notifier leaves it alone.
void SetOpenConversation(std::optional<std::string> key) { openConversation = std::move(key); }
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
// The --send errand: it sends and follows its own message and
// leaves the texts imsd keeps to the instance that owns the user's
// store, so it lists, imports and deletes nothing.
void LeaveTexts() { leaveTexts = true; }
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
std::string CountryCode() const {
if (!countryOverride.empty()) return countryOverride;
// The own number says which country a national number is in;
// the service centre's only stands in (an MVNO's centre can be
// abroad).
const std::string fromOwn = CountryCodeOf(status.ownNumber);
if (!fromOwn.empty()) return fromOwn;
const std::string fromSmsc = CountryCodeOf(status.smsc);
if (!fromSmsc.empty()) return fromSmsc;
// None known: a national number stays as typed (imsd sends the
// digits with the type unknown, and the network's own plan
// applies). The store's correspondents say nothing about where
// the subscriber is: a code taken from them would send a text to
// another country.
return "";
}
// The SIM's plan as known now: the own number's code (--country's
// when given), never the centre's stand-in, and the operator of
// imsd's status.
SimPlan Plan() const { return { !countryOverride.empty() ? countryOverride : CountryCodeOf(status.ownNumber), status.simOperator }; }
// ---- the bus -------------------------------------------------------
void OnImsdAppeared() override {
status.imsdPresent = true;
status.subscribed = false;
Subscribe();
listener.OnStatus(status);
}
void OnImsdVanished() override {
status = AppStatus{};
status.storeFailed = store.Refused(); // the store's state, not imsd's
statusFailed = false;
listFailed = false;
listener.OnStatus(status);
for (const Message& m : store.All()) {
if (m.direction == Direction::Outgoing && m.state == MessageState::Pending) Fail(m.id, "imsd stopped before confirming");
}
deleting.clear();
// A copy polkit refused to delete is tried again once imsd is
// back: its count went with the status.
undeletable.clear();
}
void OnReceived(const ReceivedMessage& message) override {
Import(message, true);
// The signal may have been the first of several, and a signal
// is queued for nobody: the store is the truth.
FetchList();
}
void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) override {
// imsd's ids are unique across its runs (the run's token): the id
// names one row.
const std::optional<std::uint64_t> row = store.FindByImsdId(id);
if (!row) {
listener.OnLog(std::format("StateChanged for a message not on record: {} {} {}", id, state, reason));
return;
}
const std::optional<MessageState> word = StateFromImsd(state);
if (!word) {
listener.OnLog(std::format("StateChanged with an unknown state: {} {} {}", id, state, reason));
return;
}
// imsd gives a message's words in order (its §8.4: the submission's
// `sent` or `failed` first, a status report's only after `sent`),
// so each applies as it comes — after the app's own failures too
// (it stopped before imsd confirmed, imsd stopped): imsd knew.
store.SetState(*row, *word, reason);
Changed(*row);
}
void OnRegistrationChanged(bool registered) override {
status.registered = registered;
listener.OnStatus(status);
// imsd fills the status it answers with, the service centre's
// number among it, at its registration, and the signal reaches
// every connection: the moment to read it again (on every change:
// an answer on its way may carry the state before the signal),
// and to retry.
if (status.subscribeFailed) Refresh();
else FetchStatus();
}
// ---- the UI --------------------------------------------------------
// Tries again the texts held for the store, and what failed since
// imsd appeared: a Subscribe that failed or that polkit refused (its
// answer reads the status and the list), else a failed GetStatus;
// and lists, a failed List among it.
void Refresh() {
RetryHeld();
if (!status.imsdPresent) return;
if (status.subscribeFailed || (status.subscribeDenied && !status.subscribed)) {
// One at a time: the answer of the Subscribe in flight
// decides, and under a rule that prompts a second one would
// ask over the first one's prompt.
if (subscribing) return;
status.subscribeFailed = false;
Subscribe();
return;
}
if (statusFailed) FetchStatus();
FetchList();
}
// A Subscribe, a GetStatus or a List failed, or the store refused a
// write, and Refresh would try it again (for the store, by listing);
// or a text is held for the store (Import), which Refresh tries
// again, imsd there or not. A polkit refusal is tried again too:
// imsd asks polkit on every gated call, so one that held while the
// session was inactive lifts when it is active again.
bool RefreshWanted() const noexcept { return !held.empty() || (status.imsdPresent && (status.subscribeFailed || status.subscribeDenied || statusFailed || listFailed || status.storeFailed)); }
// Stores the message as Pending under its conversation key and
// submits it to `to`, the address as dialled (Number's
// DialledNumber), which the key never stands in for; the row id
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
// comes back at once, the outcome through OnMessageChanged. `force`
// skips the local readiness check and lets imsd answer.
std::uint64_t Send(std::string_view conversation, std::string_view to, std::string_view text, bool force = false) {
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
Message m;
m.conversation = std::string(conversation);
m.peer = std::string(to);
m.plan = Plan(); // the plan it is dialled under
m.direction = Direction::Outgoing;
m.text = std::string(text);
m.sortTime = NowEpoch();
m.received = m.sortTime;
m.state = MessageState::Pending;
m.read = true;
const std::optional<std::uint64_t> id = store.Add(m);
if (!id) return kNotStored; // the store refused it: the caller keeps the text
m.id = *id;
listener.OnMessageChanged(m);
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
Submit(m.id, force);
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
return m.id;
}
// Send's answer when the store refused the row: the text was not
// taken, the caller keeps it (a row id is never this).
static constexpr std::uint64_t kNotStored = ~std::uint64_t{0};
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
// The user's deletes: the rows go. What imsd answers later for a
// deleted message finds no row and is logged.
void Erase(std::uint64_t id) { store.Erase(id); }
void EraseConversation(std::string_view conversation) { store.EraseConversation(conversation); }
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// A failed message of ours goes again — without the failed attempt's
// imsd id: a row's imsd id names its current attempt (imsd forgets a
// failed submission's parts, so no word of the old one is due).
void Retry(std::uint64_t id) {
const std::optional<Message> m = store.Get(id);
if (!m || m->direction != Direction::Outgoing || m->state != MessageState::Failed) return;
// The row carries the plan it was dialled under; under another
// SIM's it would reach another subscriber or another service
// (Number's AnotherPlan).
if (AnotherPlan(m->peer, m->plan, Plan())) {
Fail(id, "the number was dialled under another SIM's plan: send it again");
return;
}
// A row's imsd id names its current attempt: the failed one's goes.
store.SetState(id, MessageState::Pending, "");
store.SetImsdId(id, "");
Changed(id);
Submit(id);
}
private:
static std::int64_t NowEpoch() {
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
void Changed(std::uint64_t id) {
if (const std::optional<Message> m = store.Get(id)) listener.OnMessageChanged(*m);
}
void Fail(std::uint64_t id, std::string_view reason) {
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
if (!store.Get(id)) {
listener.OnLog(std::format("message {} failed after it was deleted: {}", id, reason));
return;
}
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
store.SetState(id, MessageState::Failed, reason);
Changed(id);
}
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
void Submit(std::uint64_t id, bool force = false) {
if (!force && !CanSend(status)) {
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
Fail(id, BannerText(status));
return;
}
const std::optional<Message> m = store.Get(id);
if (!m) return;
bus.Send(m->peer, m->text, true, [this, id](SendResult result) {
if (!result) {
Fail(id, result.error().message);
return;
}
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
if (!store.Get(id)) {
listener.OnLog(std::format("imsd took message {} as {} after it was deleted", id, *result));
return;
}
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// imsd's id names the row for its words: in place, which a
// full disk does not refuse (the row's Add fit).
if (!store.SetImsdId(id, *result)) listener.OnLog(std::format("imsd's id for message {} was not recorded: {}", id, *result));
Changed(id);
});
}
void Subscribe() {
++subscribing;
bus.Subscribe([this](std::optional<BusError> err) {
--subscribing;
status.subscribeFailed = false;
if (!err) {
status.subscribed = true;
status.subscribeDenied = false;
} else if (err->kind == BusError::Kind::AccessDenied) {
status.subscribeDenied = true;
listener.OnLog(std::format("Subscribe refused: {}", err->message));
} else {
status.subscribeFailed = true;
listener.OnLog(std::format("Subscribe failed: {}", err->message));
}
// The status ends the connecting state and the List brings what
// imsd kept: both at once, since a listed text keys itself by
// the number it arrived for (Model's MessageFromReceived).
FetchStatus();
FetchList();
listener.OnStatus(status);
});
}
void FetchStatus() {
bus.GetStatus([this](StatusResult result) {
if (!result) {
statusFailed = true;
listener.OnLog(std::format("GetStatus failed: {}", result.error().message));
listener.OnStatus(status); // RefreshWanted() is true now
} else {
statusFailed = false;
status.statusKnown = true;
status.enabled = result->enabled;
status.registered = result->registered;
status.smsc = result->smsc;
status.ownNumber = result->ownNumber; // from the snapshot smsc came from: a number imsd has is never missing
status.simOperator = result->simOperator;
listener.OnStatus(status);
}
});
}
void FetchList() {
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
if (leaveTexts) return;
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
if (listInFlight) {
listAgain = true;
return;
}
listInFlight = true;
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
bus.List([this, before = store.ErasedImsdIds()](ListResult result) {
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
listInFlight = false;
if (!result) {
// Announced at every failure: the listener's 30 s refresh
// is armed from the status, whenever none runs. A refusal
// is the degraded mode; any other failure (a timeout)
// leaves the texts imsd holds to the next Refresh.
if (result.error().kind == BusError::Kind::AccessDenied) status.subscribeDenied = true;
else listFailed = true;
listener.OnStatus(status);
listener.OnLog(std::format("List failed: {}", result.error().message));
} else {
listFailed = false;
// A gated call admitted again: the refusal is over (the
// session is active again), and sending with it; and one
// action gates List and Delete, so the copies polkit
// refused to delete can go now — this answer's imports try
// them again, a refusal counted anew.
if ((status.subscribeDenied && status.subscribed) || !undeletable.empty()) {
if (status.subscribed) status.subscribeDenied = false;
undeletable.clear();
status.undeletable = 0;
listener.OnStatus(status);
}
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
std::unordered_set<std::string> listed;
for (const ReceivedMessage& r : *result) listed.insert(r.imsdId);
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// A held text this answer carries is imsd's to keep after
// all; the rest of them are tried again below.
for (const ReceivedMessage& r : *result) held.erase(r.imsdId);
for (const ReceivedMessage& r : *result) Import(r);
RetryHeld();
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
// A deleted text imsd no longer holds needs no memory — among
// those remembered before this List went out: one deleted
// while it was in flight is a text this answer predates.
store.ForgetErased(listed, before);
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
}
if (listAgain) {
listAgain = false;
FetchList();
}
});
}
// A text from the signal or the list: stored once (imsd's id is the
// key: its run's token makes it unique across imsd's runs, §8.4),
// imsd's copy deleted — again for one still on record, so a copy
// whose delete timed out gets another chance; one polkit refused
// at the next List imsd admits, or once imsd has restarted. A short
// message type 0 (Model's IsType0) is neither stored nor announced:
// imsd acknowledged it, and its copy goes like any other.
// `signalled`: the text came by the Received signal, which imsd
// sends for a text it could not store itself too — the signal is
// then its only delivery, and no List carries the text after.
void Import(const ReceivedMessage& r, bool signalled = false) {
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
if (leaveTexts) return;
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
if (!IsType0(r) && !known.contains(r.imsdId)) {
Message m = MessageFromReceived(r);
m.read = openConversation && *openConversation == m.conversation;
const std::optional<std::uint64_t> id = store.Add(m);
if (!id) {
// The store refused the row (its disk full). A listed
// text is imsd's to keep: nothing is deleted, and the
// next List tries again. A signalled one may be nowhere
// else, so it is held here and told once (OnUnstored),
// until a write gets room (RetryHeld) or a List carries
// it; one that is nowhere else is lost with a process
// that ends before then.
if (signalled && held.try_emplace(r.imsdId, r).second) {
m.read = false;
listener.OnUnstored(m);
}
return;
}
held.erase(r.imsdId);
m.id = *id;
known.insert(r.imsdId);
listener.OnImported(m);
}
DeleteStored(r.imsdId);
}
// The texts held for a store that refused them, tried again: each
// leaves the list when its row is in.
void RetryHeld() {
const std::map<std::string, ReceivedMessage> waiting = held;
for (const auto& [id, r] : waiting) Import(r, true);
}
Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name The GLib side of the app. Variant reads imsd's Received dictionary by key and type as its SmsVariant writes it (`to`, the number the text arrived for, a tel: URI read like the status's `ppi`; `operator`, the SIM it arrived under), the GetStatus one with the subscriber's own number and the SIM's operator in it (`ppi`, a tel: URI as the frozen interface gives it; `operator`), and maps a GError to the core's error kinds off GDBus's own mapping. Client is the Sync logic's transport: asynchronous calls with their continuations as user data — every reply guarded where it is delivered (OnCallDone), as are the signal handlers and the name watch's callbacks: a throw is a fault the events hear, not the end of the process — the calls behind imsd's polkit gate allow interaction: Subscribe, List and Delete wait two minutes; Send has no bound of the client's, since imsd sends the text once its prompt lets the call through, however late, and a Send given up on would be failed by Sync and be sent all the same; GetStatus ten seconds — (one call: the Messaging status carries the own number, imsd reading both from one snapshot; AGENTS.md §1 names both interfaces), the Messaging and RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose appeared callback is where Sync subscribes. Notifier shows one desktop notification per conversation and replaces it as more texts arrive: one Notify at a time per conversation, since the id to replace comes with the answer; its default action asks the app for that conversation; the body is escaped when the server renders markup (GetCapabilities, asked once; Plasma and GNOME do), so a text's '<' or '&' shows as typed. Instance owns net.catcrafts.ImsdMessages and serves org.freedesktop.Application there, the Desktop Entry Specification's interface of a running application: Activate, Open and ActivateAction, each with its platform data — sent empty and not read: nothing in the app can use an activation token yet — and one action, quit, any other refused (the object registered before the name is asked for, so a launch that forwards the moment the name is granted finds it; Own tells a name another instance holds from a request that failed or was refused, and keeps the error's words); it forwards a call to the owner. project.cpp computes the gio flags once for the bus library, the executable and the Decode test. Tested: tests/Decode (every key of imsd's Received dictionary, one with ten of them, GetStatus, the own number, the SIM's operator, the error kinds, the markup escape, the parameters of the instance's three calls).
2026-10-17 23:45:29 +02:00
void OnFault(std::string_view what) override { listener.OnLog(std::format("a bus callback failed: {}", what)); }
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
void DeleteStored(const std::string& id) {
if (deleting.contains(id) || undeletable.contains(id)) return;
deleting.insert(id);
bus.Delete(id, [this, id](std::optional<BusError> err) {
deleting.erase(id);
if (!err || err->kind == BusError::Kind::NotFound) return;
if (err->kind == BusError::Kind::AccessDenied) {
undeletable.insert(id);
status.undeletable = static_cast<std::uint32_t>(undeletable.size());
listener.OnStatus(status);
}
listener.OnLog(std::format("Delete {} failed: {}", id, err->message));
});
}
MessageStore& store;
ImsdTransport& bus;
GuardedListener listener; // the app's, guarded
std::string countryOverride;
AppStatus status;
bool statusFailed = false; // GetStatus failed since imsd appeared
bool listFailed = false; // List failed, and not by a refusal, since one last succeeded
std::size_t subscribing = 0; // the Subscribes unanswered
std::unordered_set<std::string> known; // imsd ids in the store
std::map<std::string, ReceivedMessage> held; // signalled texts the store refused, by imsd id (Import)
std::unordered_set<std::string> deleting; // Delete calls in flight
std::unordered_set<std::string> undeletable; // Delete refused by polkit
std::optional<std::string> openConversation;
bool listInFlight = false;
bool listAgain = false;
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
bool leaveTexts = false;
};
// The --send errand's rule over Sync's events: one Send once imsd's
// status is in — latched before the call, since Sync announces a
// status from inside Send (the store's word on its write) — and one
// end: the message's final state (Sent 0, Failed 1), a store that
// refused the text (1), or none — the clock, a signal, the loop's end —
// (2). The clock is for getting the text to imsd: once imsd has taken
// it, its word ends the errand. The loop, the clock and the log are the
// shell's (main).
class SendErrand {
public:
struct End {
std::int32_t code;
std::string caption; // the log's: the state's, or what ended the errand without one
std::string reason;
};
// The Send is due on this status: once, only with imsd's status in,
// and never after an end (the loop can dispatch a status after the
// clock's or a signal's end).
bool SendDue(const AppStatus& s) {
if (started || done || !s.imsdPresent || !s.statusKnown) return false;
started = true;
return true;
}
// Send's answer: the row to follow, or kNotStored, which ends the errand.
std::optional<End> Sent(std::uint64_t id) {
if (id == Sync::kNotStored) return Ended(1, "Failed", "the store did not take the text");
sentId = id;
return std::nullopt;
}
// A message's change: the errand's own, in a final state, ends it;
// with imsd's id on it, imsd has taken the text.
std::optional<End> Changed(const Message& m) {
if (!sentId || m.id != *sentId) return std::nullopt;
if (!m.imsdId.empty()) taken = true;
if (m.state == MessageState::Sent) return Ended(0, std::string(StateCaption(m.state)), m.stateReason);
if (m.state == MessageState::Failed) return Ended(1, std::string(StateCaption(m.state)), m.stateReason);
return std::nullopt;
}
// The clock ran out (`after`: the shell's span) before imsd was ready
// or had taken the text. Once it has, the clock decides nothing:
// imsd bounds a submission itself, segment by segment, and ends it
// with a word — a clock of the app's own would report no final state
// for a text imsd goes on to send, and leave its row to fail at the
// next start.
std::optional<End> TimedOut(std::string_view after) {
if (taken) return std::nullopt;
return Ended(2, started ? std::format("no final state within {}", after) : std::format("imsd did not become ready within {}", after), "");
}
// A signal, or the loop ended by something else: no final state.
std::optional<End> NoFinalState(std::string_view how) { return Ended(2, std::string(how), ""); }
bool Done() const noexcept { return done; }
private:
std::optional<End> Ended(std::int32_t code, std::string caption, std::string reason) {
if (done) return std::nullopt;
done = true;
return End{ code, std::move(caption), std::move(reason) };
}
bool started = false; // the Send was made
bool taken = false; // imsd answered it with an id
bool done = false; // the end was given
std::optional<std::uint64_t> sentId;
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
};
}