diff --git a/src/extractcode/libarchive2.py b/src/extractcode/libarchive2.py index 024d116..0a18293 100644 --- a/src/extractcode/libarchive2.py +++ b/src/extractcode/libarchive2.py @@ -7,11 +7,14 @@ # See https://aboutcode.org for more information about nexB OSS projects. # +import contextlib from functools import partial import locale import logging import mmap import os +import threading +import time import warnings import ctypes.util @@ -133,20 +136,68 @@ def load_lib(): return command.load_shared_library(dll_loc) -def set_env_with_tz(): - # NOTE: this is important to avoid timezone differences - os.environ["TZ"] = "UTC" - - -set_env_with_tz() - -# NOTE: this is important to avoid locale-specific errors on various OS -locale.setlocale(locale.LC_ALL, "") - # load and initialize the shared library libarchive = load_lib() +# The timezone and locale are process-wide settings shared with the calling +# application. We set them only while an extraction is running rather than +# globally on import. See https://github.com/aboutcode-org/extractcode/issues/65 +_extraction_env_lock = threading.Lock() +_extraction_env_users = 0 +_saved_tz_and_locale = None + +def set_tz(tz): + """ + Set the "TZ" environment variable to ``tz`` or unset it if ``tz`` is None. + """ + if tz is None: + os.environ.pop("TZ", None) + else: + os.environ["TZ"] = tz + # Some C libraries such as glibc cache the timezone and only reload "TZ" in + # some calls: we must reload it explicitly (this is not available on Windows) + if hasattr(time, "tzset"): + time.tzset() + + +@contextlib.contextmanager +def extraction_environment(): + """ + Context manager to run an extraction with the "TZ" environment variable set + to UTC and with the user default locale, then restore the original "TZ" and + locale on exit. + + NOTE: UTC is important to avoid timezone differences in the dates of + extracted files, and the user default locale is important to avoid + locale-specific errors on various OS. + + This is reentrant and safe to use for concurrent extractions in threads: the + original "TZ" and locale are restored when the last running extraction + completes. Since these are process-wide settings, other threads also see + them while an extraction is running. + """ + global _extraction_env_users, _saved_tz_and_locale + with _extraction_env_lock: + if not _extraction_env_users: + saved = os.environ.get("TZ"), locale.setlocale(locale.LC_ALL) + locale.setlocale(locale.LC_ALL, "") + set_tz("UTC") + _saved_tz_and_locale = saved + _extraction_env_users += 1 + try: + yield + finally: + with _extraction_env_lock: + _extraction_env_users -= 1 + if not _extraction_env_users: + original_tz, original_locale = _saved_tz_and_locale + _saved_tz_and_locale = None + set_tz(original_tz) + locale.setlocale(locale.LC_ALL, original_locale) + + +@extraction_environment() def extract(location, target_dir, skip_symlinks=True): """ Extract files from a libarchive-supported archive file at `location` in the @@ -160,8 +211,6 @@ def extract(location, target_dir, skip_symlinks=True): abs_target_dir = os.path.abspath(os.path.expanduser(target_dir)) warnings = [] - set_env_with_tz() - for entry in list_entries(abs_location): logger.debug("processing entry: {}".format(entry)) if not entry: diff --git a/tests/test_libarchive2.py b/tests/test_libarchive2.py index 78315e9..188bde2 100644 --- a/tests/test_libarchive2.py +++ b/tests/test_libarchive2.py @@ -7,9 +7,19 @@ # See https://aboutcode.org for more information about nexB OSS projects. # +import locale import os +import subprocess +import sys +import time +import zipfile +from unittest import mock +import pytest + +from commoncode import date as commoncode_date from commoncode import fileutils +from commoncode.system import on_windows from extractcode_assert_utils import check_files from extractcode_assert_utils import BaseArchiveTestCase @@ -43,3 +53,115 @@ def test_libarchive_extract_can_extract_to_relative_paths(self): assert [] == result expected = ["c/a/a.txt", "c/b/a.txt", "c/c/a.txt"] check_files(test_tgt_dir, expected) + + +class TestExtractionEnvironment(BaseArchiveTestCase): + """ + Importing or using libarchive2 must not change the timezone or locale of the + calling application. See https://github.com/aboutcode-org/extractcode/issues/65 + """ + + # A POSIX-style TZ that is not UTC and has no DST + local_tz = "EST+05" + + def setUp(self): + self.original_locale = locale.setlocale(locale.LC_ALL) + + def tearDown(self): + locale.setlocale(locale.LC_ALL, self.original_locale) + # reload the TZ restored by mock.patch.dict in the C library + if hasattr(time, "tzset"): + time.tzset() + + def make_zip_with_local_date(self): + # zipfile only stores a DOS date which is in local time: libarchive + # converts it to a timestamp using the current TZ + test_file = os.path.join(self.get_temp_dir(), "dos_date.zip") + with zipfile.ZipFile(test_file, "w") as zf: + zf.writestr(zipfile.ZipInfo("a.txt", date_time=(2020, 1, 2, 3, 4, 6)), "a") + return test_file + + def test_importing_libarchive2_does_not_change_timezone_or_locale(self): + code = ( + "import locale, os\n" + "locale.setlocale(locale.LC_ALL, 'C')\n" + "import extractcode.libarchive2\n" + "assert os.environ['TZ'] == 'EST+05', os.environ['TZ']\n" + "assert locale.setlocale(locale.LC_ALL) == 'C', locale.setlocale(locale.LC_ALL)\n" + ) + env = dict(os.environ, TZ=self.local_tz) + result = subprocess.run( + [sys.executable, "-c", code], env=env, capture_output=True, text=True + ) + assert result.returncode == 0, result.stderr + + def test_extract_restores_original_timezone_and_locale(self): + from extractcode.libarchive2 import extract + + test_file = self.get_test_loc("archive/relative_path/basic.zip") + test_dir = self.get_temp_dir() + with mock.patch.dict(os.environ, {"TZ": self.local_tz}): + locale.setlocale(locale.LC_ALL, "C") + extract(test_file, test_dir) + assert os.environ["TZ"] == self.local_tz + assert locale.setlocale(locale.LC_ALL) == "C" + + def test_extract_does_not_set_timezone_when_originally_unset(self): + from extractcode.libarchive2 import extract + + test_file = self.get_test_loc("archive/relative_path/basic.zip") + test_dir = self.get_temp_dir() + with mock.patch.dict(os.environ): + os.environ.pop("TZ", None) + extract(test_file, test_dir) + assert "TZ" not in os.environ + + def test_extract_restores_original_timezone_and_locale_on_error(self): + from extractcode.libarchive2 import ArchiveError + from extractcode.libarchive2 import extract + + test_file = self.get_test_loc("archive/not_archive/wildtest.txt") + test_dir = self.get_temp_dir() + with mock.patch.dict(os.environ, {"TZ": self.local_tz}): + locale.setlocale(locale.LC_ALL, "C") + with pytest.raises(ArchiveError): + extract(test_file, test_dir) + assert os.environ["TZ"] == self.local_tz + assert locale.setlocale(locale.LC_ALL) == "C" + + @pytest.mark.skipif(on_windows, reason="The C runtime caches the TZ on Windows") + def test_extract_does_not_change_the_local_time_of_the_caller(self): + # Run in a subprocess to check the timezone as cached by the C library + # rather than only the TZ environment variable + code = ( + "import sys, time\n" + "from extractcode.libarchive2 import extract\n" + "extract(sys.argv[1], sys.argv[2])\n" + "assert time.localtime(0).tm_hour == 19, time.localtime(0)\n" + ) + env = dict(os.environ, TZ=self.local_tz) + args = [sys.executable, "-c", code, self.make_zip_with_local_date(), self.get_temp_dir()] + result = subprocess.run(args, env=env, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + def test_extraction_environment_is_reentrant(self): + from extractcode.libarchive2 import extraction_environment + + with mock.patch.dict(os.environ, {"TZ": self.local_tz}): + with extraction_environment(): + with extraction_environment(): + assert os.environ["TZ"] == "UTC" + # still in an extraction: the original TZ is not restored yet + assert os.environ["TZ"] == "UTC" + assert os.environ["TZ"] == self.local_tz + + @pytest.mark.skipif(on_windows, reason="The C runtime caches the TZ on Windows") + def test_extract_uses_utc_for_local_dates_regardless_of_the_local_timezone(self): + from extractcode.libarchive2 import extract + + test_file = self.make_zip_with_local_date() + test_dir = self.get_temp_dir() + with mock.patch.dict(os.environ, {"TZ": self.local_tz}): + extract(test_file, test_dir) + result = commoncode_date.get_file_mtime(os.path.join(test_dir, "a.txt")) + assert result == "2020-01-02 03:04:06"