Skip to content
Open
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
95 changes: 53 additions & 42 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"""

import sys
from _thread import RLock as _RLock
lazy import os
lazy import posixpath
lazy import urllib.parse
Expand Down Expand Up @@ -67,7 +68,9 @@
]

inited = False
_in_init = False
_db = None
_lock = _RLock()


class MimeTypes:
Expand All @@ -80,7 +83,9 @@ class MimeTypes:

def __init__(self, filenames=(), strict=True):
if not inited:
init()
with _lock:
if not inited and not _in_init:
init()
self.encodings_map = _encodings_map_default.copy()
self.suffix_map = _suffix_map_default.copy()
self.types_map = ({}, {}) # dict for (non-strict, strict)
Expand Down Expand Up @@ -230,9 +235,9 @@ def guess_all_extensions(self, type, strict=True):
but non-standard types.
"""
type = type.lower()
extensions = list(self.types_map_inv[True].get(type, []))
extensions = list(self.types_map_inv[True].get(type, ()))
if not strict:
for ext in self.types_map_inv[False].get(type, []):
for ext in list(self.types_map_inv[False].get(type, ())):
if ext not in extensions:
extensions.append(ext)
return extensions
Expand Down Expand Up @@ -338,6 +343,17 @@ def enum_types(mimedb):
except OSError:
continue

def _get_db():
db = _db
if db is None:
with _lock:
db = _db
if db is None:
init()
db = _db
return db


def guess_type(url, strict=True):
"""Guess the type of a file based on its URL.
Expand All @@ -356,19 +372,15 @@ def guess_type(url, strict=True):
Optional 'strict' argument when false adds a bunch of commonly found, but
non-standard types.
"""
if _db is None:
init()
return _db.guess_type(url, strict)
return _get_db().guess_type(url, strict)


def guess_file_type(path, *, strict=True):
"""Guess the type of a file based on its path.
Similar to guess_type(), but takes file path instead of URL.
"""
if _db is None:
init()
return _db.guess_file_type(path, strict=strict)
return _get_db().guess_file_type(path, strict=strict)


def guess_all_extensions(type, strict=True):
Expand All @@ -384,9 +396,7 @@ def guess_all_extensions(type, strict=True):
Optional 'strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_all_extensions(type, strict)
return _get_db().guess_all_extensions(type, strict)

def guess_extension(type, strict=True):
"""Guess the extension for a file based on its MIME type.
Expand All @@ -400,9 +410,7 @@ def guess_extension(type, strict=True):
Optional 'strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_extension(type, strict)
return _get_db().guess_extension(type, strict)

def add_type(type, ext, strict=True):
"""Add a mapping between a type and an extension.
Expand All @@ -419,37 +427,40 @@ def add_type(type, ext, strict=True):
list of standard types, else to the list of non-standard
types.
"""
if _db is None:
init()
return _db.add_type(type, ext, strict)
with _lock:
return _get_db().add_type(type, ext, strict)


def init(files=None):
global suffix_map, types_map, encodings_map, common_types
global inited, _db
inited = True # so that MimeTypes.__init__() doesn't call us again

if files is None or _db is None:
db = MimeTypes()
# Quick return if not supported
db.read_windows_registry()

if files is None:
files = knownfiles
else:
files = knownfiles + list(files)
else:
db = _db

for file in files:
if os.path.isfile(file):
db.read(file)
encodings_map = db.encodings_map
suffix_map = db.suffix_map
types_map = db.types_map[True]
common_types = db.types_map[False]
# Make the DB a global variable now that it is fully initialized
_db = db
global inited, _db, _in_init
with _lock:
_in_init = True
try:
if files is None or _db is None:
db = MimeTypes()
# Quick return if not supported
db.read_windows_registry()

if files is None:
files = knownfiles
else:
files = knownfiles + list(files)
else:
db = _db

for file in files:
if os.path.isfile(file):
db.read(file)
encodings_map = db.encodings_map
suffix_map = db.suffix_map
types_map = db.types_map[True]
common_types = db.types_map[False]
# Make the DB a global variable now that it is fully initialized
_db = db
inited = True
finally:
_in_init = False


def read_mime_types(file):
Expand Down
170 changes: 170 additions & 0 deletions Lib/test/test_free_threading/test_mimetypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import mimetypes
import os
import threading
import unittest

from test.support import os_helper, threading_helper


@threading_helper.requires_working_threading()
class TestMimeTypesFreeThreading(unittest.TestCase):
def setUp(self):
self._orig_knownfiles = mimetypes.knownfiles[:]
self.addCleanup(self._restore_mimetypes)

def _restore_mimetypes(self):
mimetypes.knownfiles = self._orig_knownfiles
mimetypes.inited = False
mimetypes._default_mime_types()
mimetypes._db = None
mimetypes.init()

@threading_helper.reap_threads
def test_concurrent_lazy_init_and_add_type(self):
with os_helper.temp_dir() as temp_dir:
mime_file = os.path.join(temp_dir, "sample.mime.types")
with open(mime_file, "w", encoding="utf-8") as fp:
for i in range(100):
fp.write(f"application/x-file-{i} fileext{i}\n")

mimetypes.knownfiles = [mime_file]
errors = []

for _ in range(10):
mimetypes.inited = False
mimetypes._default_mime_types()
mimetypes._db = None

num_writers = 4
num_readers = 4
barrier = threading.Barrier(num_writers + num_readers)

def writer(idx):
barrier.wait()
try:
mimetypes.add_type(
f"application/x-custom-{idx}", f".custom{idx}"
)
except Exception as exc:
errors.append(exc)

def reader():
barrier.wait()
try:
self.assertEqual(
mimetypes.guess_file_type("index.html"),
("text/html", None),
)
db = mimetypes.MimeTypes()
self.assertEqual(
db.guess_file_type("index.html"),
("text/html", None),
)
except Exception as exc:
errors.append(exc)

threads = [
*(threading.Thread(target=writer, args=(i,)) for i in range(num_writers)),
*(threading.Thread(target=reader) for _ in range(num_readers)),
]
with threading_helper.start_threads(threads):
pass

self.assertEqual(errors, [])
self.assertTrue(mimetypes.inited)
self.assertEqual(
mimetypes.guess_file_type("doc.fileext0"),
("application/x-file-0", None),
)
for i in range(num_writers):
self.assertEqual(
mimetypes.guess_file_type(f"sample.custom{i}"),
(f"application/x-custom-{i}", None),
)

@threading_helper.reap_threads
def test_concurrent_add_type_no_duplicates(self):
mimetypes.knownfiles = []
mimetypes.init()
num_threads = 8
barrier = threading.Barrier(num_threads)
errors = []

def worker():
barrier.wait()
try:
for i in range(50):
mimetypes.add_type("application/x-shared", f".sh{i}", strict=True)
mimetypes.add_type("application/x-shared", f".sh_ns{i}", strict=False)
if i % 5 == 0:
exts = mimetypes.guess_all_extensions(
"application/x-shared", strict=False
)
self.assertEqual(len(exts), len(set(exts)))
except Exception as exc:
errors.append(exc)

threads = [threading.Thread(target=worker) for _ in range(num_threads)]
with threading_helper.start_threads(threads):
pass

self.assertEqual(errors, [])
all_exts = mimetypes.guess_all_extensions("application/x-shared", strict=False)
self.assertEqual(len(all_exts), len(set(all_exts)))
self.assertEqual(len(all_exts), 100)

@threading_helper.reap_threads
def test_concurrent_reinit_and_lookups(self):
mimetypes.knownfiles = []
mimetypes.init()

num_readers = 6
num_reinit = 2
barrier = threading.Barrier(num_readers + num_reinit)
stop = threading.Event()
errors = []

def reader():
barrier.wait()
try:
for _ in range(300):
self.assertEqual(
mimetypes.guess_file_type("page.html"),
("text/html", None),
)
self.assertEqual(
mimetypes.guess_type("https://example.com/doc.pdf"),
("application/pdf", None),
)
self.assertEqual(
mimetypes.guess_extension("application/pdf"),
".pdf",
)
except Exception as exc:
errors.append(exc)
finally:
stop.set()

def reinitializer():
barrier.wait()
try:
i = 0
while not stop.is_set():
mimetypes.init()
mimetypes.add_type(f"application/x-temp-{i}", f".tmp{i}")
i += 1
except Exception as exc:
errors.append(exc)

threads = [
*(threading.Thread(target=reader) for _ in range(num_readers)),
*(threading.Thread(target=reinitializer) for _ in range(num_reinit)),
]
with threading_helper.start_threads(threads):
pass

self.assertEqual(errors, [])


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix thread-safety race conditions in :mod:mimetypes during lazy
initialization and concurrent :func:mimetypes.add_type calls.
Loading