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