Linux + iPhone Continuity / iMessage / SMS
feat(protocol): support external pairing clients
Nick Pisani950741aff945
diff --git a/src/cli/main.cpp b/src/cli/main.cppindex c41cc7f..cdc5a60 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -702,8 +702,12 @@ static int run_bt_transaction(tether::Client& client,const std::string result_command = command + "_result";client.send("{\"command\":\"subscribe\"}\n");+ static std::atomic<uint64_t> operation_sequence{0};+ const std::string operation_id =+ command + "-" + std::to_string(getpid()) + "-" + std::to_string(operation_sequence.fetch_add(1));nlohmann::json request;request["command"] = command;+ request["operation_id"] = operation_id;if (!address.empty())request["address"] = address;request.update(extra);@@ -737,6 +741,8 @@ static int run_bt_transaction(tether::Client& client,}const std::string cmd = event.value("command", "");+ if (event.contains("operation_id") && event.value("operation_id", "") != operation_id)+ continue;if (cmd == "bt_pair_progress") {fprintf(stdout, " %-12s %s\n", event.value("step", "").c_str(), event.value("detail", "").c_str());fflush(stdout);@@ -755,7 +761,10 @@ static int run_bt_transaction(tether::Client& client,fprintf(stdout, _("\n Cannot confirm the pairing code: input is not a terminal.\n"));fflush(stdout);}- client.send(nlohmann::json({{"command", "bt_pair_confirm"}, {"accept", accept}}).dump() + "\n");+ client.send(+ nlohmann::json({{"command", "bt_pair_confirm"}, {"operation_id", operation_id}, {"accept", accept}})+ .dump() ++ "\n");} else if (cmd == result_command) {fprintf(stdout, "\n%s\n", event.value("message", "").c_str());return event.value("success", false) ? 0 : 1;diff --git a/src/core/include/tether/bluetooth/objects.hpp b/src/core/include/tether/bluetooth/objects.hppindex 6d24e1d..63341f9 100644--- a/src/core/include/tether/bluetooth/objects.hpp+++ b/src/core/include/tether/bluetooth/objects.hpp@@ -63,6 +63,9 @@ namespace tether::bluetooth {std::vector<std::string> uuids;// Device1.Modalias, e.g. "bluetooth:v004Cp200Ed0100". Names the remote's vendor.std::string modalias;+ // Apple Nearby Info (company 0x004c, advertisement type 0x10) is+ // available before an unpaired iPhone exposes its service UUIDs.+ bool apple_nearby = false;bool ancs_notifying = false;diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hppindex 13d4b73..194c154 100644--- a/src/core/include/tether/net.hpp+++ b/src/core/include/tether/net.hpp@@ -73,6 +73,10 @@ namespace tether {std::string data_;};+ // Versioned control-protocol features. Clients use this to hide unsupported+ // controls instead of guessing from the daemon version.+ nlohmann::json build_protocol_info();+// Bluetooth state, read from the BluezMonitor snapshot.nlohmann::json build_bt_status();nlohmann::json build_bt_devices();diff --git a/src/core/src/bluetooth/objects.cpp b/src/core/src/bluetooth/objects.cppindex c525678..577c999 100644--- a/src/core/src/bluetooth/objects.cpp+++ b/src/core/src/bluetooth/objects.cpp@@ -103,6 +103,41 @@ namespace tether::bluetooth {return out;}+ bool has_apple_nearby_advertisement(GVariant* props) {+ GVariant* entries = lookup(props, "ManufacturerData");+ if (!entries || !g_variant_is_of_type(entries, G_VARIANT_TYPE("a{qv}"))) {+ if (entries)+ g_variant_unref(entries);+ return false;+ }++ bool found = false;+ GVariantIter iter;+ guint16 company = 0;+ GVariant* value = nullptr;+ g_variant_iter_init(&iter, entries);+ while (g_variant_iter_next(&iter, "{qv}", &company, &value)) {+ GVariant* payload = value;+ if (g_variant_is_of_type(value, G_VARIANT_TYPE_VARIANT)) {+ payload = g_variant_get_variant(value);+ g_variant_unref(value);+ }+ if (company == 0x004c && g_variant_is_of_type(payload, G_VARIANT_TYPE_BYTESTRING)) {+ gsize size = 0;+ const auto* bytes = static_cast<const guint8*>(g_variant_get_fixed_array(payload, &size, 1));+ // 0x10 is Apple's Nearby Info advertisement. Unlike the+ // service UUIDs it is visible while an unpaired iPhone is+ // still using a private rotating address.+ found = bytes && size > 0 && bytes[0] == 0x10;+ }+ g_variant_unref(payload);+ if (found)+ break;+ }+ g_variant_unref(entries);+ return found;+ }+// BlueZ nests the object path under the adapter, e.g.// /org/bluez/hci0/dev_AA_BB_.. the parent path is the owning adapter.std::string parent_path(const std::string& path) {@@ -220,6 +255,7 @@ namespace tether::bluetooth {d.connected = get_bool(props, "Connected");d.uuids = get_strv(props, "UUIDs");d.modalias = get_string(props, "Modalias");+ d.apple_nearby = has_apple_nearby_advertisement(props);d.preferred_bearer = get_string(props, "PreferredBearer");d.services_resolved = get_bool(props, "ServicesResolved");g_variant_unref(props);@@ -643,6 +679,7 @@ namespace tether::bluetooth {{"ancs_notifying", d.ancs_notifying},{"services_resolved", d.services_resolved},{"iphone", d.looks_like_iphone()},+ {"apple_nearby", d.apple_nearby},{"airpods", d.looks_like_airpods()},};}diff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex 8c89534..4647717 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -377,6 +377,25 @@ namespace tether {{"profile_reason", ""}};}+ nlohmann::json build_protocol_info() {+ return {{"command", "protocol_info"},+ {"version", 1},+ {"capabilities",+ {"airpods",+ "bluetooth.connection",+ "bluetooth.diagnostics",+ "bluetooth.pairing",+ "calls",+ "clipboard",+ "contacts",+ "files",+ "messages",+ "notifications",+ "otp",+ "peers",+ "settings"}}};+ }+nlohmann::json build_bt_status() {nlohmann::json status;status["command"] = "bt_status";@@ -531,6 +550,7 @@ namespace tether {static std::mutex g_bt_confirm_mutex;static std::condition_variable g_bt_confirm_cv;static int g_bt_confirm_answer = -1; // -1 pending, 0 declined, 1 accepted+ static std::string g_bt_confirm_operation_id;// A second StartDiscovery while one is running just gets stopped early by the// first one's StopDiscovery.@@ -564,31 +584,43 @@ namespace tether {broadcast_local_event(event.dump());}+ static void set_operation_id(nlohmann::json& event, const std::string& operation_id) {+ if (!operation_id.empty())+ event["operation_id"] = operation_id;+ }+// Runs on the BlueZ monitor's GLib thread, same as the local dialog it replaces.- static bool ask_client_to_confirm(const std::string& code) {+ static bool ask_client_to_confirm(const std::string& code, const std::string& operation_id) {{std::lock_guard<std::mutex> lock(g_bt_confirm_mutex);g_bt_confirm_answer = -1;+ g_bt_confirm_operation_id = operation_id;}nlohmann::json event;event["command"] = "bt_pair_confirm_request";event["code"] = code;+ set_operation_id(event, operation_id);broadcast_local_event(event.dump());std::unique_lock<std::mutex> lock(g_bt_confirm_mutex);g_bt_confirm_cv.wait_for(lock, std::chrono::seconds(BT_CONFIRM_TIMEOUT_SECONDS), [] { return g_bt_confirm_answer >= 0; });- return g_bt_confirm_answer == 1;+ const bool accepted = g_bt_confirm_answer == 1;+ g_bt_confirm_operation_id.clear();+ return accepted;}- static void run_bt_pair(const std::string& address, std::optional<bluetooth::AuthStrategy> strategy) {+ static void run_bt_pair(const std::string& address,+ std::optional<bluetooth::AuthStrategy> strategy,+ const std::string& operation_id) {if (!bluetooth::g_bluez) {nlohmann::json event;event["command"] = "bt_pair_result";event["success"] = false;event["status"] = "error";event["message"] = _("Bluetooth is unavailable.");+ set_operation_id(event, operation_id);broadcast_local_event(event.dump());return;}@@ -599,6 +631,7 @@ namespace tether {event["success"] = false;event["status"] = "busy";event["message"] = _("Another pairing attempt is already in progress.");+ set_operation_id(event, operation_id);broadcast_local_event(event.dump());return;}@@ -608,14 +641,15 @@ namespace tether {*bluetooth::g_bluez,address,strategy.value_or(config.auth_strategy),- [](const std::string& step, const std::string& detail) {+ [operation_id](const std::string& step, const std::string& detail) {nlohmann::json event;event["command"] = "bt_pair_progress";event["step"] = step;event["detail"] = detail;+ set_operation_id(event, operation_id);broadcast_local_event(event.dump());},- ask_client_to_confirm,+ [operation_id](const std::string& code) { return ask_client_to_confirm(code, operation_id); },config.calls_enabled);if (result.success) {@@ -635,7 +669,9 @@ namespace tether {}g_bt_pair_busy = false;- broadcast_local_event(bluetooth::to_json(result).dump());+ nlohmann::json event = bluetooth::to_json(result);+ set_operation_id(event, operation_id);+ broadcast_local_event(event.dump());broadcast_local_event(build_bt_status().dump());}@@ -645,12 +681,19 @@ namespace tether {broadcast_local_event(build_bt_status().dump());}- static void run_bt_unpair(const std::string& address) {- if (!bluetooth::g_bluez)+ static void run_bt_unpair(const std::string& address, const std::string& operation_id) {+ if (!bluetooth::g_bluez) {+ nlohmann::json event{{"command", "bt_unpair_result"},+ {"success", false},+ {"message", _("Bluetooth is unavailable.")}};+ set_operation_id(event, operation_id);+ broadcast_local_event(event.dump());return;+ }auto result = bluetooth::unpair_device(*bluetooth::g_bluez, address);nlohmann::json event = bluetooth::to_json(result);event["command"] = "bt_unpair_result";+ set_operation_id(event, operation_id);broadcast_local_event(event.dump());broadcast_local_event(build_bt_status().dump());}@@ -1145,6 +1188,7 @@ namespace tether {if (j.contains("command") && j["command"] == "subscribe") {register_local_subscriber(client_fd);+ write_plain_packet(client_fd, build_protocol_info().dump() + "\n");std::string payload = build_local_state_snapshot().dump() + "\n";write_plain_packet(client_fd, payload);@@ -1160,6 +1204,9 @@ namespace tether {std::string payload = "{\"command\":\"unsubscribed\"}\n";write_plain_packet(client_fd, payload);continue;+ } else if (j.contains("command") && j["command"] == "protocol_info") {+ write_plain_packet(client_fd, build_protocol_info().dump() + "\n");+ continue;} else if (j.contains("command") && j["command"] == "state_snapshot") {std::string payload = build_local_state_snapshot().dump() + "\n";write_plain_packet(client_fd, payload);@@ -1221,16 +1268,25 @@ namespace tether {std::optional<bluetooth::AuthStrategy> strategy;if (j.contains("strategy"))strategy = bluetooth::auth_strategy_from_string(j["strategy"]);- std::thread([address, strategy]() { run_bt_pair(address, strategy); }).detach();+ const std::string operation_id = j.value("operation_id", std::string{});+ std::thread([address, strategy, operation_id]() {+ run_bt_pair(address, strategy, operation_id);+ }).detach();} else if (j.contains("command") && j["command"] == "bt_pair_confirm") {+ bool matched = false;{std::lock_guard<std::mutex> lock(g_bt_confirm_mutex);- g_bt_confirm_answer = j.value("accept", false) ? 1 : 0;+ const std::string operation_id = j.value("operation_id", std::string{});+ matched = g_bt_confirm_operation_id.empty() || operation_id == g_bt_confirm_operation_id;+ if (matched)+ g_bt_confirm_answer = j.value("accept", false) ? 1 : 0;}- g_bt_confirm_cv.notify_all();+ if (matched)+ g_bt_confirm_cv.notify_all();} else if (j.contains("command") && j["command"] == "bt_unpair" && j.contains("address")) {std::string address = j["address"];- std::thread([address]() { run_bt_unpair(address); }).detach();+ const std::string operation_id = j.value("operation_id", std::string{});+ std::thread([address, operation_id]() { run_bt_unpair(address, operation_id); }).detach();} else if (j.contains("command") && j["command"] == "bt_airpods_connect" && j.contains("address")) {std::string address = j["address"];const bool connect = j.value("connect", true);diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cppindex 3b10edb..be67ee6 100644--- a/src/gtk/devices_view.cpp+++ b/src/gtk/devices_view.cpp@@ -92,6 +92,7 @@ namespace tether::ui {GtkWidget* btn_bt_solicit = nullptr;GtkWidget* chk_bt_enabled = nullptr;GtkWidget* btn_bt_unpair = nullptr;+ std::string bt_operation_id;GtkWidget* lbl_welcome_wifi = nullptr;GtkWidget* lbl_welcome_bt = nullptr;@@ -617,10 +618,21 @@ namespace tether::ui {daemon_send(j);}+ std::string new_bt_operation_id() {+ gchar* uuid = g_uuid_string_random();+ std::string operation_id = uuid;+ g_free(uuid);+ return operation_id;+ }+void on_bt_pair_click(GtkWidget*, gpointer) {if (g_devices.selected_bt_address.empty())return;- if (!daemon_send({{"command", "bt_pair"}, {"address", g_devices.selected_bt_address}})) {+ g_devices.bt_operation_id = new_bt_operation_id();+ if (!daemon_send({{"command", "bt_pair"},+ {"address", g_devices.selected_bt_address},+ {"operation_id", g_devices.bt_operation_id}})) {+ g_devices.bt_operation_id.clear();set_bt_progress(_("Could not reach the Tether daemon."));return;}@@ -647,7 +659,10 @@ namespace tether::ui {if (!confirmed)return;- daemon_send({{"command", "bt_unpair"}, {"address", g_devices.selected_bt_address}});+ g_devices.bt_operation_id = new_bt_operation_id();+ daemon_send({{"command", "bt_unpair"},+ {"address", g_devices.selected_bt_address},+ {"operation_id", g_devices.bt_operation_id}});set_bt_progress(_("Removing the pairing\u2026"));}@@ -1123,6 +1138,11 @@ namespace tether::ui {bool devices_view_handle_event(const nlohmann::json& event) {const std::string command = event.value("command", "");+ const bool pairing_event = command == "bt_pair_progress" || command == "bt_pair_confirm_request" ||+ command == "bt_pair_result" || command == "bt_unpair_result";+ if (pairing_event && event.contains("operation_id") &&+ (g_devices.bt_operation_id.empty() || event.value("operation_id", "") != g_devices.bt_operation_id))+ return false;if (command == "state_snapshot") {apply_state_snapshot(event);return true;@@ -1407,7 +1427,9 @@ namespace tether::ui {code->c_str());const bool confirmed = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK;gtk_widget_destroy(dialog);- daemon_send({{"command", "bt_pair_confirm"}, {"accept", confirmed}});+ daemon_send({{"command", "bt_pair_confirm"},+ {"operation_id", g_devices.bt_operation_id},+ {"accept", confirmed}});return G_SOURCE_REMOVE;},new std::string(event.value("code", "")));@@ -1426,6 +1448,7 @@ namespace tether::ui {}if (command == "bt_pair_result" || command == "bt_unpair_result") {gtk_widget_set_sensitive(g_devices.btn_bt_pair, TRUE);+ g_devices.bt_operation_id.clear();set_bt_progress(event.value("message", ""));// The bond and the supervised device both just changed.daemon_send({{"command", "bt_status"}});diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cppindex c7f14f0..18d9914 100644--- a/test/test_bluetooth_objects.cpp+++ b/test/test_bluetooth_objects.cpp@@ -165,6 +165,46 @@ TEST(BluetoothObjects, ParsesDeviceAndBearer) {EXPECT_TRUE(d.looks_like_iphone());}+TEST(BluetoothObjects, RecognizesAnUnpairedAppleNearbyAdvertisement) {+ Payload p(R"({+ '/org/bluez/hci0/dev_40_F6_64_3D_7A_F1': {+ 'org.bluez.Device1': {+ 'Address': <'40:F6:64:3D:7A:F1'>,+ 'AddressType': <'random'>,+ 'Alias': <'40-F6-64-3D-7A-F1'>,+ 'ManufacturerData': <{uint16 76: <[byte 0x10, 0x06, 0x71, 0x1e]>}>,+ 'UUIDs': <@as []>+ }+ }+ })");+ auto objects = parse_managed_objects(p.v);++ ASSERT_EQ(objects.devices.size(), 1u);+ const auto encoded = to_json(objects.devices[0]);+ EXPECT_TRUE(encoded.value("apple_nearby", false));+ EXPECT_FALSE(objects.devices[0].looks_like_iphone());+}++TEST(BluetoothObjects, DoesNotTreatEveryManufacturerAdvertisementAsAPhoneCandidate) {+ Payload p(R"({+ '/org/bluez/hci0/dev_AA': {+ 'org.bluez.Device1': {+ 'ManufacturerData': <{uint16 76: <[byte 0x07, 0x19]>}>+ }+ },+ '/org/bluez/hci0/dev_BB': {+ 'org.bluez.Device1': {+ 'ManufacturerData': <{uint16 64: <[byte 0x10, 0x06]>}>+ }+ }+ })");+ auto objects = parse_managed_objects(p.v);++ ASSERT_EQ(objects.devices.size(), 2u);+ EXPECT_FALSE(to_json(objects.devices[0]).value("apple_nearby", false));+ EXPECT_FALSE(to_json(objects.devices[1]).value("apple_nearby", false));+}+TEST(BluetoothObjects, UuidMatchIsCaseInsensitive) {Payload p(R"({'/org/bluez/hci0/dev_AA': {diff --git a/test/test_net.cpp b/test/test_net.cppindex 4ba2918..36be78d 100644--- a/test/test_net.cpp+++ b/test/test_net.cpp@@ -20,6 +20,7 @@#include <sys/file.h>#include <sys/socket.h>#include <sys/stat.h>+#include <sys/un.h>#include <sys/wait.h>#include <thread>#include <unistd.h>@@ -75,6 +76,19 @@ namespace {};// Helper RAII class to manage process lifecycle+ class EventLoopGuard {+ public:+ explicit EventLoopGuard(tether::EpollEventLoop& loop) : loop_(loop), thread_([&loop] { loop.run(); }) {}+ ~EventLoopGuard() {+ loop_.post([this] { loop_.stop(); });+ thread_.join();+ }++ private:+ tether::EpollEventLoop& loop_;+ std::thread thread_;+ };+class ProcessGuard {public:ProcessGuard(pid_t pid) : pid_(pid) {}@@ -310,6 +324,109 @@ namespace {EXPECT_NE(log.find("::1"), std::string::npos) << "captured log:\n" << log;}+ std::string read_socket_line(int fd) {+ std::string line;+ for (char byte = 0; byte != '\n';) {+ const ssize_t count = recv(fd, &byte, 1, 0);+ if (count <= 0)+ return {};+ line.push_back(byte);+ }+ return line;+ }++ TEST(UnixServerTest, BluetoothResultsPreserveOperationId) {+ const std::string runtime_dir = unique_test_dir("tether_unix_operation_test");+ CleanupGuard cleanup_guard(runtime_dir);+ std::filesystem::remove_all(runtime_dir);+ std::filesystem::create_directories(runtime_dir);+ ScopedEnvVar xdg_runtime_dir("XDG_RUNTIME_DIR", runtime_dir);++ tether::EpollEventLoop loop;+ tether::TcpServer tcp_server(loop, 0);+ tether::UnixServer unix_server(loop, tcp_server);+ ASSERT_TRUE(unix_server.start());+ EventLoopGuard loop_guard(loop);++ const int client = socket(AF_UNIX, SOCK_STREAM, 0);+ ASSERT_GE(client, 0);+ timeval timeout{2, 0};+ ASSERT_EQ(setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)), 0);+ sockaddr_un address{};+ address.sun_family = AF_UNIX;+ std::snprintf(+ address.sun_path, sizeof(address.sun_path), "%s", (tether::get_runtime_dir() + "/tetherd.sock").c_str());+ ASSERT_EQ(connect(client, reinterpret_cast<sockaddr*>(&address), sizeof(address)), 0);++ const std::string subscribe = "{\"command\":\"subscribe\"}\n";+ ASSERT_EQ(write(client, subscribe.data(), subscribe.size()), static_cast<ssize_t>(subscribe.size()));+ ASSERT_FALSE(read_socket_line(client).empty());++ const std::string pair =+ "{\"command\":\"bt_pair\",\"address\":\"38:9C:B2:42:3F:E7\",\"operation_id\":\"web-pair-1\"}\n";+ ASSERT_EQ(write(client, pair.data(), pair.size()), static_cast<ssize_t>(pair.size()));++ nlohmann::json result;+ for (int event = 0; event < 8; ++event) {+ const std::string line = read_socket_line(client);+ if (line.empty())+ break;+ try {+ auto candidate = nlohmann::json::parse(line);+ if (candidate.value("command", "") == "bt_pair_result") {+ result = std::move(candidate);+ break;+ }+ } catch (...) {+ }+ }+ ASSERT_FALSE(result.is_null());+ EXPECT_EQ(result.value("operation_id", ""), "web-pair-1");++ const std::string unpair =+ "{\"command\":\"bt_unpair\",\"address\":\"38:9C:B2:42:3F:E7\",\"operation_id\":\"web-unpair-1\"}\n";+ ASSERT_EQ(write(client, unpair.data(), unpair.size()), static_cast<ssize_t>(unpair.size()));++ result = nullptr;+ for (int event = 0; event < 8; ++event) {+ const std::string line = read_socket_line(client);+ if (line.empty())+ break;+ try {+ auto candidate = nlohmann::json::parse(line);+ if (candidate.value("command", "") == "bt_unpair_result") {+ result = std::move(candidate);+ break;+ }+ } catch (...) {+ }+ }+ close(client);++ ASSERT_FALSE(result.is_null());+ EXPECT_EQ(result.value("operation_id", ""), "web-unpair-1");+ }++ TEST(ControlProtocolTest, AdvertisesVersionedCapabilities) {+ const auto info = tether::build_protocol_info();+ EXPECT_EQ(info.value("command", ""), "protocol_info");+ EXPECT_EQ(info.value("version", 0), 1);+ EXPECT_EQ(info.at("capabilities"),+ nlohmann::json({"airpods",+ "bluetooth.connection",+ "bluetooth.diagnostics",+ "bluetooth.pairing",+ "calls",+ "clipboard",+ "contacts",+ "files",+ "messages",+ "notifications",+ "otp",+ "peers",+ "settings"}));+ }+TEST(ClientTest, ConnectsToAnIpv6Literal) {const std::string home = unique_test_dir("tether_client_v6_test");CleanupGuard cleanup_guard(home);