HTTPServer: implement and test AcceptConnection()

AcceptConnection() is mostly copied from CConmann in net.cpp
and then modernized.

Co-authored-by: Vasil Dimov <vd@FreeBSD.org>
This commit is contained in:
Matthew Zipkin
2025-06-04 14:14:13 -04:00
parent f5bc018948
commit 5a3aa1af28
5 changed files with 78 additions and 0 deletions

View File

@@ -976,4 +976,36 @@ void HTTPServer::StopListening()
{
m_listen.clear();
}
std::unique_ptr<Sock> HTTPServer::AcceptConnection(const Sock& listen_sock, CService& addr)
{
// Make sure we only operate on our own listening sockets
Assume(std::ranges::any_of(m_listen, [&](const auto& sock) { return sock.get() == &listen_sock; }));
sockaddr_storage storage;
socklen_t len{sizeof(storage)};
auto sa = reinterpret_cast<sockaddr*>(&storage);
auto sock{listen_sock.Accept(sa, &len)};
if (!sock) {
const int err{WSAGetLastError()};
if (err != WSAEWOULDBLOCK) {
LogDebug(BCLog::HTTP,
"Cannot accept new connection: %s",
NetworkErrorString(err));
}
return {};
}
// The OS handed us a valid socket but we can't determine its source address.
// In the unlikely event this occurs, the invalid address will be rejected
// by the downstream ClientAllowed() check.
if (!addr.SetSockAddr(sa, len)) {
LogDebug(BCLog::HTTP,
"Unknown socket family");
}
return sock;
}
} // namespace http_bitcoin