Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: bt le reconnect loop and UI disconnect

Zack Bartelf7107870d37f
diff --git a/Makefile b/Makefile
index a928501..111ad5f 100644
--- a/Makefile
+++ b/Makefile
@@ -15,7 +15,7 @@ test: debug
cd extension && npm test
install: release
- cmake --install build/release
+ sudo cmake --install build/release
package: release
cd build/release && cpack
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.md
index 79d98a7..3502624 100644
--- a/docs/BLUETOOTH.md
+++ b/docs/BLUETOOTH.md
@@ -260,8 +260,9 @@ are why the sequencer exists.
### Group messages
-Off by default, `group_messages_enabled` and
-`ancs_content_enabled` in `~/.config/tether/bluetooth.json`, so group support cannot work without content mirroring.
+Off by default, `group_messages_enabled` in `~/.config/tether/bluetooth.json`. It also
+needs `ancs_content_enabled` (on by default, `tether --bt-ancs-content off` to disable),
+so group support cannot work without content mirroring.
MAP delivers a group message with one sender, no participant list and no conversation
identifier. The only other hint is to correlate Apple Messages ANCS notification:
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 33c9942..02a2737 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -335,10 +335,23 @@ Broadcast once per newly observed message, incoming or locally sent.
`app_id`, `app_name`, `title`, `subtitle`, `body`, `category`, `timestamp`, and which
actions the notification offers.
-Bodies are present only when notification content mirroring is enabled; by default the
-daemon requests the owning app and nothing more. Messages notifications
-(`com.apple.MobileSMS`) are retained but never raise a desktop popup, since MAP already
-delivers those with working read state.
+`app_name` is the app's display name, resolved over ANCS `GetAppAttributes` and cached
+per bundle id for the session. The first notification from an app carries a name derived
+from its bundle id (`com.burbn.instagram` -> `Instagram`) and is corrected in place once
+the phone answers.
+
+Titles, subtitles and bodies are present when notification content mirroring is enabled,
+which is the default -- the iPhone's own *Settings > Bluetooth > (i) > Show Message
+Notifications* toggle is the consent gate. With it off, only `app_id` and `app_name` are
+populated. Messages notifications (`com.apple.MobileSMS`) are retained but never raise a
+desktop popup, since MAP already delivers those with working read state.
+
+#### `bt_set_ancs_content` (Client -> Daemon, broadcast)
+**Payload**: `{"command": "bt_set_ancs_content", "enabled": true}`
+Turns notification content mirroring on or off. Persists to
+`ancs_content_enabled` in `~/.config/tether/bluetooth.json`, applies to the running ANCS
+client without a restart, and answers with a fresh `bt_status`. `bt_status` carries
+`ancs_enabled` and `ancs_content_enabled` so a client can render the current state.
#### `bt_notification_action` (Client -> Daemon, broadcast)
**Payload**: `{"command": "bt_notification_action", "uid": 42, "action": "positive"}`
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 2e05ba8..0ef8980 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -117,6 +117,8 @@ void print_help() {
<< " --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-ancs-content <on|off> Mirror notification titles and bodies, not just the app.\n"
+ << " --bt-notifications List mirrored iPhone notifications.\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"
@@ -322,6 +324,40 @@ static std::string format_time(int64_t epoch) {
return buf;
}
+static int print_bt_notifications(tether::Client& client) {
+ nlohmann::json resp;
+ try {
+ resp = nlohmann::json::parse(client.send_and_wait("{\"command\":\"bt_list_notifications\"}\n"));
+ } catch (const std::exception&) {
+ debug::log(ERR, "Could not read notifications from the daemon.\n");
+ return 1;
+ }
+
+ const auto& notifications = resp["notifications"];
+ if (notifications.empty()) {
+ fprintf(stdout, "No notifications yet. Check 'tether --bt-connection'.\n");
+ return 0;
+ }
+
+ for (const auto& n : notifications) {
+ const std::string app = n.value("app_name", n.value("app_id", ""));
+ const std::string title = n.value("title", "");
+ const std::string subtitle = n.value("subtitle", "");
+ const std::string body = n.value("body", "");
+ fprintf(stdout,
+ "%s %s%s%s\n",
+ format_time(n.value("timestamp", static_cast<int64_t>(0))).c_str(),
+ app.c_str(),
+ title.empty() ? "" : " - ",
+ title.c_str());
+ for (const std::string& line : {subtitle, body}) {
+ if (!line.empty())
+ fprintf(stdout, " %s\n", line.c_str());
+ }
+ }
+ return 0;
+}
+
static int print_bt_threads(tether::Client& client) {
nlohmann::json resp;
try {
@@ -486,6 +522,12 @@ int main(int argc, char* argv[]) {
action = "bt_ancs";
if (i + 1 < argc && argv[i + 1][0] != '-')
arg_val = argv[++i];
+ } else if (arg == "--bt-ancs-content") {
+ action = "bt_ancs_content";
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ arg_val = argv[++i];
+ } else if (arg == "--bt-notifications") {
+ action = "bt_notifications";
} else if (arg == "--bt-pair") {
action = "bt_pair";
if (i + 1 < argc && argv[i + 1][0] != '-')
@@ -622,6 +664,8 @@ int main(int argc, char* argv[]) {
return print_bt_diagnostics(client);
} else if (action == "bt_threads") {
return print_bt_threads(client);
+ } else if (action == "bt_notifications") {
+ return print_bt_notifications(client);
} else if (action == "bt_messages") {
if (arg_val.empty()) {
debug::log(ERR, "A thread key is required, e.g. --bt-messages tel:+15551234567\n");
@@ -642,19 +686,23 @@ int main(int argc, char* argv[]) {
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") {
+ } else if (action == "bt_ancs" || action == "bt_ancs_content") {
+ const bool content = action == "bt_ancs_content";
if (arg_val != "on" && arg_val != "off") {
- debug::log(ERR, "Expected on or off, e.g. --bt-ancs on\n");
+ debug::log(ERR, "Expected on or off, e.g. {} on\n", content ? "--bt-ancs-content" : "--bt-ancs");
return 1;
}
nlohmann::json request;
- request["command"] = "bt_set_ancs";
+ request["command"] = content ? "bt_set_ancs_content" : "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");
+ fprintf(stdout,
+ "%s %s.\n",
+ content ? "Notification contents" : "Notification mirroring",
+ arg_val == "on" ? "enabled" : "disabled");
}
return 0;
diff --git a/src/core/include/tether/bluetooth/ancs/notifications.hpp b/src/core/include/tether/bluetooth/ancs/notifications.hpp
index 2c846af..e31f25b 100644
--- a/src/core/include/tether/bluetooth/ancs/notifications.hpp
+++ b/src/core/include/tether/bluetooth/ancs/notifications.hpp
@@ -52,6 +52,8 @@ namespace tether::bluetooth::ancs {
void clear();
void store(const Notification& notification);
+ // Applies a display name resolved after the notifications were stored.
+ void rename_app(const std::string& app_id, const std::string& name);
const Notification* find(uint32_t uid) const;
// Newest first.
std::vector<Notification> recent(size_t limit = 50) const;
@@ -65,6 +67,10 @@ namespace tether::bluetooth::ancs {
std::vector<uint32_t> order_;
};
+ // "com.burbn.instagram" -> "Instagram". Stands in until the phone answers
+ // with the app's real display name, and when it never does.
+ std::string derive_app_name(const std::string& app_id);
+
// Messages arrive over MAP already, with read state that stays in sync. The
// ANCS copy is kept for correlation but must never raise a second popup.
bool should_show_desktop_popup(const Notification& notification);
diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hpp
index 3195d41..d21fb99 100644
--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp
+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp
@@ -13,6 +13,19 @@ namespace tether::bluetooth {
inline constexpr int CLASSIC_FAILURES_BEFORE_ADVICE = 6;
inline constexpr int LE_ATTEMPTS_BEFORE_ADVICE = 6;
+ // How long an ANCS session is held across an LE outage before the path is
+ // dropped. The bearer flaps faster than a GATT subscription can be rebuilt,
+ // so a blip must not reset discovery, while a genuine loss still clears.
+ inline constexpr int ANCS_BEARER_GRACE_SECONDS = 30;
+
+ // What BlueZ did with a request to bring a bearer up. Accepting a request is
+ // not a link: only an observed Connected is that.
+ enum class ConnectResult {
+ Requested, // BlueZ took the request; a link may or may not follow
+ Busy, // a connect is already running, so do not start another
+ Failed, // refused outright
+ };
+
// The BlueZ operations the supervisor performs.
class BearerOps {
public:
@@ -26,8 +39,10 @@ namespace tether::bluetooth {
virtual void set_preferred_bearer(const std::string& bearer) = 0;
- virtual bool connect_classic(std::string& err) = 0;
- virtual bool connect_le(std::string& err) = 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.
+ virtual ConnectResult connect_le(std::string& err) = 0;
};
struct BearerStatus {
@@ -68,6 +83,9 @@ namespace tether::bluetooth {
BearerStatus status_;
int classic_failures_ = 0;
int le_attempts_ = 0;
+ // Whether LE attempts keep colliding with a connect BlueZ never
+ // finished, rather than the phone declining. Needs opposite advice.
+ bool le_stuck_locally_ = false;
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/config.hpp b/src/core/include/tether/bluetooth/config.hpp
index ebd04c4..d6c2236 100644
--- a/src/core/include/tether/bluetooth/config.hpp
+++ b/src/core/include/tether/bluetooth/config.hpp
@@ -24,8 +24,9 @@ namespace tether::bluetooth {
// not keep trying to bring up an LE bearer the phone will not answer.
bool ancs_enabled = true;
// Whether to request notification contents rather than only the app
- // they came from. Off by default.
- bool ancs_content_enabled = false;
+ // they came from. The iPhone's own notification-access toggle is the
+ // consent gate, so this is on and stays available as an opt-out.
+ bool ancs_content_enabled = true;
// Group replies are off until deliberately enabled
bool group_messages_enabled = false;
diff --git a/src/core/include/tether/bluetooth/connection.hpp b/src/core/include/tether/bluetooth/connection.hpp
index 2c72ec6..6c2fce9 100644
--- a/src/core/include/tether/bluetooth/connection.hpp
+++ b/src/core/include/tether/bluetooth/connection.hpp
@@ -40,6 +40,10 @@ namespace tether::bluetooth {
// for a GATT session it will not use.
void set_notification_handlers(NotificationFn on_notification, WithdrawFn on_withdraw);
+ // Whether mirrored notifications carry their title and body, or only
+ // which app sent them. Takes effect on the next notification.
+ void set_ancs_content_enabled(bool enabled);
+
// Invokes a mirrored notification's action.
bool perform_notification_action(uint32_t uid, ancs::ActionId action);
diff --git a/src/core/src/bluetooth/ancs/client.cpp b/src/core/src/bluetooth/ancs/client.cpp
index 5d412a2..090afb2 100644
--- a/src/core/src/bluetooth/ancs/client.cpp
+++ b/src/core/src/bluetooth/ancs/client.cpp
@@ -67,6 +67,11 @@ namespace tether::bluetooth::ancs {
// rebuilt when its response lands.
std::map<uint32_t, SourceEvent> in_progress;
+ // Bundle id -> display name, as answered by GetAppAttributes. Only
+ // touched from tick()'s thread. An entry with an empty value marks a
+ // request already in flight, so an app is asked about once per session.
+ std::map<std::string, std::string> app_names;
+
bool write_control_point(const std::vector<uint8_t>& payload);
void set_status(bool now_ready, const std::string& text);
bool discover();
@@ -74,6 +79,7 @@ namespace tether::bluetooth::ancs {
void unsubscribe();
void handle_source_event(const SourceEvent& event, int64_t now);
void handle_response(const Request& request, const Response& response, int64_t now);
+ std::string app_display_name(const std::string& app_id);
};
namespace {
@@ -346,12 +352,32 @@ namespace tether::bluetooth::ancs {
in_progress.erase(event.uid);
}
+ // Never blocks on the phone: the derived name is used now and the real one
+ // backfills the registry when GetAppAttributes answers.
+ std::string AncsClientState::app_display_name(const std::string& app_id) {
+ if (app_id.empty())
+ return {};
+ auto [entry, inserted] = app_names.try_emplace(app_id);
+ if (inserted)
+ sequencer->submit(build_app_request(app_id));
+ return entry->second.empty() ? derive_app_name(app_id) : entry->second;
+ }
+
void AncsClientState::handle_response(const Request& request, const Response& response, int64_t now) {
if (response.command == CommandId::GetAppAttributes) {
// The readiness probe: a Data Source answer proves the phone has
// authorized notification access, which StartNotify alone does not.
if (!ready)
set_status(true, "Notification mirroring is active.");
+
+ const std::string name = response.attribute(static_cast<uint8_t>(AppAttributeId::DisplayName));
+ if (!response.app_id.empty() && !name.empty()) {
+ app_names[response.app_id] = name;
+ // The name arrives after the notifications that triggered the
+ // lookup were already stored and broadcast.
+ std::lock_guard<std::mutex> lock(registry_mutex);
+ registry.rename_app(response.app_id, name);
+ }
return;
}
if (response.command != CommandId::GetNotificationAttributes)
@@ -366,7 +392,7 @@ namespace tether::bluetooth::ancs {
Notification notification;
notification.uid = request.uid;
notification.app_id = response.attribute(static_cast<uint8_t>(NotificationAttributeId::AppIdentifier));
- notification.app_name = notification.app_id;
+ notification.app_name = app_display_name(notification.app_id);
notification.title = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Title));
notification.subtitle = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Subtitle));
notification.body = response.attribute(static_cast<uint8_t>(NotificationAttributeId::Message));
@@ -437,6 +463,7 @@ namespace tether::bluetooth::ancs {
// pre-existing notifications is a sync rather than news.
state_->initial_sync = true;
if (!same_device) {
+ state_->app_names.clear();
std::lock_guard<std::mutex> lock(state_->registry_mutex);
state_->registry.clear();
}
diff --git a/src/core/src/bluetooth/ancs/notifications.cpp b/src/core/src/bluetooth/ancs/notifications.cpp
index edaf418..6d6112d 100644
--- a/src/core/src/bluetooth/ancs/notifications.cpp
+++ b/src/core/src/bluetooth/ancs/notifications.cpp
@@ -1,6 +1,7 @@
#include "tether/bluetooth/ancs/notifications.hpp"
#include <algorithm>
+#include <cctype>
namespace tether::bluetooth::ancs {
@@ -62,6 +63,24 @@ namespace tether::bluetooth::ancs {
return out;
}
+ void NotificationRegistry::rename_app(const std::string& app_id, const std::string& name) {
+ if (app_id.empty() || name.empty())
+ return;
+ for (auto& [uid, notification] : notifications_) {
+ if (notification.app_id == app_id)
+ notification.app_name = name;
+ }
+ }
+
+ std::string derive_app_name(const std::string& app_id) {
+ const size_t dot = app_id.rfind('.');
+ if (dot == std::string::npos || dot + 1 == app_id.size())
+ return app_id;
+ std::string name = app_id.substr(dot + 1);
+ name[0] = static_cast<char>(std::toupper(static_cast<unsigned char>(name[0])));
+ return name;
+ }
+
bool should_show_desktop_popup(const Notification& notification) {
if (notification.app_id == APP_ID_MESSAGES)
return false;
diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cpp
index ce1edab..b8c9204 100644
--- a/src/core/src/bluetooth/bearer_supervisor.cpp
+++ b/src/core/src/bluetooth/bearer_supervisor.cpp
@@ -18,8 +18,6 @@ namespace tether::bluetooth {
// reason for it is gone (left the room answers with a page timeout, not a rejection).
bool is_transient(const std::string& err) {
static const char* const transient[] = {
- "org.bluez.Error.InProgress",
- "already in progress",
"org.bluez.Error.NotReady",
"page-timeout",
"page timeout",
@@ -38,6 +36,22 @@ namespace tether::bluetooth {
return false;
}
+ // BlueZ is already working on a connect, or the link is already up.
+ // Neither is a failure, and retrying at the minimum backoff is what turns
+ // one stalled connect into a permanent InProgress storm.
+ bool is_already_running(const std::string& err) {
+ return err.find("InProgress") != std::string::npos ||
+ err.find("already in progress") != std::string::npos ||
+ err.find("AlreadyConnected") != std::string::npos ||
+ err.find("already-connected") != std::string::npos;
+ }
+
+ // Collapses an error a synchronous caller reported into the same shape an
+ // asynchronous one returns, so both take one code path.
+ ConnectResult classify(ConnectResult reported, const std::string& err) {
+ 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);
}
@@ -51,6 +65,7 @@ namespace tether::bluetooth {
void BearerSupervisor::reset() {
classic_failures_ = 0;
le_attempts_ = 0;
+ le_stuck_locally_ = false;
classic_connected_since_ = -1;
next_classic_attempt_ = 0;
next_le_attempt_ = 0;
@@ -75,8 +90,10 @@ 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)
+ if (status_.le_connected) {
le_attempts_ = 0;
+ le_stuck_locally_ = false;
+ }
if (status_.classic_connected) {
if (classic_connected_since_ < 0)
@@ -94,16 +111,25 @@ namespace tether::bluetooth {
if (now >= next_classic_attempt_) {
ops_.set_preferred_bearer("bredr");
std::string err;
- if (ops_.connect_classic(err)) {
+ switch (classify(ops_.connect_classic(err), err)) {
+ case ConnectResult::Requested:
status_.classic_backoff = 0;
next_classic_attempt_ = 0;
classic_failures_ = 0;
- } else {
+ break;
+ case ConnectResult::Busy:
+ // Not a refusal and not an attempt. Standing back is the
+ // whole remedy.
+ status_.classic_backoff = grow_backoff(status_.classic_backoff);
+ next_classic_attempt_ = now + status_.classic_backoff;
+ break;
+ case ConnectResult::Failed:
++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);
+ break;
}
}
@@ -141,28 +167,55 @@ namespace tether::bluetooth {
// so LE is never left preferred while idle.
ops_.set_preferred_bearer("le");
std::string err;
- const bool ok = ops_.connect_le(err);
+ const ConnectResult result = classify(ops_.connect_le(err), err);
ops_.set_preferred_bearer("bredr");
- ++le_attempts_;
-
- if (ok) {
- status_.le_backoff = 0;
- // connect can report success without the link coming up
- next_le_attempt_ = now + BEARER_BACKOFF_MIN_SECONDS;
- status_.le_connected = true;
- } else {
+
+ switch (result) {
+ case ConnectResult::Requested:
+ // BlueZ accepting the request is not a link. Believe only an
+ // observed Connected, and widen the window each time so the
+ // next attempt cannot race a connect still running inside it.
+ ++le_attempts_;
+ le_stuck_locally_ = false;
+ status_.le_backoff = grow_backoff(status_.le_backoff);
+ next_le_attempt_ = now + status_.le_backoff;
+ break;
+ case ConnectResult::Busy:
+ // A collision says nothing about the phone, so it selects
+ // different advice -- but it still counts, or a permanently
+ // wedged BlueZ would never reach any advice at all.
+ ++le_attempts_;
+ le_stuck_locally_ = true;
+ status_.le_backoff = grow_backoff(status_.le_backoff);
+ next_le_attempt_ = now + status_.le_backoff;
+ break;
+ case ConnectResult::Failed:
+ ++le_attempts_;
+ le_stuck_locally_ = false;
status_.le_backoff = next_backoff(status_.le_backoff, err);
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) {
- 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...";
+ if (le_attempts_ < LE_ATTEMPTS_BEFORE_ADVICE)
+ status_.reason = "Connected. Bringing up the LE link for notifications...";
+ else if (le_stuck_locally_)
+ // Indistinguishable from a phone that declines, so name the
+ // 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.";
+ 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.";
return !(status_ == previous);
}
}
diff --git a/src/core/src/bluetooth/config.cpp b/src/core/src/bluetooth/config.cpp
index 4919d31..d809b07 100644
--- a/src/core/src/bluetooth/config.cpp
+++ b/src/core/src/bluetooth/config.cpp
@@ -22,6 +22,10 @@ namespace tether::bluetooth {
} // namespace
+ namespace {
+ constexpr int CONFIG_VERSION = 1;
+ } // namespace
+
const char* to_string(AuthStrategy strategy) {
return strategy == AuthStrategy::ExplicitPair ? "explicit-pair" : "connect-first";
}
@@ -39,6 +43,7 @@ namespace tether::bluetooth {
std::string serialize_config(const Config& config) {
nlohmann::json j;
+ j["config_version"] = CONFIG_VERSION;
j["device_address"] = config.device_address;
j["auth_strategy"] = to_string(config.auth_strategy);
j["ancs_enabled"] = config.ancs_enabled;
@@ -56,7 +61,8 @@ namespace tether::bluetooth {
config.device_address = j.value("device_address", "");
config.auth_strategy = auth_strategy_from_string(j.value("auth_strategy", ""));
config.ancs_enabled = j.value("ancs_enabled", true);
- config.ancs_content_enabled = j.value("ancs_content_enabled", false);
+ const int version = j.value("config_version", 0);
+ config.ancs_content_enabled = version < 1 ? true : j.value("ancs_content_enabled", true);
config.group_messages_enabled = j.value("group_messages_enabled", false);
} catch (const std::exception&) {
// A corrupt file must not stop the daemon; defaults are safe.
diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cpp
index fac8f6e..7df25b6 100644
--- a/src/core/src/bluetooth/connection.cpp
+++ b/src/core/src/bluetooth/connection.cpp
@@ -215,11 +215,11 @@ namespace tether::bluetooth {
constexpr const char* OBEX_CLIENT = "org.bluez.obex.Client1";
constexpr int CONNECT_TIMEOUT_MS = 30000;
- // Paging a phone over BR/EDR is slow, but an LE connect to a bonded device
- // already in range either answers quickly or is not going to. Waiting the
- // full 30s only stalls the supervisor thread and piles up InProgress on the
- // next attempts, since BlueZ keeps working after the call gives up.
- constexpr int LE_CONNECT_TIMEOUT_MS = 5000;
+ // BlueZ keeps working on a connect long after a caller gives up, and every
+ // later attempt then collides with it. The LE connect is issued
+ // 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 MESSAGE_POLL_SECONDS = 15;
// obexd can drop a MAP session while the Classic link stays up, and the
@@ -292,47 +292,109 @@ namespace tether::bluetooth {
g_clear_error(&error);
}
- bool connect_classic(std::string& err) override {
+ ConnectResult connect_classic(std::string& err) override {
auto device = lookup();
if (!device) {
err = "device not present";
- return false;
+ return ConnectResult::Failed;
}
// 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;
+ return ConnectResult::Requested;
// some versions publish the interface without the method
if (bearer_err.find("UnknownMethod") == std::string::npos) {
err = bearer_err;
- return false;
+ return ConnectResult::Failed;
}
}
- return call(device->path, IFACE_DEVICE, "Connect", err);
+ return call(device->path, IFACE_DEVICE, "Connect", err) ? ConnectResult::Requested
+ : ConnectResult::Failed;
}
- bool connect_le(std::string& err) override {
+ // Issued asynchronously and never abandoned: a synchronous call that
+ // times out leaves BlueZ still connecting, and the next attempt then
+ // collides with it forever.
+ ConnectResult connect_le(std::string& err) override {
auto device = lookup();
if (!device) {
err = "device not present";
- return false;
+ return ConnectResult::Failed;
}
if (!device->has_le_bearer) {
err = "no LE bearer";
- return false;
+ return ConnectResult::Failed;
}
- std::string bearer_err;
- if (call(device->path, IFACE_BEARER_LE, "Connect", bearer_err, LE_CONNECT_TIMEOUT_MS))
- return true;
- if (bearer_err.find("UnknownMethod") == std::string::npos) {
- err = bearer_err;
- return false;
+
+ {
+ std::lock_guard<std::mutex> lock(le_->mutex);
+ if (le_->pending)
+ return ConnectResult::Busy;
+ if (!le_->error.empty()) {
+ err = le_->error;
+ le_->error.clear();
+ return ConnectResult::Failed;
+ }
+ le_->pending = true;
}
- return call(device->path, IFACE_DEVICE, "Connect", err, LE_CONNECT_TIMEOUT_MS);
+
+ // Some BlueZ builds publish Bearer.LE1 without Connect; the first
+ // reply says which, and every later attempt uses the one that
+ // exists.
+ const char* iface = le_->bearer_connect_missing ? IFACE_DEVICE : IFACE_BEARER_LE;
+ auto* holder = new std::shared_ptr<LeConnect>(le_);
+ const std::string path = device->path;
+ monitor_.invoke_sync([this, path, iface, holder] {
+ g_dbus_connection_call(monitor_.connection(),
+ BLUEZ_NAME,
+ path.c_str(),
+ iface,
+ "Connect",
+ nullptr,
+ nullptr,
+ G_DBUS_CALL_FLAGS_NONE,
+ LE_CONNECT_TIMEOUT_MS,
+ nullptr,
+ on_le_connected,
+ holder);
+ });
+ return ConnectResult::Requested;
}
private:
+ // Outlives the ops object: a reply can land after the supervised
+ // device is torn down and replaced.
+ struct LeConnect {
+ std::mutex mutex;
+ bool pending = false;
+ std::string error;
+ bool bearer_connect_missing = false;
+ };
+ std::shared_ptr<LeConnect> le_ = std::make_shared<LeConnect>();
+
+ static void on_le_connected(GObject* source, GAsyncResult* result, gpointer user_data) {
+ std::unique_ptr<std::shared_ptr<LeConnect>> holder(static_cast<std::shared_ptr<LeConnect>*>(user_data));
+ GError* error = nullptr;
+ GVariant* reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error);
+ std::string message;
+ if (reply)
+ g_variant_unref(reply);
+ else {
+ message = error ? error->message : "unknown error";
+ g_clear_error(&error);
+ }
+
+ std::lock_guard<std::mutex> lock((*holder)->mutex);
+ (*holder)->pending = false;
+ // Not a failure of the connect, just the wrong interface. Retry on
+ // the next tick against Device1 and report nothing.
+ if (message.find("UnknownMethod") != std::string::npos)
+ (*holder)->bearer_connect_missing = true;
+ else
+ (*holder)->error = message;
+ }
+
std::optional<Device> lookup() const {
for (const auto& device : monitor_.snapshot().devices) {
if (normalize_address(device.address) == address_)
@@ -478,6 +540,9 @@ namespace tether::bluetooth {
bool ancs_enabled = true;
bool link_was_ready = false;
bool device_was_present = false;
+ // When the LE bearer was last seen down, so a blip can be told from a
+ // session that is really gone. -1 while it is up.
+ int64_t le_down_since = -1;
int map_failures = 0;
int64_t next_message_poll = 0;
std::string open_map_path;
@@ -754,11 +819,32 @@ namespace tether::bluetooth {
if (!ancs_client)
return;
- // ANCS rides the LE bearer. Without it there is nothing to talk to, and
- // pointing the client at an empty path is what makes it forget a session
- // that no longer exists.
+ // ANCS rides the LE bearer, but BlueZ keeps exposing the bonded
+ // characteristics while that bearer reads disconnected, and the bearer
+ // flaps far faster than a GATT subscription can be rebuilt. Dropping the
+ // path on every blip resets discovery and the sequencer, so the readiness
+ // probe never lives long enough to be answered. Hold the session across a
+ // short outage and let discovery decide; a real loss still clears it,
+ // because an empty path is what makes the client forget a dead session.
+ const bool le_up = bearers->status().le_connected;
+ if (le_up)
+ le_down_since = -1;
+ else if (le_down_since < 0)
+ le_down_since = now;
+ // A live subscription outranks the property: an iPhone that is answering
+ // ANCS is reachable whatever Bearer.LE1 says, and dropping the path under
+ // it would end a session that is working.
+ bool ready;
+ {
+ std::lock_guard<std::mutex> lock(status_mutex);
+ ready = ancs_ready;
+ }
+ // ponytail: one fixed grace window rather than per-phase tuning. Widen it
+ // if a controller is seen flapping slower than this.
+ const bool hold = ready || le_up || now - le_down_since < ANCS_BEARER_GRACE_SECONDS;
+
std::string device_path;
- if (bearers->status().le_connected) {
+ if (hold && bearers->status().device_present) {
auto objects = monitor->snapshot();
for (const auto& device : objects.devices) {
if (device.address == address || normalize_address(device.address) == normalize_address(address)) {
@@ -943,6 +1029,11 @@ namespace tether::bluetooth {
state_->on_withdraw = std::move(on_withdraw);
}
+ void ConnectionManager::set_ancs_content_enabled(bool enabled) {
+ if (state_->ancs_client)
+ state_->ancs_client->set_content_enabled(enabled);
+ }
+
bool ConnectionManager::perform_notification_action(uint32_t uid, ancs::ActionId action) {
return state_->ancs_client && state_->ancs_client->perform_action(uid, action);
}
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index 1d4f30b..2da7465 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -140,7 +140,16 @@ namespace tether {
// 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 std::mutex g_write_locks_mutex;
+ static std::map<int, std::mutex> g_write_locks;
+
+ static std::mutex& write_lock_for(int fd) {
+ std::lock_guard<std::mutex> lock(g_write_locks_mutex);
+ return g_write_locks[fd];
+ }
+
static bool robust_plain_write(int fd, const void* buf, size_t num) {
+ std::lock_guard<std::mutex> lock(write_lock_for(fd));
const char* p = static_cast<const char*>(buf);
size_t written = 0;
int stalls = 0;
@@ -258,7 +267,10 @@ namespace tether {
nlohmann::json status;
status["command"] = "bt_status";
status["available"] = bluetooth::g_bluez != nullptr && bluetooth::g_bluez->running();
- status["device_address"] = bluetooth::load_config().device_address;
+ const auto config = bluetooth::load_config();
+ status["device_address"] = config.device_address;
+ status["ancs_enabled"] = config.ancs_enabled;
+ status["ancs_content_enabled"] = config.ancs_content_enabled;
if (!bluetooth::g_bluez) {
status["capability"] = nullptr;
status["adapters"] = nlohmann::json::array();
@@ -841,6 +853,17 @@ namespace tether {
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_set_ancs_content") {
+ auto config = bluetooth::load_config();
+ config.ancs_content_enabled = j.value("enabled", true);
+ bluetooth::save_config(config);
+ if (bluetooth::g_bt_connections)
+ bluetooth::g_bt_connections->set_ancs_content_enabled(config.ancs_content_enabled);
+ // Group correlation reads notification bodies, so it
+ // follows this toggle.
+ bluetooth::set_group_replies_enabled(config.group_messages_enabled &&
+ config.ancs_content_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";
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 1fd177c..d14ecde 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -188,7 +188,9 @@ int main(int argc, char** argv) {
return;
const std::string title = notification.title.empty() ? notification.app_name : notification.title;
- notifier.notify(title.empty() ? "iPhone" : title, notification.body);
+ // Some apps put the whole notification in the subtitle and leave the message empty.
+ const std::string body = notification.body.empty() ? notification.subtitle : notification.body;
+ notifier.notify(title.empty() ? "iPhone" : title, body);
},
[](uint32_t uid) {
nlohmann::json event;
diff --git a/src/gtk/daemon_client.cpp b/src/gtk/daemon_client.cpp
index 2ef1e4f..c599cd2 100644
--- a/src/gtk/daemon_client.cpp
+++ b/src/gtk/daemon_client.cpp
@@ -88,7 +88,10 @@ namespace tether::ui {
try {
if (g_on_event)
g_on_event(nlohmann::json::parse(std::string(line, length)));
- } catch (...) {
+ } catch (const std::exception& e) {
+ // Silence here hides a dropped update as a view that
+ // simply did not refresh.
+ debug::log(WARN, "daemon: discarding an unreadable event ({})", e.what());
}
}
if (line)
diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cpp
index 973cb74..206082c 100644
--- a/src/gtk/devices_view.cpp
+++ b/src/gtk/devices_view.cpp
@@ -52,6 +52,7 @@ namespace tether::ui {
GtkWidget* lbl_bt_progress = nullptr;
GtkWidget* btn_bt_pair = nullptr;
GtkWidget* btn_bt_solicit = nullptr;
+ GtkWidget* chk_bt_content = nullptr;
GtkWidget* btn_bt_unpair = nullptr;
GtkWidget* lbl_welcome_wifi = nullptr;
@@ -101,6 +102,8 @@ namespace tether::ui {
set_text(g_devices.lbl_welcome_bt, bt_note);
}
+ void on_bt_content_toggled(GtkWidget* widget, gpointer);
+
void update_bt_pane() {
const std::string address = g_devices.selected_bt_address;
const nlohmann::json* device = find_bt_device(address);
@@ -181,6 +184,16 @@ namespace tether::ui {
gtk_widget_set_visible(g_devices.btn_bt_solicit,
available && supervised &&
(map_error == "forbidden" || map_error == "no_record" || !ancs_ready));
+
+ gtk_widget_set_visible(g_devices.chk_bt_content, available && supervised);
+ // The daemon's broadcast is the source of truth, so reflecting it
+ // must not look like the user clicking the box.
+ g_signal_handlers_block_by_func(
+ g_devices.chk_bt_content, reinterpret_cast<gpointer>(on_bt_content_toggled), nullptr);
+ gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_devices.chk_bt_content),
+ g_devices.bt_status.value("ancs_content_enabled", true));
+ g_signal_handlers_unblock_by_func(
+ g_devices.chk_bt_content, reinterpret_cast<gpointer>(on_bt_content_toggled), nullptr);
}
void update_right_pane() {
@@ -305,6 +318,11 @@ namespace tether::ui {
// The advertisement that makes iOS reveal its Messages and Contacts
// permission toggles expires a few minutes after pairing. Without this the
// only way back to those toggles is to remove the bond and pair again.
+ void on_bt_content_toggled(GtkWidget* widget, gpointer) {
+ daemon_send({{"command", "bt_set_ancs_content"},
+ {"enabled", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) == TRUE}});
+ }
+
void on_bt_solicit_click(GtkWidget*, gpointer) {
if (!daemon_send({{"command", "bt_solicit"}})) {
set_text(g_devices.lbl_bt_progress, "Could not reach the Tether daemon.");
@@ -892,6 +910,14 @@ namespace tether::ui {
}
gtk_box_pack_start(GTK_BOX(bt_box), capabilities, FALSE, FALSE, 0);
+ g_devices.chk_bt_content = gtk_check_button_new_with_label("Show notification contents");
+ gtk_widget_set_tooltip_text(g_devices.chk_bt_content,
+ "Ask the iPhone for each notification's title and message text, not just "
+ "which app sent it. The phone's own Show Message Notifications toggle still "
+ "has to be on.");
+ g_signal_connect(g_devices.chk_bt_content, "toggled", G_CALLBACK(on_bt_content_toggled), nullptr);
+ gtk_box_pack_start(GTK_BOX(bt_box), g_devices.chk_bt_content, FALSE, FALSE, 0);
+
g_devices.lbl_bt_reason = gtk_label_new(nullptr);
gtk_label_set_xalign(GTK_LABEL(g_devices.lbl_bt_reason), 0.0);
gtk_label_set_line_wrap(GTK_LABEL(g_devices.lbl_bt_reason), TRUE);
diff --git a/src/gtk/messages_view.cpp b/src/gtk/messages_view.cpp
index 8197e4b..389cc54 100644
--- a/src/gtk/messages_view.cpp
+++ b/src/gtk/messages_view.cpp
@@ -534,8 +534,10 @@ namespace tether::ui {
void messages_view_set_visible(bool visible) {
g_messages.visible = visible;
- if (visible)
- request_threads();
+ if (!visible)
+ return;
+ request_threads();
+ request_messages(g_messages.selected_thread);
}
bool messages_view_handle_event(const nlohmann::json& event) {
diff --git a/src/gtk/notifications_view.cpp b/src/gtk/notifications_view.cpp
index d2344e6..94daf9e 100644
--- a/src/gtk/notifications_view.cpp
+++ b/src/gtk/notifications_view.cpp
@@ -39,6 +39,7 @@ namespace tether::ui {
GtkWidget* build_row(const nlohmann::json& notification) {
const std::string app = notification.value("app_name", notification.value("app_id", ""));
const std::string title = notification.value("title", "");
+ const std::string subtitle = notification.value("subtitle", "");
const std::string body = notification.value("body", "");
const std::string stamp = format_timestamp(notification.value("timestamp", static_cast<int64_t>(0)));
@@ -61,16 +62,23 @@ namespace tether::ui {
}
gtk_box_pack_start(GTK_BOX(box), header, FALSE, FALSE, 0);
- // With content mirroring off, only the app is known — which is the
- // point of that default, so the row says so rather than looking broken.
+ // With content mirroring off only the app is known, so the row says
+ // so rather than looking broken.
const std::string detail = !title.empty() ? title : (!body.empty() ? body : "New notification");
GtkWidget* detail_label = gtk_label_new(detail.c_str());
gtk_label_set_xalign(GTK_LABEL(detail_label), 0.0);
gtk_label_set_line_wrap(GTK_LABEL(detail_label), TRUE);
gtk_box_pack_start(GTK_BOX(box), detail_label, FALSE, FALSE, 0);
- if (!title.empty() && !body.empty()) {
- GtkWidget* body_label = gtk_label_new(body.c_str());
+ // Whatever is left over after the primary line claimed one of them.
+ std::string secondary = subtitle;
+ if (!body.empty() && body != detail) {
+ if (!secondary.empty())
+ secondary += "\n";
+ secondary += body;
+ }
+ if (!secondary.empty()) {
+ GtkWidget* body_label = gtk_label_new(secondary.c_str());
gtk_label_set_xalign(GTK_LABEL(body_label), 0.0);
gtk_label_set_line_wrap(GTK_LABEL(body_label), TRUE);
gtk_style_context_add_class(gtk_widget_get_style_context(body_label), "muted");
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 75ca1ac..b3d6053 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -7,6 +7,7 @@ add_executable(tether_test
test_bmessage_build.cpp
test_ancs_parser.cpp
test_ancs_sequencer.cpp
+ test_ancs_notifications.cpp
test_groups.cpp
test_bt_diagnostics.cpp
test_vcard.cpp
diff --git a/test/test_ancs_notifications.cpp b/test/test_ancs_notifications.cpp
new file mode 100644
index 0000000..9af4f99
--- /dev/null
+++ b/test/test_ancs_notifications.cpp
@@ -0,0 +1,70 @@
+#include <gtest/gtest.h>
+#include <tether/bluetooth/ancs/notifications.hpp>
+#include <tether/bluetooth/config.hpp>
+
+using namespace tether::bluetooth;
+using namespace tether::bluetooth::ancs;
+
+namespace {
+
+ Notification make(uint32_t uid, const std::string& app_id) {
+ Notification n;
+ n.uid = uid;
+ n.app_id = app_id;
+ n.app_name = derive_app_name(app_id);
+ return n;
+ }
+
+} // namespace
+
+TEST(AncsAppName, DerivesTheLastBundleComponent) {
+ EXPECT_EQ(derive_app_name("com.burbn.instagram"), "Instagram");
+ EXPECT_EQ(derive_app_name("com.apple.MobileSMS"), "MobileSMS");
+ EXPECT_EQ(derive_app_name("Signal"), "Signal");
+ EXPECT_EQ(derive_app_name("com.example."), "com.example.");
+ EXPECT_EQ(derive_app_name(""), "");
+}
+
+TEST(AncsRegistry, RenameAppTouchesOnlyThatApp) {
+ NotificationRegistry registry;
+ registry.store(make(1, "com.burbn.instagram"));
+ registry.store(make(2, "com.burbn.instagram"));
+ registry.store(make(3, "com.apple.MobileSMS"));
+
+ registry.rename_app("com.burbn.instagram", "Instagram");
+
+ EXPECT_EQ(registry.find(1)->app_name, "Instagram");
+ EXPECT_EQ(registry.find(2)->app_name, "Instagram");
+ EXPECT_EQ(registry.find(3)->app_name, "MobileSMS");
+}
+
+TEST(AncsRegistry, RenameAppIgnoresEmptyArguments) {
+ NotificationRegistry registry;
+ registry.store(make(1, "com.burbn.instagram"));
+
+ registry.rename_app("com.burbn.instagram", "");
+ registry.rename_app("", "Instagram");
+
+ EXPECT_EQ(registry.find(1)->app_name, "Instagram");
+}
+
+// Content mirroring was off with no way to turn it on, so a stored false from
+// before the toggle existed must not pin the new default.
+TEST(BluetoothConfig, UnversionedFileTakesTheContentDefault) {
+ const Config config = deserialize_config(R"({"ancs_content_enabled": false})");
+ EXPECT_TRUE(config.ancs_content_enabled);
+}
+
+TEST(BluetoothConfig, VersionedFileKeepsTheStoredChoice) {
+ const Config off = deserialize_config(R"({"config_version": 1, "ancs_content_enabled": false})");
+ EXPECT_FALSE(off.ancs_content_enabled);
+
+ const Config on = deserialize_config(R"({"config_version": 1, "ancs_content_enabled": true})");
+ EXPECT_TRUE(on.ancs_content_enabled);
+}
+
+TEST(BluetoothConfig, SerializeStampsTheVersion) {
+ Config config;
+ config.ancs_content_enabled = false;
+ EXPECT_FALSE(deserialize_config(serialize_config(config)).ancs_content_enabled);
+}
diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cpp
index 8eb7e9c..b573b25 100644
--- a/test/test_bluetooth_supervisor.cpp
+++ b/test/test_bluetooth_supervisor.cpp
@@ -34,24 +34,24 @@ namespace {
std::string classic_error = "br/edr refused";
std::string le_error = "le refused";
- bool connect_classic(std::string& err) override {
+ ConnectResult connect_classic(std::string& err) override {
++classic_attempts;
if (!classic_succeeds) {
err = classic_error;
- return false;
+ return ConnectResult::Failed;
}
classic = true;
- return true;
+ return ConnectResult::Requested;
}
- bool connect_le(std::string& err) override {
+ ConnectResult connect_le(std::string& err) override {
++le_attempts;
if (!le_succeeds) {
err = le_error;
- return false;
+ return ConnectResult::Failed;
}
le = true;
- return true;
+ return ConnectResult::Requested;
}
};
@@ -98,6 +98,10 @@ TEST(BearerSupervisor, ConnectsClassicThenLeAfterSettling) {
sup.tick(1 + BEARER_SETTLE_SECONDS);
EXPECT_EQ(ops.le_attempts, 1);
+ EXPECT_FALSE(sup.status().le_connected) << "BlueZ accepting a connect is not a link";
+
+ // Only an observed Connected is one.
+ sup.tick(2 + BEARER_SETTLE_SECONDS);
EXPECT_TRUE(sup.status().le_connected);
}
@@ -152,22 +156,28 @@ TEST(BearerSupervisor, ClassicBackoffGrowsAndCaps) {
// InProgress means BlueZ is still finishing an operation of its own, which
// clears without help. Treating it like a refusal pushed the retry out to
// minutes and left LE — and so ANCS — down long after the cause was gone.
-TEST(BearerSupervisor, InProgressDoesNotGrowTheClassicBackoff) {
+// InProgress means BlueZ is still working on the last connect, which it keeps
+// doing long after a caller gives up. Retrying at the same cadence guarantees
+// the next attempt collides with it too, so one stalled connect becomes a
+// permanent storm. Standing further back is the only thing that clears it.
+TEST(BearerSupervisor, InProgressWidensTheClassicWindow) {
FakeBearer ops;
ops.classic_succeeds = false;
ops.classic_error = "GDBus.Error:org.bluez.Error.InProgress: In Progress";
BearerSupervisor sup(ops, true);
int64_t now = 0;
- for (int i = 0; i < 10; ++i) {
+ int previous = 0;
+ for (int i = 0; i < 5; ++i) {
sup.tick(now);
- EXPECT_EQ(sup.status().classic_backoff, BEARER_BACKOFF_MIN_SECONDS);
- now += BEARER_BACKOFF_MIN_SECONDS;
+ EXPECT_GT(sup.status().classic_backoff, previous) << "collided again at the same cadence";
+ previous = sup.status().classic_backoff;
+ now += previous;
}
- EXPECT_EQ(ops.classic_attempts, 10);
+ EXPECT_EQ(ops.classic_attempts, 5);
}
-TEST(BearerSupervisor, InProgressDoesNotGrowTheLeBackoff) {
+TEST(BearerSupervisor, InProgressWidensTheLeWindow) {
FakeBearer ops;
ops.le_succeeds = false;
ops.le_error = "GDBus.Error:org.bluez.Error.InProgress: In Progress";
@@ -178,10 +188,12 @@ TEST(BearerSupervisor, InProgressDoesNotGrowTheLeBackoff) {
sup.tick(0);
sup.tick(1);
int64_t now = 1 + BEARER_SETTLE_SECONDS;
+ int previous = 0;
for (int i = 0; i < LE_ATTEMPTS_BEFORE_ADVICE; ++i) {
sup.tick(now);
- EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);
- now += BEARER_BACKOFF_MIN_SECONDS;
+ EXPECT_GT(sup.status().le_backoff, previous) << "collided again at the same cadence";
+ previous = sup.status().le_backoff;
+ now += previous;
}
EXPECT_EQ(ops.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE);
}
@@ -222,6 +234,7 @@ TEST(BearerSupervisor, RecoversAfterDisconnect) {
sup.tick(0);
sup.tick(1);
sup.tick(1 + BEARER_SETTLE_SECONDS);
+ sup.tick(2 + BEARER_SETTLE_SECONDS);
ASSERT_TRUE(sup.status().le_connected);
// The phone walks out of range.
@@ -235,6 +248,7 @@ TEST(BearerSupervisor, RecoversAfterDisconnect) {
// ...and comes back.
sup.tick(101);
sup.tick(101 + BEARER_SETTLE_SECONDS);
+ sup.tick(102 + BEARER_SETTLE_SECONDS);
EXPECT_TRUE(sup.status().classic_connected);
EXPECT_TRUE(sup.status().le_connected);
}
@@ -485,13 +499,11 @@ TEST(ProfileSupervisor, BusySessionKeepsPollingWithoutRetryBurst) {
// 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",
+ 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",
- "org.bluez.Error.Failed: Operation already in progress"}) {
+ "org.bluez.Error.Failed: br-connection-refused"}) {
FakeBearer ops;
ops.classic_succeeds = false;
ops.classic_error = message;
@@ -599,6 +611,7 @@ TEST(BearerSupervisor, LeStaysReportedWhenOnlyClassicIsDown) {
sup.tick(0);
sup.tick(1);
sup.tick(1 + BEARER_SETTLE_SECONDS);
+ sup.tick(2 + BEARER_SETTLE_SECONDS);
ASSERT_TRUE(sup.status().classic_connected);
ASSERT_TRUE(sup.status().le_connected);
@@ -654,10 +667,10 @@ TEST(BearerSupervisor, GivesUpDiallingLeInsteadOfSpinningForever) {
// after our call gives up, so the next attempts collide with it.
class RefusingBearer : public FakeBearer {
public:
- bool connect_le(std::string& err) override {
+ ConnectResult connect_le(std::string& err) override {
++le_attempts;
err = (le_attempts % 2) ? "Timeout was reached" : "GDBus.Error:org.bluez.Error.InProgress: In Progress";
- return false;
+ return ConnectResult::Failed;
}
} refusing;
@@ -672,7 +685,7 @@ TEST(BearerSupervisor, GivesUpDiallingLeInsteadOfSpinningForever) {
}
EXPECT_EQ(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "LE was dialled forever against a phone refusing it";
- EXPECT_NE(sup.status().reason.find("not opening the LE link"), std::string::npos);
+ 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();
@@ -683,14 +696,58 @@ TEST(BearerSupervisor, GivesUpDiallingLeInsteadOfSpinningForever) {
EXPECT_GT(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "reset must re-arm LE for the next session";
}
+// A wedged bluetoothd and a phone that declines both end in a dead LE link, but
+// only one of them is fixed on the phone. Sending the user to iOS settings for a
+// stuck local connect is the wrong errand.
+TEST(BearerSupervisor, StuckBluezAdviceNamesTheDaemonRestart) {
+ 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::Failed;
+ }
+ } stuck;
+
+ BearerSupervisor sup(stuck, true);
+ int64_t now = 0;
+ sup.tick(now);
+ now += BEARER_SETTLE_SECONDS + 1;
+ while (stuck.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {
+ now += BEARER_BACKOFF_MAX_SECONDS;
+ sup.tick(now);
+ }
+
+ EXPECT_NE(sup.status().reason.find("systemctl restart bluetooth"), std::string::npos)
+ << "the one thing that clears a stuck connect is never named";
+ EXPECT_NE(sup.status().reason.find("Messages and contacts are unaffected"), std::string::npos);
+
+ // A refusal that never collides is the phone's to fix, and must not send the
+ // user restarting daemons.
+ FakeBearer refusing;
+ refusing.le_succeeds = false;
+ refusing.le_error = "org.bluez.Error.Failed: le-connection-abort-by-local";
+ BearerSupervisor other(refusing, true);
+ now = 0;
+ other.tick(now);
+ now += BEARER_SETTLE_SECONDS + 1;
+ while (refusing.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {
+ now += BEARER_BACKOFF_MAX_SECONDS;
+ other.tick(now);
+ }
+
+ EXPECT_NE(other.status().reason.find("not opening the LE link"), std::string::npos);
+ EXPECT_EQ(other.status().reason.find("systemctl"), std::string::npos) << "nothing here says BlueZ is wedged";
+}
+
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 {
+ ConnectResult connect_le(std::string&) override {
++le_attempts;
- return true;
+ return ConnectResult::Requested;
}
} optimistic;