diff --git a/device-ui/CMakeLists.txt b/device-ui/CMakeLists.txt new file mode 100644 index 0000000..1504528 --- /dev/null +++ b/device-ui/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.16) +project(cp0-sync-ui VERSION 1.0.0 LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +option(CP0_UI_BUILD_TESTS "Build device-ui unit tests" ON) +option(CP0_UI_BUILD_APP "Build cp0-sync-ui LVGL executable" ON) +option(CP0_UI_TARGET_DEVICE "Target CardputerZero Linux fbdev/evdev instead of SDL2 simulator" OFF) + +find_package(SQLite3 REQUIRED) + +add_library(cp0_ui_core STATIC + src/theme.cpp + src/ipc_client.cpp +) +target_include_directories(cp0_ui_core PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src +) +if(TARGET SQLite3::SQLite3) + target_link_libraries(cp0_ui_core PUBLIC SQLite3::SQLite3) +else() + target_link_libraries(cp0_ui_core PUBLIC SQLite::SQLite3) +endif() +target_compile_options(cp0_ui_core PRIVATE -Wall -Wextra -Wpedantic) + +if(CP0_UI_BUILD_APP) + message(STATUS "CP0_UI_BUILD_APP=ON: app target will be configured in Task 6") +endif() + +if(CP0_UI_BUILD_TESTS) + enable_testing() + add_executable(test_ipc_and_theme + tests/test_ipc_and_theme.cpp + ) + target_link_libraries(test_ipc_and_theme PRIVATE cp0_ui_core) + target_compile_options(test_ipc_and_theme PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME test_ipc_and_theme COMMAND test_ipc_and_theme) +endif() diff --git a/device-ui/src/ipc_client.cpp b/device-ui/src/ipc_client.cpp new file mode 100644 index 0000000..900025b --- /dev/null +++ b/device-ui/src/ipc_client.cpp @@ -0,0 +1,1242 @@ +#include "ipc_client.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cp0 { + +namespace { + +// --------------------------------------------------------------------------- +// Path & string helpers +// --------------------------------------------------------------------------- + +std::string trim_ascii(const std::string& s) { + size_t start = 0; + while (start < s.size() && std::isspace(static_cast(s[start]))) { + ++start; + } + size_t end = s.size(); + while (end > start && std::isspace(static_cast(s[end - 1]))) { + --end; + } + return s.substr(start, end - start); +} + +std::string expand_tilde(const std::string& path) { + if (path.empty() || path[0] != '~') { + return path; + } + if (path.size() == 1 || path[1] == '/') { + const char* home = std::getenv("HOME"); + if (home != nullptr && home[0] != '\0') { + return std::string(home) + path.substr(1); + } + } + return path; +} + +std::string to_lower_ascii(std::string s) { + for (char& ch : s) { + ch = static_cast(std::tolower(static_cast(ch))); + } + return s; +} + +bool dir_exists(const std::string& raw_path) { + if (raw_path.empty()) { + return false; + } + std::string p = expand_tilde(raw_path); + struct stat st {}; + if (::stat(p.c_str(), &st) != 0) { + return false; + } + return S_ISDIR(st.st_mode); +} + +int64_t parse_int64_safe(const std::string& s, int64_t fallback = 0) { + if (s.empty()) { + return fallback; + } + char* end = nullptr; + errno = 0; + long long val = std::strtoll(s.c_str(), &end, 10); + if (errno != 0 || end == s.c_str() || *end != '\0') { + return fallback; + } + return static_cast(val); +} + +// --------------------------------------------------------------------------- +// Dependency-free JSON parser & serializer +// --------------------------------------------------------------------------- + +struct JsonValue { + enum class Type { Null, Bool, Number, String, Array, Object }; + + Type type = Type::Null; + bool bool_val = false; + double num_val = 0.0; + int64_t int_val = 0; + bool is_int = false; + std::string str_val; + std::vector arr_val; + std::vector> obj_val; + + const JsonValue* find(const std::string& key) const { + if (type != Type::Object) { + return nullptr; + } + for (const auto& kv : obj_val) { + if (kv.first == key) { + return &kv.second; + } + } + return nullptr; + } + + std::string as_string(const std::string& def = "") const { + return type == Type::String ? str_val : def; + } + + bool as_bool(bool def = false) const { + return type == Type::Bool ? bool_val : def; + } + + int64_t as_int64(int64_t def = 0) const { + if (type != Type::Number) { + return def; + } + return is_int ? int_val : static_cast(num_val); + } + + int as_int(int def = 0) const { + return static_cast(as_int64(def)); + } +}; + +class JsonParser { +public: + explicit JsonParser(const std::string& src) : src_(src) {} + + bool parse(JsonValue& out) { + skip_ws(); + if (!parse_value(out, 0)) { + return false; + } + skip_ws(); + return pos_ == src_.size(); + } + +private: + static constexpr int kMaxDepth = 64; + + void skip_ws() { + while (pos_ < src_.size()) { + char c = src_[pos_]; + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { + ++pos_; + } else { + break; + } + } + } + + bool parse_value(JsonValue& out, int depth) { + if (depth > kMaxDepth || pos_ >= src_.size()) { + return false; + } + char c = src_[pos_]; + if (c == 'n') return parse_null(out); + if (c == 't' || c == 'f') return parse_bool(out); + if (c == '"') return parse_string_value(out); + if (c == '[') return parse_array(out, depth + 1); + if (c == '{') return parse_object(out, depth + 1); + if (c == '-' || (c >= '0' && c <= '9')) return parse_number(out); + return false; + } + + bool parse_null(JsonValue& out) { + if (src_.compare(pos_, 4, "null") == 0) { + pos_ += 4; + out = JsonValue{}; + out.type = JsonValue::Type::Null; + return true; + } + return false; + } + + bool parse_bool(JsonValue& out) { + if (src_.compare(pos_, 4, "true") == 0) { + pos_ += 4; + out = JsonValue{}; + out.type = JsonValue::Type::Bool; + out.bool_val = true; + return true; + } + if (src_.compare(pos_, 5, "false") == 0) { + pos_ += 5; + out = JsonValue{}; + out.type = JsonValue::Type::Bool; + out.bool_val = false; + return true; + } + return false; + } + + static void append_utf8(std::string& dst, uint32_t cp) { + if (cp <= 0x7F) { + dst.push_back(static_cast(cp)); + } else if (cp <= 0x7FF) { + dst.push_back(static_cast(0xC0 | ((cp >> 6) & 0x1F))); + dst.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0xFFFF) { + dst.push_back(static_cast(0xE0 | ((cp >> 12) & 0x0F))); + dst.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + dst.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0x10FFFF) { + dst.push_back(static_cast(0xF0 | ((cp >> 18) & 0x07))); + dst.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + dst.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + dst.push_back(static_cast(0x80 | (cp & 0x3F))); + } + } + + bool parse_hex4(uint32_t& code) { + if (pos_ + 4 > src_.size()) { + return false; + } + code = 0; + for (int i = 0; i < 4; ++i) { + char c = src_[pos_++]; + code <<= 4; + if (c >= '0' && c <= '9') { + code |= static_cast(c - '0'); + } else if (c >= 'a' && c <= 'f') { + code |= static_cast(c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + code |= static_cast(c - 'A' + 10); + } else { + return false; + } + } + return true; + } + + bool parse_raw_string(std::string& out) { + if (pos_ >= src_.size() || src_[pos_] != '"') { + return false; + } + ++pos_; + out.clear(); + while (pos_ < src_.size()) { + char c = src_[pos_++]; + if (c == '"') { + return true; + } + if (static_cast(c) < 0x20) { + return false; + } + if (c != '\\') { + out.push_back(c); + continue; + } + if (pos_ >= src_.size()) { + return false; + } + char esc = src_[pos_++]; + switch (esc) { + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case '/': out.push_back('/'); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + uint32_t cp = 0; + if (!parse_hex4(cp)) { + return false; + } + if (cp >= 0xD800 && cp <= 0xDBFF) { + if (pos_ + 2 <= src_.size() && src_[pos_] == '\\' && src_[pos_ + 1] == 'u') { + pos_ += 2; + uint32_t low = 0; + if (!parse_hex4(low) || low < 0xDC00 || low > 0xDFFF) { + return false; + } + cp = 0x10000 + (((cp - 0xD800) << 10) | (low - 0xDC00)); + } else { + return false; + } + } + append_utf8(out, cp); + break; + } + default: + return false; + } + } + return false; + } + + bool parse_string_value(JsonValue& out) { + out = JsonValue{}; + out.type = JsonValue::Type::String; + return parse_raw_string(out.str_val); + } + + bool parse_number(JsonValue& out) { + size_t start = pos_; + if (src_[pos_] == '-') { + ++pos_; + } + if (pos_ >= src_.size()) { + return false; + } + if (src_[pos_] == '0') { + ++pos_; + } else if (src_[pos_] >= '1' && src_[pos_] <= '9') { + while (pos_ < src_.size() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + } else { + return false; + } + + bool is_float = false; + if (pos_ < src_.size() && src_[pos_] == '.') { + is_float = true; + ++pos_; + if (pos_ >= src_.size() || src_[pos_] < '0' || src_[pos_] > '9') { + return false; + } + while (pos_ < src_.size() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + } + if (pos_ < src_.size() && (src_[pos_] == 'e' || src_[pos_] == 'E')) { + is_float = true; + ++pos_; + if (pos_ < src_.size() && (src_[pos_] == '+' || src_[pos_] == '-')) { + ++pos_; + } + if (pos_ >= src_.size() || src_[pos_] < '0' || src_[pos_] > '9') { + return false; + } + while (pos_ < src_.size() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + } + + std::string token = src_.substr(start, pos_ - start); + out = JsonValue{}; + out.type = JsonValue::Type::Number; + + char* end = nullptr; + errno = 0; + out.num_val = std::strtod(token.c_str(), &end); + if (errno != 0 || end != token.c_str() + token.size()) { + return false; + } + + if (!is_float) { + errno = 0; + end = nullptr; + long long iv = std::strtoll(token.c_str(), &end, 10); + if (errno == 0 && end == token.c_str() + token.size()) { + out.is_int = true; + out.int_val = static_cast(iv); + } + } + return true; + } + + bool parse_array(JsonValue& out, int depth) { + ++pos_; // '[' + out = JsonValue{}; + out.type = JsonValue::Type::Array; + skip_ws(); + if (pos_ < src_.size() && src_[pos_] == ']') { + ++pos_; + return true; + } + while (pos_ < src_.size()) { + JsonValue elem; + if (!parse_value(elem, depth)) { + return false; + } + out.arr_val.push_back(std::move(elem)); + skip_ws(); + if (pos_ >= src_.size()) { + return false; + } + if (src_[pos_] == ']') { + ++pos_; + return true; + } + if (src_[pos_] != ',') { + return false; + } + ++pos_; + skip_ws(); + } + return false; + } + + bool parse_object(JsonValue& out, int depth) { + ++pos_; // '{' + out = JsonValue{}; + out.type = JsonValue::Type::Object; + skip_ws(); + if (pos_ < src_.size() && src_[pos_] == '}') { + ++pos_; + return true; + } + while (pos_ < src_.size()) { + skip_ws(); + std::string key; + if (!parse_raw_string(key)) { + return false; + } + skip_ws(); + if (pos_ >= src_.size() || src_[pos_] != ':') { + return false; + } + ++pos_; + skip_ws(); + JsonValue val; + if (!parse_value(val, depth)) { + return false; + } + out.obj_val.emplace_back(std::move(key), std::move(val)); + skip_ws(); + if (pos_ >= src_.size()) { + return false; + } + if (src_[pos_] == '}') { + ++pos_; + return true; + } + if (src_[pos_] != ',') { + return false; + } + ++pos_; + } + return false; + } + + const std::string& src_; + size_t pos_ = 0; +}; + +bool parse_json(const std::string& src, JsonValue& out) { + JsonParser parser(src); + return parser.parse(out); +} + +std::string json_escape(const std::string& s) { + std::string out; + out.reserve(s.size() + 2); + out.push_back('"'); + for (unsigned char c : s) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { + char buf[7]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(c)); + out += buf; + } else { + out.push_back(static_cast(c)); + } + break; + } + } + out.push_back('"'); + return out; +} + +// --------------------------------------------------------------------------- +// RAII helpers for fd & sqlite3 +// --------------------------------------------------------------------------- + +struct FdGuard { + int fd = -1; + ~FdGuard() { + if (fd >= 0) { + ::close(fd); + } + } +}; + +struct SqliteDbGuard { + sqlite3* db = nullptr; + ~SqliteDbGuard() { + if (db != nullptr) { + sqlite3_close(db); + } + } +}; + +struct SqliteStmtGuard { + sqlite3_stmt* stmt = nullptr; + ~SqliteStmtGuard() { + if (stmt != nullptr) { + sqlite3_finalize(stmt); + } + } +}; + +std::string col_text(sqlite3_stmt* stmt, int col) { + const unsigned char* txt = sqlite3_column_text(stmt, col); + return txt != nullptr ? reinterpret_cast(txt) : ""; +} + +int remaining_ms(std::chrono::steady_clock::time_point deadline) { + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return 0; + } + auto diff = std::chrono::duration_cast(deadline - now).count(); + return diff > 0 ? static_cast(diff) : 1; +} + +bool wait_poll(int fd, short events, std::chrono::steady_clock::time_point deadline) { + while (true) { + int rem = remaining_ms(deadline); + if (rem <= 0) { + return false; + } + pollfd pfd{}; + pfd.fd = fd; + pfd.events = events; + int rc = ::poll(&pfd, 1, rem); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + if (rc == 0) { + return false; + } + return (pfd.revents & (events | POLLHUP | POLLERR)) != 0; + } +} + +bool is_macos_os(const std::string& os) { + std::string lower = to_lower_ascii(os); + return lower == "macos" || lower == "darwin"; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Default paths +// --------------------------------------------------------------------------- + +std::string default_sock_path() { + const char* env_sock = std::getenv("CP0_SYNC_SOCK"); + if (env_sock != nullptr) { + std::string trimmed = trim_ascii(env_sock); + if (!trimmed.empty()) { + return expand_tilde(trimmed); + } + } + const char* runtime_dir = std::getenv("XDG_RUNTIME_DIR"); + std::string base = (runtime_dir != nullptr && !trim_ascii(runtime_dir).empty()) + ? trim_ascii(runtime_dir) + : "/tmp"; + if (!base.empty() && base.back() == '/') { + base.pop_back(); + } + return base + "/cp0-sync.sock"; +} + +std::string default_db_path() { + const char* env_db = std::getenv("CP0_SYNC_DB"); + if (env_db != nullptr) { + std::string trimmed = trim_ascii(env_db); + if (!trimmed.empty()) { + return expand_tilde(trimmed); + } + } + const char* home = std::getenv("HOME"); + std::string home_str = (home != nullptr && home[0] != '\0') ? std::string(home) : "/tmp"; + if (!home_str.empty() && home_str.back() == '/') { + home_str.pop_back(); + } + return home_str + "/.local/share/cp0-sync/state.db"; +} + +std::string default_config_path() { + const char* env_cfg = std::getenv("CP0_SYNC_CONFIG"); + if (env_cfg != nullptr) { + std::string trimmed = trim_ascii(env_cfg); + if (!trimmed.empty()) { + return expand_tilde(trimmed); + } + } + const char* home = std::getenv("HOME"); + std::string home_str = (home != nullptr && home[0] != '\0') ? std::string(home) : "/tmp"; + if (!home_str.empty() && home_str.back() == '/') { + home_str.pop_back(); + } + return home_str + "/.config/cp0-sync/config.json"; +} + +// --------------------------------------------------------------------------- +// JSON parsers +// --------------------------------------------------------------------------- + +DaemonStatus parse_status_json(const std::string& json_str) { + DaemonStatus status; + JsonValue root; + if (!parse_json(json_str, root) || root.type != JsonValue::Type::Object) { + status.ok = false; + status.error = "Invalid status JSON"; + return status; + } + + if (const auto* v = root.find("ok")) { + status.ok = v->as_bool(false); + } + if (const auto* v = root.find("error")) { + status.error = v->as_string(); + } + if (!status.ok) { + if (status.error.empty()) { + status.error = "Daemon returned error"; + } + return status; + } + + if (const auto* v = root.find("target_host")) status.target_host = v->as_string(); + if (const auto* v = root.find("target_port")) status.target_port = v->as_int(8765); + if (const auto* v = root.find("theme")) status.theme = v->as_string("dark"); + if (const auto* v = root.find("mac_online")) status.mac_online = v->as_bool(false); + if (const auto* v = root.find("mac_dest_root")) status.mac_dest_root = v->as_string(); + if (const auto* v = root.find("syncing")) status.syncing = v->as_bool(false); + if (const auto* v = root.find("current_file")) status.current_file = v->as_string(); + if (const auto* v = root.find("pending_count")) status.pending_count = v->as_int(0); + if (const auto* v = root.find("pending_bytes")) status.pending_bytes = v->as_int64(0); + if (const auto* v = root.find("synced_count")) status.synced_count = v->as_int(0); + if (const auto* v = root.find("failed_count")) status.failed_count = v->as_int(0); + if (const auto* v = root.find("next_retry_sec")) status.next_retry_sec = v->as_int(0); + if (const auto* v = root.find("last_sync_ts")) status.last_sync_ts = v->as_int64(0); + if (const auto* v = root.find("last_synced_file")) status.last_synced_file = v->as_string(); + if (const auto* v = root.find("last_error")) status.last_error = v->as_string(); + + if (const auto* folders = root.find("folders")) { + if (folders->type == JsonValue::Type::Array) { + for (const auto& item : folders->arr_val) { + if (item.type != JsonValue::Type::Object) continue; + FolderStatus fs; + if (const auto* f = item.find("id")) fs.id = f->as_string(); + if (const auto* f = item.find("path")) fs.path = f->as_string(); + if (const auto* f = item.find("label")) fs.label = f->as_string(); + if (const auto* f = item.find("enabled")) fs.enabled = f->as_bool(true); + if (const auto* f = item.find("exists")) fs.exists = f->as_bool(false); + if (const auto* f = item.find("pending")) fs.pending = f->as_int(0); + if (const auto* f = item.find("uploading")) fs.uploading = f->as_int(0); + if (const auto* f = item.find("synced")) fs.synced = f->as_int(0); + if (const auto* f = item.find("failed")) fs.failed = f->as_int(0); + if (const auto* f = item.find("pending_bytes")) fs.pending_bytes = f->as_int64(0); + status.folders.push_back(std::move(fs)); + } + } + } + + if (const auto* logs = root.find("logs")) { + if (logs->type == JsonValue::Type::Array) { + for (const auto& item : logs->arr_val) { + if (item.type != JsonValue::Type::Object) continue; + LogEntry entry; + if (const auto* l = item.find("id")) entry.id = l->as_int64(0); + if (const auto* l = item.find("ts")) entry.ts = l->as_int64(0); + if (const auto* l = item.find("level")) entry.level = l->as_string(); + if (const auto* l = item.find("message")) entry.message = l->as_string(); + status.logs.push_back(std::move(entry)); + } + } + } + + return status; +} + +std::vector parse_tailscale_peers(const std::string& json_str) { + std::vector peers; + JsonValue root; + if (!parse_json(json_str, root) || root.type != JsonValue::Type::Object) { + return peers; + } + + std::string self_id; + if (const auto* self_obj = root.find("Self")) { + if (const auto* id_val = self_obj->find("ID")) { + self_id = id_val->as_string(); + } + } + + const auto* peer_map = root.find("Peer"); + if (peer_map == nullptr || peer_map->type != JsonValue::Type::Object) { + return peers; + } + + for (const auto& kv : peer_map->obj_val) { + if (kv.second.type != JsonValue::Type::Object) { + continue; + } + const JsonValue& p = kv.second; + std::string pid = kv.first; + if (const auto* id_val = p.find("ID")) { + std::string explicit_id = id_val->as_string(); + if (!explicit_id.empty()) { + pid = explicit_id; + } + } + if (!self_id.empty() && (pid == self_id || kv.first == self_id)) { + continue; + } + + TailscalePeer peer; + peer.id = pid; + if (const auto* v = p.find("HostName")) peer.hostname = v->as_string(); + if (const auto* v = p.find("DNSName")) { + peer.dns_name = v->as_string(); + while (!peer.dns_name.empty() && peer.dns_name.back() == '.') { + peer.dns_name.pop_back(); + } + } + if (const auto* v = p.find("OS")) peer.os = v->as_string(); + if (const auto* v = p.find("Online")) peer.online = v->as_bool(false); + if (const auto* ips = p.find("TailscaleIPs")) { + if (ips->type == JsonValue::Type::Array) { + for (const auto& ip : ips->arr_val) { + if (ip.type == JsonValue::Type::String && !ip.str_val.empty()) { + peer.tailscale_ips.push_back(ip.str_val); + } + } + } + } + peers.push_back(std::move(peer)); + } + + std::sort(peers.begin(), peers.end(), [](const TailscalePeer& a, const TailscalePeer& b) { + bool a_mac = is_macos_os(a.os); + bool b_mac = is_macos_os(b.os); + if (a_mac != b_mac) { + return a_mac > b_mac; + } + if (a.online != b.online) { + return a.online > b.online; + } + std::string a_name = to_lower_ascii(a.hostname); + std::string b_name = to_lower_ascii(b.hostname); + if (a_name != b_name) { + return a_name < b_name; + } + return a.id < b.id; + }); + + return peers; +} + +// --------------------------------------------------------------------------- +// IpcClient +// --------------------------------------------------------------------------- + +IpcClient::IpcClient(std::string sock_path, std::string db_path, std::string config_path) + : sock_path_(std::move(sock_path)), + db_path_(std::move(db_path)), + config_path_(std::move(config_path)) {} + +std::string IpcClient::resolved_sock_path() const { + return sock_path_.empty() ? default_sock_path() : expand_tilde(sock_path_); +} + +std::string IpcClient::resolved_db_path() const { + return db_path_.empty() ? default_db_path() : expand_tilde(db_path_); +} + +std::string IpcClient::resolved_config_path() const { + return config_path_.empty() ? default_config_path() : expand_tilde(config_path_); +} + +std::string IpcClient::send_command(const std::string& json_line, int timeout_ms) const { + if (timeout_ms <= 0) { + timeout_ms = 1000; + } + std::string path = resolved_sock_path(); + sockaddr_un addr{}; + if (path.empty() || path.size() >= sizeof(addr.sun_path)) { + return ""; + } + + FdGuard fd_guard; + fd_guard.fd = ::socket(AF_UNIX, SOCK_STREAM, 0); + if (fd_guard.fd < 0) { + return ""; + } + +#ifdef SO_NOSIGPIPE + int yes = 1; + ::setsockopt(fd_guard.fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes)); +#endif + + int flags = ::fcntl(fd_guard.fd, F_GETFL, 0); + if (flags < 0 || ::fcntl(fd_guard.fd, F_SETFL, flags | O_NONBLOCK) != 0) { + return ""; + } + + addr.sun_family = AF_UNIX; + std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1); + + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + + int conn_rc = ::connect(fd_guard.fd, reinterpret_cast(&addr), sizeof(addr)); + if (conn_rc < 0) { + if (errno != EINPROGRESS && errno != EAGAIN && errno != EWOULDBLOCK) { + return ""; + } + if (!wait_poll(fd_guard.fd, POLLOUT, deadline)) { + return ""; + } + int so_err = 0; + socklen_t len = sizeof(so_err); + if (::getsockopt(fd_guard.fd, SOL_SOCKET, SO_ERROR, &so_err, &len) != 0 || so_err != 0) { + return ""; + } + } + + std::string payload = json_line; + if (payload.empty() || payload.back() != '\n') { + payload.push_back('\n'); + } + + size_t sent = 0; + while (sent < payload.size()) { + int send_flags = 0; +#ifdef MSG_NOSIGNAL + send_flags |= MSG_NOSIGNAL; +#endif + ssize_t n = ::send(fd_guard.fd, payload.data() + sent, payload.size() - sent, send_flags); + if (n > 0) { + sent += static_cast(n); + continue; + } + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + if (!wait_poll(fd_guard.fd, POLLOUT, deadline)) { + return ""; + } + continue; + } + return ""; + } + + std::string response; + char buf[4096]; + while (true) { + ssize_t n = ::recv(fd_guard.fd, buf, sizeof(buf), 0); + if (n > 0) { + for (ssize_t i = 0; i < n; ++i) { + if (buf[i] == '\n') { + if (!response.empty() && response.back() == '\r') { + response.pop_back(); + } + return response; + } + response.push_back(buf[i]); + } + continue; + } + if (n == 0) { + if (!response.empty() && response.back() == '\r') { + response.pop_back(); + } + return response; + } + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + if (!wait_poll(fd_guard.fd, POLLIN, deadline)) { + return ""; + } + continue; + } + return ""; + } +} + +DaemonStatus IpcClient::fetch_status() const { + std::string raw = send_command(R"({"cmd":"status"})", 1000); + if (!raw.empty()) { + DaemonStatus parsed = parse_status_json(raw); + if (parsed.ok || parsed.error != "Invalid status JSON") { + return parsed; + } + } + + DaemonStatus fallback = read_sqlite_fallback(); + if (fallback.ok) { + return fallback; + } + + DaemonStatus err; + err.ok = false; + err.error = "Daemon unreachable and SQLite fallback unavailable"; + return err; +} + +DaemonStatus IpcClient::read_sqlite_fallback() const { + DaemonStatus status; + status.from_fallback = true; + + // Populate config fields even if daemon is offline + std::vector configured_folders; + { + std::ifstream cfg_in(resolved_config_path()); + if (cfg_in.is_open()) { + std::ostringstream ss; + ss << cfg_in.rdbuf(); + JsonValue cfg_root; + if (parse_json(ss.str(), cfg_root) && cfg_root.type == JsonValue::Type::Object) { + if (const auto* v = cfg_root.find("target_host")) { + status.target_host = v->as_string(); + } + if (const auto* v = cfg_root.find("target_port")) { + int port = v->as_int(8765); + if (port >= 1 && port <= 65535) { + status.target_port = port; + } + } + if (const auto* v = cfg_root.find("theme")) { + std::string th = v->as_string("dark"); + if (th == "dark" || th == "light") { + status.theme = th; + } + } + if (const auto* wf = cfg_root.find("watched_folders")) { + if (wf->type == JsonValue::Type::Array) { + for (const auto& item : wf->arr_val) { + if (item.type != JsonValue::Type::Object) continue; + FolderStatus fs; + if (const auto* f = item.find("id")) fs.id = f->as_string(); + if (const auto* f = item.find("path")) fs.path = f->as_string(); + if (const auto* f = item.find("label")) fs.label = f->as_string(); + if (const auto* f = item.find("enabled")) fs.enabled = f->as_bool(true); + if (!fs.id.empty() && !fs.path.empty()) { + fs.exists = dir_exists(fs.path); + configured_folders.push_back(std::move(fs)); + } + } + } + } + } + } + } + + std::string db_path = resolved_db_path(); + SqliteDbGuard db_guard; + if (sqlite3_open_v2(db_path.c_str(), &db_guard.db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK) { + status.ok = false; + status.error = db_guard.db != nullptr ? sqlite3_errmsg(db_guard.db) : "Failed to open SQLite DB"; + return status; + } + sqlite3_busy_timeout(db_guard.db, 1000); + + // 1. Read meta table + { + SqliteStmtGuard stmt; + if (sqlite3_prepare_v2(db_guard.db, "SELECT key, value FROM meta", -1, &stmt.stmt, nullptr) == SQLITE_OK) { + while (sqlite3_step(stmt.stmt) == SQLITE_ROW) { + std::string k = col_text(stmt.stmt, 0); + std::string v = col_text(stmt.stmt, 1); + if (k == "mac_online") { + status.mac_online = (v == "true"); + } else if (k == "mac_dest_root") { + status.mac_dest_root = v; + } else if (k == "last_sync_ts") { + status.last_sync_ts = parse_int64_safe(v, 0); + } else if (k == "last_synced_file") { + status.last_synced_file = v; + } else if (k == "last_error") { + status.last_error = v; + } + } + } + } + + // 2. Aggregate files table per folder_id and status + struct FolderCounts { + int pending = 0; + int uploading = 0; + int synced = 0; + int failed = 0; + int64_t pending_bytes = 0; + }; + std::map by_folder; + std::vector seen_folder_order; + + { + SqliteStmtGuard stmt; + const char* sql = + "SELECT folder_id, status, COUNT(*), COALESCE(SUM(size_bytes), 0) " + "FROM files GROUP BY folder_id, status"; + if (sqlite3_prepare_v2(db_guard.db, sql, -1, &stmt.stmt, nullptr) == SQLITE_OK) { + while (sqlite3_step(stmt.stmt) == SQLITE_ROW) { + std::string fid = col_text(stmt.stmt, 0); + std::string st = col_text(stmt.stmt, 1); + int cnt = sqlite3_column_int(stmt.stmt, 2); + int64_t bytes = sqlite3_column_int64(stmt.stmt, 3); + + if (by_folder.find(fid) == by_folder.end()) { + seen_folder_order.push_back(fid); + } + auto& bucket = by_folder[fid]; + if (st == "PENDING") { + bucket.pending += cnt; + bucket.pending_bytes += bytes; + status.pending_count += cnt; + status.pending_bytes += bytes; + } else if (st == "UPLOADING") { + bucket.pending += cnt; + bucket.uploading += cnt; + bucket.pending_bytes += bytes; + status.pending_count += cnt; + status.pending_bytes += bytes; + } else if (st == "SYNCED") { + bucket.synced += cnt; + status.synced_count += cnt; + } else if (st == "FAILED") { + bucket.failed += cnt; + status.failed_count += cnt; + } + } + } + } + + std::map included; + for (auto& wf : configured_folders) { + auto it = by_folder.find(wf.id); + if (it != by_folder.end()) { + wf.pending = it->second.pending; + wf.uploading = it->second.uploading; + wf.synced = it->second.synced; + wf.failed = it->second.failed; + wf.pending_bytes = it->second.pending_bytes; + } + included[wf.id] = true; + status.folders.push_back(std::move(wf)); + } + + for (const auto& fid : seen_folder_order) { + if (included[fid]) { + continue; + } + const auto& c = by_folder[fid]; + FolderStatus fs; + fs.id = fid; + fs.label = fid; + fs.pending = c.pending; + fs.uploading = c.uploading; + fs.synced = c.synced; + fs.failed = c.failed; + fs.pending_bytes = c.pending_bytes; + status.folders.push_back(std::move(fs)); + } + + // 3. Read newest 50 log entries + { + SqliteStmtGuard stmt; + const char* sql = "SELECT id, ts, level, message FROM logs ORDER BY id DESC LIMIT 50"; + if (sqlite3_prepare_v2(db_guard.db, sql, -1, &stmt.stmt, nullptr) == SQLITE_OK) { + while (sqlite3_step(stmt.stmt) == SQLITE_ROW) { + LogEntry entry; + entry.id = sqlite3_column_int64(stmt.stmt, 0); + entry.ts = sqlite3_column_int64(stmt.stmt, 1); + entry.level = col_text(stmt.stmt, 2); + entry.message = col_text(stmt.stmt, 3); + status.logs.push_back(std::move(entry)); + } + } + } + + status.ok = true; + return status; +} + +std::vector IpcClient::list_tailscale_peers() const { + int pipe_fds[2] = {-1, -1}; + if (::pipe(pipe_fds) != 0) { + return {}; + } + + pid_t pid = ::fork(); + if (pid < 0) { + ::close(pipe_fds[0]); + ::close(pipe_fds[1]); + return {}; + } + + if (pid == 0) { + ::close(pipe_fds[0]); + ::dup2(pipe_fds[1], STDOUT_FILENO); + int devnull = ::open("/dev/null", O_WRONLY); + if (devnull >= 0) { + ::dup2(devnull, STDERR_FILENO); + ::close(devnull); + } + ::close(pipe_fds[1]); + + const char* argv[] = {"tailscale", "status", "--json", nullptr}; + ::execvp("tailscale", const_cast(argv)); + ::_exit(127); + } + + ::close(pipe_fds[1]); + FdGuard read_guard{pipe_fds[0]}; + + int flags = ::fcntl(read_guard.fd, F_GETFL, 0); + if (flags >= 0) { + ::fcntl(read_guard.fd, F_SETFL, flags | O_NONBLOCK); + } + + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(2000); + std::string output; + char buf[4096]; + bool timed_out = false; + + while (true) { + ssize_t n = ::read(read_guard.fd, buf, sizeof(buf)); + if (n > 0) { + output.append(buf, static_cast(n)); + continue; + } + if (n == 0) { + break; + } + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + if (!wait_poll(read_guard.fd, POLLIN, deadline)) { + timed_out = true; + break; + } + continue; + } + break; + } + + if (timed_out) { + ::kill(pid, SIGKILL); + } + + int wstatus = 0; + while (::waitpid(pid, &wstatus, 0) < 0 && errno == EINTR) { + } + + if (timed_out || !WIFEXITED(wstatus) || WEXITSTATUS(wstatus) != 0) { + return {}; + } + + return parse_tailscale_peers(output); +} + +CommandResult IpcClient::run_json_command(const std::string& payload) const { + CommandResult res; + res.raw_json = send_command(payload, 1000); + if (res.raw_json.empty()) { + res.ok = false; + res.error = "No response from daemon"; + return res; + } + + JsonValue root; + if (!parse_json(res.raw_json, root) || root.type != JsonValue::Type::Object) { + res.ok = false; + res.error = "Invalid JSON response"; + return res; + } + + if (const auto* ok_val = root.find("ok")) { + res.ok = ok_val->as_bool(false); + } + if (const auto* err_val = root.find("error")) { + res.error = err_val->as_string(); + } + if (!res.ok && res.error.empty()) { + res.error = "Command failed"; + } + return res; +} + +CommandResult IpcClient::sync_now() const { + return run_json_command(R"({"cmd":"sync_now"})"); +} + +CommandResult IpcClient::add_folder(const std::string& path, const std::string& label) const { + std::ostringstream oss; + oss << R"({"cmd":"add_folder","path":)" << json_escape(path); + if (!label.empty()) { + oss << R"(,"label":)" << json_escape(label); + } + oss << "}"; + return run_json_command(oss.str()); +} + +CommandResult IpcClient::remove_folder(const std::string& folder_id) const { + std::ostringstream oss; + oss << R"({"cmd":"remove_folder","folder_id":)" << json_escape(folder_id) << "}"; + return run_json_command(oss.str()); +} + +CommandResult IpcClient::set_target(const std::string& host, int port) const { + std::ostringstream oss; + oss << R"({"cmd":"set_target","host":)" << json_escape(host) << R"(,"port":)" << port << "}"; + return run_json_command(oss.str()); +} + +CommandResult IpcClient::set_theme(ThemeMode theme) const { + std::ostringstream oss; + oss << R"({"cmd":"set_theme","theme":)" << json_escape(theme_to_string(theme)) << "}"; + return run_json_command(oss.str()); +} + +CommandResult IpcClient::retry_failed() const { + return run_json_command(R"({"cmd":"retry_failed"})"); +} + +} // namespace cp0 diff --git a/device-ui/src/ipc_client.hpp b/device-ui/src/ipc_client.hpp new file mode 100644 index 0000000..fde71eb --- /dev/null +++ b/device-ui/src/ipc_client.hpp @@ -0,0 +1,126 @@ +#pragma once + +#include "theme.hpp" + +#include +#include +#include + +namespace cp0 { + +/// Per-watched-folder queue and existence snapshot. +struct FolderStatus { + std::string id; + std::string path; + std::string label; + bool enabled = true; + bool exists = false; + int pending = 0; + int uploading = 0; + int synced = 0; + int failed = 0; + int64_t pending_bytes = 0; +}; + +/// Single log line from the daemon's SQLite log ring buffer. +struct LogEntry { + int64_t id = 0; + int64_t ts = 0; + std::string level; + std::string message; +}; + +/// Full status snapshot from IPC `status` or read-only SQLite + config fallback. +struct DaemonStatus { + bool ok = false; + bool from_fallback = false; + std::string error; + std::string target_host; + int target_port = 8765; + std::string theme = "dark"; + bool mac_online = false; + std::string mac_dest_root; + bool syncing = false; + std::string current_file; + int pending_count = 0; + int64_t pending_bytes = 0; + int synced_count = 0; + int failed_count = 0; + int next_retry_sec = 0; + int64_t last_sync_ts = 0; + std::string last_synced_file; + std::string last_error; + std::vector folders; + std::vector logs; +}; + +/// Result of a mutating IPC command (`sync_now`, `add_folder`, etc.). +struct CommandResult { + bool ok = false; + std::string error; + std::string raw_json; +}; + +/// Non-self Tailscale peer extracted from `tailscale status --json`. +struct TailscalePeer { + std::string id; + std::string hostname; + std::string dns_name; + std::string os; + bool online = false; + std::vector tailscale_ips; +}; + +/// Return default Unix socket path (`CP0_SYNC_SOCK` or `${XDG_RUNTIME_DIR:-/tmp}/cp0-sync.sock`). +std::string default_sock_path(); + +/// Return default SQLite state DB path (`CP0_SYNC_DB` or `$HOME/.local/share/cp0-sync/state.db`). +std::string default_db_path(); + +/// Return default daemon config path (`CP0_SYNC_CONFIG` or `$HOME/.config/cp0-sync/config.json`). +std::string default_config_path(); + +/// Parse `status` JSON response string into a DaemonStatus struct. +DaemonStatus parse_status_json(const std::string& json_str); + +/// Parse `tailscale status --json` output, excluding Self and sorting online macOS/darwin peers first. +std::vector parse_tailscale_peers(const std::string& json_str); + +/// Unix domain socket IPC client with read-only SQLite fallback and Tailscale peer discovery. +class IpcClient { +public: + IpcClient() = default; + explicit IpcClient(std::string sock_path, std::string db_path = "", std::string config_path = ""); + + /// Fetch live daemon status over AF_UNIX, falling back to read-only SQLite if socket is unreachable. + DaemonStatus fetch_status() const; + + /// Send a single newline-delimited JSON command over AF_UNIX with a non-blocking timeout. + std::string send_command(const std::string& json_line, int timeout_ms = 1000) const; + + /// Read cached state directly from SQLite (`SQLITE_OPEN_READONLY`) and `config.json`. + DaemonStatus read_sqlite_fallback() const; + + /// Execute `tailscale status --json` locally and return sorted non-self peers. + std::vector list_tailscale_peers() const; + + // Typed command helpers matching Task 4 IPC protocol + CommandResult sync_now() const; + CommandResult add_folder(const std::string& path, const std::string& label = "") const; + CommandResult remove_folder(const std::string& folder_id) const; + CommandResult set_target(const std::string& host, int port = 8765) const; + CommandResult set_theme(ThemeMode theme) const; + CommandResult retry_failed() const; + +private: + std::string resolved_sock_path() const; + std::string resolved_db_path() const; + std::string resolved_config_path() const; + CommandResult run_json_command(const std::string& payload) const; + + std::string sock_path_; + std::string db_path_; + std::string config_path_; +}; + +} // namespace cp0 diff --git a/device-ui/src/theme.cpp b/device-ui/src/theme.cpp new file mode 100644 index 0000000..4bed3b7 --- /dev/null +++ b/device-ui/src/theme.cpp @@ -0,0 +1,59 @@ +#include "theme.hpp" + +namespace cp0 { + +ShadcnPalette get_palette(ThemeMode mode) { + if (mode == ThemeMode::Light) { + return ShadcnPalette{ + /* background */ 0xfafafa, + /* card */ 0xffffff, + /* muted */ 0xf4f4f5, + /* border */ 0xe4e4e7, + /* ring */ 0x71717a, + /* foreground */ 0x09090b, + /* muted_foreground */ 0x71717a, + /* active_tab_bg */ 0xffffff, + /* active_tab_fg */ 0x09090b, + /* active_tab_border */ 0xe4e4e7, + /* status_online */ 0x16a34a, + /* status_online_bg */ 0xdcfce7, + /* status_sleeping */ 0xd97706, + /* status_sleeping_bg */ 0xfef3c7, + /* status_error */ 0xdc2626, + /* status_error_bg */ 0xfee2e2, + }; + } + + return ShadcnPalette{ + /* background */ 0x09090b, + /* card */ 0x09090b, + /* muted */ 0x18181b, + /* border */ 0x27272a, + /* ring */ 0xd4d4d8, + /* foreground */ 0xfafafa, + /* muted_foreground */ 0xa1a1aa, + /* active_tab_bg */ 0x27272a, + /* active_tab_fg */ 0xfafafa, + /* active_tab_border */ 0x27272a, + /* status_online */ 0x4ade80, + /* status_online_bg */ 0x11261a, + /* status_sleeping */ 0xfbbf24, + /* status_sleeping_bg */ 0x271d0b, + /* status_error */ 0xf87171, + /* status_error_bg */ 0x2b1214, + }; +} + +ThemeMode toggle_theme(ThemeMode mode) { + return mode == ThemeMode::Dark ? ThemeMode::Light : ThemeMode::Dark; +} + +std::string theme_to_string(ThemeMode mode) { + return mode == ThemeMode::Light ? "light" : "dark"; +} + +ThemeMode theme_from_string(const std::string& theme) { + return theme == "light" ? ThemeMode::Light : ThemeMode::Dark; +} + +} // namespace cp0 diff --git a/device-ui/src/theme.hpp b/device-ui/src/theme.hpp new file mode 100644 index 0000000..cad9f51 --- /dev/null +++ b/device-ui/src/theme.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +namespace cp0 { + +/// Supported UI color themes matching daemon config values ("dark" | "light"). +enum class ThemeMode { + Dark, + Light, +}; + +/// Exact shadcn/ui Zinc color tokens (24-bit RGB hex values). +struct ShadcnPalette { + uint32_t background; + uint32_t card; + uint32_t muted; + uint32_t border; + uint32_t ring; + uint32_t foreground; + uint32_t muted_foreground; + uint32_t active_tab_bg; + uint32_t active_tab_fg; + uint32_t active_tab_border; + uint32_t status_online; + uint32_t status_online_bg; + uint32_t status_sleeping; + uint32_t status_sleeping_bg; + uint32_t status_error; + uint32_t status_error_bg; +}; + +/// Return the Zinc Dark or Zinc Light palette tokens from Spec Section 5.4. +ShadcnPalette get_palette(ThemeMode mode); + +/// Toggle between ThemeMode::Dark and ThemeMode::Light. +ThemeMode toggle_theme(ThemeMode mode); + +/// Convert ThemeMode to its persisted config/IPC string ("dark" or "light"). +std::string theme_to_string(ThemeMode mode); + +/// Parse a theme string ("light" -> Light, anything else -> Dark). +ThemeMode theme_from_string(const std::string& theme); + +} // namespace cp0 diff --git a/device-ui/tests/test_ipc_and_theme.cpp b/device-ui/tests/test_ipc_and_theme.cpp new file mode 100644 index 0000000..10b635e --- /dev/null +++ b/device-ui/tests/test_ipc_and_theme.cpp @@ -0,0 +1,463 @@ +#include "ipc_client.hpp" +#include "theme.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +struct TempDir { + fs::path path; + explicit TempDir(const std::string& prefix) { + auto base = fs::temp_directory_path(); + auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + path = base / (prefix + "_" + std::to_string(getpid()) + "_" + std::to_string(stamp)); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ec; + fs::remove_all(path, ec); + } +}; + +void test_theme_tokens() { + auto dark = cp0::get_palette(cp0::ThemeMode::Dark); + assert(dark.background == 0x09090b); + assert(dark.card == 0x09090b); + assert(dark.muted == 0x18181b); + assert(dark.border == 0x27272a); + assert(dark.ring == 0xd4d4d8); + assert(dark.foreground == 0xfafafa); + assert(dark.muted_foreground == 0xa1a1aa); + assert(dark.active_tab_bg == 0x27272a); + assert(dark.active_tab_fg == 0xfafafa); + assert(dark.active_tab_border == 0x27272a); + assert(dark.status_online == 0x4ade80); + assert(dark.status_online_bg == 0x11261a); + assert(dark.status_sleeping == 0xfbbf24); + assert(dark.status_sleeping_bg == 0x271d0b); + assert(dark.status_error == 0xf87171); + assert(dark.status_error_bg == 0x2b1214); + + auto light = cp0::get_palette(cp0::ThemeMode::Light); + assert(light.background == 0xfafafa); + assert(light.card == 0xffffff); + assert(light.muted == 0xf4f4f5); + assert(light.border == 0xe4e4e7); + assert(light.ring == 0x71717a); + assert(light.foreground == 0x09090b); + assert(light.muted_foreground == 0x71717a); + assert(light.active_tab_bg == 0xffffff); + assert(light.active_tab_fg == 0x09090b); + assert(light.active_tab_border == 0xe4e4e7); + assert(light.status_online == 0x16a34a); + assert(light.status_online_bg == 0xdcfce7); + assert(light.status_sleeping == 0xd97706); + assert(light.status_sleeping_bg == 0xfef3c7); + assert(light.status_error == 0xdc2626); + assert(light.status_error_bg == 0xfee2e2); + + assert(cp0::toggle_theme(cp0::ThemeMode::Dark) == cp0::ThemeMode::Light); + assert(cp0::toggle_theme(cp0::ThemeMode::Light) == cp0::ThemeMode::Dark); + assert(cp0::theme_to_string(cp0::ThemeMode::Dark) == "dark"); + assert(cp0::theme_to_string(cp0::ThemeMode::Light) == "light"); + assert(cp0::theme_from_string("light") == cp0::ThemeMode::Light); + assert(cp0::theme_from_string("dark") == cp0::ThemeMode::Dark); + assert(cp0::theme_from_string("unknown") == cp0::ThemeMode::Dark); +} + +void test_tailscale_peer_parsing() { + const char* ts_json = R"({ + "Self": {"ID": "self1", "HostName": "cardputerzero", "OS": "linux"}, + "Peer": { + "self1": {"ID": "self1", "HostName": "cardputerzero", "DNSName": "cp0.ts.net.", "OS": "linux", "Online": true, "TailscaleIPs": ["100.64.0.1"]}, + "p1": {"ID": "p1", "HostName": "linux-box", "DNSName": "linux.ts.net.", "OS": "linux", "Online": true, "TailscaleIPs": ["100.64.0.2"]}, + "p2": {"ID": "p2", "HostName": "macbook-offline", "DNSName": "mac-off.ts.net.", "OS": "macOS", "Online": false, "TailscaleIPs": ["100.64.0.4"]}, + "p3": {"ID": "p3", "HostName": "macbook", "DNSName": "macbook.ts.net.", "OS": "macOS", "Online": true, "TailscaleIPs": ["100.64.0.3", "fd7a:115c:a1e0::3"]}, + "p4": {"ID": "p4", "HostName": "imac-darwin", "DNSName": "imac.ts.net.", "OS": "darwin", "Online": true, "TailscaleIPs": ["100.64.0.5"]} + } + })"; + + auto peers = cp0::parse_tailscale_peers(ts_json); + assert(peers.size() == 4); + // Online macOS/darwin peers first (alphabetical by hostname: imac-darwin, macbook) + assert(peers[0].hostname == "imac-darwin"); + assert(peers[0].os == "darwin"); + assert(peers[0].online == true); + assert(peers[0].dns_name == "imac.ts.net"); + assert(peers[1].hostname == "macbook"); + assert(peers[1].os == "macOS"); + assert(peers[1].online == true); + assert(peers[1].dns_name == "macbook.ts.net"); + assert(peers[1].tailscale_ips.size() == 2); + assert(peers[1].tailscale_ips[0] == "100.64.0.3"); + // Offline macOS peer next (still macOS group before linux) + assert(peers[2].hostname == "macbook-offline"); + assert(peers[2].online == false); + // Online non-macOS peer last + assert(peers[3].hostname == "linux-box"); + assert(peers[3].os == "linux"); + + // Invalid JSON returns empty gracefully + assert(cp0::parse_tailscale_peers("{not-json").empty()); + assert(cp0::parse_tailscale_peers("").empty()); +} + +void test_ipc_socket_round_trip() { + TempDir tmp("cp0_ipc"); + fs::path sock_path = tmp.path / "cp0-sync.sock"; + + int srv_fd = socket(AF_UNIX, SOCK_STREAM, 0); + assert(srv_fd >= 0); + + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + assert(sock_path.string().size() < sizeof(addr.sun_path)); + std::strncpy(addr.sun_path, sock_path.c_str(), sizeof(addr.sun_path) - 1); + + unlink(sock_path.c_str()); + assert(bind(srv_fd, reinterpret_cast(&addr), sizeof(addr)) == 0); + assert(listen(srv_fd, 8) == 0); + + std::vector received_cmds; + std::atomic stop{false}; + + std::thread server_thread([&]() { + while (!stop.load()) { + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(srv_fd, &rfds); + timeval tv{0, 50000}; + int ready = select(srv_fd + 1, &rfds, nullptr, nullptr, &tv); + if (ready <= 0) { + continue; + } + int cli_fd = accept(srv_fd, nullptr, nullptr); + if (cli_fd < 0) { + continue; + } + std::string req; + char ch = 0; + while (read(cli_fd, &ch, 1) == 1) { + if (ch == '\n') { + break; + } + req.push_back(ch); + } + received_cmds.push_back(req); + + std::string resp; + if (req.find("\"status\"") != std::string::npos) { + resp = R"({"ok":true,"target_host":"macbook.ts.net","target_port":8765,"theme":"light","mac_online":true,"mac_dest_root":"/Users/user/Pictures/CardputerZero","syncing":true,"current_file":"IMG_0042.JPG","pending_count":3,"pending_bytes":4096,"synced_count":12,"failed_count":1,"next_retry_sec":15,"last_sync_ts":1731900000000,"last_synced_file":"IMG_0041.JPG","last_error":"none","folders":[{"id":"camera","path":"/home/user/Pictures/DCIM/Camera","label":"Camera","enabled":true,"exists":true,"pending":3,"uploading":1,"synced":12,"failed":1,"pending_bytes":4096}],"logs":[{"id":10,"ts":1731900001000,"level":"INFO","message":"Synced \"IMG_0041.JPG\""}]})" + "\n"; + } else if (req.find("\"set_theme\"") != std::string::npos) { + resp = R"({"ok":true,"theme":"light"})" "\n"; + } else if (req.find("\"add_folder\"") != std::string::npos) { + resp = R"({"ok":true,"enqueued":2})" "\n"; + } else if (req.find("\"remove_folder\"") != std::string::npos) { + resp = R"({"ok":true,"purged":0})" "\n"; + } else if (req.find("\"set_target\"") != std::string::npos) { + resp = R"({"ok":true,"target_host":"mac.local","target_port":9000})" "\n"; + } else if (req.find("\"sync_now\"") != std::string::npos) { + resp = R"({"ok":true,"enqueued":0})" "\n"; + } else if (req.find("\"retry_failed\"") != std::string::npos) { + resp = R"({"ok":true,"retried":1})" "\n"; + } else { + resp = R"({"ok":false,"error":"unknown"})" "\n"; + } + + size_t sent = 0; + while (sent < resp.size()) { + ssize_t n = write(cli_fd, resp.data() + sent, resp.size() - sent); + if (n <= 0) break; + sent += static_cast(n); + } + close(cli_fd); + } + }); + + cp0::IpcClient client(sock_path.string(), (tmp.path / "missing.db").string(), (tmp.path / "missing.json").string()); + + auto st = client.fetch_status(); + if (!st.ok) { + std::cerr << "fetch_status failed: error=" << st.error + << " raw=" << client.send_command(R"({"cmd":"status"})", 1000) << "\n"; + } + assert(st.ok == true); + assert(st.from_fallback == false); + assert(st.target_host == "macbook.ts.net"); + assert(st.target_port == 8765); + assert(st.theme == "light"); + assert(st.mac_online == true); + assert(st.mac_dest_root == "/Users/user/Pictures/CardputerZero"); + assert(st.syncing == true); + assert(st.current_file == "IMG_0042.JPG"); + assert(st.pending_count == 3); + assert(st.pending_bytes == 4096); + assert(st.synced_count == 12); + assert(st.failed_count == 1); + assert(st.next_retry_sec == 15); + assert(st.last_sync_ts == 1731900000000LL); + assert(st.last_synced_file == "IMG_0041.JPG"); + assert(st.last_error == "none"); + assert(st.folders.size() == 1); + assert(st.folders[0].id == "camera"); + assert(st.folders[0].path == "/home/user/Pictures/DCIM/Camera"); + assert(st.folders[0].label == "Camera"); + assert(st.folders[0].enabled == true); + assert(st.folders[0].exists == true); + assert(st.folders[0].pending == 3); + assert(st.folders[0].uploading == 1); + assert(st.folders[0].synced == 12); + assert(st.folders[0].failed == 1); + assert(st.folders[0].pending_bytes == 4096); + assert(st.logs.size() == 1); + assert(st.logs[0].id == 10); + assert(st.logs[0].ts == 1731900001000LL); + assert(st.logs[0].level == "INFO"); + assert(st.logs[0].message == "Synced \"IMG_0041.JPG\""); + + assert(client.sync_now().ok); + assert(client.add_folder("/tmp/My \"Photos\"", "Trips").ok); + assert(client.remove_folder("camera").ok); + assert(client.set_target("mac.local", 9000).ok); + assert(client.set_theme(cp0::ThemeMode::Light).ok); + assert(client.retry_failed().ok); + + // Check escaped JSON serialization in add_folder + assert(received_cmds.size() == 7); + assert(received_cmds[2].find("\\\"Photos\\\"") != std::string::npos); + + stop.store(true); + server_thread.join(); + close(srv_fd); +} + +void test_sqlite_fallback_and_config() { + TempDir tmp("cp0_sqlite"); + fs::path db_path = tmp.path / "state.db"; + fs::path cfg_path = tmp.path / "config.json"; + fs::path cam_dir = tmp.path / "Camera"; + fs::create_directories(cam_dir); + + { + std::ofstream cfg_out(cfg_path); + cfg_out << R"({ + "target_host": "studio-mac.ts.net", + "target_port": 8777, + "theme": "light", + "watched_folders": [ + {"id": "cam1", "path": ")" << cam_dir.string() << R"(", "label": "Camera", "enabled": true}, + {"id": "sd1", "path": "/media/missing-sd", "label": "SD", "enabled": true} + ] + })"; + } + + sqlite3* db = nullptr; + assert(sqlite3_open(db_path.c_str(), &db) == SQLITE_OK); + const char* schema_sql = R"SQL( + PRAGMA journal_mode=WAL; + CREATE TABLE files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + folder_id TEXT NOT NULL, + abs_path TEXT NOT NULL, + rel_path TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + mtime_ns INTEGER NOT NULL, + sha256 TEXT NOT NULL, + status TEXT NOT NULL, + retry_count INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + discovered_at INTEGER NOT NULL, + synced_at INTEGER + ); + CREATE TABLE logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts INTEGER NOT NULL, + level TEXT NOT NULL, + message TEXT NOT NULL + ); + CREATE TABLE meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + INSERT INTO meta(key, value) VALUES + ('mac_online', 'false'), + ('mac_dest_root', '/Users/user/Photos'), + ('last_sync_ts', '1731900500000'), + ('last_synced_file', 'DSC0001.JPG'), + ('last_error', 'connection refused'); + INSERT INTO files(folder_id, abs_path, rel_path, size_bytes, mtime_ns, sha256, status, discovered_at) + VALUES + ('cam1', '/tmp/a.jpg', 'a.jpg', 1000, 1, 'h1', 'PENDING', 100), + ('cam1', '/tmp/b.jpg', 'b.jpg', 2500, 2, 'h2', 'UPLOADING', 101), + ('cam1', '/tmp/c.jpg', 'c.jpg', 3000, 3, 'h3', 'SYNCED', 102), + ('sd1', '/tmp/d.jpg', 'd.jpg', 500, 4, 'h4', 'FAILED', 103); + INSERT INTO logs(ts, level, message) VALUES + (1731900100000, 'INFO', 'Daemon booted'), + (1731900200000, 'WARN', 'Mac unreachable'); + )SQL"; + char* errmsg = nullptr; + assert(sqlite3_exec(db, schema_sql, nullptr, nullptr, &errmsg) == SQLITE_OK); + sqlite3_close(db); + + // Point socket at a non-existent path so fetch_status() exercises SQLite fallback too + cp0::IpcClient client((tmp.path / "nonexistent.sock").string(), db_path.string(), cfg_path.string()); + + auto st = client.read_sqlite_fallback(); + assert(st.ok == true); + assert(st.from_fallback == true); + assert(st.target_host == "studio-mac.ts.net"); + assert(st.target_port == 8777); + assert(st.theme == "light"); + assert(st.mac_online == false); + assert(st.mac_dest_root == "/Users/user/Photos"); + assert(st.last_sync_ts == 1731900500000LL); + assert(st.last_synced_file == "DSC0001.JPG"); + assert(st.last_error == "connection refused"); + assert(st.pending_count == 2); + assert(st.pending_bytes == 3500); + assert(st.synced_count == 1); + assert(st.failed_count == 1); + assert(st.folders.size() == 2); + assert(st.folders[0].id == "cam1"); + assert(st.folders[0].exists == true); + assert(st.folders[0].pending == 2); + assert(st.folders[0].uploading == 1); + assert(st.folders[0].synced == 1); + assert(st.folders[0].pending_bytes == 3500); + assert(st.folders[1].id == "sd1"); + assert(st.folders[1].exists == false); + assert(st.folders[1].failed == 1); + assert(st.logs.size() == 2); + assert(st.logs[0].level == "WARN"); + assert(st.logs[0].message == "Mac unreachable"); + assert(st.logs[1].level == "INFO"); + + // fetch_status() falls back automatically when socket is unreachable + auto via_fetch = client.fetch_status(); + assert(via_fetch.ok == true); + assert(via_fetch.from_fallback == true); + assert(via_fetch.pending_count == 2); + + // SQLite fallback without config.json still aggregates DB counts & logs + cp0::IpcClient db_only((tmp.path / "nonexistent.sock").string(), db_path.string(), (tmp.path / "no-cfg.json").string()); + auto db_only_st = db_only.read_sqlite_fallback(); + assert(db_only_st.ok == true); + assert(db_only_st.pending_count == 2); + assert(db_only_st.synced_count == 1); + assert(db_only_st.failed_count == 1); + assert(db_only_st.folders.size() == 2); + + // Missing DB returns ok=false + cp0::IpcClient missing_all((tmp.path / "nonexistent.sock").string(), (tmp.path / "no.db").string(), (tmp.path / "no-cfg.json").string()); + assert(missing_all.read_sqlite_fallback().ok == false); + assert(missing_all.fetch_status().ok == false); +} + +void test_status_parsing_and_env_paths() { + // Exact daemon.py _cmd_status shape (without optional uploading/failed/pending_bytes in folders) + const char* daemon_json = R"({ + "ok": true, + "target_host": "my-mac.ts.net", + "target_port": 8765, + "theme": "dark", + "mac_online": false, + "mac_dest_root": "", + "syncing": false, + "current_file": "", + "pending_count": 0, + "pending_bytes": 0, + "synced_count": 5, + "failed_count": 0, + "next_retry_sec": 0, + "last_sync_ts": 0, + "last_synced_file": "", + "last_error": "", + "folders": [ + {"id": "camera", "path": "/home/cp0/Pictures/DCIM/Camera", "label": "Camera", "enabled": true, "exists": false, "pending": 0, "synced": 5} + ], + "logs": [] + })"; + auto st = cp0::parse_status_json(daemon_json); + assert(st.ok == true); + assert(st.folders.size() == 1); + assert(st.folders[0].id == "camera"); + assert(st.folders[0].exists == false); + assert(st.folders[0].synced == 5); + assert(st.folders[0].uploading == 0); + assert(st.folders[0].failed == 0); + assert(st.folders[0].pending_bytes == 0); + + auto err_st = cp0::parse_status_json(R"({"ok":false,"error":"bad cmd"})"); + assert(err_st.ok == false); + assert(err_st.error == "bad cmd"); + + // Env overrides for default paths + setenv("CP0_SYNC_SOCK", "/tmp/custom-cp0.sock", 1); + setenv("CP0_SYNC_DB", "/tmp/custom-cp0.db", 1); + setenv("CP0_SYNC_CONFIG", "/tmp/custom-cp0.json", 1); + assert(cp0::default_sock_path() == "/tmp/custom-cp0.sock"); + assert(cp0::default_db_path() == "/tmp/custom-cp0.db"); + assert(cp0::default_config_path() == "/tmp/custom-cp0.json"); + unsetenv("CP0_SYNC_SOCK"); + unsetenv("CP0_SYNC_DB"); + unsetenv("CP0_SYNC_CONFIG"); +} + +void test_list_tailscale_peers_subprocess() { + TempDir tmp("cp0_ts_bin"); + fs::path fake_bin = tmp.path / "tailscale"; + { + std::ofstream out(fake_bin); + out << "#!/bin/sh\n" + << "echo '{\"Self\":{\"ID\":\"s1\"},\"Peer\":{\"p1\":{\"HostName\":\"mini\",\"DNSName\":\"mini.ts.net.\",\"OS\":\"macOS\",\"Online\":true,\"TailscaleIPs\":[\"100.64.0.9\"]}}}'\n"; + } + fs::permissions(fake_bin, fs::perms::owner_exec | fs::perms::owner_read | fs::perms::owner_write); + + const char* old_path = std::getenv("PATH"); + std::string new_path = tmp.path.string() + (old_path ? (std::string(":") + old_path) : ""); + setenv("PATH", new_path.c_str(), 1); + + cp0::IpcClient client; + auto peers = client.list_tailscale_peers(); + if (old_path) { + setenv("PATH", old_path, 1); + } + + assert(peers.size() == 1); + assert(peers[0].hostname == "mini"); + assert(peers[0].dns_name == "mini.ts.net"); + assert(peers[0].os == "macOS"); + assert(peers[0].online == true); +} + +} // namespace + +int main() { + test_theme_tokens(); + test_tailscale_peer_parsing(); + test_ipc_socket_round_trip(); + test_sqlite_fallback_and_config(); + test_status_parsing_and_env_paths(); + test_list_tailscale_peers_subprocess(); + std::cout << "All test_ipc_and_theme assertions passed.\n"; + return 0; +}