Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/socket.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import :platform;

namespace mcpplibs::tinyhttps {

inline std::atomic<bool> platform_started_{ false };

#ifdef TINYHTTPS_WINSOCK
using SocketHandle = SOCKET;
constexpr SocketHandle INVALID_SOCKET_FD = INVALID_SOCKET;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
17 changes: 17 additions & 0 deletions tests/test_winsock_start.cpp
Original file line number Diff line number Diff line change
@@ -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 <gtest/gtest.h>

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());
}
Loading