Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: fable audits

Zack Bartela31bfb3188f5
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 5cb94c5..247bc47 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -4,6 +4,7 @@ add_library(tether STATIC
src/net.cpp
src/clipboard.cpp
src/base64.cpp
+ src/otp.cpp
src/file_transfer.cpp
src/crypto.cpp
src/client.cpp
diff --git a/src/core/include/tether/client.hpp b/src/core/include/tether/client.hpp
index c4ede86..5133cb7 100644
--- a/src/core/include/tether/client.hpp
+++ b/src/core/include/tether/client.hpp
@@ -37,6 +37,7 @@ namespace tether {
int sock_ = -1;
SSL* ssl_ = nullptr;
+ std::vector<char> read_buf_;
};
} // namespace tether
diff --git a/src/core/include/tether/clipboard.hpp b/src/core/include/tether/clipboard.hpp
index c8c6ea9..3b8cf0c 100644
--- a/src/core/include/tether/clipboard.hpp
+++ b/src/core/include/tether/clipboard.hpp
@@ -10,6 +10,7 @@ class CCZwlrDataControlManagerV1;
class CCWlSeat;
class CCZwlrDataControlDeviceV1;
class CCZwlrDataControlOfferV1;
+class CCZwlrDataControlSourceV1;
namespace tether {
@@ -33,6 +34,7 @@ namespace tether {
EpollEventLoop& loop_;
wl_display* display_;
std::unique_ptr<CCZwlrDataControlDeviceV1> device_;
+ std::unique_ptr<CCZwlrDataControlSourceV1> source_;
std::function<void(const std::string&)> cb_;
std::map<wl_proxy*, std::unique_ptr<CCZwlrDataControlOfferV1>> offers_;
diff --git a/src/core/include/tether/crypto.hpp b/src/core/include/tether/crypto.hpp
index 7b7afcf..9d87cb8 100644
--- a/src/core/include/tether/crypto.hpp
+++ b/src/core/include/tether/crypto.hpp
@@ -1,5 +1,8 @@
#pragma once
+#include <filesystem>
+#include <map>
+#include <mutex>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <string>
@@ -28,13 +31,25 @@ namespace tether {
~Crypto();
bool ensure_certificates();
+
+ // All three assume the caller holds hosts_mutex_.
void load_known_hosts();
void save_known_hosts();
+ void refresh_known_hosts_if_stale();
std::string cert_path_;
std::string key_path_;
std::string hosts_path_;
+ // fingerprint -> device name. Cached in memory because is_host_known() runs on
+ // every TLS handshake and used to re-read and re-parse known_hosts.json each
+ // time. Revalidated by mtime, since `tether --accept` writes the file from a
+ // separate process and the daemon must notice.
+ mutable std::mutex hosts_mutex_;
+ std::map<std::string, std::string> known_hosts_;
+ std::filesystem::file_time_type hosts_mtime_{};
+ bool hosts_loaded_ = false;
+
SSL_CTX* server_ctx_ = nullptr;
SSL_CTX* client_ctx_ = nullptr;
diff --git a/src/core/include/tether/event_loop.hpp b/src/core/include/tether/event_loop.hpp
index f76e3a3..75c0821 100644
--- a/src/core/include/tether/event_loop.hpp
+++ b/src/core/include/tether/event_loop.hpp
@@ -1,5 +1,6 @@
#pragma once
+#include <atomic>
#include <functional>
#include <map>
@@ -30,7 +31,7 @@ namespace tether {
private:
int epoll_fd_;
- bool running_;
+ std::atomic<bool> running_;
std::map<int, Callback> callbacks_;
};
diff --git a/src/core/include/tether/otp.hpp b/src/core/include/tether/otp.hpp
new file mode 100644
index 0000000..eda3473
--- /dev/null
+++ b/src/core/include/tether/otp.hpp
@@ -0,0 +1,35 @@
+#pragma once
+
+#include <chrono>
+#include <cstdint>
+#include <string>
+
+namespace tether {
+
+ // single-slot OTP vault shared by every transport
+ struct Otp {
+ std::string code;
+ uint64_t id = 0; // 0 == no code
+ explicit operator bool() const { return id != 0 && !code.empty(); }
+ };
+
+ using OtpClock = std::chrono::steady_clock;
+
+ inline constexpr auto kOtpTtl = std::chrono::minutes(5);
+
+ // Store a code, assign it the next id, drop any previous host claim.
+ uint64_t otp_store(const std::string& code, OtpClock::time_point now = OtpClock::now());
+
+ // Current code if still within the TTL, else {}. Expires the slot as a side effect.
+ Otp otp_peek(OtpClock::time_point now = OtpClock::now());
+
+ Otp otp_take_for_host(const std::string& host, OtpClock::time_point now = OtpClock::now());
+
+ // retire a code
+ void otp_consume(uint64_t id);
+
+ bool otp_is_claimed();
+
+ void otp_reset(); // tests
+
+} // namespace tether
diff --git a/src/core/src/base64.cpp b/src/core/src/base64.cpp
index 9f0a82a..addcb77 100644
--- a/src/core/src/base64.cpp
+++ b/src/core/src/base64.cpp
@@ -10,6 +10,7 @@ namespace tether {
std::string base64_encode(const unsigned char* bytes_to_encode, size_t in_len) {
std::string ret;
+ ret.reserve(((in_len + 2) / 3) * 4); // exact output size; file chunks are 512 KB
int i = 0;
int j = 0;
unsigned char char_array_3[3];
@@ -59,6 +60,7 @@ namespace tether {
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::vector<unsigned char> ret;
+ ret.reserve((encoded_string.size() / 4) * 3);
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
diff --git a/src/core/src/client.cpp b/src/core/src/client.cpp
index f596844..302bd37 100644
--- a/src/core/src/client.cpp
+++ b/src/core/src/client.cpp
@@ -5,6 +5,8 @@
#include "tether/net.hpp"
#include <arpa/inet.h>
+#include <atomic>
+#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
@@ -64,6 +66,11 @@ namespace tether {
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
std::string path = tether::get_runtime_dir() + "/tetherd.sock";
+ if (path.size() >= sizeof(addr.sun_path)) {
+ debug::log(ERR, "Socket path too long: {}", path);
+ close(sock);
+ return -1;
+ }
std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
if (::connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
@@ -104,11 +111,19 @@ namespace tether {
disconnect();
if (!host.empty()) {
- sock_ = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
- inet_pton(AF_INET, host.c_str(), &addr.sin_addr);
+ if (inet_pton(AF_INET, host.c_str(), &addr.sin_addr) != 1) {
+ debug::log(ERR, "Invalid IPv4 address: {}", host);
+ return false;
+ }
+
+ sock_ = socket(AF_INET, SOCK_STREAM, 0);
+ if (sock_ < 0) {
+ debug::log(ERR, "Failed to create socket: {}", std::strerror(errno));
+ return false;
+ }
if (::connect(sock_, (sockaddr*)&addr, sizeof(addr)) < 0) {
return false;
@@ -128,37 +143,58 @@ namespace tether {
}
std::string Client::send_and_wait(const std::string& payload) {
- char buf[1024 * 1024]; // Generous payload buffer
+ constexpr size_t kBufSize = 1024 * 1024; // Generous payload buffer
+ if (read_buf_.size() < kBufSize)
+ read_buf_.resize(kBufSize);
+ char* buf = read_buf_.data();
+
+ if (!send(payload))
+ return "";
if (ssl_) {
- int w = SSL_write(ssl_, payload.c_str(), payload.size());
- if (w <= 0)
- return "";
- int n = SSL_read(ssl_, buf, sizeof(buf) - 1);
- if (n > 0) {
- buf[n] = '\0';
- return std::string(buf);
- }
+ int n = SSL_read(ssl_, buf, static_cast<int>(kBufSize - 1));
+ if (n > 0)
+ return std::string(buf, n);
} else {
- if (write(sock_, payload.c_str(), payload.size()) < 0) {
- debug::log(ERR, "client write error\n");
- }
- ssize_t n = ::read(sock_, buf, sizeof(buf) - 1);
- if (n > 0) {
- buf[n] = '\0';
- return std::string(buf);
- }
+ ssize_t n = ::read(sock_, buf, kBufSize - 1);
+ if (n > 0)
+ return std::string(buf, n);
}
return "";
}
bool Client::send(const std::string& payload) {
- if (ssl_) {
- int w = SSL_write(ssl_, payload.c_str(), payload.size());
- return w > 0;
- } else {
- return write(sock_, payload.c_str(), payload.size()) > 0;
+ // Loop: a short write on a stream socket is legal, and reporting it as success
+ // silently desynchronises the newline-framed protocol. Matters for the ~683 KB
+ // base64 payloads send_file() produces.
+ size_t total = 0;
+ while (total < payload.size()) {
+ const char* p = payload.data() + total;
+ size_t remaining = payload.size() - total;
+
+ if (ssl_) {
+ int n = SSL_write(ssl_, p, static_cast<int>(remaining));
+ if (n <= 0) {
+ int err = SSL_get_error(ssl_, n);
+ if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ)
+ continue;
+ return false;
+ }
+ total += static_cast<size_t>(n);
+ } else {
+ ssize_t n = ::write(sock_, p, remaining);
+ if (n < 0) {
+ if (errno == EINTR)
+ continue;
+ debug::log(ERR, "client write error: {}", std::strerror(errno));
+ return false;
+ }
+ if (n == 0)
+ return false;
+ total += static_cast<size_t>(n);
+ }
}
+ return true;
}
ssize_t Client::read(char* buf, size_t count) {
@@ -261,7 +297,11 @@ namespace tether {
size_t file_size = std::filesystem::file_size(path);
std::string filename = std::filesystem::path(path).filename().string();
- std::string transfer_id = "cli_" + std::to_string(time(nullptr));
+ // pid + counter, not just time(): two transfers in the same second produced the
+ // same id, and the receiver rejects a duplicate transfer_id.
+ static std::atomic<unsigned> seq{0};
+ std::string transfer_id =
+ "cli_" + std::to_string(getpid()) + "_" + std::to_string(time(nullptr)) + "_" + std::to_string(seq++);
nlohmann::json j_start;
j_start["command"] = "file_start";
diff --git a/src/core/src/clipboard.cpp b/src/core/src/clipboard.cpp
index 9325dec..bfdda01 100644
--- a/src/core/src/clipboard.cpp
+++ b/src/core/src/clipboard.cpp
@@ -116,8 +116,10 @@ namespace tether {
loop_.removeFd(fd);
close(fd);
- // Trim trailing nulls and whitespace
- while (!result.empty() && (result.back() == '\0' || isspace(result.back()))) {
+ // Trim trailing nulls and whitespace. Cast: isspace() on a negative
+ // char is UB, and clipboard text is routinely non-ASCII.
+ while (!result.empty() &&
+ (result.back() == '\0' || isspace(static_cast<unsigned char>(result.back())))) {
result.pop_back();
}
@@ -134,6 +136,7 @@ namespace tether {
loop_.removeFd(fd);
close(fd);
}
+ source_.reset(); // before the device that owns the selection
if (device_) {
device_->sendDestroy();
}
@@ -164,9 +167,14 @@ namespace tether {
}).detach();
});
- source->setCancelled([](CCZwlrDataControlSourceV1* s) { s->sendDestroy(); });
+ // compositor cancels our source when something else takes the selection.
+ source->setCancelled([this](CCZwlrDataControlSourceV1* s) {
+ if (source_.get() == s)
+ source_.reset();
+ });
- device_->sendSetSelection(source.release());
+ device_->sendSetSelection(source.get());
+ source_ = std::move(source);
}
} // namespace tether
diff --git a/src/core/src/crypto.cpp b/src/core/src/crypto.cpp
index d87c275..ae3b3c4 100644
--- a/src/core/src/crypto.cpp
+++ b/src/core/src/crypto.cpp
@@ -8,8 +8,10 @@
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
+#include <pwd.h>
#include <sstream>
#include <tether/log.hpp>
+#include <unistd.h>
namespace tether {
@@ -28,8 +30,21 @@ namespace tether {
SSL_CTX* Crypto::get_server_context() { return server_ctx_; }
SSL_CTX* Crypto::get_client_context() { return client_ctx_; }
+ static std::string home_dir() {
+ if (const char* home = getenv("HOME"); home && *home) {
+ return home;
+ }
+ if (const passwd* pw = getpwuid(getuid()); pw && pw->pw_dir) {
+ return pw->pw_dir;
+ }
+ throw std::runtime_error("Cannot determine home directory (HOME unset and no passwd entry)");
+ }
+
bool Crypto::init() {
- std::filesystem::path config_dir = std::string(getenv("HOME")) + "/.config/tether";
+ if (server_ctx_ && client_ctx_)
+ return true;
+
+ std::filesystem::path config_dir = std::filesystem::path(home_dir()) / ".config" / "tether";
std::filesystem::create_directories(config_dir);
cert_path_ = (config_dir / "cert.pem").string();
key_path_ = (config_dir / "key.pem").string();
@@ -82,7 +97,10 @@ namespace tether {
}
}
- load_known_hosts();
+ {
+ std::lock_guard<std::mutex> lock(hosts_mutex_);
+ load_known_hosts();
+ }
return true;
}
@@ -142,55 +160,95 @@ namespace tether {
}
void Crypto::load_known_hosts() {
- if (!std::filesystem::exists(hosts_path_)) {
- nlohmann::json empty = nlohmann::json::object();
- std::ofstream off(hosts_path_);
- off << empty.dump(4);
- }
- }
+ known_hosts_.clear();
+ hosts_loaded_ = true;
- void Crypto::save_known_hosts() {
- // We do it directly in add_known_host right now
- }
-
- bool Crypto::is_host_known(const std::string& fingerprint) {
std::ifstream iff(hosts_path_);
- if (!iff.is_open())
- return false;
+ if (!iff.is_open()) {
+ save_known_hosts(); // materialise an empty file on first run
+ return;
+ }
+
try {
nlohmann::json j = nlohmann::json::parse(iff);
- return j.contains(fingerprint);
+ for (auto& [fingerprint, name] : j.items()) {
+ known_hosts_[fingerprint] = name.is_string() ? name.get<std::string>() : "Unknown Device";
+ }
} catch (...) {
- return false;
+ debug::log(ERR, "Crypto: known_hosts.json is corrupt; treating as empty");
+ }
+ iff.close();
+
+ std::error_code ec;
+ hosts_mtime_ = std::filesystem::last_write_time(hosts_path_, ec);
+ }
+
+ void Crypto::refresh_known_hosts_if_stale() {
+ std::error_code ec;
+ auto mtime = std::filesystem::last_write_time(hosts_path_, ec);
+ if (ec) {
+ if (!hosts_loaded_)
+ load_known_hosts();
+ return;
+ }
+ if (!hosts_loaded_ || mtime != hosts_mtime_) {
+ load_known_hosts();
}
}
- void Crypto::add_known_host(const std::string& name, const std::string& fingerprint) {
- nlohmann::json j;
- std::ifstream iff(hosts_path_);
- if (iff.is_open()) {
- try {
- j = nlohmann::json::parse(iff);
- } catch (...) {
+ // writes to a temp file and renames
+ void Crypto::save_known_hosts() {
+ nlohmann::json j = nlohmann::json::object();
+ for (const auto& [fingerprint, name] : known_hosts_) {
+ j[fingerprint] = name;
+ }
+
+ std::string tmp_path = hosts_path_ + ".tmp";
+ {
+ std::ofstream off(tmp_path);
+ if (!off.is_open()) {
+ debug::log(ERR, "Crypto: cannot write {}", tmp_path);
+ return;
+ }
+ off << j.dump(4);
+ off.flush();
+ if (!off) {
+ debug::log(ERR, "Crypto: failed writing {}", tmp_path);
+ return;
}
- iff.close();
}
- j[fingerprint] = name;
- std::ofstream off(hosts_path_);
- off << j.dump(4);
+ std::error_code ec;
+ std::filesystem::rename(tmp_path, hosts_path_, ec);
+ if (ec) {
+ debug::log(ERR, "Crypto: failed to replace {}: {}", hosts_path_, ec.message());
+ std::filesystem::remove(tmp_path, ec);
+ return;
+ }
+ hosts_mtime_ = std::filesystem::last_write_time(hosts_path_, ec);
+ }
+
+ bool Crypto::is_host_known(const std::string& fingerprint) {
+ std::lock_guard<std::mutex> lock(hosts_mutex_);
+ refresh_known_hosts_if_stale();
+ return known_hosts_.count(fingerprint) > 0;
+ }
+
+ void Crypto::add_known_host(const std::string& name, const std::string& fingerprint) {
+ std::lock_guard<std::mutex> lock(hosts_mutex_);
+ refresh_known_hosts_if_stale(); // don't clobber a pairing another process added
+ known_hosts_[fingerprint] = name;
+ save_known_hosts();
}
std::string Crypto::get_known_hosts_dump() const {
- std::ifstream iff(hosts_path_);
- if (iff.is_open()) {
- try {
- nlohmann::json j = nlohmann::json::parse(iff);
- return j.dump(2);
- } catch (...) {
- }
+ std::lock_guard<std::mutex> lock(hosts_mutex_);
+ const_cast<Crypto*>(this)->refresh_known_hosts_if_stale();
+ nlohmann::json j = nlohmann::json::object();
+ for (const auto& [fingerprint, name] : known_hosts_) {
+ j[fingerprint] = name;
}
- return "{}";
+ return j.dump(2);
}
std::string Crypto::get_my_fingerprint() { return my_fingerprint_; }
diff --git a/src/core/src/discovery.cpp b/src/core/src/discovery.cpp
index 3247216..fb31bbf 100644
--- a/src/core/src/discovery.cpp
+++ b/src/core/src/discovery.cpp
@@ -180,6 +180,8 @@ namespace tether {
}
}
+ std::function<void(const std::vector<DiscoveredDevice>&)> cb;
+ std::vector<DiscoveredDevice> grouped;
{
std::lock_guard<std::mutex> lock(ctx->impl->results_mutex);
// Deduplicate by address+port
@@ -195,10 +197,13 @@ namespace tether {
}
if (ctx->impl->browse_callback) {
- auto grouped = group_discovered_hosts(ctx->impl->results);
- ctx->impl->browse_callback(grouped);
+ cb = ctx->impl->browse_callback;
+ grouped = group_discovered_hosts(ctx->impl->results);
}
}
+
+ if (cb)
+ cb(grouped);
}
avahi_service_resolver_free(r);
@@ -228,16 +233,22 @@ namespace tether {
resolve_callback,
userdata);
} else if (event == AVAHI_BROWSER_REMOVE) {
- std::lock_guard<std::mutex> lock(ctx->impl->results_mutex);
- ctx->impl->results.erase(std::remove_if(ctx->impl->results.begin(),
- ctx->impl->results.end(),
- [&](const DiscoveredHost& h) { return h.name == name; }),
- ctx->impl->results.end());
-
- if (ctx->impl->browse_callback) {
- auto grouped = group_discovered_hosts(ctx->impl->results);
- ctx->impl->browse_callback(grouped);
+ std::function<void(const std::vector<DiscoveredDevice>&)> cb;
+ std::vector<DiscoveredDevice> grouped;
+ {
+ std::lock_guard<std::mutex> lock(ctx->impl->results_mutex);
+ ctx->impl->results.erase(std::remove_if(ctx->impl->results.begin(),
+ ctx->impl->results.end(),
+ [&](const DiscoveredHost& h) { return h.name == name; }),
+ ctx->impl->results.end());
+
+ if (ctx->impl->browse_callback) {
+ cb = ctx->impl->browse_callback;
+ grouped = group_discovered_hosts(ctx->impl->results);
+ }
}
+ if (cb)
+ cb(grouped);
}
}
@@ -245,7 +256,12 @@ namespace tether {
Discovery::Discovery() : impl_(std::make_unique<Impl>()) {}
- Discovery::~Discovery() { unpublish(); }
+ Discovery::~Discovery() {
+ // Both, not just unpublish(): a running continuous browse keeps its own poll
+ // thread alive and its callback fires into freed state during shutdown.
+ stop_continuous_browse();
+ unpublish();
+ }
Discovery::Discovery(Discovery&&) noexcept = default;
Discovery& Discovery::operator=(Discovery&&) noexcept = default;
@@ -418,24 +434,27 @@ namespace tether {
}
void Discovery::stop_continuous_browse() {
- if (impl_->browse_poll) {
- avahi_threaded_poll_stop(impl_->browse_poll);
- if (impl_->browse_browser)
- avahi_service_browser_free(impl_->browse_browser);
- if (impl_->browse_client)
- avahi_client_free(impl_->browse_client);
- avahi_threaded_poll_free(impl_->browse_poll);
+ if (!impl_->browse_poll)
+ return;
- if (impl_->browse_ctx) {
- delete static_cast<BrowseContext*>(impl_->browse_ctx);
- impl_->browse_ctx = nullptr;
- }
+ avahi_threaded_poll_stop(impl_->browse_poll);
- impl_->browse_browser = nullptr;
- impl_->browse_client = nullptr;
- impl_->browse_poll = nullptr;
- impl_->browse_callback = nullptr;
+ impl_->browse_callback = nullptr;
+
+ if (impl_->browse_browser)
+ avahi_service_browser_free(impl_->browse_browser);
+ if (impl_->browse_client)
+ avahi_client_free(impl_->browse_client);
+ avahi_threaded_poll_free(impl_->browse_poll);
+
+ if (impl_->browse_ctx) {
+ delete static_cast<BrowseContext*>(impl_->browse_ctx);
+ impl_->browse_ctx = nullptr;
}
+
+ impl_->browse_browser = nullptr;
+ impl_->browse_client = nullptr;
+ impl_->browse_poll = nullptr;
}
// ─── Grouping helper ────────────────────────────────────────────
diff --git a/src/core/src/file_transfer.cpp b/src/core/src/file_transfer.cpp
index 10b5a7e..4cf04a6 100644
--- a/src/core/src/file_transfer.cpp
+++ b/src/core/src/file_transfer.cpp
@@ -87,7 +87,30 @@ namespace tether {
auto& t = it->second;
auto raw_data = base64_decode(b64_data);
+ // Never write past the size the peer declared in file_start. Without this a
+ // buggy or hostile sender can stream unbounded data into $XDG_DOWNLOAD_DIR.
+ if (t->bytes_written + raw_data.size() > t->expected_size) {
+ debug::log(ERR,
+ "FileReceiveManager: transfer {} exceeds declared size {} (chunk {}); aborting",
+ transfer_id,
+ t->expected_size,
+ chunk_index);
+ t->stream->close();
+ std::error_code ec;
+ std::filesystem::remove(t->filepath, ec);
+ transfers_.erase(it);
+ return false;
+ }
+
t->stream->write(reinterpret_cast<const char*>(raw_data.data()), raw_data.size());
+ if (!*t->stream) {
+ debug::log(ERR, "FileReceiveManager: write failed for {} (disk full?)", t->filepath.string());
+ t->stream->close();
+ std::error_code ec;
+ std::filesystem::remove(t->filepath, ec);
+ transfers_.erase(it);
+ return false;
+ }
t->bytes_written += raw_data.size();
return true;
@@ -108,6 +131,20 @@ namespace tether {
auto& t = it->second;
t->stream->close();
+ // A short transfer used to be reported as "success", leaving a truncated
+ // file in Downloads and telling the sender it went through.
+ if (t->bytes_written != t->expected_size) {
+ debug::log(ERR,
+ "FileReceiveManager: transfer {} truncated ({} of {} bytes); discarding",
+ transfer_id,
+ t->bytes_written,
+ t->expected_size);
+ std::error_code ec;
+ std::filesystem::remove(t->filepath, ec);
+ transfers_.erase(it);
+ return false;
+ }
+
completed_path = t->filepath;
bytes_written = t->bytes_written;
on_complete = on_complete_;
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index a594f9d..3f78e8c 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -14,8 +14,8 @@
#include "tether/crypto.hpp"
#include "tether/discovery.hpp"
#include "tether/file_transfer.hpp"
+#include "tether/otp.hpp"
#include "tether/wayland.hpp"
-#include <chrono>
#include <cstring>
#include <filesystem>
#include <fstream>
@@ -55,34 +55,52 @@ namespace tether {
static std::vector<ReceivedFileInfo> recent_received_files;
static constexpr size_t kMaxRecentReceivedFiles = 16;
static std::map<int, ConnectedClientSnapshot> connected_remote_clients;
- static std::string g_current_otp;
- static std::chrono::steady_clock::time_point g_otp_set_at;
- // 5-min TTL backstop; consume-on-fill is the primary guard
- static constexpr auto kOtpTtl = std::chrono::minutes(5);
- void register_client_fd(int fd) { active_sessions[fd] = {fd, nullptr}; }
+ void register_client_fd(int fd) {
+ std::lock_guard<std::mutex> lock(g_sessions_mutex);
+ active_sessions[fd] = {fd, nullptr};
+ }
- void register_client_ssl(int fd, SSL* ssl) { active_sessions[fd] = {fd, ssl}; }
+ void register_client_ssl(int fd, SSL* ssl) {
+ std::lock_guard<std::mutex> lock(g_sessions_mutex);
+ active_sessions[fd] = {fd, ssl};
+ }
void unregister_client_fd(int fd) {
- active_sessions.erase(fd);
+ {
+ std::lock_guard<std::mutex> lock(g_sessions_mutex);
+ active_sessions.erase(fd);
+ }
std::lock_guard<std::mutex> lock(g_subscribers_mutex);
local_subscribers.erase(fd);
}
+ // The extension may send the code as a JSON string or a JSON number. Reading a
+ // number straight into std::string throws type_error.302, which the bare catch in
+ // the message loop swallowed, silently dropping the OTP.
+ static std::string otp_from_json(const nlohmann::json& value) {
+ if (value.is_string())
+ return value.get<std::string>();
+ if (value.is_number_integer())
+ return std::to_string(value.get<long long>());
+ if (value.is_number_unsigned())
+ return std::to_string(value.get<unsigned long long>());
+ return "";
+ }
+
+ static nlohmann::json make_otp_event(const Otp& otp) {
+ nlohmann::json event;
+ event["command"] = "otp_available";
+ event["otp"] = otp.code;
+ event["otp_id"] = otp.id;
+ return event;
+ }
+
void register_local_subscriber(int fd) {
std::lock_guard<std::mutex> lock(g_subscribers_mutex);
local_subscribers.insert(fd);
}
- // Returns the stored OTP, clearing it first if it has aged past the TTL.
- static std::string current_otp_if_fresh() {
- if (!g_current_otp.empty() && std::chrono::steady_clock::now() - g_otp_set_at >= kOtpTtl) {
- g_current_otp.clear();
- }
- return g_current_otp;
- }
-
void unregister_local_subscriber(int fd) {
std::lock_guard<std::mutex> lock(g_subscribers_mutex);
local_subscribers.erase(fd);
@@ -115,7 +133,7 @@ namespace tether {
if (!packet.empty() && packet.back() != '\n')
packet += '\n';
- std::lock_guard<std::mutex> lock(g_subscribers_mutex);
+ std::lock_guard<std::mutex> lock(g_sessions_mutex);
for (auto const& [fd, session] : active_sessions) {
if (fd == exclude_fd)
continue;
@@ -253,7 +271,7 @@ namespace tether {
packet += '\n';
size_t recipients = 0;
- std::lock_guard<std::mutex> lock(g_subscribers_mutex);
+ std::lock_guard<std::mutex> lock(g_sessions_mutex);
for (auto const& [fd, session] : active_sessions) {
if (fd == exclude_fd || !session.ssl)
continue;
@@ -320,6 +338,16 @@ namespace tether {
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
+ // sun_path is 108 bytes. strncpy would silently truncate a longer path and we
+ // would end up listening somewhere nobody is looking.
+ if (socket_path_.size() >= sizeof(addr.sun_path)) {
+ debug::log(ERR,
+ "Socket path too long ({} bytes, max {}): {}",
+ socket_path_.size(),
+ sizeof(addr.sun_path) - 1,
+ socket_path_);
+ return false;
+ }
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) {
@@ -380,15 +408,19 @@ namespace tether {
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);
+ ssize_t n = read(client_fd, buf, sizeof(buf));
if (n > 0) {
- buf[n] = '\0';
- client_buffers_[client_fd] += std::string(buf, n);
+ // Reference + cursor rather than erase(0, ...) per message: the old form
+ // shifted the whole remaining buffer down for every line, which is O(n^2)
+ // over the ~683 KB base64 payloads file transfers push through here.
+ std::string& buffer = client_buffers_[client_fd];
+ buffer.append(buf, n);
+ size_t start = 0;
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);
+ while ((pos = buffer.find('\n', start)) != std::string::npos) {
+ std::string msg = buffer.substr(start, pos - start);
+ start = pos + 1;
try {
nlohmann::json j = nlohmann::json::parse(msg);
@@ -401,13 +433,11 @@ namespace tether {
}
// Replay any current OTP so a freshly reconnected extension
// (MV3 service worker restart) gets it without waiting for a
- // new_otp push it may have missed while disconnected.
- std::string otp = current_otp_if_fresh();
- if (!otp.empty()) {
- nlohmann::json event;
- event["command"] = "otp_available";
- event["otp"] = otp;
- std::string otp_payload = event.dump() + "\n";
+ // new_otp push it may have missed while disconnected. Skip the
+ // replay once a page has already taken the code, otherwise the
+ // restart re-injects it into whatever site the user is on now.
+ if (Otp otp = otp_peek(); otp && !otp_is_claimed()) {
+ std::string otp_payload = make_otp_event(otp).dump() + "\n";
if (write(client_fd, otp_payload.c_str(), otp_payload.size()) < 0) {
debug::log(ERR, "net write error\n");
}
@@ -442,31 +472,30 @@ namespace tether {
continue;
}
} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {
- g_current_otp = j["otp"];
- g_otp_set_at = std::chrono::steady_clock::now();
+ std::string code = otp_from_json(j["otp"]);
+ uint64_t id = otp_store(code);
// Push the code to local subscribers (browser extension, GTK, etc.)
// so the browser fills it without depending on its polling timing.
- nlohmann::json event;
- event["command"] = "otp_available";
- event["otp"] = g_current_otp;
- broadcast_local_event(event.dump(), client_fd);
+ broadcast_local_event(make_otp_event({code, id}).dump(), client_fd);
std::string payload = "{\"status\":\"ok\"}\n";
if (write(client_fd, payload.c_str(), payload.size()) < 0) {
debug::log(ERR, "net write error\n");
}
continue;
} else if (j.contains("command") && j["command"] == "request_otp") {
- nlohmann::json resp;
- resp["command"] = "otp_available";
- resp["otp"] = current_otp_if_fresh();
- std::string payload = resp.dump() + "\n";
+ // Claimed by the first site that polls for it, so the next site
+ // the user visits doesn't get handed the previous site's code.
+ Otp otp = otp_take_for_host(j.value("url", std::string{}));
+ std::string payload = make_otp_event(otp).dump() + "\n";
if (write(client_fd, payload.c_str(), payload.size()) < 0) {
debug::log(ERR, "net write error\n");
}
continue;
} else if (j.contains("command") && j["command"] == "consume_otp") {
- // The extension filled the code; clear it so it isn't re-served.
- g_current_otp.clear();
+ // A page filled the code; retire it so it isn't re-served. Scoped
+ // to the id so a slow consume from the previous page can't wipe
+ // the code that just arrived for the current one.
+ otp_consume(j.value("otp_id", static_cast<uint64_t>(0)));
std::string payload = "{\"status\":\"ok\"}\n";
if (write(client_fd, payload.c_str(), payload.size()) < 0) {
debug::log(ERR, "net write error\n");
@@ -624,6 +653,10 @@ namespace tether {
debug::log(ERR, "net write error\n");
}
}
+
+ if (start > 0) {
+ buffer.erase(0, start); // compact once per read, not once per message
+ }
} else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
// Disconnected
debug::log(INFO, "UnixServer: Client disconnected (fd: {})", client_fd);
@@ -795,15 +828,18 @@ namespace tether {
}
char buf[65536];
- int n = SSL_read(ssl, buf, sizeof(buf) - 1);
+ int n = SSL_read(ssl, buf, sizeof(buf));
if (n > 0) {
- buf[n] = '\0';
- client_buffers_[client_fd] += std::string(buf, n);
+ // See UnixServer::handle_client — cursor instead of a per-message erase.
+ // This is the hot path for inbound file transfers.
+ std::string& buffer = client_buffers_[client_fd];
+ buffer.append(buf, n);
+ size_t start = 0;
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);
+ while ((pos = buffer.find('\n', start)) != std::string::npos) {
+ std::string msg = buffer.substr(start, pos - start);
+ start = pos + 1;
try {
nlohmann::json j = nlohmann::json::parse(msg);
@@ -878,14 +914,11 @@ namespace tether {
} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {
// OTP sent from a mobile client (iPhone Share Extension) over mTLS.
// Store it in the global vault so the browser extension can retrieve it.
- g_current_otp = j["otp"].get<std::string>();
- g_otp_set_at = std::chrono::steady_clock::now();
+ std::string code = otp_from_json(j["otp"]);
+ uint64_t id = otp_store(code);
// Notify local subscribers (GTK, browser ext, etc.) using the
// otp_available shape the browser extension listens for.
- nlohmann::json event;
- event["command"] = "otp_available";
- event["otp"] = g_current_otp;
- broadcast_local_event(event.dump());
+ broadcast_local_event(make_otp_event({code, id}).dump());
std::string payload = "{\"status\":\"ok\"}\n";
robust_ssl_write(ssl, payload.c_str(), payload.size());
continue;
@@ -912,6 +945,10 @@ namespace tether {
std::string response = "OK\n";
robust_ssl_write(ssl, response.c_str(), response.size());
}
+
+ if (start > 0) {
+ buffer.erase(0, start);
+ }
} else {
int err = SSL_get_error(ssl, n);
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
diff --git a/src/core/src/otp.cpp b/src/core/src/otp.cpp
new file mode 100644
index 0000000..f257ae7
--- /dev/null
+++ b/src/core/src/otp.cpp
@@ -0,0 +1,90 @@
+#include "tether/otp.hpp"
+
+#include <mutex>
+
+namespace tether {
+
+ namespace {
+ std::mutex g_mutex;
+ std::string g_code;
+ uint64_t g_id = 0;
+ uint64_t g_next_id = 1;
+ std::string g_claimed_host; // empty until some host takes the code
+ OtpClock::time_point g_set_at;
+
+ // Caller holds g_mutex.
+ void clear_locked() {
+ g_code.clear();
+ g_id = 0;
+ g_claimed_host.clear();
+ }
+
+ // Caller holds g_mutex. Drops the code once it ages past the TTL.
+ Otp peek_locked(OtpClock::time_point now) {
+ if (g_id == 0)
+ return {};
+ if (now - g_set_at >= kOtpTtl) {
+ clear_locked();
+ return {};
+ }
+ return {g_code, g_id};
+ }
+ } // namespace
+
+ uint64_t otp_store(const std::string& code, OtpClock::time_point now) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (code.empty()) {
+ clear_locked();
+ return 0;
+ }
+ g_code = code;
+ g_id = g_next_id++;
+ g_claimed_host.clear();
+ g_set_at = now;
+ return g_id;
+ }
+
+ Otp otp_peek(OtpClock::time_point now) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return peek_locked(now);
+ }
+
+ Otp otp_take_for_host(const std::string& host, OtpClock::time_point now) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ Otp current = peek_locked(now);
+ if (!current)
+ return {};
+
+ // An unknown host (older extension that doesn't send url) may take an unclaimed
+ // code but never claims it, so it can't lock other sites out.
+ if (host.empty())
+ return g_claimed_host.empty() ? current : Otp{};
+
+ if (g_claimed_host.empty()) {
+ g_claimed_host = host;
+ return current;
+ }
+ return g_claimed_host == host ? current : Otp{};
+ }
+
+ void otp_consume(uint64_t id) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (id == 0 || id == g_id) {
+ clear_locked();
+ }
+ // else: a stale consume for an already-replaced code. Ignore it, otherwise a
+ // slow round trip from the previous page wipes the code the user is waiting on.
+ }
+
+ bool otp_is_claimed() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return g_id != 0 && !g_claimed_host.empty();
+ }
+
+ void otp_reset() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ clear_locked();
+ g_next_id = 1;
+ }
+
+} // namespace tether
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 5388c9a..72f34d2 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -3,6 +3,7 @@ add_executable(tether_test
test_crypto.cpp
test_discovery.cpp
test_file_transfer.cpp
+ test_otp.cpp
)
target_include_directories(tether_test PRIVATE
diff --git a/test/test_base64.cpp b/test/test_base64.cpp
index 8b54d90..7b594ca 100644
--- a/test/test_base64.cpp
+++ b/test/test_base64.cpp
@@ -56,3 +56,54 @@ TEST(Base64Test, DecodeInvalidChars) {
auto dec = tether::base64_decode("!!!");
EXPECT_TRUE(dec.empty());
}
+
+// Every byte value must survive a round trip. High bytes (>0x7F) become negative
+// chars in the encoded buffer and used to reach isalnum() as negative ints.
+TEST(Base64Test, RoundTripAllByteValues) {
+ std::vector<unsigned char> original(256);
+ for (int i = 0; i < 256; ++i) {
+ original[i] = static_cast<unsigned char>(i);
+ }
+
+ std::string enc = tether::base64_encode(original);
+ EXPECT_EQ(enc.size(), 344u); // ceil(256/3)*4
+ EXPECT_EQ(tether::base64_decode(enc), original);
+}
+
+TEST(Base64Test, RoundTripEveryLengthUpTo64) {
+ std::vector<unsigned char> data;
+ for (size_t len = 0; len <= 64; ++len) {
+ data.assign(len, 0);
+ for (size_t i = 0; i < len; ++i) {
+ data[i] = static_cast<unsigned char>((i * 37 + 11) & 0xFF);
+ }
+ std::string enc = tether::base64_encode(data);
+ EXPECT_EQ(tether::base64_decode(enc), data) << "length " << len;
+ }
+}
+
+TEST(Base64Test, DecodeStopsAtFirstInvalidByte) {
+ // Decoding is best-effort: it halts at the first non-base64 byte rather than
+ // producing garbage for the remainder.
+ auto dec = tether::base64_decode("aGVsbG8=trailing junk");
+ std::string dec_str(dec.begin(), dec.end());
+ EXPECT_EQ(dec_str, "hello");
+}
+
+TEST(Base64Test, DecodeHandlesHighBitBytesWithoutCrashing) {
+ std::string junk;
+ junk.push_back(static_cast<char>(0x80));
+ junk.push_back(static_cast<char>(0xFF));
+ junk.push_back(static_cast<char>(0xC3));
+ EXPECT_TRUE(tether::base64_decode(junk).empty());
+}
+
+TEST(Base64Test, RoundTripLargeChunk) {
+ // Matches the 512 KB chunk size Client::send_file uses.
+ std::vector<unsigned char> data(512 * 1024);
+ for (size_t i = 0; i < data.size(); ++i) {
+ data[i] = static_cast<unsigned char>(i & 0xFF);
+ }
+ std::string enc = tether::base64_encode(data);
+ EXPECT_EQ(tether::base64_decode(enc), data);
+}
diff --git a/test/test_file_transfer.cpp b/test/test_file_transfer.cpp
index a9f905c..fe80cd3 100644
--- a/test/test_file_transfer.cpp
+++ b/test/test_file_transfer.cpp
@@ -63,3 +63,67 @@ TEST_F(FileTransferTest, NameDeduplicatorAppendsCounterGracefully) {
std::getline(i2, r2);
EXPECT_EQ(r2, "DEF");
}
+
+TEST_F(FileTransferTest, MultiChunkTransferConcatenates) {
+ tether::FileReceiveManager mgr;
+
+ std::string t_id = "multi";
+ ASSERT_TRUE(mgr.handle_start(t_id, "parts.txt", 6));
+ EXPECT_TRUE(mgr.handle_chunk(t_id, 0, tether::base64_encode((const unsigned char*)"abc", 3)));
+ EXPECT_TRUE(mgr.handle_chunk(t_id, 1, tether::base64_encode((const unsigned char*)"def", 3)));
+ EXPECT_TRUE(mgr.handle_end(t_id));
+
+ std::ifstream iff("/tmp/tether_tests/Downloads/parts.txt");
+ std::string res;
+ std::getline(iff, res);
+ EXPECT_EQ(res, "abcdef");
+}
+
+TEST_F(FileTransferTest, RejectsChunkPastDeclaredSize) {
+ tether::FileReceiveManager mgr;
+
+ std::string t_id = "overflow";
+ ASSERT_TRUE(mgr.handle_start(t_id, "small.bin", 3));
+
+ // Peer declared 3 bytes but streams 8. The extra must not be written.
+ EXPECT_FALSE(mgr.handle_chunk(t_id, 0, tether::base64_encode((const unsigned char*)"AAAABBBB", 8)));
+ EXPECT_FALSE(mgr.handle_end(t_id)) << "aborted transfer must not report success";
+ EXPECT_FALSE(std::filesystem::exists("/tmp/tether_tests/Downloads/small.bin"));
+}
+
+TEST_F(FileTransferTest, TruncatedTransferIsNotReportedAsSuccess) {
+ tether::FileReceiveManager mgr;
+
+ std::string t_id = "short";
+ ASSERT_TRUE(mgr.handle_start(t_id, "short.bin", 10));
+ EXPECT_TRUE(mgr.handle_chunk(t_id, 0, tether::base64_encode((const unsigned char*)"ABC", 3)));
+
+ // Only 3 of 10 bytes arrived; this used to return true and leave a partial file.
+ EXPECT_FALSE(mgr.handle_end(t_id));
+ EXPECT_FALSE(std::filesystem::exists("/tmp/tether_tests/Downloads/short.bin"));
+}
+
+TEST_F(FileTransferTest, DuplicateTransferIdIsRejected) {
+ tether::FileReceiveManager mgr;
+
+ EXPECT_TRUE(mgr.handle_start("dup", "a.txt", 3));
+ EXPECT_FALSE(mgr.handle_start("dup", "b.txt", 3));
+}
+
+TEST_F(FileTransferTest, UnknownTransferIdIsRejected) {
+ tether::FileReceiveManager mgr;
+
+ EXPECT_FALSE(mgr.handle_chunk("nope", 0, tether::base64_encode((const unsigned char*)"AB", 2)));
+ EXPECT_FALSE(mgr.handle_end("nope"));
+}
+
+TEST_F(FileTransferTest, PathTraversalInFilenameStaysInDownloads) {
+ tether::FileReceiveManager mgr;
+
+ ASSERT_TRUE(mgr.handle_start("trav", "../../../etc/tether_pwned", 3));
+ ASSERT_TRUE(mgr.handle_chunk("trav", 0, tether::base64_encode((const unsigned char*)"xyz", 3)));
+ ASSERT_TRUE(mgr.handle_end("trav"));
+
+ EXPECT_TRUE(std::filesystem::exists("/tmp/tether_tests/Downloads/tether_pwned"));
+ EXPECT_FALSE(std::filesystem::exists("/tmp/tether_tests/etc/tether_pwned"));
+}