Windows: full module parity and runtime-qualified test suite
- Net/IO: Winsock sockets (UdpSocket, TlsClientStream, WebSocketClient), HttpServer port with a loopback wake socket replacing eventfd, and the select-based IO backend built on Windows (ws2_32). - Net: implement StaticFileResolver::open_safe and OpenedStaticFile on Windows (reparse-point rejection plus canonical containment check on the opened handle) and widen native handles to intptr_t. - Plugin: hot reload works on Windows by loading a fresh copy while the old DLL stays mapped; enable the reload, discovery and FSM service reload tests and retire the plugin file by rename instead of replacement. - Update: activation pointer as a directory junction on Windows. - Stacktrace: portable path comparison for wide native strings. - Docs/targets: every module allowlisted on Windows; record the Wine run (2000 tests, 1977 passed, 23 skipped, 0 failed). - CMake: add -Wa,-mbig-obj for GNU MinGW targets (COFF section limit). - Async: fix the FuturePool stopped-after-close test to wait for the executor to release its admission slot instead of racing it. Windows and Linux suites both pass: Windows 2000/1977/23 skips/0 failed, Linux 2027/2023/4 skips/0 failed.
This commit is contained in:
1 parent
1b1947340f
commit
b3c959b920
32 files changed
+1836
-401
No files matched your search
@@ -36,6 +36,11 @@ set(CXX_SCAN_FOR_MODULES OFF)
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
|
||||
endif()
|
||||
# PE/COFF objects are limited to 65535 sections and GNU as fails earlier
|
||||
# ("too many sections" / "file too big") on large generated test units.
|
||||
if(MINGW AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-Wa,-mbig-obj>)
|
||||
endif()
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(CMakePackageConfigHelpers)
|
||||
|
||||
@@ -50,9 +50,8 @@ Format code with `clang-format -i <file>`.
|
||||
|
||||
## Supported targets
|
||||
|
||||
Void is qualified per target profile: Linux (reference), Linux/musl, the
|
||||
Windows client subset, and a browser/Wasm subset of the pure computation
|
||||
modules. The profile is detected from the toolchain, validated against the
|
||||
Void is qualified per target profile: Linux (reference), Linux/musl, Windows,
|
||||
and a browser/Wasm subset of the pure computation modules. The profile is detected from the toolchain, validated against the
|
||||
selected modules, and recorded in `void-target-manifest.cmake`. See
|
||||
[docs/targets.md](docs/targets.md) for the exact compiler/standard-library
|
||||
tuples, module allowlists and qualification status.
|
||||
|
||||
+4
-2
@@ -18,12 +18,14 @@ function(void_add_module MODULE_NAME)
|
||||
# on the global source layout.
|
||||
if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32)
|
||||
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32)
|
||||
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||
list(REMOVE_ITEM SRC
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/${_excl}")
|
||||
endforeach()
|
||||
endif()
|
||||
if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX)
|
||||
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX)
|
||||
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||
list(REMOVE_ITEM SRC
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/${_excl}")
|
||||
endforeach()
|
||||
endif()
|
||||
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
|
||||
|
||||
+13
-4
@@ -39,10 +39,10 @@ set(VOID_WASM_MODULES
|
||||
Unicode
|
||||
)
|
||||
|
||||
# Windows client subset: modules qualified with x86_64-w64-mingw32 (MinGW-w64).
|
||||
# Filled from the cross-build and Wine runtime observations in
|
||||
# docs/targets.md. IO is deliberately absent: it builds on Windows but its
|
||||
# native backend is Linux-only (EpollBackend), so only the mock backend works.
|
||||
# Windows: every module under src/ is qualified with x86_64-w64-mingw32
|
||||
# (MinGW-w64), cross-built and run under Wine; see docs/targets.md. IO's
|
||||
# native backend is the select-based Windows backend (EpollDriver.cpp), not
|
||||
# IOCP, which remains a separate task.
|
||||
set(VOID_WINDOWS_MODULES
|
||||
Algorithms
|
||||
Archive
|
||||
@@ -56,7 +56,15 @@ set(VOID_WINDOWS_MODULES
|
||||
MCP
|
||||
Resilience
|
||||
ResilienceAsync
|
||||
RPC
|
||||
DiscoveryRpc
|
||||
MessagingRpc
|
||||
Script
|
||||
Security
|
||||
SecurityAsync
|
||||
ShortUrlRemote
|
||||
ShortUrlStorage
|
||||
Stacktrace
|
||||
SystemAsync
|
||||
Core
|
||||
Crypto
|
||||
@@ -76,6 +84,7 @@ set(VOID_WINDOWS_MODULES
|
||||
Math
|
||||
Memory
|
||||
Messaging
|
||||
Net
|
||||
Observability
|
||||
ObservabilityHooks
|
||||
Plugin
|
||||
|
||||
@@ -25,8 +25,8 @@ transport-neutral components, not an HTTP listener or a WebSocket framing engine
|
||||
Static resolution rejects traversal and canonical symlink escapes but returns a path;
|
||||
opening that path later needs protection against filesystem replacement races.
|
||||
[Socket.hpp](../../../include/Void/Net/Socket.hpp) and
|
||||
[Socket.cpp](../../../src/Net/Socket.cpp) implement connected blocking UDP on POSIX;
|
||||
Windows operations report unsupported. `wait_readable` uses poll.
|
||||
[Socket.cpp](../../../src/Net/Socket.cpp) implement connected blocking UDP on
|
||||
POSIX and Windows (Winsock, `WSAPoll` for `wait_readable`).
|
||||
[Url.hpp](../../../include/Void/Net/Url.hpp) / [Url.cpp](../../../src/Net/Url.cpp)
|
||||
use Boost.URL and accept URI references as well as absolute URIs.
|
||||
|
||||
|
||||
+23
-15
@@ -98,7 +98,7 @@ Detection uses `CMAKE_C_COMPILER -dumpmachine` (or
|
||||
recognized and configured like Linux; musl-specific behaviour (subprocess
|
||||
`/proc`, `dl`, locale) must still be verified before claiming full support.
|
||||
|
||||
### Windows client (compile/install/consume + Wine runtime qualified)
|
||||
### Windows (compile/install/consume + Wine runtime qualified)
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
@@ -108,14 +108,15 @@ recognized and configured like Linux; musl-specific behaviour (subprocess
|
||||
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
|
||||
| Language | C++26, reflection `yes` |
|
||||
| Runtime | Wine 11.0 (`wine64`), no native Windows runner available |
|
||||
| Modules | `Algorithms Archive Async Binary Configuration ConfigurationAsync Containers Core Crypto CryptoAsync Data Discovery Fsm Functional FunctionalCoreFormatting IO IPC Log LogConfig LogState MCP Math Memory Messaging MessagingStorage Observability ObservabilityHooks Plugin Resilience ResilienceAsync Runtime Scheduler SchedulerStorage Script Service ServicePlugin ShortUrl Sqlite SqliteAsync Storage System SystemAsync Testing TestingMock Text Time Unicode Update` |
|
||||
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); each module's suite is verified under Wine before it is allowlisted. Full allowlisted set in one binary (Release) under Wine: **1851 tests, 1826 passed, 25 skipped, 0 failed** |
|
||||
| Modules | all modules under `src/` (`VOID_WINDOWS_MODULES` in `cmake/Targets.cmake`) |
|
||||
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); each module's suite is verified under Wine before it is allowlisted. Full allowlisted set in one Debug shared binary (MinGW-w64 GCC 16.2.0) under Wine 11: **2000 tests, 1977 passed, 23 skipped, 0 failed** |
|
||||
|
||||
Notes from the runtime run:
|
||||
|
||||
- `IO` uses the select-based Windows backend on Windows (the native epoll
|
||||
backend is Linux-only) with positional-file workers over the CRT; a native
|
||||
IOCP backend is still a separate task.
|
||||
- `IO` builds `EpollDriver.cpp` on every platform: it contains the Linux
|
||||
epoll backend and the Windows select-based backend. Windows also uses
|
||||
positional-file workers over the CRT; a native IOCP backend is still a
|
||||
separate task.
|
||||
- `Configuration`, `Crypto`, `System` and `Archive` are allowlisted and
|
||||
cross-compile; `System` links `winmm` for the Win32 audio backend. Archive's
|
||||
staging implementation keeps its POSIX logic and runs on Windows through a
|
||||
@@ -139,13 +140,19 @@ Notes from the runtime run:
|
||||
`_commit` instead of `fsync`); its OpenSSL-signed feed fixtures are gated by
|
||||
`// @requires-openssl`, and the compressed-package fixture skips when the
|
||||
Archive backend has no LibArchive.
|
||||
- Still outside the Windows allowlist:
|
||||
`ShortUrlStorage` (needs `Security`), `Net`,
|
||||
`RPC`, `DiscoveryRpc`, `MessagingRpc`, `Security`, `SecurityAsync`,
|
||||
`ShortUrlRemote`, `Stacktrace` (external dependencies not yet
|
||||
built for Windows in the qualification environment).
|
||||
- Plugin hot-reload/discovery tests skip on Windows (loaded DLLs cannot be
|
||||
unloaded and replaced yet), and the C ABI plugin fixtures are POSIX-only.
|
||||
- `Net` is fully allowlisted on Windows: `UdpSocket`, `TlsClientStream` and
|
||||
`WebSocketClient` use Winsock/WSAPoll, and `HttpServer` is ported to
|
||||
Winsock with a loopback wake socket replacing `eventfd`. The RPC family
|
||||
(`RPC`, `DiscoveryRpc`, `MessagingRpc`) and `ShortUrlRemote` therefore link
|
||||
on Windows too.
|
||||
- `Stacktrace` builds with Boost.Stacktrace's `windbg` backend on Windows,
|
||||
`Security`/`SecurityAsync`/`ShortUrlStorage` link the cross-built
|
||||
libsodium, and `ShortUrlRemote` links the Windows `Net` client/server.
|
||||
- Plugin hot-reload and discovery tests run on Windows: a new generation is
|
||||
loaded from a fresh copy while the old DLL stays mapped, and the plugin file
|
||||
is retired by rename instead of in-place replacement. The C ABI plugin
|
||||
fixtures remain POSIX-only, and the reload-under-load stress test is still
|
||||
gated.
|
||||
- `Observability` links after replacing the namespace-scope
|
||||
`inline thread_local` hook stack with a function-local `thread_local`
|
||||
accessor (MinGW emitted duplicate TLS init functions).
|
||||
@@ -153,8 +160,9 @@ Notes from the runtime run:
|
||||
Log hardening test closes its `ifstream` before removing the file, and the
|
||||
subprocess-isolation test skips when `current_executable_path()` is not
|
||||
implemented (Windows has no subprocess isolation yet).
|
||||
- MinGW test builds need `-Wa,-mbig-obj`: the Fsm hardening test TU exceeds
|
||||
the COFF section limit with the default object format.
|
||||
- MinGW test builds use `-Wa,-mbig-obj` (added automatically for GNU targets):
|
||||
the Fsm hardening test TU exceeds the COFF section limit with the default
|
||||
object format.
|
||||
- Runtime observations come from Wine, not a native Windows runner; a
|
||||
Windows CI runner should confirm them.
|
||||
|
||||
|
||||
@@ -108,6 +108,14 @@ namespace Void::Net
|
||||
std::vector<Route> routes_;
|
||||
};
|
||||
|
||||
/// Native file handle: a POSIX file descriptor or, on Windows, a
|
||||
/// cast `HANDLE`. `-1` means closed on both platforms.
|
||||
#if defined(_WIN32)
|
||||
using NativeFileHandle = std::intptr_t;
|
||||
#else
|
||||
using NativeFileHandle = int;
|
||||
#endif
|
||||
|
||||
struct StaticFile {
|
||||
std::filesystem::path path;
|
||||
std::string_view content_type;
|
||||
@@ -115,13 +123,16 @@ namespace Void::Net
|
||||
};
|
||||
|
||||
/// Move-only RAII handle for a regular file opened beneath a pinned root
|
||||
/// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU).
|
||||
/// directory handle and verified to stay inside it (zero TOCTOU on POSIX
|
||||
/// via `openat(..., O_NOFOLLOW)`; on Windows via reparse-point rejection
|
||||
/// plus a final canonical-path containment check on the opened handle).
|
||||
class OpenedStaticFile final
|
||||
{
|
||||
public:
|
||||
|
||||
OpenedStaticFile() noexcept = default;
|
||||
OpenedStaticFile(int fd, std::filesystem::path relative_path,
|
||||
OpenedStaticFile(NativeFileHandle fd,
|
||||
std::filesystem::path relative_path,
|
||||
std::string_view content_type,
|
||||
std::uint64_t size) noexcept;
|
||||
~OpenedStaticFile() noexcept;
|
||||
@@ -132,7 +143,10 @@ namespace Void::Net
|
||||
OpenedStaticFile& operator=(const OpenedStaticFile&) = delete;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
|
||||
[[nodiscard]] int native_handle() const noexcept { return fd_; }
|
||||
[[nodiscard]] NativeFileHandle native_handle() const noexcept
|
||||
{
|
||||
return fd_;
|
||||
}
|
||||
[[nodiscard]] const std::filesystem::path&
|
||||
relative_path() const noexcept
|
||||
{
|
||||
@@ -151,7 +165,7 @@ namespace Void::Net
|
||||
|
||||
private:
|
||||
|
||||
int fd_{-1};
|
||||
NativeFileHandle fd_{-1};
|
||||
std::filesystem::path relative_path_{};
|
||||
std::string_view content_type_{};
|
||||
std::uint64_t size_{0};
|
||||
@@ -188,8 +202,8 @@ namespace Void::Net
|
||||
private:
|
||||
|
||||
struct DirHandle {
|
||||
int fd{-1};
|
||||
explicit DirHandle(int d) noexcept : fd(d) {}
|
||||
NativeFileHandle fd{-1};
|
||||
explicit DirHandle(NativeFileHandle d) noexcept : fd(d) {}
|
||||
~DirHandle() noexcept;
|
||||
DirHandle(const DirHandle&) = delete;
|
||||
DirHandle& operator=(const DirHandle&) = delete;
|
||||
|
||||
@@ -13,6 +13,14 @@ namespace Void::Net
|
||||
class UdpSocket final
|
||||
{
|
||||
public:
|
||||
// Native socket handles are int on POSIX and SOCKET (an unsigned
|
||||
// pointer-sized value) on Windows.
|
||||
#ifdef _WIN32
|
||||
using NativeHandle = std::intptr_t;
|
||||
#else
|
||||
using NativeHandle = int;
|
||||
#endif
|
||||
|
||||
UdpSocket() noexcept = default;
|
||||
~UdpSocket();
|
||||
UdpSocket(UdpSocket&& other) noexcept;
|
||||
@@ -23,7 +31,10 @@ namespace Void::Net
|
||||
[[nodiscard]] static Void::Result::Result<UdpSocket, Void::Result::Error>
|
||||
connect(std::string_view host, std::uint16_t port);
|
||||
[[nodiscard]] bool valid() const noexcept { return handle_ >= 0; }
|
||||
[[nodiscard]] int native_handle() const noexcept { return handle_; }
|
||||
[[nodiscard]] NativeHandle native_handle() const noexcept
|
||||
{
|
||||
return handle_;
|
||||
}
|
||||
void close() noexcept;
|
||||
void shutdown() noexcept;
|
||||
[[nodiscard]] Void::Result::Result<bool, Void::Result::Error>
|
||||
@@ -34,7 +45,7 @@ namespace Void::Net
|
||||
receive(std::span<std::uint8_t> destination);
|
||||
|
||||
private:
|
||||
explicit UdpSocket(int handle) noexcept : handle_(handle) {}
|
||||
int handle_{-1};
|
||||
explicit UdpSocket(NativeHandle handle) noexcept : handle_(handle) {}
|
||||
NativeHandle handle_{-1};
|
||||
};
|
||||
}
|
||||
+2
-4
@@ -1,8 +1,6 @@
|
||||
void_add_module(IO
|
||||
INTERNAL_DEPS Core Functional Time Memory Async
|
||||
# The native epoll driver only builds on Linux/Unix; Windows uses the
|
||||
# select-based backend and needs winsock.
|
||||
EXCLUDE_SOURCES_WIN32
|
||||
EpollDriver.cpp
|
||||
# EpollDriver.cpp holds both the Linux epoll backend and the Windows
|
||||
# select-based backend, so it is built on every platform.
|
||||
DEPS_WIN32 ws2_32
|
||||
)
|
||||
+66
-14
@@ -501,6 +501,25 @@ namespace Void::Net
|
||||
}
|
||||
}
|
||||
|
||||
// Interrupts an in-flight blocking operation on the socket from another
|
||||
// thread. On Windows, CancelIoEx aborts the pending overlapped I/O
|
||||
// (shutdown alone does not reliably wake an Asio synchronous read);
|
||||
// shutdown is still issued so the peer sees a half-close.
|
||||
void interrupt_socket(std::intptr_t fd) noexcept
|
||||
{
|
||||
if (fd < 0) {
|
||||
return;
|
||||
}
|
||||
#if defined(_WIN32)
|
||||
(void)::CancelIoEx(
|
||||
reinterpret_cast<HANDLE>(static_cast<std::uintptr_t>(fd)),
|
||||
nullptr);
|
||||
(void)::shutdown(static_cast<SOCKET>(fd), SD_BOTH);
|
||||
#else
|
||||
(void)::shutdown(static_cast<int>(fd), SHUT_RDWR);
|
||||
#endif
|
||||
}
|
||||
|
||||
class DeadlineGuard
|
||||
{
|
||||
public:
|
||||
@@ -513,24 +532,40 @@ namespace Void::Net
|
||||
StopShutdown{
|
||||
&m_cancelled,
|
||||
socket.is_open()
|
||||
? socket.native_handle()
|
||||
: tcp::socket::native_handle_type{},
|
||||
? static_cast<std::intptr_t>(
|
||||
socket.native_handle())
|
||||
: std::intptr_t{-1},
|
||||
socket.is_open()})
|
||||
{
|
||||
if (!socket.is_open() ||
|
||||
timeout <= std::chrono::seconds::zero()) {
|
||||
return;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
// Winsock blocking reads honour SO_RCVTIMEO/SO_SNDTIMEO even
|
||||
// when the watchdog shutdown races the I/O call.
|
||||
const auto bounded = std::chrono::duration_cast<
|
||||
std::chrono::milliseconds>(timeout)
|
||||
.count();
|
||||
DWORD wait_ms = static_cast<DWORD>(
|
||||
std::clamp<long long>(bounded, 1, 0xFFFFFFFF));
|
||||
(void)::setsockopt(
|
||||
static_cast<SOCKET>(socket.native_handle()), SOL_SOCKET,
|
||||
SO_RCVTIMEO,
|
||||
reinterpret_cast<const char*>(&wait_ms),
|
||||
sizeof(wait_ms));
|
||||
(void)::setsockopt(
|
||||
static_cast<SOCKET>(socket.native_handle()), SOL_SOCKET,
|
||||
SO_SNDTIMEO,
|
||||
reinterpret_cast<const char*>(&wait_ms),
|
||||
sizeof(wait_ms));
|
||||
#endif
|
||||
const auto fd = socket.native_handle();
|
||||
m_worker = std::thread([this, fd, timeout] {
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (!m_cv.wait_for(lock, timeout,
|
||||
[this] { return m_done; })) {
|
||||
#if defined(_WIN32)
|
||||
::shutdown(fd, SD_BOTH);
|
||||
#else
|
||||
::shutdown(fd, SHUT_RDWR);
|
||||
#endif
|
||||
interrupt_socket(fd);
|
||||
m_timed_out.store(true, std::memory_order_release);
|
||||
}
|
||||
});
|
||||
@@ -565,7 +600,7 @@ namespace Void::Net
|
||||
|
||||
struct StopShutdown {
|
||||
std::atomic<bool>* cancelled{nullptr};
|
||||
tcp::socket::native_handle_type fd{};
|
||||
std::intptr_t fd{-1};
|
||||
bool has_fd{false};
|
||||
|
||||
void operator()() const noexcept
|
||||
@@ -575,11 +610,7 @@ namespace Void::Net
|
||||
std::memory_order_release);
|
||||
}
|
||||
if (has_fd) {
|
||||
#if defined(_WIN32)
|
||||
::shutdown(fd, SD_BOTH);
|
||||
#else
|
||||
::shutdown(fd, SHUT_RDWR);
|
||||
#endif
|
||||
interrupt_socket(fd);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -948,7 +979,13 @@ namespace Void::Net
|
||||
const std::size_t want = static_cast<std::size_t>(
|
||||
std::min<std::uint64_t>(buf.size(),
|
||||
file_size - sent_total));
|
||||
const ssize_t r = ::read(file_fd, buf.data(), want);
|
||||
const std::ptrdiff_t r =
|
||||
#ifdef _WIN32
|
||||
::_read(file_fd, buf.data(),
|
||||
static_cast<unsigned int>(want));
|
||||
#else
|
||||
::read(file_fd, buf.data(), want);
|
||||
#endif
|
||||
if (r < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
@@ -1402,7 +1439,12 @@ namespace Void::Net
|
||||
make_net_error(NetErrorCode::cancelled, "Net: upload cancelled")};
|
||||
}
|
||||
const int raw_fd =
|
||||
#ifdef _WIN32
|
||||
::_open(source_path.string().c_str(),
|
||||
_O_RDONLY | _O_BINARY | _O_NOINHERIT);
|
||||
#else
|
||||
::open(source_path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
#endif
|
||||
if (raw_fd < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
@@ -1414,12 +1456,22 @@ namespace Void::Net
|
||||
int fd;
|
||||
~FdClose() noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (fd >= 0) (void)::_close(fd);
|
||||
#else
|
||||
if (fd >= 0) (void)::close(fd);
|
||||
#endif
|
||||
}
|
||||
} fd_guard{raw_fd};
|
||||
|
||||
#ifdef _WIN32
|
||||
struct _stat64 st{};
|
||||
if (::_fstat64(raw_fd, &st) != 0 ||
|
||||
(st.st_mode & _S_IFREG) == 0) {
|
||||
#else
|
||||
struct stat st{};
|
||||
if (::fstat(raw_fd, &st) != 0 || !S_ISREG(st.st_mode)) {
|
||||
#endif
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
std::format("Net: upload source '{}' is not a regular file",
|
||||
|
||||
+365
-62
@@ -1,5 +1,39 @@
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <process.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <climits>
|
||||
|
||||
using socklen_t = int;
|
||||
using ssize_t = std::ptrdiff_t;
|
||||
|
||||
inline int poll(::pollfd* descriptors, std::size_t count, int timeout)
|
||||
{
|
||||
return ::WSAPoll(descriptors, static_cast<ULONG>(count), timeout);
|
||||
}
|
||||
|
||||
#ifndef MSG_NOSIGNAL
|
||||
#define MSG_NOSIGNAL 0
|
||||
#endif
|
||||
#ifndef SHUT_RDWR
|
||||
#define SHUT_RDWR SD_BOTH
|
||||
#endif
|
||||
#ifndef SHUT_WR
|
||||
#define SHUT_WR SD_SEND
|
||||
#endif
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
@@ -9,6 +43,7 @@
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -18,6 +53,7 @@
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
@@ -38,6 +74,189 @@ namespace Void::Net
|
||||
{
|
||||
std::atomic<std::uint64_t> g_temp_upload_seq{0};
|
||||
|
||||
void close_socket_fd(int fd) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (fd >= 0) (void)::closesocket(static_cast<SOCKET>(fd));
|
||||
#else
|
||||
if (fd >= 0) (void)::close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] int last_socket_error() noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::WSAGetLastError();
|
||||
#else
|
||||
return errno;
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_interrupted(int code) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return code == WSAEINTR;
|
||||
#else
|
||||
return code == EINTR;
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_would_block(int code) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return code == WSAEWOULDBLOCK;
|
||||
#else
|
||||
return code == EAGAIN || code == EWOULDBLOCK;
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string socket_error_text(int code)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return std::error_code{code, std::system_category()}.message();
|
||||
#else
|
||||
return std::strerror(code);
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] auto poll_fd(int fd) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return static_cast<SOCKET>(fd);
|
||||
#else
|
||||
return fd;
|
||||
#endif
|
||||
}
|
||||
|
||||
int create_wake_socket()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
const SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (s == INVALID_SOCKET) return -1;
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
address.sin_port = 0;
|
||||
if (::bind(s, reinterpret_cast<sockaddr*>(&address),
|
||||
sizeof(address)) != 0) {
|
||||
::closesocket(s);
|
||||
return -1;
|
||||
}
|
||||
int length = sizeof(address);
|
||||
if (::getsockname(s, reinterpret_cast<sockaddr*>(&address),
|
||||
&length) != 0 ||
|
||||
::connect(s, reinterpret_cast<sockaddr*>(&address),
|
||||
sizeof(address)) != 0) {
|
||||
::closesocket(s);
|
||||
return -1;
|
||||
}
|
||||
u_long nonblocking = 1;
|
||||
(void)::ioctlsocket(s, FIONBIO, &nonblocking);
|
||||
return static_cast<int>(s);
|
||||
#else
|
||||
return ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
|
||||
#endif
|
||||
}
|
||||
|
||||
void signal_wake(int fd) noexcept
|
||||
{
|
||||
const std::uint64_t one = 1;
|
||||
#ifdef _WIN32
|
||||
(void)::send(static_cast<SOCKET>(fd),
|
||||
reinterpret_cast<const char*>(&one), sizeof(one), 0);
|
||||
#else
|
||||
(void)::write(fd, &one, sizeof(one));
|
||||
#endif
|
||||
}
|
||||
|
||||
void drain_wake(int fd) noexcept
|
||||
{
|
||||
std::uint64_t value = 0;
|
||||
#ifdef _WIN32
|
||||
(void)::recv(static_cast<SOCKET>(fd),
|
||||
reinterpret_cast<char*>(&value), sizeof(value), 0);
|
||||
#else
|
||||
(void)::read(fd, &value, sizeof(value));
|
||||
#endif
|
||||
}
|
||||
|
||||
int open_file_read(const char* path) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_open(path, _O_RDONLY | _O_BINARY);
|
||||
#else
|
||||
return ::open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
#endif
|
||||
}
|
||||
|
||||
int open_file_exclusive_write(const char* path) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_open(path,
|
||||
_O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY,
|
||||
_S_IREAD | _S_IWRITE);
|
||||
#else
|
||||
return ::open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC |
|
||||
O_NOFOLLOW, 0644);
|
||||
#endif
|
||||
}
|
||||
|
||||
int close_file(int fd) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_close(fd);
|
||||
#else
|
||||
return ::close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
int sync_file(int fd) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_commit(fd);
|
||||
#else
|
||||
return ::fsync(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::ptrdiff_t read_file(int fd, void* buffer,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_read(fd, buffer, static_cast<unsigned int>(size));
|
||||
#else
|
||||
return ::read(fd, buffer, size);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::ptrdiff_t write_file(int fd, const void* buffer,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_write(fd, buffer, static_cast<unsigned int>(size));
|
||||
#else
|
||||
return ::write(fd, buffer, size);
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] bool regular_file_size(int fd,
|
||||
std::uint64_t& size) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
struct _stat64 st{};
|
||||
if (::_fstat64(fd, &st) != 0 || (st.st_mode & _S_IFREG) == 0) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
struct stat st{};
|
||||
if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
size = static_cast<std::uint64_t>(st.st_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
equal_ascii_ci(std::string_view a, std::string_view b) noexcept
|
||||
{
|
||||
@@ -92,13 +311,21 @@ namespace Void::Net
|
||||
std::string owned{text};
|
||||
IpAddress out;
|
||||
in_addr v4{};
|
||||
#ifdef _WIN32
|
||||
if (::InetPtonA(AF_INET, owned.c_str(), &v4) == 1) {
|
||||
#else
|
||||
if (::inet_pton(AF_INET, owned.c_str(), &v4) == 1) {
|
||||
#endif
|
||||
out.family = AF_INET;
|
||||
std::memcpy(out.bytes.data(), &v4, sizeof(v4));
|
||||
return out;
|
||||
}
|
||||
in6_addr v6{};
|
||||
#ifdef _WIN32
|
||||
if (::InetPtonA(AF_INET6, owned.c_str(), &v6) != 1) {
|
||||
#else
|
||||
if (::inet_pton(AF_INET6, owned.c_str(), &v6) != 1) {
|
||||
#endif
|
||||
return std::nullopt;
|
||||
}
|
||||
constexpr std::array<std::byte, 12> mapped_prefix{
|
||||
@@ -492,16 +719,22 @@ namespace Void::Net
|
||||
{
|
||||
public:
|
||||
|
||||
explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {}
|
||||
explicit OwnedFd(int fd = -1, bool is_socket = true) noexcept
|
||||
: m_fd(fd), m_socket(is_socket)
|
||||
{
|
||||
}
|
||||
~OwnedFd() noexcept { reset(); }
|
||||
OwnedFd(OwnedFd&& other) noexcept
|
||||
: m_fd(std::exchange(other.m_fd, -1))
|
||||
: m_fd(std::exchange(other.m_fd, -1)),
|
||||
m_socket(std::exchange(other.m_socket, true))
|
||||
{
|
||||
}
|
||||
OwnedFd& operator=(OwnedFd&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
reset(std::exchange(other.m_fd, -1));
|
||||
reset();
|
||||
m_fd = std::exchange(other.m_fd, -1);
|
||||
m_socket = std::exchange(other.m_socket, true);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -517,17 +750,23 @@ namespace Void::Net
|
||||
{
|
||||
return std::exchange(m_fd, -1);
|
||||
}
|
||||
void reset(int fd = -1) noexcept
|
||||
void reset(int fd = -1, bool is_socket = true) noexcept
|
||||
{
|
||||
if (m_fd >= 0) {
|
||||
(void)::close(m_fd);
|
||||
if (m_socket) {
|
||||
close_socket_fd(m_fd);
|
||||
} else {
|
||||
(void)close_file(m_fd);
|
||||
}
|
||||
}
|
||||
m_fd = fd;
|
||||
m_socket = is_socket;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
int m_fd{-1};
|
||||
bool m_socket{true};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
@@ -557,33 +796,35 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
struct pollfd pfd{};
|
||||
pfd.fd = fd;
|
||||
pfd.fd = poll_fd(fd);
|
||||
pfd.events = POLLIN;
|
||||
const int pr = ::poll(&pfd, 1, wait_ms);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::HttpServer: poll failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
socket_error_text(code)),
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (pr == 0) {
|
||||
continue;
|
||||
}
|
||||
const ssize_t n = ::recv(fd, dst.data(), dst.size(), 0);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::HttpServer: recv failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
socket_error_text(code)),
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
return static_cast<std::size_t>(n);
|
||||
}
|
||||
@@ -613,11 +854,12 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
struct pollfd pfd{};
|
||||
pfd.fd = fd;
|
||||
pfd.fd = poll_fd(fd);
|
||||
pfd.events = POLLOUT;
|
||||
const int pr = ::poll(&pfd, 1, wait_ms);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
@@ -631,15 +873,16 @@ namespace Void::Net
|
||||
reinterpret_cast<const char*>(data.data()) + off,
|
||||
data.size() - off, MSG_NOSIGNAL);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::HttpServer: send failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
socket_error_text(code)),
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (n == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
@@ -970,13 +1213,17 @@ namespace Void::Net
|
||||
|
||||
const std::filesystem::path tmp_path =
|
||||
parent / std::format(".void-upload-{}-{}",
|
||||
static_cast<long long>(::getpid()),
|
||||
static_cast<long long>(
|
||||
#ifdef _WIN32
|
||||
::_getpid()
|
||||
#else
|
||||
::getpid()
|
||||
#endif
|
||||
),
|
||||
g_temp_upload_seq.fetch_add(
|
||||
1, std::memory_order_relaxed));
|
||||
OwnedFd out_fd{::open(tmp_path.c_str(),
|
||||
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC |
|
||||
O_NOFOLLOW,
|
||||
0644)};
|
||||
OwnedFd out_fd{
|
||||
open_file_exclusive_write(tmp_path.string().c_str()), false};
|
||||
if (!out_fd) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
@@ -1012,7 +1259,7 @@ namespace Void::Net
|
||||
}
|
||||
std::size_t off = 0;
|
||||
while (off < *n) {
|
||||
const ssize_t w = ::write(
|
||||
const std::ptrdiff_t w = write_file(
|
||||
out_fd.get(),
|
||||
reinterpret_cast<const char*>(buf.data()) + off,
|
||||
*n - off);
|
||||
@@ -1032,7 +1279,7 @@ namespace Void::Net
|
||||
written_total += amt;
|
||||
}
|
||||
|
||||
if (::fsync(out_fd.get()) != 0) {
|
||||
if (sync_file(out_fd.get()) != 0) {
|
||||
return fail_cleanup(make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::BodyReader: fsync failed: {}",
|
||||
@@ -1040,7 +1287,7 @@ namespace Void::Net
|
||||
std::error_code{errno, std::generic_category()}));
|
||||
}
|
||||
const int raw = out_fd.release();
|
||||
if (::close(raw) != 0) {
|
||||
if (close_file(raw) != 0) {
|
||||
return fail_cleanup(make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::BodyReader: close failed: {}",
|
||||
@@ -1136,11 +1383,12 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
struct pollfd pfd{};
|
||||
pfd.fd = state.fd;
|
||||
pfd.fd = poll_fd(state.fd);
|
||||
pfd.events = POLLOUT;
|
||||
const int pr = ::poll(&pfd, 1, wait_ms);
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
@@ -1155,16 +1403,17 @@ namespace Void::Net
|
||||
reinterpret_cast<const char*>(data.data()) + off,
|
||||
data.size() - off, MSG_NOSIGNAL);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = last_socket_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
state.request_stop();
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::ResponseWriter: send failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
socket_error_text(code)),
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (n == 0) {
|
||||
state.request_stop();
|
||||
@@ -2089,8 +2338,8 @@ namespace Void::Net
|
||||
std::string content_type_default;
|
||||
|
||||
if (resp.file_body.has_value()) {
|
||||
OwnedFd f{::open(resp.file_body->c_str(),
|
||||
O_RDONLY | O_CLOEXEC | O_NOFOLLOW)};
|
||||
OwnedFd f{
|
||||
open_file_read(resp.file_body->string().c_str()), false};
|
||||
if (!f) {
|
||||
const std::uint16_t err_status =
|
||||
errno == ENOENT ? 404 : 500;
|
||||
@@ -2101,9 +2350,8 @@ namespace Void::Net
|
||||
: "Internal Server Error";
|
||||
body_len = resp.body.size();
|
||||
} else {
|
||||
struct stat st{};
|
||||
if (::fstat(f.get(), &st) != 0 ||
|
||||
!S_ISREG(st.st_mode)) {
|
||||
std::uint64_t size = 0;
|
||||
if (!regular_file_size(f.get(), size)) {
|
||||
resp.file_body.reset();
|
||||
resp.status = 500;
|
||||
resp.headers.clear();
|
||||
@@ -2111,7 +2359,7 @@ namespace Void::Net
|
||||
body_len = resp.body.size();
|
||||
} else {
|
||||
file_fd = std::move(f);
|
||||
body_len = static_cast<std::uint64_t>(st.st_size);
|
||||
body_len = size;
|
||||
content_type_default =
|
||||
std::string{content_type_for(*resp.file_body)};
|
||||
}
|
||||
@@ -2161,7 +2409,8 @@ namespace Void::Net
|
||||
while (remaining > 0) {
|
||||
const std::size_t want = static_cast<std::size_t>(
|
||||
std::min<std::uint64_t>(remaining, buf.size()));
|
||||
const ssize_t r = ::read(file_fd.get(), buf.data(), want);
|
||||
const std::ptrdiff_t r =
|
||||
read_file(file_fd.get(), buf.data(), want);
|
||||
if (r < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
@@ -2707,23 +2956,24 @@ namespace Void::Net
|
||||
{
|
||||
while (!stopping.load(std::memory_order_acquire)) {
|
||||
std::array<struct pollfd, 2> pfds{{
|
||||
{.fd = listen_fd, .events = POLLIN, .revents = 0},
|
||||
{.fd = wake_fd, .events = POLLIN, .revents = 0},
|
||||
{.fd = poll_fd(listen_fd), .events = POLLIN, .revents = 0},
|
||||
{.fd = poll_fd(wake_fd), .events = POLLIN, .revents = 0},
|
||||
}};
|
||||
const int pr = ::poll(pfds.data(), pfds.size(), 100);
|
||||
if (pr < 0) {
|
||||
#ifdef _WIN32
|
||||
if (::WSAGetLastError() == WSAEINTR) {
|
||||
#else
|
||||
if (errno == EINTR) {
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if ((pfds[1].revents & POLLIN) != 0) {
|
||||
std::uint64_t val = 0;
|
||||
// Best effort: the eventfd is only a wakeup hint and the
|
||||
// stopping flag is authoritative, but consume the result so
|
||||
// fortified headers do not raise -Wunused-result.
|
||||
[[maybe_unused]] const ssize_t drained =
|
||||
::read(wake_fd, &val, sizeof(val));
|
||||
// Best effort: the wake socket is only a wakeup hint and the
|
||||
// stopping flag is authoritative.
|
||||
drain_wake(wake_fd);
|
||||
}
|
||||
if (stopping.load(std::memory_order_acquire)) {
|
||||
break;
|
||||
@@ -2734,17 +2984,26 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
#ifdef _WIN32
|
||||
int client_fd =
|
||||
static_cast<int>(::accept(listen_fd, nullptr, nullptr));
|
||||
#else
|
||||
#ifdef SOCK_CLOEXEC
|
||||
int client_fd = ::accept4(listen_fd, nullptr, nullptr,
|
||||
SOCK_CLOEXEC);
|
||||
SOCK_CLOEXEC);
|
||||
#else
|
||||
int client_fd = ::accept(listen_fd, nullptr, nullptr);
|
||||
if (client_fd >= 0) {
|
||||
(void)::fcntl(client_fd, F_SETFD, FD_CLOEXEC);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
if (client_fd < 0) {
|
||||
#ifdef _WIN32
|
||||
if (::WSAGetLastError() == WSAEINTR) {
|
||||
#else
|
||||
if (errno == EINTR) {
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
@@ -2767,7 +3026,7 @@ namespace Void::Net
|
||||
[[maybe_unused]] const ssize_t sent =
|
||||
::send(client_fd, busy.data(), busy.size(),
|
||||
MSG_NOSIGNAL);
|
||||
(void)::close(client_fd);
|
||||
close_socket_fd(client_fd);
|
||||
continue;
|
||||
}
|
||||
const std::uint64_t id = ++next_worker_id;
|
||||
@@ -2799,21 +3058,17 @@ namespace Void::Net
|
||||
}
|
||||
stopping.store(true, std::memory_order_release);
|
||||
if (wake_fd >= 0) {
|
||||
const std::uint64_t one = 1;
|
||||
// Best effort wakeup: the accept loop also polls with a
|
||||
// timeout, so a full eventfd cannot delay shutdown.
|
||||
[[maybe_unused]] const ssize_t signalled =
|
||||
::write(wake_fd, &one, sizeof(one));
|
||||
signal_wake(wake_fd);
|
||||
}
|
||||
if (accept_thread.joinable()) {
|
||||
accept_thread.join();
|
||||
}
|
||||
if (listen_fd >= 0) {
|
||||
(void)::close(listen_fd);
|
||||
close_socket_fd(listen_fd);
|
||||
listen_fd = -1;
|
||||
}
|
||||
if (wake_fd >= 0) {
|
||||
(void)::close(wake_fd);
|
||||
close_socket_fd(wake_fd);
|
||||
wake_fd = -1;
|
||||
}
|
||||
|
||||
@@ -3008,12 +3263,20 @@ namespace Void::Net
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net::HttpServer::start: getaddrinfo '{}' failed: "
|
||||
"{}",
|
||||
#ifdef _WIN32
|
||||
host, ::gai_strerrorA(gai)))};
|
||||
#else
|
||||
host, ::gai_strerror(gai)))};
|
||||
#endif
|
||||
}
|
||||
|
||||
OwnedFd listen_guard;
|
||||
int last_errno = 0;
|
||||
for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) {
|
||||
#ifdef _WIN32
|
||||
int fd = static_cast<int>(
|
||||
::socket(p->ai_family, p->ai_socktype, p->ai_protocol));
|
||||
#else
|
||||
#ifdef SOCK_CLOEXEC
|
||||
int fd = ::socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC,
|
||||
p->ai_protocol);
|
||||
@@ -3022,21 +3285,31 @@ namespace Void::Net
|
||||
if (fd >= 0) {
|
||||
(void)::fcntl(fd, F_SETFD, FD_CLOEXEC);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
if (fd < 0) {
|
||||
#ifdef _WIN32
|
||||
last_errno = ::WSAGetLastError();
|
||||
#else
|
||||
last_errno = errno;
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
OwnedFd cand{fd};
|
||||
int yes = 1;
|
||||
(void)::setsockopt(cand.get(), SOL_SOCKET, SO_REUSEADDR, &yes,
|
||||
(void)::setsockopt(cand.get(), SOL_SOCKET, SO_REUSEADDR,
|
||||
reinterpret_cast<const char*>(&yes),
|
||||
sizeof(yes));
|
||||
if (::bind(cand.get(), p->ai_addr, p->ai_addrlen) == 0 &&
|
||||
::listen(cand.get(), m_impl->options.listen_backlog) == 0) {
|
||||
listen_guard = std::move(cand);
|
||||
break;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
last_errno = ::WSAGetLastError();
|
||||
#else
|
||||
last_errno = errno;
|
||||
#endif
|
||||
}
|
||||
::freeaddrinfo(res);
|
||||
|
||||
@@ -3046,12 +3319,24 @@ namespace Void::Net
|
||||
std::format("Net::HttpServer::start: bind/listen on {}:{} "
|
||||
"failed: {}",
|
||||
host, m_impl->options.port,
|
||||
#ifdef _WIN32
|
||||
std::error_code{last_errno, std::system_category()}
|
||||
.message()),
|
||||
std::error_code{last_errno, std::system_category()})};
|
||||
#else
|
||||
std::strerror(last_errno)),
|
||||
std::error_code{last_errno, std::generic_category()})};
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
u_long nonblocking = 1;
|
||||
(void)::ioctlsocket(static_cast<SOCKET>(listen_guard.get()), FIONBIO,
|
||||
&nonblocking);
|
||||
#else
|
||||
(void)::fcntl(listen_guard.get(), F_SETFL,
|
||||
::fcntl(listen_guard.get(), F_GETFL, 0) | O_NONBLOCK);
|
||||
#endif
|
||||
|
||||
struct sockaddr_storage ss{};
|
||||
socklen_t slen = sizeof(ss);
|
||||
@@ -3060,8 +3345,15 @@ namespace Void::Net
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::HttpServer::start: getsockname failed: {}",
|
||||
#ifdef _WIN32
|
||||
std::error_code{::WSAGetLastError(),
|
||||
std::system_category()}
|
||||
.message()),
|
||||
std::error_code{::WSAGetLastError(), std::system_category()})};
|
||||
#else
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
#endif
|
||||
}
|
||||
|
||||
std::array<char, INET6_ADDRSTRLEN> ip_buf{};
|
||||
@@ -3069,24 +3361,35 @@ namespace Void::Net
|
||||
if (ss.ss_family == AF_INET) {
|
||||
const auto* s4 = reinterpret_cast<const sockaddr_in*>(&ss);
|
||||
actual_port = ntohs(s4->sin_port);
|
||||
#ifdef _WIN32
|
||||
(void)::InetNtopA(AF_INET, &s4->sin_addr, ip_buf.data(),
|
||||
static_cast<DWORD>(ip_buf.size()));
|
||||
#else
|
||||
(void)::inet_ntop(AF_INET, &s4->sin_addr, ip_buf.data(),
|
||||
ip_buf.size());
|
||||
#endif
|
||||
m_impl->bind_addr_str = ip_buf.data();
|
||||
} else if (ss.ss_family == AF_INET6) {
|
||||
const auto* s6 = reinterpret_cast<const sockaddr_in6*>(&ss);
|
||||
actual_port = ntohs(s6->sin6_port);
|
||||
#ifdef _WIN32
|
||||
(void)::InetNtopA(AF_INET6, &s6->sin6_addr, ip_buf.data(),
|
||||
static_cast<DWORD>(ip_buf.size()));
|
||||
#else
|
||||
(void)::inet_ntop(AF_INET6, &s6->sin6_addr, ip_buf.data(),
|
||||
ip_buf.size());
|
||||
#endif
|
||||
m_impl->bind_addr_str = std::format("[{}]", ip_buf.data());
|
||||
}
|
||||
|
||||
int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
|
||||
int efd = create_wake_socket();
|
||||
if (efd < 0) {
|
||||
const int code = last_socket_error();
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::HttpServer::start: eventfd failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
std::format("Net::HttpServer::start: wake socket failed: {}",
|
||||
socket_error_text(code)),
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
|
||||
m_impl->listen_fd = listen_guard.release();
|
||||
|
||||
+303
-10
@@ -4,6 +4,16 @@
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#else
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
#include <io.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
@@ -67,6 +77,86 @@ namespace Void::Net
|
||||
return segments;
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
[[nodiscard]] HANDLE open_win_handle(const std::filesystem::path& path,
|
||||
DWORD access, DWORD flags) noexcept
|
||||
{
|
||||
return ::CreateFileW(
|
||||
path.c_str(), access,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
|
||||
OPEN_EXISTING, flags, nullptr);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool win_reparse_point(HANDLE handle) noexcept
|
||||
{
|
||||
FILE_ATTRIBUTE_TAG_INFO info{};
|
||||
return ::GetFileInformationByHandleEx(
|
||||
handle, FileAttributeTagInfo, &info, sizeof(info)) != 0 &&
|
||||
(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool win_directory(HANDLE handle) noexcept
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
return ::GetFileInformationByHandle(handle, &info) != 0 &&
|
||||
(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string win_error_message(DWORD code)
|
||||
{
|
||||
return std::system_category().message(static_cast<int>(code));
|
||||
}
|
||||
|
||||
// Canonical DOS path behind an open handle, without the \\?\ prefix.
|
||||
[[nodiscard]] std::optional<std::filesystem::path>
|
||||
win_final_path(HANDLE handle)
|
||||
{
|
||||
std::wstring buffer(32768, L'\0');
|
||||
const DWORD count = ::GetFinalPathNameByHandleW(
|
||||
handle, buffer.data(), static_cast<DWORD>(buffer.size()),
|
||||
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
|
||||
if (count == 0 || count >= buffer.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
buffer.resize(count);
|
||||
std::wstring_view view{buffer};
|
||||
if (view.starts_with(L"\\\\?\\UNC\\")) {
|
||||
view.remove_prefix(8);
|
||||
std::wstring unc{L"\\\\"};
|
||||
unc.append(view);
|
||||
return std::filesystem::path{unc};
|
||||
}
|
||||
if (view.starts_with(L"\\\\?\\")) {
|
||||
view.remove_prefix(4);
|
||||
}
|
||||
return std::filesystem::path{view};
|
||||
}
|
||||
|
||||
// Case-insensitive (Windows paths are) prefix containment check.
|
||||
[[nodiscard]] bool
|
||||
win_path_within(const std::filesystem::path& root,
|
||||
const std::filesystem::path& candidate)
|
||||
{
|
||||
const auto normalize = [](std::filesystem::path path) {
|
||||
std::string text = path.lexically_normal().generic_string();
|
||||
for (char& c : text) {
|
||||
c = static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
}
|
||||
while (!text.empty() && text.back() == '/') {
|
||||
text.pop_back();
|
||||
}
|
||||
return text;
|
||||
};
|
||||
const std::string base = normalize(root);
|
||||
const std::string full = normalize(candidate);
|
||||
return full == base ||
|
||||
(full.size() > base.size() &&
|
||||
full.compare(0, base.size(), base) == 0 &&
|
||||
full[base.size()] == '/');
|
||||
}
|
||||
#endif
|
||||
|
||||
[[nodiscard]] bool valid_parameter_name(std::string_view name) noexcept
|
||||
{
|
||||
return !name.empty() && std::ranges::all_of(name, [](char value) {
|
||||
@@ -451,7 +541,7 @@ namespace Void::Net
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
OpenedStaticFile::OpenedStaticFile(int fd,
|
||||
OpenedStaticFile::OpenedStaticFile(NativeFileHandle fd,
|
||||
std::filesystem::path relative_path,
|
||||
std::string_view content_type,
|
||||
std::uint64_t size) noexcept
|
||||
@@ -487,7 +577,12 @@ namespace Void::Net
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (fd_ >= 0) {
|
||||
(void)::close(fd_);
|
||||
(void)::close(static_cast<int>(fd_));
|
||||
fd_ = -1;
|
||||
}
|
||||
#else
|
||||
if (fd_ >= 0) {
|
||||
(void)::CloseHandle(reinterpret_cast<HANDLE>(fd_));
|
||||
fd_ = -1;
|
||||
}
|
||||
#endif
|
||||
@@ -511,7 +606,7 @@ namespace Void::Net
|
||||
std::array<char, 32 * 1024> buf{};
|
||||
std::uint64_t offset = 0;
|
||||
for (;;) {
|
||||
const ssize_t n = ::pread(fd_, buf.data(), buf.size(),
|
||||
const ssize_t n = ::pread(static_cast<int>(fd_), buf.data(), buf.size(),
|
||||
static_cast<off_t>(offset));
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
@@ -535,9 +630,57 @@ namespace Void::Net
|
||||
}
|
||||
return out;
|
||||
#else
|
||||
(void)max_bytes;
|
||||
return Void::Result::fail(
|
||||
"Net::OpenedStaticFile: unsupported platform");
|
||||
const HANDLE handle = reinterpret_cast<HANDLE>(fd_);
|
||||
if (handle == nullptr || handle == INVALID_HANDLE_VALUE) {
|
||||
return Void::Result::fail(
|
||||
"Net::OpenedStaticFile: file handle is closed");
|
||||
}
|
||||
if (size_ > max_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::OpenedStaticFile: file size exceeds max_bytes")};
|
||||
}
|
||||
LARGE_INTEGER start{};
|
||||
if (!::SetFilePointerEx(handle, start, nullptr, FILE_BEGIN)) {
|
||||
const DWORD code = ::GetLastError();
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::OpenedStaticFile: seek failed: {}",
|
||||
std::system_category().message(
|
||||
static_cast<int>(code))),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
std::string out;
|
||||
out.reserve(static_cast<std::size_t>(size_));
|
||||
std::array<char, 32 * 1024> buf{};
|
||||
std::uint64_t offset = 0;
|
||||
for (;;) {
|
||||
DWORD n = 0;
|
||||
if (!::ReadFile(handle, buf.data(),
|
||||
static_cast<DWORD>(buf.size()), &n, nullptr)) {
|
||||
const DWORD code = ::GetLastError();
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::OpenedStaticFile: ReadFile failed: {}",
|
||||
std::system_category().message(
|
||||
static_cast<int>(code))),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
if (n == 0) {
|
||||
break;
|
||||
}
|
||||
const auto un = static_cast<std::uint64_t>(n);
|
||||
if (un > max_bytes || offset > max_bytes - un) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::OpenedStaticFile: read exceeds max_bytes")};
|
||||
}
|
||||
out.append(buf.data(), static_cast<std::size_t>(n));
|
||||
offset += un;
|
||||
}
|
||||
return out;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -545,7 +688,12 @@ namespace Void::Net
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (fd >= 0) {
|
||||
(void)::close(fd);
|
||||
(void)::close(static_cast<int>(fd));
|
||||
fd = -1;
|
||||
}
|
||||
#else
|
||||
if (fd >= 0) {
|
||||
(void)::CloseHandle(reinterpret_cast<HANDLE>(fd));
|
||||
fd = -1;
|
||||
}
|
||||
#endif
|
||||
@@ -582,6 +730,22 @@ namespace Void::Net
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
}
|
||||
root_handle = std::make_shared<DirHandle>(dir_fd);
|
||||
#else
|
||||
const HANDLE dir = open_win_handle(
|
||||
canonical_root, FILE_LIST_DIRECTORY,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
if (dir == INVALID_HANDLE_VALUE) {
|
||||
const DWORD code = ::GetLastError();
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format(
|
||||
"Net::StaticFileResolver: cannot open root directory: {}",
|
||||
win_error_message(code)),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
root_handle = std::make_shared<DirHandle>(
|
||||
reinterpret_cast<NativeFileHandle>(dir));
|
||||
#endif
|
||||
return StaticFileResolver{std::move(canonical_root),
|
||||
std::move(index_file),
|
||||
@@ -726,9 +890,138 @@ namespace Void::Net
|
||||
file_fd, std::move(rel_path), ct,
|
||||
static_cast<std::uint64_t>(st.st_size)}};
|
||||
#else
|
||||
(void)request_path;
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver::open_safe: unsupported platform");
|
||||
if (!root_dir_ || root_dir_->fd < 0) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: root directory handle unavailable");
|
||||
}
|
||||
auto decoded = decode_url_path(request_path);
|
||||
if (!decoded) {
|
||||
return Void::Result::fail(std::move(decoded).error());
|
||||
}
|
||||
const auto segments = split_path(*decoded);
|
||||
for (const auto& seg : segments) {
|
||||
// Reject traversal, both separators, drive/ADS colons and the
|
||||
// trailing-dot/space names Windows would silently normalize.
|
||||
if (seg == "." || seg == ".." ||
|
||||
seg.find_first_of("/\\:") != std::string::npos ||
|
||||
seg.back() == '.' || seg.back() == ' ') {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: path traversal rejected");
|
||||
}
|
||||
}
|
||||
|
||||
std::filesystem::path rel_path;
|
||||
std::filesystem::path directory = root_;
|
||||
// Every intermediate component must be a real directory: reparse
|
||||
// points (symlinks/junctions) are rejected like O_NOFOLLOW does.
|
||||
for (std::size_t i = 0; i + 1U < segments.size(); ++i) {
|
||||
directory /= segments[i];
|
||||
const HANDLE handle = open_win_handle(
|
||||
directory, FILE_READ_ATTRIBUTES,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
if (handle == INVALID_HANDLE_VALUE) {
|
||||
const DWORD code = ::GetLastError();
|
||||
if (code == ERROR_FILE_NOT_FOUND ||
|
||||
code == ERROR_PATH_NOT_FOUND || code == ERROR_DIRECTORY) {
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format(
|
||||
"Net::StaticFileResolver: open directory failed: {}",
|
||||
win_error_message(code)),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
const bool reparse = win_reparse_point(handle);
|
||||
const bool is_dir = win_directory(handle);
|
||||
(void)::CloseHandle(handle);
|
||||
if (reparse) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: symlink directory rejected");
|
||||
}
|
||||
if (!is_dir) {
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
rel_path /= segments[i];
|
||||
}
|
||||
|
||||
std::filesystem::path file_path;
|
||||
if (segments.empty()) {
|
||||
file_path = directory / index_file_;
|
||||
rel_path = index_file_;
|
||||
} else {
|
||||
const std::string& leaf = segments.back();
|
||||
const auto candidate = directory / leaf;
|
||||
bool leaf_is_directory = false;
|
||||
const HANDLE probe = open_win_handle(
|
||||
candidate, FILE_READ_ATTRIBUTES,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
if (probe != INVALID_HANDLE_VALUE) {
|
||||
const bool reparse = win_reparse_point(probe);
|
||||
leaf_is_directory = win_directory(probe);
|
||||
(void)::CloseHandle(probe);
|
||||
if (reparse) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: symlink file rejected");
|
||||
}
|
||||
}
|
||||
if (leaf_is_directory) {
|
||||
file_path = candidate / index_file_;
|
||||
rel_path /= leaf;
|
||||
rel_path /= index_file_;
|
||||
} else {
|
||||
file_path = candidate;
|
||||
rel_path /= leaf;
|
||||
}
|
||||
}
|
||||
|
||||
const HANDLE file = open_win_handle(file_path, GENERIC_READ,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
if (file == INVALID_HANDLE_VALUE) {
|
||||
const DWORD code = ::GetLastError();
|
||||
if (code == ERROR_FILE_NOT_FOUND || code == ERROR_PATH_NOT_FOUND) {
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::StaticFileResolver: open file failed: {}",
|
||||
win_error_message(code)),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
if (win_reparse_point(file)) {
|
||||
(void)::CloseHandle(file);
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: symlink file rejected");
|
||||
}
|
||||
if (win_directory(file)) {
|
||||
(void)::CloseHandle(file);
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
// The opened handle is pinned; resolving its final path catches any
|
||||
// component swapped for a junction between the walk and the open.
|
||||
const auto final_path = win_final_path(file);
|
||||
if (!final_path || !win_path_within(root_, *final_path)) {
|
||||
(void)::CloseHandle(file);
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: opened file escapes document root");
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!::GetFileSizeEx(file, &size)) {
|
||||
const DWORD code = ::GetLastError();
|
||||
(void)::CloseHandle(file);
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::StaticFileResolver: size failed: {}",
|
||||
win_error_message(code)),
|
||||
std::error_code{static_cast<int>(code),
|
||||
std::system_category()})};
|
||||
}
|
||||
const auto ct = content_type_for(rel_path);
|
||||
return std::optional<OpenedStaticFile>{OpenedStaticFile{
|
||||
reinterpret_cast<NativeFileHandle>(file), std::move(rel_path), ct,
|
||||
static_cast<std::uint64_t>(size.QuadPart)}};
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
+148
-18
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <cerrno>
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
@@ -10,32 +11,158 @@
|
||||
#include <utility>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
UdpSocket::~UdpSocket() = default;
|
||||
UdpSocket::UdpSocket(UdpSocket&&) noexcept = default;
|
||||
UdpSocket& UdpSocket::operator=(UdpSocket&&) noexcept = default;
|
||||
namespace
|
||||
{
|
||||
void ensure_winsock()
|
||||
{
|
||||
// WSAStartup once per process; WSAStop is intentionally left to
|
||||
// process teardown so sockets in static objects stay usable.
|
||||
static const int started = [] {
|
||||
WSADATA data{};
|
||||
return ::WSAStartup(MAKEWORD(2, 2), &data);
|
||||
}();
|
||||
(void)started;
|
||||
}
|
||||
|
||||
Void::Result::Failure<Void::Result::Error>
|
||||
socketError(std::string_view operation)
|
||||
{
|
||||
const int code = ::WSAGetLastError();
|
||||
char* text = nullptr;
|
||||
const DWORD length = ::FormatMessageA(
|
||||
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
|
||||
FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
nullptr, static_cast<DWORD>(code),
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<char*>(&text), 0, nullptr);
|
||||
std::string detail =
|
||||
length != 0 && text != nullptr
|
||||
? std::string{text, length}
|
||||
: std::format("Winsock error {}", code);
|
||||
if (text != nullptr) ::LocalFree(text);
|
||||
while (!detail.empty() &&
|
||||
(detail.back() == '\n' || detail.back() == '\r' ||
|
||||
detail.back() == ' ')) {
|
||||
detail.pop_back();
|
||||
}
|
||||
return Void::Result::fail(
|
||||
std::format("{}: {}", operation, detail));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
UdpSocket::~UdpSocket() { close(); }
|
||||
UdpSocket::UdpSocket(UdpSocket&& other) noexcept
|
||||
: handle_(std::exchange(other.handle_, -1))
|
||||
{
|
||||
}
|
||||
UdpSocket& UdpSocket::operator=(UdpSocket&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
close();
|
||||
handle_ = std::exchange(other.handle_, -1);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
Void::Result::Result<UdpSocket, Void::Result::Error>
|
||||
UdpSocket::connect(std::string_view, std::uint16_t)
|
||||
UdpSocket::connect(std::string_view host, std::uint16_t port)
|
||||
{
|
||||
return Void::Result::fail("UdpSocket is not implemented on Windows");
|
||||
ensure_winsock();
|
||||
addrinfo hints{};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
addrinfo* addresses = nullptr;
|
||||
const auto service = std::to_string(port);
|
||||
const auto hostname = std::string(host);
|
||||
const int resolved = ::getaddrinfo(hostname.c_str(), service.c_str(),
|
||||
&hints, &addresses);
|
||||
if (resolved != 0) return Void::Result::fail(std::format(
|
||||
"getaddrinfo '{}': {}", hostname, ::gai_strerrorA(resolved)));
|
||||
std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> guard(
|
||||
addresses, &freeaddrinfo);
|
||||
for (auto* address = addresses; address; address = address->ai_next) {
|
||||
const SOCKET handle = ::socket(address->ai_family,
|
||||
address->ai_socktype, address->ai_protocol);
|
||||
if (handle == INVALID_SOCKET) continue;
|
||||
if (::connect(handle, address->ai_addr,
|
||||
static_cast<int>(address->ai_addrlen)) == 0) {
|
||||
return UdpSocket(static_cast<NativeHandle>(handle));
|
||||
}
|
||||
::closesocket(handle);
|
||||
}
|
||||
return socketError("UDP connect");
|
||||
}
|
||||
void UdpSocket::close() noexcept {}
|
||||
void UdpSocket::shutdown() noexcept {}
|
||||
|
||||
void UdpSocket::close() noexcept
|
||||
{
|
||||
if (handle_ >= 0) {
|
||||
::closesocket(static_cast<SOCKET>(handle_));
|
||||
handle_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
void UdpSocket::shutdown() noexcept
|
||||
{
|
||||
if (handle_ >= 0) {
|
||||
::shutdown(static_cast<SOCKET>(handle_), SD_BOTH);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
UdpSocket::wait_readable(std::chrono::milliseconds) const
|
||||
UdpSocket::wait_readable(std::chrono::milliseconds timeout) const
|
||||
{
|
||||
return Void::Result::fail("UdpSocket is not implemented on Windows");
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
WSAPOLLFD descriptor{};
|
||||
descriptor.fd = static_cast<SOCKET>(handle_);
|
||||
descriptor.events = POLLIN;
|
||||
const auto bounded = std::clamp<long long>(timeout.count(), 0,
|
||||
std::numeric_limits<int>::max());
|
||||
const int result = ::WSAPoll(&descriptor, 1,
|
||||
static_cast<int>(bounded));
|
||||
if (result == SOCKET_ERROR) {
|
||||
if (::WSAGetLastError() == WSAEINTR) return false;
|
||||
return socketError("UDP poll");
|
||||
}
|
||||
return result > 0 && (descriptor.revents & POLLIN) != 0;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t, Void::Result::Error>
|
||||
UdpSocket::send(std::span<const std::uint8_t>)
|
||||
UdpSocket::send(std::span<const std::uint8_t> bytes)
|
||||
{
|
||||
return Void::Result::fail("UdpSocket is not implemented on Windows");
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
if (bytes.size() > static_cast<std::size_t>(INT_MAX)) {
|
||||
return Void::Result::fail("UDP send: datagram too large");
|
||||
}
|
||||
const int result = ::send(static_cast<SOCKET>(handle_),
|
||||
reinterpret_cast<const char*>(bytes.data()),
|
||||
static_cast<int>(bytes.size()), 0);
|
||||
if (result == SOCKET_ERROR) return socketError("UDP send");
|
||||
return static_cast<std::size_t>(result);
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t, Void::Result::Error>
|
||||
UdpSocket::receive(std::span<std::uint8_t>)
|
||||
UdpSocket::receive(std::span<std::uint8_t> destination)
|
||||
{
|
||||
return Void::Result::fail("UdpSocket is not implemented on Windows");
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
if (destination.size() > static_cast<std::size_t>(INT_MAX)) {
|
||||
return Void::Result::fail("UDP receive: buffer too large");
|
||||
}
|
||||
const int result = ::recv(static_cast<SOCKET>(handle_),
|
||||
reinterpret_cast<char*>(destination.data()),
|
||||
static_cast<int>(destination.size()), 0);
|
||||
if (result == SOCKET_ERROR) return socketError("UDP receive");
|
||||
return static_cast<std::size_t>(result);
|
||||
}
|
||||
}
|
||||
#else
|
||||
@@ -99,21 +226,22 @@ namespace Void::Net
|
||||
void UdpSocket::close() noexcept
|
||||
{
|
||||
if (handle_ >= 0) {
|
||||
::close(handle_);
|
||||
::close(static_cast<int>(handle_));
|
||||
handle_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
void UdpSocket::shutdown() noexcept
|
||||
{
|
||||
if (handle_ >= 0) ::shutdown(handle_, SHUT_RDWR);
|
||||
if (handle_ >= 0) ::shutdown(static_cast<int>(handle_), SHUT_RDWR);
|
||||
}
|
||||
|
||||
Void::Result::Result<bool, Void::Result::Error>
|
||||
UdpSocket::wait_readable(std::chrono::milliseconds timeout) const
|
||||
{
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
pollfd descriptor{.fd = handle_, .events = POLLIN, .revents = 0};
|
||||
pollfd descriptor{.fd = static_cast<int>(handle_), .events = POLLIN,
|
||||
.revents = 0};
|
||||
const auto bounded = std::clamp<long long>(timeout.count(), 0,
|
||||
std::numeric_limits<int>::max());
|
||||
const int result = ::poll(&descriptor, 1, static_cast<int>(bounded));
|
||||
@@ -125,7 +253,8 @@ namespace Void::Net
|
||||
UdpSocket::send(std::span<const std::uint8_t> bytes)
|
||||
{
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
const auto result = ::send(handle_, bytes.data(), bytes.size(), 0);
|
||||
const auto result = ::send(static_cast<int>(handle_), bytes.data(),
|
||||
bytes.size(), 0);
|
||||
if (result < 0) return socketError("UDP send");
|
||||
return static_cast<std::size_t>(result);
|
||||
}
|
||||
@@ -134,7 +263,8 @@ namespace Void::Net
|
||||
UdpSocket::receive(std::span<std::uint8_t> destination)
|
||||
{
|
||||
if (!valid()) return Void::Result::fail("UDP socket is closed");
|
||||
const auto result = ::recv(handle_, destination.data(), destination.size(), 0);
|
||||
const auto result = ::recv(static_cast<int>(handle_),
|
||||
destination.data(), destination.size(), 0);
|
||||
if (result < 0) return socketError("UDP receive");
|
||||
return static_cast<std::size_t>(result);
|
||||
}
|
||||
|
||||
+259
-120
@@ -1,11 +1,22 @@
|
||||
#include <Void/Net/Tls.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#endif
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#ifndef _WIN32
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
@@ -29,7 +40,180 @@ namespace Void::Net
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
#ifdef _WIN32
|
||||
using SocketLength = int;
|
||||
|
||||
void ensure_winsock()
|
||||
{
|
||||
static const int started = [] {
|
||||
WSADATA data{};
|
||||
return ::WSAStartup(MAKEWORD(2, 2), &data);
|
||||
}();
|
||||
(void)started;
|
||||
}
|
||||
|
||||
[[nodiscard]] int socket_last_error() noexcept
|
||||
{
|
||||
return ::WSAGetLastError();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_interrupted(int code) noexcept
|
||||
{
|
||||
return code == WSAEINTR;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_would_block(int code) noexcept
|
||||
{
|
||||
return code == WSAEWOULDBLOCK || code == WSAEINPROGRESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string socket_error_text(int code)
|
||||
{
|
||||
char* text = nullptr;
|
||||
const DWORD length = ::FormatMessageA(
|
||||
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
|
||||
FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
nullptr, static_cast<DWORD>(code),
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<char*>(&text), 0, nullptr);
|
||||
std::string detail = length != 0 && text != nullptr
|
||||
? std::string{text, length}
|
||||
: std::format("Winsock error {}", code);
|
||||
if (text != nullptr) ::LocalFree(text);
|
||||
while (!detail.empty() &&
|
||||
(detail.back() == '\n' || detail.back() == '\r' ||
|
||||
detail.back() == ' ')) {
|
||||
detail.pop_back();
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string gai_error_text(int code)
|
||||
{
|
||||
return ::gai_strerrorA(code);
|
||||
}
|
||||
|
||||
void close_socket(int fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::closesocket(static_cast<SOCKET>(fd));
|
||||
}
|
||||
|
||||
void shutdown_socket(int fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::shutdown(static_cast<SOCKET>(fd), SD_BOTH);
|
||||
}
|
||||
|
||||
[[nodiscard]] int set_nonblocking(int fd) noexcept
|
||||
{
|
||||
u_long mode = 1;
|
||||
return ::ioctlsocket(static_cast<SOCKET>(fd), FIONBIO, &mode);
|
||||
}
|
||||
|
||||
[[nodiscard]] int connect_socket(int fd, const sockaddr* address,
|
||||
socklen_t length) noexcept
|
||||
{
|
||||
return ::connect(static_cast<SOCKET>(fd), address,
|
||||
static_cast<int>(length));
|
||||
}
|
||||
|
||||
[[nodiscard]] int getsockopt_socket(int fd, int level, int option,
|
||||
void* value,
|
||||
SocketLength* length) noexcept
|
||||
{
|
||||
return ::getsockopt(static_cast<SOCKET>(fd), level, option,
|
||||
static_cast<char*>(value), length);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t recv_socket(int fd, void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
return ::recv(static_cast<SOCKET>(fd),
|
||||
static_cast<char*>(data),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
size, static_cast<std::size_t>(INT_MAX))),
|
||||
0);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t send_socket(int fd, const void* data,
|
||||
std::size_t size,
|
||||
int flags) noexcept
|
||||
{
|
||||
return ::send(static_cast<SOCKET>(fd),
|
||||
static_cast<const char*>(data),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
size, static_cast<std::size_t>(INT_MAX))),
|
||||
flags);
|
||||
}
|
||||
#else
|
||||
using SocketLength = socklen_t;
|
||||
|
||||
[[nodiscard]] int socket_last_error() noexcept { return errno; }
|
||||
|
||||
[[nodiscard]] bool socket_interrupted(int code) noexcept
|
||||
{
|
||||
return code == EINTR;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_would_block(int code) noexcept
|
||||
{
|
||||
return code == EAGAIN || code == EWOULDBLOCK ||
|
||||
code == EINPROGRESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string socket_error_text(int code)
|
||||
{
|
||||
return std::strerror(code);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string gai_error_text(int code)
|
||||
{
|
||||
return ::gai_strerror(code);
|
||||
}
|
||||
|
||||
void close_socket(int fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::close(fd);
|
||||
}
|
||||
|
||||
void shutdown_socket(int fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::shutdown(fd, SHUT_RDWR);
|
||||
}
|
||||
|
||||
[[nodiscard]] int set_nonblocking(int fd) noexcept
|
||||
{
|
||||
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0) return -1;
|
||||
return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||
}
|
||||
|
||||
[[nodiscard]] int connect_socket(int fd, const sockaddr* address,
|
||||
socklen_t length) noexcept
|
||||
{
|
||||
return ::connect(fd, address, length);
|
||||
}
|
||||
|
||||
[[nodiscard]] int getsockopt_socket(int fd, int level, int option,
|
||||
void* value,
|
||||
SocketLength* length) noexcept
|
||||
{
|
||||
return ::getsockopt(fd, level, option, value, length);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t recv_socket(int fd, void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
return ::recv(fd, data, size, 0);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t send_socket(int fd, const void* data,
|
||||
std::size_t size,
|
||||
int flags) noexcept
|
||||
{
|
||||
return ::send(fd, data, size, flags);
|
||||
}
|
||||
#endif
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
@@ -100,7 +284,6 @@ namespace Void::Net
|
||||
if (stop.stop_requested()) {
|
||||
return std::unexpected{cancelled_error(operation)};
|
||||
}
|
||||
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
|
||||
int wait_ms = poll_timeout_ms(deadline);
|
||||
if (stop.stop_possible() &&
|
||||
(wait_ms < 0 || wait_ms > 50)) {
|
||||
@@ -108,15 +291,28 @@ namespace Void::Net
|
||||
// stream; poll again after the slice.
|
||||
wait_ms = 50;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
WSAPOLLFD descriptor{};
|
||||
descriptor.fd = static_cast<SOCKET>(fd);
|
||||
#else
|
||||
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
|
||||
#endif
|
||||
descriptor.events = events;
|
||||
descriptor.revents = 0;
|
||||
#ifdef _WIN32
|
||||
const int rc = ::WSAPoll(&descriptor, 1, wait_ms);
|
||||
#else
|
||||
const int rc = ::poll(&descriptor, 1, wait_ms);
|
||||
#endif
|
||||
if (rc < 0) {
|
||||
if (errno == EINTR) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS poll failed: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(code)))};
|
||||
}
|
||||
if (rc == 0) {
|
||||
if (Clock::now() >= deadline) {
|
||||
@@ -138,6 +334,9 @@ namespace Void::Net
|
||||
tcp_connect(const TlsClientOptions& options,
|
||||
Clock::time_point deadline)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
ensure_winsock();
|
||||
#endif
|
||||
if (options.host.empty() || options.port == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
@@ -155,7 +354,7 @@ namespace Void::Net
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS resolve '{}': {}", options.host,
|
||||
gai_strerror(resolved)))};
|
||||
gai_error_text(resolved)))};
|
||||
}
|
||||
std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> guard{
|
||||
addresses, &freeaddrinfo};
|
||||
@@ -166,6 +365,11 @@ namespace Void::Net
|
||||
options.port));
|
||||
for (addrinfo* address = addresses; address != nullptr;
|
||||
address = address->ai_next) {
|
||||
#ifdef _WIN32
|
||||
const int fd = static_cast<int>(
|
||||
::socket(address->ai_family, address->ai_socktype,
|
||||
address->ai_protocol));
|
||||
#else
|
||||
#ifdef SOCK_CLOEXEC
|
||||
const int fd =
|
||||
::socket(address->ai_family,
|
||||
@@ -175,46 +379,47 @@ namespace Void::Net
|
||||
const int fd =
|
||||
::socket(address->ai_family, address->ai_socktype,
|
||||
address->ai_protocol);
|
||||
#endif
|
||||
#endif
|
||||
if (fd < 0) {
|
||||
continue;
|
||||
}
|
||||
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0 ||
|
||||
::fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
::close(fd);
|
||||
if (set_nonblocking(fd) != 0) {
|
||||
close_socket(fd);
|
||||
continue;
|
||||
}
|
||||
if (::connect(fd, address->ai_addr, address->ai_addrlen) ==
|
||||
if (connect_socket(fd, address->ai_addr, address->ai_addrlen) ==
|
||||
0) {
|
||||
return fd;
|
||||
}
|
||||
if (errno != EINPROGRESS && errno != EINTR) {
|
||||
const int connect_code = socket_last_error();
|
||||
if (!socket_would_block(connect_code) &&
|
||||
!socket_interrupted(connect_code)) {
|
||||
last = make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS connect failed: {}",
|
||||
std::strerror(errno)));
|
||||
::close(fd);
|
||||
socket_error_text(connect_code)));
|
||||
close_socket(fd);
|
||||
continue;
|
||||
}
|
||||
const auto waited =
|
||||
wait_fd(fd, POLLOUT, deadline, options.stop, "connect");
|
||||
if (!waited.has_value()) {
|
||||
::close(fd);
|
||||
close_socket(fd);
|
||||
return std::unexpected{std::move(waited.error())};
|
||||
}
|
||||
int socket_error = 0;
|
||||
socklen_t length = sizeof(socket_error);
|
||||
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error,
|
||||
&length) != 0 ||
|
||||
SocketLength length = sizeof(socket_error);
|
||||
if (getsockopt_socket(fd, SOL_SOCKET, SO_ERROR,
|
||||
&socket_error, &length) != 0 ||
|
||||
socket_error != 0) {
|
||||
const int code =
|
||||
socket_error != 0 ? socket_error : errno;
|
||||
socket_error != 0 ? socket_error : socket_last_error();
|
||||
last = make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
std::format("Net: TLS connect failed: {}",
|
||||
std::strerror(code)));
|
||||
::close(fd);
|
||||
socket_error_text(code)));
|
||||
close_socket(fd);
|
||||
continue;
|
||||
}
|
||||
return fd;
|
||||
@@ -229,22 +434,26 @@ namespace Void::Net
|
||||
text.back() == ']') {
|
||||
text = text.substr(1, text.size() - 2);
|
||||
}
|
||||
unsigned char storage[sizeof(in6_addr)]{};
|
||||
unsigned char storage[16]{};
|
||||
#ifdef _WIN32
|
||||
return ::InetPtonA(AF_INET, text.c_str(), storage) == 1 ||
|
||||
::InetPtonA(AF_INET6, text.c_str(), storage) == 1;
|
||||
#else
|
||||
return ::inet_pton(AF_INET, text.c_str(), storage) == 1 ||
|
||||
::inet_pton(AF_INET6, text.c_str(), storage) == 1;
|
||||
#endif
|
||||
}
|
||||
[[nodiscard]] std::string
|
||||
verification_name(const TlsClientOptions& options)
|
||||
{
|
||||
std::string name = options.server_name.empty() ? options.host
|
||||
: options.server_name;
|
||||
: options.server_name;
|
||||
if (name.size() >= 2 && name.front() == '[' &&
|
||||
name.back() == ']') {
|
||||
name = name.substr(1, name.size() - 2);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
struct TlsClientStream::Impl {
|
||||
@@ -274,12 +483,10 @@ namespace Void::Net
|
||||
SSL_CTX_free(ctx);
|
||||
ctx = nullptr;
|
||||
}
|
||||
#if !defined(_WIN32)
|
||||
if (fd >= 0) {
|
||||
(void)::shutdown(fd, SHUT_RDWR);
|
||||
(void)::close(fd);
|
||||
shutdown_socket(fd);
|
||||
close_socket(fd);
|
||||
}
|
||||
#endif
|
||||
fd = -1;
|
||||
secure = false;
|
||||
}
|
||||
@@ -310,76 +517,6 @@ namespace Void::Net
|
||||
return m_impl != nullptr ? m_impl->fd : -1;
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect(TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect_plain(TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::adopt(int, TlsClientOptions)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<void> TlsClientStream::start_tls()
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TlsClientStream is not implemented on Windows")};
|
||||
}
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::read(std::span<std::byte>, std::chrono::milliseconds,
|
||||
std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<std::size_t>
|
||||
TlsClientStream::write(std::span<const std::byte>,
|
||||
std::chrono::milliseconds, std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::span<const std::byte>,
|
||||
std::chrono::milliseconds, std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void>
|
||||
TlsClientStream::write_all(std::string_view, std::chrono::milliseconds,
|
||||
std::stop_token)
|
||||
{
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error, "Net: TLS stream is not open")};
|
||||
}
|
||||
Void::Result::Result<void> TlsClientStream::shutdown()
|
||||
{
|
||||
if (m_impl != nullptr) {
|
||||
m_impl->close_all();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
void TlsClientStream::close() noexcept
|
||||
{
|
||||
if (m_impl != nullptr) {
|
||||
m_impl->close_all();
|
||||
}
|
||||
}
|
||||
#else
|
||||
Void::Result::Result<TlsClientStream>
|
||||
TlsClientStream::connect(TlsClientOptions options)
|
||||
{
|
||||
@@ -433,13 +570,11 @@ namespace Void::Net
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net: TLS adopt requires an open socket")};
|
||||
}
|
||||
const int flags = ::fcntl(native_socket, F_GETFL, 0);
|
||||
if (flags < 0 ||
|
||||
::fcntl(native_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
|
||||
if (set_nonblocking(native_socket) != 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS adopt failed to configure socket: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(socket_last_error())))};
|
||||
}
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->fd = native_socket;
|
||||
@@ -588,7 +723,8 @@ namespace Void::Net
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL && errno == EINTR) {
|
||||
if (error_code == SSL_ERROR_SYSCALL &&
|
||||
socket_interrupted(socket_last_error())) {
|
||||
continue;
|
||||
}
|
||||
const long verify = SSL_get_verify_result(impl.ssl);
|
||||
@@ -664,8 +800,9 @@ namespace Void::Net
|
||||
return 0;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
if (rc == 0) {
|
||||
@@ -674,24 +811,25 @@ namespace Void::Net
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS read failed: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(code)))};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
"Net: TLS read failed: " + openssl_error_text())};
|
||||
}
|
||||
const ssize_t rc = ::recv(impl.fd, destination.data(),
|
||||
destination.size(), 0);
|
||||
const std::ptrdiff_t rc = recv_socket(impl.fd, destination.data(),
|
||||
destination.size());
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
if (rc == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
if (socket_would_block(code)) {
|
||||
auto waited = wait_fd(impl.fd, POLLIN, deadline, token,
|
||||
"read");
|
||||
if (!waited.has_value()) {
|
||||
@@ -702,7 +840,7 @@ namespace Void::Net
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TCP read failed: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(code)))};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,14 +889,15 @@ namespace Void::Net
|
||||
continue;
|
||||
}
|
||||
if (error_code == SSL_ERROR_SYSCALL) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TLS write failed: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(code)))};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::tls_error,
|
||||
@@ -769,15 +908,16 @@ namespace Void::Net
|
||||
#else
|
||||
constexpr int flags = 0;
|
||||
#endif
|
||||
const ssize_t rc =
|
||||
::send(impl.fd, source.data(), source.size(), flags);
|
||||
const std::ptrdiff_t rc =
|
||||
send_socket(impl.fd, source.data(), source.size(), flags);
|
||||
if (rc > 0) {
|
||||
return static_cast<std::size_t>(rc);
|
||||
}
|
||||
if (rc < 0 && errno == EINTR) {
|
||||
const int code = socket_last_error();
|
||||
if (rc < 0 && socket_interrupted(code)) {
|
||||
continue;
|
||||
}
|
||||
if (rc < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
|
||||
if (rc < 0 && socket_would_block(code)) {
|
||||
auto waited = wait_fd(impl.fd, POLLOUT, deadline, token,
|
||||
"write");
|
||||
if (!waited.has_value()) {
|
||||
@@ -788,7 +928,7 @@ namespace Void::Net
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net: TCP write failed: {}",
|
||||
std::strerror(errno)))};
|
||||
socket_error_text(code)))};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -868,5 +1008,4 @@ namespace Void::Net
|
||||
m_impl->close_all();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
} // namespace Void::Net
|
||||
+172
-32
@@ -4,7 +4,16 @@
|
||||
|
||||
#include <openssl/evp.h>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
@@ -17,6 +26,7 @@
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <format>
|
||||
@@ -26,6 +36,125 @@ namespace Void::Net
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#ifdef _WIN32
|
||||
using SocketHandle = std::intptr_t;
|
||||
|
||||
void ensure_winsock()
|
||||
{
|
||||
static const int started = [] {
|
||||
WSADATA data{};
|
||||
return ::WSAStartup(MAKEWORD(2, 2), &data);
|
||||
}();
|
||||
(void)started;
|
||||
}
|
||||
|
||||
[[nodiscard]] int socket_last_error() noexcept
|
||||
{
|
||||
return ::WSAGetLastError();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_interrupted(int code) noexcept
|
||||
{
|
||||
return code == WSAEINTR;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_would_block(int code) noexcept
|
||||
{
|
||||
return code == WSAEWOULDBLOCK;
|
||||
}
|
||||
|
||||
[[nodiscard]] int poll_socket(SocketHandle fd, short events,
|
||||
int timeout) noexcept
|
||||
{
|
||||
WSAPOLLFD descriptor{};
|
||||
descriptor.fd = static_cast<SOCKET>(fd);
|
||||
descriptor.events = events;
|
||||
return ::WSAPoll(&descriptor, 1, timeout);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t send_socket(SocketHandle fd,
|
||||
const void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
return ::send(static_cast<SOCKET>(fd),
|
||||
static_cast<const char*>(data),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
size, static_cast<std::size_t>(INT_MAX))),
|
||||
0);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t recv_socket(SocketHandle fd, void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
return ::recv(static_cast<SOCKET>(fd),
|
||||
static_cast<char*>(data),
|
||||
static_cast<int>(std::min<std::size_t>(
|
||||
size, static_cast<std::size_t>(INT_MAX))),
|
||||
0);
|
||||
}
|
||||
|
||||
void close_socket(SocketHandle fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::closesocket(static_cast<SOCKET>(fd));
|
||||
}
|
||||
|
||||
void shutdown_socket(SocketHandle fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::shutdown(static_cast<SOCKET>(fd), SD_BOTH);
|
||||
}
|
||||
#else
|
||||
using SocketHandle = int;
|
||||
|
||||
void ensure_winsock() {}
|
||||
|
||||
[[nodiscard]] int socket_last_error() noexcept { return errno; }
|
||||
|
||||
[[nodiscard]] bool socket_interrupted(int code) noexcept
|
||||
{
|
||||
return code == EINTR;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool socket_would_block(int code) noexcept
|
||||
{
|
||||
return code == EAGAIN || code == EWOULDBLOCK;
|
||||
}
|
||||
|
||||
[[nodiscard]] int poll_socket(SocketHandle fd, short events,
|
||||
int timeout) noexcept
|
||||
{
|
||||
pollfd descriptor{.fd = fd, .events = events, .revents = 0};
|
||||
return ::poll(&descriptor, 1, timeout);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t send_socket(SocketHandle fd,
|
||||
const void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
constexpr int flags = 0;
|
||||
#endif
|
||||
return ::send(fd, data, size, flags);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::ptrdiff_t recv_socket(SocketHandle fd, void* data,
|
||||
std::size_t size) noexcept
|
||||
{
|
||||
return ::recv(fd, data, size, 0);
|
||||
}
|
||||
|
||||
void close_socket(SocketHandle fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::close(fd);
|
||||
}
|
||||
|
||||
void shutdown_socket(SocketHandle fd) noexcept
|
||||
{
|
||||
if (fd >= 0) (void)::shutdown(fd, SHUT_RDWR);
|
||||
}
|
||||
#endif
|
||||
|
||||
constexpr std::string_view kWsGuid =
|
||||
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
@@ -103,7 +232,7 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_all_fd(int fd, std::span<const std::byte> data,
|
||||
send_all_fd(SocketHandle fd, std::span<const std::byte> data,
|
||||
std::chrono::milliseconds timeout)
|
||||
{
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
@@ -119,36 +248,34 @@ namespace Void::Net
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - now)
|
||||
.count();
|
||||
struct pollfd pfd{};
|
||||
pfd.fd = fd;
|
||||
pfd.events = POLLOUT;
|
||||
const int pr = ::poll(
|
||||
&pfd, 1,
|
||||
const int pr = poll_socket(
|
||||
fd, POLLOUT,
|
||||
static_cast<int>(std::max<long long>(1, rem_ms)));
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code)) continue;
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocketClient: poll write failed",
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (pr == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
"Net::WebSocketClient: write timed out")};
|
||||
}
|
||||
const ssize_t w = ::send(
|
||||
fd, reinterpret_cast<const char*>(data.data()) + off,
|
||||
data.size() - off, MSG_NOSIGNAL);
|
||||
const std::ptrdiff_t w =
|
||||
send_socket(fd, data.data() + off, data.size() - off);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocketClient: send failed",
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (w == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
@@ -161,7 +288,7 @@ namespace Void::Net
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
recv_some_fd(int fd, std::span<std::byte> dst,
|
||||
recv_some_fd(SocketHandle fd, std::span<std::byte> dst,
|
||||
std::chrono::milliseconds timeout)
|
||||
{
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
@@ -176,34 +303,34 @@ namespace Void::Net
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
deadline - now)
|
||||
.count();
|
||||
struct pollfd pfd{};
|
||||
pfd.fd = fd;
|
||||
pfd.events = POLLIN;
|
||||
const int pr = ::poll(
|
||||
&pfd, 1,
|
||||
const int pr = poll_socket(
|
||||
fd, POLLIN,
|
||||
static_cast<int>(std::max<long long>(1, rem_ms)));
|
||||
if (pr < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code)) continue;
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocketClient: poll read failed",
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
if (pr == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
"Net::WebSocketClient: read timed out")};
|
||||
}
|
||||
const ssize_t r = ::recv(fd, dst.data(), dst.size(), 0);
|
||||
const std::ptrdiff_t r =
|
||||
recv_socket(fd, dst.data(), dst.size());
|
||||
if (r < 0) {
|
||||
if (errno == EINTR || errno == EAGAIN ||
|
||||
errno == EWOULDBLOCK) {
|
||||
const int code = socket_last_error();
|
||||
if (socket_interrupted(code) ||
|
||||
socket_would_block(code)) {
|
||||
continue;
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocketClient: recv failed",
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
std::error_code{code, std::generic_category()})};
|
||||
}
|
||||
return static_cast<std::size_t>(r);
|
||||
}
|
||||
@@ -681,7 +808,7 @@ namespace Void::Net
|
||||
// ── WebSocketClient ─────────────────────────────────────────────────────
|
||||
|
||||
struct WebSocketClient::Impl {
|
||||
int fd{-1};
|
||||
SocketHandle fd{-1};
|
||||
bool open{false};
|
||||
bool close_sent{false};
|
||||
std::optional<std::string> selected_subprotocol{};
|
||||
@@ -689,7 +816,7 @@ namespace Void::Net
|
||||
WebSocketDecoder decoder{false};
|
||||
std::deque<WebSocketMessage> pending{};
|
||||
|
||||
Impl(int f, WebSocketLimits lim)
|
||||
Impl(SocketHandle f, WebSocketLimits lim)
|
||||
: fd(f), open(f >= 0), limits(lim), decoder(false, lim)
|
||||
{
|
||||
}
|
||||
@@ -700,8 +827,8 @@ namespace Void::Net
|
||||
{
|
||||
open = false;
|
||||
if (fd >= 0) {
|
||||
(void)::shutdown(fd, SHUT_RDWR);
|
||||
(void)::close(fd);
|
||||
shutdown_socket(fd);
|
||||
close_socket(fd);
|
||||
fd = -1;
|
||||
}
|
||||
}
|
||||
@@ -752,8 +879,20 @@ namespace Void::Net
|
||||
"Net::WebSocketClient: failed to resolve host")};
|
||||
}
|
||||
|
||||
int fd = -1;
|
||||
ensure_winsock();
|
||||
SocketHandle fd = -1;
|
||||
for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) {
|
||||
#ifdef _WIN32
|
||||
SOCKET s = ::socket(p->ai_family, p->ai_socktype,
|
||||
p->ai_protocol);
|
||||
if (s == INVALID_SOCKET) continue;
|
||||
if (::connect(s, p->ai_addr,
|
||||
static_cast<int>(p->ai_addrlen)) == 0) {
|
||||
fd = static_cast<SocketHandle>(s);
|
||||
break;
|
||||
}
|
||||
::closesocket(s);
|
||||
#else
|
||||
#ifdef SOCK_CLOEXEC
|
||||
int s = ::socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC,
|
||||
p->ai_protocol);
|
||||
@@ -766,6 +905,7 @@ namespace Void::Net
|
||||
break;
|
||||
}
|
||||
::close(s);
|
||||
#endif
|
||||
}
|
||||
::freeaddrinfo(res);
|
||||
if (fd < 0) {
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
void_add_module(Net
|
||||
INTERNAL_DEPS Functional Text Time
|
||||
# The HTTP server is POSIX-only. Windows builds get the client-side
|
||||
# surface; a Windows server port is explicitly out of scope, and any
|
||||
# server symbol left undefined fails closed at link time.
|
||||
EXCLUDE_SOURCES_WIN32
|
||||
HttpServer.cpp
|
||||
EXTERNAL_DEPS
|
||||
Boost::headers
|
||||
Boost::beast
|
||||
@@ -13,6 +8,7 @@ void_add_module(Net
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
Threads::Threads
|
||||
DEPS_WIN32 ws2_32
|
||||
)
|
||||
|
||||
if(VOID_ENABLE_TSAN AND TARGET Void_Net)
|
||||
|
||||
@@ -132,7 +132,8 @@ namespace
|
||||
continue;
|
||||
}
|
||||
const auto rel = canon_file.lexically_relative(canon_root);
|
||||
if (!rel.empty() && rel.native() != "." && *rel.begin() != "..") {
|
||||
if (!rel.empty() && rel != std::filesystem::path{"."} &&
|
||||
*rel.begin() != std::filesystem::path{".."}) {
|
||||
out_canonical = canon_file;
|
||||
return true;
|
||||
}
|
||||
|
||||
+165
-11
@@ -26,10 +26,38 @@
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <winioctl.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#endif
|
||||
|
||||
namespace Void::Update
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#ifdef _WIN32
|
||||
// MinGW's headers do not declare REPARSE_DATA_BUFFER; only the mount
|
||||
// point layout is needed here.
|
||||
struct MountPointReparseBuffer {
|
||||
ULONG ReparseTag;
|
||||
USHORT ReparseDataLength;
|
||||
USHORT Reserved;
|
||||
USHORT SubstituteNameOffset;
|
||||
USHORT SubstituteNameLength;
|
||||
USHORT PrintNameOffset;
|
||||
USHORT PrintNameLength;
|
||||
WCHAR PathBuffer[1];
|
||||
};
|
||||
#endif
|
||||
[[nodiscard]] Void::Result::Error
|
||||
filesystem_error(std::string_view operation,
|
||||
const std::filesystem::path& path,
|
||||
@@ -97,6 +125,124 @@ namespace Void::Update
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// The activation pointer is a directory junction: unlike a symbolic
|
||||
// link it needs no SeCreateSymbolicLinkPrivilege (Developer Mode or an
|
||||
// elevated process), so it works on a stock Windows installation.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create_activation_junction(const std::filesystem::path& path,
|
||||
const std::filesystem::path& target)
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::remove(path, error);
|
||||
if (!::CreateDirectoryW(path.c_str(), nullptr)) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: create junction directory '{}': {}",
|
||||
path.string(), std::system_category().message(
|
||||
static_cast<int>(::GetLastError()))));
|
||||
}
|
||||
const HANDLE handle = ::CreateFileW(
|
||||
path.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
nullptr);
|
||||
if (handle == INVALID_HANDLE_VALUE) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: open junction '{}': {}", path.string(),
|
||||
std::system_category().message(
|
||||
static_cast<int>(::GetLastError()))));
|
||||
}
|
||||
const auto absolute = std::filesystem::absolute(target).native();
|
||||
const std::wstring substitute = L"\\??\\" + absolute;
|
||||
const std::size_t substitute_bytes = substitute.size() * sizeof(wchar_t);
|
||||
const std::size_t print_bytes = absolute.size() * sizeof(wchar_t);
|
||||
const std::size_t data_size = 8 + substitute_bytes + 2 +
|
||||
print_bytes + 2;
|
||||
std::vector<std::byte> buffer(
|
||||
offsetof(MountPointReparseBuffer, PathBuffer) + data_size);
|
||||
auto* reparse =
|
||||
reinterpret_cast<MountPointReparseBuffer*>(buffer.data());
|
||||
reparse->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
|
||||
reparse->ReparseDataLength =
|
||||
static_cast<USHORT>(data_size);
|
||||
reparse->Reserved = 0;
|
||||
reparse->SubstituteNameOffset = 0;
|
||||
reparse->SubstituteNameLength =
|
||||
static_cast<USHORT>(substitute_bytes);
|
||||
reparse->PrintNameOffset =
|
||||
static_cast<USHORT>(substitute_bytes + sizeof(wchar_t));
|
||||
reparse->PrintNameLength =
|
||||
static_cast<USHORT>(print_bytes);
|
||||
std::memcpy(
|
||||
reparse->PathBuffer, substitute.data(),
|
||||
substitute_bytes);
|
||||
reparse->PathBuffer[substitute.size()] = L'\0';
|
||||
std::memcpy(reparse->PathBuffer +
|
||||
substitute.size() + 1,
|
||||
absolute.data(), print_bytes);
|
||||
reparse->PathBuffer[substitute.size() + 1 + absolute.size()] = L'\0';
|
||||
DWORD returned = 0;
|
||||
const BOOL ok = ::DeviceIoControl(
|
||||
handle, FSCTL_SET_REPARSE_POINT, buffer.data(),
|
||||
static_cast<DWORD>(buffer.size()), nullptr, 0, &returned,
|
||||
nullptr);
|
||||
const int code = ok ? 0 : static_cast<int>(::GetLastError());
|
||||
(void)::CloseHandle(handle);
|
||||
if (!ok) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: set junction '{}': {}", path.string(),
|
||||
std::system_category().message(code)));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::filesystem::path>
|
||||
read_activation_junction(const std::filesystem::path& path)
|
||||
{
|
||||
const HANDLE handle = ::CreateFileW(
|
||||
path.c_str(), 0,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
nullptr);
|
||||
if (handle == INVALID_HANDLE_VALUE) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: open pointer '{}': {}", path.string(),
|
||||
std::system_category().message(
|
||||
static_cast<int>(::GetLastError()))));
|
||||
}
|
||||
std::vector<std::byte> buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
|
||||
DWORD returned = 0;
|
||||
const BOOL ok = ::DeviceIoControl(
|
||||
handle, FSCTL_GET_REPARSE_POINT, nullptr, 0, buffer.data(),
|
||||
static_cast<DWORD>(buffer.size()), &returned, nullptr);
|
||||
const int code = ok ? 0 : static_cast<int>(::GetLastError());
|
||||
(void)::CloseHandle(handle);
|
||||
if (!ok) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: read pointer '{}': {}", path.string(),
|
||||
std::system_category().message(code)));
|
||||
}
|
||||
auto* reparse =
|
||||
reinterpret_cast<MountPointReparseBuffer*>(buffer.data());
|
||||
if (reparse->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
|
||||
return Void::Result::fail(std::format(
|
||||
"VersionStore: pointer '{}' is not a junction",
|
||||
path.string()));
|
||||
}
|
||||
const std::size_t offset =
|
||||
reparse->SubstituteNameOffset /
|
||||
sizeof(wchar_t);
|
||||
const std::size_t length =
|
||||
reparse->SubstituteNameLength /
|
||||
sizeof(wchar_t);
|
||||
std::wstring target(
|
||||
reparse->PathBuffer + offset, length);
|
||||
constexpr std::wstring_view prefix = L"\\??\\";
|
||||
if (target.starts_with(prefix)) {
|
||||
target.erase(0, prefix.size());
|
||||
}
|
||||
return std::filesystem::path{target};
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
@@ -640,15 +786,7 @@ namespace Void::Update
|
||||
atomic_link(const std::filesystem::path& path,
|
||||
const std::filesystem::path& target)
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::remove(path, error);
|
||||
error.clear();
|
||||
std::filesystem::create_directory_symlink(target, path, error);
|
||||
if (error) {
|
||||
return std::unexpected{
|
||||
filesystem_error("create symlink", path, error)};
|
||||
}
|
||||
return {};
|
||||
return create_activation_junction(path, target);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
@@ -1843,22 +1981,38 @@ namespace Void::Update
|
||||
VersionStore::currentVersion() const
|
||||
{
|
||||
std::error_code error;
|
||||
std::filesystem::path target;
|
||||
const auto status =
|
||||
std::filesystem::symlink_status(m_root / "current", error);
|
||||
if (error == std::errc::no_such_file_or_directory ||
|
||||
status.type() == std::filesystem::file_type::not_found) {
|
||||
return std::optional<Semver::Version>{};
|
||||
}
|
||||
#ifdef _WIN32
|
||||
// The activation pointer is a junction on Windows, which the filesystem
|
||||
// reports as a directory; resolve it to its target.
|
||||
if (error || !std::filesystem::is_directory(status)) {
|
||||
return Void::Result::fail(
|
||||
"VersionStore: current is not a valid pointer");
|
||||
}
|
||||
auto resolved = read_activation_junction(m_root / "current");
|
||||
if (!resolved) {
|
||||
return std::unexpected{resolved.error()};
|
||||
}
|
||||
// Normalize to the relative form the shared checks below expect; the
|
||||
// published-directory check verifies it under this store.
|
||||
target = std::filesystem::path{"versions"} / resolved->filename();
|
||||
#else
|
||||
if (error || !std::filesystem::is_symlink(status)) {
|
||||
return Void::Result::fail(
|
||||
"VersionStore: current is not a valid symlink");
|
||||
}
|
||||
const auto target =
|
||||
std::filesystem::read_symlink(m_root / "current", error);
|
||||
target = std::filesystem::read_symlink(m_root / "current", error);
|
||||
if (error || target.parent_path() != "versions") {
|
||||
return Void::Result::fail(
|
||||
"VersionStore: current symlink target is invalid");
|
||||
}
|
||||
#endif
|
||||
auto version = Semver::parse_strict(target.filename().string());
|
||||
if (!version) {
|
||||
return Void::Result::fail(
|
||||
|
||||
@@ -9,10 +9,57 @@
|
||||
#include <openssl/x509.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <process.h>
|
||||
#ifndef MSG_NOSIGNAL
|
||||
#define MSG_NOSIGNAL 0
|
||||
#endif
|
||||
inline int test_close_socket(int fd) noexcept
|
||||
{
|
||||
return ::closesocket(static_cast<SOCKET>(fd));
|
||||
}
|
||||
inline int test_last_socket_error() noexcept
|
||||
{
|
||||
return ::WSAGetLastError();
|
||||
}
|
||||
inline bool test_interrupted(int code) noexcept
|
||||
{
|
||||
return code == WSAEINTR;
|
||||
}
|
||||
inline int test_getpid() noexcept
|
||||
{
|
||||
return ::_getpid();
|
||||
}
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
inline int test_close_socket(int fd) noexcept
|
||||
{
|
||||
return ::close(fd);
|
||||
}
|
||||
inline int test_last_socket_error() noexcept
|
||||
{
|
||||
return errno;
|
||||
}
|
||||
inline bool test_interrupted(int code) noexcept
|
||||
{
|
||||
return code == EINTR;
|
||||
}
|
||||
inline int test_getpid() noexcept
|
||||
{
|
||||
return ::getpid();
|
||||
}
|
||||
#endif
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
@@ -29,7 +76,7 @@ namespace Void::Testing::NetSupport
|
||||
{
|
||||
static unsigned counter = 0;
|
||||
auto path = std::filesystem::temp_directory_path() /
|
||||
(std::string{prefix} + std::to_string(::getpid()) + "_" +
|
||||
(std::string{prefix} + std::to_string(test_getpid()) + "_" +
|
||||
std::to_string(counter++));
|
||||
std::filesystem::create_directories(path);
|
||||
return path;
|
||||
@@ -97,12 +144,12 @@ namespace Void::Testing::NetSupport
|
||||
|
||||
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
|
||||
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
|
||||
FILE* cf = std::fopen(cert_path.c_str(), "wb");
|
||||
FILE* cf = std::fopen(cert_path.string().c_str(), "wb");
|
||||
Void::Testing::require(cf != nullptr);
|
||||
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
|
||||
std::fclose(cf);
|
||||
|
||||
FILE* kf = std::fopen(key_path.c_str(), "wb");
|
||||
FILE* kf = std::fopen(key_path.string().c_str(), "wb");
|
||||
Void::Testing::require(kf != nullptr);
|
||||
Void::Testing::require(PEM_write_PrivateKey(
|
||||
kf, pkey.get(), nullptr, nullptr, 0,
|
||||
@@ -121,7 +168,8 @@ namespace Void::Testing::NetSupport
|
||||
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
Void::Testing::require(fd >= 0);
|
||||
int yes = 1;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
|
||||
reinterpret_cast<const char*>(&yes),
|
||||
sizeof(yes));
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
@@ -144,23 +192,23 @@ namespace Void::Testing::NetSupport
|
||||
~LoopbackListener()
|
||||
{
|
||||
if (fd >= 0) {
|
||||
::close(fd);
|
||||
(void)test_close_socket(fd);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] int accept_one() const
|
||||
{
|
||||
return ::accept(fd, nullptr, nullptr);
|
||||
return static_cast<int>(::accept(fd, nullptr, nullptr));
|
||||
}
|
||||
};
|
||||
|
||||
inline bool write_all(int fd, std::string_view data)
|
||||
{
|
||||
while (!data.empty()) {
|
||||
const ssize_t written =
|
||||
const std::ptrdiff_t written =
|
||||
::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
|
||||
if (written <= 0) {
|
||||
if (written < 0 && errno == EINTR) {
|
||||
if (written < 0 && test_interrupted(test_last_socket_error())) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
@@ -178,7 +226,7 @@ namespace Void::Testing::NetSupport
|
||||
while (buffer.find(delimiter) == std::string::npos &&
|
||||
buffer.size() <= max_bytes) {
|
||||
char chunk[1024];
|
||||
const ssize_t count = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||
const std::ptrdiff_t count = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||
if (count <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// @requires-posix: reloads stateful plugin shared objects (dlfcn semantics).
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Fsm/Orchestrator.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
@@ -25,7 +24,7 @@ using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
#if defined(VOID_SERVICE_V1_PATH) && defined(VOID_SERVICE_V2_PATH) && \
|
||||
__has_include(<dlfcn.h>)
|
||||
(__has_include(<dlfcn.h>) || defined(_WIN32))
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -36,6 +35,15 @@ namespace
|
||||
staging += ".incoming";
|
||||
std::filesystem::copy_file(
|
||||
src, staging, std::filesystem::copy_options::overwrite_existing);
|
||||
#ifdef _WIN32
|
||||
// A loaded image can be renamed away but not replaced in place.
|
||||
std::error_code error;
|
||||
auto retired = dst;
|
||||
retired += ".old";
|
||||
std::filesystem::remove(retired, error);
|
||||
error.clear();
|
||||
std::filesystem::rename(dst, retired, error);
|
||||
#endif
|
||||
std::filesystem::rename(staging, dst);
|
||||
}
|
||||
|
||||
@@ -73,6 +81,11 @@ namespace
|
||||
// progressing to completion.
|
||||
Void::Testing::Test internal_fsm_service_hot_reload_under_load()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
// Reload-under-load is timing sensitive; the three deterministic reload
|
||||
// tests below cover the Windows path in the meantime.
|
||||
Void::Testing::skip("reload-under-load is not stable on Windows yet");
|
||||
#endif
|
||||
Void::FileSystem::TempDir tmp{"void_svcplugin"};
|
||||
const auto so = tmp.path() / "calc.so";
|
||||
std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so);
|
||||
|
||||
@@ -140,10 +140,13 @@ expect_configure_failure(wasm-rejects-net
|
||||
-DVOID_ENABLED_MODULES=Net
|
||||
-DVOID_ENABLE_TESTING=OFF)
|
||||
|
||||
# Missing external dependency fails with the dependency name.
|
||||
# Missing external dependency fails with the dependency name. The vendored
|
||||
# amalgamation would otherwise satisfy Sqlite on every platform, so point the
|
||||
# amalgamation directory at a non-existent path to force the find_package path.
|
||||
expect_configure_failure(missing-sqlite "SQLite3"
|
||||
-DVOID_ENABLED_MODULES=Sqlite
|
||||
-DVOID_ENABLE_TESTING=OFF
|
||||
-DVOID_SQLITE3_AMALGAMATION_DIR=/nonexistent/void-sqlite
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
|
||||
# The pure subset must configure for wasm and record the target.
|
||||
|
||||
@@ -169,7 +169,7 @@ Void::Testing::Test future_pool_stopped_after_close()
|
||||
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
|
||||
Void::Testing::expect_eq(callable.moves->load(), 0);
|
||||
Void::Testing::expect(callable.payload != nullptr);
|
||||
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{0});
|
||||
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
|
||||
Void::Testing::require(fx.exec->join().has_value());
|
||||
Void::Testing::expect(!ran.load());
|
||||
}
|
||||
|
||||
@@ -12,16 +12,44 @@
|
||||
#include <openssl/x509.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#ifndef SHUT_RDWR
|
||||
#define SHUT_RDWR SD_BOTH
|
||||
#endif
|
||||
#ifndef MSG_NOSIGNAL
|
||||
#define MSG_NOSIGNAL 0
|
||||
#endif
|
||||
using SocketLength = int;
|
||||
inline void close_socket(int fd) noexcept
|
||||
{
|
||||
(void)::closesocket(static_cast<SOCKET>(fd));
|
||||
}
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
using SocketLength = socklen_t;
|
||||
inline void close_socket(int fd) noexcept
|
||||
{
|
||||
(void)::close(fd);
|
||||
}
|
||||
#endif
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <netinet/in.h>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
@@ -40,13 +68,14 @@ namespace
|
||||
{
|
||||
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int yes = 1;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
|
||||
reinterpret_cast<const char*>(&yes), sizeof(yes));
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0;
|
||||
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
|
||||
socklen_t len = sizeof(addr);
|
||||
SocketLength len = sizeof(addr);
|
||||
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
|
||||
port = ntohs(addr.sin_port);
|
||||
::listen(fd, 1);
|
||||
@@ -55,15 +84,15 @@ namespace
|
||||
int conn = ::accept(fd, nullptr, nullptr);
|
||||
if (conn < 0) return;
|
||||
char buf[4096];
|
||||
const auto n = ::read(conn, buf, sizeof(buf));
|
||||
const auto n = ::recv(conn, buf, sizeof(buf), 0);
|
||||
if (n > 0) last_request.assign(buf, buf + n);
|
||||
const std::string resp =
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: " +
|
||||
std::to_string(body.size()) +
|
||||
"\r\nConnection: close\r\n\r\n" + body;
|
||||
[[maybe_unused]] auto w =
|
||||
::write(conn, resp.data(), resp.size());
|
||||
::close(conn);
|
||||
::send(conn, resp.data(), resp.size(), 0);
|
||||
close_socket(conn);
|
||||
served = true;
|
||||
});
|
||||
}
|
||||
@@ -71,7 +100,7 @@ namespace
|
||||
~OneShotServer()
|
||||
{
|
||||
if (worker.joinable()) worker.join();
|
||||
if (fd >= 0) ::close(fd);
|
||||
if (fd >= 0) close_socket(fd);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -120,12 +149,12 @@ namespace
|
||||
|
||||
const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem");
|
||||
const auto key_path = dir / (std::string{"key_"} + tag + ".pem");
|
||||
FILE* cf = std::fopen(cert_path.c_str(), "wb");
|
||||
FILE* cf = std::fopen(cert_path.string().c_str(), "wb");
|
||||
Void::Testing::require(cf != nullptr);
|
||||
Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1);
|
||||
std::fclose(cf);
|
||||
|
||||
FILE* kf = std::fopen(key_path.c_str(), "wb");
|
||||
FILE* kf = std::fopen(key_path.string().c_str(), "wb");
|
||||
Void::Testing::require(kf != nullptr);
|
||||
Void::Testing::require(PEM_write_PrivateKey(kf, pkey.get(), nullptr,
|
||||
nullptr, 0, nullptr,
|
||||
@@ -145,15 +174,18 @@ namespace
|
||||
ctx = SSL_CTX_new(TLS_server_method());
|
||||
Void::Testing::require(ctx != nullptr);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_certificate_file(ctx, creds.cert_file.c_str(),
|
||||
SSL_FILETYPE_PEM) == 1);
|
||||
SSL_CTX_use_certificate_file(ctx,
|
||||
creds.cert_file.string().c_str(),
|
||||
SSL_FILETYPE_PEM) == 1);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_PrivateKey_file(ctx, creds.key_file.c_str(),
|
||||
SSL_CTX_use_PrivateKey_file(ctx,
|
||||
creds.key_file.string().c_str(),
|
||||
SSL_FILETYPE_PEM) == 1);
|
||||
|
||||
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int yes = 1;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
|
||||
reinterpret_cast<const char*>(&yes), sizeof(yes));
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
@@ -161,7 +193,7 @@ namespace
|
||||
Void::Testing::require(
|
||||
::bind(fd, reinterpret_cast<sockaddr*>(&addr),
|
||||
sizeof(addr)) == 0);
|
||||
socklen_t len = sizeof(addr);
|
||||
SocketLength len = sizeof(addr);
|
||||
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
|
||||
port = ntohs(addr.sin_port);
|
||||
Void::Testing::require(::listen(fd, 1) == 0);
|
||||
@@ -183,14 +215,14 @@ namespace
|
||||
SSL_shutdown(ssl);
|
||||
}
|
||||
SSL_free(ssl);
|
||||
::close(conn);
|
||||
close_socket(conn);
|
||||
});
|
||||
}
|
||||
|
||||
~OneShotTlsServer()
|
||||
{
|
||||
if (worker.joinable()) worker.join();
|
||||
if (fd >= 0) ::close(fd);
|
||||
if (fd >= 0) close_socket(fd);
|
||||
if (ctx != nullptr) SSL_CTX_free(ctx);
|
||||
}
|
||||
};
|
||||
@@ -256,13 +288,14 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
|
||||
{
|
||||
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int yes = 1;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
|
||||
reinterpret_cast<const char*>(&yes), sizeof(yes));
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0;
|
||||
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
|
||||
socklen_t len = sizeof(addr);
|
||||
SocketLength len = sizeof(addr);
|
||||
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
|
||||
port = ntohs(addr.sin_port);
|
||||
::listen(fd, 1);
|
||||
@@ -273,10 +306,14 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server()
|
||||
|
||||
~StallServer()
|
||||
{
|
||||
if (fd >= 0) ::shutdown(fd, SHUT_RDWR);
|
||||
// Close the listener first: on Windows, shutdown() does not wake a
|
||||
// thread blocked in accept().
|
||||
if (fd >= 0) {
|
||||
close_socket(fd);
|
||||
fd = -1;
|
||||
}
|
||||
if (worker.joinable()) worker.join();
|
||||
if (conn >= 0) ::close(conn);
|
||||
if (fd >= 0) ::close(fd);
|
||||
if (conn >= 0) close_socket(conn);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -3,11 +3,28 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <cstddef>
|
||||
using ssize_t = std::ptrdiff_t;
|
||||
#ifndef MSG_NOSIGNAL
|
||||
#define MSG_NOSIGNAL 0
|
||||
#endif
|
||||
#define close closesocket
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -42,11 +59,19 @@ namespace
|
||||
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
Void::Testing::require(fd >= 0);
|
||||
|
||||
#ifdef _WIN32
|
||||
DWORD tv = 3000;
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO,
|
||||
reinterpret_cast<const char*>(&tv), sizeof(tv));
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO,
|
||||
reinterpret_cast<const char*>(&tv), sizeof(tv));
|
||||
#else
|
||||
timeval tv{};
|
||||
tv.tv_sec = 3;
|
||||
tv.tv_usec = 0;
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||
#endif
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
|
||||
@@ -4,10 +4,24 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#ifndef SHUT_WR
|
||||
#define SHUT_WR SD_SEND
|
||||
#endif
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -31,9 +45,18 @@ namespace
|
||||
using Void::Net::ServerRequest;
|
||||
using Void::Net::ServerResponse;
|
||||
|
||||
void close_socket(int fd) noexcept
|
||||
{
|
||||
#ifdef _WIN32
|
||||
(void)::closesocket(static_cast<SOCKET>(fd));
|
||||
#else
|
||||
(void)::close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string raw_http_exchange(std::uint16_t port, std::string_view raw_req)
|
||||
{
|
||||
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
const int fd = static_cast<int>(::socket(AF_INET, SOCK_STREAM, 0));
|
||||
Void::Testing::require(fd >= 0);
|
||||
|
||||
sockaddr_in addr{};
|
||||
@@ -46,7 +69,7 @@ namespace
|
||||
|
||||
std::size_t off = 0;
|
||||
while (off < raw_req.size()) {
|
||||
const ssize_t w =
|
||||
const std::ptrdiff_t w =
|
||||
::send(fd, raw_req.data() + off, raw_req.size() - off, 0);
|
||||
Void::Testing::require(w > 0);
|
||||
off += static_cast<std::size_t>(w);
|
||||
@@ -56,13 +79,13 @@ namespace
|
||||
std::string out;
|
||||
std::array<char, 4096> buf{};
|
||||
for (;;) {
|
||||
const ssize_t r = ::recv(fd, buf.data(), buf.size(), 0);
|
||||
const std::ptrdiff_t r = ::recv(fd, buf.data(), buf.size(), 0);
|
||||
if (r <= 0) {
|
||||
break;
|
||||
}
|
||||
out.append(buf.data(), static_cast<std::size_t>(r));
|
||||
}
|
||||
(void)::close(fd);
|
||||
close_socket(fd);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -230,7 +253,7 @@ Void::Testing::Test http_server_ephemeral_methods_and_concurrent_dispatch()
|
||||
Void::Testing::expect_eq(server.bound_port(), std::uint16_t{0});
|
||||
|
||||
// No dangling listening socket after shutdown().
|
||||
const int probe = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
const int probe = static_cast<int>(::socket(AF_INET, SOCK_STREAM, 0));
|
||||
Void::Testing::require(probe >= 0);
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
@@ -239,7 +262,7 @@ Void::Testing::Test http_server_ephemeral_methods_and_concurrent_dispatch()
|
||||
Void::Testing::expect(
|
||||
::connect(probe, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) !=
|
||||
0);
|
||||
(void)::close(probe);
|
||||
close_socket(probe);
|
||||
}
|
||||
|
||||
Void::Testing::Test http_server_limits_smuggling_streaming_and_graceful_drain()
|
||||
|
||||
@@ -228,7 +228,8 @@ Void::Testing::Test net_static_file_resolver_open_safe_pins_root_and_rejects_sym
|
||||
std::ofstream f{secret};
|
||||
f << "top-secret";
|
||||
}
|
||||
std::filesystem::create_symlink(secret, root / "escape.txt");
|
||||
std::error_code link_ec;
|
||||
std::filesystem::create_symlink(secret, root / "escape.txt", link_ec);
|
||||
|
||||
auto resolver = Void::Net::StaticFileResolver::create(root);
|
||||
Void::Testing::require(resolver.has_value());
|
||||
@@ -248,9 +249,13 @@ Void::Testing::Test net_static_file_resolver_open_safe_pins_root_and_rejects_sym
|
||||
Void::Testing::require(missing.has_value());
|
||||
Void::Testing::expect(!missing->has_value());
|
||||
|
||||
// Symlink inside root is rejected by O_NOFOLLOW.
|
||||
auto sym = resolver->open_safe("/escape.txt");
|
||||
Void::Testing::expect(!sym.has_value());
|
||||
// Symlink inside root is rejected by O_NOFOLLOW (or reparse-point
|
||||
// rejection on Windows); without symlink privilege there is nothing to
|
||||
// create, so only that assertion is skipped.
|
||||
if (!link_ec) {
|
||||
auto sym = resolver->open_safe("/escape.txt");
|
||||
Void::Testing::expect(!sym.has_value());
|
||||
}
|
||||
|
||||
// Traversal rejected.
|
||||
auto trav = resolver->open_safe("/../secret.txt");
|
||||
|
||||
@@ -49,10 +49,10 @@ namespace
|
||||
Void::Testing::require(ctx != nullptr);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_certificate_file(
|
||||
ctx, cert.cert_file.c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
ctx, cert.cert_file.string().c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_PrivateKey_file(
|
||||
ctx, cert.key_file.c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
ctx, cert.key_file.string().c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
worker = std::thread([this, mode] { serve(mode); });
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ namespace
|
||||
char byte = 0;
|
||||
while (::recv(connection, &byte, 1, 0) > 0) {
|
||||
}
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ namespace
|
||||
const int accepted = SSL_accept(ssl);
|
||||
if (accepted != 1) {
|
||||
SSL_free(ssl);
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
return;
|
||||
}
|
||||
tls = true;
|
||||
@@ -205,7 +205,7 @@ namespace
|
||||
SSL_shutdown(ssl);
|
||||
SSL_free(ssl);
|
||||
}
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -38,10 +38,10 @@ namespace
|
||||
Void::Testing::require(ctx != nullptr);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_certificate_file(
|
||||
ctx, cert.cert_file.c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
ctx, cert.cert_file.string().c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
Void::Testing::require(
|
||||
SSL_CTX_use_PrivateKey_file(
|
||||
ctx, cert.key_file.c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
ctx, cert.key_file.string().c_str(), SSL_FILETYPE_PEM) == 1);
|
||||
worker = std::thread(
|
||||
[this, behavior = std::move(behavior)] {
|
||||
const int connection = listener.accept_one();
|
||||
@@ -55,7 +55,7 @@ namespace
|
||||
SSL_shutdown(ssl);
|
||||
}
|
||||
SSL_free(ssl);
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ namespace
|
||||
char byte = 0;
|
||||
while (::recv(connection, &byte, 1, 0) > 0) {
|
||||
}
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ Void::Testing::Test tls_client_never_falls_back_to_plaintext()
|
||||
char buffer[64];
|
||||
while (::recv(connection, buffer, sizeof(buffer), 0) > 0) {
|
||||
}
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
});
|
||||
auto stream = Void::Net::TlsClientStream::connect(
|
||||
make_options(listener.port));
|
||||
@@ -329,10 +329,10 @@ Void::Testing::Test tls_client_starttls_upgrade()
|
||||
SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());
|
||||
Void::Testing::require(ctx != nullptr);
|
||||
Void::Testing::require(SSL_CTX_use_certificate_file(
|
||||
ctx, cert.cert_file.c_str(),
|
||||
ctx, cert.cert_file.string().c_str(),
|
||||
SSL_FILETYPE_PEM) == 1);
|
||||
Void::Testing::require(SSL_CTX_use_PrivateKey_file(
|
||||
ctx, cert.key_file.c_str(),
|
||||
ctx, cert.key_file.string().c_str(),
|
||||
SSL_FILETYPE_PEM) == 1);
|
||||
std::thread worker([&listener, ctx] {
|
||||
const int connection = listener.accept_one();
|
||||
@@ -356,7 +356,7 @@ Void::Testing::Test tls_client_starttls_upgrade()
|
||||
SSL_shutdown(ssl);
|
||||
}
|
||||
SSL_free(ssl);
|
||||
::close(connection);
|
||||
::test_close_socket(connection);
|
||||
});
|
||||
|
||||
auto options = make_options(listener.port, cert.cert_file.string());
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
// @requires-posix: plugin discovery reloads stateful DLLs, which Windows
|
||||
// cannot unload-and-reload yet.
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
@@ -14,12 +12,22 @@ using namespace Void::Plugin;
|
||||
|
||||
#if defined(VOID_TEST_PLUGIN_PATH) && defined(VOID_STATEFUL_V1_PATH)
|
||||
|
||||
namespace
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
constexpr std::string_view kPluginExtension = ".dll";
|
||||
#else
|
||||
constexpr std::string_view kPluginExtension = ".so";
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test discovery_loads_all_plugins_in_filename_order()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_disc"};
|
||||
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH,
|
||||
tmp.path() / "b_stateful.so");
|
||||
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "a_test.so");
|
||||
tmp.path() / ("b_stateful" + std::string{kPluginExtension}));
|
||||
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH,
|
||||
tmp.path() / ("a_test" + std::string{kPluginExtension}));
|
||||
{
|
||||
std::ofstream decoy{tmp.path() / "readme.txt"};
|
||||
decoy << "not a plugin";
|
||||
@@ -29,14 +37,19 @@ Void::Testing::Test discovery_loads_all_plugins_in_filename_order()
|
||||
PluginManager mgr;
|
||||
const auto results = mgr.load_directory(tmp.path());
|
||||
|
||||
// Only the two .so files count, sorted by filename.
|
||||
// Only the two plugin files count, sorted by filename.
|
||||
Void::Testing::expect_eq(results.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(results[0].first.filename().string(),
|
||||
std::string{"a_test.so"});
|
||||
if (results.size() != 2) {
|
||||
return;
|
||||
}
|
||||
Void::Testing::expect_eq(
|
||||
results[0].first.filename().string(),
|
||||
std::string{"a_test"} + std::string{kPluginExtension});
|
||||
Void::Testing::expect(results[0].second.has_value());
|
||||
Void::Testing::expect_eq(*results[0].second, std::string{"TestPlugin"});
|
||||
Void::Testing::expect_eq(results[1].first.filename().string(),
|
||||
std::string{"b_stateful.so"});
|
||||
Void::Testing::expect_eq(
|
||||
results[1].first.filename().string(),
|
||||
std::string{"b_stateful"} + std::string{kPluginExtension});
|
||||
Void::Testing::expect(results[1].second.has_value());
|
||||
Void::Testing::expect_eq(*results[1].second, std::string{"StatefulPlugin"});
|
||||
|
||||
@@ -47,9 +60,11 @@ Void::Testing::Test discovery_loads_all_plugins_in_filename_order()
|
||||
Void::Testing::Test discovery_reports_per_file_errors()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_disc"};
|
||||
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH, tmp.path() / "ok.so");
|
||||
std::filesystem::copy_file(VOID_TEST_PLUGIN_PATH,
|
||||
tmp.path() / ("ok" + std::string{kPluginExtension}));
|
||||
{
|
||||
std::ofstream bogus{tmp.path() / "broken.so"};
|
||||
std::ofstream bogus{tmp.path() /
|
||||
("broken" + std::string{kPluginExtension})};
|
||||
bogus << "ELF? no.";
|
||||
}
|
||||
|
||||
@@ -57,7 +72,10 @@ Void::Testing::Test discovery_reports_per_file_errors()
|
||||
const auto results = mgr.load_directory(tmp.path());
|
||||
|
||||
Void::Testing::expect_eq(results.size(), std::size_t{2});
|
||||
// broken.so sorts first and fails to dlopen; ok.so loads.
|
||||
if (results.size() != 2) {
|
||||
return;
|
||||
}
|
||||
// broken sorts first and fails to dlopen; ok loads.
|
||||
Void::Testing::expect(!results[0].second.has_value());
|
||||
Void::Testing::expect(results[0].second.error() == LoadError::DlopenFailed);
|
||||
Void::Testing::expect(results[1].second.has_value());
|
||||
|
||||
@@ -27,6 +27,15 @@ namespace
|
||||
staging += ".incoming";
|
||||
std::filesystem::copy_file(
|
||||
src, staging, std::filesystem::copy_options::overwrite_existing);
|
||||
#ifdef _WIN32
|
||||
// A loaded image can be renamed away but not replaced in place.
|
||||
std::error_code error;
|
||||
auto retired = dst;
|
||||
retired += ".old";
|
||||
std::filesystem::remove(retired, error);
|
||||
error.clear();
|
||||
std::filesystem::rename(dst, retired, error);
|
||||
#endif
|
||||
std::filesystem::rename(staging, dst);
|
||||
}
|
||||
} // namespace
|
||||
@@ -34,9 +43,6 @@ namespace
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test hot_reload_under_concurrent_load()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
Void::Testing::skip("plugin hot reload is not supported on Windows yet");
|
||||
#endif
|
||||
Void::FileSystem::TempDir tmp{"void_hotload"};
|
||||
const auto so = tmp.path() / "plugin.so";
|
||||
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
|
||||
|
||||
@@ -33,6 +33,16 @@ namespace
|
||||
staging += ".incoming";
|
||||
std::filesystem::copy_file(
|
||||
src, staging, std::filesystem::copy_options::overwrite_existing);
|
||||
#ifdef _WIN32
|
||||
// Windows keeps a loaded image locked against replacement, but it can
|
||||
// be renamed away; the old generation stays mapped under the new name.
|
||||
std::error_code error;
|
||||
auto retired = dst;
|
||||
retired += ".old";
|
||||
std::filesystem::remove(retired, error);
|
||||
error.clear();
|
||||
std::filesystem::rename(dst, retired, error);
|
||||
#endif
|
||||
std::filesystem::rename(staging, dst);
|
||||
}
|
||||
} // namespace
|
||||
@@ -97,9 +107,6 @@ Void::Testing::Test manager_candidate_validator_rejects_reload_transactionally()
|
||||
|
||||
Void::Testing::Test manager_reload_migrates_v1_state_to_v2()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
Void::Testing::skip("plugin reload is not supported on Windows yet");
|
||||
#endif
|
||||
// Copy v1 into a temp path we control, then overwrite with v2 and
|
||||
// reload — exactly the in-place upgrade a deployment performs.
|
||||
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||
@@ -163,9 +170,6 @@ Void::Testing::Test manager_replace_failure_keeps_current_generation()
|
||||
|
||||
Void::Testing::Test manager_pinned_handle_survives_reload()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
Void::Testing::skip("plugin reload is not supported on Windows yet");
|
||||
#endif
|
||||
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||
const auto so = tmp.path() / "plugin.so";
|
||||
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
|
||||
@@ -212,9 +216,6 @@ Void::Testing::Test manager_legacy_transfer_state_plugin_still_reloads()
|
||||
// @tag integration
|
||||
Void::Testing::Test manager_watch_auto_reloads_on_file_change()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
Void::Testing::skip("plugin reload is not supported on Windows yet");
|
||||
#endif
|
||||
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||
const auto so = tmp.path() / "plugin.so";
|
||||
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
|
||||
@@ -245,9 +246,6 @@ Void::Testing::Test manager_watch_auto_reloads_on_file_change()
|
||||
|
||||
Void::Testing::Test manager_multiple_reload_observers_coexist()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
Void::Testing::skip("plugin reload is not supported on Windows yet");
|
||||
#endif
|
||||
Void::FileSystem::TempDir tmp{"void_mgr"};
|
||||
const auto so = tmp.path() / "plugin.so";
|
||||
std::filesystem::copy_file(VOID_STATEFUL_V1_PATH, so);
|
||||
|
||||
@@ -621,9 +621,14 @@ Void::Testing::Test version_store_prunes_without_an_active_version()
|
||||
// the new publication must still be recorded and prunable.
|
||||
std::filesystem::create_directories(store.versionPath(version1));
|
||||
Void::Testing::require(store.recordFailed(version1).has_value());
|
||||
std::ifstream healthInput{store.root() / "health.log"};
|
||||
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
|
||||
std::istreambuf_iterator<char>{}};
|
||||
std::string healthHistory;
|
||||
{
|
||||
// Close the stream before pruning: on Windows an open file handle
|
||||
// blocks the health-history rewrite.
|
||||
std::ifstream healthInput{store.root() / "health.log"};
|
||||
healthHistory.assign(std::istreambuf_iterator<char>{healthInput},
|
||||
std::istreambuf_iterator<char>{});
|
||||
}
|
||||
const auto retired = healthHistory.find("D 1.0.0\n");
|
||||
Void::Testing::require(retired != std::string::npos);
|
||||
Void::Testing::expect(healthHistory.find("F 1.0.0\n", retired) !=
|
||||
|
||||
Reference in new issue
Block a user