Linux + iPhone Continuity / iMessage / SMS
fix: listen on ipv6 dual-stack where available
Zack Bartel755622c2bb97
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdindex 2698ac6..b7b2841 100644--- a/docs/PROTOCOL.md+++ b/docs/PROTOCOL.md@@ -126,7 +126,7 @@ For local Unix clients, `tetherd` returns `file_status` once the stream has been## 3. Device Pairing (TLS + fingerprint pinning)-The `tetherd` daemon binds `0.0.0.0:5134` and speaks TLS 1.2. Both sides present a self-signed X.509 certificate; there is no CA in this system, so certificates are **not** validated against any trust anchor.+The `tetherd` daemon binds `[::]:5134` dual-stack (falling back to `0.0.0.0:5134` where IPv6 is unavailable) and speaks TLS 1.2. Both sides present a self-signed X.509 certificate; there is no CA in this system, so certificates are **not** validated against any trust anchor.Access control is trust-on-first-use fingerprint pinning. After the handshake the daemon takes the SHA-256 fingerprint of the peer's certificate and looks it up in `known_hosts.json`. A client whose fingerprint is not pinned may only send `pair_request` — any other command is answered with `{"command":"error","message":"unauthorized"}`.diff --git a/src/core/src/client.cpp b/src/core/src/client.cppindex 707c2ff..65d7de0 100644--- a/src/core/src/client.cpp+++ b/src/core/src/client.cpp@@ -1,6 +1,5 @@#include "tether/client.hpp"#include "tether/base64.hpp"-#include "tether/core.hpp"#include "tether/crypto.hpp"#include "tether/net.hpp"@@ -10,6 +9,7 @@#include <cstring>#include <filesystem>#include <fstream>+#include <netdb.h>#include <nlohmann/json.hpp>#include <sys/socket.h>#include <sys/un.h>@@ -125,21 +125,32 @@ namespace tether {disconnect();if (!host.empty()) {- sockaddr_in addr{};- addr.sin_family = AF_INET;- addr.sin_port = htons(port);- if (inet_pton(AF_INET, host.c_str(), &addr.sin_addr) != 1) {- debug::log(ERR, "Invalid IPv4 address: {}", host);+ addrinfo hints{};+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;++ addrinfo* results = nullptr;+ const std::string service = std::to_string(port);+ if (int err = getaddrinfo(host.c_str(), service.c_str(), &hints, &results); err != 0 || !results) {+ debug::log(ERR, "Invalid address {}: {}", host, gai_strerror(err));return false;}- sock_ = socket(AF_INET, SOCK_STREAM, 0);- if (sock_ < 0) {- debug::log(ERR, "Failed to create socket: {}", std::strerror(errno));- return false;+ for (addrinfo* ai = results; ai; ai = ai->ai_next) {+ sock_ = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);+ if (sock_ < 0)+ continue;+ if (::connect(sock_, ai->ai_addr, ai->ai_addrlen) == 0)+ break;+ close(sock_);+ sock_ = -1;}+ const int connect_errno = errno;+ freeaddrinfo(results);- if (::connect(sock_, (sockaddr*)&addr, sizeof(addr)) < 0) {+ if (sock_ < 0) {+ debug::log(ERR, "Failed to connect to {}:{}: {}", host, port, std::strerror(connect_errno));return false;}diff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex deb7a17..baca121 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -5,6 +5,8 @@#include <csignal>#include <errno.h>#include <fcntl.h>+#include <netdb.h>+#include <netinet/in.h>#include <sys/file.h>#include <sys/socket.h>#include <sys/stat.h>@@ -1184,39 +1186,69 @@ namespace tether {TcpServer::~TcpServer() { stop(); }- bool TcpServer::start() {- server_fd_ = socket(AF_INET, SOCK_STREAM, 0);- if (server_fd_ < 0) {- debug::log(ERR, "Failed to create tcp socket");- return false;- }+ // 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);+ if (fd < 0)+ return -1;int opt = 1;- if (setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0) {+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0) {debug::log(ERR, "TcpServer setsockopt reuse failed");}// Set non-blocking- int flags = fcntl(server_fd_, F_GETFL, 0);- fcntl(server_fd_, F_SETFL, flags | O_NONBLOCK);+ int flags = fcntl(fd, F_GETFL, 0);+ fcntl(fd, F_SETFL, flags | O_NONBLOCK);++ sockaddr_storage ss{};+ socklen_t len = 0;+ if (family == AF_INET6) {+ int off = 0;+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off)) < 0) {+ int err = errno;+ close(fd);+ errno = err;+ return -1;+ }+ auto* a6 = reinterpret_cast<sockaddr_in6*>(&ss);+ a6->sin6_family = AF_INET6;+ a6->sin6_addr = in6addr_any;+ a6->sin6_port = htons(port);+ len = sizeof(*a6);+ } else {+ auto* a4 = reinterpret_cast<sockaddr_in*>(&ss);+ a4->sin_family = AF_INET;+ a4->sin_addr.s_addr = INADDR_ANY;+ a4->sin_port = htons(port);+ len = sizeof(*a4);+ }++ if (bind(fd, reinterpret_cast<sockaddr*>(&ss), len) < 0 || listen(fd, SOMAXCONN) < 0) {+ int err = errno;+ close(fd);+ errno = err;+ return -1;+ }- sockaddr_in addr{};- addr.sin_family = AF_INET;- addr.sin_addr.s_addr = INADDR_ANY;- addr.sin_port = htons(bind_port_);+ return fd;+ }- if (bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {- debug::log(ERR, "Failed to bind tcp socket on port {}: {}", bind_port_, std::strerror(errno));- return false;+ bool TcpServer::start() {+ bool dual_stack = true;+ server_fd_ = bind_listen_socket(AF_INET6, bind_port_);+ if (server_fd_ < 0) {+ dual_stack = false;+ server_fd_ = bind_listen_socket(AF_INET, bind_port_);}- if (listen(server_fd_, SOMAXCONN) < 0) {- debug::log(ERR, "Failed to listen on tcp socket");+ if (server_fd_ < 0) {+ debug::log(ERR, "Failed to listen on tcp port {}: {}", bind_port_, std::strerror(errno));return false;}loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });- debug::log(INFO, "TcpServer listening on 0.0.0.0:{}", bind_port_);+ debug::log(INFO, "TcpServer listening on {}:{}", dual_stack ? "[::]" : "0.0.0.0", bind_port_);return true;}@@ -1250,8 +1282,27 @@ namespace tether {}}+ // Text form of an accepted peer.+ static std::string peer_ip(const sockaddr_storage& ss, socklen_t len) {+ if (ss.ss_family == AF_INET6) {+ const auto* a6 = reinterpret_cast<const sockaddr_in6*>(&ss);+ if (IN6_IS_ADDR_V4MAPPED(&a6->sin6_addr)) {+ char ip[INET_ADDRSTRLEN] = {};+ if (inet_ntop(AF_INET, &a6->sin6_addr.s6_addr[12], ip, sizeof(ip)))+ return ip;+ return "unknown";+ }+ }++ char host[NI_MAXHOST] = {};+ if (getnameinfo(reinterpret_cast<const sockaddr*>(&ss), len, host, sizeof(host), nullptr, 0, NI_NUMERICHOST) !=+ 0)+ return "unknown";+ return host;+ }+void TcpServer::handle_accept(int fd) {- sockaddr_in client_addr{};+ sockaddr_storage client_addr{};socklen_t addrlen = sizeof(client_addr);int client_fd = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen);if (client_fd < 0)@@ -1261,8 +1312,7 @@ namespace tether {int flags = fcntl(client_fd, F_GETFL, 0);fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);- char ip[INET_ADDRSTRLEN];- inet_ntop(AF_INET, &(client_addr.sin_addr), ip, INET_ADDRSTRLEN);+ const std::string ip = peer_ip(client_addr, addrlen);debug::log(INFO, "TcpServer: New connection from {} (fd: {})", ip, client_fd);// SSL Wrappingdiff --git a/test/test_net.cpp b/test/test_net.cppindex b14e167..69cdafe 100644--- a/test/test_net.cpp+++ b/test/test_net.cpp@@ -1,5 +1,6 @@#include <gtest/gtest.h>+#include <tether/client.hpp>#include <tether/crypto.hpp>#include <tether/event_loop.hpp>#include <tether/log.hpp>@@ -13,6 +14,7 @@#include <fcntl.h>#include <filesystem>#include <fstream>+#include <netinet/in.h>#include <sstream>#include <sys/file.h>#include <sys/socket.h>@@ -240,4 +242,89 @@ namespace {EXPECT_NE(log.find("127.0.0.1"), std::string::npos) << "captured log:\n" << log;}+ // The daemon advertises AAAA records over mDNS, so it has to accept on IPv6.+ TEST(TcpServerTest, AcceptsIpv6Clients) {+ const std::string home = unique_test_dir("tether_net_v6_test");+ CleanupGuard cleanup_guard(home);+ std::filesystem::remove_all(home);+ std::filesystem::create_directories(home);+ ScopedEnvVar home_env("HOME", home);+ ASSERT_TRUE(tether::Crypto::instance().init());++ constexpr int port = 45135;+ tether::EpollEventLoop loop;+ tether::TcpServer server(loop, port);+ if (!server.start())+ GTEST_SKIP() << "port " << port << " is unavailable";++ CerrCapture captured;+ std::thread loop_thread([&loop] { loop.run(); });++ const int client = socket(AF_INET6, SOCK_STREAM, 0);+ bool connected = false;+ if (client >= 0) {+ sockaddr_in6 addr{};+ addr.sin6_family = AF_INET6;+ addr.sin6_port = htons(port);+ addr.sin6_addr = in6addr_loopback;+ connected = connect(client, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0;+ }++ std::string log;+ if (connected) {+ const char garbage[] = "this is not a tls client hello\n";+ EXPECT_GT(write(client, garbage, sizeof(garbage) - 1), 0);+ shutdown(client, SHUT_RDWR);++ for (int attempt = 0; attempt < 200; ++attempt) {+ log = captured.str();+ if (log.find("TLS handshake failed") != std::string::npos)+ break;+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ }+ }+ if (client >= 0)+ close(client);++ loop.post([&loop] { loop.stop(); });+ loop_thread.join();+ captured.restore();++ if (!connected)+ GTEST_SKIP() << "no IPv6 loopback on this host";++ EXPECT_NE(log.find("TLS handshake failed"), std::string::npos) << "captured log:\n" << log;+ EXPECT_NE(log.find("::1"), std::string::npos) << "captured log:\n" << log;+ }++ TEST(ClientTest, ConnectsToAnIpv6Literal) {+ const std::string home = unique_test_dir("tether_client_v6_test");+ CleanupGuard cleanup_guard(home);+ std::filesystem::remove_all(home);+ std::filesystem::create_directories(home);+ ScopedEnvVar home_env("HOME", home);+ ASSERT_TRUE(tether::Crypto::instance().init());++ constexpr int port = 45136;+ tether::EpollEventLoop loop;+ tether::TcpServer server(loop, port);+ if (!server.start())+ GTEST_SKIP() << "port " << port << " is unavailable";++ std::thread loop_thread([&loop] { loop.run(); });++ tether::Client client;+ const bool connected = client.connect("::1", port);+ client.disconnect();++ tether::Client bogus;+ EXPECT_FALSE(bogus.connect("not-an-address", port));++ loop.post([&loop] { loop.stop(); });+ loop_thread.join();++ if (!connected)+ GTEST_SKIP() << "no IPv6 loopback on this host";+ }+} // namespace