SocketErrorException is now a std::system_error: code() carries the errno
under std::generic_category(), or getaddrinfo's result under the new
ResolverCategory(), whose message() is gai_strerror's text; `phase` says
which step failed (resolve, open, connect, send, receive). It is still a
std::runtime_error with the message ClientTCP always threw, the code's
text after it, so existing handlers keep working.
Before, the exception carried a `kind` and an int, and a caller that had
to print the cause its own way still had to match the message prefix to
learn where the failure happened. The standard type ends both: the
category knows how to print the number, and the phase is a field. A
caller writes "[Errno {}] {}" from code().value() and code().message(),
or compares code() with std::errc::connection_refused.
Breaking: SocketErrorException's `kind` and `code` members are gone;
read code().category() and code().value().
143 lines
4.7 KiB
C++
143 lines
4.7 KiB
C++
//SPDX-License-Identifier: LGPL-3.0-only
|
|
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
// ListenerTCP can be told the address it binds and take port 0, with Port()
|
|
// reporting what the kernel picked. Before, it always bound 0.0.0.0 at a port
|
|
// the caller chose: a helper meant for this machine's own processes — a broker
|
|
// that hands out database access, say — was reachable from the network, and
|
|
// the caller had to guess a free port and hope.
|
|
//
|
|
// Also: a host name is refused rather than bound to whichever address the
|
|
// resolver ranks first, and the port-only constructor keeps listening on every
|
|
// IPv4 interface.
|
|
|
|
#include <arpa/inet.h>
|
|
#include <ifaddrs.h>
|
|
#include <netinet/in.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
#include <cerrno>
|
|
#include <cstdlib>
|
|
|
|
import Crafter.Network;
|
|
import std;
|
|
using namespace Crafter;
|
|
using namespace std::chrono_literals;
|
|
|
|
namespace {
|
|
|
|
int failures = 0;
|
|
|
|
void Check(bool ok, std::string_view what) {
|
|
std::println("{} {}", ok ? "PASS" : "FAIL", what);
|
|
if (!ok) ++failures;
|
|
}
|
|
|
|
// An IPv4 address of this host that is not loopback, if it has one.
|
|
std::optional<std::string> NonLoopbackIPv4() {
|
|
ifaddrs* interfaces = nullptr;
|
|
if (getifaddrs(&interfaces) != 0) return std::nullopt;
|
|
std::optional<std::string> found;
|
|
for (const ifaddrs* entry = interfaces; entry != nullptr && !found; entry = entry->ifa_next) {
|
|
if (entry->ifa_addr == nullptr || entry->ifa_addr->sa_family != AF_INET) continue;
|
|
const auto* v4 = reinterpret_cast<const sockaddr_in*>(entry->ifa_addr);
|
|
if (ntohl(v4->sin_addr.s_addr) >> 24 == 127) continue;
|
|
char text[INET_ADDRSTRLEN] = {};
|
|
inet_ntop(AF_INET, &v4->sin_addr, text, sizeof(text));
|
|
found = std::string(text);
|
|
}
|
|
freeifaddrs(interfaces);
|
|
return found;
|
|
}
|
|
|
|
// Runs a listener's accept loop on a thread of its own and counts the
|
|
// connections it was handed.
|
|
struct Serving {
|
|
ListenerTCP& listener;
|
|
std::atomic<int> accepted = 0;
|
|
std::thread loop;
|
|
|
|
explicit Serving(ListenerTCP& listener) : listener(listener) {
|
|
listener.connectCallback = [this](ClientTCP* client) {
|
|
++accepted;
|
|
delete client;
|
|
};
|
|
loop = std::thread([this] { this->listener.ListenSyncSync(); });
|
|
}
|
|
~Serving() {
|
|
listener.Stop();
|
|
loop.join();
|
|
}
|
|
bool WaitFor(int count) {
|
|
for (int i = 0; i < 200 && accepted.load() < count; ++i) std::this_thread::sleep_for(10ms);
|
|
return accepted.load() >= count;
|
|
}
|
|
};
|
|
|
|
} // namespace
|
|
|
|
int main() {
|
|
{
|
|
ListenerTCP listener("127.0.0.1", 0, nullptr);
|
|
const std::uint16_t port = listener.Port();
|
|
Check(port != 0, std::format("port 0 gets a port from the kernel, which Port() reports ({})", port));
|
|
Serving serving(listener);
|
|
{
|
|
ClientTCP client("127.0.0.1", port, 2s);
|
|
}
|
|
Check(serving.WaitFor(1), "a client on loopback reaches it");
|
|
|
|
if (const std::optional<std::string> outside = NonLoopbackIPv4()) {
|
|
bool refused = false;
|
|
try {
|
|
ClientTCP client(*outside, port, 2s);
|
|
} catch (const SocketErrorException& e) {
|
|
refused = e.phase == SocketPhase::Connect && e.code() == std::errc::connection_refused;
|
|
} catch (const std::exception&) {
|
|
}
|
|
Check(refused, std::format("through {} it is refused: it listens on 127.0.0.1 alone", *outside));
|
|
} else {
|
|
std::println("SKIP no non-loopback IPv4 address to try from");
|
|
}
|
|
}
|
|
|
|
{
|
|
std::optional<ListenerTCP> v6;
|
|
try {
|
|
v6.emplace("::1", 0, nullptr);
|
|
} catch (const std::exception&) {
|
|
}
|
|
if (v6) {
|
|
Serving serving(*v6);
|
|
{
|
|
ClientTCP client("::1", v6->Port(), 2s);
|
|
}
|
|
Check(serving.WaitFor(1), "an IPv6 loopback listener takes a client on ::1");
|
|
} else {
|
|
std::println("SKIP no IPv6 loopback on this host");
|
|
}
|
|
}
|
|
|
|
{
|
|
bool refused = false;
|
|
try {
|
|
ListenerTCP named("localhost", 0, nullptr);
|
|
} catch (const std::runtime_error&) {
|
|
refused = true;
|
|
}
|
|
Check(refused, "a host name is refused: the address to bind is spelled out");
|
|
}
|
|
|
|
{
|
|
ListenerTCP any(0, nullptr);
|
|
Check(any.Port() != 0, "the port-only constructor takes port 0 as well");
|
|
Serving serving(any);
|
|
{
|
|
ClientTCP client("127.0.0.1", any.Port(), 2s);
|
|
}
|
|
Check(serving.WaitFor(1), "and still listens on every IPv4 interface, loopback included");
|
|
}
|
|
|
|
std::println("{}", failures == 0 ? "all checks passed" : "check(s) failed");
|
|
return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
|
|
}
|