diff --git a/Misc/NEWS.d/next/Windows/2025-05-20-12-35-33.gh-issue-118234.HjbkIh.rst b/Misc/NEWS.d/next/Windows/2025-05-20-12-35-33.gh-issue-118234.HjbkIh.rst new file mode 100644 index 00000000000000..a1b1ef84db8d93 --- /dev/null +++ b/Misc/NEWS.d/next/Windows/2025-05-20-12-35-33.gh-issue-118234.HjbkIh.rst @@ -0,0 +1,2 @@ +Avoid socket failure with missing SYSTEMROOT env var on Windows. Patch by +John Keith Hohm. diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c index 92c9aa8b510dca..c4877dd790aa72 100644 --- a/Modules/socketmodule.c +++ b/Modules/socketmodule.c @@ -403,6 +403,21 @@ remove_unusable_flags(PyObject *m) return 0; } +/* issue #118234, avoid WinError 10106 with empty environment */ +static void ensure_system_root() { + LPCWSTR name = L"SystemRoot"; + DWORD size = GetEnvironmentVariableW(name, NULL, 0); + if (size) { + return; + } + wchar_t root[4096]; + UINT len = GetWindowsDirectoryW(root, 4096); + if (len == 0 || len >= 4096) { + return; + } + SetEnvironmentVariableW(name, root); +} + #endif #include @@ -5618,6 +5633,10 @@ sock_initobj_impl(PySocketSockObject *self, int family, int type, int proto, SOCKET_T fd = INVALID_SOCKET; socket_state *state = find_module_state_by_def(Py_TYPE(self)); +#ifdef MS_WINDOWS + ensure_system_root(); +#endif + #ifndef MS_WINDOWS #ifdef SOCK_CLOEXEC int *atomic_flag_works = &sock_cloexec_works;