Test handling of unterminated AF_UNIX addresses on Linux. diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -1392,6 +1392,53 @@ class TestExceptions(unittest.TestCase): self.assertTrue(issubclass(socket.gaierror, socket.error)) self.assertTrue(issubclass(socket.timeout, socket.error)) +class TestLinuxPathLen(unittest.TestCase): + + # Test AF_UNIX path length limits on Linux. + + UNIX_PATH_MAX = 108 + + def setUp(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.to_unlink = [] + + def tearDown(self): + self.sock.close() + for name in self.to_unlink: + support.unlink(name) + + def pathEncodingArgs(self): + # Return the encoding and error handler used to encode/decode + # pathnames. + encoding = sys.getfilesystemencoding() + if encoding is None: + encoding = sys.getdefaultencoding() + return encoding, "surrogateescape" + + def pathname(self, length): + # Return a bytes pathname of the given length. + path = os.path.abspath(support.TESTFN) + path_bytes = path.encode(*self.pathEncodingArgs()) + return path_bytes + b"a" * (length - len(path_bytes)) + + def testPathTooLong(self): + # Check we can't bind to a path longer than the assumed maximum. + path = self.pathname(self.UNIX_PATH_MAX + 1) + with self.assertRaisesRegexp(socket.error, "AF_UNIX path too long"): + self.sock.bind(path) + self.to_unlink.append(path) + + def testMaxPathLen(self): + # Test binding to a path of the maximum length and reading the + # address back. In this case, sun_path is not null terminated, + # and makesockaddr() used to read past the end of it. + path = self.pathname(self.UNIX_PATH_MAX) + self.sock.bind(path) + self.to_unlink.append(path) + self.assertEqual(self.sock.getsockname(), + path.decode(*self.pathEncodingArgs())) + os.stat(path) + class TestLinuxAbstractNamespace(unittest.TestCase): UNIX_PATH_MAX = 108 @@ -1583,6 +1630,7 @@ def test_main(): tests.append(BasicSocketPairTest) if sys.platform == 'linux2': tests.append(TestLinuxAbstractNamespace) + tests.append(TestLinuxPathLen) if isTipcAvailable(): tests.append(TIPCTest) tests.append(TIPCThreadableTest)