From f5b7ddfb538bd1d7b6be3fa8aedd633ae7f27d37 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 21:26:55 +0200 Subject: [PATCH] Expose file operations to trusted LAN clients Refs #122 --- CMakeLists.txt | 2 +- LAN-PREVIEW.md | 67 ++++++- src/lan.cpp | 105 +++-------- src/lan_client_files.cpp | 380 +++++++++++++++++++++++++++++++++++++++ src/lan_client_files.h | 15 ++ src/lan_clients.h | 57 ++++-- src/lan_files.cpp | 18 +- src/lan_files.h | 3 +- src/ui_lan.inl | 51 +++++- tests/lan_clients.cpp | 349 +++++++++++++++++++++++++++++------ 10 files changed, 885 insertions(+), 162 deletions(-) create mode 100644 src/lan_client_files.cpp create mode 100644 src/lan_client_files.h diff --git a/CMakeLists.txt b/CMakeLists.txt index f0408a3..2e71276 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -55,7 +55,7 @@ foreach(utilityTarget StayHere StayHereTest) target_link_options(${utilityTarget} PRIVATE -municode -static -static-libgcc -static-libstdc++) endif() endforeach() -add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp) +add_library(kscore src/lan_files.cpp src/lan_client_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp) target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp) foreach(field IN ITEMS ID SECRET) set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}") diff --git a/LAN-PREVIEW.md b/LAN-PREVIEW.md index b43aba1..872d51f 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -9,9 +9,72 @@ with all online paired computers: history and the active clipboard. ## Trusted LAN clients -Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process. +Open **Settings → Computers → Manage computers → Trusted clients** and choose +**Add client…**. Select the executable, confirm, and click **Save** in Settings. +A newly approved or previously enrolled executable can list pairs, browse +drives and download regular files. For each executable you can separately +enable **Allow write** for creating, editing, renaming, and copying, and +**Allow delete** for the recycle bin and permanent deletion. Move needs both +permissions. The paired computer's Windows access and file-sharing settings +still apply. KSwitcher retains the pairing credentials. -Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint. +Select an executable and choose **Remove**, or turn off an individual grant, +then click **Save** to revoke access. KSwitcher checks grants again during +streaming and before publication or source removal. Add an updated executable +again because approval covers its path and SHA-256 fingerprint. + +### Local trusted-client protocol + +The Windows pipe is `\\.\pipe\KSwitcher.LAN.Clients.v1.` and accepts +one request per connection from the resident's user. Send a JSON object in an +unsigned 32-bit little-endian length frame (maximum 16 KiB for the request). +Replies have the same length prefix. After the last reply, send one raw +acknowledgement byte and close. An error reply is a JSON object containing +a string `error`. Existing `peers`, `drives`, `list` and `download` requests +retain their original reply formats. + +- `capabilities` optionally takes a `peer`. It returns the broker `protocol` + (2), `hostRevision`, and boolean `write`, `delete`, `move`, + `revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer, + the fields describe the local broker and its grants. With a peer, the flags + also account for its supported protocol. A peer with revision 0 still + supports legacy browsing and downloading. +- `stat` takes `peer` and an absolute `path`. It returns Windows attributes, + byte `size` and `modified` (Windows FILETIME). Preserve 64-bit integers + without rounding. `readFile` takes the same arguments plus an optional + `expected` object with `size` and `modified`. It returns metadata followed + by raw frames up to 64 KiB and a zero-length frame. Require the declared + byte count and the zero-length frame before accepting the download. +- `writeFile` takes `peer`, `path`, and the incoming byte `size`. Omit + `expected` for an exclusive create. Include the original `size` and + `modified` in `expected` for an edit. After the `ready` JSON reply, send + raw frames up to 64 KiB followed by a zero-length frame. The final reply + contains the saved metadata or an error. The host stages bytes until + the upload is complete and checks the revision when publishing an edit. +- `mkdir`, `rename`, `recycle`, and `delete` take `peer` and `path`. + Rename also takes a single new `name` and fails if the destination exists. + Permanent deletion of nonempty directories requires `recursive: true`. + The recycle bin is subject to Windows availability on the paired host. +- `transfer` takes `source` and `target` objects with a `peer` and `path` + each, optional `move` (default false), and a `conflict` policy of `fail` + (default), `skip`, or `replace`. Replace merges directories and replaces + regular files after validating the destination revision. The broker + allows at most one local endpoint, represented by `"peer": null`. For a + local endpoint the client must open the pipe with Windows impersonation + enabled, and local files are accessed using the caller's token. +- Transfer replies are JSON progress frames containing `type: "progress"`, + `phase` (`copy` or `remove`), source `path`, byte `done` and `total` for the current file, and + `completed` and `skipped` item counts. Reply to each progress frame with + a JSON frame containing `continue: true` or `continue: false`. The + final frame has `type: "complete"` and counts, or an error. Transfers + on one paired computer use its own file service even across drives. The + local pipe exchanges only control and status for transfers. +- For a move, the copy phase finishes before source deletion begins. + Skipped items remain at the source. Cancellation or failure can leave + previously completed destination items. Failure during source cleanup + can leave a partially removed source tree. Unpublished file uploads are + discarded. File-tree transfer does not follow junctions or symbolic + links within the tree. ## Remote files and diagnostic logs diff --git a/src/lan.cpp b/src/lan.cpp index 364162e..c0d288f 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -9,7 +9,7 @@ #include "lan_layout.h" #include "lan_network.h" #include "lan_wake.h" -#include "lan_clients.h" +#include "lan_client_files.h" #include #include #include @@ -183,24 +183,16 @@ struct LanService::Impl ~Impl() { clients.stop(); stop(); } void startClients() { - clients.start([this](const Json &request, const auto &allowed, const auto &send) { - const auto action = request.at("action").get(); - auto reply = [&](const Json &result) { - const auto text = result.dump(); - send(text.data(), DWORD(text.size())); + clients.start([this](const Json &request, const auto &allowed, const auto &send, const auto &receive, const auto &asCaller) { + const auto reachable = [&](const Peer &peer) { + return enabled && peer.files && peer.verified && GetTickCount64() - peer.verified < lan::PeerLifetime; }; - lan::FilesPeer target; - std::string local, key; - auto machines = Json::array(); + if (request.at("action") == "peers") { - std::lock_guard gate(commandGate); - std::lock_guard lock(mutex); - const auto now = GetTickCount64(); - const auto reachable = [&](const Peer &peer) { - return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime; - }; - if (action == "peers") + auto machines = Json::array(); { + std::lock_guard gate(commandGate); + std::lock_guard lock(mutex); refreshFiles = true; for (const auto &[peer, pair] : trusted.items()) { @@ -209,74 +201,23 @@ struct LanService::Impl {"online", found != peers.end() && reachable(found->second)}}); } } - else - { - if (action != "drives" && action != "list" && action != "download") - throw std::runtime_error("Unsupported LAN client operation."); - const auto peer = request.at("peer").get(); - const auto found = peers.find(peer); - if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second)) - throw std::runtime_error("The paired computer is offline or file browsing is unavailable."); - char address[INET_ADDRSTRLEN]{}; - auto ip = found->second.address.sin_addr; - if (!InetNtopA(AF_INET, &ip, address, sizeof(address))) - throw std::runtime_error("The paired computer has no usable address."); - target = {peer, address, wide(found->second.name), lan::FilesPort, true}; - local = id; - key = trusted.at(peer).at("key").get(); - } - } - if (action == "peers") - { - reply(machines); + const auto result = machines.dump(); + send(result.data(), DWORD(result.size())); return; } - lan::FilesConnection connection(target, local, key); - if (action == "drives") - { - const auto result = connection.call({{"action", "drives"}}); - lan::checkFileReply(result); - reply(result.at("drives")); - return; - } - const auto path = lan::filePath(request.at("path")); - if (action == "list") - { - auto page = connection.call(lan::fileRequest("list", path)); - auto entries = Json::array(); - size_t bytes{}; - for (;;) - { - lan::checkFileReply(page); - for (auto &entry : page.at("entries")) - { - bytes += entry.dump().size() + 1; - if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large."); - entries.push_back(std::move(entry)); - } - if (!page.at("more").get()) break; - allowed(); - page = connection.call({{"action", "listNext"}}); - } - reply(entries); - return; - } - const auto file = connection.call(lan::fileRequest("stat", path)); - lan::checkFileReply(file); - auto open = lan::fileRequest("openRead", path); - open["size"] = file.at("size"); - open["modified"] = file.at("modified"); - lan::checkFileReply(connection.call(open)); - reply({{"size", file.at("size")}}); - for (;;) - { - allowed(); - const auto chunk = connection.call({{"action", "read"}}); - lan::checkFileReply(chunk); - const auto &data = chunk.at("data").get_binary(); - send(data.data(), DWORD(data.size())); - if (data.empty()) break; - } + lan::routeClientFiles(request, allowed, send, receive, asCaller, [&](const std::string &peer) { + std::lock_guard gate(commandGate); + std::lock_guard lock(mutex); + const auto found = peers.find(peer); + if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second)) + throw std::runtime_error("The paired computer is offline or file browsing is unavailable."); + char address[INET_ADDRSTRLEN]{}; + auto ip = found->second.address.sin_addr; + if (!InetNtopA(AF_INET, &ip, address, sizeof(address))) + throw std::runtime_error("The paired computer has no usable address."); + return lan::ClientFilesPeer{{peer, address, wide(found->second.name), lan::FilesPort, true}, + id, trusted.at(peer).at("key").get()}; + }); }); } void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted}, diff --git a/src/lan_client_files.cpp b/src/lan_client_files.cpp new file mode 100644 index 0000000..41d5c46 --- /dev/null +++ b/src/lan_client_files.cpp @@ -0,0 +1,380 @@ +#include "lan_client_files.h" +#include "files_win32_directory.h" + +namespace ks::lan +{ +namespace +{ +namespace fs = std::filesystem; +using Access = ClientFilesAccess; + +Json checked(FilesConnection &connection, const Json &request, const FileProgress &progress = {}) +{ + auto reply = connection.call(request, progress); + checkFileReply(reply); + return reply; +} +void sendJson(const ClientSend &send, const Json &reply) +{ + const auto text = reply.dump(); + send(text.data(), DWORD(text.size())); +} +void revision(Json &request, const Json &file) +{ + request["size"] = file.at("size"); + request["modified"] = file.at("modified"); +} +Json stat(FilesConnection &host, const fs::path &path) +{ + return checked(host, fileRequest("stat", path)); +} +unsigned hostRevision(FilesConnection &host) +{ + const auto result = host.call(fileRequest("fileCapabilities", L"C:\\")); + if (result.at("error") == ERROR_INVALID_FUNCTION) return 0; + checkFileReply(result); + return result.at("revision").get(); +} +void requireCurrentHost(FilesConnection &host) +{ + if (!hostRevision(host)) throw std::runtime_error("Update the paired computer to use this operation."); +} +bool granted(const ClientCheck &check, Access access) +{ + try { check(access); return true; } + catch (const std::runtime_error &) { check(Access::Browse); return false; } +} +Json capabilities(bool write, bool erase, unsigned host) +{ + return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host}, + {"delete", erase && host}, {"move", write && erase && host}, + {"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}}; +} +fs::path itemPath(const Json &value) +{ + auto path = filePath(value).lexically_normal(); + // Only regular drive paths reach remote mutations; never allow operating on a drive root. + const auto root = path.root_name().native(); + if (root.size() != 2 || root[1] != L':' || !path.is_absolute() || path.filename().empty()) + throw std::runtime_error("Choose a file or folder below a drive root."); + for (const auto &part : path.relative_path()) + if (!files::validWindowsFileName(part.native())) + throw std::runtime_error("Invalid Windows file name."); + return path; +} +bool directory(const Json &item) { return item.at("attributes").get() & FILE_ATTRIBUTE_DIRECTORY; } +bool reparse(const Json &item) { return item.at("attributes").get() & FILE_ATTRIBUTE_REPARSE_POINT; } +void requireRegular(const Json &item) +{ + if (reparse(item)) throw std::runtime_error("A file tree cannot include a junction or symbolic link."); +} +Json list(FilesConnection &host, const fs::path &path, const std::function &guard) +{ + auto page = host.call(fileRequest("list", path)); + auto entries = Json::array(); + size_t bytes{}; + for (;;) + { + checkFileReply(page); + for (auto &entry : page.at("entries")) + { + bytes += entry.dump().size() + 1; + if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large."); + entries.push_back(std::move(entry)); + } + if (!page.at("more").get()) return entries; + guard(); + page = host.call({{"action", "listNext"}}); + } +} +bool absent(const Json &result) +{ + return result.at("error") == ERROR_FILE_NOT_FOUND || result.at("error") == ERROR_PATH_NOT_FOUND; +} +bool sameOrBelow(const fs::path &parent, const fs::path &candidate) +{ + auto part = candidate.begin(); + for (const auto &component : parent) + { + if (part == candidate.end() || CompareStringOrdinal(component.c_str(), -1, part->c_str(), -1, TRUE) != CSTR_EQUAL) + return false; + ++part; + } + return true; +} +fs::path canonical(FilesConnection &host, const fs::path &path) +{ + return filePath(checked(host, fileRequest("canonical", path)).at("path")).lexically_normal(); +} +class ClientTransfer +{ + FilesConnection &source, ⌖ + const bool sameHost, move; + const std::string sourceId, conflict; + const std::function guard; + const ClientSend &send; + const ClientReceive &receive; + uint64_t completed{}, skipped{}; + struct Removal { fs::path path; Json metadata; }; + std::vector removals; + + void progress(const fs::path &path, uint64_t done, uint64_t total, const char *phase = "copy") + { + guard(); + sendJson(send, {{"type", "progress"}, {"phase", phase}, {"path", utf8(path.native())}, + {"done", done}, {"total", total}, + {"completed", completed}, {"skipped", skipped}}); + const auto result = Json::parse(receive(256)); + if (!result.at("continue").get()) throw std::system_error(ERROR_CANCELLED, std::system_category()); + guard(); + } + bool copy(const fs::path &from, const fs::path &to, unsigned depth) + { + if (depth > 256) throw std::runtime_error("The file tree is too deep."); + progress(from, 0, 0); + const auto original = stat(source, from); + requireRegular(original); + const auto existing = target.call(fileRequest("stat", to)); + const bool found = !absent(existing); + if (found) + { + checkFileReply(existing); + if (conflict == "skip") { ++skipped; return false; } + if (conflict != "replace" || directory(original) != directory(existing)) + throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category()); + requireRegular(existing); + } + + bool whole = true; + if (directory(original)) + { + if (!found) + { + guard(); + checked(target, fileRequest("mkdir", to)); + } + for (const auto &entry : list(source, from, guard)) + { + const auto child = wide(entry.at("name").get()); + if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry."); + if (!copy(from / child, to / child, depth + 1)) whole = false; + } + } + else + { + ULONGLONG last{}; + const auto onProgress = [&](uint64_t done, uint64_t total) { + guard(); + const auto now = GetTickCount64(); + if (!last || now - last >= 200 || done == total) + { + progress(from, done, total); + last = now; + } + return true; + }; + const FileRevision expected{existing.value("size", uint64_t{}), existing.value("modified", uint64_t{})}; + if (sameHost) + { + auto request = fileRequest("copy", from); + request.update({{"target", utf8(to.native())}, {"replace", found}, {"append", false}, {"resume", false}}); + revision(request, original); + if (found) request.update({{"expectedSize", expected.size}, {"expectedModified", expected.modified}}); + checked(source, request, onProgress); + } + else streamFile(source, target, sourceId, from, to, original.at("size"), original.at("modified"), + found, false, onProgress, found ? &expected : nullptr, false); + } + ++completed; + if (move && whole) removals.push_back({from, original}); + return whole; + } + +public: + ClientTransfer(FilesConnection &source, FilesConnection &target, bool sameHost, bool move, + const std::string &sourceId, const std::string &conflict, const std::function &guard, + const ClientSend &send, const ClientReceive &receive) + : source(source), target(target), sameHost(sameHost), move(move), sourceId(sourceId), conflict(conflict), + guard(guard), send(send), receive(receive) {} + + void run(const fs::path &from, const fs::path &to) + { + if (conflict != "fail" && conflict != "skip" && conflict != "replace") + throw std::runtime_error("Unknown conflict policy."); + if (sameHost) + { + const auto sourcePath = canonical(source, from); + const auto targetPath = canonical(target, to); + if (sameOrBelow(sourcePath, targetPath) || sameOrBelow(targetPath, sourcePath)) + throw std::runtime_error("Source and destination paths overlap."); + } + copy(from, to, 0); + if (!removals.empty()) progress(from, 0, 0, "remove"); + for (const auto &entry : removals) + { + guard(); + auto request = fileRequest(directory(entry.metadata) ? "rmdir" : "remove", entry.path); + if (!directory(entry.metadata)) revision(request, entry.metadata); + checked(source, request); + } + sendJson(send, {{"type", "complete"}, {"completed", completed}, {"skipped", skipped}}); + } +}; + +void read(FilesConnection &host, const fs::path &path, const Json &request, bool legacy, const ClientSend &send, + const std::function &guard) +{ + const auto file = stat(host, path); + auto open = fileRequest("openRead", path); + revision(open, file); + if (request.contains("expected") && + (request.at("expected").at("size") != file.at("size") || + request.at("expected").at("modified") != file.at("modified"))) + throw std::system_error(ERROR_FILE_INVALID, std::system_category()); + guard(); + checked(host, open); + sendJson(send, legacy ? Json{{"size", file.at("size")}} : file); + for (;;) + { + guard(); + const auto chunk = checked(host, {{"action", "read"}}); + const auto &data = chunk.at("data").get_binary(); + send(data.data(), DWORD(data.size())); + if (data.empty()) return; + } +} +void write(FilesConnection &host, const fs::path &path, const Json &request, const ClientSend &send, + const ClientReceive &receive, const std::function &guard) +{ + const auto size = request.at("size").get(); + auto upload = fileRequest("openWrite", path); + upload.update({{"size", size}, {"transfer", randomHex(32)}, {"resume", false}}); + guard(); + checked(host, upload); + sendJson(send, {{"type", "ready"}}); + uint64_t done{}; + for (;;) + { + auto data = receive(DWORD(FileChunk)); + guard(); + if (data.empty()) break; + if (data.size() > size - done) throw std::runtime_error("The upload exceeds the declared size."); + done += data.size(); + checked(host, {{"action", "write"}, {"data", Json::binary(std::move(data))}}); + } + if (done != size) throw std::runtime_error("The upload ended before the declared size."); + FILETIME now{}; + GetSystemTimeAsFileTime(&now); + Json commit{{"action", "commit"}, {"replace", false}, + {"modified", uint64_t(now.dwLowDateTime) | (uint64_t(now.dwHighDateTime) << 32)}}; + if (request.contains("expected")) + { + commit["action"] = "commitEdit"; + commit["expectedSize"] = request.at("expected").at("size"); + commit["expectedModified"] = request.at("expected").at("modified"); + } + guard(); + checked(host, commit); + sendJson(send, stat(host, path)); +} +void removeTree(FilesConnection &host, const fs::path &path, bool recursive, unsigned depth, + const std::function &guard) +{ + if (depth > 256) throw std::runtime_error("The file tree is too deep."); + guard(); + const auto item = stat(host, path); + if (recursive && directory(item) && !reparse(item)) + { + for (const auto &entry : list(host, path, guard)) + { + const auto child = wide(entry.at("name").get()); + if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry."); + removeTree(host, path / child, true, depth + 1, guard); + } + } + auto request = fileRequest(directory(item) ? "rmdir" : "remove", path); + if (!directory(item) && !reparse(item)) revision(request, item); + guard(); + checked(host, request); +} +} + +void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send, + const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve) +{ + const auto action = request.at("action").get(); + if (action == "capabilities" && !request.contains("peer")) + { + sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), 1)); + return; + } + if (action == "transfer") + { + const auto &from = request.at("source"); + const auto &to = request.at("target"); + const bool move = request.value("move", false); + const auto guard = [&] { check(move ? Access::Move : Access::Write); }; + guard(); + const bool fromLocal = from.at("peer").is_null(), toLocal = to.at("peer").is_null(); + if (fromLocal && toLocal) throw std::runtime_error("At least one path must be on a paired computer."); + const auto first = fromLocal ? ClientFilesPeer{} : resolve(from.at("peer")); + const auto second = toLocal ? ClientFilesPeer{} : resolve(to.at("peer")); + const auto copy = [&] { + const auto open = [](const ClientFilesPeer &peer) { + if (peer.peer.id.empty()) return std::make_unique(); + auto host = std::make_unique(peer.peer, peer.localId, peer.key); + requireCurrentHost(*host); + return host; + }; + const auto source = open(first), target = open(second); + ClientTransfer(*source, *target, first.peer.id == second.peer.id, move, first.peer.id, + request.value("conflict", "fail"), guard, send, receive) + .run(itemPath(from.at("path")), itemPath(to.at("path"))); + }; + if (fromLocal || toLocal) asCaller(copy); + else copy(); + return; + } + + auto access = Access::Browse; + if (action == "mkdir" || action == "rename" || action == "writeFile") access = Access::Write; + else if (action == "recycle" || action == "delete") access = Access::Delete; + else if (action != "drives" && action != "list" && action != "download" && action != "stat" && + action != "readFile" && action != "capabilities") + throw std::runtime_error("Unsupported LAN client operation."); + const auto guard = [&] { check(access); }; + guard(); + const auto resolved = resolve(request.at("peer")); + FilesConnection host(resolved.peer, resolved.localId, resolved.key); + if (action == "capabilities") + sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), hostRevision(host))); + else if (action == "drives") sendJson(send, checked(host, {{"action", "drives"}}).at("drives")); + else if (action == "list") sendJson(send, list(host, filePath(request.at("path")), guard)); + else if (action == "download") read(host, filePath(request.at("path")), Json::object(), true, send, guard); + else if (action == "stat") sendJson(send, stat(host, filePath(request.at("path")))); + else + { + requireCurrentHost(host); + const auto path = itemPath(request.at("path")); + if (action == "readFile") read(host, path, request, false, send, guard); + else if (action == "writeFile") write(host, path, request, send, receive, guard); + else if (action == "delete") + { + removeTree(host, path, request.value("recursive", false), 0, guard); + sendJson(send, {{"error", 0}}); + } + else + { + auto operation = fileRequest(action == "rename" ? "move" : action, path); + if (action == "rename") + { + const auto name = wide(request.at("name").get()); + if (!files::validWindowsFileName(name)) throw std::runtime_error("Invalid Windows file name."); + operation.update({{"target", utf8((path.parent_path() / name).native())}, {"replace", false}}); + } + guard(); + sendJson(send, checked(host, operation)); + } + } +} +} diff --git a/src/lan_client_files.h b/src/lan_client_files.h new file mode 100644 index 0000000..6684d05 --- /dev/null +++ b/src/lan_client_files.h @@ -0,0 +1,15 @@ +#pragma once +#include "lan_clients.h" +#include "lan_files.h" + +namespace ks::lan +{ +struct ClientFilesPeer +{ + FilesPeer peer; + std::string localId, key; +}; +using ClientFilesResolve = std::function; +void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send, + const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve); +} diff --git a/src/lan_clients.h b/src/lan_clients.h index fbbdc0b..96312aa 100644 --- a/src/lan_clients.h +++ b/src/lan_clients.h @@ -9,6 +9,12 @@ namespace ks::lan { +enum class ClientFilesAccess : unsigned { Browse = 0, Write = 1, Delete = 2, Move = 3 }; +using ClientCheck = std::function; +using ClientSend = std::function; +using ClientReceive = std::function; +using ClientAsCaller = std::function &)>; + class LanClients { struct Handle @@ -106,8 +112,7 @@ class LanClients { return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array(); } - using Rule = std::function; - Rule authorize(HANDLE pipe) const + ClientCheck authorize(HANDLE pipe) const { ULONG pid{}; if (!GetNamedPipeClientProcessId(pipe, &pid)) @@ -123,17 +128,25 @@ class LanClients auto image = std::make_shared(std::wstring(filename, length)); if (CompareFileTime(&image->modified, &started) > 0) throw std::runtime_error("Restart the client after replacing its executable."); - Rule check = [this, process, image] { + ClientCheck check = [this, pipe, process, image](ClientFilesAccess access) { if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT || - WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT) + WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT || + !PeekNamedPipe(pipe, nullptr, 0, nullptr, nullptr, nullptr)) throw std::runtime_error("The local client disconnected."); std::lock_guard lock(storeMutex); for (const auto &entry : clients()) if (!_wcsicmp(wide(entry.at("path").get()).c_str(), image->path.c_str()) && - entry.at("sha256") == image->digest) return; + entry.at("sha256") == image->digest) + { + const auto mask = static_cast(access); + if (((mask & 1) && !entry.value("writeFiles", false)) || + ((mask & 2) && !entry.value("deleteFiles", false))) + throw std::runtime_error("Grant the required file permission in Trusted clients."); + return; + } throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients."); }; - check(); + check(ClientFilesAccess::Browse); return check; } struct LocalMemory @@ -141,8 +154,7 @@ class LanClients void *value{}; ~LocalMemory() { if (value) LocalFree(value); } }; - using Send = std::function; - using Route = std::function; + using Route = std::function; void serve(const Route &route, const std::wstring &instance) const { HANDLE rawToken{}; @@ -194,8 +206,32 @@ class LanClients { auto check = authorize(pipe.value); route(Json::parse(request), check, [&](const void *data, DWORD bytes) { - check(); + check(ClientFilesAccess::Browse); if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected."); + }, [&](DWORD maximum) { + check(ClientFilesAccess::Browse); + DWORD bytes{}; + if (!io(pipe.value, &bytes, sizeof(bytes), false) || bytes > maximum) + throw std::runtime_error("The local client disconnected or sent an invalid frame."); + Bytes data(bytes); + if (bytes && !io(pipe.value, data.data(), bytes, false)) + throw std::runtime_error("The local client disconnected."); + return data; + }, [&](const std::function &operation) { + if (!ImpersonateNamedPipeClient(pipe.value)) + throw std::runtime_error("The pipe must allow Windows client impersonation for local paths."); + struct Revert + { + ~Revert() { if (!RevertToSelf()) std::terminate(); } + } revert; + Handle caller; + SECURITY_IMPERSONATION_LEVEL level{}; + DWORD length{}; + if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &caller.value) || + !GetTokenInformation(caller.value, TokenImpersonationLevel, &level, sizeof(level), &length) || + level < SecurityImpersonation) + throw std::runtime_error("The pipe must allow Windows client impersonation for local paths."); + operation(); }); } } @@ -235,7 +271,8 @@ public: return !_wcsicmp(wide(entry.at("path").template get()).c_str(), image.path.c_str()); }); if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full."); - entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}}); + entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}, + {"writeFiles", request.value("writeFiles", false)}, {"deleteFiles", request.value("deleteFiles", false)}}); } else { diff --git a/src/lan_files.cpp b/src/lan_files.cpp index b9523d8..d16875a 100644 --- a/src/lan_files.cpp +++ b/src/lan_files.cpp @@ -679,6 +679,7 @@ public: } return reply; } + if(action=="fileCapabilities") return {{"error",0},{"revision",1}}; if(action=="listNext") return listNext(); if(action=="read") { @@ -824,8 +825,11 @@ public: { // Both streams execute inside the serving process. FilesConnection source,target; + const auto edit=request.contains("expectedSize"); + const FileRevision expected{request.value("expectedSize",uint64_t{}), + request.value("expectedModified",uint64_t{})}; streamFile(source,target,"same host",name,destination,request.at("size"),request.at("modified"), - request.at("replace"),request.at("append"),progress); + request.at("replace"),request.at("append"),progress,edit?&expected:nullptr,request.value("resume",true)); return ok(); } return copy(name,destination,request.at("replace"),request.at("append"),progress); @@ -856,7 +860,8 @@ public: expectedSize=request.at("size").get(); const bool append=request.value("append",false); appendBase=0; - auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial"); + const bool resume=request.value("resume",true); + const auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial"); FileHandle original; if(append) { @@ -866,7 +871,7 @@ public: if(!GetFileInformationByHandle(original.value,&info)) return failure(); appendBase=fileSize(info.nFileSizeHigh,info.nFileSizeLow); } - output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS, + output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,resume?OPEN_ALWAYS:CREATE_NEW, FILE_ATTRIBUTE_HIDDEN|FILE_FLAG_OPEN_REPARSE_POINT,nullptr); if(output.value==INVALID_HANDLE_VALUE) return failure(); const bool created=GetLastError()!=ERROR_ALREADY_EXISTS; @@ -875,7 +880,7 @@ public: if(info.nNumberOfLinks!=1 || (info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))) return failure(ERROR_ACCESS_DENIED); temporary=staging; - resumable=true; + resumable=resume; if(created && appendBase) { Bytes buffer(FileChunk); @@ -971,7 +976,7 @@ Json FilesConnection::call(const Json &request,const FileProgress &progress) void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId, const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified, - bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination) + bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination,bool resumable) { auto openSource=fileRequest("openRead",from); openSource["size"]=size; @@ -982,7 +987,8 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin upload["size"]=size; const auto identity=Json::array({sourceId,ks::utf8(from.native()),ks::utf8(to.native()), size,modified,append}); - upload["transfer"]=ks::lan::mac("KSwitcher partial v1",identity.dump()); + upload["transfer"]=resumable?ks::lan::mac("KSwitcher partial v1",identity.dump()):randomHex(32); + upload["resume"]=resumable; uint64_t done=0; const auto resumeProgress=[&](uint64_t,uint64_t){return !progress || progress(done,size);}; try diff --git a/src/lan_files.h b/src/lan_files.h index 74f163d..ea96f40 100644 --- a/src/lan_files.h +++ b/src/lan_files.h @@ -31,7 +31,8 @@ public: void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId, const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified, - bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr); + bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr, + bool resumable=true); DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command, const std::function &output,std::stop_token stop={}); diff --git a/src/ui_lan.inl b/src/ui_lan.inl index d1cba87..410284e 100644 --- a/src/ui_lan.inl +++ b/src/ui_lan.inl @@ -54,6 +54,16 @@ struct LanClientsView LanView *lan{}; nlohmann::json entries, saved; }; +void selectLanClient(HWND window, const LanClientsView &view, LRESULT index) +{ + const bool selected = index >= 0 && size_t(index) < view.entries.size(); + EnableWindow(GetDlgItem(window, 734), selected); + EnableWindow(GetDlgItem(window, 736), selected); + EnableWindow(GetDlgItem(window, 737), selected); + for (const auto &[id, key] : {std::pair{736, "writeFiles"}, std::pair{737, "deleteFiles"}}) + SendDlgItemMessageW(window, id, BM_SETCHECK, + selected && view.entries[size_t(index)].value(key, false) ? BST_CHECKED : BST_UNCHECKED, 0); +} void refreshLanClients(HWND window, LanClientsView &view) { view.entries = view.saved; @@ -75,7 +85,7 @@ void refreshLanClients(HWND window, LanClientsView &view) if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0)) SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0); } - EnableWindow(GetDlgItem(window, 734), FALSE); + selectLanClient(window, view, LB_ERR); } LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) { @@ -100,7 +110,7 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0); if (id == 732 && HIWORD(wp) == LBN_SELCHANGE) { - EnableWindow(GetDlgItem(window, 734), index != LB_ERR); + selectLanClient(window, *view, index); return 0; } try @@ -116,7 +126,9 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) const auto canonical = entry.at("path").get(); const auto key = utf8(lower(wide(canonical))); auto &changes = view->lan->draft["clients"]; - if (std::find(view->saved.begin(), view->saved.end(), entry) == view->saved.end()) + if (std::none_of(view->saved.begin(), view->saved.end(), [&](const auto &saved) { + return saved.at("path") == entry.at("path") && saved.at("sha256") == entry.at("sha256"); + })) changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}}; else if (changes.is_object()) changes.erase(key); if (changes.empty()) view->lan->draft.erase("clients"); @@ -125,6 +137,27 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) } return 0; } + if ((id == 736 || id == 737) && index >= 0 && size_t(index) < view->entries.size()) + { + auto entry = view->entries[size_t(index)]; + const auto *permission = id == 736 ? "writeFiles" : "deleteFiles"; + const auto checked = SendDlgItemMessageW(window, id, BM_GETCHECK, 0, 0) == BST_CHECKED; + if (checked && MessageBoxW(window, id == 736 ? + L"Allow this executable to create, rename, copy and overwrite files on paired computers?" : + L"Allow this executable to recycle and permanently delete files on paired computers?", + L"Change trusted client permissions", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES) + { + selectLanClient(window, *view, index); + return 0; + } + entry["action"] = "trustClient"; + entry[permission] = checked; + const auto key = utf8(lower(wide(entry.at("path").get()))); + view->lan->draft["clients"][key] = entry; + view->entries[size_t(index)] = std::move(entry); + refreshLanFooter(*view->lan); + return 0; + } if (id == 734 && index >= 0 && size_t(index) < view->entries.size()) { const auto path = view->entries[size_t(index)].at("path").get(); @@ -149,17 +182,19 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) } void showLanClients(HWND parent, LanView &lan) { - auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false); + auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 318, 0, false); SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast(parent)); auto view = new LanClientsView{&lan}; SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(view)); label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578); control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152); - label(window, L"After updating an executable, add it again and click Apply or Save in Settings.", 16, 202, 578); - button(window, L"&Add client…", 733, 16, 236, 126); - button(window, L"&Remove", 734, 150, 236, 110); - button(window, L"&Close", IDCANCEL, 494, 236, 100); + control(window, L"BUTTON", L"Allow &write", WS_TABSTOP | BS_AUTOCHECKBOX, 736, 16, 200, 150, 26); + control(window, L"BUTTON", L"Allow &delete", WS_TABSTOP | BS_AUTOCHECKBOX, 737, 182, 200, 150, 26); + label(window, L"Move requires both permissions. Click Apply or Save in Settings.", 16, 232, 578); + button(window, L"&Add client…", 733, 16, 271, 126); + button(window, L"&Remove", 734, 150, 271, 110); + button(window, L"&Close", IDCANCEL, 494, 271, 100); try { view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}}); diff --git a/tests/lan_clients.cpp b/tests/lan_clients.cpp index f9b48c5..429735f 100644 --- a/tests/lan_clients.cpp +++ b/tests/lan_clients.cpp @@ -1,90 +1,335 @@ -#include "lan_clients.h" +#include +#include "lan_client_files.h" +#include "lan_network.h" +#include +#include #include namespace { -using ks::lan::Json; +using namespace ks; +using namespace ks::lan; +namespace fs = std::filesystem; + void require(bool value, const char *message) { if (!value) throw std::runtime_error(message); } - -Json request(const std::wstring &name) +class Pipe { - require(WaitNamedPipeW(name.c_str(), 3000) != FALSE, "LAN client pipe did not start"); - struct Pipe + HANDLE handle = INVALID_HANDLE_VALUE; + void io(void *buffer, DWORD length, bool write) { - HANDLE value; - ~Pipe() { if (value != INVALID_HANDLE_VALUE) CloseHandle(value); } - } pipe{CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, - SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr)}; - require(pipe.value != INVALID_HANDLE_VALUE, "could not open LAN client pipe"); - auto transfer = [&](void *buffer, DWORD length, bool write) { auto *cursor = static_cast(buffer); while (length) { DWORD count{}; - require((write ? WriteFile(pipe.value, cursor, length, &count, nullptr) : - ReadFile(pipe.value, cursor, length, &count, nullptr)) && count, "pipe transfer failed"); + require((write ? WriteFile(handle, cursor, length, &count, nullptr) : + ReadFile(handle, cursor, length, &count, nullptr)) && count, "pipe transfer failed"); cursor += count; length -= count; } + } + +public: + Pipe(const std::wstring &name, const Json &request, bool impersonate = false) + { + const auto end = GetTickCount64() + 3000; + do + { + handle = CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + SECURITY_SQOS_PRESENT | (impersonate ? SECURITY_IMPERSONATION : SECURITY_IDENTIFICATION), nullptr); + if (handle != INVALID_HANDLE_VALUE) break; + Sleep(10); + } while (GetTickCount64() < end); + require(handle != INVALID_HANDLE_VALUE, "could not open LAN client pipe"); + sendJson(request); + } + ~Pipe() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); } + void send(std::string data) + { + DWORD length = DWORD(data.size()); + io(&length, sizeof(length), true); + if (length) io(data.data(), length, true); + } + void sendJson(const Json &data) { send(data.dump()); } + std::string read() + { + DWORD length{}; + io(&length, sizeof(length), false); + require(length <= 8 * 1024 * 1024, "unexpected reply size"); + std::string payload(length, '\0'); + if (length) io(payload.data(), length, false); + return payload; + } + Json reply() { return Json::parse(read()); } + void ack() + { + char ack{}; + io(&ack, 1, true); + } +}; +Json request(const std::wstring &name, const Json &body, bool impersonate = false) +{ + Pipe pipe(name, body, impersonate); + auto reply = pipe.reply(); + pipe.ack(); + return reply; +} +void save(const fs::path &path, const std::string &content) +{ + std::ofstream file(path, std::ios::binary | std::ios::trunc); + file << content; + require(bool(file), "could not write test file"); +} +std::string read(const fs::path &path) +{ + std::ifstream file(path, std::ios::binary); + require(bool(file), "could not read test file"); + return {std::istreambuf_iterator(file), {}}; +} +Json endpoint(const Json &peer, const fs::path &path) +{ + return {{"peer", peer}, {"path", utf8(path.native())}}; +} +Json operation(const char *action, const Json &peer, const fs::path &path) +{ + auto result = endpoint(peer, path); + result["action"] = action; + return result; +} +Json transfer(const Json &from, const Json &to, bool move, const char *conflict = "fail") +{ + return {{"action", "transfer"}, {"source", from}, {"target", to}, {"move", move}, {"conflict", conflict}}; +} +Json runTransfer(const std::wstring &name, const Json &job, + const std::function &progress = {}, bool impersonate = false) +{ + Pipe pipe(name, job, impersonate); + for (;;) + { + auto result = pipe.reply(); + if (result.value("type", "") != "progress") + { + pipe.ack(); + return result; + } + pipe.sendJson({{"continue", !progress || progress(result)}}); + } +} +void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &pipe, + const fs::path &root, const fs::path &secondVolume) +{ + const auto caller = randomHex(16), a = randomHex(16), b = randomHex(16), key = randomHex(32); + std::atomic available{true}; + const auto pair = [&](const std::string &id) { return id == caller && available.load() ? key : std::string{}; }; + Network network; + FilesListener first(a, pair, 0), second(b, pair, 0); + require(first.port() && second.port(), "could not start paired file listeners"); + std::jthread listeners([&](std::stop_token stop) { + while (!stop.stop_requested()) { first.poll(); second.poll(); Sleep(1); } + }); + const auto running = [&](const std::string &peer) -> ClientFilesPeer { + require(peer == a || peer == b, "an unknown peer was routed"); + return {{peer, "127.0.0.1", L"Fixture", peer == a ? first.port() : second.port(), true}, caller, key}; }; - auto payload = Json{{"action", "peers"}}.dump(); - DWORD length = DWORD(payload.size()); - transfer(&length, sizeof(length), true); - transfer(payload.data(), length, true); - transfer(&length, sizeof(length), false); - require(length > 0 && length < 4096, "unexpected reply size"); - payload.resize(length); - transfer(payload.data(), length, false); - char ack{}; - transfer(&ack, 1, true); - return Json::parse(payload); + clients.start([&](const Json &body, const ClientCheck &check, const ClientSend &send, + const ClientReceive &receive, const ClientAsCaller &asCaller) { + if (body.at("action") == "peers") + { + constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])"; + send(reply.data(), DWORD(reply.size())); + } + else routeClientFiles(body, check, send, receive, asCaller, running); + }, pipe.substr(pipe.find(L".test."))); + struct Stop { LanClients &clients; ~Stop() { clients.stop(); } } stop{clients}; + const auto path = utf8(executable()); + const auto canonical = trusted.at("path"); + const Json peers{{"action", "peers"}}; + require(request(pipe, peers).contains("error"), "an untrusted executable was accepted"); + const auto grant = [&](bool write, bool erase) { + clients.settings("trustClient", {{"path", path}, {"writeFiles", write}, {"deleteFiles", erase}}); + }; + grant(false, false); + require(request(pipe, peers).at(0).at("name") == "Paired PC", "the trusted executable was rejected"); + const auto setCapabilities = [&](bool write, bool erase) { + const auto caps = request(pipe, {{"action", "capabilities"}, {"peer", a}}); + require(caps.value("protocol", 0) == 2 && caps.value("hostRevision", 0) == 1 && + caps.at("write") == write && caps.at("delete") == erase && caps.at("move") == (write && erase), + "wrong advertised capabilities"); + }; + setCapabilities(false, false); + const auto src = root / L"source", dst = root / L"target", file = src / L"content.txt"; + const std::string content(FileChunk * 4 + 19, 'x'); + fs::create_directory(src); + save(file, content); + const auto mkdir = operation("mkdir", b, dst); + require(request(pipe, mkdir).contains("error") && !fs::exists(dst), "browse grant allowed creation"); + const auto legacy = request(pipe, operation("list", a, src)); + require(legacy.at(0).at("name") == "content.txt", "legacy list schema changed"); + { + Pipe download(pipe, operation("download", a, file)); + const auto header = download.reply(); + require(header.size() == 1 && header.at("size") == content.size(), "legacy download schema changed"); + std::string downloaded; + for (auto chunk = download.read(); !chunk.empty(); chunk = download.read()) downloaded += chunk; + download.ack(); + require(downloaded == content, "legacy download content changed"); + } + const auto info = request(pipe, operation("stat", a, file)); + auto readVersion = operation("readFile", a, file); + readVersion["expected"] = {{"size", info.at("size")}, {"modified", info.at("modified")}}; + { + Pipe reader(pipe, readVersion); + require(reader.reply().at("modified") == info.at("modified"), "revision read omitted metadata"); + std::string downloaded; + for (auto chunk = reader.read(); !chunk.empty(); chunk = reader.read()) downloaded += chunk; + reader.ack(); + require(downloaded == content, "revision read had incorrect content"); + } + readVersion["expected"]["size"] = 0; + require(request(pipe, readVersion).at("error").is_string(), "stale revision read was accepted"); + grant(true, false); + setCapabilities(true, false); + require(request(pipe, mkdir).at("error") == 0, "mkdir failed"); + require(request(pipe, operation("delete", a, file)).contains("error") && fs::exists(file), + "write grant allowed deletion"); + auto up = operation("writeFile", b, dst / L"upload.txt"); + up["size"] = 3; + const auto upload = [&](const std::string &value) { + Pipe writer(pipe, up); + require(writer.reply().value("type", "") == "ready", "upload did not open"); + writer.send(value); + writer.send(""); + const auto result = writer.reply(); + writer.ack(); + return result; + }; + const auto original = upload("one"); + require(original.at("error") == 0 && read(dst / L"upload.txt") == "one", "exclusive create failed"); + const auto collision = upload("two"); + require(collision.at("error").is_string() && read(dst / L"upload.txt") == "one", + "exclusive create overwrote existing file"); + up["expected"] = {{"size", original.at("size")}, {"modified", original.at("modified")}}; + require(upload("two").at("error") == 0 && read(dst / L"upload.txt") == "two", "revision save failed"); + require(upload("bad").at("error").is_string() && read(dst / L"upload.txt") == "two", "stale save lost data"); + auto rename = operation("rename", b, dst / L"upload.txt"); + rename["name"] = "renamed.txt"; + require(request(pipe, rename).at("error") == 0 && read(dst / L"renamed.txt") == "two", "rename failed"); + + const auto to = dst / L"copy"; + const auto cross = transfer(endpoint(a, src), endpoint(b, to), false); + require(runTransfer(pipe, cross).at("type") == "complete" && read(to / L"content.txt") == content, + "cross-peer tree copy failed"); + require(runTransfer(pipe, cross).contains("error"), "the fail conflict policy overwrote a directory"); + require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "skip")).at("skipped") == 1, + "skip conflict policy failed"); + save(to / L"content.txt", "replace me"); + require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" && + read(to / L"content.txt") == content, "replace conflict policy failed"); + + const auto localCopy = root / L"local.txt"; + const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false); + require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files"); + const auto localUpload = runTransfer(pipe, fromLocal, {}, true); + require(localUpload.value("type", "") == "complete" && read(dst / L"from-local.txt") == content, + localUpload.value("error", "local upload failed under the caller token").c_str()); + require(runTransfer(pipe, transfer(endpoint(b, dst / L"from-local.txt"), endpoint(nullptr, localCopy), false), + {}, true).at("type") == "complete" && read(localCopy) == content, "local download failed under the caller token"); + + const auto remoteSide = secondVolume.empty() ? dst : secondVolume; + const auto sameCopy = remoteSide / L"same-host.txt"; + unsigned progressFrames{}; + require(runTransfer(pipe, transfer(endpoint(a, file), endpoint(a, sameCopy), false), + [&](const Json &) { ++progressFrames; return true; }).at("type") == "complete" && + progressFrames > 1 && read(sameCopy) == content, "same-host transfer failed"); + const auto cancelled = dst / L"cancelled.txt"; + const auto cancellation = transfer(endpoint(a, file), endpoint(a, cancelled), false); + require(runTransfer(pipe, cancellation, [](const Json &progress) { return progress.at("total") == 0; }) + .contains("error") && !fs::exists(cancelled) && read(file) == content, "same-host cancellation lost data"); + { + Pipe disconnect(pipe, cancellation); + while (disconnect.reply().at("total") == 0) disconnect.sendJson({{"continue", true}}); + } + require(request(pipe, peers).is_array() && !fs::exists(cancelled) && read(file) == content, + "pipe disconnect published an incomplete transfer"); + require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, src / L"inside"), false)).contains("error") && + !fs::exists(src / L"inside"), "same-host transfer recursed into its source"); + + grant(true, true); + setCapabilities(true, true); + const auto moved = dst / L"moved.txt"; + const auto move = transfer(endpoint(a, file), endpoint(b, moved), true); + require(runTransfer(pipe, move, [&](const Json &progress) { + if (progress.at("phase") == "remove") grant(true, false); + return true; + }).contains("error") && fs::exists(file) && read(moved) == content, + "revoked delete grant still removed the source or failed to publish the full destination"); + fs::remove(moved); + grant(true, true); + require(runTransfer(pipe, move, [&](const Json &progress) { + if (progress.at("total") != 0) available = false; + return true; + }).contains("error") && fs::exists(file) && !fs::exists(moved), "connection loss published a partial move"); + available = true; + + const auto sameMove = remoteSide / L"same-move"; + require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, sameMove), true)).at("type") == "complete" && + read(sameMove / L"content.txt") == content && !fs::exists(src), "same-host tree move failed"); + const auto crossMove = dst / L"cross-move"; + require(runTransfer(pipe, transfer(endpoint(a, sameMove), endpoint(b, crossMove), true)).at("type") == "complete" && + read(crossMove / L"content.txt") == content && !fs::exists(sameMove), "cross-peer tree move failed"); + + auto erase = operation("delete", b, crossMove); + erase["recursive"] = true; + require(request(pipe, erase).at("error") == 0 && !fs::exists(crossMove), "recursive delete failed"); + for (const auto &entry : fs::recursive_directory_iterator(root)) + require(entry.path().extension() != L".partial", "an interrupted client operation left a partial upload"); + + auto changed = clients.settings("trustedClients", {}); + changed.at(0)["sha256"] = std::string(64, '0'); + const auto differentHash = changed.dump(); + atomicWrite(root / L"lan-clients.bin", protect(Bytes(differentHash.begin(), differentHash.end()))); + require(request(pipe, peers).contains("error"), "an executable with a different fingerprint was accepted"); + grant(true, true); + clients.settings("removeClient", {{"path", canonical}}); + require(request(pipe, peers).contains("error"), "revocation must reject the next request"); } } int main() { const auto suffix = L".test." + std::to_wstring(GetCurrentProcessId()); - const auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-LAN" + suffix); + const auto root = fs::temp_directory_path() / (L"KSwitcher-LAN" + suffix); + fs::path secondVolume; try { - require(std::filesystem::create_directory(root), "could not create test directory"); + require(fs::create_directory(root), "could not create test directory"); + wchar_t other[512]{}; + const auto length = GetEnvironmentVariableW(L"KSWITCHER_TEST_LAN_OTHER_VOLUME", other, DWORD(std::size(other))); + if (length && length < std::size(other)) + { + secondVolume = fs::path(other) / root.filename(); + require(fs::create_directory(secondVolume), "could not create other-volume fixture"); + } DWORD session{}; require(ProcessIdToSessionId(GetCurrentProcessId(), &session) != FALSE, "no Windows session"); const auto pipe = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + suffix; { - ks::lan::LanClients clients(root); - clients.start([](const Json &request, const auto &, const auto &send) { - require(request.at("action") == "peers", "unexpected request"); - constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])"; - send(reply.data(), DWORD(reply.size())); - }, suffix); - // WaitNamedPipe returns immediately if the instance has not been created yet. - for (int n = 0; n < 100 && !WaitNamedPipeW(pipe.c_str(), 20); ++n) Sleep(20); - require(request(pipe).contains("error"), "an untrusted executable was accepted"); - const auto path = ks::utf8(ks::executable()); - const auto trusted = clients.settings("trustClient", {{"path", path}}); - require(trusted.size() == 1, "the program must be enrolled exactly once"); - require(request(pipe).at(0).at("name") == "Paired PC", "the trusted program was rejected"); - auto changed = trusted; - changed.at(0)["sha256"] = std::string(64, '0'); - const auto store = root / L"lan-clients.bin"; - const auto differentHash = changed.dump(); - ks::atomicWrite(store, ks::protect(ks::Bytes(differentHash.begin(), differentHash.end()))); - require(request(pipe).contains("error"), "an executable with a different fingerprint was accepted"); - clients.settings("trustClient", {{"path", path}}); - clients.settings("removeClient", {{"path", trusted.at(0).at("path")}}); - require(request(pipe).contains("error"), "revocation must reject the next request"); + LanClients clients(root); + const auto trusted = clients.settings("inspectClient", {{"path", utf8(executable())}}); + verifyFiles(clients, trusted, pipe, root, secondVolume); + clients.stop(); } - std::filesystem::remove(root / L"lan-clients.bin"); - std::filesystem::remove(root); - std::cout << "Verified executable approval, resident pipe access and revocation.\n"; + if (!secondVolume.empty()) fs::remove_all(secondVolume); + fs::remove_all(root); + std::cout << "Verified approval, permissions, legacy discovery/download, revisions and transfers between paired hosts.\n"; return 0; } catch (const std::exception &error) { + if (!secondVolume.empty()) { std::error_code ignored; fs::remove_all(secondVolume, ignored); } + { std::error_code ignored; fs::remove_all(root, ignored); } std::cerr << error.what() << '\n'; return 1; }