From 5ee2925459372a8af805e952f433acd75e426325 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C5=82=20G=C3=B3rny?= <mgorny@gentoo.org>
Date: Sun, 4 Oct 2020 15:46:23 +0200
Subject: [PATCH] Fix sethostname() failure when passed bytes

My implementation of sethostname() was broken and failed when passed
bytes on Python 3. Update the implementation to match CPython -- that
is, use bytes if provided, or fsencode() when str is provided.

--HG--
branch : py3.6
---
 pypy/module/_socket/interp_func.py        |  8 +++++++-
 pypy/module/_socket/test/test_sock_app.py | 12 ++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/pypy/module/_socket/interp_func.py b/pypy/module/_socket/interp_func.py
index bdc4f1293f..1727e51d51 100644
--- a/pypy/module/_socket/interp_func.py
+++ b/pypy/module/_socket/interp_func.py
@@ -392,7 +392,13 @@ if hasattr(rsocket, 'sethostname'):
 
         Set the host name.
         """
-        hostname = space.text_w(w_hostname)
+        if space.isinstance_w(w_hostname, space.w_bytes):
+            hostname = space.bytes_w(w_hostname)
+        elif space.isinstance_w(w_hostname, space.w_unicode):
+            hostname = space.fsencode_w(w_hostname)
+        else:
+            raise oefmt(space.w_TypeError,
+                        "sethostname() argument 1 must be str or bytes")
         try:
             res = rsocket.sethostname(hostname)
         except SocketError as e:
diff --git a/pypy/module/_socket/test/test_sock_app.py b/pypy/module/_socket/test/test_sock_app.py
index fe3efec8e3..355fb8a2a9 100644
--- a/pypy/module/_socket/test/test_sock_app.py
+++ b/pypy/module/_socket/test/test_sock_app.py
@@ -210,6 +210,18 @@ def test_getaddrinfo(space, w_socket):
     assert space.unwrap(w_l) == True
 
 
+def test_sethostname(space, w_socket):
+    space.raises_w(space.w_OSError, space.appexec,
+                   [w_socket],
+                   "(_socket): _socket.sethostname(_socket.gethostname())")
+
+
+def test_sethostname_bytes(space, w_socket):
+    space.raises_w(space.w_OSError, space.appexec,
+                   [w_socket],
+                   "(_socket): _socket.sethostname(_socket.gethostname().encode())")
+
+
 def test_unknown_addr_as_object(space, ):
     from pypy.module._socket.interp_socket import addr_as_object
     c_addr = lltype.malloc(rsocket._c.sockaddr, flavor='raw', track_allocation=False)
-- 
GitLab

