Linux + iPhone Continuity / iMessage / SMS
file transfer poc
Zack Bartelacc6547f0f08
diff --git a/.clang-format b/.clang-formatnew file mode 100644index 0000000..e9f3654--- /dev/null+++ b/.clang-format@@ -0,0 +1,45 @@+BasedOnStyle: LLVM++# --- Indentation ---+IndentWidth: 4+TabWidth: 4+UseTab: Never++# --- Access Modifiers ---+AccessModifierOffset: -4++ConstructorInitializerAllOnOneLineOrOnePerLine: true++# --- Braces ---+BreakBeforeBraces: Attach # Opening brace stays on same line++# --- Pointers & References ---+PointerAlignment: Left+DerivePointerAlignment: false++# --- Line Length ---+ColumnLimit: 120++# --- Namespace formatting ---+NamespaceIndentation: All++# --- Include formatting ---+SortIncludes: true+IncludeBlocks: Preserve++# --- Function arguments ---+BinPackParameters: false+BinPackArguments: false+AllowAllParametersOfDeclarationOnNextLine: true++# --- Constructor initializer formatting ---+BreakConstructorInitializersBeforeComma: true++# --- Lists ---+Cpp11BracedListStyle: true+SpacesInContainerLiterals: true++# --- Misc ---+AlignAfterOpenBracket: Align+IndentWrappedFunctionNames: true+diff --git a/README.md b/README.mdindex 1e237bf..3c6e6cf 100644--- a/README.md+++ b/README.md@@ -7,8 +7,8 @@ If you have migrated away from macOS but still carry an iPhone, Tether provides## Scope & Features* **Clipboard Sync:** Seamlessly shares your Wayland compositor (`wlr-data-control`) clipboard over the Tether network so copied text propagates instantly to the iPhone app, and vice-versa.+* **File Transfer:** Drag and drop files from Linux directly into the iPhone app natively, or Vice Versa using Base64 JSON chunking automatically deposited to your `$XDG_DOWNLOAD_DIR`.* **TOTP/OTP Vault (WIP):** Encrypted TOTP secret management synced across your daemon and phone, with Safari autofill via `ASCredentialProviderExtension` on iOS, and Wayland browser autofill via a WebExtension.-* **File Transfer (WIP):** Drag and drop files from Linux directly into the iPhone app natively.## Architecturediff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdindex 4dda37b..22bec63 100644--- a/docs/PROTOCOL.md+++ b/docs/PROTOCOL.md@@ -45,3 +45,58 @@ The clipboard capabilities allow seamless copying and pasting between the Host (```**Daemon Behavior**: Fired asynchronously whenever the `wlr_data_control_device` `setDataOffer` informs the daemon that the primary clipboard selection has rotated.++---++## 2. File Transfers++Tether supports streaming large binary files seamlessly through JSON using Base64 chunks to adhere to extension native messaging payload restrictions.++### `file_start` (Client -> Daemon)++**Description**: Announces an incoming binary transmission.++**Payload**:+```json+{+ "command": "file_start",+ "filename": "image.png",+ "size": 2048500,+ "transfer_id": "unique_string"+}+```++### `file_chunk` (Client -> Daemon)++**Description**: Sends a sequential Base64 chunk of the file data.++**Payload**:+```json+{+ "command": "file_chunk",+ "transfer_id": "unique_string",+ "chunk_index": 0,+ "data": "iVBORw0KGgoAAAANSUhEUgAA..."+}+```++### `file_end` (Client -> Daemon)++**Description**: Closes the file handle on the daemon and returns a success status back.++**Payload**:+```json+{+ "command": "file_end",+ "transfer_id": "unique_string"+}+```++**Response (Daemon -> Client):**+```json+{+ "command": "file_status",+ "transfer_id": "unique_string",+ "status": "success"+}+```diff --git a/src/cli/main.cpp b/src/cli/main.cppindex 3c95f45..87be7c2 100644--- a/src/cli/main.cpp+++ b/src/cli/main.cpp@@ -1,11 +1,13 @@#include <cstring>#include <filesystem>+#include <fstream>#include <iostream>#include <nlohmann/json.hpp>#include <string>#include <sys/socket.h>#include <sys/un.h>#include <sys/wait.h>+#include <tether/base64.hpp>#include <tether/net.hpp> // for get_runtime_dir#include <unistd.h>#include <vector>@@ -16,7 +18,8 @@ void print_help() {<< " -h, --help Show this help message.\n"<< " -g, --get-clipboard Retrieve the current Wayland clipboard text.\n"<< " -s, --set-clipboard Take string input and copy it to the local Wayland clipboard.\n"- << " If no argument is given, it reads from STDIN.\n\n"+ << " If no argument is given, it reads from STDIN.\n"+ << " -f, --send-file Send a file securely to the local Wayland download directory.\n\n"<< "Examples:\n"<< " tether -g\n"<< " tether -s \"Hello world\"\n"@@ -99,6 +102,11 @@ int main(int argc, char* argv[]) {return 0;} else if (arg == "-g" || arg == "--get-clipboard") {action = "get";+ } else if (arg == "-f" || arg == "--send-file") {+ action = "file";+ if (i + 1 < argc && argv[i + 1][0] != '-') {+ arg_val = argv[++i];+ }} else if (arg == "-s" || arg == "--set-clipboard") {action = "set";// Check if there is an argument immediately following the flag@@ -150,6 +158,62 @@ int main(int argc, char* argv[]) {j["content"] = arg_val;std::string payload = j.dump() + "\n";send_and_wait(sock, payload); // Ignore daemon's "OK\n"+ } else if (action == "file") {+ if (arg_val.empty() || !std::filesystem::exists(arg_val)) {+ std::cerr << "Invalid or missing file path: " << arg_val << "\n";+ return 1;+ }++ std::ifstream file(arg_val, std::ios::binary);+ if (!file.is_open()) {+ std::cerr << "Failed to open file.\n";+ return 1;+ }++ size_t file_size = std::filesystem::file_size(arg_val);+ std::string filename = std::filesystem::path(arg_val).filename().string();+ std::string transfer_id = "cli_" + std::to_string(time(nullptr));++ std::cout << "Uploading " << filename << " (" << file_size << " bytes)..." << std::endl;++ nlohmann::json j_start;+ j_start["command"] = "file_start";+ j_start["filename"] = filename;+ j_start["size"] = file_size;+ j_start["transfer_id"] = transfer_id;+ send_and_wait(sock, j_start.dump() + "\n");++ const size_t chunk_size = 512 * 1024;+ std::vector<unsigned char> buffer(chunk_size);+ int chunk_idx = 0;++ while (file) {+ file.read(reinterpret_cast<char*>(buffer.data()), chunk_size);+ size_t bytes_read = file.gcount();+ if (bytes_read == 0)+ break;++ nlohmann::json j_chunk;+ j_chunk["command"] = "file_chunk";+ j_chunk["chunk_index"] = chunk_idx++;+ j_chunk["transfer_id"] = transfer_id;+ j_chunk["data"] = tether::base64_encode(buffer.data(), bytes_read);++ send_and_wait(sock, j_chunk.dump() + "\n");+ }++ nlohmann::json j_end;+ j_end["command"] = "file_end";+ j_end["transfer_id"] = transfer_id;++ std::string resp = send_and_wait(sock, j_end.dump() + "\n");+ try {+ nlohmann::json r = nlohmann::json::parse(resp);+ if (r.contains("status") && r["status"] == "success") {+ std::cout << "File transfer successfully saved.\n";+ }+ } catch (...) {+ }}close(sock);diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txtindex 2618538..df7bec0 100644--- a/src/core/CMakeLists.txt+++ b/src/core/CMakeLists.txt@@ -3,6 +3,8 @@ add_library(tether_core STATICsrc/event_loop.cppsrc/net.cppsrc/clipboard.cpp+ src/base64.cpp+ src/file_transfer.cppsrc/wayland.cppsrc/wayland_protocols/wayland.cppsrc/wayland_protocols/wlr-data-control-unstable-v1.cppdiff --git a/src/core/include/tether/base64.hpp b/src/core/include/tether/base64.hppnew file mode 100644index 0000000..c29c09b--- /dev/null+++ b/src/core/include/tether/base64.hpp@@ -0,0 +1,10 @@+#pragma once++#include <string>+#include <vector>++namespace tether {+ std::string base64_encode(const std::vector<unsigned char>& data);+ std::string base64_encode(const unsigned char* data, size_t len);+ std::vector<unsigned char> base64_decode(const std::string& input);+}diff --git a/src/core/include/tether/file_transfer.hpp b/src/core/include/tether/file_transfer.hppnew file mode 100644index 0000000..4c6f91a--- /dev/null+++ b/src/core/include/tether/file_transfer.hpp@@ -0,0 +1,39 @@+#pragma once++#include <string>+#include <map>+#include <memory>+#include <fstream>+#include <filesystem>+#include <mutex>++namespace tether {++class FileReceiveManager {+public:+ FileReceiveManager();+ ~FileReceiveManager();++ bool handle_start(const std::string& transfer_id, const std::string& filename, size_t size);+ bool handle_chunk(const std::string& transfer_id, int chunk_index, const std::string& b64_data);+ bool handle_end(const std::string& transfer_id);++private:+ std::string get_downloads_dir();+ std::filesystem::path resolve_filename(const std::string& raw_name);++ struct Transfer {+ std::string transfer_id;+ std::filesystem::path filepath;+ std::unique_ptr<std::ofstream> stream;+ size_t expected_size;+ size_t bytes_written = 0;+ };++ std::mutex mutex_;+ std::map<std::string, std::shared_ptr<Transfer>> transfers_;+};++extern FileReceiveManager* g_file_manager;++}diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hppindex 543b90c..7e1cb4d 100644--- a/src/core/include/tether/net.hpp+++ b/src/core/include/tether/net.hpp@@ -32,6 +32,7 @@ private:EpollEventLoop& loop_;int server_fd_ = -1;std::string socket_path_;+ std::map<int, std::string> client_buffers_;};class TcpServer {@@ -50,6 +51,7 @@ private:EpollEventLoop& loop_;int server_fd_ = -1;int bind_port_;+ std::map<int, std::string> client_buffers_;};} // namespace tetherdiff --git a/src/core/src/base64.cpp b/src/core/src/base64.cppnew file mode 100644index 0000000..b9205aa--- /dev/null+++ b/src/core/src/base64.cpp@@ -0,0 +1,99 @@+#include "tether/base64.hpp"++namespace tether {++static const std::string base64_chars =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "abcdefghijklmnopqrstuvwxyz"+ "0123456789+/";++static inline bool is_base64(unsigned char c) {+ return (isalnum(c) || (c == '+') || (c == '/'));+}++std::string base64_encode(const unsigned char* bytes_to_encode, size_t in_len) {+ std::string ret;+ int i = 0;+ int j = 0;+ unsigned char char_array_3[3];+ unsigned char char_array_4[4];++ while (in_len--) {+ char_array_3[i++] = *(bytes_to_encode++);+ if (i == 3) {+ char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;+ char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);+ char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);+ char_array_4[3] = char_array_3[2] & 0x3f;++ for(i = 0; (i <4) ; i++)+ ret += base64_chars[char_array_4[i]];+ i = 0;+ }+ }++ if (i) {+ for(j = i; j < 3; j++)+ char_array_3[j] = '\0';++ char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;+ char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);+ char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);+ char_array_4[3] = char_array_3[2] & 0x3f;++ for (j = 0; (j < i + 1); j++)+ ret += base64_chars[char_array_4[j]];++ while((i++ < 3))+ ret += '=';+ }++ return ret;+}++std::string base64_encode(const std::vector<unsigned char>& data) {+ return base64_encode(data.data(), data.size());+}++std::vector<unsigned char> base64_decode(const std::string& encoded_string) {+ int in_len = encoded_string.size();+ int i = 0;+ int j = 0;+ int in_ = 0;+ unsigned char char_array_4[4], char_array_3[3];+ std::vector<unsigned char> ret;++ while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {+ char_array_4[i++] = encoded_string[in_]; in_++;+ if (i ==4) {+ for (i = 0; i <4; i++)+ char_array_4[i] = base64_chars.find(char_array_4[i]);++ char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);+ char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);+ char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];++ for (i = 0; (i < 3); i++)+ ret.push_back(char_array_3[i]);+ i = 0;+ }+ }++ if (i) {+ for (j = i; j <4; j++)+ char_array_4[j] = 0;++ for (j = 0; j <4; j++)+ char_array_4[j] = base64_chars.find(char_array_4[j]);++ char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);+ char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);+ char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];++ for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);+ }++ return ret;+}++} // namespace tetherdiff --git a/src/core/src/file_transfer.cpp b/src/core/src/file_transfer.cppnew file mode 100644index 0000000..39673e0--- /dev/null+++ b/src/core/src/file_transfer.cpp@@ -0,0 +1,108 @@+#include "tether/file_transfer.hpp"+#include "tether/base64.hpp"+#include <iostream>+#include <stdlib.h>+#include <stdio.h>++namespace tether {++FileReceiveManager* g_file_manager = nullptr;++FileReceiveManager::FileReceiveManager() {}+FileReceiveManager::~FileReceiveManager() {+ std::lock_guard<std::mutex> lock(mutex_);+ for (auto& [id, t] : transfers_) {+ if (t->stream && t->stream->is_open()) {+ t->stream->close();+ }+ }+}++std::string FileReceiveManager::get_downloads_dir() {+ std::string path;+ FILE* pipe = popen("xdg-user-dir DOWNLOAD 2>/dev/null", "r");+ if (pipe) {+ char buffer[1024];+ if (fgets(buffer, sizeof(buffer), pipe) != nullptr) {+ path = buffer;+ if (!path.empty() && path.back() == '\n') path.pop_back();+ }+ pclose(pipe);+ }+ if (path.empty() || path == getenv("HOME")) {+ const char* home = getenv("HOME");+ if (home) path = std::string(home) + "/Downloads";+ }+ return path;+}++std::filesystem::path FileReceiveManager::resolve_filename(const std::string& raw_name) {+ auto dl_dir = std::filesystem::path(get_downloads_dir());+ std::filesystem::create_directories(dl_dir);++ std::filesystem::path p = dl_dir / raw_name;+ if (!std::filesystem::exists(p)) return p;++ std::string stem = p.stem().string();+ std::string ext = p.extension().string();++ int counter = 1;+ while (true) {+ p = dl_dir / (stem + "(" + std::to_string(counter) + ")" + ext);+ if (!std::filesystem::exists(p)) return p;+ counter++;+ }+}++bool FileReceiveManager::handle_start(const std::string& transfer_id, const std::string& filename, size_t size) {+ std::lock_guard<std::mutex> lock(mutex_);++ if (transfers_.find(transfer_id) != transfers_.end()) return false;++ auto t = std::make_shared<Transfer>();+ t->transfer_id = transfer_id;+ t->expected_size = size;+ t->filepath = resolve_filename(filename);++ t->stream = std::make_unique<std::ofstream>(t->filepath, std::ios::binary);+ if (!t->stream->is_open()) {+ std::cerr << "FileReceiveManager: Failed to open output file: " << t->filepath << std::endl;+ return false;+ }++ transfers_[transfer_id] = t;+ std::cout << "FileReceiveManager: Started transfer " << transfer_id << " saving to " << t->filepath << std::endl;+ return true;+}++bool FileReceiveManager::handle_chunk(const std::string& transfer_id, int chunk_index, const std::string& b64_data) {+ std::lock_guard<std::mutex> lock(mutex_);++ auto it = transfers_.find(transfer_id);+ if (it == transfers_.end()) return false;++ auto& t = it->second;+ auto raw_data = base64_decode(b64_data);++ t->stream->write(reinterpret_cast<const char*>(raw_data.data()), raw_data.size());+ t->bytes_written += raw_data.size();++ return true;+}++bool FileReceiveManager::handle_end(const std::string& transfer_id) {+ std::lock_guard<std::mutex> lock(mutex_);++ auto it = transfers_.find(transfer_id);+ if (it == transfers_.end()) return false;++ auto& t = it->second;+ t->stream->close();++ std::cout << "FileReceiveManager: Finished transfer " << transfer_id << ". Wrote " << t->bytes_written << " bytes to " << t->filepath << std::endl;++ transfers_.erase(it);+ return true;+}++}diff --git a/src/core/src/net.cpp b/src/core/src/net.cppindex 00db88d..5763067 100644--- a/src/core/src/net.cpp+++ b/src/core/src/net.cpp@@ -1,307 +1,334 @@#include "tether/net.hpp"-#include <sys/socket.h>-#include <sys/un.h>+#include <arpa/inet.h>+#include <errno.h>+#include <fcntl.h>#include <sys/file.h>+#include <sys/socket.h>#include <sys/stat.h>-#include <arpa/inet.h>+#include <sys/un.h>#include <unistd.h>-#include <fcntl.h>-#include <errno.h>-#include <iostream>+#include "tether/file_transfer.hpp"+#include "tether/wayland.hpp"#include <cstring>#include <filesystem>-#include <set>+#include <iostream>#include <nlohmann/json.hpp>-#include "tether/wayland.hpp"+#include <set>namespace tether {-// Global list of active connected clients-static std::set<int> active_clients;+ // Global list of active connected clients+ static std::set<int> active_clients;-void register_client_fd(int fd) {- active_clients.insert(fd);-}+ void register_client_fd(int fd) { active_clients.insert(fd); }-void unregister_client_fd(int fd) {- active_clients.erase(fd);-}+ void unregister_client_fd(int fd) { active_clients.erase(fd); }-void broadcast_message(const std::string& msg) {- std::string packet = msg;- if (packet.back() != '\n') packet += '\n';+ void broadcast_message(const std::string& msg) {+ std::string packet = msg;+ if (packet.back() != '\n')+ packet += '\n';- for(int fd : active_clients) {- write(fd, packet.c_str(), packet.size());+ for (int fd : active_clients) {+ write(fd, packet.c_str(), packet.size());+ }}-}-std::string get_runtime_dir() {- const char* xdg_runtime = std::getenv("XDG_RUNTIME_DIR");- if (!xdg_runtime) {- throw std::runtime_error("XDG_RUNTIME_DIR is not set");- }- std::filesystem::path tether_dir = std::filesystem::path(xdg_runtime) / "tether";- if (!std::filesystem::exists(tether_dir)) {- std::filesystem::create_directories(tether_dir);- std::filesystem::permissions(tether_dir,- std::filesystem::perms::owner_all,- std::filesystem::perm_options::replace);- }- return tether_dir.string();-}--void ensure_single_instance() {- std::string lock_file = get_runtime_dir() + "/tetherd.lock";- int fd = open(lock_file.c_str(), O_RDWR | O_CREAT, 0600);- if (fd < 0) {- throw std::system_error(errno, std::system_category(), "Failed to open lock file");+ std::string get_runtime_dir() {+ const char* xdg_runtime = std::getenv("XDG_RUNTIME_DIR");+ if (!xdg_runtime) {+ throw std::runtime_error("XDG_RUNTIME_DIR is not set");+ }+ std::filesystem::path tether_dir = std::filesystem::path(xdg_runtime) / "tether";+ if (!std::filesystem::exists(tether_dir)) {+ std::filesystem::create_directories(tether_dir);+ std::filesystem::permissions(+ tether_dir, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace);+ }+ return tether_dir.string();}- if (flock(fd, LOCK_EX | LOCK_NB) < 0) {- if (errno == EWOULDBLOCK) {- std::cerr << "tetherd is already running." << std::endl;- exit(1);- } else {- throw std::system_error(errno, std::system_category(), "Failed to lock file");+ void ensure_single_instance() {+ std::string lock_file = get_runtime_dir() + "/tetherd.lock";+ int fd = open(lock_file.c_str(), O_RDWR | O_CREAT, 0600);+ if (fd < 0) {+ throw std::system_error(errno, std::system_category(), "Failed to open lock file");+ }++ if (flock(fd, LOCK_EX | LOCK_NB) < 0) {+ if (errno == EWOULDBLOCK) {+ std::cerr << "tetherd is already running." << std::endl;+ exit(1);+ } else {+ throw std::system_error(errno, std::system_category(), "Failed to lock file");+ }}+ // TODO: dont do this+ // we intentionally leak the fd so the lock is held for the lifetime of the process.+ // lock is automatically released by OS on exit.}- // We intentionally leak the fd so the lock is held for the lifetime of the process.- // lock is automatically released by OS on exit.-}+ // --- UnixServer ----// --- UnixServer ---+ UnixServer::UnixServer(EpollEventLoop& loop) : loop_(loop) { socket_path_ = get_runtime_dir() + "/tetherd.sock"; }-UnixServer::UnixServer(EpollEventLoop& loop) : loop_(loop) {- socket_path_ = get_runtime_dir() + "/tetherd.sock";-}+ UnixServer::~UnixServer() { stop(); }-UnixServer::~UnixServer() {- stop();-}+ bool UnixServer::start() {+ server_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);+ if (server_fd_ < 0) {+ std::cerr << "Failed to create unix socket" << std::endl;+ return false;+ }-bool UnixServer::start() {- server_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);- if (server_fd_ < 0) {- std::cerr << "Failed to create unix socket" << std::endl;- return false;- }+ // Set non-blocking+ int flags = fcntl(server_fd_, F_GETFL, 0);+ fcntl(server_fd_, F_SETFL, flags | O_NONBLOCK);- // Set non-blocking- int flags = fcntl(server_fd_, F_GETFL, 0);- fcntl(server_fd_, F_SETFL, flags | O_NONBLOCK);+ unlink(socket_path_.c_str());- unlink(socket_path_.c_str());+ sockaddr_un addr{};+ addr.sun_family = AF_UNIX;+ std::strncpy(addr.sun_path, socket_path_.c_str(), sizeof(addr.sun_path) - 1);- sockaddr_un addr{};- addr.sun_family = AF_UNIX;- std::strncpy(addr.sun_path, socket_path_.c_str(), sizeof(addr.sun_path) - 1);+ if (bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {+ std::cerr << "Failed to bind unix socket: " << std::strerror(errno) << std::endl;+ return false;+ }- if (bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {- std::cerr << "Failed to bind unix socket: " << std::strerror(errno) << std::endl;- return false;- }+ if (listen(server_fd_, SOMAXCONN) < 0) {+ std::cerr << "Failed to listen on unix socket" << std::endl;+ return false;+ }- if (listen(server_fd_, SOMAXCONN) < 0) {- std::cerr << "Failed to listen on unix socket" << std::endl;- return false;+ loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });+ std::cout << "UnixServer listening on " << socket_path_ << std::endl;+ return true;}- loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });- std::cout << "UnixServer listening on " << socket_path_ << std::endl;- return true;-}--void UnixServer::stop() {- if (server_fd_ >= 0) {- loop_.removeFd(server_fd_);- close(server_fd_);- server_fd_ = -1;- unlink(socket_path_.c_str());+ void UnixServer::stop() {+ if (server_fd_ >= 0) {+ loop_.removeFd(server_fd_);+ close(server_fd_);+ server_fd_ = -1;+ unlink(socket_path_.c_str());+ }}-}-void UnixServer::handle_accept(int fd) {- int client_fd = accept(fd, nullptr, nullptr);- if (client_fd < 0) {- if (errno != EAGAIN && errno != EWOULDBLOCK) {- std::cerr << "UnixServer accept error: " << std::strerror(errno) << std::endl;+ void UnixServer::handle_accept(int fd) {+ int client_fd = accept(fd, nullptr, nullptr);+ if (client_fd < 0) {+ if (errno != EAGAIN && errno != EWOULDBLOCK) {+ std::cerr << "UnixServer accept error: " << std::strerror(errno) << std::endl;+ }+ return;}- return;++ // Set non-blocking+ int flags = fcntl(client_fd, F_GETFL, 0);+ fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);++ // Register client+ loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });+ std::cout << "UnixServer: New connection (fd: " << client_fd << ")" << std::endl;}- // Set non-blocking- int flags = fcntl(client_fd, F_GETFL, 0);- fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);-- // Register client- loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });- std::cout << "UnixServer: New connection (fd: " << client_fd << ")" << std::endl;-}--void UnixServer::handle_client(int client_fd) {- char buf[1024];- ssize_t n = read(client_fd, buf, sizeof(buf) - 1);- if (n > 0) {- buf[n] = '\0';- std::string msg(buf);- std::cout << "UnixServer received: " << msg << std::endl;-- // Try to parse json just to show we can- try {- nlohmann::json j = nlohmann::json::parse(msg);- std::cout << " (Parsed JSON: " << j.dump() << ")" << std::endl;-- if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {- std::string content = j["content"];- if (g_wayland) {- g_wayland->copy_to_clipboard(content);- }- } else if (j.contains("command") && j["command"] == "clipboard_get") {- if (g_wayland) {- nlohmann::json resp;- resp["command"] = "clipboard_content";- resp["content"] = g_wayland->get_clipboard();- std::string payload = resp.dump() + "\n";- write(client_fd, payload.c_str(), payload.size());- return;+ void UnixServer::handle_client(int client_fd) {+ // 64k buffer sizes for chunks+ char buf[65536];+ ssize_t n = read(client_fd, buf, sizeof(buf) - 1);+ if (n > 0) {+ buf[n] = '\0';+ client_buffers_[client_fd] += std::string(buf, n);++ size_t pos;+ while ((pos = client_buffers_[client_fd].find('\n')) != std::string::npos) {+ std::string msg = client_buffers_[client_fd].substr(0, pos);+ client_buffers_[client_fd].erase(0, pos + 1);++ try {+ nlohmann::json j = nlohmann::json::parse(msg);++ if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {+ std::string content = j["content"];+ if (g_wayland)+ g_wayland->copy_to_clipboard(content);+ } else if (j.contains("command") && j["command"] == "clipboard_get") {+ if (g_wayland) {+ nlohmann::json resp;+ resp["command"] = "clipboard_content";+ resp["content"] = g_wayland->get_clipboard();+ std::string payload = resp.dump() + "\n";+ write(client_fd, payload.c_str(), payload.size());+ continue;+ }+ } else if (j.contains("command") && j["command"] == "file_start") {+ if (g_file_manager)+ g_file_manager->handle_start(j["transfer_id"], j["filename"], j["size"]);+ } else if (j.contains("command") && j["command"] == "file_chunk") {+ if (g_file_manager)+ g_file_manager->handle_chunk(j["transfer_id"], j["chunk_index"], j["data"]);+ } else if (j.contains("command") && j["command"] == "file_end") {+ if (g_file_manager && g_file_manager->handle_end(j["transfer_id"])) {+ nlohmann::json resp;+ resp["command"] = "file_status";+ resp["transfer_id"] = j["transfer_id"];+ resp["status"] = "success";+ std::string payload = resp.dump() + "\n";+ write(client_fd, payload.c_str(), payload.size());+ continue;+ }+ }+ } catch (...) {}++ std::string response = "OK\n";+ write(client_fd, response.c_str(), response.size());}- } catch (...) {- // Ignore parse errors for raw text protocol+ } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {+ // Disconnected+ std::cout << "UnixServer: Client disconnected (fd: " << client_fd << ")" << std::endl;+ client_buffers_.erase(client_fd);+ unregister_client_fd(client_fd);+ loop_.removeFd(client_fd);+ close(client_fd);}-- std::string response = "OK\n";- write(client_fd, response.c_str(), response.size());- } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {- // Disconnected- std::cout << "UnixServer: Client disconnected (fd: " << client_fd << ")" << std::endl;- unregister_client_fd(client_fd);- loop_.removeFd(client_fd);- close(client_fd);}-}-// --- TcpServer ---+ // --- TcpServer ----TcpServer::TcpServer(EpollEventLoop& loop, int bind_port)- : loop_(loop), bind_port_(bind_port) {}+ TcpServer::TcpServer(EpollEventLoop& loop, int bind_port) : loop_(loop), bind_port_(bind_port) {}-TcpServer::~TcpServer() {- stop();-}+ TcpServer::~TcpServer() { stop(); }-bool TcpServer::start() {- server_fd_ = socket(AF_INET, SOCK_STREAM, 0);- if (server_fd_ < 0) {- std::cerr << "Failed to create tcp socket" << std::endl;- return false;- }+ bool TcpServer::start() {+ server_fd_ = socket(AF_INET, SOCK_STREAM, 0);+ if (server_fd_ < 0) {+ std::cerr << "Failed to create tcp socket" << std::endl;+ return false;+ }- int opt = 1;- if (setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0) {- std::cerr << "TcpServer setsockopt reuse failed" << std::endl;- }+ int opt = 1;+ if (setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0) {+ std::cerr << "TcpServer setsockopt reuse failed" << std::endl;+ }- // Set non-blocking- int flags = fcntl(server_fd_, F_GETFL, 0);- fcntl(server_fd_, F_SETFL, flags | O_NONBLOCK);+ // Set non-blocking+ int flags = fcntl(server_fd_, F_GETFL, 0);+ fcntl(server_fd_, F_SETFL, flags | O_NONBLOCK);- sockaddr_in addr{};- addr.sin_family = AF_INET;- addr.sin_addr.s_addr = INADDR_ANY;- addr.sin_port = htons(bind_port_);+ sockaddr_in addr{};+ addr.sin_family = AF_INET;+ addr.sin_addr.s_addr = INADDR_ANY;+ addr.sin_port = htons(bind_port_);- if (bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {- std::cerr << "Failed to bind tcp socket on port " << bind_port_ << ": " << std::strerror(errno) << std::endl;- return false;- }+ if (bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {+ std::cerr << "Failed to bind tcp socket on port " << bind_port_ << ": " << std::strerror(errno)+ << std::endl;+ return false;+ }- if (listen(server_fd_, SOMAXCONN) < 0) {- std::cerr << "Failed to listen on tcp socket" << std::endl;- return false;- }+ if (listen(server_fd_, SOMAXCONN) < 0) {+ std::cerr << "Failed to listen on tcp socket" << std::endl;+ return false;+ }- loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });- std::cout << "TcpServer listening on 0.0.0.0:" << bind_port_ << std::endl;- return true;-}+ loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });+ std::cout << "TcpServer listening on 0.0.0.0:" << bind_port_ << std::endl;+ return true;+ }-void TcpServer::stop() {- if (server_fd_ >= 0) {- loop_.removeFd(server_fd_);- close(server_fd_);- server_fd_ = -1;+ void TcpServer::stop() {+ if (server_fd_ >= 0) {+ loop_.removeFd(server_fd_);+ close(server_fd_);+ server_fd_ = -1;+ }}-}--void TcpServer::handle_accept(int fd) {- sockaddr_in client_addr{};- socklen_t addrlen = sizeof(client_addr);- int client_fd = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen);- if (client_fd < 0) {- if (errno != EAGAIN && errno != EWOULDBLOCK) {- std::cerr << "TcpServer accept error: " << std::strerror(errno) << std::endl;++ void TcpServer::handle_accept(int fd) {+ sockaddr_in client_addr{};+ socklen_t addrlen = sizeof(client_addr);+ int client_fd = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &addrlen);+ if (client_fd < 0) {+ if (errno != EAGAIN && errno != EWOULDBLOCK) {+ std::cerr << "TcpServer accept error: " << std::strerror(errno) << std::endl;+ }+ return;}- return;++ // Set non-blocking+ int flags = fcntl(client_fd, F_GETFL, 0);+ fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);++ register_client_fd(client_fd);+ loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });++ char ip[INET_ADDRSTRLEN];+ inet_ntop(AF_INET, &(client_addr.sin_addr), ip, INET_ADDRSTRLEN);+ std::cout << "TcpServer: New connection from " << ip << " (fd: " << client_fd << ")" << std::endl;}- // Set non-blocking- int flags = fcntl(client_fd, F_GETFL, 0);- fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);-- register_client_fd(client_fd);- loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });-- char ip[INET_ADDRSTRLEN];- inet_ntop(AF_INET, &(client_addr.sin_addr), ip, INET_ADDRSTRLEN);- std::cout << "TcpServer: New connection from " << ip << " (fd: " << client_fd << ")" << std::endl;-}--void TcpServer::handle_client(int client_fd) {- char buf[1024];- ssize_t n = read(client_fd, buf, sizeof(buf) - 1);- if (n > 0) {- buf[n] = '\0';- std::string msg(buf);- std::cout << "TcpServer received: " << msg << std::endl;-- // Try to parse json just to show we can- try {- nlohmann::json j = nlohmann::json::parse(msg);- std::cout << " (Parsed JSON: " << j.dump() << ")" << std::endl;-- if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {- std::string content = j["content"];- if (g_wayland) {- g_wayland->copy_to_clipboard(content);- }- } else if (j.contains("command") && j["command"] == "clipboard_get") {- if (g_wayland) {- nlohmann::json resp;- resp["command"] = "clipboard_content";- resp["content"] = g_wayland->get_clipboard();- std::string payload = resp.dump() + "\n";- write(client_fd, payload.c_str(), payload.size());- return;+ void TcpServer::handle_client(int client_fd) {+ char buf[65536];+ ssize_t n = read(client_fd, buf, sizeof(buf) - 1);+ if (n > 0) {+ buf[n] = '\0';+ client_buffers_[client_fd] += std::string(buf, n);++ size_t pos;+ while ((pos = client_buffers_[client_fd].find('\n')) != std::string::npos) {+ std::string msg = client_buffers_[client_fd].substr(0, pos);+ client_buffers_[client_fd].erase(0, pos + 1);++ try {+ nlohmann::json j = nlohmann::json::parse(msg);++ if (j.contains("command") && j["command"] == "clipboard_set" && j.contains("content")) {+ std::string content = j["content"];+ if (g_wayland)+ g_wayland->copy_to_clipboard(content);+ } else if (j.contains("command") && j["command"] == "clipboard_get") {+ if (g_wayland) {+ nlohmann::json resp;+ resp["command"] = "clipboard_content";+ resp["content"] = g_wayland->get_clipboard();+ std::string payload = resp.dump() + "\n";+ write(client_fd, payload.c_str(), payload.size());+ continue;+ }+ } else if (j.contains("command") && j["command"] == "file_start") {+ if (g_file_manager)+ g_file_manager->handle_start(j["transfer_id"], j["filename"], j["size"]);+ } else if (j.contains("command") && j["command"] == "file_chunk") {+ if (g_file_manager)+ g_file_manager->handle_chunk(j["transfer_id"], j["chunk_index"], j["data"]);+ } else if (j.contains("command") && j["command"] == "file_end") {+ if (g_file_manager && g_file_manager->handle_end(j["transfer_id"])) {+ nlohmann::json resp;+ resp["command"] = "file_status";+ resp["transfer_id"] = j["transfer_id"];+ resp["status"] = "success";+ std::string payload = resp.dump() + "\n";+ write(client_fd, payload.c_str(), payload.size());+ continue;+ }+ }+ } catch (...) {}++ std::string response = "OK\n";+ write(client_fd, response.c_str(), response.size());}- } catch (...) {- // Ignore parse errors for raw text protocol+ } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {+ std::cout << "TcpServer: Client disconnected (fd: " << client_fd << ")" << std::endl;+ client_buffers_.erase(client_fd);+ unregister_client_fd(client_fd);+ loop_.removeFd(client_fd);+ close(client_fd);}-- std::string response = "OK\n";- write(client_fd, response.c_str(), response.size());- } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {- // Disconnected- std::cout << "TcpServer: Client disconnected (fd: " << client_fd << ")" << std::endl;- unregister_client_fd(client_fd);- loop_.removeFd(client_fd);- close(client_fd);}-}} // namespace tetherdiff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex 03c133b..837ac5e 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -3,6 +3,7 @@#include <tether/net.hpp>#include <tether/event_loop.hpp>#include <tether/wayland.hpp>+#include <tether/file_transfer.hpp>#include <nlohmann/json.hpp>#include <csignal>@@ -55,6 +56,9 @@ int main(int argc, char** argv) {});}+ tether::FileReceiveManager file_mgr;+ tether::g_file_manager = &file_mgr;+std::cout << "tetherd is running. Press Ctrl-C to stop." << std::endl;loop.run();