Linux + iPhone Continuity / iMessage / SMS
fix: daemon started before compositor will retry
Zack Bartel2948e6c7fb0d
diff --git a/docs/HEADLESS.md b/docs/HEADLESS.mdindex 2432a88..39d7be7 100644--- a/docs/HEADLESS.md+++ b/docs/HEADLESS.md@@ -131,7 +131,9 @@ launch a desktop dialog does not by itself reject or accept the request.`tether status` says `Clipboard: off, no Wayland session on this machine` andthat is the whole story: without a compositor there is no clipboard to sync. The-rest of the daemon does not care. If the machine does run a compositor and this+rest of the daemon does not care. A compositor that starts later, such as at+login after the unit started at boot, is picked up within a few seconds, with+or without `WAYLAND_DISPLAY`. If the machine does run a compositor and thisstill says off, the compositor is missing `wlr-data-control` or`ext-data-control`.diff --git a/src/core/include/tether/wayland.hpp b/src/core/include/tether/wayland.hppindex cd1c52f..017e482 100644--- a/src/core/include/tether/wayland.hpp+++ b/src/core/include/tether/wayland.hpp@@ -2,10 +2,12 @@#include "tether/clipboard.hpp"#include "tether/event_loop.hpp"+#include <filesystem>#include <functional>#include <memory>#include <mutex>#include <string>+#include <vector>class CCWlDisplay;class CCWlRegistry;@@ -21,8 +23,13 @@ namespace tether {WaylandContext(EpollEventLoop& loop);~WaylandContext();+ // Connects now if a compositor is up, otherwise keeps retrying on the loop.+ // False only means clipboard sync is not available yet.bool init();+ // Socket name of the connected compositor, empty while disconnected.+ const std::string& display_name() const { return display_name_; }+bool clipboard_available() const { return clipboard_ != nullptr; }void set_clipboard_callback(std::function<void(const std::string&)> cb);void set_clipboard_image_callback(std::function<void(const std::string&)> cb);@@ -32,11 +39,18 @@ namespace tether {std::string get_clipboard_image();private:+ bool connect_display();+ bool setup();+ void disconnect();+ void start_retry();+std::mutex clip_mutex_;std::string cached_clipboard_;std::string cached_clipboard_image_;EpollEventLoop& loop_;wl_display* raw_display_ = nullptr;+ std::string display_name_;+ int retry_fd_ = -1;std::unique_ptr<CCWlDisplay> display_;std::unique_ptr<CCWlRegistry> registry_;@@ -49,6 +63,9 @@ namespace tether {std::function<void(const std::string&)> clipboard_image_cb_;};+ // Sorted wayland-* socket names in runtime_dir, lock files and non-sockets skipped.+ std::vector<std::string> wayland_sockets(const std::filesystem::path& runtime_dir);+extern WaylandContext* g_wayland;} // namespace tetherdiff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex 7be90a6..cd97b82 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -704,9 +704,8 @@ namespace tether {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.")}};+ 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;@@ -1708,7 +1707,8 @@ namespace tether {: tr_format(_("Send failed: {}"), err.empty() ? _("unknown error") : err);} else {resp["success"] = false;- resp["message"] = tr_format(_("Send failed: {}"), _("Could not reach the Tether daemon."));+ resp["message"] =+ tr_format(_("Send failed: {}"), _("Could not reach the Tether daemon."));}broadcast_local_event(resp.dump());}).detach();@@ -2500,9 +2500,11 @@ namespace tether {// A headless client approves through the command socket. No GUI is not a rejection.// WAYLAND_DISPLAY alone would also skip a working X11 session: tether-dialog// falls back to an ordinary window when gtk-layer-shell isn't available.+ // A daemon started before the compositor finds it later, without WAYLAND_DISPLAY.+ const std::string live_display = g_wayland ? g_wayland->display_name() : std::string{};const char* wayland_display = std::getenv("WAYLAND_DISPLAY");const char* x11_display = std::getenv("DISPLAY");- if ((!wayland_display || !*wayland_display) && (!x11_display || !*x11_display))+ if (live_display.empty() && (!wayland_display || !*wayland_display) && (!x11_display || !*x11_display))return;// Translated before the fork: gettext takes a lock, and calling it in the@@ -2517,6 +2519,29 @@ namespace tether {const std::string accept = _("Accept");const std::string reject = _("Reject");+ // build before the fork, child of a thread must not allocate+ const std::string live_env = "WAYLAND_DISPLAY=" + live_display;+ std::vector<char*> envp;+ for (char** e = environ; *e; ++e) {+ if (live_display.empty() || std::strncmp(*e, "WAYLAND_DISPLAY=", 16) != 0)+ envp.push_back(*e);+ }+ if (!live_display.empty())+ envp.push_back(const_cast<char*>(live_env.c_str()));+ envp.push_back(nullptr);+ const char* const argv[] = {"tether-dialog",+ "--title",+ title.c_str(),+ "--body",+ body.c_str(),+ "--accept",+ accept.c_str(),+ "--reject",+ reject.c_str(),+ "--timeout",+ "60",+ nullptr};+// Create a pipe so the parent can detect when the child exits via epollint pipefd[2];if (pipe(pipefd) < 0) {@@ -2546,33 +2571,9 @@ namespace tether {}std::string sibling = (self_path.parent_path() / "tether-dialog").string();- execl(sibling.c_str(),- "tether-dialog",- "--title",- title.c_str(),- "--body",- body.c_str(),- "--accept",- accept.c_str(),- "--reject",- reject.c_str(),- "--timeout",- "60",- nullptr);+ execve(sibling.c_str(), const_cast<char* const*>(argv), envp.data());// If sibling path failed, try PATH- execlp("tether-dialog",- "tether-dialog",- "--title",- title.c_str(),- "--body",- body.c_str(),- "--accept",- accept.c_str(),- "--reject",- reject.c_str(),- "--timeout",- "60",- nullptr);+ execvpe("tether-dialog", const_cast<char* const*>(argv), envp.data());// exec failed entirelydebug::log(ERR, "spawn_pair_dialog: exec failed: {}", std::strerror(errno));_exit(3);diff --git a/src/core/src/wayland.cpp b/src/core/src/wayland.cppindex bd0ae70..9c14f5f 100644--- a/src/core/src/wayland.cpp+++ b/src/core/src/wayland.cpp@@ -3,9 +3,13 @@#include "wayland_protocols/wayland.hpp"#include "wayland_protocols/wlr-data-control-unstable-v1.hpp"+#include <algorithm>+#include <cstdlib>#include <cstring>#include <poll.h>+#include <sys/timerfd.h>#include <tether/log.hpp>+#include <unistd.h>#include <wayland-client.h>namespace tether {@@ -14,34 +18,114 @@ namespace tether {WaylandContext::WaylandContext(EpollEventLoop& loop) : loop_(loop) {}+ std::vector<std::string> wayland_sockets(const std::filesystem::path& runtime_dir) {+ std::vector<std::string> names;+ std::error_code ec;+ for (const auto& entry : std::filesystem::directory_iterator(runtime_dir, ec)) {+ const std::string name = entry.path().filename().string();+ if (!name.starts_with("wayland-") || name.ends_with(".lock"))+ continue;+ if (entry.is_socket(ec))+ names.push_back(name);+ }+ std::sort(names.begin(), names.end());+ return names;+ }+WaylandContext::~WaylandContext() {g_wayland = nullptr;- if (raw_display_) {- // Crucial: Destroy all regular proxies BEFORE disconnecting the display.- clipboard_.reset();- ext_data_control_manager_.reset();- wlr_data_control_manager_.reset();- seat_.reset();- registry_.reset();-- // High-level wrapper for the display itself.- if (display_) {- display_.release();+ if (retry_fd_ >= 0) {+ loop_.removeFd(retry_fd_);+ close(retry_fd_);+ }+ disconnect();+ }++ void WaylandContext::disconnect() {+ if (!raw_display_)+ return;+ // Crucial: Destroy all regular proxies BEFORE disconnecting the display.+ clipboard_.reset();+ ext_data_control_manager_.reset();+ wlr_data_control_manager_.reset();+ seat_.reset();+ registry_.reset();++ // High-level wrapper for the display itself.+ if (display_) {+ display_.release();+ }++ loop_.removeFd(wl_display_get_fd(raw_display_));+ wl_display_disconnect(raw_display_);+ raw_display_ = nullptr;+ display_name_.clear();+ }++ // A unit started at boot runs before the compositor and without its+ // WAYLAND_DISPLAY, so fall back to any compositor socket in the runtime dir.+ bool WaylandContext::connect_display() {+ const char* env = std::getenv("WAYLAND_DISPLAY");+ const std::string env_name = env && *env ? env : "wayland-0";+ if ((raw_display_ = wl_display_connect(nullptr))) {+ display_name_ = env_name;+ return true;+ }+ const char* runtime_dir = std::getenv("XDG_RUNTIME_DIR");+ if (!runtime_dir || !*runtime_dir)+ return false;+ for (const auto& name : wayland_sockets(runtime_dir)) {+ if (name == env_name)+ continue;+ if ((raw_display_ = wl_display_connect(name.c_str()))) {+ display_name_ = name;+ return true;}+ }+ return false;+ }- loop_.removeFd(wl_display_get_fd(raw_display_));- wl_display_disconnect(raw_display_);- raw_display_ = nullptr;+ void WaylandContext::start_retry() {+ if (retry_fd_ >= 0)+ return;+ // libwayland can find no socket without it, and complains on every attempt.+ const char* runtime_dir = std::getenv("XDG_RUNTIME_DIR");+ if (!runtime_dir || !*runtime_dir) {+ debug::log(ERR, "WaylandContext: XDG_RUNTIME_DIR unset; clipboard sync unavailable.");+ return;}+ retry_fd_ = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);+ if (retry_fd_ < 0) {+ debug::log(ERR, "WaylandContext: no compositor and no retry timer; clipboard sync unavailable.");+ return;+ }+ itimerspec spec{};+ spec.it_value.tv_sec = 2;+ spec.it_interval.tv_sec = 2;+ timerfd_settime(retry_fd_, 0, &spec, nullptr);+ debug::log(INFO, "WaylandContext: no Wayland display yet; waiting for a compositor.");+ loop_.addFd(retry_fd_, [this](int fd) {+ uint64_t ticks = 0;+ ssize_t ignored = read(fd, &ticks, sizeof(ticks));+ (void)ignored;+ if (!connect_display())+ return;+ loop_.removeFd(fd);+ close(fd);+ retry_fd_ = -1;+ setup();+ });}bool WaylandContext::init() {- raw_display_ = wl_display_connect(nullptr);- if (!raw_display_) {- debug::log(ERR, "WaylandContext: Failed to connect to Wayland display");+ if (!connect_display()) {+ start_retry();return false;}+ return setup();+ }+ bool WaylandContext::setup() {display_ = std::make_unique<CCWlDisplay>((wl_proxy*)raw_display_);auto proxy = display_->sendGetRegistry();@@ -119,14 +203,15 @@ namespace tether {loop_.addFd(fd, [this](int wfd) {struct pollfd pfd{wfd, 0, 0};if (poll(&pfd, 1, 0) == 1 && (pfd.revents & (POLLHUP | POLLERR))) {- debug::log(ERR, "WaylandContext: compositor hung up; exiting for on-demand restart.");- loop_.stop();+ debug::log(ERR, "WaylandContext: compositor hung up; waiting for the next one.");+ disconnect();+ start_retry();return;}if (wl_display_dispatch(raw_display_) < 0) {- // Display connection is dead- debug::log(ERR, "WaylandContext: Display connection lost; shutting down for on-demand restart.");- loop_.stop();+ debug::log(ERR, "WaylandContext: Display connection lost; waiting for a compositor.");+ disconnect();+ start_retry();return;}wl_display_flush(raw_display_); // flush requests queued during dispatch (offer/source destroys)@@ -135,7 +220,7 @@ namespace tether {// Flush any pending requestswl_display_flush(raw_display_);- debug::log(INFO, "WaylandContext initialized successfully.");+ debug::log(INFO, "WaylandContext initialized successfully on {}.", display_name_);return true;}diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex fc4019e..f5c8618 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -154,18 +154,16 @@ int main(int argc, char** argv) {tether::WaylandContext wayland_srv(loop);tether::g_wayland = &wayland_srv;- if (wayland_srv.init()) {- wayland_srv.set_clipboard_callback([](const std::string& text) {- nlohmann::json j;- j["command"] = "clipboard_updated";- j["content"] = text;- // replace bad UTF-8 instead of throwing; a clipboard- // app can still mislabel binary as text/plain. Don't abort the daemon.- tether::broadcast_message(j.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));- });- wayland_srv.set_clipboard_image_callback(- [](const std::string& png) { tether::broadcast_clipboard_image(png); });- }+ wayland_srv.set_clipboard_callback([](const std::string& text) {+ nlohmann::json j;+ j["command"] = "clipboard_updated";+ j["content"] = text;+ // replace bad UTF-8 instead of throwing; a clipboard+ // app can still mislabel binary as text/plain. Don't abort the daemon.+ tether::broadcast_message(j.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));+ });+ wayland_srv.set_clipboard_image_callback([](const std::string& png) { tether::broadcast_clipboard_image(png); });+ wayland_srv.init();tether::FileReceiveManager file_mgr;tether::DesktopNotifier notifier;diff --git a/test/test_clipboard.cpp b/test/test_clipboard.cppindex 94cc5cb..1d433c1 100644--- a/test/test_clipboard.cpp+++ b/test/test_clipboard.cpp@@ -3,6 +3,12 @@#include <tether/base64.hpp>#include <tether/clipboard.hpp>#include <tether/net.hpp>+#include <tether/wayland.hpp>++#include <fstream>+#include <sys/socket.h>+#include <sys/un.h>+#include <unistd.h>TEST(ClipboardMimeTest, TextWinsOverImage) {EXPECT_EQ(tether::pick_clipboard_mime({"image/png", "text/plain"}), "text/plain");@@ -77,3 +83,31 @@ TEST(ClipboardImageTest, ReceiverDropsBadTransfers) {EXPECT_TRUE(rx.chunk("over", b64));EXPECT_EQ(rx.finish("over"), "");}++TEST(WaylandSocketTest, OnlyCompositorSocketsAreCandidates) {+ char dir[] = "/tmp/tether-wl-XXXXXX";+ ASSERT_NE(mkdtemp(dir), nullptr);+ const std::filesystem::path root = dir;+ std::ofstream(root / "wayland-0"); // stale regular file+ std::ofstream(root / "wayland-1.lock"); // compositor lock file++ const auto bind_socket = [&](const std::string& name) {+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);+ sockaddr_un addr{};+ addr.sun_family = AF_UNIX;+ std::strncpy(addr.sun_path, (root / name).c_str(), sizeof(addr.sun_path) - 1);+ EXPECT_EQ(bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)), 0);+ return fd;+ };+ int fd2 = bind_socket("wayland-2");+ int fd1 = bind_socket("wayland-1");+ int other = bind_socket("pipewire-0");++ EXPECT_EQ(tether::wayland_sockets(root), (std::vector<std::string>{"wayland-1", "wayland-2"}));+ EXPECT_TRUE(tether::wayland_sockets(root / "missing").empty());++ close(fd1);+ close(fd2);+ close(other);+ std::filesystem::remove_all(root);+}