imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's opt-in raw dump of the last MESSAGE outside a call's dialog, so with no app listening it was gone. It is now written to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a .tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms record codec, pinned by tests/Engine — before the signal, and stays until Delete. List hands over the records it can read, by arrival second, then within a run by sequence number. The record is named by the message's id and published with link(2), which refuses a name the store already holds, so the next number is tried and nothing is replaced. link(2) refuses only a name the store still holds: a client that deleted the daemon's copy after importing it freed the name, and the run's token in the id is what keeps a later run from giving it to another text, unless that run draws the same token and meets the same second and number. The two methods sit behind the Messaging polkit action with Send, and the policy text says so; GetStatus, the open read, does not count the store, since the count would tell any local account when a text arrived, and the unit makes the state directory 0700 (StateDirectoryMode) for the same reason. For a message the store cannot write the delivery report stays an RP-ACK: the signal is its only delivery, and the journal says so. The protocol's refusal — RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a mechanism: the other half, the UE's memory-available notification (RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment would also lose its set. The refusal was built and benched on KPN — the store made unwritable, the text refused; it came again five minutes later, the store writable by then, and a later text came at once — and taken out again; no other core is measured. It returns with the notification and a probe of the store. The record's directory is fsynced after the link, its result unchecked like the directory open's; a concatenated text's earlier segments are held in memory, not in the store, until the set is whole (§7.9). Tested on the dev phone (KPN): a text from the phone to its own number on 2026-10-18 23:30, under this publish (a build of this range ahead of this history, 735dfda, whose StoreReceivedSms has this commit's code), stored as ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof). The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory made immutable at 01:37, a text to the phone's own number not stored (EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again at 01:42:56 under its first SC time stamp, stored and acknowledged, a later text not held. Not on the phone: List's skip of a file that is no record and four of Delete's answers ran on the workstation, in dev mode on a private session bus, on this commit's host build (2026-11-19; its sha256 begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs for a string that is no id; IOError, the record still listed, for a record in a store directory made unwritable; the removal once it was writable; FileNotFound for an id with no record. The engine's start sweeps the .tmp names a crash left — one it cannot unlink stays, unreported — so a deleted text's second name goes at the next engine start that can remove it (Delete leaves .tmp names alone). A Delete whose removal fails answers IOError with the system's reason, and a record that is there is kept; FileNotFound is left for a removal that found no file. List's order breaks a tie between two texts of one run in one second by the sequence number (pinned), not by the id as text.
This commit is contained in:
parent
aa3c394041
commit
d0cfaf712d
10 changed files with 475 additions and 77 deletions
|
|
@ -833,6 +833,7 @@ struct Event {
|
|||
StatusSnapshot status; // Registration/Status
|
||||
std::string text; // Fatal, Idle
|
||||
imsd::engine::SmsReceived sms; // SmsReceived
|
||||
std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds)
|
||||
};
|
||||
|
||||
GDBusConnection* DbusConn = nullptr;
|
||||
|
|
@ -977,14 +978,114 @@ void EmitSignalTo(const std::string& destination, const char* name, GVariant* pa
|
|||
g_dbus_connection_emit_signal(DbusConn, destination.c_str(), ObjPath, MessagingIface, name, params, nullptr);
|
||||
}
|
||||
|
||||
// ---- the store of received messages (§7.9): one record file per message
|
||||
// under <state dir>/sms, written by the engine thread as a message arrives
|
||||
// and read, listed and deleted by the D-Bus thread (List/Delete, §8.4).
|
||||
// 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.
|
||||
std::string SmsStoreDir() { return std::format("{}/sms", StateDir()); }
|
||||
|
||||
bool ValidSmsId(std::string_view id) {
|
||||
if (id.empty() || id.size() > 64) return false;
|
||||
for (char c : id)
|
||||
if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string SmsRecordPath(std::string_view id) { return std::format("{}/{}.msg", SmsStoreDir(), id); }
|
||||
|
||||
// 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.
|
||||
int SweepSmsStore() {
|
||||
std::error_code ec;
|
||||
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++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Stores a received message under its id. Exists: the store already
|
||||
// holds that name (a run's own ids never repeat); the caller takes the
|
||||
// next id. Failed (with `why`): the directory or the
|
||||
// file could not be made.
|
||||
enum class StoreResult { Stored, Exists, Failed };
|
||||
StoreResult StoreReceivedSms(const imsd::engine::StoredSms& r, std::string& why) {
|
||||
std::error_code ec;
|
||||
const std::filesystem::path dir = SmsStoreDir();
|
||||
std::filesystem::create_directories(dir, ec);
|
||||
if (ec) { why = std::format("{}: {}", dir.string(), ec.message()); return StoreResult::Failed; }
|
||||
std::filesystem::permissions(dir, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, ec);
|
||||
const std::string path = SmsRecordPath(r.id);
|
||||
const std::string tmp = path + ".tmp";
|
||||
const std::string text = imsd::engine::FormatStoredSms(r);
|
||||
// a stale .tmp — a crash between link(2) and unlink(2) below — may be a
|
||||
// record's second name: unlinked, never truncated (every .tmp is also
|
||||
// swept at the engine's start, SweepSmsStore); close-on-exec, so no descriptor of this
|
||||
// writer reaches a program imsd runs
|
||||
unlink(tmp.c_str());
|
||||
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
|
||||
if (fd < 0) { why = std::format("{}: {}", tmp, std::strerror(errno)); return StoreResult::Failed; }
|
||||
std::size_t done = 0;
|
||||
while (done < text.size()) {
|
||||
const ssize_t n = write(fd, text.data() + done, text.size() - done);
|
||||
if (n < 0) { why = std::format("{}: {}", tmp, std::strerror(errno)); close(fd); unlink(tmp.c_str()); return StoreResult::Failed; }
|
||||
done += static_cast<std::size_t>(n);
|
||||
}
|
||||
const int syncErr = fsync(fd) < 0 ? errno : 0;
|
||||
const int closeErr = close(fd) < 0 ? errno : 0; // closed on every path
|
||||
if (syncErr || closeErr) { why = std::format("{}: {}", tmp, std::strerror(syncErr ? syncErr : closeErr)); unlink(tmp.c_str()); return StoreResult::Failed; }
|
||||
// link(2) publishes the name only if it is free — rename(2) would
|
||||
// replace a record already there
|
||||
if (link(tmp.c_str(), path.c_str()) < 0) {
|
||||
const int e = errno;
|
||||
unlink(tmp.c_str());
|
||||
if (e == EEXIST) return StoreResult::Exists;
|
||||
why = std::format("{} -> {}: {}", tmp, path, std::strerror(e));
|
||||
return StoreResult::Failed;
|
||||
}
|
||||
unlink(tmp.c_str());
|
||||
// the directory entry too: link(2) and unlink(2) are durable only with
|
||||
// the directory's own fsync (its result, like the open's, is not checked:
|
||||
// a failure here does not unstore the record)
|
||||
if (int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); dfd >= 0) { fsync(dfd); close(dfd); }
|
||||
return StoreResult::Stored;
|
||||
}
|
||||
|
||||
// The stored messages, oldest first: the `.msg` files, one that is no
|
||||
// record skipped (logged when `log`).
|
||||
std::vector<imsd::engine::StoredSms> LoadStoredSms(bool log = true) {
|
||||
std::vector<imsd::engine::StoredSms> 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<char>(in)), std::istreambuf_iterator<char>());
|
||||
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));
|
||||
}
|
||||
std::sort(out.begin(), out.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(); }
|
||||
|
||||
// a received short message as the Messaging interface's a{sv} (§8.4)
|
||||
GVariant* SmsVariant(const imsd::engine::SmsReceived& m) {
|
||||
GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt) {
|
||||
GVariantBuilder b;
|
||||
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
|
||||
g_variant_builder_add(&b, "{sv}", "from", g_variant_new_string(m.from.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "text", g_variant_new_string(m.text.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "timestamp", g_variant_new_string(m.scts.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(NowEpoch()));
|
||||
g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(receivedAt));
|
||||
g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string(m.sc.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "class", g_variant_new_int32(m.msgClass.value_or(-1)));
|
||||
g_variant_builder_add(&b, "{sv}", "pid", g_variant_new_byte(m.pid));
|
||||
|
|
@ -1040,7 +1141,7 @@ gboolean OnIdleEvent(gpointer data) {
|
|||
break;
|
||||
case Event::Type::SmsReceived:
|
||||
for (const std::string& to : Subscribers)
|
||||
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms)));
|
||||
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at)));
|
||||
break;
|
||||
case Event::Type::SmsState: {
|
||||
std::set<std::string> to = Subscribers;
|
||||
|
|
@ -1185,6 +1286,7 @@ public:
|
|||
}
|
||||
|
||||
void Run() {
|
||||
if (const int n = SweepSmsStore(); n > 0) Log(std::format("sms store: {} stale temporary file(s) removed", n));
|
||||
if (auto h = LoadHolds(pdnLocal_)) {
|
||||
recovery_.Restore(Boot(), *h);
|
||||
auto kept = recovery_.Holds(Boot()); // what the policy took over: the file's values after the clamp
|
||||
|
|
@ -2784,13 +2886,32 @@ private:
|
|||
for (const auto& w : e.post) PostSmsState(w.id, w.state, w.reason);
|
||||
}
|
||||
|
||||
// A received message: stored first, then the bus hears it. The id is
|
||||
// this run's token, the arrival's epoch second and a per-start sequence
|
||||
// number — the token tells runs apart where the clock cannot; a name
|
||||
// the store already holds is never replaced: the store refuses it and
|
||||
// the next number is tried, a thousand at most. A store failure is logged and the signal still goes
|
||||
// out — the message is then the listener's or nobody's, and the
|
||||
// delivery report stays an RP-ACK: the protocol's refusal (RP-ERROR
|
||||
// cause 22) is half of a mechanism whose other half, the
|
||||
// memory-available notification, imsd does not send yet (AGENTS.md §7.9).
|
||||
void PostSmsReceived(const imsd::engine::SmsReceived& m) {
|
||||
auto ev = std::make_unique<Event>();
|
||||
ev->type = Event::Type::SmsReceived;
|
||||
ev->uni = imsd::engine::ReceivedSmsId(smsRun_, NowEpoch(), ++smsInSeq_);
|
||||
ev->at = NowEpoch();
|
||||
ev->sms = m;
|
||||
std::string why;
|
||||
StoreResult stored = StoreResult::Failed;
|
||||
for (int tries = 0; tries < 1000; tries++) {
|
||||
ev->uni = imsd::engine::ReceivedSmsId(smsRun_, ev->at, ++smsInSeq_);
|
||||
stored = StoreReceivedSms({ev->uni, ev->at, m}, why);
|
||||
if (stored != StoreResult::Exists) break;
|
||||
Log(std::format("sms store: {} exists already; taking the next id", ev->uni));
|
||||
}
|
||||
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));
|
||||
PostEvent(std::move(ev));
|
||||
}
|
||||
void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) {
|
||||
|
|
@ -3083,6 +3204,8 @@ constexpr const char* IntrospectionXml = R"xml(
|
|||
<arg type="s" name="id" direction="out"/>
|
||||
</method>
|
||||
<method name="GetStatus"><arg type="a{sv}" name="status" direction="out"/></method>
|
||||
<method name="List"><arg type="a(sa{sv})" name="messages" direction="out"/></method>
|
||||
<method name="Delete"><arg type="s" name="id" direction="in"/></method>
|
||||
<method name="Subscribe"/>
|
||||
<signal name="Received"><arg type="s" name="id"/><arg type="a{sv}" name="message"/></signal>
|
||||
<signal name="StateChanged">
|
||||
|
|
@ -3183,6 +3306,40 @@ void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, co
|
|||
g_dbus_method_invocation_return_value(inv, g_variant_new("(a{sv})", &b));
|
||||
return;
|
||||
}
|
||||
if (m == "List") {
|
||||
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));
|
||||
g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b));
|
||||
return;
|
||||
}
|
||||
if (m == "Delete") {
|
||||
const gchar* id = nullptr;
|
||||
g_variant_get(params, "(&s)", &id);
|
||||
const std::string_view sid = id ? id : "";
|
||||
if (!ValidSmsId(sid)) {
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.InvalidArgs", "not a message id");
|
||||
return;
|
||||
}
|
||||
std::error_code ec;
|
||||
const bool removed = std::filesystem::remove(SmsRecordPath(sid), ec);
|
||||
if (ec) {
|
||||
// the removal failed: nothing says the record is gone
|
||||
Log(std::format("sms {}: not deleted from the store: {}", sid, ec.message()));
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.IOError", ec.message().c_str());
|
||||
return;
|
||||
}
|
||||
if (!removed) {
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.FileNotFound", "no such message");
|
||||
return;
|
||||
}
|
||||
// the record only: a `<id>.msg.tmp` beside it is left alone — the
|
||||
// writer unlinks its own, and the engine's next start removes a crash's
|
||||
// leftover (SweepSmsStore)
|
||||
Log(std::format("sms {}: deleted from the store", sid));
|
||||
g_dbus_method_invocation_return_value(inv, nullptr);
|
||||
return;
|
||||
}
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue