Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion include/hyprwire/core/ClientSocket.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include <hyprutils/memory/SharedPtr.hpp>
#include <functional>

namespace Hyprwire {
class IProtocolClientImplementation;
Expand Down Expand Up @@ -46,6 +47,17 @@ namespace Hyprwire {
*/
virtual Hyprutils::Memory::CSharedPointer<IObject> bindProtocol(const Hyprutils::Memory::CSharedPointer<IProtocolSpec>& spec, uint32_t version) = 0;

/*
Bind without waiting for the server's binding reply. Writes may still block under backpressure.
A non-empty completion is called exactly once, with a confirmed object or nullptr on failure.
Validation failures may complete inline; pending binds complete during dispatch or socket teardown.
Success runs before subsequent events, allowing the completion to attach object listeners.
Completions may bind again or release the socket. Releasing its last reference cancels remaining
binds with nullptr, after any active dispatch finishes. Keep callback captures alive until completion.
*/
virtual void bindProtocolAsync(const Hyprutils::Memory::CSharedPointer<IProtocolSpec>& spec, uint32_t version,
std::function<void(Hyprutils::Memory::CSharedPointer<IObject>)>&& completion) = 0;

/*
Get an object from an id
*/
Expand All @@ -69,4 +81,4 @@ namespace Hyprwire {
protected:
IClientSocket() = default;
};
};
};
27 changes: 26 additions & 1 deletion include/hyprwire/core/ServerSocket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,50 @@

#include <hyprutils/memory/SharedPtr.hpp>
#include <functional>
#include <optional>
#include <string_view>
#include <sys/types.h>

namespace Hyprwire {
class IProtocolServerImplementation;
class IObject;

struct SPeerCredentials {
pid_t pid = -1;
uid_t uid = static_cast<uid_t>(-1);
gid_t gid = static_cast<gid_t>(-1);
};

class IServerClient {
public:
virtual ~IServerClient();

virtual int getPID() = 0;

/*
Socket peer credentials captured when the client is added, before the
new-client handler or handshake. Empty if they could not be obtained.
These remain a snapshot, not the current credentials of a process or
an attestation of the original sender behind a forwarded socket.
*/
virtual std::optional<SPeerCredentials> getPeerCredentials() const = 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<bool(std::string_view)>&& fn) = 0;

/*
Called once after the socket is closed and wire objects are torn down,
even if the application retains this client. Runs during dispatch,
explicit removal, or server destruction, not on the polling thread.
Replaces the previous handler; an empty handler clears it. Installing
a handler on an already disconnected client calls it immediately.
*/
virtual void setDisconnectHandler(std::function<void()>&& fn) = 0;

protected:
IServerClient() = default;
};
Expand Down Expand Up @@ -75,4 +100,4 @@ namespace Hyprwire {
protected:
IServerSocket() = default;
};
};
};
6 changes: 5 additions & 1 deletion include/hyprwire/core/types/MessageMagic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ namespace Hyprwire {

/*
[magic : 1B][len : VLQ][data : len B]

VARCHAR protocol method arguments must be NUL-free, including array elements.
Empty strings are allowed. Callbacks receive NUL-terminated C strings;
the terminator is not part of the payload or its length.
*/
HW_MESSAGE_MAGIC_TYPE_VARCHAR = 0x20,

Expand Down Expand Up @@ -56,4 +60,4 @@ namespace Hyprwire {
*/
HW_MESSAGE_MAGIC_TYPE_FD = 0x40,
};
};
};
122 changes: 105 additions & 17 deletions src/core/client/ClientSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include <cstring>

#include <filesystem>
#include <utility>
#include <hyprutils/utils/ScopeGuard.hpp>

using namespace Hyprwire;
Expand Down Expand Up @@ -55,6 +56,10 @@ SP<IClientSocket> IClientSocket::open(const int fd) {
return sock;
}

CClientSocket::~CClientSocket() {
disconnectOnError();
}

bool CClientSocket::attempt(const std::string& path) {
m_fd = CFileDescriptor{socket(AF_UNIX, SOCK_STREAM, 0)};
sockaddr_un serverAddress = {.sun_family = AF_UNIX};
Expand Down Expand Up @@ -116,12 +121,18 @@ void CClientSocket::resetHandshakeTimeoutForTests() {

//
bool CClientSocket::dispatchEvents(bool block) {
const auto self = m_self.lock();
CScopeGuard onError([this] {
if (m_error)
disconnectOnError();
});

if (m_error)
return false;

collectOrphanedObjects();

int ret = 0;
if (!m_handshakeDone) {
const auto elapsed = std::chrono::steady_clock::now() - m_handshakeBegin;
const auto maxMs = g_handshakeMax;
Expand All @@ -133,7 +144,7 @@ bool CClientSocket::dispatchEvents(bool block) {
}

const auto timeout = block ? std::chrono::duration_cast<std::chrono::milliseconds>(maxMs - elapsed).count() : 0;
int ret = Syscalls::poll(m_pollfds.data(), m_pollfds.size(), static_cast<int>(timeout));
ret = Syscalls::poll(m_pollfds.data(), m_pollfds.size(), static_cast<int>(timeout));
if (block && !ret) {
Debug::log(ERR, "handshake error: timed out");
disconnectOnError();
Expand All @@ -142,11 +153,23 @@ bool CClientSocket::dispatchEvents(bool block) {
}

if (m_handshakeDone)
Syscalls::poll(m_pollfds.data(), m_pollfds.size(), block ? -1 : 0);
ret = Syscalls::poll(m_pollfds.data(), m_pollfds.size(), block ? -1 : 0);

if (ret < 0) {
if (errno == EINTR)
return !m_error;
disconnectOnError();
return false;
}

if (!(m_pollfds[0].revents & POLLIN)) {
const auto revents = m_pollfds[0].revents;
if (!(revents & POLLIN)) {
if (revents & (POLLHUP | POLLERR | POLLNVAL)) {
disconnectOnError();
return false;
}
collectOrphanedObjects();
return !(m_pollfds[0].revents & POLLHUP);
return !m_error;
}

// dispatch
Expand All @@ -159,17 +182,27 @@ bool CClientSocket::dispatchEvents(bool block) {
return false;
}

if (data.data.empty())
if (data.data.empty()) {
disconnectOnError();
return false;
}

const auto RET = g_messageParser->handleMessage(data, m_self.lock());
const auto RET = g_messageParser->handleMessage(data, self);

if (RET != MESSAGE_PARSED_OK) {
Debug::log(ERR, "fatal: failed to handle message on wire");
disconnectOnError();
return false;
}

if (m_error)
return false;

if (revents & (POLLHUP | POLLERR | POLLNVAL)) {
disconnectOnError();
return false;
}

std::erase_if(m_pendingOutgoing, [this](auto& msg) {
auto obj = objectForSeq(msg.m_dependsOnSeq);
if (!obj)
Expand Down Expand Up @@ -256,6 +289,7 @@ void CClientSocket::serverSpecs(const std::vector<std::string>& s) {
}

bool CClientSocket::waitForHandshake() {
const auto self = m_self.lock();
m_handshakeBegin = std::chrono::steady_clock::now();

while (!m_error && !m_handshakeDone) {
Expand All @@ -279,25 +313,71 @@ SP<IProtocolSpec> CClientSocket::getSpec(const std::string& name) {
}

void CClientSocket::onSeq(uint32_t seq, uint32_t id) {
for (const auto& c : m_objects) {
if (c->m_seq == seq) {
c->m_id = id;
return;
}
if (m_error)
return;

auto object = reinterpretPointerCast<CClientObject>(objectForSeq(seq));
if (!object) {
Debug::log(WARN, "[{} @ {:.3f}] -> No object for sequence {} (Would be id {}).!", m_fd.get(), steadyMillis(), seq, id);
return;
}

Debug::log(WARN, "[{} @ {:.3f}] -> No object for sequence {} (Would be id {}).!", m_fd.get(), steadyMillis(), seq, id);
if (!id) {
Debug::log(ERR, "invalid object id for sequence {}", seq);
disconnectOnError();
return;
}

object->m_id = id;
// Detach before calling user code: it can bind again or disconnect the socket.
auto completion = m_pendingBinds.extract(seq);
if (!completion.empty() && completion.mapped())
completion.mapped()(object);
}

SP<IObject> CClientSocket::bindProtocol(const SP<IProtocolSpec>& spec, uint32_t version) {
const auto self = m_self.lock();
auto object = beginBindProtocol(spec, version);
if (!object)
return nullptr;

waitForObject(object);
return !m_error && object->m_id ? object : nullptr;
}

void CClientSocket::bindProtocolAsync(const SP<IProtocolSpec>& spec, uint32_t version, std::function<void(SP<IObject>)>&& completion) {
const auto self = m_self.lock();
auto object = beginBindProtocol(spec, version);
if (!object) {
if (completion)
completion(nullptr);
return;
}

m_pendingBinds.emplace(object->m_seq, std::move(completion));
}

SP<CClientObject> CClientSocket::beginBindProtocol(const SP<IProtocolSpec>& spec, uint32_t version) {
if (m_error || !spec) {
disconnectOnError();
return nullptr;
}

if (version > spec->specVer()) {
Debug::log(ERR, "version {} is larger than current spec ver of {}", version, spec->specVer());
disconnectOnError();
return nullptr;
}

const auto objects = spec->objects();
if (objects.empty() || !objects.front()) {
Debug::log(ERR, "protocol spec has no binding object");
disconnectOnError();
return nullptr;
}

auto object = makeShared<CClientObject>(m_self.lock());
object->m_spec = spec->objects().front();
object->m_spec = objects.front();
object->m_seq = ++m_seq;
object->m_version = version;
object->m_self = object;
Expand All @@ -307,8 +387,6 @@ SP<IObject> CClientSocket::bindProtocol(const SP<IProtocolSpec>& spec, uint32_t
auto bindMessage = CBindProtocolMessage(spec->specName(), object->m_seq, version);
sendMessage(bindMessage);

waitForObject(object);

return object;
}

Expand Down Expand Up @@ -341,9 +419,11 @@ SP<CClientObject> CClientSocket::makeObject(const std::string& protocolName, con
}

void CClientSocket::waitForObject(SP<IWireObject> x) {
const auto self = m_self.lock();
m_waitingOnObject = x;
while (!x->m_id && !m_error) {
dispatchEvents(true);
if (!dispatchEvents(true))
break;
}
m_waitingOnObject.reset();
}
Expand Down Expand Up @@ -405,11 +485,19 @@ SP<IObject> CClientSocket::objectForSeq(uint32_t seq) {
}

void CClientSocket::disconnectOnError() {
m_error = true;
const auto self = m_self.lock();
m_error = true;
m_fd.reset();

auto pending = std::exchange(m_pendingBinds, {});
for (auto& [seq, completion] : pending) {
if (completion)
completion(nullptr);
}
}

void CClientSocket::roundtrip() {
const auto self = m_self.lock();
if (m_error)
return;

Expand Down
11 changes: 9 additions & 2 deletions src/core/client/ClientSocket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "../wireObject/IWireObject.hpp"

#include <vector>
#include <unordered_map>
#include <sys/poll.h>
#include <chrono>

Expand All @@ -17,8 +18,8 @@ namespace Hyprwire {

class CClientSocket : public IClientSocket {
public:
CClientSocket() = default;
virtual ~CClientSocket() = default;
CClientSocket() = default;
virtual ~CClientSocket();

bool attempt(const std::string& path);
bool attemptFromFd(const int fd);
Expand All @@ -29,6 +30,7 @@ namespace Hyprwire {
virtual bool waitForHandshake();
virtual SP<IProtocolSpec> getSpec(const std::string& name);
virtual SP<IObject> bindProtocol(const SP<IProtocolSpec>& spec, uint32_t version);
virtual void bindProtocolAsync(const SP<IProtocolSpec>& spec, uint32_t version, std::function<void(SP<IObject>)>&& completion);
virtual SP<IObject> objectForId(uint32_t id);
virtual SP<IObject> objectForSeq(uint32_t seq);
virtual void roundtrip();
Expand Down Expand Up @@ -70,5 +72,10 @@ namespace Hyprwire {

uint32_t m_lastAckdRoundtripSeq = 0;
uint32_t m_lastSentRoundtripSeq = 0;

private:
SP<CClientObject> beginBindProtocol(const SP<IProtocolSpec>& spec, uint32_t version);

std::unordered_map<uint32_t, std::function<void(SP<IObject>)>> m_pendingBinds;
};
};
2 changes: 1 addition & 1 deletion src/core/message/MessageParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ eMessageParsingResult CMessageParser::handleMessage(SSocketRawParsedMessage& dat

eMessageParsingResult CMessageParser::handleMessage(SSocketRawParsedMessage& data, SP<CClientSocket> client) {
size_t needle = 0;
while (needle < data.data.size()) {
while (needle < data.data.size() && !client->m_error) {
auto ret = parseSingleMessage(data, needle, client);
if (ret == 0)
return MESSAGE_PARSED_ERROR;
Expand Down
Loading
Loading