[glib/wip/lantw/enable-ci-on-freebsd-12: 1/2] gutils: Don't limit the length of the host name to 99



commit 1fd2781dcfd320fc5e4aeea39af3afa68df0cf48
Author: Ting-Wei Lan <lantw src gnome org>
Date:   Mon Jun 24 01:47:26 2019 +0800

    gutils: Don't limit the length of the host name to 99
    
    It is unclear that why the size of the buffer was chosen to be 100
    because the commit introduced the code didn't mention the reason.
    POSIX defines _POSIX_HOST_NAME_MAX to be 255 and provides a way to
    determine the suitable value with sysconf, so we should use it instead
    of hard-coding a small value.

 glib/gutils.c | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)
---
diff --git a/glib/gutils.c b/glib/gutils.c
index 87db6a1f3..749badc24 100644
--- a/glib/gutils.c
+++ b/glib/gutils.c
@@ -1003,8 +1003,32 @@ g_get_host_name (void)
       gchar *utmp;
 
 #ifndef G_OS_WIN32
-      gchar *tmp = g_malloc (sizeof (gchar) * 100);
-      failed = (gethostname (tmp, sizeof (gchar) * 100) == -1);
+      glong max;
+      gsize size;
+      const gsize size_large = (gsize) 256 * 256;
+      gchar *tmp;
+
+      max = sysconf (_SC_HOST_NAME_MAX);
+      if (max > 0)
+        size = (gsize) max + 1;
+      else
+#ifdef HOST_NAME_MAX
+        size = HOST_NAME_MAX + 1;
+#else
+        /* _POSIX_HOST_NAME_MAX is defined to be 255, so 'size' is 256 here. */
+        size = _POSIX_HOST_NAME_MAX + 1;
+#endif
+
+      tmp = g_malloc (size);
+      failed = (gethostname (tmp, size) == -1);
+      if (failed && size < size_large)
+        {
+          /* Try again with a larger buffer if 'size' may be too small. */
+          g_free (tmp);
+          tmp = g_malloc (size_large);
+          failed = (gethostname (tmp, size_large) == -1);
+        }
+
       if (failed)
         g_clear_pointer (&tmp, g_free);
       utmp = tmp;


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