Linux + iPhone Continuity / iMessage / SMS
fix: ancs reconnect can wedge kernel bt
Zack Bartel6851efda8add
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.mdindex 72d22bd..c5a80cd 100644--- a/docs/BLUETOOTH.md+++ b/docs/BLUETOOTH.md@@ -55,7 +55,7 @@ sudo systemctl enable --now tether-btclass@hci0````PartOf=bluetooth.service` re-runs it on every `bluetooth.service` restart. It writes the-class, reads it back, and retries for ten seconds.+class, reads it back, and retries for 30 seconds.**A portable build has no unit on disk to enable**, since neither the AppImage nor the Flatpakcan write a system directory. That command fails there with `Unit [email protected]@@ -3884,3 +3884,32 @@ Open: a call that rang while Linux played media (20:38:09, `YES 501`) never gotphone. iOS put it on this computer's hands-free link until the user picked AirPods on the phone19 s later. This change does not touch that path. Whether it happened before this change is notyet known.++### 2026-10-31 - Paging an absent phone every five seconds, and four smaller gaps++**An iPhone with Bluetooth off was paged every 5s forever.** `is_transient` listed+`page-timeout`, `Host is down` and `Connection timed out`, so `next_backoff` reset each to the+5s minimum. Those are what an absent phone answers.++**A removal that beat its fetch brought the notification back.** Removed arrived while the fetch+for the same UID was queued: the registry forgot it and the clients were told, then the+response found `in_progress[uid]` and stored and popped it up again. Withdraw now drops the+`in_progress` entry.++**`rebuild()` kept the old session's buffered packets.** Only `set_device()` cleared the inbox,+so packets buffered before an LE drop were drained after the resubscribe and fetched in the new+UID space. `rebuild()` clears it.++**A Classic connect could abort the LE dial.** `connect_classic()` wrote `PreferredBearer=bredr`+with the async LE dial in flight, which cancels it as `le-connection-abort-by-local`, and the+dial is one-shot. It now skips the write while the dial is outstanding.++**The PBAP owner card was read as a contact.** `pb` index 0 is the owner card (iOS: "My+Number"), and the first card per number wins the lookup, so self-threads took its name. The+main phonebook is pulled with `Offset=1`; `fav` and `cch` have no owner card.++**A popup outlived its dismissal on the iPhone.** Removal reached GTK and the TUI only. The+notifier now keeps UID -> popup and closes it on withdraw.++Not settled: all of it on hardware. iPhone Bluetooth off for ten minutes should show the backoff+stop at 60s; a notification dismissed on the phone should close its popup.diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hppindex 8c2ab4d..05aa78f 100644--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp@@ -10,6 +10,11 @@ namespace tether::bluetooth {inline constexpr int BEARER_BACKOFF_MIN_SECONDS = 5;inline constexpr int BEARER_BACKOFF_MAX_SECONDS = 300;+ // Ceiling for the BR/EDR backoff while the phone does not answer pages.+ // Paging an absent phone every 5s can wedge bluetoothd in the kernel's+ // l2cap connect; a minute still finds it soon after it returns without LE.+ inline constexpr int ABSENT_CLASSIC_BACKOFF_MAX_SECONDS = 60;+// Ceiling for the BR/EDR backoff while LE is connected.inline constexpr int LE_UP_CLASSIC_BACKOFF_MAX_SECONDS = 30;diff --git a/src/core/include/tether/bluetooth/pbap_session.hpp b/src/core/include/tether/bluetooth/pbap_session.hppindex 17952aa..3aa2ea6 100644--- a/src/core/include/tether/bluetooth/pbap_session.hpp+++ b/src/core/include/tether/bluetooth/pbap_session.hpp@@ -39,9 +39,12 @@ namespace tether::bluetooth {// Pulls the selected phonebook and parses it.//// Uses PullAll's MaxCount filter. MaxListCount is MAP's option and makes a- // PBAP transfer fail or return nothing at all.- std::vector<VCard>- pull_all(std::string& err, int max = PBAP_MAX_CONTACTS, const char* fields = PBAP_CONTACT_FIELDS);+ // PBAP transfer fail or return nothing at all. `offset` 1 skips the main+ // phonebook's owner card (0.vcf); other phonebooks have none.+ std::vector<VCard> pull_all(std::string& err,+ int max = PBAP_MAX_CONTACTS,+ const char* fields = PBAP_CONTACT_FIELDS,+ int offset = 0);const std::string& path() const;diff --git a/src/core/src/bluetooth/ancs/client.cpp b/src/core/src/bluetooth/ancs/client.cppindex 56379f3..97b90c4 100644--- a/src/core/src/bluetooth/ancs/client.cpp+++ b/src/core/src/bluetooth/ancs/client.cpp@@ -429,6 +429,11 @@ namespace tether::bluetooth::ancs {set_status(false, "Subscribing to the iPhone's notifications...");sequencer->reset();in_progress.clear();+ // Buffered packets carry the old session's UIDs.+ std::lock_guard<std::mutex> lock(inbox);+ pending_source.clear();+ pending_data.clear();+ pending_actions.clear();}bool AncsClientState::link_alive() const {@@ -454,6 +459,8 @@ namespace tether::bluetooth::ancs {case Decision::Ignore:return;case Decision::Withdraw:+ // A fetch still queued or in flight must not bring it back.+ in_progress.erase(event.uid);if (on_withdraw)on_withdraw(event.uid);return;diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cppindex c985fd9..c287ce3 100644--- a/src/core/src/bluetooth/bearer_supervisor.cpp+++ b/src/core/src/bluetooth/bearer_supervisor.cpp@@ -18,12 +18,8 @@ namespace tether::bluetooth {bool is_transient(const std::string& err) {static const char* const transient[] = {"org.bluez.Error.NotReady",- "page-timeout",- "page timeout","connection-abort","Software caused connection abort",- "Host is down",- "Connection timed out","br-connection-canceled","le-connection-abort-by-local","br-connection-refused",@@ -51,8 +47,27 @@ namespace tether::bluetooth {return reported == ConnectResult::Failed && is_already_running(err) ? ConnectResult::Busy : reported;}+ // The phone did not answer the page: out of range or Bluetooth off.+ bool is_absent(const std::string& err) {+ static const char* const absent[] = {+ "page-timeout",+ "page timeout",+ "Host is down",+ "Connection timed out",+ };+ for (const char* needle : absent) {+ if (err.find(needle) != std::string::npos)+ return true;+ }+ return false;+ }+int next_backoff(int current, const std::string& err, int ceiling = BEARER_BACKOFF_MAX_SECONDS) {- return is_transient(err) ? BEARER_BACKOFF_MIN_SECONDS : grow_backoff(current, ceiling);+ if (is_transient(err))+ return BEARER_BACKOFF_MIN_SECONDS;+ if (is_absent(err))+ return grow_backoff(current, std::min(ceiling, ABSENT_CLASSIC_BACKOFF_MAX_SECONDS));+ return grow_backoff(current, ceiling);}// Marked here, translated where it is read: gettext cannot run at namespace scope.diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cppindex ae1ee30..b5cf519 100644--- a/src/core/src/bluetooth/connection.cpp+++ b/src/core/src/bluetooth/connection.cpp@@ -426,7 +426,8 @@ namespace tether::bluetooth {}}- if (!link_up(*device))+ // Never over an LE dial in flight: the write aborts it.+ if (!link_up(*device) && !le_connect_outstanding())set_preferred_bearer("bredr");if (call(device->path, IFACE_DEVICE, "Connect", err))return ConnectResult::Requested;@@ -1125,7 +1126,7 @@ namespace tether::bluetooth {return;}- auto contacts = session.pull_all(err);+ auto contacts = session.pull_all(err, PBAP_MAX_CONTACTS, PBAP_CONTACT_FIELDS, 1);if (!err.empty()) {debug::log(WARN, "bluetooth: PBAP PullAll failed: {}", err);return;diff --git a/src/core/src/bluetooth/pbap_session.cpp b/src/core/src/bluetooth/pbap_session.cppindex 2cbf992..829618c 100644--- a/src/core/src/bluetooth/pbap_session.cpp+++ b/src/core/src/bluetooth/pbap_session.cpp@@ -74,7 +74,7 @@ namespace tether::bluetooth {return true;}- std::vector<VCard> PbapSession::pull_all(std::string& err, int max, const char* fields) {+ std::vector<VCard> PbapSession::pull_all(std::string& err, int max, const char* fields, int offset) {std::vector<VCard> contacts;const std::filesystem::path target = staging_file();@@ -90,6 +90,8 @@ namespace tether::bluetooth {g_variant_builder_add(&filter, "{sv}", "Format", g_variant_new_string("vcard30"));// MaxCount, not MAP's MaxListCount.g_variant_builder_add(&filter, "{sv}", "MaxCount", g_variant_new_uint16(static_cast<guint16>(max)));+ if (offset > 0)+ g_variant_builder_add(&filter, "{sv}", "Offset", g_variant_new_uint16(static_cast<guint16>(offset)));// only what parse_vcards reads. kill PHOTOg_variant_builder_add(&filter, "{sv}", "Fields", g_variant_new_parsed(fields));diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex 32433c3..011d8b6 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -730,9 +730,12 @@ int main(int argc, char** argv) {notification.silent,"",otp,- notification.app_id});+ notification.app_id,+ "",+ notification.uid});},- [](uint32_t uid) {+ [¬ifier](uint32_t uid) {+ notifier.withdraw(uid);nlohmann::json event;event["command"] = "bt_notification_removed";event["uid"] = uid;diff --git a/src/daemon/notification.cpp b/src/daemon/notification.cppindex 00a9d1d..6082dbd 100644--- a/src/daemon/notification.cpp+++ b/src/daemon/notification.cpp@@ -113,6 +113,9 @@ namespace tether {// inline reply field. Touched only on the notifier's thread.std::unordered_map<guint32, std::string> g_reply_threads;+ // iPhone notification UID -> its open popup+ std::unordered_map<uint32_t, NotifyNotification*> g_ancs_popups;+guint32 notification_id(NotifyNotification* notification) {gint id = 0;g_object_get(notification, "id", &id, nullptr);@@ -275,9 +278,20 @@ namespace tether {void on_notification_closed(NotifyNotification* notification, gpointer) {g_reply_threads.erase(notification_id(notification));+ std::erase_if(g_ancs_popups, [notification](const auto& entry) { return entry.second == notification; });g_object_unref(notification);}+ gboolean withdraw_on_main(gpointer user_data) {+ const auto uid = static_cast<uint32_t>(GPOINTER_TO_UINT(user_data));+ const auto it = g_ancs_popups.find(uid);+ if (it == g_ancs_popups.end())+ return G_SOURCE_REMOVE;+ // The "closed" signal that follows drops the entry and the reference.+ notify_notification_close(it->second, nullptr);+ return G_SOURCE_REMOVE;+ }+gboolean show_notification_on_main(gpointer user_data) {std::unique_ptr<NotificationRequest> request(static_cast<NotificationRequest*>(user_data));@@ -343,8 +357,8 @@ namespace tether {notify_notification_set_urgency(notification, spec->quiet ? NOTIFY_URGENCY_LOW : NOTIFY_URGENCY_NORMAL);const AppLauncher launcher = spec->app_id.empty() ? AppLauncher{} : resolve_launcher(spec->app_id);- const bool has_actions =- !spec->reply_thread.empty() || !spec->otp_code.empty() || !launcher.payload.empty();+ const bool has_actions = !spec->reply_thread.empty() || !spec->otp_code.empty() ||+ !launcher.payload.empty() || spec->ancs_uid >= 0;if (has_actions)g_signal_connect(notification, "closed", G_CALLBACK(on_notification_closed), nullptr);@@ -408,6 +422,8 @@ namespace tether {}if (inline_reply)g_reply_threads[notification_id(notification)] = spec->reply_thread;+ if (spec->ancs_uid >= 0)+ g_ancs_popups[static_cast<uint32_t>(spec->ancs_uid)] = notification;if (!has_actions)g_object_unref(notification);return G_SOURCE_REMOVE;@@ -517,6 +533,13 @@ namespace tether {g_main_context_invoke_full(impl_->context, G_PRIORITY_DEFAULT, show_spec_on_main, copy, nullptr);}+ void DesktopNotifier::withdraw(uint32_t ancs_uid) {+ if (!impl_ || !impl_->initialized)+ return;+ g_main_context_invoke_full(+ impl_->context, G_PRIORITY_DEFAULT, withdraw_on_main, GUINT_TO_POINTER(ancs_uid), nullptr);+ }+void DesktopNotifier::notify_file_arrived(const std::filesystem::path& path) {if (!impl_->initialized || !desktop_popups_enabled()) {return;diff --git a/src/daemon/notification.hpp b/src/daemon/notification.hppindex d4779fa..96f6a5e 100644--- a/src/daemon/notification.hpp+++ b/src/daemon/notification.hpp@@ -1,5 +1,6 @@#pragma once+#include <cstdint>#include <filesystem>#include <functional>#include <memory>@@ -25,6 +26,8 @@ namespace tether {// MAP handle to mark read when the code is copied. Empty for// notifications with no message behind them.std::string read_handle;+ // iPhone notification UID, or -1. Set, the popup closes on withdraw().+ int64_t ancs_uid = -1;};class DesktopNotifier {@@ -52,6 +55,9 @@ namespace tether {void notify(const NotificationSpec& spec);+ // Closes the popup shown for this iPhone notification UID, if any.+ void withdraw(uint32_t ancs_uid);+private:struct Impl;std::unique_ptr<Impl> impl_;diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cppindex 07c4d86..737a848 100644--- a/test/test_bluetooth_supervisor.cpp+++ b/test/test_bluetooth_supervisor.cpp@@ -730,12 +730,8 @@ TEST(ProfileSupervisor, BusySessionKeepsPollingWithoutRetryBurst) {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.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","org.bluez.Error.Failed: br-connection-refused"}) {@@ -753,6 +749,30 @@ TEST(BearerSupervisor, TransientFailuresDoNotEscalateTheBackoff) {}}+// A phone that walked out of the room, or has Bluetooth off, answers with a page+// timeout. Paging it every 5s forever is what wedges bluetoothd; the five-minute+// ceiling would leave the link down long after it is back on the desk.+TEST(BearerSupervisor, AbsentPhoneBacksOffToTheAbsentCeiling) {+ for (const char* message : {"org.bluez.Error.Failed: br-connection-page-timeout",+ "org.bluez.Error.Failed: Host is down",+ "org.bluez.Error.Failed: Connection timed out"}) {+ FakeBearer ops;+ ops.classic_succeeds = false;+ ops.classic_error = message;+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ const int first = sup.status().classic_backoff;+ for (int attempt = 0; attempt < 10; ++attempt) {+ now += sup.status().classic_backoff;+ sup.tick(now);+ }+ EXPECT_GT(sup.status().classic_backoff, first) << message;+ EXPECT_EQ(sup.status().classic_backoff, ABSENT_CLASSIC_BACKOFF_MAX_SECONDS) << message;+ }+}+// A refusal from the phone is a real answer, and repeating it every five seconds// helps nobody.TEST(BearerSupervisor, PersistentFailuresStillEscalate) {