diff --git a/AGENTS.md b/AGENTS.md index de49c6f..9f42bf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,7 +162,8 @@ that asked for one `SameRecipient` 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, 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 order are the core's, with tests. @@ -692,6 +693,25 @@ Rules: `IOError` for a record in a store directory made unwritable, the record still listed; the removal once it was 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 `SMSC=` override — `SMSC=+31653131313` gives `service centre +31653131313 (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 : NOT stored — ; the bus signal is its only delivery`; `sms : deleted from the store`; `sms : not deleted from the store: `; `sms - store: is no record; skipped`. + store: is no record; skipped`; `sms store: cannot read : + ` — 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 : stored` alone. - `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 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 temporary file(s) removed`; a start that exits before the engine runs 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 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 — @@ -2002,7 +2038,7 @@ when it does not know it. | `Send(number, text, options)` | `ssa{sv} → s` (the message's id, `ims-sms---`: 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---`) 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 | | `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 | | `Received` | `s a{sv}` — unicast to each subscriber (id `ims-sms-in---`; `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) | diff --git a/README.md b/README.md index b072e38..a0a4c38 100644 --- a/README.md +++ b/README.md @@ -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 (`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 -gain a key. +1.2.0: its members and their signatures stay as they are, and a dictionary +imsd gives may gain a key. | 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 | | `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 | -| `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 | | `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 | diff --git a/implementations/main.cpp b/implementations/main.cpp index 5f8b078..1a29618 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -29,6 +29,7 @@ its subscriber set on the main thread too. */ #include +#include #include #include #include @@ -40,6 +41,7 @@ its subscriber set on the main thread too. #include #include #include +#include #include #include #include @@ -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 // 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 -// 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()); } 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); } +// 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& 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: `.msg` a record, +// `.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(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 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 // 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() { - std::error_code ec; + std::vector names; + StoreFault fault = SmsStoreNames(names); int n = 0; - for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { - if (!e.is_regular_file() || e.path().extension() != ".tmp") continue; - if (unlink(e.path().c_str()) == 0) n++; + for (const std::string& name : names) { + if (!HasStoreSuffix(name, ".tmp")) continue; + 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; } @@ -1107,25 +1200,42 @@ StoreResult StoreReceivedSms(const imsd::engine::StoredSms& r, std::string& why) return StoreResult::Stored; } -// The stored messages, oldest first: the `.msg` files, one that is no -// record skipped (logged when `log`). -std::vector LoadStoredSms(bool log = true) { - std::vector out; - std::error_code ec; - for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { - if (!e.is_regular_file() || e.path().extension() != ".msg") continue; - std::ifstream in(e.path(), std::ios::binary); - std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +// The stored messages, oldest first: the `.msg` files, one that reads and +// is no record skipped (logged when `log`) — one corrupt file does not +// close the store. The scan stops at the first thing it cannot read — the +// directory, a file's type, a file — with that as `fault`, logged: the +// records are then not the store's, and a caller must not hand them over +// as if they were. +struct StoreRead { + std::vector records; + StoreFault fault; +}; +StoreRead LoadStoredSms(bool log = true) { + StoreRead out; + std::vector 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); - if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", e.path().string())); continue; } - out.push_back(std::move(*r)); + if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", path)); continue; } + 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; } -// The records in the store (what List would hand over), not the files. -std::size_t StoredSmsCount() { return LoadStoredSms(false).size(); } +// The records in the store (what List would hand over), not the files; +// none when the store could not be read. +std::optional 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) 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()), 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())); - else Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why)); + if (stored == StoreResult::Stored) { + // 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)); } 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; } 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; 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)); return; }