Linux + iPhone Continuity / iMessage / SMS
fix: LE bearer corrections and backoff retry fixes
Zack Bartele201c3c6d04a
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.mdindex a539ab5..b9a0ba7 100644--- a/docs/BLUETOOTH.md+++ b/docs/BLUETOOTH.md@@ -588,6 +588,58 @@ phone-side Bluetooth cycle, while a refused registration still points at`systemctl restart bluetooth`. Sharing one message for both is what sent thissession chasing the local stack for an hour.+### 2026-08-20 - Three ways the LE cycle sabotaged itself++A cold boot came up with BR/EDR, MAP and PBAP working and LE never forming, on a+machine that had soaked cleanly the evening before. The local stack measured+correct throughout: `bearer_api: confirmed`, `bond_has_le: true`,+`secure_connections: true`, CoD `0x7c0408`, and the solicitation advert on air+(`ActiveInstances` alternating 0 and 1 on the expected 45s/180s cycle). The+phone was the immediate cause -- a dial with nothing competing, against a freshly+restarted `bluetoothd`, returned `Connection timed out` in 25s, and 180s of+uninterrupted solicitation went unanswered. But reading the daemon log across a+full cycle turned up three faults of our own, each of which turns one bad minute+into a permanent outage.++**The solicitation aborted our own dial.** `connect_le()` is asynchronous, and+`le_dialling` was derived from the clock alone. When the 45s dial window closed+the advert went up immediately, while BlueZ was still connecting, and the connect+died with `le-connection-abort-by-local` -- observed once per cycle, forever. The+window now stays open while a dial is outstanding and closes on the reply, so the+two routes really do alternate instead of overlapping. `connect_le()` abandons+the call at its own timeout, which is what bounds the window.++**Dialling stopped for good after six failures.** `LE_ATTEMPTS_BEFORE_ADVICE`+gated the retry as well as the advice string it is named for, and `le_failures_`+is cleared only by `reset()` or by an observed LE link -- neither of which+happens while BR/EDR stays up. Six failures into a daemon's life, LE was never+dialled again. Combined with the abort above, that is roughly twenty minutes from+boot to a daemon that will not try. This is the "worked all morning, then stopped+until I restarted it" report. The cap now selects the message only; the retry+runs as long as LE is down, paced by the existing 300s backoff ceiling.++**PreferredBearer was written under a live LE link.** The Classic path called+`set_preferred_bearer("bredr")` on every reconnect attempt, including while LE+was up, which drops the LE link -- the mirror image of the race removed on+2026-08-19, where the LE path wrote `"le"` under an in-flight connect. A bug+reporter independently described the consequence exactly: the bond stays+`BR/EDR + LE` but only one bearer holds a live connection at a time, trading off+every few minutes. The property steers the untyped `Device1.Connect` and nothing+else, so it is now written only on that fallback, which is reached only with+nothing connected. It is gone from `BearerOps` entirely -- the supervisor cannot+touch it by construction, which is a stronger guarantee than the test it replaces.++None of the three explains a phone that will not answer. All three explain why it+never recovered once it stopped.++Cycling Bluetooth on the iPhone brought LE straight back -- first dial, no+aborts, both ANCS notify characteristics subscribed, clean over a soak. But the+daemon that had been failing all morning did not notice for minutes: LE shared+BR/EDR's 300s backoff ceiling, so a phone the user had just fixed still read as+broken. LE now backs off to its own 60s ceiling. A dial costs nothing since one+is never issued while another is outstanding, and the failure it recovers from+is the one a human has just cleared by hand.+### PBAP`Select("int", "pb")` followed by `PullAll` with `Format: vcard30` and `MaxCount` returned 456 contacts on the first attempt.diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hppindex f208bc2..f937983 100644--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp@@ -9,6 +9,7 @@ namespace tether::bluetooth {inline constexpr int BEARER_SETTLE_SECONDS = 3;inline constexpr int BEARER_BACKOFF_MIN_SECONDS = 5;inline constexpr int BEARER_BACKOFF_MAX_SECONDS = 300;+ inline constexpr int LE_BACKOFF_MAX_SECONDS = 60;// How many refused attempts before the status stops saying "connecting"inline constexpr int CLASSIC_FAILURES_BEFORE_ADVICE = 6;inline constexpr int LE_ATTEMPTS_BEFORE_ADVICE = 6;@@ -40,8 +41,6 @@ namespace tether::bluetooth {virtual bool le_bearer_available() const = 0;virtual bool le_connected() const = 0;- virtual void set_preferred_bearer(const std::string& bearer) = 0;-virtual ConnectResult connect_classic(std::string& err) = 0;// Must not block: BlueZ keeps working on a connect after a synchronous// call gives up, and every later attempt then collides with it.diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cppindex 50fd26a..b55cc67 100644--- a/src/core/src/bluetooth/bearer_supervisor.cpp+++ b/src/core/src/bluetooth/bearer_supervisor.cpp@@ -7,10 +7,10 @@ namespace tether::bluetooth {namespace {- int grow_backoff(int current) {+ int grow_backoff(int current, int ceiling = BEARER_BACKOFF_MAX_SECONDS) {if (current <= 0)return BEARER_BACKOFF_MIN_SECONDS;- return std::min(current * 2, BEARER_BACKOFF_MAX_SECONDS);+ return std::min(current * 2, ceiling);}// Failures that clear on their own, unlike a refusal from the phone.@@ -52,10 +52,15 @@ namespace tether::bluetooth {return reported == ConnectResult::Failed && is_already_running(err) ? ConnectResult::Busy : reported;}- int next_backoff(int current, const std::string& err) {- return is_transient(err) ? BEARER_BACKOFF_MIN_SECONDS : grow_backoff(current);+ 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);}+ constexpr const char* LE_PHONE_SILENT_ADVICE =+ "The iPhone is not answering on LE. Its Bluetooth is wedged on its own side: turn Bluetooth off "+ "and back on on the iPhone, which clears this even when Share System Notifications is already on. "+ "Messages and contacts are unaffected.";+} // namespaceBearerSupervisor::BearerSupervisor(BearerOps& ops, bool ancs_enabled) : ops_(ops), ancs_enabled_(ancs_enabled) {}@@ -121,7 +126,6 @@ namespace tether::bluetooth {classic_connected_since_ = -1;if (now >= next_classic_attempt_) {- ops_.set_preferred_bearer("bredr");std::string err;switch (classify(ops_.connect_classic(err), err)) {case ConnectResult::Requested:@@ -170,13 +174,13 @@ namespace tether::bluetooth {if (!status_.le_connected) {// alternate the two routes rather than running bothconst int64_t phase = (now - le_down_since_) % (LE_DIAL_WINDOW_SECONDS + LE_SOLICIT_WINDOW_SECONDS);- status_.le_dialling = phase < LE_DIAL_WINDOW_SECONDS;++ status_.le_dialling = phase < LE_DIAL_WINDOW_SECONDS || ops_.le_connect_outstanding();const bool settled =classic_connected_since_ >= 0 && now - classic_connected_since_ >= BEARER_SETTLE_SECONDS;- if (settled && status_.le_dialling && !ops_.le_connect_outstanding() &&- le_failures_ < LE_ATTEMPTS_BEFORE_ADVICE && now >= next_le_attempt_) {+ if (settled && status_.le_dialling && !ops_.le_connect_outstanding() && now >= next_le_attempt_) {std::string err;const ConnectResult result = classify(ops_.connect_le(err), err);@@ -193,22 +197,21 @@ namespace tether::bluetooth {le_listening_ = false;le_stuck_locally_ = false;le_phone_silent_ = is_transient(err);- status_.le_backoff = next_backoff(status_.le_backoff, err);+ status_.le_backoff = next_backoff(status_.le_backoff, err, LE_BACKOFF_MAX_SECONDS);next_le_attempt_ = now + status_.le_backoff;debug::log(WARN, "bluetooth: LE connect failed ({}), retrying in {}s", err, status_.le_backoff);break;}}if (!status_.le_connected) {- if (ops_.le_connect_outstanding() || le_listening_)+ if (le_phone_silent_ && le_failures_ >= LE_ATTEMPTS_BEFORE_ADVICE)+ status_.reason = LE_PHONE_SILENT_ADVICE;+ else if (ops_.le_connect_outstanding() || le_listening_)status_.reason = "Connected. Waiting for the iPhone to open the LE link that carries ""notifications. If it does not, open Settings > Bluetooth > (i) on the ""iPhone and check Share System Notifications.";else if (le_phone_silent_)- status_.reason = "The iPhone is not answering on LE. Its Bluetooth is wedged on its own "- "side: turn Bluetooth off and back on on the iPhone, which clears this even "- "when Share System Notifications is already on. Messages and contacts are "- "unaffected.";+ status_.reason = LE_PHONE_SILENT_ADVICE;elsestatus_.reason = "Nothing is listening for the iPhone's LE link. BlueZ refused to register ""for it, which only \"sudo systemctl restart bluetooth\" clears. Messages "diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cppindex 2e98f91..d389c44 100644--- a/src/core/src/bluetooth/connection.cpp+++ b/src/core/src/bluetooth/connection.cpp@@ -270,7 +270,7 @@ namespace tether::bluetooth {return device && device->le_link_up();}- void set_preferred_bearer(const std::string& bearer) override {+ void set_preferred_bearer(const std::string& bearer) {auto device = lookup();if (!device)return;@@ -310,6 +310,7 @@ namespace tether::bluetooth {return ConnectResult::Failed;}}+ set_preferred_bearer("bredr");return call(device->path, IFACE_DEVICE, "Connect", err) ? ConnectResult::Requested: ConnectResult::Failed;}diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cppindex a10b7bf..4fdf2d9 100644--- a/src/gtk/devices_view.cpp+++ b/src/gtk/devices_view.cpp@@ -255,8 +255,9 @@ namespace tether::ui {bool online = std::find(g_devices.connected_fps.begin(),g_devices.connected_fps.end(),g_devices.selected_device_fp) != g_devices.connected_fps.end();- set_status_action(online ? "Connected and ready."- : "Device is offline. Pair again or wait for network.");+ set_status_action(online+ ? "Connected and ready."+ : "Device is offline. Open the Tether app on iPhone while on the same network.");if (g_devices.btn_grid) {gtk_widget_set_visible(g_devices.btn_grid, online);}diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cppindex 2b98d07..4d068c5 100644--- a/test/test_bluetooth_objects.cpp+++ b/test/test_bluetooth_objects.cpp@@ -203,7 +203,10 @@ TEST(Capability, CompatibilityWhenExperimentalIsOff) {EXPECT_EQ(cap.mode, DeliveryMode::Compatibility);EXPECT_EQ(cap.bearer_api, BearerApi::Absent);ASSERT_EQ(cap.setup.size(), 1u);- EXPECT_NE(cap.setup[0].command.find("--experimental"), std::string::npos);+ // Either form of the step -- copying the shipped drop-in or writing one --+ // lands in the same place, so that is what is asserted rather than a literal+ // flag that only one of the two branches contains.+ EXPECT_NE(cap.setup[0].command.find("bluetooth.service.d"), std::string::npos);}// Without --experimental bluetoothd registers Bearer.LE1 as an empty marker: no@@ -227,7 +230,10 @@ TEST(Capability, AnEmptyBearerInterfaceIsNotProofOfTheApi) {EXPECT_FALSE(objects.devices[0].has_le_bearer);EXPECT_EQ(cap.bearer_api, BearerApi::Absent);ASSERT_EQ(cap.setup.size(), 1u);- EXPECT_NE(cap.setup[0].command.find("--experimental"), std::string::npos);+ // Either form of the step -- copying the shipped drop-in or writing one --+ // lands in the same place, so that is what is asserted rather than a literal+ // flag that only one of the two branches contains.+ EXPECT_NE(cap.setup[0].command.find("bluetooth.service.d"), std::string::npos);}TEST(Capability, ClassicOnlyBondDoesNotDisproveBearerApi) {diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cppindex 9728dfa..e7092a7 100644--- a/test/test_bluetooth_supervisor.cpp+++ b/test/test_bluetooth_supervisor.cpp@@ -21,7 +21,6 @@ namespace {int classic_attempts = 0;int le_attempts = 0;- std::vector<std::string> preferred;bool device_present() const override { return present; }bool device_paired() const override { return paired; }@@ -29,8 +28,6 @@ namespace {bool le_bearer_available() const override { return le_available; }bool le_connected() const override { return le; }- void set_preferred_bearer(const std::string& bearer) override { preferred.push_back(bearer); }-std::string classic_error = "br/edr refused";std::string le_error = "le refused";@@ -111,27 +108,6 @@ TEST(BearerSupervisor, ConnectsClassicThenLeAfterSettling) {EXPECT_TRUE(sup.status().le_connected);}-// PreferredBearer steers Device1.Connect, but the LE path calls the per-bearer-// Connect, which already names the transport. Writing "le" and then "bredr" back-// milliseconds later raced the asynchronous connect that was still in flight and-// produced le-connection-abort-by-local, so the LE path must not touch it at all.-TEST(BearerSupervisor, DoesNotSteerPreferredBearerWhenDiallingLe) {- FakeBearer ops;- BearerSupervisor sup(ops, true);-- sup.tick(0);- sup.tick(1);- sup.tick(1 + BEARER_SETTLE_SECONDS);- ASSERT_EQ(ops.le_attempts, 1) << "the LE attempt this is about never happened";-- for (const auto& choice : ops.preferred)- EXPECT_NE(choice, "le") << "raced the async LE connect by rewriting PreferredBearer under it";-- // Classic still selects it, and must leave it there rather than clearing it.- ASSERT_FALSE(ops.preferred.empty());- EXPECT_EQ(ops.preferred.back(), "bredr");-}-TEST(BearerSupervisor, ClassicBackoffGrowsAndCaps) {FakeBearer ops;ops.classic_succeeds = false;@@ -301,7 +277,6 @@ TEST(BearerSupervisor, StandsDownWhenDeviceIsUnpaired) {EXPECT_FALSE(sup.status().device_paired);EXPECT_EQ(ops.classic_attempts, 0) << "must not dial an unpaired device";EXPECT_EQ(ops.le_attempts, 0);- EXPECT_TRUE(ops.preferred.empty()) << "must not touch PreferredBearer before a bond exists";}// Forbidden and Busy look similar but call for opposite advice. Reporting a@@ -611,9 +586,15 @@ TEST(BearerSupervisor, AlternatesBetweenDiallingAndSoliciting) {EXPECT_TRUE(sup.status().le_dialling) << "the dial window should come first";EXPECT_EQ(ops.le_attempts, 1);- // The registration never completes. The phase must still end.+ // The clock runs out while BlueZ is still connecting. Soliciting now would+ // abort that connect, so the window stays open until the reply lands.now += LE_DIAL_WINDOW_SECONDS;sup.tick(now);+ EXPECT_TRUE(sup.status().le_dialling) << "solicited on top of a dial that was still in flight";++ // connect_le() abandons the call at its own timeout, which is what ends it.+ ops.outstanding = false;+ sup.tick(++now);EXPECT_FALSE(sup.status().le_dialling) << "deadlocked: an open registration froze the dial phase";// No connect may be issued anywhere in the solicitation window.@@ -858,3 +839,82 @@ TEST(BearerSupervisor, ASuccessfulLeLinkClearsTheBackoffItGrew) {EXPECT_EQ(ops.le_attempts, attempts + 1) << "sat out a backoff inherited from a previous outage";EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);}++// The advice threshold names the message, not the end of the retry. Letting it+// gate the loop meant one daemon lifetime got six LE attempts and then never+// dialled again -- the "worked all morning, then stopped for good" report.+TEST(BearerSupervisor, KeepsDiallingPastTheAdviceThreshold) {+ FakeBearer ops;+ ops.le_succeeds = false;+ ops.le_error = "GDBus.Error:org.bluez.Error.Failed: Connection timed out";+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;++ // Well past the threshold, over many dial/solicit cycles.+ const int64_t cycle = LE_DIAL_WINDOW_SECONDS + LE_SOLICIT_WINDOW_SECONDS;+ for (int i = 0; i < 20; ++i) {+ sup.tick(now);+ now += cycle;+ }+ EXPECT_GT(ops.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "stopped dialling for good";+ EXPECT_NE(sup.status().reason.find("not answering on LE"), std::string::npos);+}++// A dial that BlueZ has not answered yet must keep the solicitation off the air:+// raising an advert mid-connect is what produced le-connection-abort-by-local on+// every cycle, so the phone was never dialled and never solicited cleanly.+TEST(BearerSupervisor, HoldsTheSolicitationOffWhileADialIsInFlight) {+ class ListeningBearer : public FakeBearer {+ public:+ ConnectResult connect_le(std::string&) override {+ ++le_attempts;+ outstanding = true;+ return ConnectResult::Requested;+ }+ } ops;++ BearerSupervisor sup(ops, true);+ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;+ sup.tick(now);+ ASSERT_TRUE(ops.outstanding);++ const int64_t cycle = LE_DIAL_WINDOW_SECONDS + LE_SOLICIT_WINDOW_SECONDS;+ for (int64_t t = now; t < now + 3 * cycle; t += BEARER_POLL_SECONDS) {+ sup.tick(t);+ ASSERT_TRUE(sup.status().le_dialling) << "solicited over an outstanding dial at t=" << t;+ }+}++// LE and BR/EDR back off to different ceilings on purpose. The LE failure this+// recovers from is usually cleared by the user cycling Bluetooth on the phone,+// and BR/EDR's five-minute ceiling meant a phone that had just been fixed still+// looked broken for minutes. A dial is cheap now that one is never issued while+// another is outstanding.+TEST(BearerSupervisor, LeBacksOffLessFarThanClassic) {+ static_assert(LE_BACKOFF_MAX_SECONDS < BEARER_BACKOFF_MAX_SECONDS);++ FakeBearer ops;+ ops.le_succeeds = false;+ ops.le_error = "org.bluez.Error.AuthenticationFailed"; // not transient, so it grows+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;++ // Only the dial window issues attempts, so grow it one whole cycle at a time.+ const int64_t cycle = LE_DIAL_WINDOW_SECONDS + LE_SOLICIT_WINDOW_SECONDS;+ for (int i = 0; i < 20; ++i) {+ sup.tick(now);+ now += cycle;+ }+ EXPECT_EQ(sup.status().le_backoff, LE_BACKOFF_MAX_SECONDS) << "LE inherited the BR/EDR ceiling";+}