[glib] g_get_host_name: ensure hostname has UTF8 encoding on Windows



commit d011223085063ff23589fb92c7e68bcfb50fdd02
Author: Tom Schoonjans <Tom Schoonjans diamond ac uk>
Date:   Wed Nov 1 09:52:29 2017 +0000

    g_get_host_name: ensure hostname has UTF8 encoding on Windows
    
    Ensures that the hostname returned by g_get_host_name is always UTF8 encoded.
    Previously, on Windows, the returned string would be encoded in the
    current codepage, if it contained non-ASCII characters.
    
    The unit test for g_get_host_name was updated with a check to ensure
    that the hostname is indeed at UTF-8 string.
    
    https://bugzilla.gnome.org/show_bug.cgi?id=789755

 glib/gutils.c      |   19 ++++++++++++++-----
 glib/tests/utils.c |    1 +
 2 files changed, 15 insertions(+), 5 deletions(-)
---
diff --git a/glib/gutils.c b/glib/gutils.c
index 60370d5..e84d8ac 100644
--- a/glib/gutils.c
+++ b/glib/gutils.c
@@ -970,6 +970,8 @@ g_get_tmp_dir (void)
  * name can be determined, a default fixed string "localhost" is
  * returned.
  *
+ * The encoding of the returned string is UTF-8.
+ *
  * Returns: the host name of the machine.
  *
  * Since: 2.8
@@ -982,16 +984,23 @@ g_get_host_name (void)
   if (g_once_init_enter (&hostname))
     {
       gboolean failed;
-      gchar tmp[100];
+      gchar *utmp;
 
 #ifndef G_OS_WIN32
-      failed = (gethostname (tmp, sizeof (tmp)) == -1);
+      gchar *tmp = g_malloc (sizeof (gchar) * 100);
+      failed = (gethostname (tmp, sizeof (gchar) * 100) == -1);
+      utmp = tmp;
 #else
-      DWORD size = sizeof (tmp);
-      failed = (!GetComputerName (tmp, &size));
+      wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
+      DWORD size = sizeof (tmp) / sizeof (tmp[0]);
+      failed = (!GetComputerNameW (tmp, &size));
+      if (!failed)
+        utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
+      if (utmp == NULL)
+        failed = TRUE;
 #endif
 
-      g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
+      g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
     }
 
   return hostname;
diff --git a/glib/tests/utils.c b/glib/tests/utils.c
index 65ca806..c7a1f6e 100644
--- a/glib/tests/utils.c
+++ b/glib/tests/utils.c
@@ -391,6 +391,7 @@ test_hostname (void)
   name = g_get_host_name ();
 
   g_assert (name != NULL);
+  g_assert_true (g_utf8_validate (name, -1, NULL));
 }
 
 #ifdef G_OS_UNIX


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]