Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: le retry

Zack Bartelcc5390616564
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.md
index 0a355e3..0512318 100644
--- a/docs/BLUETOOTH.md
+++ b/docs/BLUETOOTH.md
@@ -121,7 +121,9 @@ checks the daemon does not make.
| MAP reports `busy`, or the transport says `Connection refused (111)` | Another computer holds the iPhone's single MAP session | Stop the other client |
| Pairing fails with `br-connection-key-missing` | A stale bond on one side, or the adapter is not `Pairable` | Delete the computer's entry on the phone (Forget This Device) and `tether --bt-unpair <addr>` locally, then pair again |
| The phone shows two entries for this computer | A failed pairing left both a Classic and an LE record | Delete both on the phone before retrying |
-| LE never connects and the log repeats `org.bluez.Error.InProgress` | BlueZ is holding a connect operation that never completed | `sudo systemctl restart bluetooth`. Disconnecting the device does not clear it. With `tether-btclass@hci0` enabled the class survives the restart |
+| LE never connects and the log repeats `org.bluez.Error.InProgress` | BlueZ is holding a connect operation that never completed | The daemon now drops the LE bearer itself and redials, which clears it without a restart. If it persists, `sudo systemctl restart bluetooth`. With `tether-btclass@hci0` enabled the class survives the restart |
+| Notifications stopped and never came back, while messages and contacts kept working | Fixed. The bearer supervisor used to stop retrying LE after six attempts, and only a Classic drop or a daemon restart re-armed it | Nothing. LE is now retried indefinitely at the five-minute ceiling, and the ANCS solicitation is kept on air whenever LE is down |
+| `tether --bt-status` reports `Bond: BR/EDR only` | The bond was made without cross-transport key derivation, so it has no LE half and can never carry ANCS | Forget this computer on the iPhone and pair again. Check `secure-connections` in the same output first: re-pairing cannot help while it is off |
| Everything connects but `ancs_ready` stays false | Compatibility mode, or iOS has not authorized notification content yet | Check `Mode:` in `tether --bt-status`. In full mode the daemon retries, the first request returns `NotPermitted` until the prompt on the phone is approved |
| A group conversation cannot be replied to | Working as designed until the route is unambiguous | The thread's `reply_reason` says which condition failed |
@@ -330,6 +332,56 @@ refusal. It now retries `InProgress` at the base interval and reserves the expon
which is what the phone actually sends when it declines. That does not fix the stuck state, but it stops the daemon from
sleeping through the recovery.
+### 2026-08-19 - `Bearer.LE1.Connected` is false on a working ANCS link
+
+| | |
+|---|---|
+| Controller | MediaTek MT7925 (RZ717) Wi-Fi 7 |
+| BlueZ | 5.87, running with `--experimental` |
+| Phone | iPhone 15 Pro |
+
+Captured with notification mirroring demonstrably live -- `ancs: Notification
+mirroring is active`, the full GATT tree enumerated under the device including
+all three ANCS characteristics, notifications arriving:
+
+- `org.bluez.Bearer.LE1.Connected` read **false** throughout, while
+ `Paired` and `Bonded` on the same interface read true.
+- The link was opened by the phone, inbound, in answer to the solicitation
+ advert. BlueZ appears not to credit the LE bearer for a connection it did not
+ initiate. An outbound `Bearer.LE1.Connect()` sets it true as expected.
+
+So `Bearer.LE1.Connected` is evidence that LE is up, not evidence that it is
+down. Trusting it alone reported "notifications are unavailable" over a session
+that was delivering them, and kept the supervisor dialling a link that was
+already open.
+
+The ANCS characteristics in the object tree are the better signal, and are what
+Tether now reads (`Device::le_link_up()`). GATT exists only over LE, and BlueZ
+withdraws those objects when the link drops -- confirmed on this hardware, where
+an LE-down device shows only `avrcp` and `sep1-6` under its path and no
+`service*` objects at all. Anything that tears the bearer down now refuses to do
+so while that tree is present.
+
+### 2026-08-19 - The solicitation advert was a one-shot
+
+Same hardware. `LEAdvertisingManager1.ActiveInstances` sat at `0` on a machine
+whose LE link had been down for hours, with BR/EDR, MAP and PBAP up throughout.
+
+The advert carries `Timeout = 180`, BlueZ retires it and calls `Release`, and
+nothing re-registered it: the only callers were `pair_device()` and
+`--bt-solicit`. Since iOS reveals the notification permission, and dials the LE
+link, only while it is broadcasting, a bond went permanently quiet three minutes
+after pairing unless a human kept running `--bt-solicit`.
+
+It is now driven from the connection loop: on air whenever BR/EDR is up, ANCS is
+enabled and LE is down, re-armed each time BlueZ retires it, and unregistered as
+soon as LE connects so the advertising instance is freed. A pairing transaction
+still owns it outright while it runs.
+
+Measured on the machine above, which had been in the broken state all day: the
+daemon brought LE up 12 seconds after starting, with no manual step, and reported
+`Notification mirroring is active`.
+
### PBAP
`Select("int", "pb")` followed by `PullAll` with `Format: vcard30` and `MaxCount` returned 456 contacts on the first attempt.
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 29b9944..b90b01f 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -199,6 +199,13 @@ static int print_bt_status(tether::Client& client) {
cap.value("le_peripheral", false) ? "yes" : "no",
cap.value("advertising", false) ? "yes" : "no",
cap.value("class_ok", false) ? "ok" : "wrong");
+ fprintf(stdout,
+ " secure-connections=%s\n",
+ cap.contains("secure_connections") && cap["secure_connections"].is_boolean()
+ ? (cap["secure_connections"].get<bool>() ? "on" : "OFF")
+ : "unknown");
+ if (cap.value("bonded_device_present", false))
+ fprintf(stdout, "Bond: %s\n", cap.value("bond_has_le", false) ? "BR/EDR + LE" : "BR/EDR only");
for (const auto& adapter : resp["adapters"]) {
fprintf(stdout, " %s %s\n", adapter.value("address", "").c_str(), adapter.value("name", "").c_str());
diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hpp
index d21fb99..3d2372e 100644
--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp
+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp
@@ -9,7 +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;
- // How many refused BR/EDR attempts before the status stops saying "connecting"
+ // 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;
@@ -43,6 +43,8 @@ namespace tether::bluetooth {
// Must not block: BlueZ keeps working on a connect after a synchronous
// call gives up, and every later attempt then collides with it.
virtual ConnectResult connect_le(std::string& err) = 0;
+ // Drops the LE transport alone
+ virtual ConnectResult disconnect_le(std::string& err) = 0;
};
struct BearerStatus {
diff --git a/src/core/include/tether/bluetooth/objects.hpp b/src/core/include/tether/bluetooth/objects.hpp
index ab31da4..f723453 100644
--- a/src/core/include/tether/bluetooth/objects.hpp
+++ b/src/core/include/tether/bluetooth/objects.hpp
@@ -48,6 +48,8 @@ namespace tether::bluetooth {
bool connected = false;
std::vector<std::string> uuids;
+ bool has_ancs_gatt = false;
+
bool has_le_bearer = false;
bool le_paired = false;
bool le_bonded = false;
@@ -60,6 +62,7 @@ namespace tether::bluetooth {
bool classic_state_known = false;
bool classic_link_up() const { return classic_state_known ? classic_connected : connected; }
+ bool le_link_up() const { return le_connected || has_ancs_gatt; }
bool has_uuid(const std::string& uuid) const;
bool supports_map() const { return has_uuid(UUID_MAP_MAS); }
@@ -106,6 +109,10 @@ namespace tether::bluetooth {
bool le_peripheral = false;
bool advertising = false;
bool class_ok = false;
+ bool bonded_device_present = false;
+ bool bond_has_le = false;
+ bool secure_connections = false;
+ bool secure_connections_known = false;
// Adapter the steps below apply to, e.g. "hci0". The class unit is templated on it.
std::string adapter_id;
// Human-readable explanations for anything short of full mode, shown verbatim
diff --git a/src/core/include/tether/bluetooth/pairing.hpp b/src/core/include/tether/bluetooth/pairing.hpp
index 14723c0..65da248 100644
--- a/src/core/include/tether/bluetooth/pairing.hpp
+++ b/src/core/include/tether/bluetooth/pairing.hpp
@@ -53,6 +53,15 @@ namespace tether::bluetooth {
// there has to be a way back to it short of removing the bond.
bool solicit_ancs(BluezMonitor& monitor, std::string& err);
+ // Whether that advertisement is on air right now
+ bool ancs_solicitation_active();
+
+ // Takes it off air, freeing the LE advertising instance
+ void stop_ancs_solicitation(BluezMonitor& monitor);
+
+ // Holds the solicitation on air for exactly as long as `want`
+ void supervise_ancs_solicitation(BluezMonitor& monitor, bool want);
+
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/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cpp
index b8c9204..3cb0e32 100644
--- a/src/core/src/bluetooth/bearer_supervisor.cpp
+++ b/src/core/src/bluetooth/bearer_supervisor.cpp
@@ -93,6 +93,8 @@ namespace tether::bluetooth {
if (status_.le_connected) {
le_attempts_ = 0;
le_stuck_locally_ = false;
+ status_.le_backoff = 0;
+ next_le_attempt_ = 0;
}
if (status_.classic_connected) {
@@ -158,11 +160,17 @@ namespace tether::bluetooth {
if (!status_.le_connected) {
const bool settled =
classic_connected_since_ >= 0 && now - classic_connected_since_ >= BEARER_SETTLE_SECONDS;
- // Dialling LE from this side only works if the phone is willing to be
- // dialled. When it is not, every attempt either times out or collides
- // with the previous one still running inside bluez, stop after
- // LE_ATTEMPTS_BEFORE_ADVICE and leave it to the phone.
- if (settled && le_attempts_ < LE_ATTEMPTS_BEFORE_ADVICE && now >= next_le_attempt_) {
+
+ if (settled && now >= next_le_attempt_) {
+ // connect that keeps colliding is bluez still holding one that never finished
+ if (le_stuck_locally_ && le_attempts_ >= LE_ATTEMPTS_BEFORE_ADVICE) {
+ std::string drop_err;
+ if (ops_.disconnect_le(drop_err) == ConnectResult::Failed)
+ debug::log(WARN, "bluetooth: LE bearer disconnect failed ({})", drop_err);
+ else
+ debug::log(INFO, "bluetooth: dropped a stuck LE bearer before retrying");
+ }
+
// Select LE only for this attempt, then hand the preference back
// so LE is never left preferred while idle.
ops_.set_preferred_bearer("le");
@@ -206,16 +214,14 @@ namespace tether::bluetooth {
// local remedy first and the phone second rather than
// sending the user to settings that may be fine already.
status_.reason = "Nothing is bringing up the LE link that carries notifications. BlueZ is "
- "holding a connect that never completed: run \"sudo systemctl restart "
- "bluetooth\" -- disconnecting the iPhone does not clear it. If it still "
- "will not come up, run \"tether --bt-solicit\" (or press Show iPhone "
- "Permissions) and check Settings > Bluetooth > (i) on the iPhone. Messages "
- "and contacts are unaffected.";
+ "holding a connect that never completed; Tether keeps dropping and "
+ "redialling the LE bearer. If it still will not come up, run \"sudo "
+ "systemctl restart bluetooth\" -- disconnecting the iPhone does not clear "
+ "it. Messages and contacts are unaffected.";
else
- status_.reason = "The iPhone is not opening the LE link that carries notifications. "
- "Run \"tether --bt-solicit\" (or press Show iPhone Permissions) to ask it "
- "to, then check Settings > Bluetooth > (i) on the iPhone. Messages and "
- "contacts are unaffected.";
+ status_.reason = "The iPhone is not opening the LE link that carries notifications. Tether "
+ "keeps asking; open Settings > Bluetooth > (i) on the iPhone and turn on "
+ "Share System Notifications. Messages and contacts are unaffected.";
return !(status_ == previous);
}
}
diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cpp
index 7df25b6..50be0b0 100644
--- a/src/core/src/bluetooth/connection.cpp
+++ b/src/core/src/bluetooth/connection.cpp
@@ -6,6 +6,7 @@
#include "tether/bluetooth/journal.hpp"
#include "tether/bluetooth/map_session.hpp"
#include "tether/bluetooth/monitor.hpp"
+#include "tether/bluetooth/pairing.hpp"
#include "tether/bluetooth/pbap_session.hpp"
#include "tether/log.hpp"
@@ -220,6 +221,7 @@ namespace tether::bluetooth {
// asynchronously and left to run to completion rather than abandoned, so
// this is generous on purpose.
constexpr int LE_CONNECT_TIMEOUT_MS = 45000;
+ constexpr int DISCONNECT_TIMEOUT_MS = 10000;
constexpr int MESSAGE_POLL_SECONDS = 15;
// obexd can drop a MAP session while the Classic link stays up, and the
@@ -266,7 +268,7 @@ namespace tether::bluetooth {
bool le_connected() const override {
auto device = lookup();
- return device && device->le_connected;
+ return device && device->le_link_up();
}
void set_preferred_bearer(const std::string& bearer) override {
@@ -362,6 +364,36 @@ namespace tether::bluetooth {
return ConnectResult::Requested;
}
+ // Drops the LE transport so a wedged connect can be retried.
+ ConnectResult disconnect_le(std::string& err) override {
+ auto device = lookup();
+ if (!device) {
+ err = "device not present";
+ return ConnectResult::Failed;
+ }
+ if (!device->has_le_bearer) {
+ err = "no LE bearer";
+ return ConnectResult::Failed;
+ }
+ // bluez can report the bearer disconnected while gatt is live and ancs is delivering over it.
+ if (device->has_ancs_gatt) {
+ err = "ANCS is live on this link";
+ return ConnectResult::Failed;
+ }
+ if (!call(device->path, IFACE_BEARER_LE, "Disconnect", err, DISCONNECT_TIMEOUT_MS)) {
+ if (err.find("NotConnected") == std::string::npos)
+ return ConnectResult::Failed;
+ err.clear();
+ }
+
+ // A dropped bearer cannot still be the subject of our own outstanding connect
+ {
+ std::lock_guard<std::mutex> lock(le_->mutex);
+ le_->pending = false;
+ }
+ return ConnectResult::Requested;
+ }
+
private:
// Outlives the ops object: a reply can land after the supervised
// device is torn down and replaced.
@@ -886,6 +918,10 @@ namespace tether::bluetooth {
profiles->tick(now, link_ready);
+ const auto& bearer = bearers->status();
+ supervise_ancs_solicitation(
+ *monitor, ancs_enabled && bearer.classic_connected && bearer.le_available && !bearer.le_connected);
+
// publish() drops a payload identical to the last one, so refreshing
// every tick costs nothing and cannot miss a transition.
refresh_status();
diff --git a/src/core/src/bluetooth/diagnostics.cpp b/src/core/src/bluetooth/diagnostics.cpp
index eebccb2..df5be72 100644
--- a/src/core/src/bluetooth/diagnostics.cpp
+++ b/src/core/src/bluetooth/diagnostics.cpp
@@ -1,6 +1,7 @@
#include "tether/bluetooth/diagnostics.hpp"
#include "tether/bluetooth/config.hpp"
+#include "tether/bluetooth/pairing.hpp"
#include "tether/version.hpp"
#include <algorithm>
@@ -190,6 +191,7 @@ namespace tether::bluetooth {
report["ancs_enabled"] = config.ancs_enabled;
report["ancs_content_enabled"] = config.ancs_content_enabled;
report["group_messages_enabled"] = config.group_messages_enabled;
+ report["ancs_soliciting"] = ancs_solicitation_active();
report["status"] = redactor.value(status);
report["connection"] = redactor.value(connection);
report["timeline"] = redactor.value(diagnostic_timeline());
diff --git a/src/core/src/bluetooth/objects.cpp b/src/core/src/bluetooth/objects.cpp
index 5e4548d..805429b 100644
--- a/src/core/src/bluetooth/objects.cpp
+++ b/src/core/src/bluetooth/objects.cpp
@@ -1,6 +1,7 @@
#include "tether/bluetooth/objects.hpp"
#include <algorithm>
+#include <cstdio>
#include <cstring>
#include <filesystem>
@@ -13,6 +14,8 @@ namespace tether::bluetooth {
constexpr const char* IFACE_LE_ADV_MGR = "org.bluez.LEAdvertisingManager1";
constexpr const char* IFACE_BEARER_LE = "org.bluez.Bearer.LE1";
constexpr const char* IFACE_BEARER_BREDR = "org.bluez.Bearer.BREDR1";
+ constexpr const char* IFACE_CHARACTERISTIC = "org.bluez.GattCharacteristic1";
+ constexpr const char* UUID_ANCS_NOTIFICATION_SOURCE = "9fbf120d-6301-42d9-8c58-25e699a21dbd";
bool iequals(const std::string& a, const std::string& b) {
return a.size() == b.size() &&
@@ -234,13 +237,30 @@ namespace tether::bluetooth {
GVariantIter iter;
const gchar* path = nullptr;
GVariant* ifaces = nullptr;
+ std::vector<std::string> ancs_char_paths;
g_variant_iter_init(&iter, dict);
while (g_variant_iter_loop(&iter, "{&o@a{sa{sv}}}", &path, &ifaces)) {
read_adapter(path, ifaces, out);
read_device(path, ifaces, out);
+
+ GVariant* chr = g_variant_lookup_value(ifaces, IFACE_CHARACTERISTIC, G_VARIANT_TYPE("a{sv}"));
+ if (!chr)
+ continue;
+ if (iequals(get_string(chr, "UUID"), UUID_ANCS_NOTIFICATION_SOURCE))
+ ancs_char_paths.emplace_back(path);
+ g_variant_unref(chr);
}
g_variant_unref(dict);
+ // A characteristic lives under its device's path. BlueZ enumerates in an
+ // unspecified order, so this cannot be done in the loop above.
+ for (const auto& char_path : ancs_char_paths) {
+ for (auto& device : out.devices) {
+ if (char_path.rfind(device.path + "/", 0) == 0)
+ device.has_ancs_gatt = true;
+ }
+ }
+
// BlueZ enumerates in a stable but unspecified order; sorting keeps
// snapshot comparison and UI listing deterministic.
std::sort(out.adapters.begin(), out.adapters.end(), [](const Adapter& a, const Adapter& b) {
@@ -263,6 +283,35 @@ namespace tether::bluetooth {
return "/usr/lib/bluetooth/bluetoothd";
}
+ // Reads the controller's current mgmt settings. BlueZ exposes Secure
+ // Connections nowhere on D-Bus, and it is the precondition for the
+ // cross-transport key derivation that gives a BR/EDR bond its LE half.
+ // without it the bond is Classic-only and ANCS is unreachable, which is
+ // otherwise indistinguishable from a dozen other failures.
+ //
+ // TODO: shelling out to btmgmt, which reads the mgmt socket
+ // unprivileged. Only worth opening an AF_BLUETOOTH mgmt socket here if
+ // this ever needs to run somewhere btmgmt is not installed.
+ bool read_secure_connections(const std::string& adapter_id, bool& enabled) {
+ const std::string cmd = "btmgmt --index " + adapter_id + " info 2>/dev/null";
+ FILE* pipe = popen(cmd.c_str(), "r");
+ if (!pipe)
+ return false;
+
+ bool found = false;
+ char line[1024];
+ while (std::fgets(line, sizeof(line), pipe)) {
+ const std::string text(line);
+ if (text.find("current settings:") == std::string::npos)
+ continue;
+ enabled = text.find("secure-conn") != std::string::npos;
+ found = true;
+ break;
+ }
+ pclose(pipe);
+ return found;
+ }
+
// The package ships the drop-in for the user to copy.
std::string enable_experimental_command() {
const std::string shipped = std::string(TETHER_DATADIR) + "/bluetooth-experimental.conf";
@@ -317,10 +366,18 @@ namespace tether::bluetooth {
for (const auto& d : objects.devices) {
if (d.has_le_bearer)
cap.bearer_api = BearerApi::Confirmed;
+
+ if ((d.bonded || d.paired) && d.looks_like_iphone()) {
+ cap.bonded_device_present = true;
+ if (d.has_le_bearer)
+ cap.bond_has_le = true;
+ }
}
if (cap.bearer_api != BearerApi::Confirmed)
cap.bearer_api = objects.experimental_api ? BearerApi::Unknown : BearerApi::Absent;
+ cap.secure_connections_known = read_secure_connections(cap.adapter_id, cap.secure_connections);
+
if (!cap.powered) {
cap.reasons.emplace_back("Bluetooth adapter is powered off.");
cap.mode = DeliveryMode::Blocked;
@@ -350,9 +407,20 @@ namespace tether::bluetooth {
"pairing: a bond made without it has no LE half.",
enable_experimental_command()});
cap.mode = DeliveryMode::Compatibility;
- } else if (cap.bearer_api == BearerApi::Unknown) {
+ } else if (cap.bearer_api == BearerApi::Unknown && !cap.bonded_device_present) {
+ // only an iphone bond can confirm the api
cap.reasons.emplace_back("Bearer API support is unconfirmed until a device is bonded.");
}
+
+ if (cap.bonded_device_present && !cap.bond_has_le) {
+ std::string reason = "A device is bonded, but the bond covers BR/EDR only -- no LE keys were derived, "
+ "so notification mirroring cannot work on it. Delete this computer on the iPhone "
+ "(Forget This Device) and pair again.";
+ if (cap.secure_connections_known && !cap.secure_connections)
+ reason += " Secure Connections is off on this controller, which is what blocks the derivation; "
+ "re-pairing will not help until it is on.";
+ cap.reasons.emplace_back(std::move(reason));
+ }
if (!cap.class_ok) {
cap.setup.push_back({"The iPhone will not offer its Messages and Contacts permissions until this "
"adapter presents itself as A/V Hands-Free (major 4, minor 8).",
@@ -392,6 +460,7 @@ namespace tether::bluetooth {
{"map", d.supports_map()},
{"pbap", d.supports_pbap()},
{"ancs", d.supports_ancs()},
+ {"ancs_gatt", d.has_ancs_gatt},
{"iphone", d.looks_like_iphone()},
};
}
@@ -417,6 +486,10 @@ namespace tether::bluetooth {
{"le_peripheral", c.le_peripheral},
{"advertising", c.advertising},
{"class_ok", c.class_ok},
+ {"bonded_device_present", c.bonded_device_present},
+ {"bond_has_le", c.bond_has_le},
+ {"secure_connections",
+ c.secure_connections_known ? nlohmann::json(c.secure_connections) : nlohmann::json(nullptr)},
{"adapter_id", c.adapter_id},
{"reasons", c.reasons},
{"setup", setup},
diff --git a/src/core/src/bluetooth/pairing.cpp b/src/core/src/bluetooth/pairing.cpp
index 3277bd1..3184782 100644
--- a/src/core/src/bluetooth/pairing.cpp
+++ b/src/core/src/bluetooth/pairing.cpp
@@ -4,8 +4,10 @@
#include "tether/bluetooth/monitor.hpp"
#include "tether/log.hpp"
+#include <atomic>
#include <chrono>
#include <filesystem>
+#include <mutex>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
@@ -26,6 +28,9 @@ namespace tether::bluetooth {
constexpr int CLASSIC_SETTLE_SECONDS = 3;
constexpr int DISCOVERY_TIMEOUT_SECONDS = 30;
+ // how long to stand back after bluez refuses to put the solicitation on air
+ constexpr int SOLICIT_RETRY_SECONDS = 30;
+
std::string normalize_address(std::string address) {
for (char& c : address)
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
@@ -262,12 +267,20 @@ namespace tether::bluetooth {
return objects.adapters.empty() ? std::string{} : objects.adapters.front().path;
}
- // The solicitation advertise outlives the transaction that started it, so it
- // is owned here rather than on a stack frame.
+ std::mutex g_advert_mutex;
AncsAdvertisement* g_advert = nullptr;
+ std::atomic<bool> g_pairing_owns_advert{false};
+
+ struct AdvertOwnership {
+ AdvertOwnership() { g_pairing_owns_advert = true; }
+ ~AdvertOwnership() { g_pairing_owns_advert = false; }
+ AdvertOwnership(const AdvertOwnership&) = delete;
+ AdvertOwnership& operator=(const AdvertOwnership&) = delete;
+ };
+
// An advert soliciting ANCS must never be on air while Classic pairing is in flight
- void stop_advert(BluezMonitor& monitor) {
+ void stop_advert_locked(BluezMonitor& monitor) {
if (!g_advert)
return;
g_advert->unregister_with_bluez();
@@ -276,13 +289,19 @@ namespace tether::bluetooth {
g_advert = nullptr;
}
+ void stop_advert(BluezMonitor& monitor) {
+ std::lock_guard<std::mutex> lock(g_advert_mutex);
+ stop_advert_locked(monitor);
+ }
+
// 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);
+ std::lock_guard<std::mutex> lock(g_advert_mutex);
+ stop_advert_locked(monitor);
auto* advert = new AncsAdvertisement(monitor.connection(), adapter_path);
bool exported = false;
@@ -348,6 +367,38 @@ namespace tether::bluetooth {
return start_advert(monitor, adapter, err);
}
+ bool ancs_solicitation_active() {
+ std::lock_guard<std::mutex> lock(g_advert_mutex);
+ return g_advert && g_advert->active();
+ }
+
+ void stop_ancs_solicitation(BluezMonitor& monitor) { stop_advert(monitor); }
+
+ void supervise_ancs_solicitation(BluezMonitor& monitor, bool want) {
+ if (g_pairing_owns_advert)
+ return;
+ if (!want) {
+ if (ancs_solicitation_active())
+ stop_advert(monitor);
+ return;
+ }
+ if (ancs_solicitation_active())
+ return;
+
+ static std::chrono::steady_clock::time_point next_attempt{};
+ const auto now = std::chrono::steady_clock::now();
+ if (now < next_attempt)
+ return;
+
+ std::string err;
+ if (solicit_ancs(monitor, err)) {
+ next_attempt = {};
+ return;
+ }
+ next_attempt = now + std::chrono::seconds(SOLICIT_RETRY_SECONDS);
+ debug::log(WARN, "bluetooth: could not re-arm the ANCS solicitation ({})", 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;
@@ -430,6 +481,7 @@ namespace tether::bluetooth {
return result;
}
+ AdvertOwnership advert_owned;
PairableWindow pairable(conn, [&] {
auto objects = monitor.snapshot();
return objects.adapters.empty() ? std::string{} : objects.adapters.front().path;
diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cpp
index b0a14ab..57730db 100644
--- a/test/test_bluetooth_objects.cpp
+++ b/test/test_bluetooth_objects.cpp
@@ -245,6 +245,126 @@ TEST(Capability, ClassicOnlyBondDoesNotDisproveBearerApi) {
EXPECT_EQ(cap.mode, DeliveryMode::Full);
}
+// A bonded iPhone whose Device1 carries no LE bearer is a bond that was made
+// without cross-transport key derivation: it can never carry ANCS, and no amount
+// of re-soliciting or restarting bluetoothd changes that. Reporting it as
+// "unconfirmed until a device is bonded" -- to someone looking at a bonded device
+// -- was a dead end in every bug report it produced.
+TEST(Capability, ClassicOnlyIphoneBondIsNamedAsSuch) {
+ Payload p(join(ADAPTER_FULL, R"({
+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
+ 'org.bluez.Device1': {
+ 'Paired': <true>,
+ 'Bonded': <true>,
+ 'UUIDs': <['00001132-0000-1000-8000-00805f9b34fb', '0000112f-0000-1000-8000-00805f9b34fb']>
+ }
+ }
+ })")
+ .c_str());
+ auto objects = parse_managed_objects(p.v);
+ objects.experimental_api = true;
+ auto cap = resolve_capability(objects);
+
+ EXPECT_TRUE(cap.bonded_device_present);
+ EXPECT_FALSE(cap.bond_has_le);
+
+ bool named = false;
+ for (const auto& reason : cap.reasons) {
+ if (reason.find("BR/EDR only") != std::string::npos) {
+ named = true;
+ EXPECT_NE(reason.find("Forget This Device"), std::string::npos) << "names no remedy";
+ }
+ EXPECT_EQ(reason.find("unconfirmed until a device is bonded"), std::string::npos)
+ << "still claims nothing is bonded";
+ }
+ EXPECT_TRUE(named) << "a bond with no LE half went unreported";
+
+ // The controller can still do ANCS; it is this bond that cannot. Downgrading
+ // the mode would be a claim about the hardware.
+ EXPECT_EQ(cap.mode, DeliveryMode::Full);
+}
+
+// Headsets and controllers bond over BR/EDR alone by design. Reading one of
+// those as a broken bond fires on nearly every machine.
+TEST(Capability, ClassicOnlyBondOnANonPhoneIsNotReported) {
+ Payload p(join(ADAPTER_FULL, R"({
+ '/org/bluez/hci0/dev_F8_D3_F0_3C_84_4A': {
+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Alias': <'ZBZ AirPros'> }
+ }
+ })")
+ .c_str());
+ auto objects = parse_managed_objects(p.v);
+ objects.experimental_api = true;
+ auto cap = resolve_capability(objects);
+
+ EXPECT_FALSE(cap.bonded_device_present);
+ for (const auto& reason : cap.reasons)
+ EXPECT_EQ(reason.find("BR/EDR only"), std::string::npos) << "blamed a headset for having no LE bond";
+}
+
+// Observed on a MediaTek MT7925 with the phone's ANCS session live and
+// delivering: Bearer.LE1.Connected read false the whole time, because the phone
+// opened the link inbound in answer to the solicitation advert. GATT exists only
+// over LE and BlueZ withdraws these objects when the link drops, so their
+// presence is the more trustworthy signal of the two.
+TEST(DeviceParsing, AncsCharacteristicsProveTheLeLinkIsUp) {
+ Payload p(join(ADAPTER_FULL, R"({
+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <true> },
+ 'org.bluez.Bearer.LE1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <false> }
+ },
+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7/service004f/char0050': {
+ 'org.bluez.GattCharacteristic1': { 'UUID': <'9FBF120D-6301-42D9-8C58-25E699A21DBD'> }
+ }
+ })")
+ .c_str());
+ auto objects = parse_managed_objects(p.v);
+
+ ASSERT_EQ(objects.devices.size(), 1u);
+ EXPECT_FALSE(objects.devices[0].le_connected) << "the fixture is not reproducing the disagreement";
+ EXPECT_TRUE(objects.devices[0].has_ancs_gatt);
+ EXPECT_TRUE(objects.devices[0].le_link_up()) << "a live ANCS session was reported as no LE link";
+}
+
+// The characteristic has to belong to this device. A sibling device's GATT tree
+// saying nothing about ours is the whole reason the paths are matched.
+TEST(DeviceParsing, AncsCharacteristicsBelongToOneDeviceOnly) {
+ Payload p(join(ADAPTER_FULL, R"({
+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }
+ },
+ '/org/bluez/hci0/dev_F8_D3_F0_3C_84_4A': {
+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }
+ },
+ '/org/bluez/hci0/dev_F8_D3_F0_3C_84_4A/service004f/char0050': {
+ 'org.bluez.GattCharacteristic1': { 'UUID': <'9fbf120d-6301-42d9-8c58-25e699a21dbd'> }
+ }
+ })")
+ .c_str());
+ auto objects = parse_managed_objects(p.v);
+
+ ASSERT_EQ(objects.devices.size(), 2u);
+ EXPECT_FALSE(objects.devices[0].has_ancs_gatt) << "borrowed a sibling device's GATT tree";
+ EXPECT_TRUE(objects.devices[1].has_ancs_gatt);
+}
+
+// An LE link that is down has no GATT tree, which is what makes its presence
+// mean anything.
+TEST(DeviceParsing, NoGattTreeMeansNoLeLink) {
+ Payload p(join(ADAPTER_FULL, R"({
+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {
+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <true> },
+ 'org.bluez.Bearer.LE1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <false> }
+ }
+ })")
+ .c_str());
+ auto objects = parse_managed_objects(p.v);
+
+ ASSERT_EQ(objects.devices.size(), 1u);
+ EXPECT_FALSE(objects.devices[0].has_ancs_gatt);
+ EXPECT_FALSE(objects.devices[0].le_link_up());
+}
+
TEST(Capability, BearerUnknownWithoutAnyBondStaysFull) {
Payload p(ADAPTER_FULL);
auto objects = parse_managed_objects(p.v);
diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cpp
index b573b25..3bc2e18 100644
--- a/test/test_bluetooth_supervisor.cpp
+++ b/test/test_bluetooth_supervisor.cpp
@@ -53,6 +53,19 @@ namespace {
le = true;
return ConnectResult::Requested;
}
+
+ int le_disconnects = 0;
+ bool disconnect_le_succeeds = true;
+
+ ConnectResult disconnect_le(std::string& err) override {
+ ++le_disconnects;
+ if (!disconnect_le_succeeds) {
+ err = "no LE bearer";
+ return ConnectResult::Failed;
+ }
+ le = false;
+ return ConnectResult::Requested;
+ }
};
class FakeProfiles : public ProfileOps {
@@ -658,11 +671,12 @@ TEST(BearerSupervisor, RepeatedRefusalNamesTheRemedy) {
EXPECT_TRUE(sup.status().classic_connected);
}
-// BlueZ cannot always dial LE: the per-bearer Connect is gone while the
-// transport is down, and Device1.Connect quietly no-ops once BR/EDR is up, so
-// the attempt "succeeds" without a link. Saying "bringing it up" forever hides
-// that only the phone can open it.
-TEST(BearerSupervisor, GivesUpDiallingLeInsteadOfSpinningForever) {
+// BR/EDR can stay up for days, so the LE half is the only one that ever needs
+// re-dialling, and nothing else in the daemon dials it. Standing down for good
+// after a run of failures left notification mirroring dead until a restart even
+// though the phone had long since become willing. The backoff ceiling, not a
+// attempt cap, is what keeps this from being a storm.
+TEST(BearerSupervisor, KeepsDiallingLeAtTheCappedCadence) {
// A phone that will not accept an inbound LE connect: BlueZ keeps working
// after our call gives up, so the next attempts collide with it.
class RefusingBearer : public FakeBearer {
@@ -684,16 +698,124 @@ TEST(BearerSupervisor, GivesUpDiallingLeInsteadOfSpinningForever) {
sup.tick(now);
}
- EXPECT_EQ(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "LE was dialled forever against a phone refusing it";
+ EXPECT_GT(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "LE was abandoned for the daemon's whole lifetime";
EXPECT_NE(sup.status().reason.find("LE link that carries notifications"), std::string::npos);
- // A reconnect is a new session and has to try again.
- sup.reset();
+ // ...but no faster than the ceiling. Every tick above is a full backoff
+ // window apart, so one attempt per window is the most that may happen.
+ EXPECT_LE(refusing.le_attempts, 202) << "the backoff ceiling is not pacing the retries";
+
+ // And it recovers the moment the phone becomes willing, with no reset() and
+ // no restart.
+ refusing.le = true;
now += BEARER_BACKOFF_MAX_SECONDS;
sup.tick(now);
+ EXPECT_TRUE(sup.status().le_connected);
+}
+
+// An LE link that needed a few tries, then held, must not resume at the backoff
+// those tries grew to. Inheriting it means the first drop after a healthy day
+// costs five minutes of dead notification mirroring.
+TEST(BearerSupervisor, ASuccessfulLeLinkClearsTheBackoffItGrew) {
+ FakeBearer ops;
+ ops.le_succeeds = false;
+ BearerSupervisor sup(ops, true);
+
+ // Classic is observed connected on the tick after it is dialed, and the
+ // settle window runs from there.
+ sup.tick(0);
+ sup.tick(1);
+ int64_t now = 1 + BEARER_SETTLE_SECONDS;
+ for (int i = 0; i < 4; ++i) {
+ sup.tick(now);
+ now += sup.status().le_backoff;
+ }
+ ASSERT_GT(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);
+
+ // The phone accepts, and the link holds.
+ ops.le_succeeds = true;
+ ops.le = true;
+ sup.tick(now);
+ ASSERT_TRUE(sup.status().le_connected);
+ EXPECT_EQ(sup.status().le_backoff, 0) << "carried the old backoff into a healthy link";
+
+ // It drops much later. The retry is prompt, not held over from before.
+ ops.le = false;
+ ops.le_succeeds = false;
+ now += 100000;
+ const int attempts = ops.le_attempts;
+ sup.tick(now);
+ 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);
+}
+
+// A connect that keeps colliding is BlueZ holding one that never finished.
+// Waiting does not clear it; dropping the bearer does. Without this the only
+// documented remedy was restarting bluetoothd.
+TEST(BearerSupervisor, DropsAStuckLeBearerBeforeRedialling) {
+ class StuckBearer : public FakeBearer {
+ public:
+ ConnectResult connect_le(std::string& err) override {
+ ++le_attempts;
+ err = "GDBus.Error:org.bluez.Error.InProgress: In Progress";
+ return ConnectResult::Busy;
+ }
+ } stuck;
+
+ BearerSupervisor sup(stuck, true);
+ int64_t now = 0;
+ sup.tick(now);
now += BEARER_SETTLE_SECONDS + 1;
+
+ // Nothing is dropped while the run is still short enough to be ordinary.
+ while (stuck.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {
+ sup.tick(now);
+ now += BEARER_BACKOFF_MAX_SECONDS;
+ }
+ EXPECT_EQ(stuck.le_disconnects, 0) << "dropped the bearer before the collisions meant anything";
+
sup.tick(now);
- EXPECT_GT(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "reset must re-arm LE for the next session";
+ EXPECT_EQ(stuck.le_disconnects, 1) << "a wedged bearer was never dropped";
+
+ // One per backoff window at most, not one per tick.
+ sup.tick(now + 1);
+ EXPECT_EQ(stuck.le_disconnects, 1) << "dropped the bearer again inside its own backoff";
+}
+
+// A refusal from the phone is not a collision, and tearing the transport down
+// over one would interrupt a link that is merely unwelcome, not stuck.
+TEST(BearerSupervisor, DoesNotDropTheBearerOverAPlainRefusal) {
+ FakeBearer ops;
+ ops.le_succeeds = false;
+ ops.le_error = "org.bluez.Error.Failed: le-connection-abort-by-local";
+ BearerSupervisor sup(ops, true);
+
+ int64_t now = 0;
+ sup.tick(now);
+ now += BEARER_SETTLE_SECONDS + 1;
+ for (int i = 0; i < LE_ATTEMPTS_BEFORE_ADVICE * 3; ++i) {
+ sup.tick(now);
+ now += BEARER_BACKOFF_MAX_SECONDS;
+ }
+
+ EXPECT_GT(ops.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE);
+ EXPECT_EQ(ops.le_disconnects, 0) << "a refusal is the phone's answer, not a wedged bearer";
+}
+
+// A link that is up must never be torn down by the recovery path.
+TEST(BearerSupervisor, NeverDropsAConnectedLeBearer) {
+ FakeBearer ops;
+ BearerSupervisor sup(ops, true);
+
+ sup.tick(0);
+ sup.tick(1);
+ sup.tick(1 + BEARER_SETTLE_SECONDS);
+ sup.tick(2 + BEARER_SETTLE_SECONDS);
+ ASSERT_TRUE(sup.status().le_connected);
+
+ for (int i = 0; i < 50; ++i)
+ sup.tick(10 + BEARER_BACKOFF_MAX_SECONDS * i);
+ EXPECT_EQ(ops.le_disconnects, 0);
}
// A wedged bluetoothd and a phone that declines both end in a dead LE link, but