Linux + iPhone Continuity / iMessage / SMS
fix(bluetooth): harden container pairing retries
Nick Pisani24c3d9dde9c7
diff --git a/docs/CONTAINER.md b/docs/CONTAINER.mdindex ed1678c..74ab8a5 100644--- a/docs/CONTAINER.md+++ b/docs/CONTAINER.md@@ -35,7 +35,11 @@ needs a Wayland session and is not available here.has its own packaged OBEX client (currently 5.72). Record both versions when testing.2. Run Avahi and the system bus on the host. Open inbound 5134/tcp and mDNS5353/udp on the trusted local network; see the README's firewall instructions.-3. Choose a real non-root host UID/GID authorized to use the host system bus and+3. Verify the host settings, then set `TETHER_BLUEZ_SECURE_CONNECTIONS=1` in+ the container environment. Tether can detect BlueZ's experimental API over+ D-Bus, but the container cannot run host management tools to inspect the+ controller's Secure Connections setting.+4. Choose a real non-root host UID/GID authorized to use the host system bus andBluetooth services. Do not run another `tetherd` on that host port/adapter.The example mounts `/run/dbus` read-only at `/host/run/dbus`. **This is privileged@@ -70,6 +74,8 @@ Edit `packaging/container/.env`:paths. Replace the example `/home/your-user` values; do not use literal `$HOME`.- Optionally choose `TETHER_HOSTNAME`, a DNS-style host label such as `tether-pi`.It is the advertised display name; the persisted certificate is the identity.+- Leave `TETHER_BLUEZ_SECURE_CONNECTIONS=1` only after checking that the host+ controller meets that prerequisite. Set it to `0` when the capability is absent.The entrypoint refuses wrong ownership or a non-private data directory ratherthan recursively changing your files. Existing directories must already be@@ -202,12 +208,17 @@ requires handling that host's bonds separately.- Docker does **not** restart a still-running container just because it isunhealthy. Inspect logs and restart deliberately if needed.-The two new opt-in environment switches are also usable outside Docker:+These environment switches are also usable outside Docker:-| Variable | Exact value `1` does this | Otherwise |+| Variable | Value | Behavior ||---|---|---|-| `TETHER_LOG_STDERR` | Keep daemon stderr attached to its supervisor | Preserve normal nonterminal log-file behavior |-| `TETHER_NO_AUTOSTART` | Prevent CLI/client helpers from spawning `tetherd` | Preserve normal spawning/systemd ownership behavior |+| `TETHER_LOG_STDERR` | `1` | Keep daemon stderr attached to its supervisor |+| `TETHER_NO_AUTOSTART` | `1` | Prevent CLI/client helpers from spawning `tetherd` |+| `TETHER_BLUEZ_SECURE_CONNECTIONS` | Boolean (`1`/`0`, `true`/`false`, `yes`/`no`, `on`/`off`) | Declare whether the host controller has Secure Connections enabled |++Unset runtime switches preserve normal behavior. An unset capability declaration+falls back to the local `btmgmt` probe, which may not be able to inspect the host+controller from inside a container.`XDG_DOWNLOAD_DIR` now takes precedence when nonempty and absolute; invalid orempty overrides fall back to the existing GLib/HOME lookup.@@ -225,8 +236,8 @@ Troubleshooting:connectivity. This container cannot make mDNS cross an isolated network/VPN.- **Misleading `tether bt setup` advice:** the experimental-API check readsBlueZ's own objects now, so the container's PID namespace no longer hides the- answer, but `btmgmt` probes (Secure Connections) may still lack permission.- Apply the documented setup on the host; don't share host PID space just to+ answer. Set `TETHER_BLUEZ_SECURE_CONNECTIONS` if the `btmgmt` probe lacks+ permission; don't share host PID space or add management capabilities just toimprove a diagnostic.- **Host service repaired/restarted:** Tether may need a container restart ifBlueZ was unavailable during startup. This packaging does not promise newdiff --git a/packaging/container/.env.example b/packaging/container/.env.exampleindex 790ffcc..085c620 100644--- a/packaging/container/.env.example+++ b/packaging/container/.env.example@@ -6,5 +6,8 @@ TETHER_GID=1000TETHER_DATA_DIR=/home/your-user/.local/share/tether-containerTETHER_DOWNLOADS_DIR=/home/your-user/tether-inboxTETHER_HOSTNAME=tether+# Set this only after verifying the controller setting on the host.+# Containers cannot run host Bluetooth management tools reliably.+TETHER_BLUEZ_SECURE_CONNECTIONS=1# Optional local build label. No image is published by this configuration.TETHER_VERSION=0.2.32-container-devdiff --git a/packaging/container/compose.yaml b/packaging/container/compose.yamlindex 795e309..229e1fb 100644--- a/packaging/container/compose.yaml+++ b/packaging/container/compose.yaml@@ -15,6 +15,8 @@ services:security_opt: ["no-new-privileges:true"]restart: unless-stoppedstop_grace_period: 15s+ environment:+ TETHER_BLUEZ_SECURE_CONNECTIONS: ${TETHER_BLUEZ_SECURE_CONNECTIONS:?Confirm host Secure Connections is enabled}volumes:- type: bindsource: ${TETHER_DATA_DIR:?Set an absolute private host data directory}diff --git a/src/core/include/tether/bluetooth/monitor.hpp b/src/core/include/tether/bluetooth/monitor.hppindex 50f52be..ac6099f 100644--- a/src/core/include/tether/bluetooth/monitor.hpp+++ b/src/core/include/tether/bluetooth/monitor.hpp@@ -63,8 +63,9 @@ namespace tether::bluetooth {extern BluezMonitor* g_bluez;// BlueZ exposes Secure Connections only through the management interface.- // Runs btmgmt without a shell and returns no value if it fails or exceeds the- // deadline. Public so the process boundary and timeout can be tested directly.+ // Reads TETHER_BLUEZ_SECURE_CONNECTIONS when supplied by a container+ // orchestrator, otherwise runs btmgmt and returns no value if it fails or+ // exceeds the deadline. Public so the process boundary can be tested directly.std::optional<bool> probe_secure_connections(const std::string& adapter_id,std::chrono::milliseconds timeout = std::chrono::seconds(1));diff --git a/src/core/include/tether/bluetooth/pairing.hpp b/src/core/include/tether/bluetooth/pairing.hppindex d470c36..63ea17d 100644--- a/src/core/include/tether/bluetooth/pairing.hpp+++ b/src/core/include/tether/bluetooth/pairing.hpp@@ -31,6 +31,10 @@ namespace tether::bluetooth {// at all. Device1.Pair() involves no profile.bool should_fall_back(AuthStrategy tried, bool paired, bool confirmation_failed);+ // Connect-first must select the BR/EDR profile path. Leaving BlueZ on+ // "last-used" can make it try LE first, which cannot induce Classic pairing.+ const char* preferred_bearer_for(AuthStrategy strategy);+// Whether a finished tether-dialog answered one way or another.bool dialog_answered(int wait_status);diff --git a/src/core/src/bluetooth/monitor.cpp b/src/core/src/bluetooth/monitor.cppindex 35504cd..d00aed0 100644--- a/src/core/src/bluetooth/monitor.cpp+++ b/src/core/src/bluetooth/monitor.cpp@@ -8,12 +8,14 @@#include <chrono>#include <condition_variable>#include <csignal>+#include <cstdlib>#include <fcntl.h>#include <gio/gio.h>#include <map>#include <mutex>#include <optional>#include <poll.h>+#include <string_view>#include <sys/eventfd.h>#include <sys/wait.h>#include <thread>@@ -168,9 +170,28 @@ namespace tether::bluetooth {g_source_unref(source);}+ namespace {+ std::optional<bool> environment_flag(const char* name) {+ const char* raw = std::getenv(name);+ if (!raw)+ return std::nullopt;++ const std::string_view value(raw);+ if (value == "1" || value == "true" || value == "yes" || value == "on")+ return true;+ if (value == "0" || value == "false" || value == "no" || value == "off")+ return false;++ debug::log(WARN, "bluetooth: ignoring invalid {}={}", name, value);+ return std::nullopt;+ }+ } // namespace+std::optional<bool> probe_secure_connections(const std::string& adapter_id, std::chrono::milliseconds timeout) {if (adapter_id.empty())return std::nullopt;+ if (const auto configured = environment_flag("TETHER_BLUEZ_SECURE_CONNECTIONS"))+ return configured;std::array<gchar*, 5> argv = {const_cast<gchar*>("btmgmt"),diff --git a/src/core/src/bluetooth/pairing.cpp b/src/core/src/bluetooth/pairing.cppindex 43f427f..d56e126 100644--- a/src/core/src/bluetooth/pairing.cpp+++ b/src/core/src/bluetooth/pairing.cpp@@ -18,6 +18,7 @@ namespace tether::bluetooth {namespace {constexpr const char* BLUEZ_NAME = "org.bluez";+ constexpr const char* OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager";constexpr const char* IFACE_DEVICE = "org.bluez.Device1";constexpr const char* IFACE_ADAPTER = "org.bluez.Adapter1";constexpr const char* IFACE_PROPS = "org.freedesktop.DBus.Properties";@@ -118,6 +119,40 @@ namespace tether::bluetooth {return false;}+ // Pairing retries must not use the debounced monitor snapshot: a failed+ // Connect() can make BlueZ remove and recreate Device1 between attempts.+ // Resolve the object tree synchronously so Pair() never targets the path+ // of an object that has already disappeared.+ bool lookup_live(GDBusConnection* conn, const std::string& address, Device& out) {+ GError* error = nullptr;+ GVariant* reply = g_dbus_connection_call_sync(conn,+ BLUEZ_NAME,+ "/",+ OBJECT_MANAGER,+ "GetManagedObjects",+ nullptr,+ G_VARIANT_TYPE("(a{oa{sa{sv}}})"),+ G_DBUS_CALL_FLAGS_NONE,+ 5000,+ nullptr,+ &error);+ if (!reply) {+ debug::log(WARN,+ "bluetooth: could not refresh devices before pairing: {}",+ error ? error->message : "unknown error");+ g_clear_error(&error);+ return false;+ }++ BluezObjects objects = parse_managed_objects(reply);+ g_variant_unref(reply);+ if (const Device* device = find_by_address(objects, address)) {+ out = *device;+ return true;+ }+ return false;+ }+bool call_adapter(GDBusConnection* conn,const std::string& path,const char* method,@@ -194,7 +229,7 @@ namespace tether::bluetooth {const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(DISCOVERY_TIMEOUT_SECONDS);bool found = false;while (std::chrono::steady_clock::now() < deadline) {- if (lookup(monitor, address, out)) {+ if (lookup_live(conn, address, out)) {found = true;break;}@@ -544,6 +579,10 @@ namespace tether::bluetooth {return tried == AuthStrategy::ConnectFirst && !paired && !confirmation_failed;}+ const char* preferred_bearer_for(AuthStrategy strategy) {+ return strategy == AuthStrategy::ConnectFirst ? "bredr" : nullptr;+ }+PairResult pair_device(BluezMonitor& monitor,const std::string& address,AuthStrategy strategy,@@ -652,10 +691,43 @@ namespace tether::bluetooth {std::this_thread::sleep_for(std::chrono::seconds(2));};+ auto refresh_device = [&] {+ if (lookup_live(conn, result.device_address, device)) {+ result.device_path = device.path;+ return true;+ }++ notify(progress, "rediscovering", result.device_address);+ if (discover(monitor, conn, result.device_address, device)) {+ result.device_path = device.path;+ return true;+ }++ err = "Device1 disappeared and could not be rediscovered";+ return false;+ };+// The agent stays registered across all attempts; re-registering// mid-transaction races BlueZ's own agent bookkeeping.auto attempt = [&](AuthStrategy how) {err.clear();+ if (!refresh_device()) {+ initiated = false;+ notify(progress, "error", err);+ return false;+ }++ if (const char* bearer = preferred_bearer_for(how)) {+ std::string bearer_err;+ if (!set_property(conn,+ device.path,+ IFACE_DEVICE,+ "PreferredBearer",+ g_variant_new_string(bearer),+ &bearer_err))+ debug::log(WARN, "bluetooth: could not select {} before pairing: {}", bearer, bearer_err);+ }+if (how == AuthStrategy::ConnectFirst) {notify(progress, "connecting", display_name);initiated = call_device(conn, device.path, "Connect", PAIR_TIMEOUT_SECONDS * 1000, err);diff --git a/test/test_bluetooth_monitor.cpp b/test/test_bluetooth_monitor.cppindex 6d4b09b..c3f106d 100644--- a/test/test_bluetooth_monitor.cpp+++ b/test/test_bluetooth_monitor.cpp@@ -6,6 +6,7 @@#include <fcntl.h>#include <filesystem>#include <fstream>+#include <optional>#include <string>#include <sys/types.h>#include <unistd.h>@@ -15,6 +16,32 @@ using tether::bluetooth::probe_secure_connections;namespace {+ class ScopedEnvironment {+ public:+ ScopedEnvironment(const char* name, const char* value) : name_(name) {+ if (const char* current = std::getenv(name))+ old_value_ = current;+ if (value)+ setenv(name, value, 1);+ else+ unsetenv(name);+ }++ ~ScopedEnvironment() {+ if (old_value_)+ setenv(name_.c_str(), old_value_->c_str(), 1);+ else+ unsetenv(name_.c_str());+ }++ ScopedEnvironment(const ScopedEnvironment&) = delete;+ ScopedEnvironment& operator=(const ScopedEnvironment&) = delete;++ private:+ std::string name_;+ std::optional<std::string> old_value_;+ };+class FakeBtmgmt {public:explicit FakeBtmgmt(const std::string& body) {@@ -50,6 +77,17 @@ namespace {} // namespace+TEST(ContainerCapabilityHints, ReportsHostSecureConnectionsWithoutManagementTools) {+ {+ ScopedEnvironment secure("TETHER_BLUEZ_SECURE_CONNECTIONS", "true");+ EXPECT_EQ(probe_secure_connections("hci0", 1ms), true);+ }+ {+ ScopedEnvironment secure("TETHER_BLUEZ_SECURE_CONNECTIONS", "false");+ EXPECT_EQ(probe_secure_connections("hci0", 1ms), false);+ }+}+TEST(SecureConnectionsProbe, ParsesEnabledAndDisabledSettings) {{FakeBtmgmt fake("printf 'current settings: powered secure-conn bondable\\n'\n");diff --git a/test/test_bluetooth_pairing.cpp b/test/test_bluetooth_pairing.cppindex 633cf63..7cf8164 100644--- a/test/test_bluetooth_pairing.cpp+++ b/test/test_bluetooth_pairing.cpp@@ -145,6 +145,11 @@ TEST(BluetoothConfig, SurvivesCorruptFile) {// Connect-first induces authentication only as a side effect of a profile// connect. A phone that refuses that profile never starts pairing at all, so the// transaction is retried as an explicit Device1.Pair() -- see issue #49.+TEST(PairingBearer, ConnectFirstPinsTheClassicTransport) {+ EXPECT_STREQ(preferred_bearer_for(AuthStrategy::ConnectFirst), "bredr");+ EXPECT_EQ(preferred_bearer_for(AuthStrategy::ExplicitPair), nullptr);+}+TEST(FallbackPolicy, RetriesARefusedConnectFirst) {EXPECT_TRUE(should_fall_back(AuthStrategy::ConnectFirst, /*paired=*/false, /*user_rejected=*/false));}