Linux + iPhone Continuity / iMessage / SMS
fix: bad state LE vs classic
Zack Bartelb6416a9917d3
diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hppindex d379c0f..3195d41 100644--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp@@ -9,6 +9,9 @@ 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"+ inline constexpr int CLASSIC_FAILURES_BEFORE_ADVICE = 6;+ inline constexpr int LE_ATTEMPTS_BEFORE_ADVICE = 6;// The BlueZ operations the supervisor performs.class BearerOps {@@ -63,6 +66,8 @@ namespace tether::bluetooth {bool ancs_enabled_ = true;BearerStatus status_;+ int classic_failures_ = 0;+ int le_attempts_ = 0;int64_t classic_connected_since_ = -1;int64_t next_classic_attempt_ = 0;int64_t next_le_attempt_ = 0;diff --git a/src/core/include/tether/bluetooth/objects.hpp b/src/core/include/tether/bluetooth/objects.hppindex 7d34149..b1acf7e 100644--- a/src/core/include/tether/bluetooth/objects.hpp+++ b/src/core/include/tether/bluetooth/objects.hpp@@ -53,6 +53,14 @@ namespace tether::bluetooth {bool le_bonded = false;bool le_connected = false;+ bool has_classic_bearer = false;+ bool classic_paired = false;+ bool classic_bonded = false;+ bool classic_connected = false;+ bool classic_state_known = false;++ bool classic_link_up() const { return classic_state_known ? classic_connected : connected; }+bool has_uuid(const std::string& uuid) const;bool supports_map() const { return has_uuid(UUID_MAP_MAS); }bool supports_pbap() const { return has_uuid(UUID_PBAP_PSE); }diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cppindex b4eb5ab..316c8d8 100644--- a/src/core/src/bluetooth/bearer_supervisor.cpp+++ b/src/core/src/bluetooth/bearer_supervisor.cpp@@ -19,8 +19,8 @@ namespace tether::bluetooth {bool is_transient(const std::string& err) {static const char* const transient[] = {"org.bluez.Error.InProgress",+ "already in progress","org.bluez.Error.NotReady",- // BlueZ spells these as the tail of an Error.Failed message."page-timeout","page timeout","connection-abort",@@ -29,6 +29,7 @@ namespace tether::bluetooth {"Connection timed out","br-connection-canceled","le-connection-abort-by-local",+ "br-connection-refused",};for (const char* needle : transient) {if (err.find(needle) != std::string::npos)@@ -48,6 +49,8 @@ namespace tether::bluetooth {void BearerSupervisor::set_ancs_enabled(bool enabled) { ancs_enabled_ = enabled; }void BearerSupervisor::reset() {+ classic_failures_ = 0;+ le_attempts_ = 0;classic_connected_since_ = -1;next_classic_attempt_ = 0;next_le_attempt_ = 0;@@ -72,16 +75,21 @@ namespace tether::bluetooth {status_.classic_connected = ops_.classic_connected();status_.le_available = ops_.le_bearer_available();status_.le_connected = status_.le_available && ops_.le_connected();+ if (status_.le_connected)+ le_attempts_ = 0;if (status_.classic_connected) {if (classic_connected_since_ < 0)classic_connected_since_ = now;status_.classic_backoff = 0;+ classic_failures_ = 0;} else {- // A dropped link invalidates the settle window and any LE state that- // depended on it.+ // A dropped link invalidates the settle window, so no LE attempt is+ // made until BR/EDR is back and has settled. An LE link that is+ // already up is a separate matter and is reported as it is: ANCS+ // rides LE alone, so calling it down here would switch notification+ // mirroring off for a phone that is still delivering notifications.classic_connected_since_ = -1;- status_.le_connected = false;if (now >= next_classic_attempt_) {ops_.set_preferred_bearer("bredr");@@ -89,14 +97,24 @@ namespace tether::bluetooth {if (ops_.connect_classic(err)) {status_.classic_backoff = 0;next_classic_attempt_ = 0;+ classic_failures_ = 0;} else {+ ++classic_failures_;status_.classic_backoff = next_backoff(status_.classic_backoff, err);next_classic_attempt_ = now + status_.classic_backoff;debug::log(WARN, "bluetooth: BR/EDR connect failed ({}), retrying in {}s", err, status_.classic_backoff);}}- status_.reason = "Connecting to the iPhone over Bluetooth...";++ // An iPhone that keeps refusing while unlocked, with its Bluetooth+ // permissions already on, is wedged on its own side: nothing here+ // clears it, and saying "connecting" forever hides that.+ status_.reason = classic_failures_ >= CLASSIC_FAILURES_BEFORE_ADVICE+ ? "The iPhone keeps refusing the Bluetooth connection. Turn Bluetooth off and "+ "back on on the iPhone — that clears it even when the permissions are already "+ "on. Re-pairing is not the fix."+ : "Connecting to the iPhone over Bluetooth...";return !(status_ == previous);}@@ -121,10 +139,12 @@ namespace tether::bluetooth {std::string err;const bool ok = ops_.connect_le(err);ops_.set_preferred_bearer("bredr");+ ++le_attempts_;if (ok) {status_.le_backoff = 0;- next_le_attempt_ = 0;+ // connect can report success without the link coming up+ next_le_attempt_ = now + BEARER_BACKOFF_MIN_SECONDS;status_.le_connected = true;} else {status_.le_backoff = next_backoff(status_.le_backoff, err);@@ -133,7 +153,12 @@ namespace tether::bluetooth {}}if (!status_.le_connected) {- status_.reason = "Connected. Bringing up the LE link for notifications...";+ status_.reason = le_attempts_ >= LE_ATTEMPTS_BEFORE_ADVICE+ ? "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."+ : "Connected. Bringing up the LE link for notifications...";return !(status_ == previous);}}diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cppindex 2eb74bb..e78a3ea 100644--- a/src/core/src/bluetooth/connection.cpp+++ b/src/core/src/bluetooth/connection.cpp@@ -207,6 +207,7 @@ namespace tether::bluetooth {constexpr const char* BLUEZ_NAME = "org.bluez";constexpr const char* IFACE_DEVICE = "org.bluez.Device1";constexpr const char* IFACE_BEARER_LE = "org.bluez.Bearer.LE1";+ constexpr const char* IFACE_BEARER_BREDR = "org.bluez.Bearer.BREDR1";constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";constexpr const char* OBEX_NAME = "org.bluez.obex";@@ -220,6 +221,7 @@ namespace tether::bluetooth {// 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 SENT_EMPTY_LISTINGS_BEFORE_GIVING_UP = 3;constexpr int MESSAGE_LIST_MAX = 200;constexpr int SUPERVISOR_TICK_SECONDS = 1;@@ -250,7 +252,7 @@ namespace tether::bluetooth {bool classic_connected() const override {auto device = lookup();- return device && device->connected;+ return device && device->classic_link_up();}bool le_bearer_available() const override {@@ -292,6 +294,17 @@ namespace tether::bluetooth {err = "device not present";return false;}+ // bluez only exposes the per-bearer Connect while the device is connected on some bearer+ if (device->has_classic_bearer && device->connected) {+ std::string bearer_err;+ if (call(device->path, IFACE_BEARER_BREDR, "Connect", bearer_err))+ return true;+ // some versions publish the interface without the method+ if (bearer_err.find("UnknownMethod") == std::string::npos) {+ err = bearer_err;+ return false;+ }+ }return call(device->path, IFACE_DEVICE, "Connect", err);}@@ -305,7 +318,14 @@ namespace tether::bluetooth {err = "no LE bearer";return false;}- return call(device->path, IFACE_BEARER_LE, "Connect", err);+ std::string bearer_err;+ if (call(device->path, IFACE_BEARER_LE, "Connect", bearer_err))+ return true;+ if (bearer_err.find("UnknownMethod") == std::string::npos) {+ err = bearer_err;+ return false;+ }+ return call(device->path, IFACE_DEVICE, "Connect", err);}private:@@ -456,9 +476,8 @@ namespace tether::bluetooth {// Whether the phone answers a listing for a child of the message root.// Cleared once, permanently for the session, if it turns out not to.bool map_lists_subfolders = true;- // Not every phone serves the sent folder; losing it must not cost us the- // inbox as well.bool map_lists_sent = true;+ int map_empty_sent_listings = 0;// The first listing on a new MAP session returns the phone's existing// inbox, which on a first run is every message it holds.bool map_session_backfill = true;@@ -568,6 +587,7 @@ namespace tether::bluetooth {map_session_backfill = true;map_lists_subfolders = true;map_lists_sent = true;+ map_empty_sent_listings = 0;}if (now < next_message_poll)@@ -625,12 +645,20 @@ namespace tether::bluetooth {if (map_lists_sent) {std::string sent_err;auto sent = session->list_messages(MAP_FOLDER_SENT, MESSAGE_LIST_MAX, sent_err);- if (sent_err.empty()) {- listings.insert(listings.end(), sent.begin(), sent.end());- } else {+ if (!sent_err.empty()) {debug::log(WARN, "bluetooth: the sent folder is unavailable ({}); showing received messages only", sent_err);map_lists_sent = false;+ } else if (sent.empty() && !listings.empty()) {+ if (++map_empty_sent_listings >= SENT_EMPTY_LISTINGS_BEFORE_GIVING_UP) {+ debug::log(INFO,+ "bluetooth: the phone serves no sent messages over MAP; "+ "conversations will show received messages and replies sent from here");+ map_lists_sent = false;+ }+ } else {+ map_empty_sent_listings = 0;+ listings.insert(listings.end(), sent.begin(), sent.end());}}diff --git a/src/core/src/bluetooth/objects.cpp b/src/core/src/bluetooth/objects.cppindex b00cf8a..7b3bb0b 100644--- a/src/core/src/bluetooth/objects.cpp+++ b/src/core/src/bluetooth/objects.cpp@@ -11,6 +11,7 @@ namespace tether::bluetooth {constexpr const char* IFACE_DEVICE = "org.bluez.Device1";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";bool iequals(const std::string& a, const std::string& b) {return a.size() == b.size() &&@@ -154,6 +155,18 @@ namespace tether::bluetooth {g_variant_unref(le);}+ if (GVariant* br = g_variant_lookup_value(ifaces, IFACE_BEARER_BREDR, G_VARIANT_TYPE("a{sv}"))) {+ d.has_classic_bearer = true;+ if (GVariant* connected = g_variant_lookup_value(br, "Connected", G_VARIANT_TYPE_BOOLEAN)) {+ d.classic_state_known = true;+ d.classic_connected = g_variant_get_boolean(connected);+ g_variant_unref(connected);+ }+ d.classic_paired = get_bool(br, "Paired");+ d.classic_bonded = get_bool(br, "Bonded", d.classic_paired);+ g_variant_unref(br);+ }+out.devices.push_back(std::move(d));}@@ -331,6 +344,7 @@ namespace tether::bluetooth {{"bonded", d.bonded},{"trusted", d.trusted},{"connected", d.connected},+ {"classic_connected", d.classic_link_up()},{"le_bearer", d.has_le_bearer},{"le_bonded", d.le_bonded},{"le_connected", d.le_connected},diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cppindex ef6fe40..7beae7a 100644--- a/test/test_bluetooth_objects.cpp+++ b/test/test_bluetooth_objects.cpp@@ -302,3 +302,102 @@ TEST(Capability, PrefersAPoweredAdapter) {EXPECT_TRUE(cap.powered);EXPECT_TRUE(cap.le_peripheral);}++// Device1.Connected is an aggregate across bearers. A phone holding an LE link+// with no BR/EDR link reports Connected=true while MAP and PBAP — which both+// ride BR/EDR — are unreachable, so obexd answers every session attempt with+// "Unable to find service record". Reading the aggregate as the Classic link+// makes the daemon report a healthy BR/EDR connection and never reconnect it.+constexpr const char* IPHONE_LE_ONLY_LINK = R"({+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {+ 'org.bluez.Device1': {+ 'Address': <'60:57:C8:30:6A:F7'>,+ 'Adapter': <objectpath '/org/bluez/hci0'>,+ 'Paired': <true>,+ 'Bonded': <true>,+ 'Connected': <true>,+ 'UUIDs': <['00001132-0000-1000-8000-00805f9b34fb']>+ },+ 'org.bluez.Bearer.BREDR1': {+ 'Paired': <true>,+ 'Bonded': <true>,+ 'Connected': <false>+ },+ 'org.bluez.Bearer.LE1': {+ 'Paired': <true>,+ 'Bonded': <true>,+ 'Connected': <true>+ }+ }+})";++TEST(BluetoothObjects, ClassicLinkComesFromTheBredrBearerNotTheAggregate) {+ Payload payload(IPHONE_LE_ONLY_LINK);+ ASSERT_TRUE(payload.v);++ auto objects = parse_managed_objects(payload.v);+ ASSERT_EQ(objects.devices.size(), 1u);+ const Device& device = objects.devices.front();++ EXPECT_TRUE(device.connected) << "the aggregate is still reported as BlueZ gave it";+ EXPECT_TRUE(device.has_classic_bearer);+ EXPECT_TRUE(device.classic_state_known);+ EXPECT_FALSE(device.classic_connected);+ EXPECT_TRUE(device.le_connected);++ EXPECT_FALSE(device.classic_link_up())+ << "an LE-only link must not be reported as a Classic connection: every OBEX profile rides BR/EDR";+}++// Not every BlueZ exposes the bearer interfaces. Where they are absent the+// aggregate is the only signal there is, and it is the right one.+TEST(BluetoothObjects, ClassicLinkFallsBackToTheAggregateWithoutBearers) {+ constexpr const char* NO_BEARERS = R"({+ '/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF': {+ 'org.bluez.Device1': {+ 'Address': <'AA:BB:CC:DD:EE:FF'>,+ 'Adapter': <objectpath '/org/bluez/hci0'>,+ 'Paired': <true>,+ 'Connected': <true>,+ 'UUIDs': <@as []>+ }+ }+ })";+ Payload payload(NO_BEARERS);+ ASSERT_TRUE(payload.v);++ auto objects = parse_managed_objects(payload.v);+ ASSERT_EQ(objects.devices.size(), 1u);+ EXPECT_FALSE(objects.devices.front().has_classic_bearer);+ EXPECT_TRUE(objects.devices.front().classic_link_up());+}++// BlueZ strips a bearer interface down to a bare signal while the device is+// disconnected: the name is still in the object tree, but there are no+// properties to read and no methods to call. Treating that as an authoritative+// "BR/EDR is down" would let a stub contradict a link that is genuinely up.+TEST(BluetoothObjects, StubBearerIsNotMistakenForAReading) {+ constexpr const char* STUB_BEARERS = R"({+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {+ 'org.bluez.Device1': {+ 'Address': <'60:57:C8:30:6A:F7'>,+ 'Adapter': <objectpath '/org/bluez/hci0'>,+ 'Paired': <true>,+ 'Connected': <true>,+ 'UUIDs': <@as []>+ },+ 'org.bluez.Bearer.BREDR1': {},+ 'org.bluez.Bearer.LE1': {}+ }+ })";+ Payload payload(STUB_BEARERS);+ ASSERT_TRUE(payload.v);++ auto objects = parse_managed_objects(payload.v);+ ASSERT_EQ(objects.devices.size(), 1u);+ const Device& device = objects.devices.front();++ EXPECT_TRUE(device.has_classic_bearer) << "the interface is present, which is what confirms the bearer API";+ EXPECT_FALSE(device.classic_state_known) << "a stub carries no Connected property to believe";+ EXPECT_TRUE(device.classic_link_up()) << "with nothing to read, the aggregate is the only answer available";+}diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cppindex 2e2593d..e6e415a 100644--- a/test/test_bluetooth_supervisor.cpp+++ b/test/test_bluetooth_supervisor.cpp@@ -229,7 +229,7 @@ TEST(BearerSupervisor, RecoversAfterDisconnect) {ops.le = false;sup.tick(100);EXPECT_FALSE(sup.status().classic_connected);- EXPECT_FALSE(sup.status().le_connected) << "LE cannot be up while Classic is down";+ EXPECT_FALSE(sup.status().le_connected);EXPECT_EQ(ops.classic_attempts, 2);// ...and comes back.@@ -477,7 +477,9 @@ TEST(BearerSupervisor, TransientFailuresDoNotEscalateTheBackoff) {"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: le-connection-abort-by-local",+ "org.bluez.Error.Failed: br-connection-refused",+ "org.bluez.Error.Failed: Operation already in progress"}) {FakeBearer ops;ops.classic_succeeds = false;ops.classic_error = message;@@ -574,3 +576,105 @@ TEST(ProfileSupervisor, DropMapReopensWithoutTouchingPbap) {EXPECT_NE(sup.map_session(), first_map);EXPECT_EQ(sup.pbap_session(), pbap) << "the surviving PBAP session was reopened needlessly";}++// iOS routinely keeps an LE link while letting BR/EDR lapse. ANCS rides LE+// alone, so notification mirroring keeps working there — reporting LE as down+// because BR/EDR is would tear down a GATT session that is still delivering.+TEST(BearerSupervisor, LeStaysReportedWhenOnlyClassicIsDown) {+ FakeBearer ops;+ BearerSupervisor sup(ops, true);++ sup.tick(0);+ sup.tick(1);+ sup.tick(1 + BEARER_SETTLE_SECONDS);+ ASSERT_TRUE(sup.status().classic_connected);+ ASSERT_TRUE(sup.status().le_connected);++ // BR/EDR lapses; the LE link is untouched.+ ops.classic = false;+ ops.classic_succeeds = false;+ sup.tick(100);++ EXPECT_FALSE(sup.status().classic_connected);+ EXPECT_TRUE(sup.status().le_connected) << "an LE link that is still up must not be reported as down";+ EXPECT_GT(ops.classic_attempts, 1) << "BR/EDR must still be retried";+}++// An iPhone that refuses BR/EDR while unlocked with its permissions on is wedged+// on its own side. Only cycling Bluetooth on the phone clears it, so the status+// has to say that rather than claiming to still be connecting.+TEST(BearerSupervisor, RepeatedRefusalNamesTheRemedy) {+ FakeBearer ops;+ ops.classic_succeeds = false;+ ops.classic_error = "org.bluez.Error.Failed: br-connection-refused";+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ EXPECT_NE(sup.status().reason.find("Connecting"), std::string::npos)+ << "one refusal is not yet evidence of anything";++ while (ops.classic_attempts < CLASSIC_FAILURES_BEFORE_ADVICE) {+ now += sup.status().classic_backoff;+ sup.tick(now);+ }++ EXPECT_NE(sup.status().reason.find("Turn Bluetooth off and back on"), std::string::npos)+ << "the status never names the one thing that clears this";+ EXPECT_NE(sup.status().reason.find("Re-pairing is not the fix"), std::string::npos);++ // And it goes away the moment the phone accepts. The backoff has to elapse+ // first, or no attempt is made and the advice rightly still stands.+ ops.classic_succeeds = true;+ now += sup.status().classic_backoff;+ sup.tick(now);+ EXPECT_EQ(sup.status().reason.find("Turn Bluetooth off"), std::string::npos);+ sup.tick(++now);+ 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, UndiallableLeStopsClaimingItIsComingUp) {+ // The connect reports success but the link never appears, which is exactly+ // what a Device1.Connect fallback does on an already-connected device.+ class OptimisticBearer : public FakeBearer {+ public:+ bool connect_le(std::string&) override {+ ++le_attempts;+ return true;+ }+ } optimistic;++ BearerSupervisor sup(optimistic, true);+ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;+ sup.tick(now);+ // The attempt reports success, so this tick believes it. The next one reads+ // the real state back and finds nothing there.+ sup.tick(++now);+ ASSERT_FALSE(sup.status().le_connected) << "the fake never actually brings LE up";+ EXPECT_NE(sup.status().reason.find("Bringing up the LE link"), std::string::npos);++ while (optimistic.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {+ now += BEARER_BACKOFF_MIN_SECONDS;+ sup.tick(now);+ }+ // The tick that made the last attempt believed it worked; the one after reads+ // the truth back, and that is where the status has to change.+ sup.tick(++now);++ EXPECT_NE(sup.status().reason.find("not opening the LE link"), std::string::npos)+ << "the status never admits the link is not coming from this end";+ EXPECT_NE(sup.status().reason.find("Messages and contacts are unaffected"), std::string::npos)+ << "a user reading this needs to know messages still work";++ // An optimistic success must not turn into a connect attempt every tick.+ const int attempts = optimistic.le_attempts;+ sup.tick(++now);+ EXPECT_EQ(optimistic.le_attempts, attempts) << "LE was re-dialled inside its own backoff";+}