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:
1 parent
9a3c5d86ef
commit
39a48d5c0a
13 files changed
+4187
No files matched your search
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(IPC
|
||||
INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience
|
||||
)
|
||||
Reference in new issue
Block a user