diff --git a/Lib/ssl.py b/Lib/ssl.py index 0ebef58d69c..3ee3d6ac0b2 100644 --- a/Lib/ssl.py +++ b/Lib/ssl.py @@ -320,7 +320,9 @@ class SSLSocket(socket): from the socket module.""" self._makefile_refs += 1 - return _fileobject(self, mode, bufsize) + # close=True so as to decrement the reference count when done with + # the file-like object. + return _fileobject(self, mode, bufsize, close=True) diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py index ef82ed3e924..c1de0c1efb1 100644 --- a/Lib/test/test_ssl.py +++ b/Lib/test/test_ssl.py @@ -9,7 +9,9 @@ import select import errno import subprocess import time +import gc import os +import errno import pprint import urllib, urlparse import shutil @@ -123,6 +125,26 @@ class BasicTests(unittest.TestCase): del ss self.assertEqual(wr(), None) + def test_makefile_close(self): + # Issue #5238: creating a file-like object with makefile() shouldn't + # leak the underlying file descriptor. + ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) + fd = ss.fileno() + f = ss.makefile() + f.close() + # The fd is still open + os.read(fd, 0) + # Closing the SSL socket should close the fd too + ss.close() + gc.collect() + try: + os.read(fd, 0) + except OSError, e: + self.assertEqual(e.errno, errno.EBADF) + else: + self.fail("OSError wasn't raised") + + class NetworkedTests(unittest.TestCase): def testConnect(self): diff --git a/Misc/NEWS b/Misc/NEWS index 291109688f8..0d07c73f226 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -33,6 +33,9 @@ Core and Builtins Library ------- +- Issue #5238: Calling makefile() on an SSL object would prevent the + underlying socket from being closed until all objects get truely destroyed. + - Issue #7943: Fix circular reference created when instantiating an SSL socket. Initial patch by Péter Szabó.