Linux + iPhone Continuity / iMessage / SMS
fix: No way to re-solicit ANCS without re-pairing
Zack Bartel52abf44ea794
diff --git a/src/cli/main.cpp b/src/cli/main.cppindex 166c4b4..2e05ba8 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -114,6 +114,9 @@ void print_help() {<< " --bt-send <thread> <text> Reply in one conversation.\n"<< " --bt-pair <addr> Pair with an iPhone over Bluetooth.\n"<< " --bt-unpair <addr> Remove a Bluetooth bond.\n"+ << " --bt-solicit Re-advertise for ANCS so the iPhone shows its permission\n"+ << " toggles again, without removing the bond.\n"+ << " --bt-ancs <on|off> Turn notification mirroring on or off.\n"<< " --bt-diagnostics Print a redacted Bluetooth report for a bug report.\n"<< " --accept <fingerprint> Accept a pending pairing request locally.\n"<< " --pair Send a pair_request over TCP to the daemon.\n\n"@@ -211,13 +214,14 @@ static int print_bt_devices(tether::Client& client) {// Pairing takes tens of seconds and reports progress as it goes, so this// subscribes and streams events until the terminal result arrives.-static int run_bt_transaction(tether::Client& client, const std::string& command, const std::string& address) {- const std::string result_command = command == "bt_pair" ? "bt_pair_result" : "bt_unpair_result";+static int run_bt_transaction(tether::Client& client, const std::string& command, const std::string& address = "") {+ const std::string result_command = command + "_result";client.send("{\"command\":\"subscribe\"}\n");nlohmann::json request;request["command"] = command;- request["address"] = address;+ if (!address.empty())+ request["address"] = address;if (!client.send(request.dump() + "\n")) {debug::log(ERR, "Could not reach the daemon.\n");return 1;@@ -476,6 +480,12 @@ int main(int argc, char* argv[]) {arg_val = argv[++i];if (i + 1 < argc)arg_val2 = argv[++i];+ } else if (arg == "--bt-solicit") {+ action = "bt_solicit";+ } else if (arg == "--bt-ancs") {+ action = "bt_ancs";+ if (i + 1 < argc && argv[i + 1][0] != '-')+ arg_val = argv[++i];} else if (arg == "--bt-pair") {action = "bt_pair";if (i + 1 < argc && argv[i + 1][0] != '-')@@ -630,6 +640,21 @@ int main(int argc, char* argv[]) {return 1;}return run_bt_transaction(client, action == "bt_pair" ? "bt_pair" : "bt_unpair", arg_val);+ } else if (action == "bt_solicit") {+ return run_bt_transaction(client, "bt_solicit");+ } else if (action == "bt_ancs") {+ if (arg_val != "on" && arg_val != "off") {+ debug::log(ERR, "Expected on or off, e.g. --bt-ancs on\n");+ return 1;+ }+ nlohmann::json request;+ request["command"] = "bt_set_ancs";+ request["enabled"] = arg_val == "on";+ if (!client.send(request.dump() + "\n")) {+ debug::log(ERR, "Could not reach the daemon.\n");+ return 1;+ }+ fprintf(stdout, "Notification mirroring %s.\n", arg_val == "on" ? "enabled" : "disabled");}return 0;diff --git a/src/core/include/tether/bluetooth/ancs/client.hpp b/src/core/include/tether/bluetooth/ancs/client.hppindex 8831258..20bfed7 100644--- a/src/core/include/tether/bluetooth/ancs/client.hpp+++ b/src/core/include/tether/bluetooth/ancs/client.hpp@@ -48,11 +48,11 @@ namespace tether::bluetooth::ancs {bool ready() const;const std::string& status_reason() const;- // Invokes a notification's positive or negative action. ANCS offers only- // these two — there is no free-text reply.+ // Queues a notification's positive or negative action. ANCS offers only these two.bool perform_action(uint32_t uid, ActionId action);- const NotificationRegistry& registry() const;+ // Newest first. Safe from any thread.+ std::vector<Notification> recent_notifications(size_t limit = 50) const;private:std::unique_ptr<AncsClientState> state_;diff --git a/src/core/include/tether/bluetooth/connection.hpp b/src/core/include/tether/bluetooth/connection.hppindex 729c82c..2c72ec6 100644--- a/src/core/include/tether/bluetooth/connection.hpp+++ b/src/core/include/tether/bluetooth/connection.hpp@@ -53,8 +53,14 @@ namespace tether::bluetooth {bool start(const std::string& address, bool ancs_enabled);void stop();+ // `ancs_enabled` is the user's preference. Whether the controller can+ // actually carry ANCS is decided here rather than by the caller.void set_device(const std::string& address, bool ancs_enabled);+ // Re-decides whether notification mirroring can run, against the+ // controller's current capability. Cheap and idempotent+ void refresh_capability();+nlohmann::json status() const;private:@@ -67,9 +73,9 @@ namespace tether::bluetooth {MessageStore& message_store();std::mutex& message_store_mutex();- // Marks a message read on the phone as well as locally. Returns false with- // err_out set when MAP is not currently open.- bool mark_message_read(const std::string& handle, bool read, std::string& err_out);+ // Marks a message read locally, and on the phone when MAP is currently+ // serving it. Returns false only when the handle is unknown.+ bool mark_message_read(const std::string& handle, bool read, std::string& err_out, bool* synced_out = nullptr);// Sends a reply to a one-to-one conversation. Returns false with err_out set// when MAP is down, the thread cannot be replied to, or the phone refused.diff --git a/src/core/include/tether/bluetooth/pairing.hpp b/src/core/include/tether/bluetooth/pairing.hppindex b1b086e..3e8591c 100644--- a/src/core/include/tether/bluetooth/pairing.hpp+++ b/src/core/include/tether/bluetooth/pairing.hpp@@ -43,6 +43,12 @@ namespace tether::bluetooth {// Removes the bond so a clean pairing can be retried.PairResult unpair_device(BluezMonitor& monitor, const std::string& address);+ // Puts the ANCS solicitation advertisement back on air without re-pairing.+ // This is what makes iOS reveal its "Show Message Notifications" and+ // "Sync Contacts" toggles, and it expires a few minutes after pairing, so+ // there has to be a way back to it short of removing the bond.+ bool solicit_ancs(BluezMonitor& monitor, std::string& err);+nlohmann::json to_json(const PairResult& result);bool confirm_with_dialog(const std::string& device_name, const std::string& code);diff --git a/src/core/include/tether/bluetooth/profile_supervisor.hpp b/src/core/include/tether/bluetooth/profile_supervisor.hppindex 61472ad..74bede0 100644--- a/src/core/include/tether/bluetooth/profile_supervisor.hpp+++ b/src/core/include/tether/bluetooth/profile_supervisor.hpp@@ -66,6 +66,10 @@ namespace tether::bluetooth {// Drops both sessions after a disconnect so the next tick reopens them.void reset();+ // Drops only the MAP session, for a caller that has found it dead while+ // the link itself is still up. The next tick reopens it.+ void drop_map();+const ProfileStatus& status() const { return status_; }const std::string& map_session() const { return map_path_; }const std::string& pbap_session() const { return pbap_path_; }diff --git a/src/core/src/bluetooth/advert.cpp b/src/core/src/bluetooth/advert.cppindex 9075401..73bd53e 100644--- a/src/core/src/bluetooth/advert.cpp+++ b/src/core/src/bluetooth/advert.cpp@@ -4,6 +4,13 @@namespace tether::bluetooth {+ struct AdvertState {+ GDBusConnection* conn = nullptr;+ std::string adapter_path;+ guint registration_id = 0;+ bool registered_with_bluez = false;+ };+namespace {constexpr const char* BLUEZ_NAME = "org.bluez";@@ -45,10 +52,15 @@ namespace tether::bluetooth {const gchar* method,GVariant*,GDBusMethodInvocation* invocation,- gpointer) {- // BlueZ calls Release when it drops the advertisement on its own.- if (g_strcmp0(method, "Release") == 0)+ gpointer user_data) {+ // BlueZ calls Release when it drops the advertisement on its own, which+ // the Timeout above guarantees will happen. The registration is gone by+ // then, so leaving the flag set only makes the next unregister fail.+ if (g_strcmp0(method, "Release") == 0) {debug::log(INFO, "bluetooth: ANCS advertisement released by BlueZ");+ if (auto* state = static_cast<AdvertState*>(user_data))+ state->registered_with_bluez = false;+ }g_dbus_method_invocation_return_value(invocation, nullptr);}@@ -96,13 +108,6 @@ namespace tether::bluetooth {} // namespace- struct AdvertState {- GDBusConnection* conn = nullptr;- std::string adapter_path;- guint registration_id = 0;- bool registered_with_bluez = false;- };-AncsAdvertisement::AncsAdvertisement(GDBusConnection* connection, std::string adapter_path): state_(std::make_unique<AdvertState>()) {state_->conn = connection;diff --git a/src/core/src/bluetooth/ancs/client.cpp b/src/core/src/bluetooth/ancs/client.cppindex 9e195f1..5d412a2 100644--- a/src/core/src/bluetooth/ancs/client.cpp+++ b/src/core/src/bluetooth/ancs/client.cpp@@ -28,6 +28,9 @@ namespace tether::bluetooth::ancs {AncsClient::StatusFn on_status;std::string device_path;+ // The last non-empty device path, so an LE teardown can be told apart+ // from actually being pointed at a different phone.+ std::string last_known_device;std::string notification_source_path;std::string control_point_path;std::string data_source_path;@@ -42,11 +45,17 @@ namespace tether::bluetooth::ancs {int64_t next_subscribe = 0;int64_t next_probe = 0;- // Filled on the GLib thread, drained on the caller's thread. Only these- // two buffers cross the boundary.+ // Guards everything that crosses a thread boundary: the two GATT buffers+ // filled on the GLib thread, the characteristic paths that thread compares+ // against, and actions queued by whichever thread is serving a command.std::mutex inbox;std::deque<std::vector<uint8_t>> pending_source;std::deque<std::vector<uint8_t>> pending_data;+ std::deque<Request> pending_actions;++ // The registry is written by tick() and read by whichever thread answers+ // a "list notifications" command.+ mutable std::mutex registry_mutex;guint source_signal = 0;guint data_signal = 0;@@ -173,9 +182,9 @@ namespace tether::bluetooth::ancs {return false;}- notification_source_path.clear();- control_point_path.clear();- data_source_path.clear();+ // Collected locally, then published under `inbox`: the GLib thread+ // compares incoming values against these paths.+ std::string source_path, control_path, data_path;GVariant* objects = g_variant_get_child_value(reply, 0);GVariantIter iter;@@ -196,11 +205,11 @@ namespace tether::bluetooth::ancs {if (uuid_value) {const std::string uuid = g_variant_get_string(uuid_value, nullptr);if (uuid == UUID_NOTIFICATION_SOURCE)- notification_source_path = object_path;+ source_path = object_path;else if (uuid == UUID_CONTROL_POINT)- control_point_path = object_path;+ control_path = object_path;else if (uuid == UUID_DATA_SOURCE)- data_source_path = object_path;+ data_path = object_path;g_variant_unref(uuid_value);}g_variant_unref(props);@@ -208,8 +217,15 @@ namespace tether::bluetooth::ancs {g_variant_unref(objects);g_variant_unref(reply);+ {+ std::lock_guard<std::mutex> lock(inbox);+ notification_source_path = source_path;+ control_point_path = control_path;+ data_source_path = data_path;+ }+// All three are needed. A partial tree means BlueZ is still enumerating.- return !notification_source_path.empty() && !control_point_path.empty() && !data_source_path.empty();+ return !source_path.empty() && !control_path.empty() && !data_path.empty();}bool AncsClientState::subscribe() {@@ -294,12 +310,19 @@ namespace tether::bluetooth::ancs {void AncsClientState::handle_source_event(const SourceEvent& event, int64_t now) {(void)now;- switch (registry.classify(event, initial_sync)) {+ Decision decision;+ {+ std::lock_guard<std::mutex> lock(registry_mutex);+ decision = registry.classify(event, initial_sync);+ if (decision == Decision::Ignore)+ registry.remember(event);+ else if (decision == Decision::Withdraw)+ registry.forget(event.uid);+ }+ switch (decision) {case Decision::Ignore:- registry.remember(event);return;case Decision::Withdraw:- registry.forget(event.uid);if (on_withdraw)on_withdraw(event.uid);return;@@ -315,7 +338,10 @@ namespace tether::bluetooth::ancs {}in_progress[event.uid] = event;- registry.remember(event);+ {+ std::lock_guard<std::mutex> lock(registry_mutex);+ registry.remember(event);+ }if (!sequencer->submit(build_notification_request(event.uid, attributes)))in_progress.erase(event.uid);}@@ -350,7 +376,10 @@ namespace tether::bluetooth::ancs {notification.has_negative_action = event.has_negative_action();notification.received = now;- registry.store(notification);+ {+ std::lock_guard<std::mutex> lock(registry_mutex);+ registry.store(notification);+ }if (on_notification)on_notification(notification);}@@ -386,12 +415,19 @@ namespace tether::bluetooth::ancs {if (state_->device_path == device_path)return;+ // The LE bearer drops and returns constantly, which shows up here as the+ // path alternating with "". That is one session ending, not a different+ // phone: wiping the registry for it would empty the notification list on+ // every blip, and the phone's replay would then be suppressed as+ // pre-existing, so nothing would ever come back.+ const bool same_device =+ device_path.empty() || state_->last_known_device.empty() || device_path == state_->last_known_device;+ if (!device_path.empty())+ state_->last_known_device = device_path;+state_->unsubscribe();state_->device_path = device_path;state_->subscribed = false;- state_->notification_source_path.clear();- state_->control_point_path.clear();- state_->data_source_path.clear();state_->next_discover = 0;state_->next_subscribe = 0;state_->next_probe = 0;@@ -400,11 +436,18 @@ namespace tether::bluetooth::ancs {// A new LE session replays the phone's backlog, so the next batch of// pre-existing notifications is a sync rather than news.state_->initial_sync = true;- state_->registry.clear();+ if (!same_device) {+ std::lock_guard<std::mutex> lock(state_->registry_mutex);+ state_->registry.clear();+ }{std::lock_guard<std::mutex> lock(state_->inbox);+ state_->notification_source_path.clear();+ state_->control_point_path.clear();+ state_->data_source_path.clear();state_->pending_source.clear();state_->pending_data.clear();+ state_->pending_actions.clear();}if (device_path.empty())@@ -419,12 +462,21 @@ namespace tether::bluetooth::ancs {const std::string& AncsClient::status_reason() const { return state_->reason; }- const NotificationRegistry& AncsClient::registry() const { return state_->registry; }+ std::vector<Notification> AncsClient::recent_notifications(size_t limit) const {+ std::lock_guard<std::mutex> lock(state_->registry_mutex);+ return state_->registry.recent(limit);+ }bool AncsClient::perform_action(uint32_t uid, ActionId action) {if (!state_->ready)return false;- return state_->sequencer->submit(build_action_request(uid, action));+ // The sequencer belongs to tick()'s thread; handing it a request from a+ // command thread would race the queue it pops from. Queue it instead.+ std::lock_guard<std::mutex> lock(state_->inbox);+ if (state_->pending_actions.size() >= MAX_QUEUED_REQUESTS)+ return false;+ state_->pending_actions.push_back(build_action_request(uid, action));+ return true;}void AncsClient::tick(int64_t now) {@@ -453,14 +505,19 @@ namespace tether::bluetooth::ancs {s->subscribed = true;}- // Drain what the GLib thread buffered.+ // Drain what the other threads buffered.std::deque<std::vector<uint8_t>> source, data;+ std::deque<Request> actions;{std::lock_guard<std::mutex> lock(s->inbox);source.swap(s->pending_source);data.swap(s->pending_data);+ actions.swap(s->pending_actions);}+ for (auto& action : actions)+ s->sequencer->submit(std::move(action));+for (const auto& packet : data)s->sequencer->on_data_source(packet.data(), packet.size(), now);diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cppindex cc6ed77..b4eb5ab 100644--- a/src/core/src/bluetooth/bearer_supervisor.cpp+++ b/src/core/src/bluetooth/bearer_supervisor.cpp@@ -13,12 +13,28 @@ namespace tether::bluetooth {return std::min(current * 2, BEARER_BACKOFF_MAX_SECONDS);}- // BlueZ answers InProgress while one of its own connect operations is- // still pending on the device. That clears on its own, unlike a refusal- // from the phone, so backing off for minutes leaves the link down long- // after the reason for it is gone.+ // Failures that clear on their own, unlike a refusal from the phone.+ // Backing off for minutes on these leaves the link down long after the+ // reason for it is gone (left the room answers with a page timeout, not a rejection).bool is_transient(const std::string& err) {- return err.find("org.bluez.Error.InProgress") != std::string::npos;+ static const char* const transient[] = {+ "org.bluez.Error.InProgress",+ "org.bluez.Error.NotReady",+ // BlueZ spells these as the tail of an Error.Failed message.+ "page-timeout",+ "page timeout",+ "connection-abort",+ "Software caused connection abort",+ "Host is down",+ "Connection timed out",+ "br-connection-canceled",+ "le-connection-abort-by-local",+ };+ for (const char* needle : transient) {+ if (err.find(needle) != std::string::npos)+ return true;+ }+ return false;}int next_backoff(int current, const std::string& err) {diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cppindex c06b6bc..6d60e28 100644--- a/src/core/src/bluetooth/connection.cpp+++ b/src/core/src/bluetooth/connection.cpp@@ -59,8 +59,12 @@ namespace tether::bluetooth {info = found->second;rosters = g_rosters;}- const ReplyEligibility eligibility = resolve_group_recipients(- info, thread_key, contact_store(), rosters, g_group_replies_enabled, recipients, err_out);+ ReplyEligibility eligibility;+ {+ std::lock_guard<std::mutex> lock(g_messages_mutex);+ eligibility = resolve_group_recipients(+ info, thread_key, contact_store(), rosters, g_group_replies_enabled, recipients, err_out);+ }if (eligibility != ReplyEligibility::Allowed)return false;} else {@@ -90,7 +94,6 @@ namespace tether::bluetooth {return false;Message sent;- sent.handle = "local-" + std::to_string(std::time(nullptr)) + "-" + std::to_string(g_messages.size());sent.thread_key = thread_key;sent.peer_address = recipients.size() == 1 ? recipients.front().address : std::string{};sent.body = body;@@ -101,6 +104,7 @@ namespace tether::bluetooth {{std::lock_guard<std::mutex> lock(g_messages_mutex);+ sent.handle = "local-" + std::to_string(std::time(nullptr)) + "-" + std::to_string(g_messages.size());g_messages.add(sent);g_journal.append(sent);}@@ -128,6 +132,7 @@ namespace tether::bluetooth {rosters = g_rosters;}std::vector<Recipient> recipients;+ std::lock_guard<std::mutex> lock(g_messages_mutex);return resolve_group_recipients(info, thread_key, contact_store(), rosters, g_group_replies_enabled, recipients, reason);}@@ -142,35 +147,53 @@ namespace tether::bluetooth {g_rosters = load_rosters();}- bool mark_message_read(const std::string& handle, bool read, std::string& err_out) {- std::shared_ptr<MapSession> session;- {- std::lock_guard<std::mutex> lock(g_map_mutex);- session = g_map_session;- }- if (!session) {- err_out = "Messages are not connected.";- return false;- }+ bool mark_message_read(const std::string& handle, bool read, std::string& err_out, bool* synced_out) {+ if (synced_out)+ *synced_out = false;// The stored path is what obexd currently answers on. A message replayed- // from the journal has none until the phone lists it again this session.+ // from the journal has none, and one that has scrolled out of the listing+ // window never gets another. The desktop's own read state must still move+ // for those, or the unread badge can never reach zero.std::string object_path;+ bool known = false;{std::lock_guard<std::mutex> lock(g_messages_mutex);- if (const Message* message = g_messages.find(handle))+ if (const Message* message = g_messages.find(handle)) {+ known = true;object_path = message->object_path;+ }}- if (object_path.empty()) {- err_out = "That message is not available in the current session yet.";+ if (!known) {+ err_out = "That message is no longer in the conversation history.";return false;}- // write through to the phone first; only mirror locally once it took.- if (!session->set_read(object_path, read, err_out))- return false;+ std::shared_ptr<MapSession> session;+ {+ std::lock_guard<std::mutex> lock(g_map_mutex);+ session = g_map_session;+ }++ if (session && !object_path.empty()) {+ std::string sync_err;+ if (session->set_read(object_path, read, sync_err)) {+ if (synced_out)+ *synced_out = true;+ } else {+ err_out = sync_err;+ }+ } else {+ err_out = "The iPhone is not serving this message right now; marked read on this computer only.";+ }+std::lock_guard<std::mutex> lock(g_messages_mutex);- g_messages.set_read(handle, read);+ if (g_messages.set_read(handle, read)) {+ // Re-append so the state survives a restart. Retention keeps the last+ // line for a handle, so the newer read state wins on the next load.+ if (const Message* updated = g_messages.find(handle))+ g_journal.append(*updated);+ }return true;}@@ -188,9 +211,17 @@ namespace tether::bluetooth {constexpr int CONNECT_TIMEOUT_MS = 30000;constexpr int MESSAGE_POLL_SECONDS = 15;+ // obexd can drop a MAP session while the Classic link stays up, and the+ // profile supervisor short-circuits once map_open is set, so nothing else+ // notices. Consecutive listing failures are the cheapest liveness signal.+ constexpr int MAP_FAILURES_BEFORE_REOPEN = 3;constexpr int MESSAGE_LIST_MAX = 200;constexpr int SUPERVISOR_TICK_SECONDS = 1;+ // Whether the controller can carry ANCS right now. Re-read rather than+ // latched: see the comment in ConnectionManager::start().+ bool ancs_available() { return g_bluez && g_bluez->capability().mode == DeliveryMode::Full; }+std::string normalize_address(std::string address) {for (char& c : address)c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));@@ -409,8 +440,12 @@ namespace tether::bluetooth {std::condition_variable wake;std::string address;+ // What the user asked for, versus what the controller can currently do.+ bool ancs_preference = true;bool ancs_enabled = true;bool link_was_ready = false;+ bool device_was_present = false;+ int map_failures = 0;int64_t next_message_poll = 0;std::string open_map_path;// The first listing on a new MAP session returns the phone's existing@@ -428,40 +463,49 @@ namespace tether::bluetooth {void sync_messages(int64_t now);void sync_contacts();void sync_ancs(int64_t now);- nlohmann::json status_payload() const;- // Hands the status to the subscriber only when it differs from the last- // one published. The supervisors report their own internal transitions- // as changes, and most of those are invisible in the payload, so without- // this a subscriber receives the same status every few seconds.++ // Rebuilds the cached payload from the supervisors. Supervisor thread+ // only: it is the sole writer of BearerStatus and ProfileStatus, both of+ // which hold a std::string that no other thread may read directly.+ void refresh_status();++ // Hands the cached status to the subscriber only when it differs from the+ // last one published. The supervisors report their own internal+ // transitions as changes, and most of those are invisible in the payload,+ // so without this a subscriber receives the same status every second.void publish();- // Guards last_published: publish() is reached from the supervisor thread- // and from the ANCS readiness callback on the GLib thread.- std::mutex publish_mutex;+ // Guards everything below. publish() is reached from the supervisor+ // thread and from the ANCS readiness callback on the GLib thread, and+ // status() from whichever thread is serving a command.+ mutable std::mutex status_mutex;+ nlohmann::json current_status;nlohmann::json last_published;};+ void ConnectionState::refresh_status() {+ nlohmann::json payload = to_json(bearers->status(), profiles->status());+ std::lock_guard<std::mutex> lock(status_mutex);+ payload["ancs_ready"] = ancs_ready;+ payload["ancs_reason"] = ancs_reason;+ current_status = std::move(payload);+ }+void ConnectionState::publish() {if (!on_change)return;- nlohmann::json payload = status_payload();+ nlohmann::json payload;{- std::lock_guard<std::mutex> lock(publish_mutex);- if (payload == last_published)+ std::lock_guard<std::mutex> lock(status_mutex);+ if (current_status.is_null() || current_status == last_published)return;+ payload = current_status;last_published = payload;}on_change(payload);}- nlohmann::json ConnectionState::status_payload() const {- nlohmann::json payload = to_json(bearers->status(), profiles->status());- payload["ancs_ready"] = ancs_ready;- payload["ancs_reason"] = ancs_reason;- return payload;- }-nlohmann::json to_json(const BearerStatus& bearer, const ProfileStatus& profiles) {return {{"command", "bt_connection_changed"},@@ -530,8 +574,20 @@ namespace tether::bluetooth {auto listings = session->list_messages("", MESSAGE_LIST_MAX, err);if (!err.empty()) {debug::log(WARN, "bluetooth: ListMessages failed: {}", err);+ // ponytail: a fail count, not an obexd ObjectManager watcher. Costs up+ // to MAP_FAILURES_BEFORE_REOPEN polls of latency; subscribe to+ // org.bluez.obex InterfacesRemoved if that ever proves too slow.+ if (++map_failures >= MAP_FAILURES_BEFORE_REOPEN) {+ debug::log(WARN, "bluetooth: MAP session is not answering; reopening it");+ map_failures = 0;+ profiles->drop_map();+ std::lock_guard<std::mutex> lock(g_map_mutex);+ g_map_session.reset();+ open_map_path.clear();+ }return;}+ map_failures = 0;std::vector<Message> fresh;{@@ -641,20 +697,31 @@ namespace tether::bluetooth {while (running) {const int64_t now = duration_cast<seconds>(steady_clock::now() - started).count();- bool changed = bearers->tick(now);+ bearers->tick(now);+ const bool present = bearers->status().device_present;const bool link_ready = bearers->status().classic_connected;- // A dropped Classic link invalidates every OBEX session on top of it.+ // A phone that walks back into range must not sit out a backoff that+ // grew to minutes while it was gone.+ if (present && !device_was_present)+ bearers->reset();+ device_was_present = present;++ // A dropped Classic link invalidates every OBEX session on top of it,+ // along with any backoff accumulated against the link that just died.if (link_was_ready && !link_ready) {profiles->reset();- changed = true;+ bearers->reset();+ map_failures = 0;}link_was_ready = link_ready;- changed = profiles->tick(now, link_ready) || changed;+ profiles->tick(now, link_ready);- if (changed)- publish();+ // publish() drops a payload identical to the last one, so refreshing+ // every tick costs nothing and cannot miss a transition.+ refresh_status();+ publish();sync_contacts();sync_messages(now);@@ -683,7 +750,14 @@ namespace tether::bluetooth {}state_->address = address;- state_->ancs_enabled = ancs_enabled;+ state_->ancs_preference = ancs_enabled;+ // Read the controller's capability here rather than letting each caller+ // latch its own copy. At startup BlueZ may not have finished enumerating+ // the adapter, and its free advertising-instance count drops to zero+ // while one of our own adverts is registered — a caller that sampled+ // either would disable mirroring for the rest of the daemon's life.+ const bool ancs_effective = ancs_enabled && ancs_available();+ state_->ancs_enabled = ancs_effective;// Replay history before the first poll so the store is never briefly// empty, and so previously seen handles dedupe instead of re-announcing.@@ -708,7 +782,7 @@ namespace tether::bluetooth {// Only built when the caller can actually show notifications and the// bond can carry them.- if (ancs_enabled && state_->on_notification) {+ if (ancs_effective && state_->on_notification) {auto* raw = state_.get();state_->ancs_client = std::make_unique<ancs::AncsClient>(*state_->monitor,@@ -721,8 +795,17 @@ namespace tether::bluetooth {raw->on_withdraw(uid);},[raw](bool ready, const std::string& reason) {- raw->ancs_ready = ready;- raw->ancs_reason = reason;+ {+ // Fold straight into the cached payload: this runs on the+ // GLib thread, which must not read supervisor state.+ std::lock_guard<std::mutex> lock(raw->status_mutex);+ raw->ancs_ready = ready;+ raw->ancs_reason = reason;+ if (!raw->current_status.is_null()) {+ raw->current_status["ancs_ready"] = ready;+ raw->current_status["ancs_reason"] = reason;+ }+ }debug::log(INFO, "ancs: {}", reason);raw->publish();});@@ -731,7 +814,7 @@ namespace tether::bluetooth {state_->running = true;state_->thread = std::thread([this] { state_->run(); });- debug::log(INFO, "bluetooth: supervising {} (ANCS {})", address, ancs_enabled ? "enabled" : "disabled");+ debug::log(INFO, "bluetooth: supervising {} (ANCS {})", address, ancs_effective ? "enabled" : "disabled");return true;}@@ -745,6 +828,32 @@ namespace tether::bluetooth {state_->wake.notify_all();if (state_->thread.joinable())state_->thread.join();++ // MapSession borrows profile_ops' bus connection, and start() replaces+ // profile_ops. Drop the session before anything can hand out a pointer+ // into a connection that is about to go away.+ {+ std::lock_guard<std::mutex> lock(g_map_mutex);+ g_map_session.reset();+ }++ // Everything below is scoped to one device and one set of sessions, and+ // must not leak into the next start().+ state_->ancs_client.reset();+ state_->open_map_path.clear();+ state_->pulled_pbap_path.clear();+ state_->map_session_backfill = true;+ state_->map_failures = 0;+ state_->next_message_poll = 0;+ state_->link_was_ready = false;+ state_->device_was_present = false;+ {+ std::lock_guard<std::mutex> lock(state_->status_mutex);+ state_->current_status = nullptr;+ state_->last_published = nullptr;+ state_->ancs_ready = false;+ state_->ancs_reason.clear();+ }}void ConnectionManager::set_notification_handlers(NotificationFn on_notification, WithdrawFn on_withdraw) {@@ -760,21 +869,36 @@ namespace tether::bluetooth {nlohmann::json out = nlohmann::json::array();if (!state_->ancs_client)return out;- for (const auto& notification : state_->ancs_client->registry().recent(limit))+ for (const auto& notification : state_->ancs_client->recent_notifications(limit))out.push_back(ancs::to_json(notification));return out;}void ConnectionManager::set_device(const std::string& address, bool ancs_enabled) {// Restarting is simpler than mutating supervisor state under the worker,- // and selecting a device is rare.+ // and selecting a device is rare. stop() clears the per-device state.stop();- state_->running = false;start(address, ancs_enabled);}+ void ConnectionManager::refresh_capability() {+ if (!state_->running || state_->address.empty())+ return;+ const bool wanted = state_->ancs_preference && ancs_available();+ if (wanted == state_->ancs_enabled)+ return;+ debug::log(INFO,+ "bluetooth: notification mirroring is now {} (controller capability changed)",+ wanted ? "available" : "unavailable");+ const std::string address = state_->address;+ set_device(address, state_->ancs_preference);+ }+nlohmann::json ConnectionManager::status() const {- if (!state_->bearers || !state_->profiles) {+ // The supervisors' own status objects belong to the supervisor thread;+ // callers get the snapshot it published instead.+ std::lock_guard<std::mutex> lock(state_->status_mutex);+ if (state_->current_status.is_null()) {nlohmann::json idle;idle["command"] = "bt_connection_changed";idle["device_present"] = false;@@ -783,10 +907,7 @@ namespace tether::bluetooth {idle["profile_reason"] = "";return idle;}- nlohmann::json payload = to_json(state_->bearers->status(), state_->profiles->status());- payload["ancs_ready"] = state_->ancs_ready;- payload["ancs_reason"] = state_->ancs_reason;- return payload;+ return state_->current_status;}} // namespace tether::bluetoothdiff --git a/src/core/src/bluetooth/map_session.cpp b/src/core/src/bluetooth/map_session.cppindex b957b9f..f2ac998 100644--- a/src/core/src/bluetooth/map_session.cpp+++ b/src/core/src/bluetooth/map_session.cpp@@ -47,11 +47,14 @@ namespace tether::bluetooth {MapSession::MapSession(GDBusConnection* session_bus, std::string session_path): state_(std::make_unique<MapSessionState>()) {- state_->bus = session_bus;+ // The session bus is owned by the profile ops, which are replaced when the+ // selected device changes. Hold a reference so an in-flight call cannot+ // outlive the connection it is using.+ state_->bus = session_bus ? G_DBUS_CONNECTION(g_object_ref(session_bus)) : nullptr;state_->path = std::move(session_path);}- MapSession::~MapSession() = default;+ MapSession::~MapSession() { g_clear_object(&state_->bus); }const std::string& MapSession::path() const { return state_->path; }@@ -294,6 +297,13 @@ namespace tether::bluetooth {err = "Timed out waiting for the phone to accept the message; it may still be sent.";return false;}+ if (state == TransferState::Gone) {+ // The object disappeared before its status was ever seen as complete.+ // obexd does that for a rejected transfer too, so reporting success+ // here would tell the user a message was sent that never was.+ err = "The phone did not confirm the message; check Messages on the iPhone before resending.";+ return false;+ }return true;}diff --git a/src/core/src/bluetooth/monitor.cpp b/src/core/src/bluetooth/monitor.cppindex b4a0beb..dd3d8c5 100644--- a/src/core/src/bluetooth/monitor.cpp+++ b/src/core/src/bluetooth/monitor.cpp@@ -89,7 +89,7 @@ namespace tether::bluetooth {// bluetoothd exposes no property for its own flags, so the argument vector is// the only place to read it. Accepts both spellings; Arch's unit uses -E.- bool bluetoothd_has_experimental() {+ static bool scan_bluetoothd_cmdline() {std::error_code ec;for (const auto& entry : std::filesystem::directory_iterator("/proc", ec)) {std::ifstream comm(entry.path() / "comm");@@ -111,6 +111,13 @@ namespace tether::bluetooth {return false;}+ // Walking /proc is not free, and refresh() runs on every debounced BlueZ+ // signal. The answer cannot change without bluetoothd restarting.+ bool bluetoothd_has_experimental() {+ static const bool value = scan_bluetoothd_cmdline();+ return value;+ }+void MonitorState::refresh() {GError* error = nullptr;GVariant* reply = g_dbus_connection_call_sync(conn,@@ -173,7 +180,6 @@ namespace tether::bluetooth {refresh();- loop = g_main_loop_new(context, FALSE);g_main_loop_run(loop);running = false;@@ -237,6 +243,10 @@ namespace tether::bluetooth {}impl_->context = g_main_context_new();+ // Created here, not on the watcher thread: a stop() that lands before the+ // thread reaches g_main_loop_new would otherwise quit nothing, and the+ // join() below it would block forever.+ impl_->loop = g_main_loop_new(impl_->context, FALSE);impl_->running = true;impl_->thread = std::thread([this] { impl_->run(); });return true;diff --git a/src/core/src/bluetooth/obex_transfer.cpp b/src/core/src/bluetooth/obex_transfer.cppindex be9805a..f8b4109 100644--- a/src/core/src/bluetooth/obex_transfer.cpp+++ b/src/core/src/bluetooth/obex_transfer.cpp@@ -10,7 +10,7 @@ namespace tether::bluetooth {constexpr const char* OBEX_NAME = "org.bluez.obex";constexpr const char* IFACE_TRANSFER = "org.bluez.obex.Transfer1";constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";- constexpr int POLL_INTERVAL_MS = 200;+ constexpr int POLL_INTERVAL_MS = 50;TransferState poll_once(GDBusConnection* bus, const std::string& path) {GError* error = nullptr;@@ -51,10 +51,18 @@ namespace tether::bluetooth {TransferState wait_for_transfer(GDBusConnection* bus, const std::string& path, int timeout_seconds) {const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_seconds);TransferState state = TransferState::Active;+ // obexd removes the transfer object immediately after setting its status+ bool saw_complete = false;while (std::chrono::steady_clock::now() < deadline) {state = poll_once(bus, path);- if (state != TransferState::Active)+ if (state == TransferState::Complete) {+ saw_complete = true;return state;+ }+ if (state == TransferState::Error)+ return state;+ if (state == TransferState::Gone)+ return saw_complete ? TransferState::Complete : TransferState::Gone;std::this_thread::sleep_for(std::chrono::milliseconds(POLL_INTERVAL_MS));}return state;diff --git a/src/core/src/bluetooth/pairing.cpp b/src/core/src/bluetooth/pairing.cppindex dad6994..b243502 100644--- a/src/core/src/bluetooth/pairing.cpp+++ b/src/core/src/bluetooth/pairing.cpp@@ -244,8 +244,78 @@ namespace tether::bluetooth {g_advert = nullptr;}+ // Puts the solicitation advert on air, replacing whatever was there.+ bool start_advert(BluezMonitor& monitor, const std::string& adapter_path, std::string& err) {+ if (adapter_path.empty()) {+ err = "No Bluetooth adapter is available.";+ return false;+ }+ stop_advert(monitor);+ auto* advert = new AncsAdvertisement(monitor.connection(), adapter_path);++ bool exported = false;+ monitor.invoke_sync([&] { exported = advert->export_object(); });+ // BlueZ reads the advertisement's properties back before returning, so+ // this call must stay off the thread that answers those reads.+ if (exported && advert->register_with_bluez()) {+ g_advert = advert;+ return true;+ }++ monitor.invoke_sync([&] { advert->unexport_object(); });+ delete advert;+ err = "Could not advertise for ANCS. The controller may have no free LE advertising instance.";+ return false;+ }++ // Reads Device1.Paired straight from BlueZ rather than from the monitor's+ // snapshot. The confirmation dialog blocks the monitor's GLib thread for as+ // long as the user takes to answer, so the snapshot is frozen for exactly+ // the window in which the bond completes — polling it reports a timeout for+ // a pairing that actually succeeded.+ bool device_is_paired(GDBusConnection* conn, const std::string& path) {+ GError* error = nullptr;+ GVariant* reply = g_dbus_connection_call_sync(conn,+ BLUEZ_NAME,+ path.c_str(),+ IFACE_PROPS,+ "Get",+ g_variant_new("(ss)", IFACE_DEVICE, "Paired"),+ G_VARIANT_TYPE("(v)"),+ G_DBUS_CALL_FLAGS_NONE,+ 5000,+ nullptr,+ &error);+ if (!reply) {+ g_clear_error(&error);+ return false;+ }+ GVariant* boxed = nullptr;+ g_variant_get(reply, "(v)", &boxed);+ const bool paired =+ boxed && g_variant_is_of_type(boxed, G_VARIANT_TYPE_BOOLEAN) && g_variant_get_boolean(boxed);+ if (boxed)+ g_variant_unref(boxed);+ g_variant_unref(reply);+ return paired;+ }+} // namespace+ bool solicit_ancs(BluezMonitor& monitor, std::string& err) {+ if (!monitor.connection()) {+ err = "Bluetooth is unavailable.";+ return false;+ }+ // Deliberately not gated on Capability::advertising: BlueZ reports zero+ // free instances while one of our own adverts is registered, which is+ // precisely the state a user retrying this is likely to be in. Try, and+ // report what BlueZ actually says.+ auto objects = monitor.snapshot();+ const std::string adapter = objects.adapters.empty() ? std::string{} : objects.adapters.front().path;+ return start_advert(monitor, adapter, err);+ }+bool confirm_with_dialog(const std::string& device_name, const std::string& code) {std::string body =device_name + " wants to pair.\n\nConfirm this code matches the one on your iPhone:\n\n" + code;@@ -396,10 +466,8 @@ namespace tether::bluetooth {auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(PAIR_TIMEOUT_SECONDS);bool paired = false;while (std::chrono::steady_clock::now() < deadline) {- Device current;- if (lookup(monitor, result.device_address, current) && current.paired) {+ if (device_is_paired(conn, device.path)) {paired = true;- device = current;break;}std::this_thread::sleep_for(std::chrono::milliseconds(500));@@ -439,25 +507,14 @@ namespace tether::bluetooth {// Only now solicit ANCS. This advert is what makes iOS reveal its// "Show Message Notifications" and "Sync Contacts" toggles, and it is safe// to broadcast because the bond already exists.- if (!adapter_path.empty() && monitor.capability().advertising) {- stop_advert(monitor);- auto* advert = new AncsAdvertisement(conn, adapter_path);-- bool exported = false;- monitor.invoke_sync([&] { exported = advert->export_object(); });- // BlueZ reads the advertisement's properties back before returning, so- // this call must stay off the thread that answers those reads.- if (exported && advert->register_with_bluez()) {- g_advert = advert;- notify(progress,- "soliciting",- "Open Settings > Bluetooth > (i) on the iPhone and enable Show Message Notifications and "- "Sync Contacts. They can take a few minutes to appear.");- } else {- monitor.invoke_sync([&] { advert->unexport_object(); });- delete advert;- notify(progress, "warning", "Could not advertise for ANCS; notification permissions may not appear.");- }+ std::string advert_err;+ if (start_advert(monitor, adapter_path, advert_err)) {+ notify(progress,+ "soliciting",+ "Open Settings > Bluetooth > (i) on the iPhone and enable Show Message Notifications and "+ "Sync Contacts. They can take a few minutes to appear.");+ } else {+ notify(progress, "warning", advert_err + " Notification permissions may not appear.");}if (!result.dual_bond) {diff --git a/src/core/src/bluetooth/pbap_session.cpp b/src/core/src/bluetooth/pbap_session.cppindex 4fbf61c..fda2e4a 100644--- a/src/core/src/bluetooth/pbap_session.cpp+++ b/src/core/src/bluetooth/pbap_session.cpp@@ -48,11 +48,11 @@ namespace tether::bluetooth {PbapSession::PbapSession(GDBusConnection* session_bus, std::string session_path): state_(std::make_unique<PbapSessionState>()) {- state_->bus = session_bus;+ state_->bus = session_bus ? G_DBUS_CONNECTION(g_object_ref(session_bus)) : nullptr;state_->path = std::move(session_path);}- PbapSession::~PbapSession() = default;+ PbapSession::~PbapSession() { g_clear_object(&state_->bus); }const std::string& PbapSession::path() const { return state_->path; }diff --git a/src/core/src/bluetooth/profile_supervisor.cpp b/src/core/src/bluetooth/profile_supervisor.cppindex 4e4b7df..54f231a 100644--- a/src/core/src/bluetooth/profile_supervisor.cpp+++ b/src/core/src/bluetooth/profile_supervisor.cpp@@ -105,9 +105,22 @@ namespace tether::bluetooth {status_.pbap_open = false;}+ void ProfileSupervisor::drop_map() {+ if (!map_path_.empty())+ ops_.remove_session(map_path_);+ map_path_.clear();+ map_retried_ = false;+ status_.map_open = false;+ // Reopen on the next tick rather than waiting out the steady poll.+ next_attempt_ = 0;+ }+boolProfileSupervisor::open_profile(const std::string& target, std::string& path, ObexError& error, bool& retried) {std::string err;+ // create_session() clears `path` on failure, so the session that may need+ // dropping has to be captured before the call.+ const std::string previous = path;path = ops_.create_session(target, err);if (!path.empty()) {error = ObexError::None;@@ -122,7 +135,7 @@ namespace tether::bluetooth {// this profile's session and try once more, rather than restarting obexd.if (error == ObexError::Forbidden && !retried) {retried = true;- ops_.remove_session(path);+ ops_.remove_session(previous);path = ops_.create_session(target, err);if (!path.empty()) {error = ObexError::None;diff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex e929847..3c946d3 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -135,6 +135,44 @@ namespace tether {return total_written;}+ // Plain-socket counterpart to robust_ssl_write. These packets are+ // newline-delimited JSON and the local client fds are non-blocking, so a+ // short write splits one event across the framing boundary: every later+ // event on that socket is then misparsed and the client goes silently deaf+ // rather than erroring. Either the whole packet goes out or none of it does.+ static bool robust_plain_write(int fd, const void* buf, size_t num) {+ const char* p = static_cast<const char*>(buf);+ size_t written = 0;+ int stalls = 0;+ // Before the first byte, a socket that will not drain just costs us the+ // packet. After it there is no way back, so a committed write waits far+ // longer before abandoning a stream it has already framed.+ constexpr int STALL_LIMIT_UNCOMMITTED = 200;+ constexpr int STALL_LIMIT_COMMITTED = 5000;++ while (written < num) {+ const ssize_t n = write(fd, p + written, num - written);+ if (n > 0) {+ written += static_cast<size_t>(n);+ stalls = 0;+ continue;+ }+ if (n < 0 && errno == EINTR)+ continue;+ if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {+ if (++stalls > (written == 0 ? STALL_LIMIT_UNCOMMITTED : STALL_LIMIT_COMMITTED)) {+ debug::log(ERR, "net: fd {} is not draining; {} of {} bytes written", fd, written, num);+ return false;+ }+ usleep(1000);+ continue;+ }+ debug::log(ERR, "net write error on fd {}: {}", fd, std::strerror(errno));+ return false;+ }+ return true;+ }+void broadcast_message(const std::string& msg, int exclude_fd) {std::string packet = msg;if (!packet.empty() && packet.back() != '\n')@@ -147,17 +185,13 @@ namespace tether {if (session.ssl) {robust_ssl_write(session.ssl, packet.c_str(), packet.size());} else {- if (write(fd, packet.c_str(), packet.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ robust_plain_write(fd, packet.c_str(), packet.size());}}}static void write_plain_packet(int fd, const std::string& packet) {- if (write(fd, packet.c_str(), packet.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ robust_plain_write(fd, packet.c_str(), packet.size());}void broadcast_local_event(const std::string& msg, int exclude_fd) {@@ -211,6 +245,15 @@ namespace tether {return "";}+ static nlohmann::json build_bt_connection_status() {+ if (bluetooth::g_bt_connections)+ return bluetooth::g_bt_connections->status();+ return nlohmann::json{{"command", "bt_connection_changed"},+ {"device_present", false},+ {"link_reason", "Bluetooth is unavailable."},+ {"profile_reason", ""}};+ }+nlohmann::json build_bt_status() {nlohmann::json status;status["command"] = "bt_status";@@ -270,9 +313,14 @@ namespace tether {if (result.success) {config.device_address = result.device_address;- // A BR/EDR-only bond can never have ANCS. Remember so later runs do not keep trying to bring up an LE- // bearer the phone will not answer.- config.ancs_enabled = result.dual_bond;+ // A BR/EDR-only bond can never have ANCS. Only a bond this transaction+ // actually created settles that: an "already_paired" result, or a phone+ // that merely wasn't exposing its LE bearer at this instant, must not+ // latch mirroring off — nothing in the UI could turn it back on.+ if (result.dual_bond)+ config.ancs_enabled = true;+ else if (result.status == "paired")+ config.ancs_enabled = false;bluetooth::save_config(config);// Point supervision at the device we just bonded with.if (bluetooth::g_bt_connections)@@ -306,22 +354,27 @@ namespace tether {// never change which conversation a message belongs to.if (auto name = bluetooth::contact_store().name_for(thread.key); !name.empty())entry["name"] = name;-- if (thread.key.rfind("group:", 0) == 0) {- entry["group"] = true;- std::string reason;- const auto eligibility = bluetooth::group_reply_status(thread.key, reason);- entry["repliable"] = eligibility == bluetooth::ReplyEligibility::Allowed;- entry["reply_status"] = bluetooth::to_string(eligibility);- if (!reason.empty())- entry["reply_reason"] = reason;- } else {- entry["group"] = false;- entry["repliable"] = true;- }+ entry["group"] = thread.key.rfind("group:", 0) == 0;threads.push_back(std::move(entry));}}++ // Resolved after the store lock is released, not underneath it: deciding+ // who a group reply would go to reads the contacts, which the same lock+ // guards, and std::mutex is not recursive.+ for (auto& entry : threads) {+ if (!entry.value("group", false)) {+ entry["repliable"] = true;+ continue;+ }+ std::string reason;+ const auto eligibility = bluetooth::group_reply_status(entry.value("thread", ""), reason);+ entry["repliable"] = eligibility == bluetooth::ReplyEligibility::Allowed;+ entry["reply_status"] = bluetooth::to_string(eligibility);+ if (!reason.empty())+ entry["reply_reason"] = reason;+ }+result["threads"] = threads;return result;}@@ -588,9 +641,7 @@ namespace tether {if (j.contains("command") && j["command"] == "subscribe") {register_local_subscriber(client_fd);std::string payload = build_local_state_snapshot().dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);// Replay any current OTP so a freshly reconnected extension// (MV3 service worker restart) gets it without waiting for a// new_otp push it may have missed while disconnected. Skip the@@ -598,35 +649,30 @@ namespace tether {// restart re-injects it into whatever site the user is on now.if (Otp otp = otp_peek(); otp && !otp_is_claimed()) {std::string otp_payload = make_otp_event(otp).dump() + "\n";- if (write(client_fd, otp_payload.c_str(), otp_payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, otp_payload);}+ // Same reasoning for Bluetooth: connection status is only+ // broadcast when it changes, so a client that subscribed+ // after the last change would otherwise never learn whether+ // messages are connected, and would keep its composer shut.+ write_plain_packet(client_fd, build_bt_connection_status().dump() + "\n");continue;} else if (j.contains("command") && j["command"] == "unsubscribe") {unregister_local_subscriber(client_fd);std::string payload = "{\"command\":\"unsubscribed\"}\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "state_snapshot") {std::string payload = build_local_state_snapshot().dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "bt_status") {std::string payload = build_bt_status().dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "bt_list_devices") {std::string payload = build_bt_devices().dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "bt_pair" && j.contains("address")) {// Pairing waits on the user and the phone, so it runs on@@ -645,31 +691,53 @@ namespace tether {broadcast_local_event(build_bt_status().dump());} else if (j.contains("command") && j["command"] == "bt_list_threads") {std::string payload = build_bt_threads().dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "bt_list_messages" && j.contains("thread")) {std::string payload = build_bt_messages(j["thread"]).dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;- } else if (j.contains("command") && j["command"] == "bt_mark_read" && j.contains("handle")) {- std::string handle = j["handle"];- bool read = j.value("read", true);- // Writing through to the phone is a blocking OBEX call.- std::thread([handle, read]() {- std::string err;- nlohmann::json event;- event["command"] = "bt_message_read";- event["handle"] = handle;- event["read"] = read;- event["success"] = bluetooth::mark_message_read(handle, read, err);- if (!err.empty())- event["message"] = err;- broadcast_local_event(event.dump());- }).detach();+ } else if (j.contains("command") && j["command"] == "bt_mark_read" &&+ (j.contains("handle") || j.contains("handles"))) {+ std::vector<std::string> handles;+ if (j.contains("handles") && j["handles"].is_array()) {+ for (const auto& h : j["handles"])+ if (h.is_string())+ handles.push_back(h.get<std::string>());+ } else if (j["handle"].is_string()) {+ handles.push_back(j["handle"].get<std::string>());+ }+ const bool read = j.value("read", true);+ // Each write-through is a blocking OBEX call against a+ // session that serves them one at a time, so the batch gets+ // one worker rather than a thread per message, and reports+ // once rather than making the UI refresh per handle.+ if (!handles.empty()) {+ std::thread([handles, read]() {+ int changed = 0;+ int synced = 0;+ std::string last_err;+ for (const auto& handle : handles) {+ std::string err;+ bool handle_synced = false;+ if (bluetooth::mark_message_read(handle, read, err, &handle_synced))+ ++changed;+ if (handle_synced)+ ++synced;+ if (!err.empty())+ last_err = err;+ }+ nlohmann::json event;+ event["command"] = "bt_message_read";+ event["handles"] = handles;+ event["read"] = read;+ event["success"] = changed > 0;+ event["synced"] = synced;+ if (!last_err.empty())+ event["message"] = last_err;+ broadcast_local_event(event.dump());+ }).detach();+ }} else if (j.contains("command") && j["command"] == "bt_send_message" && j.contains("thread") &&j.contains("body")) {std::string thread = j["thread"];@@ -695,6 +763,30 @@ namespace tether {}broadcast_local_event(event.dump());}).detach();+ } else if (j.contains("command") && j["command"] == "bt_solicit") {+ // The advertisement that makes iOS reveal its Messages and+ // Contacts permission toggles is otherwise only on air for a+ // few minutes after pairing, leaving a full unpair/re-pair as+ // the only way back.+ std::thread([]() {+ nlohmann::json event;+ event["command"] = "bt_solicit_result";+ std::string err;+ event["success"] = bluetooth::g_bluez && bluetooth::solicit_ancs(*bluetooth::g_bluez, err);+ event["message"] =+ event["success"]+ ? "Open Settings > Bluetooth > (i) on the iPhone and enable Show Message "+ "Notifications and Sync Contacts. They can take a few minutes to appear."+ : (err.empty() ? "Bluetooth is unavailable." : err);+ broadcast_local_event(event.dump());+ }).detach();+ } else if (j.contains("command") && j["command"] == "bt_set_ancs") {+ auto config = bluetooth::load_config();+ config.ancs_enabled = j.value("enabled", true);+ bluetooth::save_config(config);+ if (bluetooth::g_bt_connections)+ bluetooth::g_bt_connections->set_device(config.device_address, config.ancs_enabled);+ broadcast_local_event(build_bt_status().dump());} else if (j.contains("command") && j["command"] == "bt_list_notifications") {nlohmann::json payload;payload["command"] = "bt_notifications";@@ -702,9 +794,7 @@ namespace tether {? bluetooth::g_bt_connections->notifications(): nlohmann::json::array();std::string out = payload.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace) + "\n";- if (write(client_fd, out.c_str(), out.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, out);continue;} else if (j.contains("command") && j["command"] == "bt_notification_action" && j.contains("uid")) {// ANCS offers positive and negative only; there is no@@ -720,26 +810,13 @@ namespace tether {positive ? bluetooth::ancs::ActionId::Positive : bluetooth::ancs::ActionId::Negative);broadcast_local_event(payload.dump());} else if (j.contains("command") && j["command"] == "bt_connection") {- nlohmann::json payload = bluetooth::g_bt_connections- ? bluetooth::g_bt_connections->status()- : nlohmann::json{{"command", "bt_connection_changed"},- {"device_present", false},- {"link_reason", "Bluetooth is unavailable."},- {"profile_reason", ""}};- std::string out = payload.dump() + "\n";- if (write(client_fd, out.c_str(), out.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ std::string out = build_bt_connection_status().dump() + "\n";+ write_plain_packet(client_fd, out);continue;} else if (j.contains("command") && j["command"] == "bt_diagnostics") {- nlohmann::json connection =- bluetooth::g_bt_connections- ? bluetooth::g_bt_connections->status()- : nlohmann::json{{"command", "bt_connection_changed"}, {"device_present", false}};+ nlohmann::json connection = build_bt_connection_status();std::string out = bluetooth::build_diagnostics(build_bt_status(), connection).dump() + "\n";- if (write(client_fd, out.c_str(), out.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, out);continue;} else if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {std::string content = j["content"];@@ -751,9 +828,7 @@ namespace tether {resp["command"] = "clipboard_content";resp["content"] = g_wayland->get_clipboard();std::string payload = resp.dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;}} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {@@ -763,18 +838,14 @@ namespace tether {// so the browser fills it without depending on its polling timing.broadcast_local_event(make_otp_event({code, id}).dump(), client_fd);std::string payload = "{\"status\":\"ok\"}\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "request_otp") {// Claimed by the first site that polls for it, so the next site// the user visits doesn't get handed the previous site's code.Otp otp = otp_take_for_host(j.value("url", std::string{}));std::string payload = make_otp_event(otp).dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "consume_otp") {// A page filled the code; retire it so it isn't re-served. Scoped@@ -782,9 +853,7 @@ namespace tether {// the code that just arrived for the current one.otp_consume(j.value("otp_id", static_cast<uint64_t>(0)));std::string payload = "{\"status\":\"ok\"}\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "file_start") {if (broadcast_tcp_message(msg) == 0) {@@ -792,9 +861,7 @@ namespace tether {resp["command"] = "error";resp["message"] = "no_connected_mobile_client";std::string payload = resp.dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;}} else if (j.contains("command") && j["command"] == "file_chunk") {@@ -803,9 +870,7 @@ namespace tether {resp["command"] = "error";resp["message"] = "no_connected_mobile_client";std::string payload = resp.dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;}} else if (j.contains("command") && j["command"] == "file_end") {@@ -814,9 +879,7 @@ namespace tether {resp["command"] = "error";resp["message"] = "no_connected_mobile_client";std::string payload = resp.dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;}@@ -825,9 +888,7 @@ namespace tether {resp["transfer_id"] = j["transfer_id"];resp["status"] = "success";std::string payload = resp.dump() + "\n";- if (write(client_fd, payload.c_str(), payload.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, payload);continue;} else if (j.contains("command") && j["command"] == "accept_device" && j.contains("fingerprint")) {std::string print = j["fingerprint"];@@ -934,9 +995,7 @@ namespace tether {}std::string response = "OK\n";- if (write(client_fd, response.c_str(), response.size()) < 0) {- debug::log(ERR, "net write error\n");- }+ write_plain_packet(client_fd, response);}if (start > 0) {diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex 59741ea..1fd177c 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -1,6 +1,7 @@#include "notification.hpp"#include <csignal>#include <ctime>+#include <mutex>#include <nlohmann/json.hpp>#include <tether/bluetooth/config.hpp>#include <tether/bluetooth/connection.hpp>@@ -133,16 +134,22 @@ int main(int argc, char** argv) {if (backfill || message.outgoing || message.read)return;- std::string who = tether::bluetooth::contact_store().name_for(message.thread_key);+ std::string who;+ {+ std::lock_guard<std::mutex> lock(tether::bluetooth::message_store_mutex());+ who = tether::bluetooth::contact_store().name_for(message.thread_key);+ }if (who.empty())who = message.peer_name.empty() ? message.peer_address : message.peer_name;notifier.notify(who.empty() ? "iPhone" : who, message.body);});if (bluez.start()) {tether::bluetooth::g_bluez = &bluez;- loop.addFd(bluez.event_fd(), [&bluez](int) {+ loop.addFd(bluez.event_fd(), [&bluez, &connections](int) {bluez.drain();tether::broadcast_local_event(tether::build_bt_status().dump());+ // controller capability re-read on every bluez+ connections.refresh_capability();});auto cap = bluez.capability();debug::log(INFO, "Bluetooth: {} mode", tether::bluetooth::to_string(cap.mode));@@ -153,14 +160,13 @@ int main(int argc, char** argv) {// attempted when the controller can carry it and pairing produced a bond// that covers LE.auto bt_config = tether::bluetooth::load_config();- const bool ancs = bt_config.ancs_enabled && cap.mode == tether::bluetooth::DeliveryMode::Full;tether::bluetooth::g_bt_connections = &connections;tether::bluetooth::set_group_replies_enabled(bt_config.group_messages_enabled &&bt_config.ancs_content_enabled);tether::bluetooth::reload_group_rosters();- if (ancs) {+ {connections.set_notification_handlers([¬ifier](const tether::bluetooth::ancs::Notification& notification) {// Messages notifications are the only side channel that says@@ -192,7 +198,7 @@ int main(int argc, char** argv) {});}- connections.start(bt_config.device_address, ancs);+ connections.start(bt_config.device_address, bt_config.ancs_enabled);} else {debug::log(INFO, "Bluetooth unavailable; messages and notifications are disabled");}diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cppindex 612803e..2e2593d 100644--- a/test/test_bluetooth_supervisor.cpp+++ b/test/test_bluetooth_supervisor.cpp@@ -468,3 +468,109 @@ TEST(ProfileSupervisor, BusySessionKeepsPollingWithoutRetryBurst) {EXPECT_EQ(ops.map_attempts, 1);EXPECT_EQ(sup.status().map_error, ObexError::Busy);}++// A phone that walked out of the room answers with a page timeout, not a+// refusal. Escalating those to the five-minute ceiling leaves the link down long+// after the phone is back on the desk.+TEST(BearerSupervisor, TransientFailuresDoNotEscalateTheBackoff) {+ for (const char* message : {"org.bluez.Error.InProgress: Operation already in progress",+ "org.bluez.Error.NotReady: Resource Not Ready",+ "org.bluez.Error.Failed: br-connection-page-timeout",+ "org.bluez.Error.Failed: Software caused connection abort",+ "org.bluez.Error.Failed: le-connection-abort-by-local"}) {+ FakeBearer ops;+ ops.classic_succeeds = false;+ ops.classic_error = message;+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ for (int attempt = 0; attempt < 6; ++attempt) {+ sup.tick(now);+ EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS) << message;+ now += sup.status().classic_backoff;+ }+ }+}++// A refusal from the phone is a real answer, and repeating it every five seconds+// helps nobody.+TEST(BearerSupervisor, PersistentFailuresStillEscalate) {+ FakeBearer ops;+ ops.classic_succeeds = false;+ ops.classic_error = "org.bluez.Error.AuthenticationFailed";+ BearerSupervisor sup(ops, true);++ sup.tick(0);+ const int first = sup.status().classic_backoff;+ sup.tick(first);+ EXPECT_GT(sup.status().classic_backoff, first);+}++// reset() is what a caller reaches for when the phone reappears. The existing+// coverage stops at a minimum backoff; the case that actually bites is a backoff+// that grew to minutes while the phone was out of range.+TEST(BearerSupervisor, ResetClearsAnEscalatedBackoff) {+ FakeBearer ops;+ ops.classic_succeeds = false;+ ops.classic_error = "org.bluez.Error.AuthenticationFailed";+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ now += sup.status().classic_backoff;+ sup.tick(now);+ ASSERT_GT(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS);+ const int attempts = ops.classic_attempts;++ sup.reset();+ EXPECT_EQ(sup.status().classic_backoff, 0);+ sup.tick(++now);+ EXPECT_EQ(ops.classic_attempts, attempts + 1) << "reset() left the grown backoff in place";+}++// The Forbidden retry exists to drop a stale session left by a previous run.+// Removing the empty string that the failed CreateSession just wrote drops+// nothing at all.+TEST(ProfileSupervisor, ForbiddenRetryRemovesThePreviousSession) {+ FakeProfiles ops;+ ProfileSupervisor sup(ops);++ sup.tick(0, true);+ ASSERT_TRUE(sup.status().map_open);+ const std::string stale = sup.map_session();+ ASSERT_FALSE(stale.empty());++ // The session goes sour; the next attempt is refused.+ sup.drop_map();+ ops.removed.clear();+ ops.map_error = "org.bluez.obex.Error.Forbidden";+ sup.tick(PROFILE_STEADY_POLL_SECONDS * 2, true);++ EXPECT_EQ(sup.status().map_error, ObexError::Forbidden);+ EXPECT_EQ(ops.map_attempts, 3) << "the one extra retry did not happen";+}++// A MAP session can die while the Classic link stays up. Nothing else notices,+// because tick() short-circuits once map_open is set.+TEST(ProfileSupervisor, DropMapReopensWithoutTouchingPbap) {+ FakeProfiles ops;+ ProfileSupervisor sup(ops);++ sup.tick(0, true);+ ASSERT_TRUE(sup.status().map_open);+ ASSERT_TRUE(sup.status().pbap_open);+ const std::string first_map = sup.map_session();+ const std::string pbap = sup.pbap_session();++ sup.drop_map();+ EXPECT_FALSE(sup.status().map_open);+ EXPECT_TRUE(sup.status().pbap_open) << "contacts were dropped along with messages";+ ASSERT_EQ(ops.removed.size(), 1u);+ EXPECT_EQ(ops.removed.front(), first_map);++ // And reopens on the very next tick rather than waiting out the steady poll.+ sup.tick(1, true);+ EXPECT_TRUE(sup.status().map_open);+ EXPECT_NE(sup.map_session(), first_map);+ EXPECT_EQ(sup.pbap_session(), pbap) << "the surviving PBAP session was reopened needlessly";+}diff --git a/test/test_journal.cpp b/test/test_journal.cppindex 47feec6..8c4586a 100644--- a/test/test_journal.cpp+++ b/test/test_journal.cpp@@ -1,6 +1,10 @@#include <gtest/gtest.h>#include <tether/bluetooth/journal.hpp>+#include <cstdlib>+#include <filesystem>+#include <string>+using namespace tether::bluetooth;namespace {@@ -96,3 +100,65 @@ TEST(Journal, RetentionCollapsesRepeatedHandles) {ASSERT_EQ(kept.size(), 1u);EXPECT_TRUE(kept[0].read) << "the newest copy carries the current read state";}++namespace {++ // journal_path() is derived from $HOME, so the only way to point the journal+ // at a scratch file is to move HOME for the duration of the test.+ class ScopedHome {+ public:+ explicit ScopedHome(const std::filesystem::path& dir) {+ if (const char* previous = getenv("HOME"))+ previous_ = previous;+ setenv("HOME", dir.c_str(), 1);+ }+ ~ScopedHome() {+ if (previous_.empty())+ unsetenv("HOME");+ else+ setenv("HOME", previous_.c_str(), 1);+ }++ private:+ std::string previous_;+ };++} // namespace++// The unread badge has to survive a daemon restart, so a mark-read is only+// really applied once it has been written back. The journal is append-only, and+// retention keeps the last line for a handle: re-appending is the whole fix.+TEST(Journal, ReadStateSurvivesARestart) {+ const auto home = std::filesystem::temp_directory_path() / "tether-journal-read-state";+ std::filesystem::remove_all(home);+ std::filesystem::create_directories(home);+ ScopedHome scoped(home);++ const Message arrived = make("/msg/1", NOW);+ {+ MessageJournal journal;+ ASSERT_TRUE(journal.open());+ journal.append(arrived);+ }++ // A restart in between: the message comes back exactly as it went in.+ {+ MessageJournal journal;+ ASSERT_TRUE(journal.open());+ auto loaded = journal.load(NOW);+ ASSERT_EQ(loaded.size(), 1u);+ ASSERT_FALSE(loaded[0].read);++ Message seen = arrived;+ seen.read = true;+ journal.append(seen);+ }++ MessageJournal reader;+ ASSERT_TRUE(reader.open());+ auto loaded = reader.load(NOW);+ ASSERT_EQ(loaded.size(), 1u) << "the re-appended line was not collapsed onto the original";+ EXPECT_TRUE(loaded[0].read) << "the message came back unread, so the badge would refill on every restart";++ std::filesystem::remove_all(home);+}