Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: stale or pending pairing requests are not cleaned

Zack Bartel620a63112c79
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index d7adf9c..e42aa1c 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -264,6 +264,10 @@ Trusts a pending pair request by moving the target fingerprint into the daemon's
then replies with `{"command":"accept_device_result","accepted":true,"connected":true}`. `connected` is false
when the trust record was saved for a device that is no longer connected.
+A pending request expires an hour after it arrives, and an explicit rejection drops it at once. A peer
+that still wants to pair re-sends `pair_request` on its next connection, so the only thing a longer
+window buys is dead requests in the device list.
+
### `forget_device` (Local Client -> Daemon)
Removes a fingerprint from `known_hosts.json` and closes any live session holding it.
**Payload**: `{"command": "forget_device", "fingerprint": "12:aa:bb:cc..."}`
diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hpp
index 89a93f9..4c0a1d3 100644
--- a/src/core/include/tether/net.hpp
+++ b/src/core/include/tether/net.hpp
@@ -32,6 +32,10 @@ namespace tether {
void unregister_local_subscriber(int fd);
void broadcast_local_event(const std::string& msg, int exclude_fd = -1);
+ // Normalizes stored pairing requests to {fingerprint: {name, ts}} and drops
+ // the ones older than the TTL.
+ nlohmann::json prune_pending_pairs(const nlohmann::json& raw, int64_t now);
+
// Store an OTP and push it to local subscribers (browser extension, GTK).
// sender_domain is the registrable domain of the email sender, "" when the
// code did not come from email.
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index df91c30..11bcb42 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -36,6 +36,7 @@
#include <chrono>
#include <condition_variable>
#include <cstring>
+#include <ctime>
#include <filesystem>
#include <fstream>
#include <mutex>
@@ -284,27 +285,66 @@ namespace tether {
}
}
- static nlohmann::json load_pending_pairs() {
- std::string pending_path = get_runtime_dir() + "/pending_pairs.json";
- nlohmann::json pending = nlohmann::json::object();
+ // How long an unanswered pairing request stays offerable.
+ static constexpr int64_t PENDING_PAIR_TTL_SECONDS = 3600;
+
+ static void save_pending_pairs(const nlohmann::json& pending) {
+ std::ofstream ofs(get_runtime_dir() + "/pending_pairs.json");
+ ofs << pending.dump(4);
+ }
- std::ifstream ifs(pending_path);
- if (!ifs.is_open()) {
- return pending;
+ nlohmann::json prune_pending_pairs(const nlohmann::json& raw, int64_t now) {
+ nlohmann::json live = nlohmann::json::object();
+ if (!raw.is_object())
+ return live;
+
+ for (const auto& [fingerprint, value] : raw.items()) {
+ if (value.is_string()) {
+ live[fingerprint] = {{"name", value.get<std::string>()}, {"ts", now}};
+ continue;
+ }
+ if (!value.is_object() || !value.contains("name"))
+ continue;
+ if (now - value.value("ts", static_cast<int64_t>(0)) > PENDING_PAIR_TTL_SECONDS)
+ continue;
+ live[fingerprint] = value;
}
+ return live;
+ }
+
+ // Expired entries are dropped on read rather than on a timer.
+ static nlohmann::json load_pending_pairs() {
+ std::ifstream ifs(get_runtime_dir() + "/pending_pairs.json");
+ if (!ifs.is_open())
+ return nlohmann::json::object();
+ nlohmann::json raw;
try {
- pending = nlohmann::json::parse(ifs);
+ raw = nlohmann::json::parse(ifs);
} catch (...) {
- pending = nlohmann::json::object();
+ return nlohmann::json::object();
}
+ ifs.close();
- return pending;
+ nlohmann::json live = prune_pending_pairs(raw, static_cast<int64_t>(std::time(nullptr)));
+ if (live.size() != raw.size() || live != raw)
+ save_pending_pairs(live);
+ return live;
}
- static void save_pending_pairs(const nlohmann::json& pending) {
- std::ofstream ofs(get_runtime_dir() + "/pending_pairs.json");
- ofs << pending.dump(4);
+ static std::string pending_pair_name(const nlohmann::json& pending, const std::string& fingerprint) {
+ if (!pending.contains(fingerprint))
+ return "";
+ return pending[fingerprint].value("name", "");
+ }
+
+ // A request that was answered, or whose peer has gone, is not pending.
+ static void erase_pending_pair(const std::string& fingerprint) {
+ auto pending = load_pending_pairs();
+ if (!pending.contains(fingerprint))
+ return;
+ pending.erase(fingerprint);
+ save_pending_pairs(pending);
}
static std::string lookup_known_host_name(const std::string& fingerprint) {
@@ -757,10 +797,11 @@ namespace tether {
nlohmann::json pending_pairs = nlohmann::json::array();
auto pending = load_pending_pairs();
- for (auto& [fingerprint, name_value] : pending.items()) {
+ for (auto& [fingerprint, entry] : pending.items()) {
nlohmann::json item;
item["fingerprint"] = fingerprint;
- item["device_name"] = name_value.is_string() ? name_value.get<std::string>() : "Unknown Device";
+ const std::string name = entry.value("name", "");
+ item["device_name"] = name.empty() ? "Unknown Device" : name;
pending_pairs.push_back(item);
}
snapshot["pending_pairs"] = pending_pairs;
@@ -978,7 +1019,7 @@ namespace tether {
UnixServer::~UnixServer() { stop(); }
bool UnixServer::start() {
- server_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
+ server_fd_ = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (server_fd_ < 0) {
debug::log(ERR, "Failed to create unix socket");
return false;
@@ -1041,7 +1082,7 @@ namespace tether {
}
void UnixServer::handle_accept(int fd) {
- int client_fd = accept(fd, nullptr, nullptr);
+ int client_fd = accept4(fd, nullptr, nullptr, SOCK_CLOEXEC);
if (client_fd < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
debug::log(ERR, "UnixServer accept error: {}", std::strerror(errno));
@@ -1597,7 +1638,10 @@ namespace tether {
// Binds and listens on the wildcard address of `family`. AF_INET6 socket dual-stack.
static int bind_listen_socket(int family, int port) {
- int fd = socket(family, SOCK_STREAM, 0);
+ // CLOEXEC: the pairing dialog is fork+exec'd from this process and must
+ // not inherit the listening socket, or it keeps the port bound and
+ // SO_REUSEPORT hands it connections it will never accept.
+ int fd = socket(family, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0)
return -1;
@@ -1721,7 +1765,7 @@ namespace tether {
void TcpServer::handle_accept(int fd) {
sockaddr_storage client_addr{};
socklen_t addrlen = sizeof(client_addr);
- int client_fd = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen);
+ int client_fd = accept4(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen, SOCK_CLOEXEC);
if (client_fd < 0)
return;
@@ -2057,19 +2101,9 @@ namespace tether {
// Persist the pending request so accept_device can retrieve the name
{
- std::string pending_path = get_runtime_dir() + "/pending_pairs.json";
- nlohmann::json pending;
- std::ifstream ifs(pending_path);
- if (ifs.is_open()) {
- try {
- pending = nlohmann::json::parse(ifs);
- } catch (...) {
- }
- ifs.close();
- }
- pending[print] = dev_name;
- std::ofstream ofs(pending_path);
- ofs << pending.dump(4);
+ auto pending = load_pending_pairs();
+ pending[print] = {{"name", dev_name}, {"ts", static_cast<int64_t>(std::time(nullptr))}};
+ save_pending_pairs(pending);
}
char hostname[256] = {};
@@ -2269,8 +2303,8 @@ namespace tether {
std::string device_name = lookup_known_host_name(fingerprint);
if (device_name.empty())
device_name = fallback_name.empty() ? "Paired Device" : fallback_name;
- if (pending.contains(fingerprint) && pending[fingerprint].is_string()) {
- device_name = pending[fingerprint].get<std::string>();
+ if (const std::string pending_name = pending_pair_name(pending, fingerprint); !pending_name.empty()) {
+ device_name = pending_name;
pending.erase(fingerprint);
save_pending_pairs(pending);
}
@@ -2455,6 +2489,7 @@ namespace tether {
exit_code);
} else {
debug::log(INFO, "[Pairing Rejected] {} (exit code {})", info.device_name, exit_code);
+ erase_pending_pair(info.fingerprint);
auto remote_it = connected_remote_clients.find(info.client_fd);
auto ssl_it = active_ssl_.find(info.client_fd);
diff --git a/src/gtk/devices_view.cpp b/src/gtk/devices_view.cpp
index 3c1668a..64ad254 100644
--- a/src/gtk/devices_view.cpp
+++ b/src/gtk/devices_view.cpp
@@ -20,6 +20,7 @@ namespace tether::ui {
struct DevicesState {
std::vector<tether::DiscoveredDevice> discovered_devices;
+ std::vector<tether::DiscoveredDevice> unpaired_clients;
std::vector<tether::DiscoveredDevice> pending_pairing_requests;
std::vector<std::pair<std::string, std::string>> paired_devices; // fp, name
std::vector<std::string> connected_fps; // active connections
@@ -837,6 +838,7 @@ namespace tether::ui {
g_devices.clipboard_ok = j.value("clipboard_available", true);
g_devices.firewall_active = j.value("firewall_active", false);
g_devices.connected_fps.clear();
+ g_devices.unpaired_clients.clear();
if (j.contains("connected_clients") && j["connected_clients"].is_array()) {
for (auto& c : j["connected_clients"]) {
if (c.value("paired", false)) {
@@ -846,7 +848,7 @@ namespace tether::ui {
dev.fingerprint = c.value("fingerprint", "");
dev.name = c.value("device_name", _("Unknown Device"));
dev.addresses.push_back({c.value("address", ""), 5134});
- g_devices.discovered_devices.push_back(dev);
+ g_devices.unpaired_clients.push_back(dev);
}
}
}
@@ -1034,22 +1036,28 @@ namespace tether::ui {
}
}
- for (const auto& disc : g_devices.discovered_devices) {
- if (disc.fingerprint == my_fp)
- continue;
- bool is_paired = false;
- for (const auto& p : g_devices.paired_devices) {
- if (p.first == disc.fingerprint) {
- is_paired = true;
- break;
+ std::vector<std::string> shown_fps;
+ for (const auto* source : {&g_devices.discovered_devices, &g_devices.unpaired_clients}) {
+ for (const auto& disc : *source) {
+ if (disc.fingerprint == my_fp)
+ continue;
+ if (std::find(shown_fps.begin(), shown_fps.end(), disc.fingerprint) != shown_fps.end())
+ continue;
+ bool is_paired = false;
+ for (const auto& p : g_devices.paired_devices) {
+ if (p.first == disc.fingerprint) {
+ is_paired = true;
+ break;
+ }
}
+ if (is_paired)
+ continue; // already added above
+ shown_fps.push_back(disc.fingerprint);
+ std::string ip = disc.addresses.empty() ? "" : disc.addresses[0].address;
+ uint16_t port = disc.addresses.empty() ? 5134 : disc.addresses[0].port;
+ GtkWidget* r = create_row(disc.name, disc.fingerprint, ip, port, false, false);
+ discovered_rows.push_back(r);
}
- if (is_paired)
- continue; // already added above
- std::string ip = disc.addresses.empty() ? "" : disc.addresses[0].address;
- uint16_t port = disc.addresses.empty() ? 5134 : disc.addresses[0].port;
- GtkWidget* r = create_row(disc.name, disc.fingerprint, ip, port, false, false);
- discovered_rows.push_back(r);
}
// Render Pending Pair Requests
@@ -1064,15 +1072,8 @@ namespace tether::ui {
if (is_paired)
continue; // ignore if they successfully paired
- bool already_shown = false;
- for (const auto& disc : g_devices.discovered_devices) {
- if (disc.fingerprint == req.fingerprint) {
- already_shown = true;
- break;
- }
- }
- if (already_shown)
- continue; // ignore if mDNS already populated it
+ if (std::find(shown_fps.begin(), shown_fps.end(), req.fingerprint) != shown_fps.end())
+ continue; // ignore if mDNS or a live connection already populated it
std::string ip = req.addresses.empty() ? "" : req.addresses[0].address;
uint16_t port = req.addresses.empty() ? 5134 : req.addresses[0].port;
diff --git a/test/test_headless_runtime.cpp b/test/test_headless_runtime.cpp
index fcfcc3b..4f6649e 100644
--- a/test/test_headless_runtime.cpp
+++ b/test/test_headless_runtime.cpp
@@ -178,7 +178,26 @@ namespace {
}
throw std::runtime_error("child timed out");
}
+ // The fake phone dials a fixed 127.0.0.1:5134. A daemon already holding
+ // that port takes the pair requests instead, pops its dialogs at the
+ // user, and records the requests in the real runtime dir.
+ static bool port_5134_taken() {
+ int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return false;
+ sockaddr_in address{};
+ address.sin_family = AF_INET;
+ address.sin_port = htons(5134);
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ const bool taken = connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0;
+ close(fd);
+ return taken;
+ }
+
void start(Peer& local) {
+ if (port_5134_taken())
+ throw std::runtime_error(
+ "another tetherd is listening on 127.0.0.1:5134; stop it before running this suite");
spawn({"/usr/bin/dbus-daemon",
"--session",
"--nofork",
diff --git a/test/test_net.cpp b/test/test_net.cpp
index 414c510..4ba2918 100644
--- a/test/test_net.cpp
+++ b/test/test_net.cpp
@@ -598,3 +598,38 @@ TEST(ShouldDialPeer, SkipsUnknownIncompleteAndSelf) {
EXPECT_FALSE(tether::should_dial_peer("aaa", "", true)); // peer published no fp= TXT record
EXPECT_FALSE(tether::should_dial_peer("aaa", "aaa", true));
}
+
+// A pairing request whose peer never came back used to sit in the device list
+// forever, and every run of a test suite added another.
+TEST(PendingPairs, DropsRequestsPastTheTtl) {
+ const int64_t now = 1'700'000'000;
+ nlohmann::json raw;
+ raw["fresh"] = {{"name", "iPhone"}, {"ts", now - 60}};
+ raw["stale"] = {{"name", "test phone"}, {"ts", now - 7200}};
+
+ const auto live = tether::prune_pending_pairs(raw, now);
+ EXPECT_TRUE(live.contains("fresh"));
+ EXPECT_FALSE(live.contains("stale"));
+ EXPECT_EQ(live["fresh"]["name"], "iPhone");
+}
+
+TEST(PendingPairs, AgesTheLegacyBareNameFormatFromNow) {
+ const int64_t now = 1'700'000'000;
+ nlohmann::json raw;
+ raw["old"] = "iPhone";
+
+ const auto live = tether::prune_pending_pairs(raw, now);
+ ASSERT_TRUE(live.contains("old"));
+ EXPECT_EQ(live["old"]["name"], "iPhone");
+ EXPECT_EQ(live["old"]["ts"], now);
+ // Migrated, not immortal.
+ EXPECT_TRUE(tether::prune_pending_pairs(live, now + 7200).empty());
+}
+
+TEST(PendingPairs, IgnoresJunkEntries) {
+ nlohmann::json raw;
+ raw["no_name"] = {{"ts", 1}};
+ raw["wrong_type"] = 42;
+ EXPECT_TRUE(tether::prune_pending_pairs(raw, 1'700'000'000).empty());
+ EXPECT_TRUE(tether::prune_pending_pairs(nlohmann::json::array(), 1).empty());
+}