121925
From e41ee7cf3347ced6e689c198dbf3c5900009d70f Mon Sep 17 00:00:00 2001
121925
From: usa <usa@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>
121925
Date: Thu, 25 Feb 2016 10:58:02 +0000
121925
Subject: [PATCH] merge revision(s) 53677: [Backport #11877]
121925
121925
        * ext/socket/socket.c (sock_gethostname): support unlimited size
121925
          hostname.
121925
121925
121925
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_2_1@53936 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
121925
---
121925
 ChangeLog           |  5 +++++
121925
 ext/socket/socket.c | 26 ++++++++++++++++++++------
121925
 version.h           |  2 +-
121925
 3 files changed, 26 insertions(+), 7 deletions(-)
121925
121925
diff --git a/ChangeLog b/ChangeLog
121925
index f407b73..2216dd4 100644
121925
--- a/ChangeLog
121925
+++ b/ChangeLog
121925
@@ -1,3 +1,8 @@
121925
+Thu Feb 25 19:49:31 2016  Nobuyoshi Nakada  <nobu@ruby-lang.org>
121925
+
121925
+	* ext/socket/socket.c (sock_gethostname): support unlimited size
121925
+	  hostname.
121925
+
121925
 Sat Feb 13 17:11:58 2016  Fabian Wiesel  <fabian.wiesel@sap.com>
121925
121925
 	* lib/uri/generic.rb (find_proxy): exclude white-spaces and allow
121925
diff --git a/ext/socket/socket.c b/ext/socket/socket.c
121925
index 0592432..13006ab 100644
121925
--- a/ext/socket/socket.c
121925
+++ b/ext/socket/socket.c
121925
@@ -898,14 +898,28 @@ sock_gethostname(VALUE obj)
121925
 #ifndef HOST_NAME_MAX
121925
 #  define HOST_NAME_MAX 1024
121925
 #endif
121925
-    char buf[HOST_NAME_MAX+1];
121925
+    long len = HOST_NAME_MAX;
121925
+    VALUE name;
121925
 
121925
     rb_secure(3);
121925
-    if (gethostname(buf, (int)sizeof buf - 1) < 0)
121925
-	rb_sys_fail("gethostname");
121925
-
121925
-    buf[sizeof buf - 1] = '\0';
121925
-    return rb_str_new2(buf);
121925
+    name = rb_str_new(0, len);
121925
+    while (gethostname(RSTRING_PTR(name), len) < 0) {
121925
+	int e = errno;
121925
+	switch (e) {
121925
+	  case ENAMETOOLONG:
121925
+#ifdef __linux__
121925
+	  case EINVAL:
121925
+	    /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */
121925
+#endif
121925
+	    break;
121925
+	  default:
121925
+	    rb_syserr_fail(e, "gethostname(3)");
121925
+	}
121925
+	rb_str_modify_expand(name, len);
121925
+	len += len;
121925
+    }
121925
+    rb_str_resize(name, strlen(RSTRING_PTR(name)));
121925
+    return name;
121925
 }
121925
 #else
121925
 #ifdef HAVE_UNAME