imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon

LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.

The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.

The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.

Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
This commit is contained in:
Jorijn van der Graaf 2026-11-22 17:35:12 +01:00
commit 710f884575
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
3 changed files with 187 additions and 30 deletions

View file

@ -162,7 +162,8 @@ that asked for one `SameRecipient`
and `StatusReportBook`, all with tests. The received-message store (§7.9) and `StatusReportBook`, all with tests. The received-message store (§7.9)
keeps in the shell, among others, the `link(2)` publish and its retry with the next id, keeps in the shell, among others, the `link(2)` publish and its retry with the next id,
the sweep of `.tmp` files at the engine's start, `Delete`'s id check and its the sweep of `.tmp` files at the engine's start, `Delete`'s id check and its
answers by the removal's outcome, `List`'s skip of a file that is no record and the delivery answers by the removal's outcome, `List`'s skip of a file that is no record, its `IOError`
for a store it could not read, the count the `stored` line loses for one, and the delivery
report a store failure leaves unchanged; the record codec and `List`'s report a store failure leaves unchanged; the record codec and `List`'s
order are the core's, with tests. order are the core's, with tests.
@ -692,6 +693,25 @@ Rules:
`IOError` for a record in a store directory `IOError` for a record in a store directory
made unwritable, the record still listed; the removal once it was made unwritable, the record still listed; the removal once it was
writable; `FileNotFound` for an id with no record. writable; `FileNotFound` for an id with no record.
A store that cannot be read ran there too (2026-11-20 to 2026-11-22, the fp6 journal's
`2026-11-20-issues-2-5` capture, `list-io`): `List` answered `IOError`
with `Permission denied` for a store directory of mode 000, for one of
mode 400 (its names read, its first record's `stat` refused) and for a
record of mode 000, and with `Not a directory` for a file where the
directory should be; it answered an empty list with no store directory,
and the two records beside a file that is no record, a directory and a
dangling symbolic link named like records; a start with the directory
at mode 000 wrote the sweep's `cannot read` line and the daemon
answered afterwards. On the dev phone (2026-11-22, the
same capture, `phone-form6`, `checks.log`, the binary of 1.2.1)
`List` answered an empty list with the store directory
moved away and `IOError` with `Not a directory` with a file in its
place, with the journal's `cannot read` line for each of the two calls
it refused. Not reached by any bench: a directory or a file
whose read fails part-way, a file removed between the directory's read
and its own, a process out of descriptors, and the `stored` line
without its count, which takes a text received, and dev mode receives
none.
Reached from 2026-10-18 02:17 (`smsc-override-2026-10-18-0217`): the Reached from 2026-10-18 02:17 (`smsc-override-2026-10-18-0217`): the
`SMSC=` override — `SMSC=+31653131313` gives `service centre +31653131313 `SMSC=` override — `SMSC=+31653131313` gives `service centre +31653131313
(SMSC=)` and a `Send` through it reaches `sent`; `SMSC=abc` gives (SMSC=)` and a `Send` through it reaches `sent`; `SMSC=abc` gives
@ -1613,7 +1633,13 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `:
temporary file(s) removed` (at the engine's start); `sms <id>: NOT temporary file(s) removed` (at the engine's start); `sms <id>: NOT
stored — <why>; the bus signal is its only delivery`; `sms <id>: deleted stored — <why>; the bus signal is its only delivery`; `sms <id>: deleted
from the store`; `sms <id>: not deleted from the store: <reason>`; `sms from the store`; `sms <id>: not deleted from the store: <reason>`; `sms
store: <path> is no record; skipped`. store: <path> is no record; skipped`; `sms store: cannot read <path>:
<reason>` — the first thing a scan of the store cannot read, for
another reason than that nothing is there: the store directory, opened
or read to its end, at any scan; a `.tmp` name's `stat` at the engine's
start (the sweep); a `.msg` name's `stat`, `open` or `read` at a `List`
(which answers `IOError`, §8.4) and at the count for the `stored` line,
which is then `sms <id>: stored` alone.
- `idle: no SIM — nothing to do; systemctl start imsd when that changes` - `idle: no SIM — nothing to do; systemctl start imsd when that changes`
(or `idle: no ims PDN from the network — …` from `IMSD_IDLE`; `idle: no (or `idle: no ims PDN from the network — …` from `IMSD_IDLE`; `idle: no
P-CSCF — none configured (PCSCF=), none discovered (see the ims-pdn-up P-CSCF — none configured (PCSCF=), none discovered (see the ims-pdn-up
@ -1721,7 +1747,17 @@ do that answers without state.
record's second name — is removed when the engine next starts (`sms store: N stale record's second name — is removed when the engine next starts (`sms store: N stale
temporary file(s) removed`; a start that exits before the engine runs temporary file(s) removed`; a start that exits before the engine runs
leaves it, and one the sweep cannot unlink stays unreported); `Delete` leaves it, and one the sweep cannot unlink stays unreported); `Delete`
leaves `.tmp` names alone. `received` is that wall clock: before a boot's first time leaves `.tmp` names alone. A store that cannot be read — its directory,
or the file of a `.msg` or a `.tmp` name in it — is logged (`sms
store: cannot read …`) by the scan that meets it and ends no process:
the start's sweep lets the daemon start, the `stored` line goes
without its count, and `List` answers `IOError` (§8.4), never a shorter
list — every `List` while the fault lasts, the readable records beside
an unreadable one with it: the line names the path. No fault, and passed over without a line: a store directory that
does not exist, which holds nothing, and a name behind which stat(2)
finds no regular file — a directory — or nothing (`ENOENT`: a dangling
link, a file removed since the directory was read). A file that reads and is no record is
skipped with its line, the rest listed. `received` is that wall clock: before a boot's first time
sync it reads 1970, and `List`'s oldest-first order follows it, so an sync it reads 1970, and `List`'s oldest-first order follows it, so an
app that cares orders by the SC's `timestamp`. A store failure is logged, app that cares orders by the SC's `timestamp`. A store failure is logged,
the signal still goes out, and the delivery report stays an RP-ACK — the signal still goes out, and the delivery report stays an RP-ACK —
@ -2002,7 +2038,7 @@ when it does not know it.
| `Send(number, text, options)` | `ssa{sv} → s` (the message's id, `ims-sms-<run>-<start>-<N>`: this run's token — eight hex digits drawn at the daemon's start —, its start second and a counter; a later run gives the same id only if it draws the same token and starts in the same second, and a received id (`ims-sms-in-<run>-<epoch>-<N>`) only with the same token, arrival second and counter; a client keys `StateChanged` by id); options: `status-report` (b). `org.freedesktop.DBus.Error.NotSupported` while `SMS_OVER_IMS` is off | | `Send(number, text, options)` | `ssa{sv} → s` (the message's id, `ims-sms-<run>-<start>-<N>`: this run's token — eight hex digits drawn at the daemon's start —, its start second and a counter; a later run gives the same id only if it draws the same token and starts in the same second, and a received id (`ims-sms-in-<run>-<epoch>-<N>`) only with the same token, arrival second and counter; a client keys `StateChanged` by id); options: `status-report` (b). `org.freedesktop.DBus.Error.NotSupported` while `SMS_OVER_IMS` is off |
| `GetStatus()` | `→ a{sv}`: `enabled` (b, the daemon's configuration — answered before the first registration too), `smsc` (s, the service centre as of the daemon's last status snapshot, the one the frozen `GetStatus` answers from — so empty before a run's first, and when none is known), `ppi` (s, the own number in that snapshot — the frozen interface's `ppi`, made valid UTF-8 as `to` is, so a consumer needs no second call — empty while the snapshot holds none), `operator` (s, the SIM's operator id — MCC then MNC, as ModemManager gives it, and never the IMSI — empty until the first status after the SIM is read), `registered` (b), `subscribers` (u). No count of the store: `GetStatus` is the open read, and a count would tell any local account when a text arrived; `List`'s length is behind the gate | | `GetStatus()` | `→ a{sv}`: `enabled` (b, the daemon's configuration — answered before the first registration too), `smsc` (s, the service centre as of the daemon's last status snapshot, the one the frozen `GetStatus` answers from — so empty before a run's first, and when none is known), `ppi` (s, the own number in that snapshot — the frozen interface's `ppi`, made valid UTF-8 as `to` is, so a consumer needs no second call — empty while the snapshot holds none), `operator` (s, the SIM's operator id — MCC then MNC, as ModemManager gives it, and never the IMSI — empty until the first status after the SIM is read), `registered` (b), `subscribers` (u). No count of the store: `GetStatus` is the open read, and a count would tell any local account when a text arrived; `List`'s length is behind the gate |
| `Subscribe()` | `→` nothing: the caller's connection receives the two signals below from now on, until it closes. It succeeds while SMS over IP is off too (only `Send` is refused then); a consumer reads `enabled` for that state | | `Subscribe()` | `→` nothing: the caller's connection receives the two signals below from now on, until it closes. It succeeds while SMS over IP is off too (only `Send` is refused then); a consumer reads `enabled` for that state |
| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number — oldest first on a synced clock (a 1970 second before the first time sync sorts first; the SC's `timestamp` is the chronology, §7.9) — each the id and the same dictionary `Received` carries (its `received` the arrival time) | | `List()` | `→ a(sa{sv})`: the stored messages, by the arrival second on the phone's wall clock, then within a run the sequence number — oldest first on a synced clock (a 1970 second before the first time sync sorts first; the SC's `timestamp` is the chronology, §7.9) — each the id and the same dictionary `Received` carries (its `received` the arrival time); a file in the store that reads and is no record is left out, as is a name behind which stat(2) finds no regular file or nothing (`ENOENT`), and a store directory that does not exist is an empty list. `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the store directory or a record's file could not be read: no list comes then, and none while the fault lasts, so a consumer asks again later and takes no message for deleted |
| `Delete(id)` | `s`: removes a stored message; `org.freedesktop.DBus.Error.InvalidArgs` for an empty string, one over 64 bytes or one with a character other than an ASCII letter, an ASCII digit or `-`; `org.freedesktop.DBus.Error.FileNotFound` for any other string when the removal found no file; `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the removal failed — a record that is there is kept | | `Delete(id)` | `s`: removes a stored message; `org.freedesktop.DBus.Error.InvalidArgs` for an empty string, one over 64 bytes or one with a character other than an ASCII letter, an ASCII digit or `-`; `org.freedesktop.DBus.Error.FileNotFound` for any other string when the removal found no file; `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the removal failed — a record that is there is kept |
| `Received` | `s a{sv}` — unicast to each subscriber (id `ims-sms-in-<run>-<epoch>-<N>`; `from` s, `text` s, `timestamp` s (the SC's, with its offset: `2026-10-16T22:50:00+02:00`), `received` x (epoch), `sc` s, `to` s when the daemon held an own number at receipt (the first tel: P-Associated-URI of this run's latest answer to a fresh registration, a resume or a reconnect that carried one — a periodic refresh's answer is not read for it — and, until the first such, the state file's once a resume attempt has taken it up): the subscriber the text arrived for, which a later SIM's status cannot tell, `operator` s when the SIM's operator id was known at receipt: the subscription's country and operator, by which a consumer reads a sender in national form or a short code, `class` i (-1: none), `pid` y, `dcs` y, `segments` i, `message-waiting` b, `port-dst`/`port-src` u when the header addresses a port, `data` ay for 8-bit data, `pdu` ay — the SMS-DELIVER as received; of a concatenated message, the segment that completed the set, the last to arrive) | | `Received` | `s a{sv}` — unicast to each subscriber (id `ims-sms-in-<run>-<epoch>-<N>`; `from` s, `text` s, `timestamp` s (the SC's, with its offset: `2026-10-16T22:50:00+02:00`), `received` x (epoch), `sc` s, `to` s when the daemon held an own number at receipt (the first tel: P-Associated-URI of this run's latest answer to a fresh registration, a resume or a reconnect that carried one — a periodic refresh's answer is not read for it — and, until the first such, the state file's once a resume attempt has taken it up): the subscriber the text arrived for, which a later SIM's status cannot tell, `operator` s when the SIM's operator id was known at receipt: the subscription's country and operator, by which a consumer reads a sender in national form or a short code, `class` i (-1: none), `pid` y, `dcs` y, `segments` i, `message-waiting` b, `port-dst`/`port-src` u when the header addresses a port, `data` ay for 8-bit data, `pdu` ay — the SMS-DELIVER as received; of a concatenated message, the segment that completed the set, the last to arrive) |
| `StateChanged` | `s s s` — unicast to each subscriber, and the submission's `sent` / `failed` also to the connection that called `Send` (id, state, reason): `sent` / `failed` for the submission, `delivered` / `delivery-pending` / `delivery-failed` from a status report — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once; `delivered` only when every segment's report is in the completed class (§7.9; the reason carries the SC's status word). The words of one message come in this order: the submission's first — `sent`, or `failed`, after which nothing follows — and a status report's only after `sent` (a report the SC sends while a later segment is still on its way is held until the submission ends; a submission whose every segment the SC reported delivered before its last submit report came ends as `sent` then `delivered`), so a consumer applies each word as it comes. Every string of the two signals is valid UTF-8: a `failed` reason can hold the network's text (a refused final's, `RefusalSummary`), so the emission makes it valid — bytes that are not UTF-8 become U+FFFD, and a NUL byte ends the string (the `Received` strings are the codecs' own; `to` is made valid the same way, and `operator` is digits) | | `StateChanged` | `s s s` — unicast to each subscriber, and the submission's `sent` / `failed` also to the connection that called `Send` (id, state, reason): `sent` / `failed` for the submission, `delivered` / `delivery-pending` / `delivery-failed` from a status report — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once; `delivered` only when every segment's report is in the completed class (§7.9; the reason carries the SC's status word). The words of one message come in this order: the submission's first — `sent`, or `failed`, after which nothing follows — and a status report's only after `sent` (a report the SC sends while a later segment is still on its way is held until the submission ends; a submission whose every segment the SC reported delivered before its last submit report came ends as `sent` then `delivered`), so a consumer applies each word as it comes. Every string of the two signals is valid UTF-8: a `failed` reason can hold the network's text (a refused final's, `RefusalSummary`), so the emission makes it valid — bytes that are not UTF-8 become U+FFFD, and a NUL byte ends the string (the `Received` strings are the codecs' own; `to` is made valid the same way, and `operator` is digits) |

View file

@ -147,15 +147,15 @@ A new desktop needs a new translation daemon, not changes here.
A second interface on the same object, for short messages over IMS A second interface on the same object, for short messages over IMS
(`SMS_OVER_IMS=1`). Additive: the interface above is unchanged. Frozen as of (`SMS_OVER_IMS=1`). Additive: the interface above is unchanged. Frozen as of
1.2.0: what the table lists stays as it is, and a dictionary imsd gives may 1.2.0: its members and their signatures stay as they are, and a dictionary
gain a key. imsd gives may gain a key.
| Member | Signature | | Member | Signature |
|---|---| |---|---|
| `Send(number, text, options)` | `ssa{sv} → s` (id); options: `status-report` (b, ask the SC to report delivery). Refused with `NotSupported` while SMS over IMS is off | | `Send(number, text, options)` | `ssa{sv} → s` (id); options: `status-report` (b, ask the SC to report delivery). Refused with `NotSupported` while SMS over IMS is off |
| `GetStatus()` | `→ a{sv}`: `enabled` (b), `smsc` (s), `ppi` (s, the own number in the daemon's last status, e.g. `tel:+31612345678`), `operator` (s, the SIM's operator id in that status), `registered` (b), `subscribers` (u) | | `GetStatus()` | `→ a{sv}`: `enabled` (b), `smsc` (s), `ppi` (s, the own number in the daemon's last status, e.g. `tel:+31612345678`), `operator` (s, the SIM's operator id in that status), `registered` (b), `subscribers` (u) |
| `Subscribe()` | `→` nothing: the calling connection receives `Received` and `StateChanged` from now on (unicast, never broadcast: to subscribers, and a submission's `sent` / `failed` also to its `Send` caller); subscribe again when imsd's name reappears on the bus | | `Subscribe()` | `→` nothing: the calling connection receives `Received` and `StateChanged` from now on (unicast, never broadcast: to subscribers, and a submission's `sent` / `failed` also to its `Send` caller); subscribe again when imsd's name reappears on the bus |
| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries | | `List()` | `→ a(sa{sv})`: the stored messages, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries; `IOError` when a store that is there cannot be read |
| `Delete(id)` | `s`: removes a stored message | | `Delete(id)` | `s`: removes a stored message |
| `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `to` (when the daemon held an own number at receipt: that number, e.g. `tel:+31612345678`), `operator` (the SIM's operator id at receipt), `class` (i, -1 none), `pid` (y), `dcs` (y), `segments` (i), `message-waiting` (b), `port-dst`/`port-src` (u, when addressed to a port), `data` (ay, 8-bit data), `pdu` (ay, the SMS-DELIVER as received; of a concatenated message, the segment that completed it)) | | `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `to` (when the daemon held an own number at receipt: that number, e.g. `tel:+31612345678`), `operator` (the SIM's operator id at receipt), `class` (i, -1 none), `pid` (y), `dcs` (y), `segments` (i), `message-waiting` (b), `port-dst`/`port-src` (u, when addressed to a port), `data` (ay, 8-bit data), `pdu` (ay, the SMS-DELIVER as received; of a concatenated message, the segment that completed it)) |
| `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once | | `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once |

View file

@ -29,6 +29,7 @@ its subscriber set on the main thread too.
*/ */
#include <arpa/inet.h> #include <arpa/inet.h>
#include <dirent.h>
#include <fcntl.h> #include <fcntl.h>
#include <gio/gio.h> #include <gio/gio.h>
#include <glib-unix.h> #include <glib-unix.h>
@ -40,6 +41,7 @@ its subscriber set on the main thread too.
#include <pwd.h> #include <pwd.h>
#include <signal.h> #include <signal.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
@ -1033,7 +1035,12 @@ void EmitSignalTo(const std::string& destination, const char* name, GVariant* pa
// A record is written whole to a .tmp beside it, fsynced, linked to its // A record is written whole to a .tmp beside it, fsynced, linked to its
// name with link(2) — which refuses a name already taken — and the .tmp // name with link(2) — which refuses a name already taken — and the .tmp
// removed, the directory fsynced after it, so a listing never sees a // removed, the directory fsynced after it, so a listing never sees a
// half-written one and nothing is replaced. // half-written one and nothing is replaced. The three scans — the start's
// sweep, List's read and the count for the journal — go through
// opendir(3), readdir(3), stat(2) and read(2), whose errors come back as
// values. What a scan cannot read is a StoreFault, logged by the scan that
// met it;
// List's read and the count hand theirs back as well.
std::string SmsStoreDir() { return std::format("{}/sms", StateDir()); } std::string SmsStoreDir() { return std::format("{}/sms", StateDir()); }
bool ValidSmsId(std::string_view id) { bool ValidSmsId(std::string_view id) {
@ -1045,18 +1052,104 @@ bool ValidSmsId(std::string_view id) {
std::string SmsRecordPath(std::string_view id) { return std::format("{}/{}.msg", SmsStoreDir(), id); } std::string SmsRecordPath(std::string_view id) { return std::format("{}/{}.msg", SmsStoreDir(), id); }
// What kept a scan of the store from reading it whole: where it stopped
// and the system's error. Empty when nothing did.
struct StoreFault {
std::string path;
int err = 0;
explicit operator bool() const { return err != 0; }
std::string Reason() const { return std::generic_category().message(err); }
};
void LogStoreFault(const StoreFault& f) { Log(std::format("sms store: cannot read {}: {}", f.path, f.Reason())); }
// The names in the store directory. A directory that is not there holds
// none and is no fault: the first record stored makes it. Any other
// failure to open it, or to read it to its end, is — and the names read
// until then are not handed over.
StoreFault SmsStoreNames(std::vector<std::string>& names) {
const std::string dir = SmsStoreDir();
DIR* d = opendir(dir.c_str());
if (!d) {
const int err = errno; // read before the fault copies the path: an allocation may change it
return err == ENOENT ? StoreFault{} : StoreFault{dir, err};
}
StoreFault fault;
for (;;) {
errno = 0; // readdir(3): a null with errno unchanged is the end
const dirent* e = readdir(d);
if (!e) {
if (const int err = errno; err != 0) fault = {dir, err};
break;
}
names.emplace_back(e->d_name);
}
closedir(d);
if (fault) names.clear();
return fault;
}
// A store file's name by its ending: `<something>.msg` a record,
// `<something>.tmp` a writer's temporary file.
bool HasStoreSuffix(std::string_view name, std::string_view suffix) { return name.size() > suffix.size() && name.ends_with(suffix); }
// Whether `path` is a regular file, a symbolic link to one included. One
// that is gone since the directory was read is not, and no fault; any
// other failure of stat(2) is the fault.
bool IsStoreFile(const std::string& path, StoreFault& fault) {
struct stat st {};
if (stat(path.c_str(), &st) != 0) {
if (const int err = errno; err != ENOENT) fault = {path, err};
return false;
}
return S_ISREG(st.st_mode);
}
// A store file's whole content into `text`. False when the file is gone
// since the directory was read (no fault) or could not be opened or read
// to its end (the fault).
bool ReadStoreFile(const std::string& path, std::string& text, StoreFault& fault) {
const int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
if (const int err = errno; err != ENOENT) fault = {path, err};
return false;
}
bool whole = false;
char buf[4096];
for (;;) {
const ssize_t n = read(fd, buf, sizeof buf);
if (n > 0) { text.append(buf, static_cast<std::size_t>(n)); continue; }
const int err = n < 0 ? errno : 0;
if (err == EINTR) continue;
if (err != 0) fault = {path, err};
else whole = true;
break;
}
close(fd);
return whole;
}
// The .tmp files a crash left (between the open and the link, or between // The .tmp files a crash left (between the open and the link, or between
// the link and the unlink, when one is a record's second name): unlinked // the link and the unlink, when one is a record's second name): unlinked
// at the engine's start, before it takes its first message; the count is // at the engine's start, before it takes its first message; the count is
// of those the unlink removed. A record whose second name goes keeps its // of those the unlink removed. A record whose second name goes keeps its
// inode. // inode. A store that cannot be read is logged and left: the daemon
// starts all the same.
int SweepSmsStore() { int SweepSmsStore() {
std::error_code ec; std::vector<std::string> names;
StoreFault fault = SmsStoreNames(names);
int n = 0; int n = 0;
for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { for (const std::string& name : names) {
if (!e.is_regular_file() || e.path().extension() != ".tmp") continue; if (!HasStoreSuffix(name, ".tmp")) continue;
if (unlink(e.path().c_str()) == 0) n++; const std::string path = std::format("{}/{}", SmsStoreDir(), name);
StoreFault here;
if (!IsStoreFile(path, here)) {
if (here && !fault) fault = here;
continue;
} }
if (unlink(path.c_str()) == 0) n++;
}
if (fault) LogStoreFault(fault);
return n; return n;
} }
@ -1107,25 +1200,42 @@ StoreResult StoreReceivedSms(const imsd::engine::StoredSms& r, std::string& why)
return StoreResult::Stored; return StoreResult::Stored;
} }
// The stored messages, oldest first: the `.msg` files, one that is no // The stored messages, oldest first: the `.msg` files, one that reads and
// record skipped (logged when `log`). // is no record skipped (logged when `log`) — one corrupt file does not
std::vector<imsd::engine::StoredSms> LoadStoredSms(bool log = true) { // close the store. The scan stops at the first thing it cannot read — the
std::vector<imsd::engine::StoredSms> out; // directory, a file's type, a file — with that as `fault`, logged: the
std::error_code ec; // records are then not the store's, and a caller must not hand them over
for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { // as if they were.
if (!e.is_regular_file() || e.path().extension() != ".msg") continue; struct StoreRead {
std::ifstream in(e.path(), std::ios::binary); std::vector<imsd::engine::StoredSms> records;
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); StoreFault fault;
};
StoreRead LoadStoredSms(bool log = true) {
StoreRead out;
std::vector<std::string> names;
out.fault = SmsStoreNames(names);
for (const std::string& name : names) {
if (out.fault) break;
if (!HasStoreSuffix(name, ".msg")) continue;
const std::string path = std::format("{}/{}", SmsStoreDir(), name);
std::string text;
if (!IsStoreFile(path, out.fault) || !ReadStoreFile(path, text, out.fault)) continue;
auto r = imsd::engine::ParseStoredSms(text); auto r = imsd::engine::ParseStoredSms(text);
if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", e.path().string())); continue; } if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", path)); continue; }
out.push_back(std::move(*r)); out.records.push_back(std::move(*r));
} }
std::sort(out.begin(), out.end(), imsd::engine::StoredSmsBefore); if (out.fault) LogStoreFault(out.fault);
std::sort(out.records.begin(), out.records.end(), imsd::engine::StoredSmsBefore);
return out; return out;
} }
// The records in the store (what List would hand over), not the files. // The records in the store (what List would hand over), not the files;
std::size_t StoredSmsCount() { return LoadStoredSms(false).size(); } // none when the store could not be read.
std::optional<std::size_t> StoredSmsCount() {
const StoreRead store = LoadStoredSms(false);
if (store.fault) return std::nullopt;
return store.records.size();
}
// a received short message as the Messaging interface's a{sv} (§8.4) // a received short message as the Messaging interface's a{sv} (§8.4)
GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt, const std::string& to, const std::string& simOperator) { GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt, const std::string& to, const std::string& simOperator) {
@ -2975,8 +3085,13 @@ private:
} }
Log(std::format("sms {}: from {} via {}, {}{}", ev->uni, m.from, m.sc, m.data.empty() ? std::format("{} bytes of text", m.text.size()) : std::format("{} bytes of 8-bit data", m.data.size()), Log(std::format("sms {}: from {} via {}, {}{}", ev->uni, m.from, m.sc, m.data.empty() ? std::format("{} bytes of text", m.text.size()) : std::format("{} bytes of 8-bit data", m.data.size()),
m.segments > 1 ? std::format(" in {} segments", m.segments) : std::string())); m.segments > 1 ? std::format(" in {} segments", m.segments) : std::string()));
if (stored == StoreResult::Stored) Log(std::format("sms {}: stored ({} kept until an app deletes them)", ev->uni, StoredSmsCount())); if (stored == StoreResult::Stored) {
else Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why)); // a store that cannot be read back costs this line its count (the scan has logged why), never the signal or the delivery report
const auto kept = StoredSmsCount();
Log(kept ? std::format("sms {}: stored ({} kept until an app deletes them)", ev->uni, *kept) : std::format("sms {}: stored", ev->uni));
} else {
Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why));
}
PostEvent(std::move(ev)); PostEvent(std::move(ev));
} }
void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) { void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) {
@ -3374,9 +3489,15 @@ void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, co
return; return;
} }
if (m == "List") { if (m == "List") {
const StoreRead store = LoadStoredSms();
if (store.fault) {
// not a shorter list: a consumer takes a record List leaves out for one it may forget
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.IOError", store.fault.Reason().c_str());
return;
}
GVariantBuilder b; GVariantBuilder b;
g_variant_builder_init(&b, G_VARIANT_TYPE("a(sa{sv})")); g_variant_builder_init(&b, G_VARIANT_TYPE("a(sa{sv})"));
for (const auto& r : LoadStoredSms()) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt, r.to, r.simOperator)); for (const auto& r : store.records) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt, r.to, r.simOperator));
g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b)); g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b));
return; return;
} }