From 95f88f47f28b4686a6959377c8d2c31daa40bd64 Mon Sep 17 00:00:00 2001 From: Eagle Liang Date: Thu, 13 May 2021 23:42:55 +0800 Subject: [PATCH] win: fix string encoding issue of uv_os_gethostname Windows API gethostname(buffer, size) return unicode string in char array. It will cause garbled code if the host name contains non ascii characters without cast into multi byte char. This change keep the same encoding with the implementation on Unix/macOS platform, which is utf-8. Requires Windows 8 / Server 2012. Fixes: https://github.com/libuv/libuv/issues/3148 PR-URL: https://github.com/libuv/libuv/pull/3149 Reviewed-By: Jameson Nash --- src/win/util.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/win/util.c b/src/win/util.c index aad8f1a1..88602c7e 100644 --- a/src/win/util.c +++ b/src/win/util.c @@ -1664,26 +1664,33 @@ int uv_os_unsetenv(const char* name) { int uv_os_gethostname(char* buffer, size_t* size) { - char buf[UV_MAXHOSTNAMESIZE]; + WCHAR buf[UV_MAXHOSTNAMESIZE]; size_t len; + char* utf8_str; + int convert_result; if (buffer == NULL || size == NULL || *size == 0) return UV_EINVAL; uv__once_init(); /* Initialize winsock */ - if (gethostname(buf, sizeof(buf)) != 0) + if (GetHostNameW(buf, UV_MAXHOSTNAMESIZE) != 0) return uv_translate_sys_error(WSAGetLastError()); - buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */ - len = strlen(buf); + convert_result = uv__convert_utf16_to_utf8(buf, -1, &utf8_str); + if (convert_result != 0) + return convert_result; + + len = strlen(utf8_str); if (len >= *size) { *size = len + 1; + uv__free(utf8_str); return UV_ENOBUFS; } - memcpy(buffer, buf, len + 1); + memcpy(buffer, utf8_str, len + 1); + uv__free(utf8_str); *size = len; return 0; }