Issue #20331: Fixed possible FD leaks in various modules:

http.server, imghdr, mailcap, mimetypes, xml.etree.
This commit is contained in:
Serhiy Storchaka 2014-01-25 19:43:56 +02:00
commit c0b0bb6e01
5 changed files with 34 additions and 30 deletions

View File

@ -678,7 +678,9 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
"""Serve a GET request."""
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
def do_HEAD(self):
@ -720,6 +722,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
except OSError:
self.send_error(404, "File not found")
return None
try:
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
@ -727,6 +730,9 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
return f
except:
f.close()
raise
def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).

View File

@ -7,6 +7,8 @@ __all__ = ["what"]
#-------------------------#
def what(file, h=None):
f = None
try:
if h is None:
if isinstance(file, str):
f = open(file, 'rb')
@ -15,10 +17,6 @@ def what(file, h=None):
location = file.tell()
h = file.read(32)
file.seek(location)
f = None
else:
f = None
try:
for tf in tests:
res = tf(h, f)
if res:

View File

@ -22,8 +22,8 @@ def getcaps():
fp = open(mailcap, 'r')
except OSError:
continue
with fp:
morecaps = readmailcapfile(fp)
fp.close()
for key, value in morecaps.items():
if not key in caps:
caps[key] = value

View File

@ -363,6 +363,7 @@ def read_mime_types(file):
f = open(file)
except OSError:
return None
with f:
db = MimeTypes()
db.readfp(f, True)
return db.types_map[True]

View File

@ -76,14 +76,13 @@ class FatalIncludeError(SyntaxError):
def default_loader(href, parse, encoding=None):
if parse == "xml":
file = open(href, 'rb')
with open(href, 'rb') as file:
data = ElementTree.parse(file).getroot()
else:
if not encoding:
encoding = 'UTF-8'
file = open(href, 'r', encoding=encoding)
with open(href, 'r', encoding=encoding) as file:
data = file.read()
file.close()
return data
##