Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.11] gh-94821: Fix autobind of empty unix domain address (GH-94826) #94873

Merged
merged 1 commit into from
Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -5480,6 +5480,20 @@ def testBytearrayName(self):
s.bind(bytearray(b"\x00python\x00test\x00"))
self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")

def testAutobind(self):
# Check that binding to an empty string binds to an available address
# in the abstract namespace as specified in unix(7) "Autobind feature".
abstract_address = b"^\0[0-9a-f]{5}"
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
s1.bind("")
self.assertRegex(s1.getsockname(), abstract_address)
# Each socket is bound to a different abstract address.
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
s2.bind("")
self.assertRegex(s2.getsockname(), abstract_address)
self.assertNotEqual(s1.getsockname(), s2.getsockname())


@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
class TestUnixDomain(unittest.TestCase):

Expand Down Expand Up @@ -5549,6 +5563,11 @@ def testUnencodableAddr(self):
self.addCleanup(os_helper.unlink, path)
self.assertEqual(self.sock.getsockname(), path)

@unittest.skipIf(sys.platform == 'linux', 'Linux specific test')
def testEmptyAddress(self):
# Test that binding empty address fails.
self.assertRaises(OSError, self.sock.bind, "")


class BufferIOTest(SocketConnectedTest):
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix binding of unix socket to empty address on Linux to use an available
address from the abstract namespace, instead of "\0".
6 changes: 4 additions & 2 deletions Modules/socketmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1692,8 +1692,10 @@ getsockaddrarg(PySocketSockObject *s, PyObject *args,

struct sockaddr_un* addr = &addrbuf->un;
#ifdef __linux__
if (path.len > 0 && *(const char *)path.buf == 0) {
/* Linux abstract namespace extension */
if (path.len == 0 || *(const char *)path.buf == 0) {
/* Linux abstract namespace extension:
- Empty address auto-binding to an abstract address
- Address that starts with null byte */
if ((size_t)path.len > sizeof addr->sun_path) {
PyErr_SetString(PyExc_OSError,
"AF_UNIX path too long");
Expand Down