From 2a49a5971baded00322f33235368a29ab0499c76 Mon Sep 17 00:00:00 2001 From: eagleliang Date: Fri, 16 Apr 2021 17:11:09 +0800 Subject: [PATCH] win: fix encoding issue of uv_os_gethostname() Windows API gethostname(buffer, size) return unicode string in char array. It will cause grabled 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" Fix issue #3148 --- src/win/util.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/win/util.c b/src/win/util.c index aad8f1a1..5bf6d722 100644 --- a/src/win/util.c +++ b/src/win/util.c @@ -1676,14 +1676,27 @@ int uv_os_gethostname(char* buffer, size_t* size) { return uv_translate_sys_error(WSAGetLastError()); buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */ - len = strlen(buf); + int utf16StrBufSize = MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0); + WCHAR* utf16Str = uv__malloc(sizeof(WCHAR) * utf16StrBufSize); + MultiByteToWideChar(CP_ACP, 0, buf, -1, utf16Str, utf16StrBufSize); + char* utf8Str = uv__malloc(sizeof(char) * UV_MAXHOSTNAMESIZE); + int res = uv__convert_utf16_to_utf8(utf16Str, utf16StrBufSize, &utf8Str); + uv__free(utf16Str); + if (res != 0) { + uv__free(utf8Str); + return res; + } + + len = strlen(utf8Str); if (len >= *size) { *size = len + 1; + uv__free(utf8Str); return UV_ENOBUFS; } - memcpy(buffer, buf, len + 1); + memcpy(buffer, utf8Str, len + 1); + uv__free(utf8Str); *size = len; return 0; }