From c3cf8a042d961fccbb0855ad97e323bcdf3a47e1 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:10:03 -0600 Subject: [PATCH 1/3] ws2_offline: refuse the local computer's name, answer localhost with loopback literals, keep WSAIoctl synchronous From kevincommits' finding (batch 18, item 3) in #1608. - An empty name ("") passed is_loopback_node_a, so getaddrinfo, GetAddrInfoW, GetAddrInfoExA/W, gethostbyname and WSAAsyncGetHostByName forwarded it to the host, which answers with every address of the local computer (its LAN and external adapters). A null name did the same for gethostbyname and WSAAsyncGetHostByName. Both are refused now; a null getaddrinfo node (a service-only lookup: loopback, or the wildcard that bind narrows) is still answered. - "localhost" went to the host as a name, so its hosts file could map it off loopback. The lookups now hand the host a loopback literal for it (::1 for an AF_INET6 lookup, else 127.0.0.1), as WSAConnectByNameA/W already do. - WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) for ConnectEx and WSASendMsg passed the caller's overlapped and completion routine to the host along with pointers into its own stack frame. The host lookup is now synchronous, as in host_extension, and an overlapped request is reported as completed at once: status and byte count in the OVERLAPPED, its event set or its routine queued. ws2_offline_test gains section 9 for each case. With main's shim the test fails at gethostbyname(NULL) and then crashes; 83/83 checks pass with the fix. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/ws2_offline.cpp | 79 ++++++++++++++++++++----- runtime/test/ws2_offline_test.cpp | 95 +++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+), 15 deletions(-) diff --git a/runtime/shims/ws2_offline.cpp b/runtime/shims/ws2_offline.cpp index 0a278eb99f..8fbdbd27f1 100644 --- a/runtime/shims/ws2_offline.cpp +++ b/runtime/shims/ws2_offline.cpp @@ -17,15 +17,20 @@ // - bind (#2) rewrites wildcard binds (0.0.0.0 or ::) to 127.0.0.1 or ::1 so no external peer can connect in, // allows explicit loopback binds, and refuses any other address with WSAEADDRNOTAVAIL. // - getaddrinfo, GetAddrInfoW, GetAddrInfoExA/W, gethostbyname (#52), gethostbyaddr (#51), and -// WSAAsyncGetHostByName/Addr (#103/#102) permit only null/empty nodes, "localhost", and loopback IP literals; -// everything else fails with WSAHOST_NOT_FOUND without sending DNS packets. A dotted octet with a leading zero +// WSAAsyncGetHostByName/Addr (#103/#102) permit only "localhost" and loopback IP literals, and for the +// getaddrinfo family a null node (a service-only lookup: loopback, or the wildcard for AI_PASSIVE, which bind +// rewrites); everything else fails with WSAHOST_NOT_FOUND without sending DNS packets. An empty name, and a null +// one for gethostbyname, names the local computer and would return its real (LAN) addresses, so it is refused. +// "localhost" goes to the host as a loopback literal (::1 for an AF_INET6 lookup, else 127.0.0.1), as +// WSAConnectByName does, so the hosts file cannot send it off loopback. A dotted octet with a leading zero // (0127.0.0.1) is refused: Windows reads it as octal, so it is not the loopback name it looks like. // - WSALookupServiceBeginA/W (name-service queries) always fail with WSASERVICE_NOT_FOUND. // - getnameinfo / GetNameInfoW force NI_NUMERICHOST for non-loopback addresses (or return WSAHOST_NOT_FOUND when // NI_NAMEREQD is set), avoiding reverse DNS lookups. // - WSAIoctl wraps WSAID_CONNECTEX and WSAID_WSASENDMSG and refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER // with WSAEINVAL so extension functions cannot bypass the checks. The wrappers ask the host for the native -// pointer of the socket they are called on, since each Winsock provider has its own. +// pointer of the socket they are called on, since each Winsock provider has its own. The lookup itself is +// synchronous; an overlapped request is reported as completed at once (its event set, its routine queued). // // Every host ws2_32.dll call is resolved dynamically from System32 so gta6rt needs no static ws2_32.lib link // dependency. Each refused destination is logged once ("[rt] ws2: offline, refused ") with no payload. @@ -212,8 +217,11 @@ bool parse_ipv4_literal(const char* s, uint8_t out[4]) { return *p == '\0'; } +// Null: no node (a service-only getaddrinfo, answered with loopback or the wildcard). Empty: the local computer, +// whose answer is every address it has, so not loopback. bool is_loopback_node_a(const char* node) { - if (!node || !*node) return true; + if (!node) return true; + if (!*node) return false; if (ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.")) return true; uint8_t v4[4] = {}; @@ -240,7 +248,8 @@ bool is_loopback_node_a(const char* node) { } bool is_loopback_node_w(const wchar_t* node) { - if (!node || !*node) return true; + if (!node) return true; + if (!*node) return false; for (const wchar_t* p = node; *p; ++p) { if (*p >= 0x80) return false; } @@ -252,6 +261,17 @@ bool is_localhost_name_a(const char* node) { return ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost."); } +// What a lookup hands the host for `node`: "localhost" becomes a loopback literal, so the host's hosts file is never +// read for it (it could map the name off loopback); IPv6 for an AF_INET6 lookup, else IPv4. Any other node as is. +const char* lookup_node_a(const char* node, int family) { + if (!node || !is_localhost_name_a(node)) return node; + return family == AF_INET6 ? "::1" : "127.0.0.1"; +} +const wchar_t* lookup_node_w(const wchar_t* node, int family) { + if (!node || !is_localhost_name_a(narrow_ascii(node).c_str())) return node; + return family == AF_INET6 ? L"::1" : L"127.0.0.1"; +} + // ---- Socket connect / send / bind shims ---- int WSAAPI connect_offline(SOCKET s, const sockaddr* name, int namelen) { @@ -589,7 +609,7 @@ INT WSAAPI getaddrinfo_offline(PCSTR node, PCSTR service, const ADDRINFOA* hints set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(node, service, hints, result); + return real_fn(lookup_node_a(node, hints ? hints->ai_family : AF_UNSPEC), service, hints, result); } INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) { @@ -605,7 +625,7 @@ INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(node, service, hints, result); + return real_fn(lookup_node_w(node, hints ? hints->ai_family : AF_UNSPEC), service, hints, result); } INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXA* hints, @@ -625,7 +645,7 @@ INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUI set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); + return real_fn(lookup_node_a(name, hints ? hints->ai_family : AF_UNSPEC), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); } INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXW* hints, @@ -645,11 +665,11 @@ INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPG set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); + return real_fn(const_cast(lookup_node_w(name, hints ? hints->ai_family : AF_UNSPEC)), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); } hostent* WSAAPI gethostbyname_offline(const char* name) { - if (!is_loopback_node_a(name)) { + if (!name || !is_loopback_node_a(name)) { // a null name is the local computer here log_refused("gethostbyname", name ? name : ""); set_wsa_error(WSAHOST_NOT_FOUND); return nullptr; @@ -660,7 +680,7 @@ hostent* WSAAPI gethostbyname_offline(const char* name) { set_wsa_error(WSAHOST_NOT_FOUND); return nullptr; } - return real_fn(name); + return real_fn(lookup_node_a(name, AF_INET)); // IPv4 only } bool is_loopback_raw_addr(const char* addr, int len, int type) { @@ -690,7 +710,7 @@ hostent* WSAAPI gethostbyaddr_offline(const char* addr, int len, int type) { } HANDLE WSAAPI wsa_async_get_host_by_name_offline(HWND hWnd, u_int wMsg, const char* name, char* buf, int buflen) { - if (!is_loopback_node_a(name)) { + if (!name || !is_loopback_node_a(name)) { log_refused("WSAAsyncGetHostByName", name ? name : ""); set_wsa_error(WSAHOST_NOT_FOUND); return nullptr; @@ -701,7 +721,7 @@ HANDLE WSAAPI wsa_async_get_host_by_name_offline(HWND hWnd, u_int wMsg, const ch set_wsa_error(WSAHOST_NOT_FOUND); return nullptr; } - return real_fn(hWnd, wMsg, name, buf, buflen); + return real_fn(hWnd, wMsg, lookup_node_a(name, AF_INET), buf, buflen); } HANDLE WSAAPI wsa_async_get_host_by_addr_offline(HWND hWnd, u_int wMsg, const char* addr, int len, int type, @@ -828,6 +848,31 @@ int PASCAL wsa_send_msg_ext_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD return real_fn(s, msg, flags, bytes_sent, overlapped, completion); } +// An overlapped extension-pointer lookup that the shim answered synchronously: report it the way Winsock reports an +// overlapped call that completed at once (status and byte count in the OVERLAPPED, its event set, its completion +// routine queued to this thread for its next alertable wait). +void complete_now(LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion, DWORD bytes) { + if (!overlapped) return; + overlapped->Internal = 0; + overlapped->InternalHigh = bytes; + if (completion) { + struct Call { + LPWSAOVERLAPPED_COMPLETION_ROUTINE routine; + LPWSAOVERLAPPED overlapped; + DWORD bytes; + }; + auto* call = new Call{completion, overlapped, bytes}; + const auto run = [](ULONG_PTR p) { + auto* c = reinterpret_cast(p); + c->routine(0, c->bytes, c->overlapped, 0); + delete c; + }; + if (!QueueUserAPC(run, GetCurrentThread(), reinterpret_cast(call))) delete call; + } else if (overlapped->hEvent) { + SetEvent(overlapped->hEvent); + } +} + int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf, DWORD out_len, LPDWORD bytes_returned, LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { @@ -855,14 +900,17 @@ int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWO set_wsa_error(WSAEFAULT); return SOCKET_ERROR; } + // Synchronous, as host_extension asks: an overlapped host call could finish after this frame is gone, + // writing through &real_ext and &returned. The caller's overlapped is completed here instead. LPFN_CONNECTEX real_ext = nullptr; DWORD returned = 0; const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, - overlapped, completion); + nullptr, nullptr); if (rc != 0) return rc; LPFN_CONNECTEX wrapped = &connect_ex_offline; std::memcpy(out_buf, &wrapped, sizeof(wrapped)); *bytes_returned = sizeof(wrapped); + complete_now(overlapped, completion, sizeof(wrapped)); return 0; } if (std::memcmp(&requested, &kSendMsgGuid, sizeof(GUID)) == 0) { @@ -873,11 +921,12 @@ int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWO LPFN_WSASENDMSG real_ext = nullptr; DWORD returned = 0; const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, - overlapped, completion); + nullptr, nullptr); // synchronous: see ConnectEx above if (rc != 0) return rc; LPFN_WSASENDMSG wrapped = &wsa_send_msg_ext_offline; std::memcpy(out_buf, &wrapped, sizeof(wrapped)); *bytes_returned = sizeof(wrapped); + complete_now(overlapped, completion, sizeof(wrapped)); return 0; } } diff --git a/runtime/test/ws2_offline_test.cpp b/runtime/test/ws2_offline_test.cpp index 32cdda48c2..16a30fc5bb 100644 --- a/runtime/test/ws2_offline_test.cpp +++ b/runtime/test/ws2_offline_test.cpp @@ -541,6 +541,101 @@ int main() { closesocket(receiver); } + // 9. kevincommits' finding (#1608, batch 18, item 3). An empty name, and a null one for gethostbyname, is the + // local computer: the host would answer with its real (LAN) addresses, so it is refused. A null getaddrinfo + // node (a service-only lookup) is still answered. "localhost" is answered with loopback addresses only, as + // the shim hands the host a loopback literal for it. An overlapped extension-pointer lookup is completed + // synchronously: its event is set, its routine runs, and nothing writes into the shim's frame afterwards. + { + using AsyncByNameFn = HANDLE(WSAAPI*)(HWND, u_int, const char*, char*, int); + const auto sh_async_by_name = resolve("WSAAsyncGetHostByName"); + WSASetLastError(0); + check(sh_gethostbyname(nullptr) == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND, + "gethostbyname(NULL) is refused (the local computer's addresses)"); + WSASetLastError(0); + check(sh_gethostbyname("") == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND, + "gethostbyname(\"\") is refused (the local computer's addresses)"); + char async_buf[MAXGETHOSTSTRUCT] = {}; + check(sh_async_by_name && sh_async_by_name(nullptr, 0, nullptr, async_buf, sizeof(async_buf)) == nullptr && + sh_async_by_name(nullptr, 0, "", async_buf, sizeof(async_buf)) == nullptr, + "WSAAsyncGetHostByName refuses a null or empty name"); + ADDRINFOA* res = nullptr; + check(sh_getaddrinfo("", "80", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr, + "getaddrinfo(\"\") is refused (the local computer's addresses)"); + ADDRINFOW* res_w = nullptr; + check(sh_getaddrinfo_w(L"", L"80", nullptr, &res_w) == WSAHOST_NOT_FOUND && res_w == nullptr, + "GetAddrInfoW(L\"\") is refused"); + ADDRINFOA hints{}; + hints.ai_family = AF_INET; + check(sh_getaddrinfo(nullptr, "80", &hints, &res) == 0 && res != nullptr, + "getaddrinfo(NULL, service) is still answered"); + if (res) freeaddrinfo(res); + + // Every answer for localhost is loopback: IPv4 for AF_INET (and gethostbyname), IPv6 for AF_INET6. + const auto all_loopback = [](const ADDRINFOA* list, int family) { + if (!list) return false; + for (const ADDRINFOA* a = list; a; a = a->ai_next) { + if (a->ai_family != family) return false; + if (family == AF_INET && + reinterpret_cast(&reinterpret_cast(a->ai_addr)->sin_addr)[0] != 127) + return false; + if (family == AF_INET6 && !IN6_IS_ADDR_LOOPBACK(&reinterpret_cast(a->ai_addr)->sin6_addr)) + return false; + } + return true; + }; + res = nullptr; + check(sh_getaddrinfo("localhost", "80", &hints, &res) == 0 && all_loopback(res, AF_INET), + "getaddrinfo(localhost, AF_INET) answers 127.0.0.1 only"); + if (res) freeaddrinfo(res); + res = nullptr; + hints.ai_family = AF_INET6; + check(sh_getaddrinfo("localhost.", "80", &hints, &res) == 0 && all_loopback(res, AF_INET6), + "getaddrinfo(localhost., AF_INET6) answers ::1 only"); + if (res) freeaddrinfo(res); + const hostent* host = sh_gethostbyname("LOCALHOST"); + bool host_loopback = host && host->h_addrtype == AF_INET && host->h_addr_list && host->h_addr_list[0]; + for (int i = 0; host_loopback && host->h_addr_list[i]; ++i) + host_loopback = static_cast(host->h_addr_list[i][0]) == 127; + check(host_loopback, "gethostbyname(LOCALHOST) answers loopback only"); + + // An overlapped SIO_GET_EXTENSION_FUNCTION_POINTER: answered at once, reported through the OVERLAPPED. + const SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + GUID connect_ex_guid = WSAID_CONNECTEX; + LPFN_CONNECTEX direct = nullptr, overlapped_ex = nullptr; + DWORD returned = 0; + sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, sizeof(connect_ex_guid), &direct, + sizeof(direct), &returned, nullptr, nullptr); + WSAOVERLAPPED ov{}; + ov.hEvent = WSACreateEvent(); + returned = 0; + const int rc = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, sizeof(connect_ex_guid), + &overlapped_ex, sizeof(overlapped_ex), &returned, &ov, nullptr); + check(rc == 0 && overlapped_ex && overlapped_ex == direct && returned == sizeof(overlapped_ex), + "an overlapped WSAIoctl returns the same wrapped ConnectEx at once"); + check(WaitForSingleObject(ov.hEvent, 0) == WAIT_OBJECT_0 && ov.Internal == 0 && + ov.InternalHigh == sizeof(overlapped_ex), + "an overlapped WSAIoctl sets its event and its OVERLAPPED's status and byte count"); + WSACloseEvent(ov.hEvent); + + static int routine_calls = 0; + static DWORD routine_bytes = 0; + routine_calls = 0; + const LPWSAOVERLAPPED_COMPLETION_ROUTINE routine = [](DWORD error, DWORD bytes, LPWSAOVERLAPPED, DWORD) { + if (!error) ++routine_calls; + routine_bytes = bytes; + }; + WSAOVERLAPPED ov2{}; + GUID send_msg_guid = WSAID_WSASENDMSG; + LPFN_WSASENDMSG send_msg = nullptr; + const int rc2 = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &send_msg_guid, sizeof(send_msg_guid), + &send_msg, sizeof(send_msg), &returned, &ov2, routine); + SleepEx(0, TRUE); // an alertable wait runs the queued routine + check(rc2 == 0 && send_msg && routine_calls == 1 && routine_bytes == sizeof(send_msg), + "an overlapped WSAIoctl with a completion routine runs it once at the next alertable wait"); + closesocket(tcp); + } + WSACleanup(); std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); return g_failures ? 1 : 0; From f589998bf73cab6d0cf2f7fca6c62c6c39e0bd38 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:10:25 -0600 Subject: [PATCH 2/3] docs: ws2_offline's empty names, localhost literals and synchronous WSAIoctl lookup Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index b7c4e37b3d..c6abfb18b2 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -840,6 +840,12 @@ works for loopback traffic: `MCAST_JOIN_GROUP`, `MCAST_JOIN_SOURCE_GROUP`, and `wsock32.dll`'s Winsock 1.1 `IP_ADD_MEMBERSHIP` = 5) fail with `WSAEADDRNOTAVAIL`; other options pass through. `WSAJoinLeaf` gets the same loopback check as `connect`, so a group address is refused with `WSAENETUNREACH`. +- An empty name (`""`), and a null one for `gethostbyname` and `WSAAsyncGetHostByName`, names the local computer, + whose answer is every address it has (its LAN and external adapters): it is refused with `WSAHOST_NOT_FOUND`. A + null `getaddrinfo` node (a service-only lookup) is still answered. Forward lookups of `localhost` hand the host a + loopback literal (`::1` for an `AF_INET6` lookup, else `127.0.0.1`), so its hosts file cannot map the name off + loopback. `WSAIoctl`'s extension-pointer lookup is synchronous; an overlapped request is reported as completed at + once (its event set, or its completion routine queued). - Forward lookups refuse external names with `WSAHOST_NOT_FOUND` without sending DNS traffic. A dotted octet with a leading zero (`0127.0.0.1`) is refused too: Windows reads it as octal, so it is not the loopback address it looks like. `getnameinfo` / `GetNameInfoW` force `NI_NUMERICHOST` (or return `WSAHOST_NOT_FOUND` under `NI_NAMEREQD`) for From 37163d100f429ba5467f104142268b575c8d49a1 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:07:18 -0600 Subject: [PATCH 3/3] ws2_offline: the host reports an extension lookup's completion; AI_NUMERICHOST keeps localhost a name From timbot103's review of #2533. - The ConnectEx and WSASendMsg lookups no longer complete the caller's overlapped themselves (complete_now). That posted no packet for a socket on an I/O completion port, so a caller waiting in GetQueuedCompletionStatus hung, and it signalled an overlapped a socket without WSA_FLAG_OVERLAPPED must ignore; its APC record also leaked if the thread never waited alertably. The host's WSAIoctl now gets the caller's overlapped and completion routine again, so the completion is reported as Winsock reports it, but writes its own pointer and byte count into storage of the shim's (wrap_extension_lookup): freed when the call completed, kept if the host reports it pending. The caller's buffer holds the wrapper before the host is called, so a packet another thread dequeues already finds it, and gets its old contents back on failure. - With AI_NUMERICHOST, "localhost" is passed on as the name, so the host refuses it with EAI_NONAME instead of the shim answering with a literal. ws2_offline_test: a completion-port socket gets its packet with the wrapped pointer; on a socket without WSA_FLAG_OVERLAPPED the overlapped ends as the host's own WSAIoctl leaves it; getaddrinfo(localhost, AI_NUMERICHOST) is EAI_NONAME. The event and routine cases follow what Windows 11 does for this lookup (measured: event set, routine run once, packet posted, 0 bytes in the OVERLAPPED). The previous commit fails these 3 checks; 87/87 pass. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 8 ++- runtime/shims/ws2_offline.cpp | 109 +++++++++++++++--------------- runtime/test/ws2_offline_test.cpp | 65 ++++++++++++++++-- 3 files changed, 119 insertions(+), 63 deletions(-) diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index c6abfb18b2..5b8e0df032 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -843,9 +843,11 @@ works for loopback traffic: - An empty name (`""`), and a null one for `gethostbyname` and `WSAAsyncGetHostByName`, names the local computer, whose answer is every address it has (its LAN and external adapters): it is refused with `WSAHOST_NOT_FOUND`. A null `getaddrinfo` node (a service-only lookup) is still answered. Forward lookups of `localhost` hand the host a - loopback literal (`::1` for an `AF_INET6` lookup, else `127.0.0.1`), so its hosts file cannot map the name off - loopback. `WSAIoctl`'s extension-pointer lookup is synchronous; an overlapped request is reported as completed at - once (its event set, or its completion routine queued). + loopback literal (`::1` for an `AF_INET6` lookup, else `127.0.0.1`; not under `AI_NUMERICHOST`, which refuses the + name), so its hosts file cannot map the name off loopback. `WSAIoctl`'s extension-pointer lookup for `ConnectEx` and + `WSASendMsg` is answered by the host with the caller's overlapped and completion routine (so a completion port, + event or routine is told as Winsock tells it, and a socket without `WSA_FLAG_OVERLAPPED` ignores them), but the host + writes its own pointer into the shim's storage; the caller's buffer holds the wrapper before the call. - Forward lookups refuse external names with `WSAHOST_NOT_FOUND` without sending DNS traffic. A dotted octet with a leading zero (`0127.0.0.1`) is refused too: Windows reads it as octal, so it is not the loopback address it looks like. `getnameinfo` / `GetNameInfoW` force `NI_NUMERICHOST` (or return `WSAHOST_NOT_FOUND` under `NI_NAMEREQD`) for diff --git a/runtime/shims/ws2_offline.cpp b/runtime/shims/ws2_offline.cpp index 8fbdbd27f1..fc124af135 100644 --- a/runtime/shims/ws2_offline.cpp +++ b/runtime/shims/ws2_offline.cpp @@ -29,8 +29,9 @@ // NI_NAMEREQD is set), avoiding reverse DNS lookups. // - WSAIoctl wraps WSAID_CONNECTEX and WSAID_WSASENDMSG and refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER // with WSAEINVAL so extension functions cannot bypass the checks. The wrappers ask the host for the native -// pointer of the socket they are called on, since each Winsock provider has its own. The lookup itself is -// synchronous; an overlapped request is reported as completed at once (its event set, its routine queued). +// pointer of the socket they are called on, since each Winsock provider has its own. The host answers the +// lookup with the caller's overlapped and completion routine (so a completion port, event or routine is told as +// Winsock tells it), but writes its own pointer into storage of the shim's, never into the caller's buffer. // // Every host ws2_32.dll call is resolved dynamically from System32 so gta6rt needs no static ws2_32.lib link // dependency. Each refused destination is logged once ("[rt] ws2: offline, refused ") with no payload. @@ -262,13 +263,14 @@ bool is_localhost_name_a(const char* node) { } // What a lookup hands the host for `node`: "localhost" becomes a loopback literal, so the host's hosts file is never -// read for it (it could map the name off loopback); IPv6 for an AF_INET6 lookup, else IPv4. Any other node as is. -const char* lookup_node_a(const char* node, int family) { - if (!node || !is_localhost_name_a(node)) return node; +// read for it (it could map the name off loopback); IPv6 for an AF_INET6 lookup, else IPv4. Any other node as is, and +// "localhost" too under AI_NUMERICHOST, where the host refuses it (EAI_NONAME) without a lookup, as it should. +const char* lookup_node_a(const char* node, int family, int flags = 0) { + if (!node || (flags & AI_NUMERICHOST) || !is_localhost_name_a(node)) return node; return family == AF_INET6 ? "::1" : "127.0.0.1"; } -const wchar_t* lookup_node_w(const wchar_t* node, int family) { - if (!node || !is_localhost_name_a(narrow_ascii(node).c_str())) return node; +const wchar_t* lookup_node_w(const wchar_t* node, int family, int flags = 0) { + if (!node || (flags & AI_NUMERICHOST) || !is_localhost_name_a(narrow_ascii(node).c_str())) return node; return family == AF_INET6 ? L"::1" : L"127.0.0.1"; } @@ -609,7 +611,7 @@ INT WSAAPI getaddrinfo_offline(PCSTR node, PCSTR service, const ADDRINFOA* hints set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(lookup_node_a(node, hints ? hints->ai_family : AF_UNSPEC), service, hints, result); + return real_fn(lookup_node_a(node, hints ? hints->ai_family : AF_UNSPEC, hints ? hints->ai_flags : 0), service, hints, result); } INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) { @@ -625,7 +627,7 @@ INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(lookup_node_w(node, hints ? hints->ai_family : AF_UNSPEC), service, hints, result); + return real_fn(lookup_node_w(node, hints ? hints->ai_family : AF_UNSPEC, hints ? hints->ai_flags : 0), service, hints, result); } INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXA* hints, @@ -645,7 +647,7 @@ INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUI set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(lookup_node_a(name, hints ? hints->ai_family : AF_UNSPEC), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); + return real_fn(lookup_node_a(name, hints ? hints->ai_family : AF_UNSPEC, hints ? hints->ai_flags : 0), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); } INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXW* hints, @@ -665,7 +667,7 @@ INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPG set_wsa_error(WSAHOST_NOT_FOUND); return WSAHOST_NOT_FOUND; } - return real_fn(const_cast(lookup_node_w(name, hints ? hints->ai_family : AF_UNSPEC)), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); + return real_fn(const_cast(lookup_node_w(name, hints ? hints->ai_family : AF_UNSPEC, hints ? hints->ai_flags : 0)), service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); } hostent* WSAAPI gethostbyname_offline(const char* name) { @@ -848,29 +850,43 @@ int PASCAL wsa_send_msg_ext_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD return real_fn(s, msg, flags, bytes_sent, overlapped, completion); } -// An overlapped extension-pointer lookup that the shim answered synchronously: report it the way Winsock reports an -// overlapped call that completed at once (status and byte count in the OVERLAPPED, its event set, its completion -// routine queued to this thread for its next alertable wait). -void complete_now(LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion, DWORD bytes) { - if (!overlapped) return; - overlapped->Internal = 0; - overlapped->InternalHigh = bytes; - if (completion) { - struct Call { - LPWSAOVERLAPPED_COMPLETION_ROUTINE routine; - LPWSAOVERLAPPED overlapped; - DWORD bytes; - }; - auto* call = new Call{completion, overlapped, bytes}; - const auto run = [](ULONG_PTR p) { - auto* c = reinterpret_cast(p); - c->routine(0, c->bytes, c->overlapped, 0); - delete c; - }; - if (!QueueUserAPC(run, GetCurrentThread(), reinterpret_cast(call))) delete call; - } else if (overlapped->hEvent) { - SetEvent(overlapped->hEvent); +// SIO_GET_EXTENSION_FUNCTION_POINTER for an extension the shim wraps: the caller gets `wrapped`, never the host's +// pointer. The host still answers the call itself, with the caller's overlapped and completion routine, so the +// completion is reported the way Winsock reports it for this socket: an I/O completion port packet, the event, the +// routine, or nothing for a socket without WSA_FLAG_OVERLAPPED. What the host writes (its own pointer and byte +// count) goes to storage of the shim's own, never to the caller's buffer or to this frame: it is freed when the call +// completed here, and kept when the host reports the call pending, since the host may write it later (a few bytes; +// this lookup completes at once in practice). `wrapped` is in the caller's buffer before the host is called, so a +// completion another thread dequeues already finds it there; on failure the buffer gets its old contents back. +template +int wrap_extension_lookup(Fn real_fn, SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf, + LPDWORD bytes_returned, LPWSAOVERLAPPED overlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE completion, Wrapped wrapped) { + struct HostAnswer { + Wrapped pointer = nullptr; + DWORD returned = 0; + }; + auto* answer = new (std::nothrow) HostAnswer; + if (!answer) { + set_wsa_error(WSA_NOT_ENOUGH_MEMORY); + return SOCKET_ERROR; + } + Wrapped previous = nullptr; + std::memcpy(&previous, out_buf, sizeof(previous)); + std::memcpy(out_buf, &wrapped, sizeof(wrapped)); + const int rc = real_fn(s, io_control_code, in_buf, in_len, &answer->pointer, sizeof(answer->pointer), + &answer->returned, overlapped, completion); + const int error = rc == 0 ? 0 : WSAGetLastError(); + if (rc == 0) { + *bytes_returned = sizeof(wrapped); + delete answer; + return 0; } + if (error == WSA_IO_PENDING) return rc; // the host still owns `answer`; `wrapped` stays in the caller's buffer + std::memcpy(out_buf, &previous, sizeof(previous)); + delete answer; + set_wsa_error(error); + return rc; } int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf, @@ -900,34 +916,17 @@ int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWO set_wsa_error(WSAEFAULT); return SOCKET_ERROR; } - // Synchronous, as host_extension asks: an overlapped host call could finish after this frame is gone, - // writing through &real_ext and &returned. The caller's overlapped is completed here instead. - LPFN_CONNECTEX real_ext = nullptr; - DWORD returned = 0; - const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, - nullptr, nullptr); - if (rc != 0) return rc; - LPFN_CONNECTEX wrapped = &connect_ex_offline; - std::memcpy(out_buf, &wrapped, sizeof(wrapped)); - *bytes_returned = sizeof(wrapped); - complete_now(overlapped, completion, sizeof(wrapped)); - return 0; + return wrap_extension_lookup(real_fn, s, io_control_code, in_buf, in_len, out_buf, + bytes_returned, overlapped, completion, &connect_ex_offline); } if (std::memcmp(&requested, &kSendMsgGuid, sizeof(GUID)) == 0) { if (!out_buf || out_len < sizeof(void*) || !bytes_returned) { set_wsa_error(WSAEFAULT); return SOCKET_ERROR; } - LPFN_WSASENDMSG real_ext = nullptr; - DWORD returned = 0; - const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, - nullptr, nullptr); // synchronous: see ConnectEx above - if (rc != 0) return rc; - LPFN_WSASENDMSG wrapped = &wsa_send_msg_ext_offline; - std::memcpy(out_buf, &wrapped, sizeof(wrapped)); - *bytes_returned = sizeof(wrapped); - complete_now(overlapped, completion, sizeof(wrapped)); - return 0; + return wrap_extension_lookup(real_fn, s, io_control_code, in_buf, in_len, out_buf, + bytes_returned, overlapped, completion, + &wsa_send_msg_ext_offline); } } diff --git a/runtime/test/ws2_offline_test.cpp b/runtime/test/ws2_offline_test.cpp index 16a30fc5bb..a35d19d9cb 100644 --- a/runtime/test/ws2_offline_test.cpp +++ b/runtime/test/ws2_offline_test.cpp @@ -598,8 +598,19 @@ int main() { for (int i = 0; host_loopback && host->h_addr_list[i]; ++i) host_loopback = static_cast(host->h_addr_list[i][0]) == 127; check(host_loopback, "gethostbyname(LOCALHOST) answers loopback only"); + // Under AI_NUMERICHOST "localhost" is not a numeric host: refused as the host refuses it, not rewritten. + ADDRINFOA numeric{}; + numeric.ai_flags = AI_NUMERICHOST; + res = nullptr; + check(sh_getaddrinfo("localhost", "80", &numeric, &res) == EAI_NONAME && res == nullptr, + "getaddrinfo(localhost, AI_NUMERICHOST) is EAI_NONAME, as on the host"); + check(sh_getaddrinfo("127.0.0.1", "80", &numeric, &res) == 0 && res != nullptr, + "getaddrinfo(127.0.0.1, AI_NUMERICHOST) is answered"); + if (res) freeaddrinfo(res); - // An overlapped SIO_GET_EXTENSION_FUNCTION_POINTER: answered at once, reported through the OVERLAPPED. + // An overlapped SIO_GET_EXTENSION_FUNCTION_POINTER: answered at once, and its completion reported as the host + // reports it. Windows 11 (measured): the event set, the routine run once, a port packet posted, with 0 bytes + // in the OVERLAPPED and the completion (lpcbBytesReturned is 8). const SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); GUID connect_ex_guid = WSAID_CONNECTEX; LPFN_CONNECTEX direct = nullptr, overlapped_ex = nullptr; @@ -613,9 +624,8 @@ int main() { &overlapped_ex, sizeof(overlapped_ex), &returned, &ov, nullptr); check(rc == 0 && overlapped_ex && overlapped_ex == direct && returned == sizeof(overlapped_ex), "an overlapped WSAIoctl returns the same wrapped ConnectEx at once"); - check(WaitForSingleObject(ov.hEvent, 0) == WAIT_OBJECT_0 && ov.Internal == 0 && - ov.InternalHigh == sizeof(overlapped_ex), - "an overlapped WSAIoctl sets its event and its OVERLAPPED's status and byte count"); + check(WaitForSingleObject(ov.hEvent, 0) == WAIT_OBJECT_0 && ov.Internal == 0, + "an overlapped WSAIoctl sets its event and a success status"); WSACloseEvent(ov.hEvent); static int routine_calls = 0; @@ -631,9 +641,54 @@ int main() { const int rc2 = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &send_msg_guid, sizeof(send_msg_guid), &send_msg, sizeof(send_msg), &returned, &ov2, routine); SleepEx(0, TRUE); // an alertable wait runs the queued routine - check(rc2 == 0 && send_msg && routine_calls == 1 && routine_bytes == sizeof(send_msg), + check(rc2 == 0 && send_msg && routine_calls == 1, "an overlapped WSAIoctl with a completion routine runs it once at the next alertable wait"); closesocket(tcp); + + // A socket on an I/O completion port, an OVERLAPPED with no event and no routine: the completion is a port + // packet, and the caller's buffer already holds the wrapper when it is dequeued (timbot103's review). + const SOCKET on_port = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); + const HANDLE port = CreateIoCompletionPort(reinterpret_cast(on_port), nullptr, 0x5a, 0); + WSAOVERLAPPED ov3{}; + LPFN_CONNECTEX port_ex = nullptr; + returned = 0; + const int rc3 = sh_wsa_ioctl(on_port, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, + sizeof(connect_ex_guid), &port_ex, sizeof(port_ex), &returned, &ov3, nullptr); + const bool pending3 = rc3 == SOCKET_ERROR && WSAGetLastError() == WSA_IO_PENDING; + DWORD port_bytes = 0; + ULONG_PTR key = 0; + LPOVERLAPPED dequeued = nullptr; + const BOOL got = port ? GetQueuedCompletionStatus(port, &port_bytes, &key, &dequeued, 2000) : FALSE; + check(port && (rc3 == 0 || pending3) && got && key == 0x5a && dequeued == &ov3 && port_ex == direct, + "an overlapped WSAIoctl on a completion-port socket posts its packet, with the wrapped ConnectEx"); + if (port) CloseHandle(port); + closesocket(on_port); + + // A socket without WSA_FLAG_OVERLAPPED ignores the overlapped and the routine: the shim's answer leaves them + // as the host's own WSAIoctl does on the same socket. + const SOCKET blocking = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, 0); + using HostIoctl = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, + LPWSAOVERLAPPED_COMPLETION_ROUTINE); + const auto host_ioctl = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"ws2_32.dll"), "WSAIoctl")); + WSAOVERLAPPED ov_shim{}, ov_host{}; + ov_shim.hEvent = WSACreateEvent(); + ov_host.hEvent = WSACreateEvent(); + LPFN_CONNECTEX blocking_ex = nullptr, host_ex = nullptr; + DWORD host_returned = 0; + const int rc_shim = sh_wsa_ioctl(blocking, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, + sizeof(connect_ex_guid), &blocking_ex, sizeof(blocking_ex), &returned, + &ov_shim, nullptr); + const int rc_host = host_ioctl(blocking, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, + sizeof(connect_ex_guid), &host_ex, sizeof(host_ex), &host_returned, &ov_host, + nullptr); + const bool shim_set = WaitForSingleObject(ov_shim.hEvent, 0) == WAIT_OBJECT_0; + const bool host_set = WaitForSingleObject(ov_host.hEvent, 0) == WAIT_OBJECT_0; + check(rc_shim == 0 && rc_host == 0 && blocking_ex == direct && host_ex != direct && shim_set == host_set && + ov_shim.Internal == ov_host.Internal && ov_shim.InternalHigh == ov_host.InternalHigh, + "on a socket without WSA_FLAG_OVERLAPPED the overlapped is left as the host leaves it"); + WSACloseEvent(ov_shim.hEvent); + WSACloseEvent(ov_host.hEvent); + closesocket(blocking); } WSACleanup();