337 lines
16 KiB
C++
337 lines
16 KiB
C++
#include <winsock2.h>
|
|
#include "lan_client_files.h"
|
|
#include "lan_network.h"
|
|
#include <atomic>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
|
|
namespace
|
|
{
|
|
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);
|
|
}
|
|
class Pipe
|
|
{
|
|
HANDLE handle = INVALID_HANDLE_VALUE;
|
|
void io(void *buffer, DWORD length, bool write)
|
|
{
|
|
auto *cursor = static_cast<char *>(buffer);
|
|
while (length)
|
|
{
|
|
DWORD count{};
|
|
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<char>(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<bool(const Json &)> &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<bool> 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};
|
|
};
|
|
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 = fs::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
|
|
fs::path secondVolume;
|
|
try
|
|
{
|
|
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;
|
|
{
|
|
LanClients clients(root);
|
|
const auto trusted = clients.settings("inspectClient", {{"path", utf8(executable())}});
|
|
verifyFiles(clients, trusted, pipe, root, secondVolume);
|
|
clients.stop();
|
|
}
|
|
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;
|
|
}
|
|
}
|