feat(IPC): add V1 VDIP framed codec, quota reservations, local UDS/pipe transport, full-duplex Session, and IPCOnly consumer (S-IPC-01..03)

This commit is contained in:
faumaray committed 2026-11-24 15:27:40 +03:00
1 parent 9a3c5d86ef
commit 39a48d5c0a
13 files changed
+4187

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
#pragma once
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IPC/Types.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::IPC
{
struct FrameHeader {
std::uint16_t version{kWireVersion};
std::uint8_t flags{0};
FrameType type{FrameType::request};
std::uint32_t payload_len{0};
std::uint32_t stream_id{0};
std::uint64_t request_id{0};
};
class BufferQuota;
class QuotaPermit
{
public:
QuotaPermit() noexcept = default;
~QuotaPermit() noexcept;
QuotaPermit(const QuotaPermit&) = delete;
QuotaPermit& operator=(const QuotaPermit&) = delete;
QuotaPermit(QuotaPermit&& other) noexcept;
QuotaPermit& operator=(QuotaPermit&& other) noexcept;
[[nodiscard]] bool valid() const noexcept { return bytes_ > 0; }
[[nodiscard]] std::size_t bytes() const noexcept { return bytes_; }
void reset() noexcept;
private:
friend class BufferQuota;
std::weak_ptr<BufferQuota> quota_{};
std::size_t bytes_{0};
};
class BufferQuota : public std::enable_shared_from_this<BufferQuota>
{
public:
explicit BufferQuota(std::size_t capacity_bytes);
[[nodiscard]] static std::shared_ptr<BufferQuota>
create(std::size_t capacity_bytes);
[[nodiscard]] Void::Result::Result<QuotaPermit, Void::Result::Error>
reserve(std::size_t bytes);
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
[[nodiscard]] std::size_t used() const noexcept;
private:
friend class QuotaPermit;
void release(std::size_t bytes) noexcept;
std::size_t capacity_{0};
mutable std::mutex mu_{};
std::size_t used_{0};
};
struct DecodedFrame {
FrameHeader header{};
Void::Binary::FrozenBytes payload{};
QuotaPermit global_permit{};
QuotaPermit session_permit{};
};
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
validate_frame_header(const FrameHeader& header, const IpcLimits& limits);
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
encode_frame_header(const FrameHeader& header,
std::span<std::byte, kFrameHeaderSize> out);
[[nodiscard]] Void::Result::Result<FrameHeader, Void::Result::Error>
decode_frame_header(std::span<const std::byte, kFrameHeaderSize> in);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_frame(
const FrameHeader& header,
std::span<const std::byte> payload = {},
const IpcLimits& limits = {},
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_hello(const HelloInfo& info,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<HelloInfo, Void::Result::Error>
decode_hello(std::span<const std::byte> payload,
std::size_t max_bytes = 4096);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_error_payload(
IpcErrorCode code,
std::string_view message,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<std::pair<IpcErrorCode, std::string>,
Void::Result::Error>
decode_error_payload(std::span<const std::byte> payload);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_goaway_payload(
IpcErrorCode code,
std::uint64_t last_request_id,
std::string_view reason,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<
std::tuple<IpcErrorCode, std::uint64_t, std::string>,
Void::Result::Error>
decode_goaway_payload(std::span<const std::byte> payload);
class FrameDecoder
{
public:
explicit FrameDecoder(
IpcLimits limits = {},
std::shared_ptr<BufferQuota> global_quota = {},
std::shared_ptr<BufferQuota> session_quota = {},
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] static constexpr std::size_t
frame_quota_cost(std::size_t payload_len) noexcept
{
return kFrameHeaderSize + payload_len;
}
[[nodiscard]] Void::Result::Result<std::vector<DecodedFrame>,
Void::Result::Error>
feed(std::span<const std::byte> chunk);
[[nodiscard]] std::size_t header_bytes_buffered() const noexcept
{
return header_len_;
}
[[nodiscard]] std::size_t payload_bytes_buffered() const noexcept
{
return has_header_ ? payload_written_ : 0;
}
[[nodiscard]] bool in_mid_frame() const noexcept
{
return header_len_ > 0 || has_header_;
}
private:
enum class State {
reading_header,
reading_payload,
failed,
};
IpcLimits limits_{};
std::shared_ptr<BufferQuota> global_quota_{};
std::shared_ptr<BufferQuota> session_quota_{};
std::pmr::memory_resource* mr_{nullptr};
State state_{State::reading_header};
std::array<std::byte, kFrameHeaderSize> header_buf_{};
std::size_t header_len_{0};
bool has_header_{false};
FrameHeader current_header_{};
QuotaPermit current_global_permit_{};
QuotaPermit current_session_permit_{};
std::optional<Void::Binary::ByteBuffer> payload_buf_{};
std::size_t payload_written_{0};
void reset_frame_state() noexcept;
};
} // namespace Void::IPC
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <Void/IPC/Codec.hpp>
#include <Void/IPC/Session.hpp>
#include <Void/IPC/Transport.hpp>
#include <Void/IPC/Types.hpp>
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IPC/Codec.hpp>
#include <Void/IPC/Transport.hpp>
#include <Void/IPC/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <expected>
#include <functional>
#include <memory>
#include <stop_token>
namespace Void::IPC
{
using RequestHandler = std::function<Void::Coro::Task<
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>(
Void::Binary::FrozenBytes payload, std::stop_token cancel)>;
using OneWayHandler = std::function<void(Void::Binary::FrozenBytes payload)>;
class Session
{
public:
struct State;
explicit Session(
Void::IO::Driver& driver,
Void::Async::Executor& executor,
DuplexTransport transport,
IpcLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
std::shared_ptr<BufferQuota> global_quota = {});
~Session() noexcept;
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
Session(Session&&) = delete;
Session& operator=(Session&&) = delete;
[[nodiscard]] Void::Coro::Task<Void::Result::Result<HelloInfo, Void::Result::Error>>
handshake(HelloInfo local_hello = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
start(RequestHandler on_request, OneWayHandler on_one_way = {});
[[nodiscard]] Void::Coro::Task<
std::expected<Void::Binary::FrozenBytes, CallFailure>>
request(Void::Binary::FrozenBytes payload,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_one_way(Void::Binary::FrozenBytes payload);
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_goaway(IpcErrorCode code = IpcErrorCode::closed,
std::string_view reason = "closing");
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] SessionStats stats() const noexcept;
[[nodiscard]] HelloInfo negotiated_hello() const;
[[nodiscard]] const PeerCredentials& peer_credentials() const noexcept;
// Test hook to inspect/force request ID near exhaustion without 2^64 calls.
void set_next_request_id_for_test(std::uint64_t next_id) noexcept;
private:
std::shared_ptr<State> state_{};
};
} // namespace Void::IPC
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IPC/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
namespace Void::IPC
{
class DuplexTransport
{
public:
DuplexTransport() noexcept = default;
DuplexTransport(Void::IO::ByteStream unified_stream,
PeerCredentials creds) noexcept;
DuplexTransport(Void::IO::ByteStream read_stream,
Void::IO::ByteStream write_stream,
PeerCredentials creds) noexcept;
DuplexTransport(const DuplexTransport&) = delete;
DuplexTransport& operator=(const DuplexTransport&) = delete;
DuplexTransport(DuplexTransport&&) noexcept = default;
DuplexTransport& operator=(DuplexTransport&&) noexcept = default;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool is_split() const noexcept { return split_; }
[[nodiscard]] const PeerCredentials& credentials() const noexcept
{
return credentials_;
}
[[nodiscard]] Void::IO::ByteStream& reader_stream() noexcept
{
return read_stream_;
}
[[nodiscard]] Void::IO::ByteStream& writer_stream() noexcept
{
return split_ ? write_stream_ : read_stream_;
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
private:
friend class LocalListener;
bool split_{false};
Void::IO::ByteStream read_stream_{};
Void::IO::ByteStream write_stream_{};
PeerCredentials credentials_{};
std::shared_ptr<void> listener_slot_{};
};
class LocalListener
{
public:
struct SlotState;
LocalListener() noexcept = default;
~LocalListener() noexcept;
LocalListener(const LocalListener&) = delete;
LocalListener& operator=(const LocalListener&) = delete;
LocalListener(LocalListener&& other) noexcept;
LocalListener& operator=(LocalListener&& other) noexcept;
[[nodiscard]] static Void::Result::Result<LocalListener, Void::Result::Error>
listen(const std::filesystem::path& socket_path,
IpcLimits limits = {},
PeerPolicy policy = {});
[[nodiscard]] Void::Result::Result<std::optional<DuplexTransport>,
Void::Result::Error>
try_accept(Void::IO::Driver& driver);
[[nodiscard]] bool valid() const noexcept { return listen_fd_ >= 0; }
[[nodiscard]] std::size_t active_sessions() const noexcept;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return socket_path_;
}
[[nodiscard]] int fd() const noexcept { return listen_fd_; }
void close() noexcept;
private:
int listen_fd_{-1};
int dir_fd_{-1};
int lock_fd_{-1};
std::filesystem::path socket_path_{};
std::string socket_name_{};
std::uint64_t socket_dev_{0};
std::uint64_t socket_ino_{0};
IpcLimits limits_{};
PeerPolicy policy_{};
std::shared_ptr<SlotState> slot_state_{};
};
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
connect_local(Void::IO::Driver& driver,
const std::filesystem::path& socket_path,
PeerPolicy policy = {});
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd);
[[nodiscard]] Void::Result::Result<std::pair<DuplexTransport, DuplexTransport>,
Void::Result::Error>
create_socket_pair_transports(Void::IO::Driver& driver);
} // namespace Void::IPC
+181
View File
@@ -0,0 +1,181 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <format>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
namespace Void::IPC
{
inline constexpr std::size_t kFrameHeaderSize = 24;
inline constexpr std::uint16_t kWireVersion = 1;
enum class IpcErrorCode : std::int32_t {
invalid_argument = 1,
corrupt_frame = 2,
unsupported_version = 3,
frame_too_large = 4,
quota_exceeded = 5,
overloaded = 6,
rate_limited = 7,
cancelled = 8,
timed_out = 9,
transport_lost = 10,
closed = 11,
permission_denied = 12,
already_exists = 13,
not_found = 14,
handshake_failed = 15,
id_exhausted = 16,
self_join = 17,
peer_error = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_ipc_error(IpcErrorCode code) noexcept
{
switch (code) {
case IpcErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case IpcErrorCode::corrupt_frame:
return Void::Result::ErrorKind::corrupt;
case IpcErrorCode::unsupported_version:
return Void::Result::ErrorKind::unsupported;
case IpcErrorCode::frame_too_large:
case IpcErrorCode::quota_exceeded:
case IpcErrorCode::id_exhausted:
return Void::Result::ErrorKind::exhausted;
case IpcErrorCode::overloaded:
case IpcErrorCode::rate_limited:
return Void::Result::ErrorKind::overloaded;
case IpcErrorCode::cancelled:
case IpcErrorCode::closed:
return Void::Result::ErrorKind::cancelled;
case IpcErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case IpcErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case IpcErrorCode::already_exists:
case IpcErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case IpcErrorCode::permission_denied:
case IpcErrorCode::transport_lost:
case IpcErrorCode::handshake_failed:
case IpcErrorCode::peer_error:
return Void::Result::ErrorKind::io;
case IpcErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline Void::Result::Error make_ipc_error(
IpcErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
std::error_code sys_ec{};
if (sys_errno != 0) {
detail = std::format(
"{} (errno={}: {})", message, sys_errno, std::strerror(sys_errno));
sys_ec = std::error_code{sys_errno, std::generic_category()};
} else {
detail.assign(message);
}
return Void::Result::Error{
classify_ipc_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kIpcErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
enum class FrameType : std::uint8_t {
hello = 1,
request = 2,
response = 3,
error = 4,
cancel = 5,
one_way = 6,
goaway = 7,
};
enum class EffectStatus : std::uint8_t {
not_sent = 0,
unknown = 1,
};
struct CallFailure {
Void::Result::Error error{};
EffectStatus effect{EffectStatus::not_sent};
bool may_have_executed{false};
};
struct IpcLimits {
std::size_t max_frame_payload{1024ULL * 1024ULL};
std::size_t max_hello_bytes{4096};
std::size_t max_inflight_requests{64};
std::size_t max_active_handlers{64};
std::size_t max_outbound_frames{128};
std::size_t max_outbound_bytes{4ULL * 1024ULL * 1024ULL};
std::size_t max_recv_buffer_bytes{2ULL * 1024ULL * 1024ULL};
std::size_t max_tombstones{256};
std::size_t max_sessions{128};
std::size_t global_buffer_budget_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_waiters{128};
std::size_t control_lane_max_bytes{8192};
std::size_t control_lane_max_frames{16};
double rate_limit_per_sec{1000.0};
double rate_limit_burst{128.0};
std::chrono::milliseconds handshake_timeout{std::chrono::milliseconds{5000}};
std::chrono::milliseconds progress_timeout{std::chrono::milliseconds{5000}};
std::chrono::milliseconds idle_timeout{std::chrono::milliseconds{60000}};
};
struct PeerCredentials {
bool available{false};
long long pid{-1};
unsigned long uid{0};
unsigned long gid{0};
};
struct PeerPolicy {
bool require_uid_match{true};
bool set_allowed_uid_to_current_user{true};
unsigned long allowed_uid{0};
std::optional<unsigned long> required_gid{};
};
struct HelloInfo {
std::string protocol_id{"void.ipc.v1"};
std::uint32_t protocol_version{1};
std::uint32_t capabilities{0};
std::uint32_t max_frame_payload{1024u * 1024u};
std::uint32_t max_inflight_requests{64u};
std::uint32_t max_active_handlers{64u};
};
struct SessionStats {
std::uint64_t frames_sent{0};
std::uint64_t frames_received{0};
std::uint64_t requests_sent{0};
std::uint64_t requests_received{0};
std::uint64_t late_responses_dropped{0};
std::uint64_t cancels_coalesced{0};
std::size_t active_inflight{0};
std::size_t active_handlers{0};
std::size_t outbound_queued_bytes{0};
std::size_t control_queued_frames{0};
std::uint64_t next_request_id{1};
};
} // namespace Void::IPC
+602
View File
@@ -0,0 +1,602 @@
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/IPC/Codec.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <cstring>
#include <expected>
#include <format>
#include <limits>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
namespace Void::IPC
{
namespace
{
constexpr std::array<std::byte, 4> kMagicBytes{
std::byte{'V'}, std::byte{'D'}, std::byte{'I'}, std::byte{'P'}};
[[nodiscard]] bool is_valid_frame_type(std::uint8_t raw) noexcept
{
return raw >= static_cast<std::uint8_t>(FrameType::hello) &&
raw <= static_cast<std::uint8_t>(FrameType::goaway);
}
[[nodiscard]] bool is_valid_error_code(std::int32_t raw) noexcept
{
return raw >= static_cast<std::int32_t>(IpcErrorCode::invalid_argument) &&
raw <= static_cast<std::int32_t>(IpcErrorCode::internal);
}
} // namespace
QuotaPermit::~QuotaPermit() noexcept { reset(); }
QuotaPermit::QuotaPermit(QuotaPermit&& other) noexcept
: quota_(std::move(other.quota_)),
bytes_(std::exchange(other.bytes_, 0))
{
}
QuotaPermit& QuotaPermit::operator=(QuotaPermit&& other) noexcept
{
if (this != &other) {
reset();
quota_ = std::move(other.quota_);
bytes_ = std::exchange(other.bytes_, 0);
}
return *this;
}
void QuotaPermit::reset() noexcept
{
const std::size_t rel = std::exchange(bytes_, 0);
if (rel > 0) {
if (auto q = quota_.lock()) {
q->release(rel);
}
}
quota_.reset();
}
BufferQuota::BufferQuota(std::size_t capacity_bytes) : capacity_(capacity_bytes)
{
}
std::shared_ptr<BufferQuota> BufferQuota::create(std::size_t capacity_bytes)
{
return std::make_shared<BufferQuota>(capacity_bytes);
}
Void::Result::Result<QuotaPermit, Void::Result::Error>
BufferQuota::reserve(std::size_t bytes)
{
std::lock_guard lk{mu_};
if (bytes > capacity_ || used_ > capacity_ - bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded,
std::format(
"IPC buffer quota exceeded (requested {}, used {}/{})",
bytes,
used_,
capacity_))};
}
used_ += bytes;
QuotaPermit permit;
permit.quota_ = weak_from_this();
permit.bytes_ = bytes;
return permit;
}
void BufferQuota::release(std::size_t bytes) noexcept
{
std::lock_guard lk{mu_};
used_ = (used_ >= bytes) ? (used_ - bytes) : 0;
}
std::size_t BufferQuota::used() const noexcept
{
std::lock_guard lk{mu_};
return used_;
}
Void::Result::Result<void, Void::Result::Error>
validate_frame_header(const FrameHeader& header, const IpcLimits& limits)
{
if (header.version != kWireVersion) {
return std::unexpected{make_ipc_error(
IpcErrorCode::unsupported_version,
std::format("Unsupported IPC wire version {}", header.version))};
}
if (header.flags != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format("Unsupported non-zero IPC flags {:#x}", header.flags))};
}
if (!is_valid_frame_type(static_cast<std::uint8_t>(header.type))) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format(
"Unknown IPC frame type {}",
static_cast<unsigned>(header.type)))};
}
if (header.stream_id != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format(
"IPC V1 requires stream_id == 0 (got {})", header.stream_id))};
}
if (header.payload_len > limits.max_frame_payload) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
std::format(
"IPC frame payload_len {} exceeds max_frame_payload {}",
header.payload_len,
limits.max_frame_payload))};
}
if (header.type == FrameType::hello &&
header.payload_len > limits.max_hello_bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
std::format(
"IPC hello payload_len {} exceeds max_hello_bytes {}",
header.payload_len,
limits.max_hello_bytes))};
}
switch (header.type) {
case FrameType::request:
case FrameType::response:
case FrameType::cancel:
if (header.request_id == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"IPC request/response/cancel frame requires nonzero request_id")};
}
break;
case FrameType::hello:
case FrameType::one_way:
case FrameType::goaway:
if (header.request_id != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"IPC hello/one_way/goaway frame requires request_id == 0")};
}
break;
case FrameType::error:
break;
}
return {};
}
Void::Result::Result<void, Void::Result::Error> encode_frame_header(
const FrameHeader& header, std::span<std::byte, kFrameHeaderSize> out)
{
Void::Binary::Writer w{out};
if (auto r = w.writeBytes(kMagicBytes); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint16_t>(header.version); !r) {
return std::unexpected{std::move(r.error())};
}
const std::uint16_t flags_type =
static_cast<std::uint16_t>((static_cast<std::uint16_t>(header.flags) << 8) |
static_cast<std::uint8_t>(header.type));
if (auto r = w.writeBig<std::uint16_t>(flags_type); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint32_t>(header.payload_len); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint32_t>(header.stream_id); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint64_t>(header.request_id); !r) {
return std::unexpected{std::move(r.error())};
}
return {};
}
Void::Result::Result<FrameHeader, Void::Result::Error>
decode_frame_header(std::span<const std::byte, kFrameHeaderSize> in)
{
Void::Binary::Reader r{in};
auto magic = r.readBytes(4);
if (!magic || !std::equal(magic->begin(), magic->end(), kMagicBytes.begin())) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Invalid IPC wire magic (expected VDIP)")};
}
auto ver = r.read<std::uint16_t>(std::endian::big);
auto flags_type = r.read<std::uint16_t>(std::endian::big);
auto plen = r.read<std::uint32_t>(std::endian::big);
auto sid = r.read<std::uint32_t>(std::endian::big);
auto rid = r.read<std::uint64_t>(std::endian::big);
if (!ver || !flags_type || !plen || !sid || !rid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC frame header")};
}
const auto raw_flags = static_cast<std::uint8_t>((*flags_type >> 8) & 0xffu);
const auto raw_type = static_cast<std::uint8_t>(*flags_type & 0xffu);
if (!is_valid_frame_type(raw_type)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format("Invalid IPC frame type byte {}", raw_type))};
}
FrameHeader hdr;
hdr.version = *ver;
hdr.flags = raw_flags;
hdr.type = static_cast<FrameType>(raw_type);
hdr.payload_len = *plen;
hdr.stream_id = *sid;
hdr.request_id = *rid;
return hdr;
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error> encode_frame(
const FrameHeader& header,
std::span<const std::byte> payload,
const IpcLimits& limits,
std::pmr::memory_resource* mr)
{
if (payload.size() > std::numeric_limits<std::uint32_t>::max()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
"IPC payload exceeds uint32_t length field")};
}
FrameHeader effective = header;
effective.payload_len = static_cast<std::uint32_t>(payload.size());
if (auto v = validate_frame_header(effective, limits); !v) {
return std::unexpected{std::move(v.error())};
}
std::array<std::byte, kFrameHeaderSize> hdr_bytes{};
if (auto e = encode_frame_header(effective, hdr_bytes); !e) {
return std::unexpected{std::move(e.error())};
}
Void::Binary::ByteBuffer buf{kFrameHeaderSize + payload.size(), mr};
if (auto r = buf.reserve(kFrameHeaderSize + payload.size()); !r) {
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded, r.error().message())};
}
if (auto r = buf.append(hdr_bytes); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.append(payload); !r) {
return std::unexpected{std::move(r.error())};
}
return buf.freeze();
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_hello(const HelloInfo& info, std::pmr::memory_resource* mr)
{
if (info.protocol_id.empty() || info.protocol_id.size() > 256) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"HelloInfo protocol_id must be 1..256 bytes")};
}
const std::size_t total = 4 + info.protocol_id.size() + 20;
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(info.protocol_id.size()));
!r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeString(info.protocol_id); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.protocol_version); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.capabilities); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_frame_payload); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_inflight_requests); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_active_handlers); !r) {
return std::unexpected{std::move(r.error())};
}
return buf.freeze();
}
Void::Result::Result<HelloInfo, Void::Result::Error> decode_hello(
std::span<const std::byte> payload, std::size_t max_bytes)
{
if (payload.size() > max_bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
"Hello payload exceeds max_hello_bytes")};
}
Void::Binary::Reader r{payload};
auto pid_len = r.read<std::uint32_t>(std::endian::big);
if (!pid_len || *pid_len == 0 || *pid_len > 256) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed, "Invalid hello protocol_id length")};
}
auto pid_bytes = r.readBytes(*pid_len);
auto pver = r.read<std::uint32_t>(std::endian::big);
auto caps = r.read<std::uint32_t>(std::endian::big);
auto max_frame = r.read<std::uint32_t>(std::endian::big);
auto max_inf = r.read<std::uint32_t>(std::endian::big);
auto max_hdl = r.read<std::uint32_t>(std::endian::big);
if (!pid_bytes || !pver || !caps || !max_frame || !max_inf || !max_hdl ||
!r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed, "Malformed IPC hello payload")};
}
if (*max_frame == 0 || *max_inf == 0 || *max_hdl == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed,
"Hello limits must be strictly positive")};
}
HelloInfo out;
out.protocol_id.assign(
reinterpret_cast<const char*>(pid_bytes->data()), pid_bytes->size());
out.protocol_version = *pver;
out.capabilities = *caps;
out.max_frame_payload = *max_frame;
out.max_inflight_requests = *max_inf;
out.max_active_handlers = *max_hdl;
return out;
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_error_payload(IpcErrorCode code,
std::string_view message,
std::pmr::memory_resource* mr)
{
const std::string_view bounded =
message.substr(0, std::min<std::size_t>(message.size(), 512));
const std::size_t total = 8 + bounded.size();
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
(void)buf.writeBig<std::int32_t>(static_cast<std::int32_t>(code));
(void)buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(bounded.size()));
(void)buf.writeString(bounded);
return buf.freeze();
}
Void::Result::Result<std::pair<IpcErrorCode, std::string>, Void::Result::Error>
decode_error_payload(std::span<const std::byte> payload)
{
Void::Binary::Reader r{payload};
auto raw_code = r.read<std::int32_t>(std::endian::big);
auto mlen = r.read<std::uint32_t>(std::endian::big);
if (!raw_code || !mlen || *mlen > r.remaining()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Malformed IPC error payload")};
}
auto msg_bytes = r.readBytes(*mlen);
if (!msg_bytes || !r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC error payload")};
}
const auto code = is_valid_error_code(*raw_code)
? static_cast<IpcErrorCode>(*raw_code)
: IpcErrorCode::peer_error;
std::string msg{reinterpret_cast<const char*>(msg_bytes->data()),
msg_bytes->size()};
return std::pair<IpcErrorCode, std::string>{code, std::move(msg)};
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_goaway_payload(IpcErrorCode code,
std::uint64_t last_request_id,
std::string_view reason,
std::pmr::memory_resource* mr)
{
const std::string_view bounded =
reason.substr(0, std::min<std::size_t>(reason.size(), 512));
const std::size_t total = 16 + bounded.size();
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
(void)buf.writeBig<std::int32_t>(static_cast<std::int32_t>(code));
(void)buf.writeBig<std::uint64_t>(last_request_id);
(void)buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(bounded.size()));
(void)buf.writeString(bounded);
return buf.freeze();
}
Void::Result::Result<
std::tuple<IpcErrorCode, std::uint64_t, std::string>,
Void::Result::Error>
decode_goaway_payload(std::span<const std::byte> payload)
{
Void::Binary::Reader r{payload};
auto raw_code = r.read<std::int32_t>(std::endian::big);
auto last_id = r.read<std::uint64_t>(std::endian::big);
auto rlen = r.read<std::uint32_t>(std::endian::big);
if (!raw_code || !last_id || !rlen || *rlen > r.remaining()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Malformed IPC goaway payload")};
}
auto msg_bytes = r.readBytes(*rlen);
if (!msg_bytes || !r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC goaway payload")};
}
const auto code = is_valid_error_code(*raw_code)
? static_cast<IpcErrorCode>(*raw_code)
: IpcErrorCode::closed;
std::string reason{reinterpret_cast<const char*>(msg_bytes->data()),
msg_bytes->size()};
return std::tuple<IpcErrorCode, std::uint64_t, std::string>{
code, *last_id, std::move(reason)};
}
FrameDecoder::FrameDecoder(IpcLimits limits,
std::shared_ptr<BufferQuota> global_quota,
std::shared_ptr<BufferQuota> session_quota,
std::pmr::memory_resource* mr)
: limits_(limits),
global_quota_(std::move(global_quota)),
session_quota_(std::move(session_quota)),
mr_(mr ? mr : std::pmr::get_default_resource())
{
}
void FrameDecoder::reset_frame_state() noexcept
{
header_len_ = 0;
has_header_ = false;
current_header_ = FrameHeader{};
current_global_permit_.reset();
current_session_permit_.reset();
payload_buf_.reset();
payload_written_ = 0;
state_ = State::reading_header;
}
Void::Result::Result<std::vector<DecodedFrame>, Void::Result::Error>
FrameDecoder::feed(std::span<const std::byte> chunk)
{
if (state_ == State::failed) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"FrameDecoder is poisoned after prior frame error")};
}
std::vector<DecodedFrame> frames;
std::size_t off = 0;
while (off < chunk.size()) {
if (state_ == State::reading_header) {
const std::size_t need = kFrameHeaderSize - header_len_;
const std::size_t take = std::min(need, chunk.size() - off);
std::memcpy(header_buf_.data() + header_len_,
chunk.data() + off,
take);
header_len_ += take;
off += take;
if (header_len_ < kFrameHeaderSize) {
break;
}
auto hdr_res = decode_frame_header(header_buf_);
if (!hdr_res.has_value()) {
state_ = State::failed;
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(hdr_res.error())};
}
if (auto v = validate_frame_header(*hdr_res, limits_); !v.has_value()) {
state_ = State::failed;
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(v.error())};
}
const std::size_t quota_cost = frame_quota_cost(hdr_res->payload_len);
if (quota_cost > limits_.max_recv_buffer_bytes) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded,
"IPC frame exceeds max_recv_buffer_bytes")};
}
// Reserve global + per-session permits BEFORE allocating payload buffer!
QuotaPermit g_perm;
QuotaPermit s_perm;
if (global_quota_) {
auto gr = global_quota_->reserve(quota_cost);
if (!gr.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(gr.error())};
}
g_perm = std::move(*gr);
}
if (session_quota_) {
auto sr = session_quota_->reserve(quota_cost);
if (!sr.has_value()) {
g_perm.reset();
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(sr.error())};
}
s_perm = std::move(*sr);
}
current_header_ = *hdr_res;
current_global_permit_ = std::move(g_perm);
current_session_permit_ = std::move(s_perm);
has_header_ = true;
if (current_header_.payload_len == 0) {
DecodedFrame df;
df.header = current_header_;
df.global_permit = std::move(current_global_permit_);
df.session_permit = std::move(current_session_permit_);
frames.push_back(std::move(df));
reset_frame_state();
continue;
}
payload_buf_.emplace(current_header_.payload_len, mr_);
if (auto rr = payload_buf_->reserve(current_header_.payload_len);
!rr.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded, rr.error().message())};
}
payload_written_ = 0;
state_ = State::reading_payload;
}
if (state_ == State::reading_payload) {
const std::size_t rem_payload =
current_header_.payload_len - payload_written_;
const std::size_t take = std::min(rem_payload, chunk.size() - off);
if (auto ar = payload_buf_->append(chunk.subspan(off, take));
!ar.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(ar.error())};
}
payload_written_ += take;
off += take;
if (payload_written_ == current_header_.payload_len) {
DecodedFrame df;
df.header = current_header_;
df.payload = payload_buf_->freeze();
df.global_permit = std::move(current_global_permit_);
df.session_permit = std::move(current_session_permit_);
frames.push_back(std::move(df));
reset_frame_state();
}
}
}
return frames;
}
} // namespace Void::IPC
+1550
View File
File diff suppressed because it is too large. Load diff
+673
View File
@@ -0,0 +1,673 @@
#include <Void/IPC/Transport.hpp>
#include <fcntl.h>
#include <poll.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#include <atomic>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <filesystem>
#include <format>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace Void::IPC
{
namespace
{
[[nodiscard]] IpcErrorCode map_errno_to_ipc(int err) noexcept
{
switch (err) {
case ENOENT:
return IpcErrorCode::not_found;
case EACCES:
case EPERM:
case ELOOP:
return IpcErrorCode::permission_denied;
case EEXIST:
return IpcErrorCode::already_exists;
case EINVAL:
case ENAMETOOLONG:
case ENOTDIR:
case EISDIR:
return IpcErrorCode::invalid_argument;
case ETIMEDOUT:
return IpcErrorCode::timed_out;
case ECONNREFUSED:
case ECONNRESET:
case EPIPE:
case ENOTCONN:
return IpcErrorCode::transport_lost;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return IpcErrorCode::overloaded;
default:
return IpcErrorCode::transport_lost;
}
}
[[nodiscard]] Void::Result::Result<PeerCredentials, Void::Result::Error>
query_peer_credentials(int fd)
{
struct ucred cred{};
socklen_t len = sizeof(cred);
if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to query SO_PEERCRED", err)};
}
PeerCredentials out;
out.available = true;
out.pid = static_cast<long long>(cred.pid);
out.uid = static_cast<unsigned long>(cred.uid);
out.gid = static_cast<unsigned long>(cred.gid);
return out;
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
check_peer_policy(const PeerCredentials& creds, const PeerPolicy& policy)
{
if (!creds.available) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Peer credentials unavailable for SO_PEERCRED check")};
}
if (policy.require_uid_match) {
const unsigned long expected_uid =
policy.set_allowed_uid_to_current_user
? static_cast<unsigned long>(::geteuid())
: policy.allowed_uid;
if (creds.uid != expected_uid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format("Peer UID {} denied (expected {})",
creds.uid,
expected_uid))};
}
}
if (policy.required_gid.has_value() && creds.gid != *policy.required_gid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format("Peer GID {} denied (expected {})",
creds.gid,
*policy.required_gid))};
}
return {};
}
[[nodiscard]] Void::Result::Result<sockaddr_un, Void::Result::Error>
build_sockaddr(const std::filesystem::path& socket_path,
socklen_t& out_len)
{
const std::string& raw = socket_path.native();
if (raw.empty() || raw.find('\0') != std::string::npos) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"IPC socket path must be non-empty without NUL bytes")};
}
sockaddr_un addr{};
if (raw.size() >= sizeof(addr.sun_path)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
std::format("IPC socket path length {} >= sun_path limit ({})",
raw.size(),
sizeof(addr.sun_path)))};
}
addr.sun_family = AF_UNIX;
std::memcpy(addr.sun_path, raw.data(), raw.size());
addr.sun_path[raw.size()] = '\0';
out_len = static_cast<socklen_t>(
offsetof(sockaddr_un, sun_path) + raw.size() + 1);
return addr;
}
[[nodiscard]] bool probe_socket_alive(const sockaddr_un& addr,
socklen_t addr_len,
int& out_errno) noexcept
{
const int probe =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (probe < 0) {
out_errno = errno;
return false;
}
const int rc =
::connect(probe, reinterpret_cast<const sockaddr*>(&addr), addr_len);
out_errno = (rc == 0) ? 0 : errno;
(void)::close(probe);
return rc == 0 || out_errno == EINPROGRESS || out_errno == EAGAIN;
}
} // namespace
struct LocalListener::SlotState {
std::size_t max_sessions{128};
mutable std::mutex mu{};
std::size_t active{0};
};
namespace
{
struct ListenerSlotGuard {
std::weak_ptr<LocalListener::SlotState> state;
~ListenerSlotGuard() noexcept
{
if (auto p = state.lock()) {
std::lock_guard lk{p->mu};
if (p->active > 0) {
--p->active;
}
}
}
};
} // namespace
DuplexTransport::DuplexTransport(Void::IO::ByteStream unified_stream,
PeerCredentials creds) noexcept
: split_(false),
read_stream_(std::move(unified_stream)),
credentials_(creds)
{
}
DuplexTransport::DuplexTransport(Void::IO::ByteStream read_stream,
Void::IO::ByteStream write_stream,
PeerCredentials creds) noexcept
: split_(true),
read_stream_(std::move(read_stream)),
write_stream_(std::move(write_stream)),
credentials_(creds)
{
}
bool DuplexTransport::valid() const noexcept
{
return split_ ? (read_stream_.valid() && write_stream_.valid())
: read_stream_.valid();
}
Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
DuplexTransport::close_and_join(Void::Async::OperationOptions options)
{
if (!split_) {
if (read_stream_.valid()) {
auto r = co_await read_stream_.close_and_join(options);
listener_slot_.reset();
co_return r;
}
listener_slot_.reset();
co_return {};
}
Void::Result::Result<void, Void::Result::Error> first_err;
if (write_stream_.valid()) {
auto w = co_await write_stream_.close_and_join(options);
if (!w.has_value()) {
first_err = std::move(w);
}
}
if (read_stream_.valid()) {
auto r = co_await read_stream_.close_and_join(options);
if (!r.has_value() && first_err.has_value()) {
first_err = std::move(r);
}
}
listener_slot_.reset();
co_return first_err;
}
LocalListener::~LocalListener() noexcept { close(); }
LocalListener::LocalListener(LocalListener&& other) noexcept
: listen_fd_(std::exchange(other.listen_fd_, -1)),
dir_fd_(std::exchange(other.dir_fd_, -1)),
lock_fd_(std::exchange(other.lock_fd_, -1)),
socket_path_(std::move(other.socket_path_)),
socket_name_(std::move(other.socket_name_)),
socket_dev_(std::exchange(other.socket_dev_, 0)),
socket_ino_(std::exchange(other.socket_ino_, 0)),
limits_(other.limits_),
policy_(other.policy_),
slot_state_(std::move(other.slot_state_))
{
}
LocalListener& LocalListener::operator=(LocalListener&& other) noexcept
{
if (this != &other) {
close();
listen_fd_ = std::exchange(other.listen_fd_, -1);
dir_fd_ = std::exchange(other.dir_fd_, -1);
lock_fd_ = std::exchange(other.lock_fd_, -1);
socket_path_ = std::move(other.socket_path_);
socket_name_ = std::move(other.socket_name_);
socket_dev_ = std::exchange(other.socket_dev_, 0);
socket_ino_ = std::exchange(other.socket_ino_, 0);
limits_ = other.limits_;
policy_ = other.policy_;
slot_state_ = std::move(other.slot_state_);
}
return *this;
}
void LocalListener::close() noexcept
{
if (listen_fd_ >= 0) {
(void)::close(listen_fd_);
listen_fd_ = -1;
}
if (dir_fd_ >= 0 && !socket_name_.empty() && socket_ino_ != 0) {
struct stat st {};
if (::fstatat(dir_fd_,
socket_name_.c_str(),
&st,
AT_SYMLINK_NOFOLLOW) == 0 &&
S_ISSOCK(st.st_mode) &&
static_cast<std::uint64_t>(st.st_dev) == socket_dev_ &&
static_cast<std::uint64_t>(st.st_ino) == socket_ino_) {
(void)::unlinkat(dir_fd_, socket_name_.c_str(), 0);
}
}
if (dir_fd_ >= 0 && !socket_name_.empty() && lock_fd_ >= 0) {
const std::string lock_name = socket_name_ + ".lock";
(void)::unlinkat(dir_fd_, lock_name.c_str(), 0);
}
if (lock_fd_ >= 0) {
(void)::close(lock_fd_);
lock_fd_ = -1;
}
if (dir_fd_ >= 0) {
(void)::close(dir_fd_);
dir_fd_ = -1;
}
socket_name_.clear();
socket_dev_ = 0;
socket_ino_ = 0;
}
std::size_t LocalListener::active_sessions() const noexcept
{
if (!slot_state_) {
return 0;
}
std::lock_guard lk{slot_state_->mu};
return slot_state_->active;
}
Void::Result::Result<LocalListener, Void::Result::Error> LocalListener::listen(
const std::filesystem::path& socket_path,
IpcLimits limits,
PeerPolicy policy)
{
if (limits.max_sessions == 0 || limits.max_frame_payload == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"IpcLimits max_sessions and max_frame_payload must be non-zero")};
}
socklen_t addr_len = 0;
auto addr_res = build_sockaddr(socket_path, addr_len);
if (!addr_res.has_value()) {
return std::unexpected{std::move(addr_res.error())};
}
const std::string fname = socket_path.filename().string();
if (fname.empty() || fname == "." || fname == "..") {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"LocalListener socket path must have a valid filename")};
}
const std::filesystem::path parent =
socket_path.parent_path().empty() ? std::filesystem::path{"."}
: socket_path.parent_path();
const int raw_dir_fd = ::open(
parent.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (raw_dir_fd < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Cannot safely open IPC socket parent dir '{}'",
parent.string()),
err)};
}
LocalListener listener;
listener.dir_fd_ = raw_dir_fd;
listener.socket_path_ = socket_path;
listener.socket_name_ = fname;
listener.limits_ = limits;
listener.policy_ = policy;
struct stat dir_st {};
if (::fstat(listener.dir_fd_, &dir_st) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to stat IPC socket parent dir", err)};
}
if (dir_st.st_uid != ::geteuid() || (dir_st.st_mode & 0077) != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format(
"IPC socket parent dir '{}' must be owned by current user with 0700 permissions",
parent.string()))};
}
const std::string lock_name = fname + ".lock";
listener.lock_fd_ = ::openat(listener.dir_fd_,
lock_name.c_str(),
O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC,
0600);
if (listener.lock_fd_ < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
"Failed to open IPC startup lock file",
err)};
}
if (::flock(listener.lock_fd_, LOCK_EX | LOCK_NB) != 0) {
const int err = errno;
(void)::close(listener.lock_fd_);
listener.lock_fd_ = -1;
return std::unexpected{make_ipc_error(
IpcErrorCode::already_exists,
"Another listener holds the startup lock for this socket",
err)};
}
struct stat existing_st {};
if (::fstatat(listener.dir_fd_,
fname.c_str(),
&existing_st,
AT_SYMLINK_NOFOLLOW) == 0) {
if (!S_ISSOCK(existing_st.st_mode) ||
existing_st.st_uid != ::geteuid()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Refusing to remove non-socket, symlink, or foreign path at IPC endpoint")};
}
int probe_err = 0;
if (probe_socket_alive(*addr_res, addr_len, probe_err)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::already_exists,
"IPC socket endpoint is already active")};
}
if (probe_err != ECONNREFUSED) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Failed to confirm stale state before unlinking existing socket",
probe_err)};
}
if (::unlinkat(listener.dir_fd_, fname.c_str(), 0) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to remove stale IPC socket", err)};
}
} else if (errno != ENOENT) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to inspect IPC socket path", err)};
}
listener.listen_fd_ =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (listener.listen_fd_ < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to create AF_UNIX socket", err)};
}
if (::bind(listener.listen_fd_,
reinterpret_cast<const sockaddr*>(&*addr_res),
addr_len) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Failed to bind AF_UNIX socket '{}'",
socket_path.string()),
err)};
}
struct stat bound_st {};
if (::fstatat(listener.dir_fd_,
fname.c_str(),
&bound_st,
AT_SYMLINK_NOFOLLOW) != 0 ||
!S_ISSOCK(bound_st.st_mode)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Bound IPC endpoint missing or replaced unexpectedly")};
}
listener.socket_dev_ = static_cast<std::uint64_t>(bound_st.st_dev);
listener.socket_ino_ = static_cast<std::uint64_t>(bound_st.st_ino);
if (::chmod(socket_path.c_str(), 0600) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to set 0600 mode on IPC socket", err)};
}
if (::listen(listener.listen_fd_, 128) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to listen on AF_UNIX socket", err)};
}
listener.slot_state_ = std::make_shared<SlotState>();
listener.slot_state_->max_sessions = limits.max_sessions;
return listener;
}
Void::Result::Result<std::optional<DuplexTransport>, Void::Result::Error>
LocalListener::try_accept(Void::IO::Driver& driver)
{
if (listen_fd_ < 0 || !slot_state_) {
return std::unexpected{make_ipc_error(
IpcErrorCode::closed, "LocalListener is closed")};
}
for (;;) {
const int client_fd =
::accept4(listen_fd_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (client_fd < 0) {
const int err = errno;
if (err == EINTR) {
continue;
}
if (err == EAGAIN || err == EWOULDBLOCK) {
return std::optional<DuplexTransport>{std::nullopt};
}
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "accept4 failed on IPC listener", err)};
}
std::shared_ptr<ListenerSlotGuard> slot_guard;
{
std::lock_guard lk{slot_state_->mu};
if (slot_state_->active >= slot_state_->max_sessions) {
(void)::close(client_fd);
return std::unexpected{make_ipc_error(
IpcErrorCode::overloaded,
std::format("LocalListener max_sessions ({}) reached",
slot_state_->max_sessions))};
}
++slot_state_->active;
slot_guard = std::make_shared<ListenerSlotGuard>(slot_state_);
}
auto creds = query_peer_credentials(client_fd);
if (!creds.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(creds.error())};
}
if (auto auth = check_peer_policy(*creds, policy_); !auth.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(auth.error())};
}
auto stream = driver.adopt_fd(client_fd);
if (!stream.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(stream.error())};
}
DuplexTransport transport{std::move(*stream), *creds};
transport.listener_slot_ = std::move(slot_guard);
return std::optional<DuplexTransport>{std::move(transport)};
}
}
Void::Result::Result<DuplexTransport, Void::Result::Error> connect_local(
Void::IO::Driver& driver,
const std::filesystem::path& socket_path,
PeerPolicy policy)
{
socklen_t addr_len = 0;
auto addr_res = build_sockaddr(socket_path, addr_len);
if (!addr_res.has_value()) {
return std::unexpected{std::move(addr_res.error())};
}
struct stat st {};
if (::lstat(socket_path.c_str(), &st) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Cannot stat IPC socket '{}'", socket_path.string()),
err)};
}
if (S_ISLNK(st.st_mode) || !S_ISSOCK(st.st_mode)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"IPC connect target must be a real AF_UNIX socket, not a symlink")};
}
const int fd =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to create AF_UNIX client socket", err)};
}
for (;;) {
if (::connect(fd, reinterpret_cast<const sockaddr*>(&*addr_res), addr_len) ==
0) {
break;
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (err == EINPROGRESS) {
struct pollfd pfd{fd, POLLOUT, 0};
const int prc = ::poll(&pfd, 1, 5000);
if (prc <= 0) {
(void)::close(fd);
return std::unexpected{make_ipc_error(
IpcErrorCode::timed_out,
"Timed out connecting to AF_UNIX socket")};
}
int so_err = 0;
socklen_t slen = sizeof(so_err);
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 ||
so_err != 0) {
(void)::close(fd);
return std::unexpected{make_ipc_error(
map_errno_to_ipc(so_err != 0 ? so_err : errno),
"AF_UNIX connect failed",
so_err != 0 ? so_err : errno)};
}
break;
}
(void)::close(fd);
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Failed connecting to '{}'", socket_path.string()),
err)};
}
auto creds = query_peer_credentials(fd);
if (!creds.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(creds.error())};
}
if (auto auth = check_peer_policy(*creds, policy); !auth.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(auth.error())};
}
auto stream = driver.adopt_fd(fd);
if (!stream.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(stream.error())};
}
return DuplexTransport{std::move(*stream), *creds};
}
Void::Result::Result<DuplexTransport, Void::Result::Error>
adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd)
{
if (read_fd < 0 || write_fd < 0 || read_fd == write_fd) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"adopt_pipe_pair requires distinct valid read_fd and write_fd")};
}
if (::fcntl(read_fd, F_GETFD) == -1 || ::fcntl(write_fd, F_GETFD) == -1) {
const int err = errno;
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"adopt_pipe_pair received closed or invalid descriptor",
err)};
}
auto rstream = driver.adopt_fd(read_fd);
if (!rstream.has_value()) {
return std::unexpected{std::move(rstream.error())};
}
auto wstream = driver.adopt_fd(write_fd);
if (!wstream.has_value()) {
// read_fd already owned by rstream (EpollDriver closes on destroy).
return std::unexpected{std::move(wstream.error())};
}
return DuplexTransport{std::move(*rstream),
std::move(*wstream),
PeerCredentials{.available = false}};
}
Void::Result::Result<std::pair<DuplexTransport, DuplexTransport>,
Void::Result::Error>
create_socket_pair_transports(Void::IO::Driver& driver)
{
auto pair = driver.create_socket_pair();
if (!pair.has_value()) {
return std::unexpected{std::move(pair.error())};
}
PeerCredentials self_creds;
self_creds.available = true;
self_creds.pid = static_cast<long long>(::getpid());
self_creds.uid = static_cast<unsigned long>(::geteuid());
self_creds.gid = static_cast<unsigned long>(::getegid());
return std::pair<DuplexTransport, DuplexTransport>{
DuplexTransport{std::move(pair->first), self_creds},
DuplexTransport{std::move(pair->second), self_creds}};
}
} // namespace Void::IPC
+3
View File
@@ -0,0 +1,3 @@
void_add_module(IPC
INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience
)
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidIPCOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS IPC)
add_executable(void_ipc_only_consumer main.cpp)
target_link_libraries(void_ipc_only_consumer PRIVATE Void::IPC)
target_compile_features(void_ipc_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME IPCOnlyConsumer COMMAND void_ipc_only_consumer)
+29
View File
@@ -0,0 +1,29 @@
#include <Void/Async/Executor.hpp>
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IPC/IPC.hpp>
int main()
{
Void::Binary::ByteBuffer buf{16};
(void)buf.writeString("hi");
auto encoded = Void::IPC::encode_frame(
Void::IPC::FrameHeader{.type = Void::IPC::FrameType::one_way,
.request_id = 0},
buf.view());
if (!encoded.has_value()) {
return 1;
}
Void::IPC::FrameDecoder dec;
auto decoded = dec.feed(encoded->view());
if (!decoded.has_value() || decoded->size() != 1) {
return 2;
}
Void::Async::ManualExecutor exec;
auto drv = Void::IO::Driver::create(exec);
if (!drv.has_value()) {
return 3;
}
(void)(*drv)->shutdown_and_join();
return 0;
}
+5
View File
@@ -136,6 +136,11 @@ if(_has_system_async)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_ipc IPC Core Functional Memory Time Binary Async IO Resilience ObservabilityHooks)
if(_has_ipc)
run_consumer(IPCOnly "${install_prefix}" "IPCOnly" ${_no_external_deps})
endif()
has_modules(_has_obs_hooks ObservabilityHooks)
if(_has_obs_hooks)
run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps})
+739
View File
@@ -0,0 +1,739 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IPC/IPC.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <array>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <format>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[nodiscard]] Void::Binary::FrozenBytes make_bytes(std::string_view sv)
{
Void::Binary::ByteBuffer buf{sv.size()};
(void)buf.writeString(sv);
return buf.freeze();
}
[[nodiscard]] std::string as_string(const Void::Binary::FrozenBytes& fb)
{
return std::string{reinterpret_cast<const char*>(fb.data()), fb.size()};
}
void pump_loop(Void::IO::Driver& driver,
Void::Async::ManualExecutor& exec,
Void::Async::TaskScope& scope,
int max_iters = 4000)
{
for (int i = 0; i < max_iters && scope.active_count() > 0; ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
const bool drained = (scope.active_count() == 0);
if (!drained) {
scope.request_stop();
for (int i = 0; i < 200 && scope.active_count() > 0; ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{0});
(void)exec.drain();
}
}
require(drained);
}
struct ShortIpcDir {
std::filesystem::path dir{};
ShortIpcDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
dir = std::filesystem::path{
std::format("/tmp/v_ipc_{}_{}", ::getpid(), id)};
std::filesystem::remove_all(dir);
require(::mkdir(dir.c_str(), 0700) == 0);
}
~ShortIpcDir()
{
std::error_code ec;
std::filesystem::remove_all(dir, ec);
}
ShortIpcDir(const ShortIpcDir&) = delete;
ShortIpcDir& operator=(const ShortIpcDir&) = delete;
};
[[nodiscard]] Void::Coro::Task<void> run_handshake_task(
Void::IPC::Session* sess,
Void::IPC::HelloInfo info,
Void::Async::OperationOptions opts,
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error>* out)
{
*out = co_await sess->handshake(std::move(info), std::move(opts));
}
[[nodiscard]] Void::Coro::Task<void> run_request_task(
Void::IPC::Session* sess,
Void::Binary::FrozenBytes req,
Void::Async::OperationOptions opts,
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure>* out)
{
*out = co_await sess->request(std::move(req), std::move(opts));
}
[[nodiscard]] Void::Coro::Task<void> run_close_session_task(
Void::IPC::Session* sess,
Void::Async::OperationOptions opts,
Void::Result::Result<void, Void::Result::Error>* out)
{
*out = co_await sess->close_and_join(std::move(opts));
}
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>
echo_upper_handler(Void::Binary::FrozenBytes payload, std::stop_token)
{
std::string s = as_string(payload);
for (char& ch : s) {
if (ch >= 'a' && ch <= 'z') {
ch = static_cast<char>(ch - 'a' + 'A');
}
}
co_return make_bytes(s);
}
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>
gated_echo_handler(
Void::Binary::FrozenBytes payload,
std::stop_token cancel,
std::shared_ptr<Void::Async::OperationState<void>> gate,
std::atomic<bool>* entered)
{
(void)cancel;
if (entered != nullptr) {
entered->store(true, std::memory_order_release);
}
(void)co_await gate->awaitable();
co_return payload;
}
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>
cancel_aware_wait_handler(Void::Binary::FrozenBytes payload,
std::stop_token cancel,
Void::Async::Executor* exec,
std::atomic<bool>* entered)
{
if (entered != nullptr) {
entered->store(true, std::memory_order_release);
}
auto op = Void::Async::OperationState<void>::create(
Void::Async::OperationOptions{.stop = cancel},
exec,
Void::Async::StopBehavior::settle_cancelled);
(void)co_await op->awaitable(exec);
co_return payload;
}
} // namespace
Void::Testing::Test ipc_wire_codec_fragmentation_coalescing_and_quotas()
{
// 1. V1 24B golden big-endian header + payload validation.
Void::IPC::FrameHeader hdr;
hdr.type = Void::IPC::FrameType::request;
hdr.request_id = 0x0102030405060708ULL;
auto f1 = Void::IPC::encode_frame(hdr, make_bytes("alpha").view());
require(f1.has_value());
expect_eq(f1->size(), Void::IPC::kFrameHeaderSize + std::size_t{5});
expect_eq(static_cast<char>((*f1).data()[0]), 'V');
expect_eq(static_cast<char>((*f1).data()[1]), 'D');
expect_eq(static_cast<char>((*f1).data()[2]), 'I');
expect_eq(static_cast<char>((*f1).data()[3]), 'P');
// Request/response/cancel require nonzero request_id; hello/one_way/goaway forbid it.
expect(!Void::IPC::validate_frame_header(
Void::IPC::FrameHeader{.type = Void::IPC::FrameType::request,
.request_id = 0},
Void::IPC::IpcLimits{})
.has_value());
expect(!Void::IPC::validate_frame_header(
Void::IPC::FrameHeader{.type = Void::IPC::FrameType::hello,
.request_id = 7},
Void::IPC::IpcLimits{})
.has_value());
expect(!Void::IPC::validate_frame_header(
Void::IPC::FrameHeader{.version = 99,
.type = Void::IPC::FrameType::request,
.request_id = 1},
Void::IPC::IpcLimits{})
.has_value());
expect(!Void::IPC::validate_frame_header(
Void::IPC::FrameHeader{.stream_id = 1,
.request_id = 1},
Void::IPC::IpcLimits{})
.has_value());
// 2. Fragmentation (1 byte at a time) + coalescing + exact global/session quota enforcement.
auto gq = Void::IPC::BufferQuota::create(128);
auto sq = Void::IPC::BufferQuota::create(128);
Void::IPC::IpcLimits lim;
lim.max_frame_payload = 64;
Void::IPC::FrameDecoder decoder{lim, gq, sq};
auto f2 = Void::IPC::encode_frame(
Void::IPC::FrameHeader{.type = Void::IPC::FrameType::response,
.request_id = 42},
make_bytes("beta").view());
require(f2.has_value());
std::vector<std::byte> combined;
combined.insert(combined.end(), f1->view().begin(), f1->view().end());
combined.insert(combined.end(), f2->view().begin(), f2->view().end());
std::vector<Void::IPC::DecodedFrame> out_frames;
for (std::size_t i = 0; i < combined.size(); ++i) {
auto fed = decoder.feed(std::span<const std::byte>{&combined[i], 1});
require(fed.has_value());
for (auto& df : *fed) {
out_frames.push_back(std::move(df));
}
}
require(out_frames.size() == 2);
expect_eq(as_string(out_frames[0].payload), std::string{"alpha"});
expect_eq(out_frames[1].header.request_id, std::uint64_t{42});
expect_eq(as_string(out_frames[1].payload), std::string{"beta"});
expect_eq(gq->used(),
Void::IPC::FrameDecoder::frame_quota_cost(5) +
Void::IPC::FrameDecoder::frame_quota_cost(4));
out_frames.clear();
expect_eq(gq->used(), std::size_t{0});
expect_eq(sq->used(), std::size_t{0});
// Oversize payload_len fails BEFORE reserving quota.
std::array<std::byte, Void::IPC::kFrameHeaderSize> big_hdr{};
require(Void::IPC::encode_frame_header(
Void::IPC::FrameHeader{.type = Void::IPC::FrameType::request,
.payload_len = 65,
.request_id = 9},
big_hdr)
.has_value());
Void::IPC::FrameDecoder oversize_dec{lim, gq, sq};
auto ov_res = oversize_dec.feed(big_hdr);
require(!ov_res.has_value());
expect_eq(ov_res.error().code().value,
static_cast<std::int32_t>(Void::IPC::IpcErrorCode::frame_too_large));
expect_eq(gq->used(), std::size_t{0});
}
Void::Testing::Test ipc_uds_security_stale_recovery_and_pipe_pair_session()
{
ShortIpcDir tmp;
Void::Async::ManualExecutor exec;
auto drv_res = Void::IO::Driver::create(exec);
require(drv_res.has_value());
auto& driver = **drv_res;
// 1. Reject >= 108B sun_path, 0755 dir, and symlink paths.
{
const std::string long_path = "/tmp/" + std::string(110, 'x') + ".sock";
auto r = Void::IPC::LocalListener::listen(long_path);
require(!r.has_value());
expect_eq(r.error().code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::invalid_argument));
}
{
const auto bad_dir = tmp.dir / "world";
require(::mkdir(bad_dir.c_str(), 0755) == 0);
(void)::chmod(bad_dir.c_str(), 0755);
auto r = Void::IPC::LocalListener::listen(bad_dir / "s.sock");
require(!r.has_value());
expect_eq(r.error().code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::permission_denied));
}
{
const auto priv_dir = tmp.dir / "priv";
require(::mkdir(priv_dir.c_str(), 0700) == 0);
const auto sym = priv_dir / "link.sock";
std::filesystem::create_symlink(tmp.dir / "missing", sym);
auto r = Void::IPC::LocalListener::listen(sym);
require(!r.has_value());
expect_eq(r.error().code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::permission_denied));
}
// 2. Stale socket recovery succeeds safely without disturbing active sockets.
const auto sock_path = tmp.dir / "svc.sock";
{
const int stale_fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
require(stale_fd >= 0);
sockaddr_un un{};
un.sun_family = AF_UNIX;
std::memcpy(un.sun_path, sock_path.native().data(), sock_path.native().size());
require(::bind(stale_fd,
reinterpret_cast<const sockaddr*>(&un),
static_cast<socklen_t>(
offsetof(sockaddr_un, sun_path) +
sock_path.native().size() + 1)) == 0);
::close(stale_fd); // leaves stale unbound/non-listening socket file!
}
auto listener_res = Void::IPC::LocalListener::listen(sock_path);
require(listener_res.has_value());
auto& listener = *listener_res;
struct stat sock_st {};
require(::lstat(sock_path.c_str(), &sock_st) == 0);
expect_eq(static_cast<unsigned>(sock_st.st_mode & 0777), 0600U);
// Live listener refuses second concurrent listener.
auto dup_listener = Void::IPC::LocalListener::listen(sock_path);
require(!dup_listener.has_value());
expect_eq(dup_listener.error().code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::already_exists));
// Wrong UID policy rejected cleanly on connect.
auto deny_res = Void::IPC::connect_local(
driver,
sock_path,
Void::IPC::PeerPolicy{.require_uid_match = true,
.set_allowed_uid_to_current_user = false,
.allowed_uid = ::geteuid() + 1000});
require(!deny_res.has_value());
expect_eq(deny_res.error().code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::permission_denied));
{
auto stale = listener.try_accept(driver);
(void)stale;
(void)driver.poll_once(std::chrono::milliseconds{0});
}
// Accept & full-duplex handshake + echo request over AF_UNIX.
auto client_tr = Void::IPC::connect_local(driver, sock_path);
require(client_tr.has_value());
auto server_opt = listener.try_accept(driver);
require(server_opt.has_value() && server_opt->has_value());
expect((*server_opt)->credentials().available);
Void::IPC::Session client_sess{driver, exec, std::move(*client_tr)};
Void::IPC::Session server_sess{driver, exec, std::move(**server_opt)};
require(server_sess
.start([](Void::Binary::FrozenBytes payload, std::stop_token st) {
return echo_upper_handler(std::move(payload), st);
})
.has_value());
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> h1;
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> h2;
{
Void::Async::TaskScope scope{exec};
require(scope
.spawn(run_handshake_task(&client_sess, {}, {}, &h1))
.has_value());
require(scope
.spawn(run_handshake_task(&server_sess, {}, {}, &h2))
.has_value());
pump_loop(driver, exec, scope);
}
require(h1.has_value() && h2.has_value());
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure> rpc_out{
std::unexpected{Void::IPC::CallFailure{}}};
{
Void::Async::TaskScope scope{exec};
require(scope
.spawn(run_request_task(
&client_sess, make_bytes("hello_uds"), {}, &rpc_out))
.has_value());
pump_loop(driver, exec, scope);
}
require(rpc_out.has_value());
expect_eq(as_string(*rpc_out), std::string{"HELLO_UDS"});
Void::Result::Result<void, Void::Result::Error> c1;
Void::Result::Result<void, Void::Result::Error> c2;
{
Void::Async::TaskScope scope{exec};
require(scope.spawn(run_close_session_task(&client_sess, {}, &c1))
.has_value());
require(scope.spawn(run_close_session_task(&server_sess, {}, &c2))
.has_value());
pump_loop(driver, exec, scope);
}
require(c1.has_value() && c2.has_value());
listener.close();
// 3. adopt_pipe_pair with supervised VoidProcessHelper ipc-pipe-echo child.
int to_child[2]{-1, -1};
int from_child[2]{-1, -1};
require(::pipe2(to_child, O_CLOEXEC) == 0);
require(::pipe2(from_child, O_CLOEXEC) == 0);
const pid_t cpid = ::fork();
require(cpid >= 0);
if (cpid == 0) {
::dup2(to_child[0], STDIN_FILENO);
::dup2(from_child[1], STDOUT_FILENO);
::close(to_child[0]);
::close(to_child[1]);
::close(from_child[0]);
::close(from_child[1]);
const std::string helper = VOID_PROCESS_HELPER_PATH;
char arg0[] = "VoidProcessHelper";
char arg1[] = "ipc-pipe-echo";
char* argv[] = {arg0, arg1, nullptr};
::execv(helper.c_str(), argv);
::_exit(127);
}
::close(to_child[0]);
::close(from_child[1]);
auto pipe_tr = Void::IPC::adopt_pipe_pair(driver, from_child[0], to_child[1]);
require(pipe_tr.has_value());
expect(!pipe_tr->credentials().available);
Void::IPC::Session pipe_sess{driver, exec, std::move(*pipe_tr)};
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> ph;
{
Void::Async::TaskScope scope{exec};
require(scope
.spawn(run_handshake_task(&pipe_sess, {}, {}, &ph))
.has_value());
pump_loop(driver, exec, scope);
}
require(ph.has_value());
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure> pipe_reply{
std::unexpected{Void::IPC::CallFailure{}}};
{
Void::Async::TaskScope scope{exec};
require(scope
.spawn(run_request_task(
&pipe_sess, make_bytes("pipe_echo_ok"), {}, &pipe_reply))
.has_value());
pump_loop(driver, exec, scope);
}
require(pipe_reply.has_value());
expect_eq(as_string(*pipe_reply), std::string{"pipe_echo_ok"});
{
Void::Result::Result<void, Void::Result::Error> pc;
Void::Async::TaskScope scope{exec};
require(scope
.spawn(run_close_session_task(&pipe_sess, {}, &pc))
.has_value());
pump_loop(driver, exec, scope);
require(pc.has_value());
}
int cstat = 0;
while (::waitpid(cpid, &cstat, 0) < 0 && errno == EINTR) {
}
expect(WIFEXITED(cstat) && WEXITSTATUS(cstat) == 0);
(void)driver.shutdown_and_join();
}
Void::Testing::Test ipc_session_control_lane_timeouts_tombstones_and_disconnect()
{
Void::Async::ManualExecutor exec;
Void::Time::ManualClock clock{
Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}};
auto drv_res =
Void::IO::Driver::create(exec, Void::IO::BackendOptions{}, clock);
require(drv_res.has_value());
auto& driver = **drv_res;
// 1. Handshake timeout via injected ManualClock.
{
auto pair = Void::IPC::create_socket_pair_transports(driver);
require(pair.has_value());
Void::IPC::IpcLimits lim;
lim.handshake_timeout = std::chrono::milliseconds{100};
Void::IPC::Session client{driver, exec, std::move(pair->first), lim, clock};
Void::IPC::Session silent_server{
driver, exec, std::move(pair->second), lim, clock};
(void)silent_server;
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> hs_res;
Void::Async::TaskScope scope{exec, {}, clock};
require(scope.spawn(run_handshake_task(&client, {}, {}, &hs_res))
.has_value());
for (int i = 0; i < 4; ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{0});
(void)exec.drain();
}
(void)clock.advance(std::chrono::milliseconds{150});
pump_loop(driver, exec, scope, 200);
require(!hs_res.has_value());
expect_eq(hs_res.error().code().value,
static_cast<std::int32_t>(Void::IPC::IpcErrorCode::timed_out));
}
// 2. Saturated handlers + reserved control-lane overload + late response tombstone + cancel.
{
auto pair = Void::IPC::create_socket_pair_transports(driver);
require(pair.has_value());
Void::IPC::IpcLimits lim;
lim.max_active_handlers = 1;
lim.max_outbound_frames = 32;
lim.rate_limit_burst = 64.0;
lim.rate_limit_per_sec = 10000.0;
Void::IPC::Session client{driver, exec, std::move(pair->first), lim, clock};
Void::IPC::Session server{driver, exec, std::move(pair->second), lim, clock};
auto gate = Void::Async::OperationState<void>::create({}, &exec);
std::atomic<bool> gate_acquired{false};
require(server
.start([gate, &gate_acquired](
Void::Binary::FrozenBytes payload,
std::stop_token cancel) {
return gated_echo_handler(
std::move(payload), cancel, gate, &gate_acquired);
})
.has_value());
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> h1;
Void::Result::Result<Void::IPC::HelloInfo, Void::Result::Error> h2;
{
Void::Async::TaskScope scope{exec, {}, clock};
require(scope.spawn(run_handshake_task(&client, {}, {}, &h1))
.has_value());
require(scope.spawn(run_handshake_task(&server, {}, {}, &h2))
.has_value());
pump_loop(driver, exec, scope);
}
require(h1.has_value() && h2.has_value());
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure> slow_call{
std::unexpected{Void::IPC::CallFailure{}}};
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure> ov_call{
std::unexpected{Void::IPC::CallFailure{}}};
Void::Async::TaskScope scope{exec, {}, clock};
gate->acquire_backend_ref();
require(scope
.spawn(run_request_task(
&client,
make_bytes("slow_one"),
Void::Async::OperationOptions{
.deadline =
clock.now() + std::chrono::milliseconds{100}},
&slow_call))
.has_value());
// Pump until server handler enters gate.
for (int i = 0; i < 400 && !gate_acquired.load(); ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
require(gate_acquired.load());
// 2nd concurrent request hits max_active_handlers == 1 -> immediate control-lane overloaded error!
require(scope
.spawn(run_request_task(&client, make_bytes("second"), {}, &ov_call))
.has_value());
for (int i = 0; i < 400 && ov_call.error().error.message().empty(); ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
require(!ov_call.has_value());
expect_eq(ov_call.error().error.code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::overloaded));
expect(ov_call.error().effect == Void::IPC::EffectStatus::not_sent);
// Advance ManualClock so slow_call times out cleanly -> EffectStatus::unknown & tombstone added.
(void)clock.advance(std::chrono::milliseconds{150});
for (int i = 0; i < 400 && slow_call.error().error.message().empty();
++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
require(!slow_call.has_value());
expect_eq(slow_call.error().error.code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::timed_out));
expect(slow_call.error().effect == Void::IPC::EffectStatus::unknown);
expect(slow_call.error().may_have_executed);
// Release server handler -> late response arrives and is dropped cleanly via tombstone!
if (auto t = gate->try_commit_value(); t.has_value()) {
t->dispatch();
}
gate->release_backend_ref_and_dispatch();
for (int i = 0;
i < 400 && client.stats().late_responses_dropped == 0;
++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
pump_loop(driver, exec, scope);
expect(client.stats().late_responses_dropped >= 1);
// Self-join rejected inside synchronous OneWayHandler.
std::optional<Void::Result::Error> self_join_err;
Void::IPC::Session* client_ptr = &client;
require(client
.start(echo_upper_handler,
[client_ptr, &self_join_err](
Void::Binary::FrozenBytes) {
auto task = client_ptr->close_and_join();
auto res = task.run();
if (!res.has_value()) {
self_join_err = res.error();
}
})
.has_value());
require(server.send_one_way(make_bytes("trigger_sj")).has_value());
for (int i = 0; i < 400 && !self_join_err.has_value(); ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
require(self_join_err.has_value());
expect_eq(self_join_err->code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::self_join));
// Peer disconnect faults in-flight request once with transport_lost + unknown.
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure> disc_call{
std::unexpected{Void::IPC::CallFailure{}}};
std::atomic<bool> entered_stuck{false};
require(server
.start([&exec, &entered_stuck](
Void::Binary::FrozenBytes payload,
std::stop_token cancel) {
return cancel_aware_wait_handler(
std::move(payload), cancel, &exec, &entered_stuck);
})
.has_value());
Void::Async::TaskScope dc_scope{exec, {}, clock};
require(dc_scope
.spawn(run_request_task(
&client, make_bytes("in_flight"), {}, &disc_call))
.has_value());
for (int i = 0; i < 400 && !entered_stuck.load(); ++i) {
(void)exec.drain();
(void)driver.poll_once(std::chrono::milliseconds{1});
(void)exec.drain();
}
require(entered_stuck.load());
// Close server cleanly while client has an unfulfilled request -> client sees transport_lost / closed.
Void::Result::Result<void, Void::Result::Error> s_close;
require(dc_scope
.spawn(run_close_session_task(&server, {}, &s_close))
.has_value());
pump_loop(driver, exec, dc_scope);
require(!disc_call.has_value());
expect(disc_call.error().error.code().value ==
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::transport_lost) ||
disc_call.error().error.code().value ==
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::closed));
expect(disc_call.error().effect == Void::IPC::EffectStatus::unknown);
expect(disc_call.error().may_have_executed);
// Rate limit rejects bursts beyond token bucket capacity via control lane.
{
auto rpair = Void::IPC::create_socket_pair_transports(driver);
require(rpair.has_value());
Void::IPC::IpcLimits rlim;
rlim.rate_limit_burst = 1.0;
rlim.rate_limit_per_sec = 0.001;
Void::IPC::Session rcli{
driver, exec, std::move(rpair->first), rlim, clock};
Void::IPC::Session rsrv{
driver, exec, std::move(rpair->second), rlim, clock};
require(rsrv.start(echo_upper_handler).has_value());
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure>
rok{std::unexpected{Void::IPC::CallFailure{}}};
std::expected<Void::Binary::FrozenBytes, Void::IPC::CallFailure>
rlim_res{std::unexpected{Void::IPC::CallFailure{}}};
Void::Async::TaskScope rscope{exec, {}, clock};
require(rscope
.spawn(run_request_task(
&rcli, make_bytes("ok"), {}, &rok))
.has_value());
require(rscope
.spawn(run_request_task(
&rcli, make_bytes("excess"), {}, &rlim_res))
.has_value());
pump_loop(driver, exec, rscope);
require(rok.has_value());
expect_eq(as_string(*rok), std::string{"OK"});
require(!rlim_res.has_value());
expect_eq(rlim_res.error().error.code().value,
static_cast<std::int32_t>(
Void::IPC::IpcErrorCode::rate_limited));
expect(rlim_res.error().effect == Void::IPC::EffectStatus::not_sent);
Void::Result::Result<void, Void::Result::Error> rc1;
Void::Result::Result<void, Void::Result::Error> rc2;
Void::Async::TaskScope rc_scope{exec, {}, clock};
require(rc_scope.spawn(run_close_session_task(&rcli, {}, &rc1))
.has_value());
require(rc_scope.spawn(run_close_session_task(&rsrv, {}, &rc2))
.has_value());
pump_loop(driver, exec, rc_scope);
require(rc1.has_value() && rc2.has_value());
}
Void::Result::Result<void, Void::Result::Error> c_close;
Void::Async::TaskScope fin_scope{exec, {}, clock};
require(fin_scope
.spawn(run_close_session_task(&client, {}, &c_close))
.has_value());
pump_loop(driver, exec, fin_scope);
}
(void)driver.shutdown_and_join();
}