#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)); } } } }