Skip to content

Linux + iPhone Continuity / iMessage / SMS

format and cleanup stdout/err

Zack Bartel20d50fea7e0c
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 47b6d2e..6ce439f 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -1,9 +1,9 @@
-#include <iostream>
#include <string>
-#include <unistd.h>
#include <tether/client.hpp>
-#include <tether/discovery.hpp>
#include <tether/crypto.hpp>
+#include <tether/discovery.hpp>
+#include <tether/log.hpp>
+#include <unistd.h>
void print_help() {
std::cout << "tether - Wayland companion CLI\n\n"
@@ -44,25 +44,40 @@ int main(int argc, char* argv[]) {
if (arg == "-h" || arg == "--help") {
print_help();
return 0;
- } else if (arg == "-g" || arg == "--get-clipboard") { action = "get"; }
- else if (arg == "-d" || arg == "--discover") { action = "discover"; }
- else if (arg == "--list-devices") { action = "list"; }
- else if (arg == "--pair") { action = "pair"; }
- else if (arg == "--accept") { action = "accept"; if (i + 1 < argc && argv[i + 1][0] != '-') arg_val = argv[++i]; }
- else if (arg == "--host") { if (i + 1 < argc && argv[i + 1][0] != '-') host = argv[++i]; }
- else if (arg == "--port") { if (i + 1 < argc && argv[i + 1][0] != '-') port = std::stoi(argv[++i]); }
- else if (arg == "--timeout") { if (i + 1 < argc && argv[i + 1][0] != '-') timeout_ms = std::stoi(argv[++i]); }
- else if (arg == "-f" || arg == "--send-file") {
+ } else if (arg == "-g" || arg == "--get-clipboard") {
+ action = "get";
+ } else if (arg == "-d" || arg == "--discover") {
+ action = "discover";
+ } else if (arg == "--list-devices") {
+ action = "list";
+ } else if (arg == "--pair") {
+ action = "pair";
+ } else if (arg == "--accept") {
+ action = "accept";
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ arg_val = argv[++i];
+ } else if (arg == "--host") {
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ host = argv[++i];
+ } else if (arg == "--port") {
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ port = std::stoi(argv[++i]);
+ } else if (arg == "--timeout") {
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ timeout_ms = std::stoi(argv[++i]);
+ } else if (arg == "-f" || arg == "--send-file") {
action = "file";
- if (i + 1 < argc && argv[i + 1][0] != '-') arg_val = argv[++i];
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ arg_val = argv[++i];
} else if (arg == "-s" || arg == "--set-clipboard") {
action = "set";
- if (i + 1 < argc && argv[i + 1][0] != '-') arg_val = argv[++i];
+ if (i + 1 < argc && argv[i + 1][0] != '-')
+ arg_val = argv[++i];
}
}
if (action.empty()) {
- std::cerr << "Unknown action. Run tether --help for options\n";
+ debug::log(ERR, "Unknown action. Run tether --help for options\n");
return 1;
}
@@ -70,21 +85,21 @@ int main(int argc, char* argv[]) {
// Fast-path local operations that don't need active daemon connection fundamentally
if (action == "list") {
- std::cout << client.list_devices() << "\n";
+ debug::log(INFO, "{}", client.list_devices());
return 0;
} else if (action == "accept") {
client.accept_device(arg_val);
- std::cout << "Successfully paired device: " << arg_val << "\n";
+ debug::log(INFO, "Successfully paired device: {}", arg_val);
return 0;
} else if (action == "discover") {
- std::cout << "Scanning for tetherd instances on the local network...\n\n";
+ debug::log(INFO, "Scanning for tetherd instances on the local network...\n\n");
tether::Discovery discovery;
auto hosts = discovery.discover(timeout_ms);
auto devices = tether::group_discovered_hosts(hosts);
if (devices.empty()) {
- std::cout << " No tetherd instances found.\n";
+ debug::log(INFO, " No tetherd instances found.\n");
} else {
tether::Crypto::instance().init();
for (const auto& dev : devices) {
@@ -92,27 +107,31 @@ int main(int argc, char* argv[]) {
if (!dev.fingerprint.empty() && tether::Crypto::instance().is_host_known(dev.fingerprint)) {
status = "[known]";
}
- printf(" %-20s %s\n", dev.name.c_str(), status.c_str());
+ debug::log(INFO, " %-20s %s\n", dev.name.c_str(), status.c_str());
for (const auto& addr : dev.addresses) {
- printf(" %s:%d\n", addr.address.c_str(), addr.port);
+ debug::log(INFO, " %s:%d\n", addr.address.c_str(), addr.port);
}
- printf("\n");
+ debug::log(INFO, "\n");
}
}
- printf("Found %zu device(s) in %.1fs\n", devices.size(), timeout_ms / 1000.0);
+ debug::log(INFO, "Found %zu device(s) in %.1fs\n", devices.size(), timeout_ms / 1000.0);
return 0;
}
if (action == "set" && arg_val.empty()) {
std::string line;
- while (std::getline(std::cin, line)) arg_val += line + "\n";
- if (!arg_val.empty() && arg_val.back() == '\n') arg_val.pop_back();
+ while (std::getline(std::cin, line))
+ arg_val += line + "\n";
+ if (!arg_val.empty() && arg_val.back() == '\n')
+ arg_val.pop_back();
}
// Bind network abstraction natively
if (!client.connect(host, port)) {
- std::cerr << "Explicit framework connection locally rejected! Did you target explicitly invalid TLS or is daemon broken?\n";
+ debug::log(ERR,
+ "Explicit framework connection locally rejected! Did you target explicitly invalid TLS or is daemon "
+ "broken?\n");
return 1;
}
@@ -122,29 +141,29 @@ int main(int argc, char* argv[]) {
gethostname(hostname, sizeof(hostname) - 1);
std::string resp = client.pair(hostname, err);
if (!err.empty()) {
- std::cerr << err << "\n";
+ debug::log(ERR, "{}", err);
return 1;
}
- std::cout << "Pairing response: " << resp << std::flush;
+ debug::log(INFO, "Pairing response: {}", resp);
} else if (action == "get") {
std::string clip = client.get_clipboard(err);
if (!err.empty()) {
- std::cerr << err << "\n";
+ debug::log(ERR, "{}", err);
return 1;
}
- std::cout << clip << std::flush;
+ debug::log(INFO, "{}", clip);
} else if (action == "set") {
if (!client.set_clipboard(arg_val, err)) {
- std::cerr << err << "\n";
+ debug::log(ERR, "{}", err);
return 1;
}
} else if (action == "file") {
- std::cout << "Sending " << arg_val << "..." << std::endl;
+ debug::log(INFO, "Sending {}...", arg_val);
if (!client.send_file(arg_val, err)) {
- std::cerr << "Transfer Failed: " << err << "\n";
+ debug::log(ERR, "Transfer Failed: {}", err);
return 1;
}
- std::cout << "File transfer delivered.\n";
+ debug::log(INFO, "File transfer delivered.\n");
}
return 0;
diff --git a/src/core/include/tether/log.hpp b/src/core/include/tether/log.hpp
new file mode 100644
index 0000000..4a74f1f
--- /dev/null
+++ b/src/core/include/tether/log.hpp
@@ -0,0 +1,56 @@
+#pragma once
+
+#include <format>
+#include <iostream>
+#include <filesystem>
+
+template <>
+struct std::formatter<std::filesystem::path> : std::formatter<std::string> {
+ auto format(const std::filesystem::path& p, std::format_context& ctx) const {
+ return std::formatter<std::string>::format(p.string(), ctx);
+ }
+};
+
+enum LogLevel { TRACE = 0, DEBUG, INFO, WARN, ERR, CRIT };
+
+namespace debug {
+ inline bool verbose = false;
+ inline bool quiet = false;
+ template <typename... Args> void log(LogLevel level, const std::string& fmt, Args&&... args) {
+
+ if (quiet && level < ERR) {
+ return;
+ }
+ if (!verbose && level == TRACE) {
+ return;
+ }
+ std::cerr << '[';
+
+ switch (level) {
+ case TRACE:
+ std::cerr << "TRACE";
+ break;
+ case DEBUG:
+ std::cerr << "DEBUG";
+ break;
+ case INFO:
+ std::cerr << "INFO";
+ break;
+ case WARN:
+ std::cerr << "WARN";
+ break;
+ case ERR:
+ std::cerr << "ERR";
+ break;
+ case CRIT:
+ std::cerr << "CRIT";
+ break;
+ default:
+ break;
+ }
+
+ std::cerr << "] ";
+
+ std::cerr << std::vformat(fmt, std::make_format_args(args...)) << std::endl;
+ }
+} // namespace debug
diff --git a/src/core/src/client.cpp b/src/core/src/client.cpp
index f2c6189..98d6598 100644
--- a/src/core/src/client.cpp
+++ b/src/core/src/client.cpp
@@ -1,312 +1,320 @@
#include "tether/client.hpp"
+#include "tether/base64.hpp"
#include "tether/core.hpp"
#include "tether/crypto.hpp"
#include "tether/net.hpp"
-#include "tether/base64.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <filesystem>
#include <fstream>
-#include <iostream>
#include <nlohmann/json.hpp>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
+#include <tether/log.hpp>
#include <unistd.h>
namespace tether {
-namespace {
+ namespace {
-std::string extract_protocol_error(const std::string& response) {
- try {
- nlohmann::json parsed = nlohmann::json::parse(response);
- if (parsed.value("command", "") == "error") {
- return parsed.value("message", "unknown_error");
- }
- } catch (...) {
- }
+ std::string extract_protocol_error(const std::string& response) {
+ try {
+ nlohmann::json parsed = nlohmann::json::parse(response);
+ if (parsed.value("command", "") == "error") {
+ return parsed.value("message", "unknown_error");
+ }
+ } catch (...) {
+ }
- return "";
-}
+ return "";
+ }
-}
+ } // namespace
-Client::Client() {}
+ Client::Client() {}
-Client::~Client() {
- disconnect();
-}
+ Client::~Client() { disconnect(); }
-void Client::disconnect() {
- if (ssl_) {
- SSL_free(ssl_);
- ssl_ = nullptr;
+ void Client::disconnect() {
+ if (ssl_) {
+ SSL_free(ssl_);
+ ssl_ = nullptr;
+ }
+ if (sock_ >= 0) {
+ close(sock_);
+ sock_ = -1;
+ }
}
- if (sock_ >= 0) {
- close(sock_);
- sock_ = -1;
+
+ bool Client::is_connected() const { return sock_ >= 0; }
+
+ std::string Client::get_peer_fingerprint() const {
+ if (!ssl_)
+ return "";
+ return Crypto::get_peer_fingerprint(ssl_);
}
-}
-
-bool Client::is_connected() const {
- return sock_ >= 0;
-}
-
-std::string Client::get_peer_fingerprint() const {
- if (!ssl_) return "";
- return Crypto::get_peer_fingerprint(ssl_);
-}
-
-int Client::connect_unix(bool retry) {
- int sock = socket(AF_UNIX, SOCK_STREAM, 0);
- if (sock < 0) return -1;
-
- sockaddr_un addr{};
- addr.sun_family = AF_UNIX;
- std::string path = tether::get_runtime_dir() + "/tetherd.sock";
- std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
-
- if (::connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
- close(sock);
- if (!retry) return -1;
-
- pid_t pid = fork();
- if (pid == 0) {
- std::filesystem::path self_path = std::filesystem::read_symlink("/proc/self/exe");
- std::string daemon_path = (self_path.parent_path() / "tetherd").string();
-
- if (fork() == 0) {
- if (freopen("/dev/null", "w", stdout) == nullptr) {}
- if (freopen("/dev/null", "w", stderr) == nullptr) {}
- if (freopen("/dev/null", "r", stdin) == nullptr) {}
-
- execl(daemon_path.c_str(), "tetherd", nullptr);
- execlp("tetherd", "tetherd", nullptr);
- exit(1);
+
+ int Client::connect_unix(bool retry) {
+ int sock = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (sock < 0)
+ return -1;
+
+ sockaddr_un addr{};
+ addr.sun_family = AF_UNIX;
+ std::string path = tether::get_runtime_dir() + "/tetherd.sock";
+ std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
+
+ if (::connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
+ close(sock);
+ if (!retry)
+ return -1;
+
+ pid_t pid = fork();
+ if (pid == 0) {
+ std::filesystem::path self_path = std::filesystem::read_symlink("/proc/self/exe");
+ std::string daemon_path = (self_path.parent_path() / "tetherd").string();
+
+ if (fork() == 0) {
+ if (freopen("/dev/null", "w", stdout) == nullptr) {
+ }
+ if (freopen("/dev/null", "w", stderr) == nullptr) {
+ }
+ if (freopen("/dev/null", "r", stdin) == nullptr) {
+ }
+
+ execl(daemon_path.c_str(), "tetherd", nullptr);
+ execlp("tetherd", "tetherd", nullptr);
+ exit(1);
+ }
+ exit(0);
+ } else if (pid > 0) {
+ int status;
+ waitpid(pid, &status, 0);
+ usleep(300000);
+ return connect_unix(false);
}
- exit(0);
- } else if (pid > 0) {
- int status;
- waitpid(pid, &status, 0);
- usleep(300000);
- return connect_unix(false);
+ return -1;
}
- return -1;
+ return sock;
}
- return sock;
-}
-bool Client::connect(const std::string& host, int port) {
- disconnect();
+ bool Client::connect(const std::string& host, int port) {
+ 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 (!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 (::connect(sock_, (sockaddr*)&addr, sizeof(addr)) < 0) {
- return false;
- }
+ if (::connect(sock_, (sockaddr*)&addr, sizeof(addr)) < 0) {
+ return false;
+ }
- tether::Crypto::instance().init();
- ssl_ = SSL_new(tether::Crypto::instance().get_client_context());
- SSL_set_fd(ssl_, sock_);
- if (SSL_connect(ssl_) <= 0) {
- return false;
+ tether::Crypto::instance().init();
+ ssl_ = SSL_new(tether::Crypto::instance().get_client_context());
+ SSL_set_fd(ssl_, sock_);
+ if (SSL_connect(ssl_) <= 0) {
+ return false;
+ }
+ return true;
+ } else {
+ sock_ = connect_unix(true);
+ return sock_ >= 0;
}
- return true;
- } else {
- sock_ = connect_unix(true);
- return sock_ >= 0;
}
-}
-
-std::string Client::send_and_wait(const std::string& payload) {
- char buf[1024 * 1024]; // Generous payload buffer
-
- 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);
- }
- } else {
- if (write(sock_, payload.c_str(), payload.size()) < 0) {
- std::cerr << "client write error\n";
- }
- ssize_t n = read(sock_, buf, sizeof(buf) - 1);
- if (n > 0) {
- buf[n] = '\0';
- return std::string(buf);
+
+ std::string Client::send_and_wait(const std::string& payload) {
+ char buf[1024 * 1024]; // Generous payload buffer
+
+ 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);
+ }
+ } 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);
+ }
}
+ return "";
}
- return "";
-}
-
-std::string Client::get_clipboard(std::string& err_out) {
- nlohmann::json j;
- j["command"] = "clipboard_get";
- std::string response = send_and_wait(j.dump() + "\n");
-
- try {
- nlohmann::json r = nlohmann::json::parse(response);
- if (r.contains("content")) {
- return r["content"].get<std::string>();
- } else if (r.contains("message") && r["message"] == "unauthorized") {
- err_out = "Unauthorized. You must pair this device first.";
+
+ std::string Client::get_clipboard(std::string& err_out) {
+ nlohmann::json j;
+ j["command"] = "clipboard_get";
+ std::string response = send_and_wait(j.dump() + "\n");
+
+ try {
+ nlohmann::json r = nlohmann::json::parse(response);
+ if (r.contains("content")) {
+ return r["content"].get<std::string>();
+ } else if (r.contains("message") && r["message"] == "unauthorized") {
+ err_out = "Unauthorized. You must pair this device first.";
+ }
+ } catch (...) {
}
- } catch (...) {}
- return "";
-}
-
-bool Client::set_clipboard(const std::string& text, std::string& err_out) {
- nlohmann::json j;
- j["command"] = "clipboard_set";
- j["content"] = text;
- std::string s_resp = send_and_wait(j.dump() + "\n");
- if (s_resp.find("unauthorized") != std::string::npos) {
- err_out = "Unauthorized. Device not paired.";
- return false;
+ return "";
}
- return true;
-}
-
-std::string Client::list_devices() {
- tether::Crypto::instance().init();
- return tether::Crypto::instance().get_known_hosts_dump();
-}
-
-bool Client::accept_device(const std::string& fingerprint, const std::string& name) {
- tether::Crypto::instance().init();
-
- // Check if the daemon stored a name from the pair_request
- std::string resolved_name = name;
- std::string pending_path = tether::get_runtime_dir() + "/pending_pairs.json";
- nlohmann::json pending;
-
- std::ifstream ifs(pending_path);
- if (ifs.is_open()) {
- try { pending = nlohmann::json::parse(ifs); } catch (...) {}
- ifs.close();
+
+ bool Client::set_clipboard(const std::string& text, std::string& err_out) {
+ nlohmann::json j;
+ j["command"] = "clipboard_set";
+ j["content"] = text;
+ std::string s_resp = send_and_wait(j.dump() + "\n");
+ if (s_resp.find("unauthorized") != std::string::npos) {
+ err_out = "Unauthorized. Device not paired.";
+ return false;
+ }
+ return true;
}
- if (pending.contains(fingerprint) && pending[fingerprint].is_string()) {
- resolved_name = pending[fingerprint].get<std::string>();
- // Remove the accepted entry
- pending.erase(fingerprint);
- std::ofstream ofs(pending_path);
- ofs << pending.dump(4);
+ std::string Client::list_devices() {
+ tether::Crypto::instance().init();
+ return tether::Crypto::instance().get_known_hosts_dump();
}
- tether::Crypto::instance().add_known_host(resolved_name, fingerprint);
- return true;
-}
+ bool Client::accept_device(const std::string& fingerprint, const std::string& name) {
+ tether::Crypto::instance().init();
-std::string Client::pair(const std::string& device_name, std::string& err_out) {
- if (!ssl_) {
- err_out = "Pairing requires a TCP+TLS connection. Use --host to specify a target.";
- return "";
- }
- nlohmann::json j;
- j["command"] = "pair_request";
- j["device_name"] = device_name;
- std::string response = send_and_wait(j.dump() + "\n");
- if (response.empty()) {
- err_out = "No response from daemon.";
- }
- return response;
-}
+ // Check if the daemon stored a name from the pair_request
+ std::string resolved_name = name;
+ std::string pending_path = tether::get_runtime_dir() + "/pending_pairs.json";
+ nlohmann::json pending;
-bool Client::send_file(const std::string& path, std::string& err_out) {
- if (path.empty() || !std::filesystem::exists(path)) {
- err_out = "Invalid or missing file path.";
- return false;
- }
+ std::ifstream ifs(pending_path);
+ if (ifs.is_open()) {
+ try {
+ pending = nlohmann::json::parse(ifs);
+ } catch (...) {
+ }
+ ifs.close();
+ }
- std::ifstream file(path, std::ios::binary);
- if (!file.is_open()) {
- err_out = "Failed to open file.";
- return false;
+ if (pending.contains(fingerprint) && pending[fingerprint].is_string()) {
+ resolved_name = pending[fingerprint].get<std::string>();
+ // Remove the accepted entry
+ pending.erase(fingerprint);
+ std::ofstream ofs(pending_path);
+ ofs << pending.dump(4);
+ }
+
+ tether::Crypto::instance().add_known_host(resolved_name, fingerprint);
+ return true;
}
- 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));
-
- nlohmann::json j_start;
- j_start["command"] = "file_start";
- j_start["filename"] = filename;
- j_start["size"] = file_size;
- j_start["transfer_id"] = transfer_id;
-
- std::string s_resp = send_and_wait(j_start.dump() + "\n");
- if (std::string protocol_error = extract_protocol_error(s_resp); !protocol_error.empty()) {
- if (protocol_error == "unauthorized") {
- err_out = "Unauthorized. Device not paired.";
- } else if (protocol_error == "no_connected_mobile_client") {
- err_out = "No connected iPhone client is available.";
- } else {
- err_out = protocol_error;
+ std::string Client::pair(const std::string& device_name, std::string& err_out) {
+ if (!ssl_) {
+ err_out = "Pairing requires a TCP+TLS connection. Use --host to specify a target.";
+ return "";
}
- return false;
+ nlohmann::json j;
+ j["command"] = "pair_request";
+ j["device_name"] = device_name;
+ std::string response = send_and_wait(j.dump() + "\n");
+ if (response.empty()) {
+ err_out = "No response from daemon.";
+ }
+ return response;
}
- 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;
+ bool Client::send_file(const std::string& path, std::string& err_out) {
+ if (path.empty() || !std::filesystem::exists(path)) {
+ err_out = "Invalid or missing file path.";
+ return false;
+ }
- 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);
+ std::ifstream file(path, std::ios::binary);
+ if (!file.is_open()) {
+ err_out = "Failed to open file.";
+ return false;
+ }
- std::string chunk_resp = send_and_wait(j_chunk.dump() + "\n");
- if (std::string protocol_error = extract_protocol_error(chunk_resp); !protocol_error.empty()) {
- if (protocol_error == "no_connected_mobile_client") {
+ 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));
+
+ nlohmann::json j_start;
+ j_start["command"] = "file_start";
+ j_start["filename"] = filename;
+ j_start["size"] = file_size;
+ j_start["transfer_id"] = transfer_id;
+
+ std::string s_resp = send_and_wait(j_start.dump() + "\n");
+ if (std::string protocol_error = extract_protocol_error(s_resp); !protocol_error.empty()) {
+ if (protocol_error == "unauthorized") {
+ err_out = "Unauthorized. Device not paired.";
+ } else if (protocol_error == "no_connected_mobile_client") {
err_out = "No connected iPhone client is available.";
} else {
err_out = protocol_error;
}
return false;
}
- }
-
- nlohmann::json j_end;
- j_end["command"] = "file_end";
- j_end["transfer_id"] = transfer_id;
- std::string resp = send_and_wait(j_end.dump() + "\n");
- try {
- nlohmann::json r = nlohmann::json::parse(resp);
- if (r.contains("status") && r["status"] == "success") {
- return true;
+ 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);
+
+ std::string chunk_resp = send_and_wait(j_chunk.dump() + "\n");
+ if (std::string protocol_error = extract_protocol_error(chunk_resp); !protocol_error.empty()) {
+ if (protocol_error == "no_connected_mobile_client") {
+ err_out = "No connected iPhone client is available.";
+ } else {
+ err_out = protocol_error;
+ }
+ return false;
+ }
}
- if (r.value("command", "") == "error") {
- std::string message = r.value("message", "Transfer sequence explicitly rejected externally.");
- if (message == "no_connected_mobile_client") {
- err_out = "No connected iPhone client is available.";
- } else {
- err_out = message;
+
+ nlohmann::json j_end;
+ j_end["command"] = "file_end";
+ j_end["transfer_id"] = transfer_id;
+
+ std::string resp = send_and_wait(j_end.dump() + "\n");
+ try {
+ nlohmann::json r = nlohmann::json::parse(resp);
+ if (r.contains("status") && r["status"] == "success") {
+ return true;
}
- return false;
+ if (r.value("command", "") == "error") {
+ std::string message = r.value("message", "Transfer sequence explicitly rejected externally.");
+ if (message == "no_connected_mobile_client") {
+ err_out = "No connected iPhone client is available.";
+ } else {
+ err_out = message;
+ }
+ return false;
+ }
+ } catch (...) {
}
- } catch (...) {
+
+ err_out = "Transfer sequence explicitly rejected externally.";
+ return false;
}
-
- err_out = "Transfer sequence explicitly rejected externally.";
- return false;
-}
} // namespace tether
diff --git a/src/core/src/clipboard.cpp b/src/core/src/clipboard.cpp
index 3c2b1f5..6389757 100644
--- a/src/core/src/clipboard.cpp
+++ b/src/core/src/clipboard.cpp
@@ -1,7 +1,7 @@
#include "tether/clipboard.hpp"
#include "wayland_protocols/wlr-data-control-unstable-v1.hpp"
#include "wayland_protocols/wayland.hpp"
-#include <iostream>
+#include <tether/log.hpp>
#include <thread>
#include <unistd.h>
#include <fcntl.h>
@@ -159,7 +159,7 @@ void ClipboardManager::copy(const std::string& text) {
// the write simple but ensure it doesn't touch any manager state.
std::thread([text_to_send, fd]() {
if (write(fd, text_to_send.c_str(), text_to_send.size()) < 0) {
- std::cerr << "clipboard write error\n";
+ debug::log(ERR, "clipboard write error\n");
}
close(fd);
}).detach();
diff --git a/src/core/src/crypto.cpp b/src/core/src/crypto.cpp
index b8f0e70..dd175fa 100644
--- a/src/core/src/crypto.cpp
+++ b/src/core/src/crypto.cpp
@@ -3,7 +3,7 @@
#include <filesystem>
#include <fstream>
#include <iomanip>
-#include <iostream>
+#include <tether/log.hpp>
#include <nlohmann/json.hpp>
#include <openssl/evp.h>
#include <openssl/pem.h>
@@ -91,7 +91,7 @@ namespace tether {
return true;
}
- std::cout << "Crypto: Generating native mTLS RSA/X509 Keypair into ~/.config/tether/..." << std::endl;
+ debug::log(INFO, "Crypto: Generating native mTLS RSA/X509 Keypair into ~/.config/tether/...");
/*
EVP_PKEY* pkey = EVP_PKEY_new();
diff --git a/src/core/src/discovery.cpp b/src/core/src/discovery.cpp
index ed69e41..21b7e0f 100644
--- a/src/core/src/discovery.cpp
+++ b/src/core/src/discovery.cpp
@@ -11,7 +11,7 @@
#include <algorithm>
#include <chrono>
#include <cstring>
-#include <iostream>
+#include <tether/log.hpp>
#include <map>
#include <mutex>
#include <thread>
@@ -53,15 +53,13 @@ namespace tether {
auto* impl = static_cast<DiscoveryImpl*>(userdata);
switch (state) {
case AVAHI_ENTRY_GROUP_ESTABLISHED:
- std::cout << "mDNS: Published \"" << SERVICE_TYPE << "\" as \"" << impl->pub_name
- << "\" on port " << impl->pub_port << std::endl;
+ debug::log(INFO, "mDNS: Published \"{}\" as \"{}\" on port {}", SERVICE_TYPE, impl->pub_name, impl->pub_port);
break;
case AVAHI_ENTRY_GROUP_COLLISION:
- std::cerr << "mDNS: Service name collision for \"" << impl->pub_name << "\"" << std::endl;
+ debug::log(ERR, "mDNS: Service name collision for \"{}\"", impl->pub_name);
break;
case AVAHI_ENTRY_GROUP_FAILURE:
- std::cerr << "mDNS: Entry group failure: "
- << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << std::endl;
+ debug::log(ERR, "mDNS: Entry group failure: {}", avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))));
break;
default:
break;
@@ -74,8 +72,7 @@ namespace tether {
if (!impl->pub_group) {
impl->pub_group = avahi_entry_group_new(impl->pub_client, entry_group_callback, impl);
if (!impl->pub_group) {
- std::cerr << "mDNS: avahi_entry_group_new() failed: "
- << avahi_strerror(avahi_client_errno(impl->pub_client)) << std::endl;
+ debug::log(ERR, "mDNS: avahi_entry_group_new() failed: {}", avahi_strerror(avahi_client_errno(impl->pub_client)));
return;
}
}
@@ -100,13 +97,13 @@ namespace tether {
);
if (ret < 0) {
- std::cerr << "mDNS: Failed to add service: " << avahi_strerror(ret) << std::endl;
+ debug::log(ERR, "mDNS: Failed to add service: {}", avahi_strerror(ret));
return;
}
ret = avahi_entry_group_commit(impl->pub_group);
if (ret < 0) {
- std::cerr << "mDNS: Failed to commit entry group: " << avahi_strerror(ret) << std::endl;
+ debug::log(ERR, "mDNS: Failed to commit entry group: {}", avahi_strerror(ret));
}
}
}
@@ -120,7 +117,7 @@ namespace tether {
create_services(impl);
break;
case AVAHI_CLIENT_FAILURE:
- std::cerr << "mDNS: Client failure: " << avahi_strerror(avahi_client_errno(c)) << std::endl;
+ debug::log(ERR, "mDNS: Client failure: {}", avahi_strerror(avahi_client_errno(c)));
break;
case AVAHI_CLIENT_S_COLLISION:
case AVAHI_CLIENT_S_REGISTERING:
@@ -265,7 +262,7 @@ namespace tether {
impl_->pub_poll = avahi_threaded_poll_new();
if (!impl_->pub_poll) {
- std::cerr << "mDNS: Failed to create threaded poll" << std::endl;
+ debug::log(ERR, "mDNS: Failed to create threaded poll");
return false;
}
@@ -278,14 +275,14 @@ namespace tether {
&error);
if (!impl_->pub_client) {
- std::cerr << "mDNS: Failed to create client: " << avahi_strerror(error) << std::endl;
+ debug::log(ERR, "mDNS: Failed to create client: {}", avahi_strerror(error));
avahi_threaded_poll_free(impl_->pub_poll);
impl_->pub_poll = nullptr;
return false;
}
if (avahi_threaded_poll_start(impl_->pub_poll) < 0) {
- std::cerr << "mDNS: Failed to start threaded poll" << std::endl;
+ debug::log(ERR, "mDNS: Failed to start threaded poll");
avahi_client_free(impl_->pub_client);
impl_->pub_client = nullptr;
avahi_threaded_poll_free(impl_->pub_poll);
@@ -317,7 +314,7 @@ namespace tether {
std::vector<DiscoveredHost> Discovery::discover(int timeout_ms) {
AvahiThreadedPoll* poll = avahi_threaded_poll_new();
if (!poll) {
- std::cerr << "mDNS: Failed to create browse poll" << std::endl;
+ debug::log(ERR, "mDNS: Failed to create browse poll");
return {};
}
@@ -336,7 +333,7 @@ namespace tether {
&error);
if (!client) {
- std::cerr << "mDNS: Failed to create browse client: " << avahi_strerror(error) << std::endl;
+ debug::log(ERR, "mDNS: Failed to create browse client: {}", avahi_strerror(error));
avahi_threaded_poll_free(poll);
return {};
}
@@ -354,8 +351,7 @@ namespace tether {
&ctx);
if (!browser) {
- std::cerr << "mDNS: Failed to create browser: "
- << avahi_strerror(avahi_client_errno(client)) << std::endl;
+ debug::log(ERR, "mDNS: Failed to create browser: {}", avahi_strerror(avahi_client_errno(client)));
avahi_client_free(client);
avahi_threaded_poll_free(poll);
return {};
@@ -386,7 +382,7 @@ namespace tether {
impl_->browse_poll = avahi_threaded_poll_new();
if (!impl_->browse_poll) {
- std::cerr << "mDNS: Failed to create browse poll" << std::endl;
+ debug::log(ERR, "mDNS: Failed to create browse poll");
return;
}
diff --git a/src/core/src/event_loop.cpp b/src/core/src/event_loop.cpp
index 0ded5e6..c144d55 100644
--- a/src/core/src/event_loop.cpp
+++ b/src/core/src/event_loop.cpp
@@ -2,7 +2,7 @@
#include <sys/epoll.h>
#include <unistd.h>
#include <stdexcept>
-#include <iostream>
+#include <tether/log.hpp>
namespace tether {
@@ -26,7 +26,7 @@ bool EpollEventLoop::addFd(int fd, Callback cb) {
ev.data.fd = fd;
if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) < 0) {
- std::cerr << "Failed to add fd to epoll: " << fd << std::endl;
+ debug::log(ERR, "Failed to add fd to epoll: {}", fd);
return false;
}
callbacks_[fd] = std::move(cb);
@@ -50,7 +50,7 @@ void EpollEventLoop::run() {
int n = epoll_wait(epoll_fd_, events, MAX_EVENTS, -1);
if (n == -1) {
if (errno == EINTR) continue;
- std::cerr << "epoll_wait failed" << std::endl;
+ debug::log(ERR, "epoll_wait failed");
break;
}
diff --git a/src/core/src/file_transfer.cpp b/src/core/src/file_transfer.cpp
index 27a1dcb..7fdbcc4 100644
--- a/src/core/src/file_transfer.cpp
+++ b/src/core/src/file_transfer.cpp
@@ -1,7 +1,7 @@
#include "tether/file_transfer.hpp"
#include "tether/base64.hpp"
#include <glib.h>
-#include <iostream>
+#include <tether/log.hpp>
namespace tether {
@@ -64,12 +64,12 @@ bool FileReceiveManager::handle_start(const std::string& transfer_id, const std:
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;
+ debug::log(ERR, "FileReceiveManager: Failed to open output file: {}", t->filepath.string());
return false;
}
transfers_[transfer_id] = t;
- std::cout << "FileReceiveManager: Started transfer " << transfer_id << " saving to " << t->filepath << std::endl;
+ debug::log(INFO, "FileReceiveManager: Started transfer {} saving to {}", transfer_id, t->filepath.string());
return true;
}
@@ -106,7 +106,7 @@ bool FileReceiveManager::handle_end(const std::string& transfer_id) {
bytes_written = t->bytes_written;
on_complete = on_complete_;
- std::cout << "FileReceiveManager: Finished transfer " << transfer_id << ". Wrote " << t->bytes_written << " bytes to " << t->filepath << std::endl;
+ debug::log(INFO, "FileReceiveManager: Finished transfer {}. Wrote {} bytes to {}", transfer_id, t->bytes_written, t->filepath.string());
transfers_.erase(it);
}
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index 6d6ebb0..4efd07a 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -18,13 +18,13 @@
#include <cstring>
#include <filesystem>
#include <fstream>
-#include <iostream>
+#include <tether/log.hpp>
#include <mutex>
#include <thread>
#include <nlohmann/json.hpp>
#include <filesystem>
#include <fstream>
-#include <iostream>
+#include <tether/log.hpp>
#include <nlohmann/json.hpp>
#include <set>
#include <vector>
@@ -110,13 +110,13 @@ namespace tether {
if (session.ssl) {
robust_ssl_write(session.ssl, packet.c_str(), packet.size());
} else {
- if (write(fd, packet.c_str(), packet.size()) < 0) { std::cerr << "net write error\n"; }
+ if (write(fd, packet.c_str(), packet.size()) < 0) { debug::log(ERR, "net write error\n"); }
}
}
}
static void write_plain_packet(int fd, const std::string& packet) {
- if (write(fd, packet.c_str(), packet.size()) < 0) { std::cerr << "net write error\n"; }
+ if (write(fd, packet.c_str(), packet.size()) < 0) { debug::log(ERR, "net write error\n"); }
}
void broadcast_local_event(const std::string& msg, int exclude_fd) {
@@ -271,7 +271,7 @@ namespace tether {
if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
if (errno == EWOULDBLOCK) {
- std::cerr << "tetherd is already running." << std::endl;
+ debug::log(ERR, "tetherd is already running.");
exit(1);
} else {
throw std::system_error(errno, std::system_category(), "Failed to lock file");
@@ -291,7 +291,7 @@ namespace tether {
bool UnixServer::start() {
server_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
if (server_fd_ < 0) {
- std::cerr << "Failed to create unix socket" << std::endl;
+ debug::log(ERR, "Failed to create unix socket");
return false;
}
@@ -306,17 +306,17 @@ namespace tether {
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;
+ debug::log(ERR, "Failed to bind unix socket: {}", std::strerror(errno));
return false;
}
if (listen(server_fd_, SOMAXCONN) < 0) {
- std::cerr << "Failed to listen on unix socket" << std::endl;
+ debug::log(ERR, "Failed to listen on unix socket");
return false;
}
loop_.addFd(server_fd_, [this](int fd) { handle_accept(fd); });
- std::cout << "UnixServer listening on " << socket_path_ << std::endl;
+ debug::log(INFO, "UnixServer listening on {}", socket_path_);
return true;
}
@@ -345,7 +345,7 @@ namespace tether {
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;
+ debug::log(ERR, "UnixServer accept error: {}", std::strerror(errno));
}
return;
}
@@ -357,7 +357,7 @@ namespace tether {
// Register client for broadcasts
register_client_fd(client_fd);
loop_.addFd(client_fd, [this](int cfd) { handle_client(cfd); });
- std::cout << "UnixServer: New connection (fd: " << client_fd << ")" << std::endl;
+ debug::log(INFO, "UnixServer: New connection (fd: {})", client_fd);
}
void UnixServer::handle_client(int client_fd) {
@@ -379,16 +379,16 @@ namespace tether {
if (j.contains("command") && j["command"] == "subscribe") {
register_local_subscriber(client_fd);
std::string payload = build_local_state_snapshot().dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "unsubscribe") {
unregister_local_subscriber(client_fd);
std::string payload = "{\"command\":\"unsubscribed\"}\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "state_snapshot") {
std::string payload = build_local_state_snapshot().dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "clipboard_set" && j.contains("content")) {
std::string content = j["content"];
@@ -400,7 +400,7 @@ namespace tether {
resp["command"] = "clipboard_content";
resp["content"] = g_wayland->get_clipboard();
std::string payload = resp.dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "file_start") {
@@ -409,7 +409,7 @@ namespace tether {
resp["command"] = "error";
resp["message"] = "no_connected_mobile_client";
std::string payload = resp.dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "file_chunk") {
@@ -418,7 +418,7 @@ namespace tether {
resp["command"] = "error";
resp["message"] = "no_connected_mobile_client";
std::string payload = resp.dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "file_end") {
@@ -427,7 +427,7 @@ namespace tether {
resp["command"] = "error";
resp["message"] = "no_connected_mobile_client";
std::string payload = resp.dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\n"; }
+ if (write(client_fd, payload.c_str(), payload.size()) < 0) { debug::log(ERR, "net write error\n"); }
continue;
}
@@ -436,7 +436,7 @@ namespace tether {
resp["transfer_id"] = j["transfer_id"];
resp["status"] = "success";
std::string payload = resp.dump() + "\n";
- if (write(client_fd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\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"] == "accept_device" && j.contains("fingerprint")) {
std::string print = j["fingerprint"];
@@ -527,7 +527,7 @@ namespace tether {
resp["message"] = ok ? ("Sent " + std::filesystem::path(path).filename().string()) : ("Send failed: " + (err.empty() ? "unknown error" : err));
std::string payload = resp.dump() + "\n";
// direct write is fine, or we can use broadcast_local_event. We'll reply directly to the GUI socket.
- if (write(pfd, payload.c_str(), payload.size()) < 0) { std::cerr << "net write error\n"; }
+ if (write(pfd, payload.c_str(), payload.size()) < 0) { debug::log(ERR, "net write error\n"); }
}
}).detach();
continue; // skip the "OK\n" below because we reply asynchronously
@@ -536,11 +536,11 @@ namespace tether {
}
std::string response = "OK\n";
- if (write(client_fd, response.c_str(), response.size()) < 0) { std::cerr << "net write error\n"; }
+ if (write(client_fd, response.c_str(), response.size()) < 0) { debug::log(ERR, "net write error\n"); }
}
} else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
// Disconnected
- std::cout << "UnixServer: Client disconnected (fd: " << client_fd << ")" << std::endl;
+ debug::log(INFO, "UnixServer: Client disconnected (fd: {})", client_fd);
client_buffers_.erase(client_fd);
unregister_client_fd(client_fd);
loop_.removeFd(client_fd);
@@ -557,13 +557,13 @@ namespace tether {
bool TcpServer::start() {
server_fd_ = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd_ < 0) {
- std::cerr << "Failed to create tcp socket" << std::endl;
+ debug::log(ERR, "Failed to create tcp socket");
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;
+ debug::log(ERR, "TcpServer setsockopt reuse failed");
}
// Set non-blocking
@@ -576,18 +576,17 @@ namespace tether {
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;
+ debug::log(ERR, "Failed to bind tcp socket on port {}: {}", bind_port_, std::strerror(errno));
return false;
}
if (listen(server_fd_, SOMAXCONN) < 0) {
- std::cerr << "Failed to listen on tcp socket" << std::endl;
+ debug::log(ERR, "Failed to listen on tcp socket");
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;
+ debug::log(INFO, "TcpServer listening on 0.0.0.0:{}", bind_port_);
return true;
}
@@ -634,7 +633,7 @@ namespace tether {
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;
+ debug::log(INFO, "TcpServer: New connection from {} (fd: {})", ip, client_fd);
// SSL Wrapping
SSL* ssl = SSL_new(tether::Crypto::instance().get_server_context());
@@ -680,7 +679,7 @@ namespace tether {
event["paired"] = true;
broadcast_local_event(event.dump());
} else {
- std::cout << "TcpServer: Untrusted client connected. Fingerprint: " << print << std::endl;
+ debug::log(INFO, "TcpServer: Untrusted client connected. Fingerprint: {}", print);
nlohmann::json event;
event["command"] = "untrusted_client_connected";
event["address"] = client_info_[client_fd].address;
@@ -729,8 +728,7 @@ namespace tether {
std::string dev_name = j.value("device_name", "Unknown Device");
client_info_[client_fd].device_name = dev_name;
connected_remote_clients[client_fd].device_name = dev_name;
- std::cout << "[Pairing Request Pending] from " << dev_name
- << ". Accept by running: tether --accept " << print << std::endl;
+ debug::log(INFO, "[Pairing Request Pending] from {}. Accept by running: tether --accept {}", dev_name, print);
// Persist the pending request so accept_device can retrieve the name
{
@@ -817,7 +815,7 @@ namespace tether {
return;
}
- std::cout << "TcpServer: Client disconnected (fd: " << client_fd << ")" << std::endl;
+ debug::log(INFO, "TcpServer: Client disconnected (fd: {})", client_fd);
if (connected_remote_clients.count(client_fd)) {
nlohmann::json event;
event["command"] = "client_disconnected";
@@ -847,13 +845,13 @@ namespace tether {
// Create a pipe so the parent can detect when the child exits via epoll
int pipefd[2];
if (pipe(pipefd) < 0) {
- std::cerr << "spawn_pair_dialog: pipe() failed: " << std::strerror(errno) << std::endl;
+ debug::log(ERR, "spawn_pair_dialog: pipe() failed: {}", std::strerror(errno));
return;
}
pid_t pid = fork();
if (pid < 0) {
- std::cerr << "spawn_pair_dialog: fork() failed: " << std::strerror(errno) << std::endl;
+ debug::log(ERR, "spawn_pair_dialog: fork() failed: {}", std::strerror(errno));
close(pipefd[0]);
close(pipefd[1]);
return;
@@ -908,7 +906,7 @@ namespace tether {
"60",
nullptr);
// exec failed entirely
- std::cerr << "spawn_pair_dialog: exec failed: " << std::strerror(errno) << std::endl;
+ debug::log(ERR, "spawn_pair_dialog: exec failed: {}", std::strerror(errno));
_exit(3);
}
@@ -924,7 +922,7 @@ namespace tether {
loop_.addFd(pipefd[0], [this](int read_fd) {
// Pipe became readable → child exited (EOF on write end)
char dummy;
- if (read(read_fd, &dummy, 1) < 0) { std::cerr << "net read error\n"; } // consume EOF
+ if (read(read_fd, &dummy, 1) < 0) { debug::log(ERR, "net read error\n"); } // consume EOF
auto it = pending_dialogs_.find(read_fd);
if (it == pending_dialogs_.end()) {
@@ -943,7 +941,7 @@ namespace tether {
if (exit_code == 0) {
// User accepted — trust the device
Crypto::instance().add_known_host(info.device_name, info.fingerprint);
- std::cout << "[Pairing Accepted] " << info.device_name << " (" << info.fingerprint << ")" << std::endl;
+ debug::log(INFO, "[Pairing Accepted] {} ({})", info.device_name, info.fingerprint);
// Mark as paired if still connected
if (client_paired_.count(info.client_fd)) {
@@ -1006,8 +1004,7 @@ namespace tether {
ofs << pending.dump(4);
}
} else {
- std::cout << "[Pairing Rejected] " << info.device_name << " (exit code " << exit_code << ")"
- << std::endl;
+ debug::log(INFO, "[Pairing Rejected] {} (exit code {})", info.device_name, exit_code);
nlohmann::json event;
event["command"] = "pair_rejected";
@@ -1032,7 +1029,7 @@ namespace tether {
close(read_fd);
});
- std::cout << "spawn_pair_dialog: Launched dialog (pid " << pid << ") for " << device_name << std::endl;
+ debug::log(INFO, "spawn_pair_dialog: Launched dialog (pid {}) for {}", pid, device_name);
}
} // namespace tether
diff --git a/src/core/src/wayland.cpp b/src/core/src/wayland.cpp
index e522af6..82265d0 100644
--- a/src/core/src/wayland.cpp
+++ b/src/core/src/wayland.cpp
@@ -3,7 +3,7 @@
#include "wayland_protocols/wlr-data-control-unstable-v1.hpp"
#include <wayland-client.h>
-#include <iostream>
+#include <tether/log.hpp>
#include <cstring>
namespace tether {
@@ -38,7 +38,7 @@ WaylandContext::~WaylandContext() {
bool WaylandContext::init() {
raw_display_ = wl_display_connect(nullptr);
if (!raw_display_) {
- std::cerr << "WaylandContext: Failed to connect to Wayland display" << std::endl;
+ debug::log(ERR, "WaylandContext: Failed to connect to Wayland display");
return false;
}
@@ -63,7 +63,7 @@ bool WaylandContext::init() {
wl_display_roundtrip(raw_display_);
if (!seat_ || !data_control_manager_) {
- std::cerr << "WaylandContext: Failed to obtain necessary globals." << std::endl;
+ debug::log(ERR, "WaylandContext: Failed to obtain necessary globals.");
return false;
}
@@ -87,14 +87,14 @@ bool WaylandContext::init() {
int fd = wl_display_get_fd(raw_display_);
loop_.addFd(fd, [this](int) {
if (wl_display_dispatch(raw_display_) < 0) {
- std::cerr << "WaylandContext: Display disconnected." << std::endl;
+ debug::log(ERR, "WaylandContext: Display disconnected.");
}
});
// Flush any pending requests
wl_display_flush(raw_display_);
- std::cout << "WaylandContext initialized successfully." << std::endl;
+ debug::log(INFO, "WaylandContext initialized successfully.");
return true;
}
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 523d4ed..72ae161 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -1,5 +1,5 @@
#include <csignal>
-#include <iostream>
+#include <tether/log.hpp>
#include <nlohmann/json.hpp>
#include "notification.hpp"
#include <tether/core.hpp>
@@ -15,24 +15,24 @@ tether::EpollEventLoop* g_loop = nullptr;
void signal_handler(int) {
if (g_loop) {
- std::cout << "\nStopping tetherd..." << std::endl;
+ debug::log(INFO, "\nStopping tetherd...");
g_loop->stop();
g_loop = nullptr;
}
}
int main(int argc, char** argv) {
- std::cout << "tetherd version " << tether::get_version() << "\n";
+ debug::log(INFO, "tetherd version {}", tether::get_version());
try {
tether::ensure_single_instance();
} catch (const std::exception& e) {
- std::cerr << "Initialization error: " << e.what() << std::endl;
+ debug::log(ERR, "Initialization error: {}", e.what());
return 1;
}
if (!tether::Crypto::instance().init()) {
- std::cerr << "Fatal: Failed to initialize OpenSSL mTLS engine." << std::endl;
+ debug::log(ERR, "Fatal: Failed to initialize OpenSSL mTLS engine.");
return 1;
}
@@ -46,13 +46,13 @@ int main(int argc, char** argv) {
tether::UnixServer unix_srv(loop);
if (!unix_srv.start()) {
- std::cerr << "Failed to start Unix server" << std::endl;
+ debug::log(ERR, "Failed to start Unix server");
return 1;
}
tether::TcpServer tcp_srv(loop, 5134);
if (!tcp_srv.start()) {
- std::cerr << "Failed to start TCP server" << std::endl;
+ debug::log(ERR, "Failed to start TCP server");
return 1;
}
@@ -63,7 +63,7 @@ int main(int argc, char** argv) {
gethostname(hostname, sizeof(hostname) - 1);
std::string my_fp = tether::Crypto::instance().get_my_fingerprint();
if (!discovery.publish(hostname, 5134, my_fp)) {
- std::cerr << "Warning: mDNS advertisement failed (is avahi-daemon running?)" << std::endl;
+ debug::log(ERR, "Warning: mDNS advertisement failed (is avahi-daemon running?)");
}
discovery.start_continuous_browse([](const std::vector<tether::DiscoveredDevice>& devices) {
@@ -101,7 +101,7 @@ int main(int argc, char** argv) {
tether::FileReceiveManager file_mgr;
tether::FileArrivalNotifier notifier;
if (!notifier.init()) {
- std::cerr << "Warning: desktop notifications unavailable" << std::endl;
+ debug::log(ERR, "Warning: desktop notifications unavailable");
} else {
file_mgr.set_on_complete([&notifier](const std::filesystem::path& path, size_t bytes_written) {
notifier.notify_file_arrived(path);
@@ -110,11 +110,11 @@ int main(int argc, char** argv) {
}
tether::g_file_manager = &file_mgr;
- std::cout << "tetherd is running. Press Ctrl-C to stop." << std::endl;
+ debug::log(INFO, "tetherd is running. Press Ctrl-C to stop.");
loop.run();
// discovery destructor calls unpublish() automatically
- std::cout << "tetherd shutdown complete." << std::endl;
+ debug::log(INFO, "tetherd shutdown complete.");
// explicitly null globals to be safe during final stack unwinding
tether::g_wayland = nullptr;
diff --git a/src/daemon/notification.cpp b/src/daemon/notification.cpp
index 093fe21..ecb4acd 100644
--- a/src/daemon/notification.cpp
+++ b/src/daemon/notification.cpp
@@ -4,7 +4,7 @@
#include <glib.h>
#include <libnotify/notify.h>
-#include <iostream>
+#include <tether/log.hpp>
#include <string>
#include <thread>
@@ -32,12 +32,12 @@ bool launch_uri(const std::string& uri) {
GError* error = nullptr;
gboolean ok = g_app_info_launch_default_for_uri(uri.c_str(), nullptr, &error);
if (!ok) {
- std::cerr << "Failed to open URI '" << uri << "'";
+ debug::log(ERR, "Failed to open URI '{}'", uri);
if (error) {
- std::cerr << ": " << error->message;
+ debug::log(ERR, ": {}", error->message);
g_error_free(error);
}
- std::cerr << std::endl;
+ debug::log(ERR, "");
return false;
}
@@ -69,7 +69,7 @@ gboolean show_notification_on_main(gpointer user_data) {
if (!file_uri || !folder_uri) {
if (file_uri) g_free(file_uri);
if (folder_uri) g_free(folder_uri);
- std::cerr << "Failed to create notification URI for " << file << std::endl;
+ debug::log(ERR, "Failed to create notification URI for {}", file);
return G_SOURCE_REMOVE;
}
@@ -104,12 +104,12 @@ gboolean show_notification_on_main(gpointer user_data) {
GError* error = nullptr;
gboolean shown = notify_notification_show(notification, &error);
if (!shown) {
- std::cerr << "Failed to show notification";
+ debug::log(ERR, "Failed to show notification");
if (error) {
- std::cerr << ": " << error->message;
+ debug::log(ERR, ": {}", error->message);
g_error_free(error);
}
- std::cerr << std::endl;
+ debug::log(ERR, "");
g_object_unref(notification);
}
g_free(file_uri);
@@ -154,7 +154,7 @@ bool FileArrivalNotifier::init() {
}
if (!notify_init("tetherd")) {
- std::cerr << "Failed to initialize libnotify" << std::endl;
+ debug::log(ERR, "Failed to initialize libnotify");
return false;
}
diff --git a/src/dialog/main.cpp b/src/dialog/main.cpp
index d90b286..ad75ff0 100644
--- a/src/dialog/main.cpp
+++ b/src/dialog/main.cpp
@@ -3,7 +3,7 @@
#include <cstdlib>
#include <cstring>
-#include <iostream>
+#include "../core/include/tether/log.hpp"
#include <string>
// Exit codes:
@@ -44,8 +44,7 @@ static gboolean on_key_press(GtkWidget*, GdkEventKey* event, gpointer has_reject
}
static void print_usage(const char* argv0) {
- std::cerr << "Usage: " << argv0 << " --title <text> --body <text> --accept <label>"
- << " [--reject <label>] [--timeout <seconds>]\n";
+ debug::log(ERR, "Usage: {} --title <text> --body <text> --accept <label> [--reject <label>] [--timeout <seconds>]\n", argv0);
}
static const char* CSS = R"(
@@ -125,7 +124,7 @@ int main(int argc, char** argv) {
}
if (title.empty() || body.empty() || accept_label.empty()) {
- std::cerr << "Error: --title, --body, and --accept are required.\n";
+ debug::log(ERR, "Error: --title, --body, and --accept are required.\n");
print_usage(argv[0]);
return 3;
}
diff --git a/src/gtk/main.cpp b/src/gtk/main.cpp
index 1a7da06..0a08eae 100644
--- a/src/gtk/main.cpp
+++ b/src/gtk/main.cpp
@@ -8,7 +8,7 @@
#include <cstdlib>
#include <ctime>
#include <filesystem>
-#include <iostream>
+#include <tether/log.hpp>
#include <string>
#include <sys/socket.h>
#include <sys/un.h>
@@ -95,7 +95,7 @@ namespace {
if (g_app.event_fd >= 0) {
std::string payload = j.dump() + "\n";
if (::write(g_app.event_fd, payload.c_str(), payload.size()) < 0) {
- std::cerr << "daemon write error\n";
+ debug::log(ERR, "daemon write error\n");
}
}
}
@@ -565,7 +565,7 @@ namespace {
}
if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR) {
if (error) {
- std::cerr << "Stream err: " << error->message << std::endl;
+ debug::log(ERR, "Stream err: {}", error->message);
g_error_free(error);
}
if (line)
@@ -644,7 +644,7 @@ namespace {
nullptr);
static const char kSubscribe[] = "{\"command\":\"subscribe\"}\n";
if (write(fd, kSubscribe, sizeof(kSubscribe) - 1) < 0) {
- std::cerr << "subscribe write error\n";
+ debug::log(ERR, "subscribe write error\n");
}
set_status_main("Daemon Online");
return G_SOURCE_REMOVE;