diff --git a/include/hyprwire/core/ServerSocket.hpp b/include/hyprwire/core/ServerSocket.hpp index c5dbd36..5d7ee17 100644 --- a/include/hyprwire/core/ServerSocket.hpp +++ b/include/hyprwire/core/ServerSocket.hpp @@ -1,6 +1,8 @@ #pragma once #include +#include +#include namespace Hyprwire { class IProtocolServerImplementation; @@ -12,6 +14,13 @@ namespace Hyprwire { virtual int getPID() = 0; + /* + Set a protocol filter. If the function returns false, + the protocol will not be exposed in the handshake, and will not + be bindable. + */ + virtual void setProtocolFilter(std::function&& fn) = 0; + protected: IServerClient() = default; }; @@ -57,6 +66,12 @@ namespace Hyprwire { */ virtual bool removeClient(int fd) = 0; + /* + Add a listener to each new client. This is emitted before we even + start a handshake, and is mostly exposed for setting up filters. + */ + virtual void setNewClientHandler(std::function)>&& fn) = 0; + protected: IServerSocket() = default; }; diff --git a/src/core/message/MessageParser.cpp b/src/core/message/MessageParser.cpp index cf2f9d5..054af75 100644 --- a/src/core/message/MessageParser.cpp +++ b/src/core/message/MessageParser.cpp @@ -93,6 +93,11 @@ size_t CMessageParser::parseSingleMessage(SSocketRawParsedMessage& raw, size_t o std::vector protocolNames; protocolNames.reserve(client->m_server->m_impls.size()); for (const auto& impl : client->m_server->m_impls) { + + // skip filtered out protocols + if (!std::ranges::contains(client->m_exposedProtocols, impl->protocol()->specName())) + continue; + protocolNames.emplace_back(std::format("{}@{}", impl->protocol()->specName(), impl->protocol()->specVer())); } client->sendMessage(CHandshakeProtocolsMessage(protocolNames)); diff --git a/src/core/server/ServerClient.cpp b/src/core/server/ServerClient.cpp index 5785a1e..219a51c 100644 --- a/src/core/server/ServerClient.cpp +++ b/src/core/server/ServerClient.cpp @@ -11,10 +11,13 @@ #include #include +#include #include #include +#include + #if defined(__FreeBSD__) #include #include @@ -38,6 +41,18 @@ void CServerClient::dispatchFirstPoll() { if (m_firstPollDone) return; + auto x = Hyprutils::Utils::CScopeGuard([this] { + if (!m_server) { + TRACE(Debug::log(TRACE, "[{}] dispatchFirstPoll: no server?", m_fd.get())); + return; + } + + if (m_server->m_newClientHandler) + m_server->m_newClientHandler(m_self.lock()); + + setupExposedProtocols(); + }); + m_firstPollDone = true; // get peer's pid @@ -124,6 +139,13 @@ SP CServerClient::createObject(const std::string& protocol, const if (p->protocol()->specName() != protocol) continue; + if (!std::ranges::contains(m_exposedProtocols, protocol)) { + Debug::log(ERR, "[{} @ {:.3f}] Error: createObject on a non-exposed protocol", m_fd.get(), steadyMillis()); + sendMessage(CFatalErrorMessage(obj->m_id, static_cast(-1), "Invalid protocol")); + m_error = true; + return nullptr; + } + for (const auto& s : p->protocol()->objects()) { if (s->objectName() != object && !object.empty()) continue; @@ -136,6 +158,7 @@ SP CServerClient::createObject(const std::string& protocol, const if (!obj->m_spec) { Debug::log(ERR, "[{} @ {:.3f}] Error: createObject has no spec", m_fd.get(), steadyMillis()); + sendMessage(CFatalErrorMessage(obj->m_id, static_cast(-1), "Invalid protocol")); m_error = true; return nullptr; } @@ -143,6 +166,7 @@ SP CServerClient::createObject(const std::string& protocol, const if (p->protocol()->specVer() < version) { Debug::log(ERR, "[{} @ {:.3f}] Error: createObject for protocol {} object {} for version {}, but we have only {}", m_fd.get(), steadyMillis(), obj->m_protocolName, object, version, p->protocol()->specVer()); + sendMessage(CFatalErrorMessage(obj->m_id, static_cast(-1), std::format("Invalid protocol version ({} > {})", version, p->protocol()->specVer()))); m_error = true; return nullptr; } @@ -152,6 +176,7 @@ SP CServerClient::createObject(const std::string& protocol, const if (!obj->m_spec) { Debug::log(ERR, "[{} @ {:.3f}] Error: createObject has no spec", m_fd.get(), steadyMillis()); + sendMessage(CFatalErrorMessage(obj->m_id, static_cast(-1), "Invalid protocol")); m_error = true; return nullptr; } @@ -210,3 +235,27 @@ void CServerClient::onGeneric(const CGenericProtocolMessage& msg) { int CServerClient::getPID() { return m_pid; } + +void CServerClient::setProtocolFilter(std::function&& fn) { + m_protocolFilter = std::move(fn); +} + +void CServerClient::setupExposedProtocols() { + for (const auto& i : m_server->m_impls) { + const auto NAME = i->protocol()->specName(); + + if (!m_protocolFilter) { + Debug::log(TRACE, "[{} @ {:.3f}] Exposing {} (no filter set up)", m_fd.get(), steadyMillis(), NAME); + m_exposedProtocols.emplace_back(NAME); + continue; + } + + if (!m_protocolFilter(NAME)) { + Debug::log(TRACE, "[{} @ {:.3f}] Not exposing {} (filter failed)", m_fd.get(), steadyMillis(), NAME); + continue; + } + + Debug::log(TRACE, "[{} @ {:.3f}] Exposing {} (filter passed)", m_fd.get(), steadyMillis(), NAME); + m_exposedProtocols.emplace_back(NAME); + } +} diff --git a/src/core/server/ServerClient.hpp b/src/core/server/ServerClient.hpp index 2c84da5..322df7f 100644 --- a/src/core/server/ServerClient.hpp +++ b/src/core/server/ServerClient.hpp @@ -17,28 +17,33 @@ namespace Hyprwire { CServerClient(int fd); virtual ~CServerClient(); - virtual int getPID(); + virtual int getPID() override; + virtual void setProtocolFilter(std::function&& fn) override; - void sendMessage(const IMessage& message); - SP createObject(const std::string& protocol, const std::string& object, uint32_t version, uint32_t seq); - void destroyObject(uint32_t id); - void onBind(SP obj); - void onGeneric(const CGenericProtocolMessage& msg); - void dispatchFirstPoll(); + void sendMessage(const IMessage& message); + SP createObject(const std::string& protocol, const std::string& object, uint32_t version, uint32_t seq); + void destroyObject(uint32_t id); + void onBind(SP obj); + void onGeneric(const CGenericProtocolMessage& msg); + void dispatchFirstPoll(); + void setupExposedProtocols(); - Hyprutils::OS::CFileDescriptor m_fd; + Hyprutils::OS::CFileDescriptor m_fd; - int m_pid = -1; - bool m_firstPollDone = false; + int m_pid = -1; + bool m_firstPollDone = false; - uint32_t m_version = 0, m_maxId = 1; - bool m_error = false; + uint32_t m_version = 0, m_maxId = 1; + bool m_error = false; - uint32_t m_scheduledRoundtripSeq = 0; + uint32_t m_scheduledRoundtripSeq = 0; - std::vector> m_objects; + std::vector> m_objects; - WP m_server; - WP m_self; + WP m_server; + WP m_self; + + std::function m_protocolFilter; + std::vector m_exposedProtocols; }; }; diff --git a/src/core/server/ServerSocket.cpp b/src/core/server/ServerSocket.cpp index 1122aaf..faf0b24 100644 --- a/src/core/server/ServerSocket.cpp +++ b/src/core/server/ServerSocket.cpp @@ -206,7 +206,7 @@ void CServerSocket::clearWakeupFd() { clearFd(m_wakeupFd); } -SP CServerSocket::addClient(int fd) { +SP CServerSocket::createClient(int fd) { auto x = makeShared(fd); if (x->m_fd.isClosed() || !x->m_fd.isValid()) return nullptr; @@ -215,6 +215,12 @@ SP CServerSocket::addClient(int fd) { x->m_server = m_self; m_clients.emplace_back(x); + return x; +} + +SP CServerSocket::addClient(int fd) { + auto x = createClient(fd); + recheckPollFds(); // wake up any poller @@ -275,9 +281,13 @@ bool CServerSocket::dispatchNewConnections() { sockaddr_in clientAddress = {}; socklen_t clientSize = sizeof(clientAddress); - auto x = m_clients.emplace_back(makeShared(accept(m_fd.get(), (sockaddr*)&clientAddress, &clientSize))); - x->m_server = m_self; - x->m_self = x; + int fd = accept(m_fd.get(), (sockaddr*)&clientAddress, &clientSize); + auto x = createClient(fd); + + if (!x) { + Debug::log(ERR, "[{} @ {:.3f}] Failed to create a new client", fd, steadyMillis()); + return false; + } recheckPollFds(); @@ -437,3 +447,7 @@ SP CServerSocket::createObject(SP clientIface, SP)>&& fn) { + m_newClientHandler = std::move(fn); +} diff --git a/src/core/server/ServerSocket.hpp b/src/core/server/ServerSocket.hpp index 79ac4bb..acec196 100644 --- a/src/core/server/ServerSocket.hpp +++ b/src/core/server/ServerSocket.hpp @@ -21,12 +21,13 @@ namespace Hyprwire { bool attempt(const std::string& path); bool attemptEmpty(); - virtual void addImplementation(SP&&); - virtual bool dispatchEvents(bool block); - virtual int extractLoopFD(); - virtual SP createObject(SP client, SP reference, const std::string& object, uint32_t seq); - virtual SP addClient(int fd); - virtual bool removeClient(int fd); + virtual void addImplementation(SP&&) override; + virtual bool dispatchEvents(bool block) override; + virtual int extractLoopFD() override; + virtual SP createObject(SP client, SP reference, const std::string& object, uint32_t seq) override; + virtual SP addClient(int fd) override; + virtual bool removeClient(int fd) override; + virtual void setNewClientHandler(std::function)>&& fn) override; void recheckPollFds(); bool dispatchNewConnections(); @@ -59,5 +60,10 @@ namespace Hyprwire { bool m_isEmptyListener = false; std::string m_path; + + std::function)> m_newClientHandler; + + private: + SP createClient(int fd); }; }; diff --git a/tests/unit/IntegrationProtocolFilter.cpp b/tests/unit/IntegrationProtocolFilter.cpp new file mode 100644 index 0000000..aab83dd --- /dev/null +++ b/tests/unit/IntegrationProtocolFilter.cpp @@ -0,0 +1,295 @@ +#include + +#include + +#include "../../src/core/message/messages/BindProtocol.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace Hyprwire; +using namespace Hyprutils::Memory; + +template +using SP = CSharedPointer; + +static constexpr std::string_view ALLOWED_PROTOCOL = "allowed_protocol"; +static constexpr std::string_view BLOCKED_PROTOCOL = "blocked_protocol"; + +class CFilterObjectSpec final : public IProtocolObjectSpec { + public: + std::string objectName() override { + return "manager"; + } + + const std::vector& c2s() override { + static const std::vector methods = {}; + return methods; + } + + const std::vector& s2c() override { + static const std::vector methods = {}; + return methods; + } +}; + +class CFilterProtocolSpec final : public IProtocolSpec { + public: + explicit CFilterProtocolSpec(std::string name) : m_name(std::move(name)) { + ; + } + + std::string specName() override { + return m_name; + } + + uint32_t specVer() override { + return 1; + } + + std::vector> objects() override { + return { + m_objectSpec, + }; + } + + private: + std::string m_name; + SP m_objectSpec = makeShared(); +}; + +class CFilterServerImpl final : public IProtocolServerImplementation { + public: + explicit CFilterServerImpl(SP spec) : m_spec(std::move(spec)) { + ; + } + + SP protocol() override { + return m_spec; + } + + std::vector> implementation() override { + return { + makeShared(SServerObjectImplementation{.objectName = "manager", .version = 1}), + }; + } + + private: + SP m_spec; +}; + +class CProtocolFilterHarness { + public: + using TNewClientHandler = std::function)>; + + explicit CProtocolFilterHarness(TNewClientHandler handler = {}) { + int fds[2] = {-1, -1}; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) + throw std::runtime_error("socketpair failed"); + + m_clientFd = fds[1]; + m_server = IServerSocket::open(); + if (!m_server) + throw std::runtime_error("server open failed"); + + addFilterImplementations(m_server); + + if (handler) + m_server->setNewClientHandler(std::move(handler)); + + auto serverClient = m_server->addClient(fds[0]); + if (!serverClient) + throw std::runtime_error("server addClient failed"); + + m_client = IClientSocket::open(fds[1]); + if (!m_client) + throw std::runtime_error("client open failed"); + + m_pumpThread = std::thread([this] { + while (!m_stop) { + m_server->dispatchEvents(false); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + }); + } + + ~CProtocolFilterHarness() { + m_stop = true; + if (m_pumpThread.joinable()) + m_pumpThread.join(); + } + + bool waitForHandshake() { + return m_client->waitForHandshake(); + } + + SP client() { + return m_client; + } + + bool sendRawBind(std::string_view protocol) { + const CBindProtocolMessage msg(std::string{protocol}, 100, 1); + return write(m_clientFd, msg.m_data.data(), msg.m_data.size()) == static_cast(msg.m_data.size()); + } + + bool waitForClientDisconnect() { + for (int i = 0; i < 500; ++i) { + if (!m_client->dispatchEvents(false)) + return true; + + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + return false; + } + + static void addFilterImplementations(const SP& server) { + auto allowedSpec = makeShared(std::string{ALLOWED_PROTOCOL}); + auto blockedSpec = makeShared(std::string{BLOCKED_PROTOCOL}); + + server->addImplementation(makeShared(std::move(allowedSpec))); + server->addImplementation(makeShared(std::move(blockedSpec))); + } + + private: + std::atomic m_stop = false; + std::thread m_pumpThread; + + SP m_server; + SP m_client; + + int m_clientFd = -1; +}; + +class CPathProtocolFilterHarness { + public: + explicit CPathProtocolFilterHarness(CProtocolFilterHarness::TNewClientHandler handler) { + m_path = makeSocketPath(); + m_server = IServerSocket::open(m_path); + if (!m_server) + throw std::runtime_error("server open(path) failed"); + + CProtocolFilterHarness::addFilterImplementations(m_server); + m_server->setNewClientHandler(std::move(handler)); + + m_pumpThread = std::thread([this] { + while (!m_stop) { + m_server->dispatchEvents(false); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + }); + } + + ~CPathProtocolFilterHarness() { + m_stop = true; + if (m_pumpThread.joinable()) + m_pumpThread.join(); + + m_server.reset(); + + std::error_code ec; + std::filesystem::remove(m_path, ec); + std::filesystem::remove(std::filesystem::path(m_path).parent_path(), ec); + } + + SP openClient() { + return IClientSocket::open(m_path); + } + + private: + static std::string makeSocketPath() { + const auto dir = std::filesystem::temp_directory_path() / ("hyprwire-filter-" + std::to_string(getpid())); + std::filesystem::create_directories(dir); + return (dir / "wire.sock").string(); + } + + std::string m_path; + std::atomic m_stop = false; + std::thread m_pumpThread; + SP m_server; +}; + +static bool contains(const std::vector& values, std::string_view value) { + return std::ranges::find(values, value) != values.end(); +} + +TEST(IntegrationProtocolFilter, DefaultExposesAllProtocols) { + CProtocolFilterHarness harness; + + ASSERT_TRUE(harness.waitForHandshake()); + EXPECT_NE(harness.client()->getSpec(std::string{ALLOWED_PROTOCOL}), nullptr); + EXPECT_NE(harness.client()->getSpec(std::string{BLOCKED_PROTOCOL}), nullptr); +} + +TEST(IntegrationProtocolFilter, FilterLimitsHandshakeExposureAndRunsOnce) { + std::atomic handlerCalls = 0; + std::mutex filterNamesMutex; + std::vector filterNames; + + CProtocolFilterHarness harness([&](SP client) { + handlerCalls.fetch_add(1); + client->setProtocolFilter([&](std::string_view name) { + std::scoped_lock lock(filterNamesMutex); + filterNames.emplace_back(name); + return name == ALLOWED_PROTOCOL; + }); + }); + + ASSERT_TRUE(harness.waitForHandshake()); + + EXPECT_EQ(handlerCalls.load(), 1u); + EXPECT_NE(harness.client()->getSpec(std::string{ALLOWED_PROTOCOL}), nullptr); + EXPECT_EQ(harness.client()->getSpec(std::string{BLOCKED_PROTOCOL}), nullptr); + + std::scoped_lock lock(filterNamesMutex); + EXPECT_TRUE(contains(filterNames, ALLOWED_PROTOCOL)); + EXPECT_TRUE(contains(filterNames, BLOCKED_PROTOCOL)); +} + +TEST(IntegrationProtocolFilter, AllFilteredHandshakeStillSucceeds) { + CProtocolFilterHarness harness([](SP client) { client->setProtocolFilter([](std::string_view) { return false; }); }); + + ASSERT_TRUE(harness.waitForHandshake()); + EXPECT_EQ(harness.client()->getSpec(std::string{ALLOWED_PROTOCOL}), nullptr); + EXPECT_EQ(harness.client()->getSpec(std::string{BLOCKED_PROTOCOL}), nullptr); +} + +TEST(IntegrationProtocolFilter, FilteredProtocolCannotBeBound) { + CProtocolFilterHarness harness([](SP client) { client->setProtocolFilter([](std::string_view name) { return name == ALLOWED_PROTOCOL; }); }); + + ASSERT_TRUE(harness.waitForHandshake()); + ASSERT_EQ(harness.client()->getSpec(std::string{BLOCKED_PROTOCOL}), nullptr); + + ASSERT_TRUE(harness.sendRawBind(BLOCKED_PROTOCOL)); + EXPECT_TRUE(harness.waitForClientDisconnect()); +} + +TEST(IntegrationProtocolFilter, AcceptedPathClientsUseNewClientFilter) { + std::atomic handlerCalls = 0; + + CPathProtocolFilterHarness harness([&](SP client) { + handlerCalls.fetch_add(1); + client->setProtocolFilter([](std::string_view name) { return name == ALLOWED_PROTOCOL; }); + }); + + auto client = harness.openClient(); + ASSERT_NE(client, nullptr); + + ASSERT_TRUE(client->waitForHandshake()); + EXPECT_EQ(handlerCalls.load(), 1u); + EXPECT_NE(client->getSpec(std::string{ALLOWED_PROTOCOL}), nullptr); + EXPECT_EQ(client->getSpec(std::string{BLOCKED_PROTOCOL}), nullptr); +}