[glib/wip/lantw/dont-limit-host-name-to-99-bytes: 3/3] gutils: Don't limit the length of the host name to 99



commit 446ba28d31650067c0094952aa686a0e51daabd5
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 | 33 +++++++++++++++++++++++++++++++--
 1 file changed, 31 insertions(+), 2 deletions(-)
---
diff --git a/glib/gutils.c b/glib/gutils.c
index 87db6a1f3..62a64d912 100644
--- a/glib/gutils.c
+++ b/glib/gutils.c
@@ -1003,8 +1003,37 @@ 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;
+      /* The number 256 * 256 is taken from the value of _POSIX_HOST_NAME_MAX,
+       * which is 255. Since we use _POSIX_HOST_NAME_MAX + 1 (= 256) in the
+       * fallback case, we pick 256 * 256 as the size of the larger buffer here.
+       * It should be large enough. It doesn't looks reasonable to name a host
+       * with a string that is longer than 64 KiB.
+       */
+      const gsize size_large = (gsize) 256 * 256;
+      gchar *tmp;
+
+      max = sysconf (_SC_HOST_NAME_MAX);
+      if (max > 0 && max <= G_MAXSIZE - 1)
+        size = (gsize) max + 1;
+      else
+#ifdef HOST_NAME_MAX
+        size = HOST_NAME_MAX + 1;
+#else
+        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]