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 <vtjnash@gmail.com>
This commit is contained in:
Eagle Liang 2021-05-13 23:42:55 +08:00 committed by GitHub
parent 9864053c9c
commit 95f88f47f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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;
}