diff --git a/src/socket.cppm b/src/socket.cppm index de56075..18264b9 100644 --- a/src/socket.cppm +++ b/src/socket.cppm @@ -30,6 +30,8 @@ import :platform; namespace mcpplibs::tinyhttps { +inline std::atomic platform_started_{ false }; + #ifdef TINYHTTPS_WINSOCK using SocketHandle = SOCKET; constexpr SocketHandle INVALID_SOCKET_FD = INVALID_SOCKET; @@ -117,6 +119,9 @@ public: } bool connect(const char* host, int port, int timeoutMs) { + // Winsock first: a socket or getaddrinfo before WSAStartup fails with + // WSANOTINITIALISED, which reaches the caller as a bare "Connection failed". + ensure_platform_started(); // Close existing connection if any if (is_valid()) { close(); @@ -372,6 +377,22 @@ public: #endif } + // Winsock must be started before the first socket or getaddrinfo, and a + // library cannot assume its user did it: 0.3.5 never called platform_init + // itself, and on Windows every request then ended in "Connection failed" + // (status 0, nothing saying why). Every path that opens a socket calls + // this first; it runs once per process, and platform_started says whether. + static void ensure_platform_started() { + static const bool once = [] { + platform_init(); + platform_started_.store(true); + return true; + }(); + (void)once; + } + + static bool platform_started() { return platform_started_.load(); } + static void platform_cleanup() { #ifdef TINYHTTPS_WINSOCK WSACleanup(); diff --git a/tests/test_winsock_start.cpp b/tests/test_winsock_start.cpp new file mode 100644 index 0000000..c0f170e --- /dev/null +++ b/tests/test_winsock_start.cpp @@ -0,0 +1,17 @@ +// Winsock must be started before the first socket or getaddrinfo, and the +// library starts it itself: 0.3.5 never did, and on Windows every request then +// ended in "Connection failed" with no reason. This program is the first +// socket of its process, so platform_started() is false until connect runs. +#include + +import mcpplibs.tinyhttps; +import std; + +TEST(Winsock, StartedByTheFirstConnect) { + EXPECT_FALSE(mcpplibs::tinyhttps::Socket::platform_started()); + mcpplibs::tinyhttps::Socket socket; + // Nothing listens on port 1 of the loopback: the connection is refused + // quickly, which is a started Winsock answering, not an unstarted one. + socket.connect("127.0.0.1", 1, 500); + EXPECT_TRUE(mcpplibs::tinyhttps::Socket::platform_started()); +}