zipimport.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. """zipimport provides support for importing Python modules from Zip archives.
  2. This module exports three objects:
  3. - zipimporter: a class; its constructor takes a path to a Zip archive.
  4. - ZipImportError: exception raised by zipimporter objects. It's a
  5. subclass of ImportError, so it can be caught as ImportError, too.
  6. - _zip_directory_cache: a dict, mapping archive paths to zip directory
  7. info dicts, as used in zipimporter._files.
  8. It is usually not needed to use the zipimport module explicitly; it is
  9. used by the builtin import mechanism for sys.path items that are paths
  10. to Zip archives.
  11. """
  12. #from importlib import _bootstrap_external
  13. #from importlib import _bootstrap # for _verbose_message
  14. import _frozen_importlib_external as _bootstrap_external
  15. from _frozen_importlib_external import _unpack_uint16, _unpack_uint32
  16. import _frozen_importlib as _bootstrap # for _verbose_message
  17. import _imp # for check_hash_based_pycs
  18. import _io # for open
  19. import marshal # for loads
  20. import sys # for modules
  21. import time # for mktime
  22. import _warnings # For warn()
  23. __all__ = ['ZipImportError', 'zipimporter']
  24. path_sep = _bootstrap_external.path_sep
  25. alt_path_sep = _bootstrap_external.path_separators[1:]
  26. class ZipImportError(ImportError):
  27. pass
  28. # _read_directory() cache
  29. _zip_directory_cache = {}
  30. _module_type = type(sys)
  31. END_CENTRAL_DIR_SIZE = 22
  32. STRING_END_ARCHIVE = b'PK\x05\x06'
  33. MAX_COMMENT_LEN = (1 << 16) - 1
  34. class zipimporter(_bootstrap_external._LoaderBasics):
  35. """zipimporter(archivepath) -> zipimporter object
  36. Create a new zipimporter instance. 'archivepath' must be a path to
  37. a zipfile, or to a specific path inside a zipfile. For example, it can be
  38. '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a
  39. valid directory inside the archive.
  40. 'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip
  41. archive.
  42. The 'archive' attribute of zipimporter objects contains the name of the
  43. zipfile targeted.
  44. """
  45. # Split the "subdirectory" from the Zip archive path, lookup a matching
  46. # entry in sys.path_importer_cache, fetch the file directory from there
  47. # if found, or else read it from the archive.
  48. def __init__(self, path):
  49. if not isinstance(path, str):
  50. raise TypeError(f"expected str, not {type(path)!r}")
  51. if not path:
  52. raise ZipImportError('archive path is empty', path=path)
  53. if alt_path_sep:
  54. path = path.replace(alt_path_sep, path_sep)
  55. prefix = []
  56. while True:
  57. try:
  58. st = _bootstrap_external._path_stat(path)
  59. except (OSError, ValueError):
  60. # On Windows a ValueError is raised for too long paths.
  61. # Back up one path element.
  62. dirname, basename = _bootstrap_external._path_split(path)
  63. if dirname == path:
  64. raise ZipImportError('not a Zip file', path=path)
  65. path = dirname
  66. prefix.append(basename)
  67. else:
  68. # it exists
  69. if (st.st_mode & 0o170000) != 0o100000: # stat.S_ISREG
  70. # it's a not file
  71. raise ZipImportError('not a Zip file', path=path)
  72. break
  73. try:
  74. files = _zip_directory_cache[path]
  75. except KeyError:
  76. files = _read_directory(path)
  77. _zip_directory_cache[path] = files
  78. self._files = files
  79. self.archive = path
  80. # a prefix directory following the ZIP file path.
  81. self.prefix = _bootstrap_external._path_join(*prefix[::-1])
  82. if self.prefix:
  83. self.prefix += path_sep
  84. # Check whether we can satisfy the import of the module named by
  85. # 'fullname', or whether it could be a portion of a namespace
  86. # package. Return self if we can load it, a string containing the
  87. # full path if it's a possible namespace portion, None if we
  88. # can't load it.
  89. def find_loader(self, fullname, path=None):
  90. """find_loader(fullname, path=None) -> self, str or None.
  91. Search for a module specified by 'fullname'. 'fullname' must be the
  92. fully qualified (dotted) module name. It returns the zipimporter
  93. instance itself if the module was found, a string containing the
  94. full path name if it's possibly a portion of a namespace package,
  95. or None otherwise. The optional 'path' argument is ignored -- it's
  96. there for compatibility with the importer protocol.
  97. Deprecated since Python 3.10. Use find_spec() instead.
  98. """
  99. _warnings.warn("zipimporter.find_loader() is deprecated and slated for "
  100. "removal in Python 3.12; use find_spec() instead",
  101. DeprecationWarning)
  102. mi = _get_module_info(self, fullname)
  103. if mi is not None:
  104. # This is a module or package.
  105. return self, []
  106. # Not a module or regular package. See if this is a directory, and
  107. # therefore possibly a portion of a namespace package.
  108. # We're only interested in the last path component of fullname
  109. # earlier components are recorded in self.prefix.
  110. modpath = _get_module_path(self, fullname)
  111. if _is_dir(self, modpath):
  112. # This is possibly a portion of a namespace
  113. # package. Return the string representing its path,
  114. # without a trailing separator.
  115. return None, [f'{self.archive}{path_sep}{modpath}']
  116. return None, []
  117. # Check whether we can satisfy the import of the module named by
  118. # 'fullname'. Return self if we can, None if we can't.
  119. def find_module(self, fullname, path=None):
  120. """find_module(fullname, path=None) -> self or None.
  121. Search for a module specified by 'fullname'. 'fullname' must be the
  122. fully qualified (dotted) module name. It returns the zipimporter
  123. instance itself if the module was found, or None if it wasn't.
  124. The optional 'path' argument is ignored -- it's there for compatibility
  125. with the importer protocol.
  126. Deprecated since Python 3.10. Use find_spec() instead.
  127. """
  128. _warnings.warn("zipimporter.find_module() is deprecated and slated for "
  129. "removal in Python 3.12; use find_spec() instead",
  130. DeprecationWarning)
  131. return self.find_loader(fullname, path)[0]
  132. def find_spec(self, fullname, target=None):
  133. """Create a ModuleSpec for the specified module.
  134. Returns None if the module cannot be found.
  135. """
  136. module_info = _get_module_info(self, fullname)
  137. if module_info is not None:
  138. return _bootstrap.spec_from_loader(fullname, self, is_package=module_info)
  139. else:
  140. # Not a module or regular package. See if this is a directory, and
  141. # therefore possibly a portion of a namespace package.
  142. # We're only interested in the last path component of fullname
  143. # earlier components are recorded in self.prefix.
  144. modpath = _get_module_path(self, fullname)
  145. if _is_dir(self, modpath):
  146. # This is possibly a portion of a namespace
  147. # package. Return the string representing its path,
  148. # without a trailing separator.
  149. path = f'{self.archive}{path_sep}{modpath}'
  150. spec = _bootstrap.ModuleSpec(name=fullname, loader=None,
  151. is_package=True)
  152. spec.submodule_search_locations.append(path)
  153. return spec
  154. else:
  155. return None
  156. def get_code(self, fullname):
  157. """get_code(fullname) -> code object.
  158. Return the code object for the specified module. Raise ZipImportError
  159. if the module couldn't be imported.
  160. """
  161. code, ispackage, modpath = _get_module_code(self, fullname)
  162. return code
  163. def get_data(self, pathname):
  164. """get_data(pathname) -> string with file data.
  165. Return the data associated with 'pathname'. Raise OSError if
  166. the file wasn't found.
  167. """
  168. if alt_path_sep:
  169. pathname = pathname.replace(alt_path_sep, path_sep)
  170. key = pathname
  171. if pathname.startswith(self.archive + path_sep):
  172. key = pathname[len(self.archive + path_sep):]
  173. try:
  174. toc_entry = self._files[key]
  175. except KeyError:
  176. raise OSError(0, '', key)
  177. return _get_data(self.archive, toc_entry)
  178. # Return a string matching __file__ for the named module
  179. def get_filename(self, fullname):
  180. """get_filename(fullname) -> filename string.
  181. Return the filename for the specified module or raise ZipImportError
  182. if it couldn't be imported.
  183. """
  184. # Deciding the filename requires working out where the code
  185. # would come from if the module was actually loaded
  186. code, ispackage, modpath = _get_module_code(self, fullname)
  187. return modpath
  188. def get_source(self, fullname):
  189. """get_source(fullname) -> source string.
  190. Return the source code for the specified module. Raise ZipImportError
  191. if the module couldn't be found, return None if the archive does
  192. contain the module, but has no source for it.
  193. """
  194. mi = _get_module_info(self, fullname)
  195. if mi is None:
  196. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
  197. path = _get_module_path(self, fullname)
  198. if mi:
  199. fullpath = _bootstrap_external._path_join(path, '__init__.py')
  200. else:
  201. fullpath = f'{path}.py'
  202. try:
  203. toc_entry = self._files[fullpath]
  204. except KeyError:
  205. # we have the module, but no source
  206. return None
  207. return _get_data(self.archive, toc_entry).decode()
  208. # Return a bool signifying whether the module is a package or not.
  209. def is_package(self, fullname):
  210. """is_package(fullname) -> bool.
  211. Return True if the module specified by fullname is a package.
  212. Raise ZipImportError if the module couldn't be found.
  213. """
  214. mi = _get_module_info(self, fullname)
  215. if mi is None:
  216. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
  217. return mi
  218. # Load and return the module named by 'fullname'.
  219. def load_module(self, fullname):
  220. """load_module(fullname) -> module.
  221. Load the module specified by 'fullname'. 'fullname' must be the
  222. fully qualified (dotted) module name. It returns the imported
  223. module, or raises ZipImportError if it could not be imported.
  224. Deprecated since Python 3.10. Use exec_module() instead.
  225. """
  226. msg = ("zipimport.zipimporter.load_module() is deprecated and slated for "
  227. "removal in Python 3.12; use exec_module() instead")
  228. _warnings.warn(msg, DeprecationWarning)
  229. code, ispackage, modpath = _get_module_code(self, fullname)
  230. mod = sys.modules.get(fullname)
  231. if mod is None or not isinstance(mod, _module_type):
  232. mod = _module_type(fullname)
  233. sys.modules[fullname] = mod
  234. mod.__loader__ = self
  235. try:
  236. if ispackage:
  237. # add __path__ to the module *before* the code gets
  238. # executed
  239. path = _get_module_path(self, fullname)
  240. fullpath = _bootstrap_external._path_join(self.archive, path)
  241. mod.__path__ = [fullpath]
  242. if not hasattr(mod, '__builtins__'):
  243. mod.__builtins__ = __builtins__
  244. _bootstrap_external._fix_up_module(mod.__dict__, fullname, modpath)
  245. exec(code, mod.__dict__)
  246. except:
  247. del sys.modules[fullname]
  248. raise
  249. try:
  250. mod = sys.modules[fullname]
  251. except KeyError:
  252. raise ImportError(f'Loaded module {fullname!r} not found in sys.modules')
  253. _bootstrap._verbose_message('import {} # loaded from Zip {}', fullname, modpath)
  254. return mod
  255. def get_resource_reader(self, fullname):
  256. """Return the ResourceReader for a package in a zip file.
  257. If 'fullname' is a package within the zip file, return the
  258. 'ResourceReader' object for the package. Otherwise return None.
  259. """
  260. try:
  261. if not self.is_package(fullname):
  262. return None
  263. except ZipImportError:
  264. return None
  265. from importlib.readers import ZipReader
  266. return ZipReader(self, fullname)
  267. def invalidate_caches(self):
  268. """Reload the file data of the archive path."""
  269. try:
  270. self._files = _read_directory(self.archive)
  271. _zip_directory_cache[self.archive] = self._files
  272. except ZipImportError:
  273. _zip_directory_cache.pop(self.archive, None)
  274. self._files = {}
  275. def __repr__(self):
  276. return f'<zipimporter object "{self.archive}{path_sep}{self.prefix}">'
  277. # _zip_searchorder defines how we search for a module in the Zip
  278. # archive: we first search for a package __init__, then for
  279. # non-package .pyc, and .py entries. The .pyc entries
  280. # are swapped by initzipimport() if we run in optimized mode. Also,
  281. # '/' is replaced by path_sep there.
  282. _zip_searchorder = (
  283. (path_sep + '__init__.pyc', True, True),
  284. (path_sep + '__init__.py', False, True),
  285. ('.pyc', True, False),
  286. ('.py', False, False),
  287. )
  288. # Given a module name, return the potential file path in the
  289. # archive (without extension).
  290. def _get_module_path(self, fullname):
  291. return self.prefix + fullname.rpartition('.')[2]
  292. # Does this path represent a directory?
  293. def _is_dir(self, path):
  294. # See if this is a "directory". If so, it's eligible to be part
  295. # of a namespace package. We test by seeing if the name, with an
  296. # appended path separator, exists.
  297. dirpath = path + path_sep
  298. # If dirpath is present in self._files, we have a directory.
  299. return dirpath in self._files
  300. # Return some information about a module.
  301. def _get_module_info(self, fullname):
  302. path = _get_module_path(self, fullname)
  303. for suffix, isbytecode, ispackage in _zip_searchorder:
  304. fullpath = path + suffix
  305. if fullpath in self._files:
  306. return ispackage
  307. return None
  308. # implementation
  309. # _read_directory(archive) -> files dict (new reference)
  310. #
  311. # Given a path to a Zip archive, build a dict, mapping file names
  312. # (local to the archive, using SEP as a separator) to toc entries.
  313. #
  314. # A toc_entry is a tuple:
  315. #
  316. # (__file__, # value to use for __file__, available for all files,
  317. # # encoded to the filesystem encoding
  318. # compress, # compression kind; 0 for uncompressed
  319. # data_size, # size of compressed data on disk
  320. # file_size, # size of decompressed data
  321. # file_offset, # offset of file header from start of archive
  322. # time, # mod time of file (in dos format)
  323. # date, # mod data of file (in dos format)
  324. # crc, # crc checksum of the data
  325. # )
  326. #
  327. # Directories can be recognized by the trailing path_sep in the name,
  328. # data_size and file_offset are 0.
  329. def _read_directory(archive):
  330. try:
  331. fp = _io.open_code(archive)
  332. except OSError:
  333. raise ZipImportError(f"can't open Zip file: {archive!r}", path=archive)
  334. with fp:
  335. # GH-87235: On macOS all file descriptors for /dev/fd/N share the same
  336. # file offset, reset the file offset after scanning the zipfile diretory
  337. # to not cause problems when some runs 'python3 /dev/fd/9 9<some_script'
  338. start_offset = fp.tell()
  339. try:
  340. try:
  341. fp.seek(-END_CENTRAL_DIR_SIZE, 2)
  342. header_position = fp.tell()
  343. buffer = fp.read(END_CENTRAL_DIR_SIZE)
  344. except OSError:
  345. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  346. if len(buffer) != END_CENTRAL_DIR_SIZE:
  347. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  348. if buffer[:4] != STRING_END_ARCHIVE:
  349. # Bad: End of Central Dir signature
  350. # Check if there's a comment.
  351. try:
  352. fp.seek(0, 2)
  353. file_size = fp.tell()
  354. except OSError:
  355. raise ZipImportError(f"can't read Zip file: {archive!r}",
  356. path=archive)
  357. max_comment_start = max(file_size - MAX_COMMENT_LEN -
  358. END_CENTRAL_DIR_SIZE, 0)
  359. try:
  360. fp.seek(max_comment_start)
  361. data = fp.read()
  362. except OSError:
  363. raise ZipImportError(f"can't read Zip file: {archive!r}",
  364. path=archive)
  365. pos = data.rfind(STRING_END_ARCHIVE)
  366. if pos < 0:
  367. raise ZipImportError(f'not a Zip file: {archive!r}',
  368. path=archive)
  369. buffer = data[pos:pos+END_CENTRAL_DIR_SIZE]
  370. if len(buffer) != END_CENTRAL_DIR_SIZE:
  371. raise ZipImportError(f"corrupt Zip file: {archive!r}",
  372. path=archive)
  373. header_position = file_size - len(data) + pos
  374. header_size = _unpack_uint32(buffer[12:16])
  375. header_offset = _unpack_uint32(buffer[16:20])
  376. if header_position < header_size:
  377. raise ZipImportError(f'bad central directory size: {archive!r}', path=archive)
  378. if header_position < header_offset:
  379. raise ZipImportError(f'bad central directory offset: {archive!r}', path=archive)
  380. header_position -= header_size
  381. arc_offset = header_position - header_offset
  382. if arc_offset < 0:
  383. raise ZipImportError(f'bad central directory size or offset: {archive!r}', path=archive)
  384. files = {}
  385. # Start of Central Directory
  386. count = 0
  387. try:
  388. fp.seek(header_position)
  389. except OSError:
  390. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  391. while True:
  392. buffer = fp.read(46)
  393. if len(buffer) < 4:
  394. raise EOFError('EOF read where not expected')
  395. # Start of file header
  396. if buffer[:4] != b'PK\x01\x02':
  397. break # Bad: Central Dir File Header
  398. if len(buffer) != 46:
  399. raise EOFError('EOF read where not expected')
  400. flags = _unpack_uint16(buffer[8:10])
  401. compress = _unpack_uint16(buffer[10:12])
  402. time = _unpack_uint16(buffer[12:14])
  403. date = _unpack_uint16(buffer[14:16])
  404. crc = _unpack_uint32(buffer[16:20])
  405. data_size = _unpack_uint32(buffer[20:24])
  406. file_size = _unpack_uint32(buffer[24:28])
  407. name_size = _unpack_uint16(buffer[28:30])
  408. extra_size = _unpack_uint16(buffer[30:32])
  409. comment_size = _unpack_uint16(buffer[32:34])
  410. file_offset = _unpack_uint32(buffer[42:46])
  411. header_size = name_size + extra_size + comment_size
  412. if file_offset > header_offset:
  413. raise ZipImportError(f'bad local header offset: {archive!r}', path=archive)
  414. file_offset += arc_offset
  415. try:
  416. name = fp.read(name_size)
  417. except OSError:
  418. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  419. if len(name) != name_size:
  420. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  421. # On Windows, calling fseek to skip over the fields we don't use is
  422. # slower than reading the data because fseek flushes stdio's
  423. # internal buffers. See issue #8745.
  424. try:
  425. if len(fp.read(header_size - name_size)) != header_size - name_size:
  426. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  427. except OSError:
  428. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  429. if flags & 0x800:
  430. # UTF-8 file names extension
  431. name = name.decode()
  432. else:
  433. # Historical ZIP filename encoding
  434. try:
  435. name = name.decode('ascii')
  436. except UnicodeDecodeError:
  437. name = name.decode('latin1').translate(cp437_table)
  438. name = name.replace('/', path_sep)
  439. path = _bootstrap_external._path_join(archive, name)
  440. t = (path, compress, data_size, file_size, file_offset, time, date, crc)
  441. files[name] = t
  442. count += 1
  443. finally:
  444. fp.seek(start_offset)
  445. _bootstrap._verbose_message('zipimport: found {} names in {!r}', count, archive)
  446. return files
  447. # During bootstrap, we may need to load the encodings
  448. # package from a ZIP file. But the cp437 encoding is implemented
  449. # in Python in the encodings package.
  450. #
  451. # Break out of this dependency by using the translation table for
  452. # the cp437 encoding.
  453. cp437_table = (
  454. # ASCII part, 8 rows x 16 chars
  455. '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
  456. '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
  457. ' !"#$%&\'()*+,-./'
  458. '0123456789:;<=>?'
  459. '@ABCDEFGHIJKLMNO'
  460. 'PQRSTUVWXYZ[\\]^_'
  461. '`abcdefghijklmno'
  462. 'pqrstuvwxyz{|}~\x7f'
  463. # non-ASCII part, 16 rows x 8 chars
  464. '\xc7\xfc\xe9\xe2\xe4\xe0\xe5\xe7'
  465. '\xea\xeb\xe8\xef\xee\xec\xc4\xc5'
  466. '\xc9\xe6\xc6\xf4\xf6\xf2\xfb\xf9'
  467. '\xff\xd6\xdc\xa2\xa3\xa5\u20a7\u0192'
  468. '\xe1\xed\xf3\xfa\xf1\xd1\xaa\xba'
  469. '\xbf\u2310\xac\xbd\xbc\xa1\xab\xbb'
  470. '\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556'
  471. '\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510'
  472. '\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f'
  473. '\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567'
  474. '\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b'
  475. '\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580'
  476. '\u03b1\xdf\u0393\u03c0\u03a3\u03c3\xb5\u03c4'
  477. '\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229'
  478. '\u2261\xb1\u2265\u2264\u2320\u2321\xf7\u2248'
  479. '\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0'
  480. )
  481. _importing_zlib = False
  482. # Return the zlib.decompress function object, or NULL if zlib couldn't
  483. # be imported. The function is cached when found, so subsequent calls
  484. # don't import zlib again.
  485. def _get_decompress_func():
  486. global _importing_zlib
  487. if _importing_zlib:
  488. # Someone has a zlib.py[co] in their Zip file
  489. # let's avoid a stack overflow.
  490. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  491. raise ZipImportError("can't decompress data; zlib not available")
  492. _importing_zlib = True
  493. try:
  494. from zlib import decompress
  495. except Exception:
  496. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  497. raise ZipImportError("can't decompress data; zlib not available")
  498. finally:
  499. _importing_zlib = False
  500. _bootstrap._verbose_message('zipimport: zlib available')
  501. return decompress
  502. # Given a path to a Zip file and a toc_entry, return the (uncompressed) data.
  503. def _get_data(archive, toc_entry):
  504. datapath, compress, data_size, file_size, file_offset, time, date, crc = toc_entry
  505. if data_size < 0:
  506. raise ZipImportError('negative data size')
  507. with _io.open_code(archive) as fp:
  508. # Check to make sure the local file header is correct
  509. try:
  510. fp.seek(file_offset)
  511. except OSError:
  512. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  513. buffer = fp.read(30)
  514. if len(buffer) != 30:
  515. raise EOFError('EOF read where not expected')
  516. if buffer[:4] != b'PK\x03\x04':
  517. # Bad: Local File Header
  518. raise ZipImportError(f'bad local file header: {archive!r}', path=archive)
  519. name_size = _unpack_uint16(buffer[26:28])
  520. extra_size = _unpack_uint16(buffer[28:30])
  521. header_size = 30 + name_size + extra_size
  522. file_offset += header_size # Start of file data
  523. try:
  524. fp.seek(file_offset)
  525. except OSError:
  526. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  527. raw_data = fp.read(data_size)
  528. if len(raw_data) != data_size:
  529. raise OSError("zipimport: can't read data")
  530. if compress == 0:
  531. # data is not compressed
  532. return raw_data
  533. # Decompress with zlib
  534. try:
  535. decompress = _get_decompress_func()
  536. except Exception:
  537. raise ZipImportError("can't decompress data; zlib not available")
  538. return decompress(raw_data, -15)
  539. # Lenient date/time comparison function. The precision of the mtime
  540. # in the archive is lower than the mtime stored in a .pyc: we
  541. # must allow a difference of at most one second.
  542. def _eq_mtime(t1, t2):
  543. # dostime only stores even seconds, so be lenient
  544. return abs(t1 - t2) <= 1
  545. # Given the contents of a .py[co] file, unmarshal the data
  546. # and return the code object. Raises ImportError it the magic word doesn't
  547. # match, or if the recorded .py[co] metadata does not match the source.
  548. def _unmarshal_code(self, pathname, fullpath, fullname, data):
  549. exc_details = {
  550. 'name': fullname,
  551. 'path': fullpath,
  552. }
  553. flags = _bootstrap_external._classify_pyc(data, fullname, exc_details)
  554. hash_based = flags & 0b1 != 0
  555. if hash_based:
  556. check_source = flags & 0b10 != 0
  557. if (_imp.check_hash_based_pycs != 'never' and
  558. (check_source or _imp.check_hash_based_pycs == 'always')):
  559. source_bytes = _get_pyc_source(self, fullpath)
  560. if source_bytes is not None:
  561. source_hash = _imp.source_hash(
  562. _bootstrap_external._RAW_MAGIC_NUMBER,
  563. source_bytes,
  564. )
  565. _bootstrap_external._validate_hash_pyc(
  566. data, source_hash, fullname, exc_details)
  567. else:
  568. source_mtime, source_size = \
  569. _get_mtime_and_size_of_source(self, fullpath)
  570. if source_mtime:
  571. # We don't use _bootstrap_external._validate_timestamp_pyc
  572. # to allow for a more lenient timestamp check.
  573. if (not _eq_mtime(_unpack_uint32(data[8:12]), source_mtime) or
  574. _unpack_uint32(data[12:16]) != source_size):
  575. _bootstrap._verbose_message(
  576. f'bytecode is stale for {fullname!r}')
  577. return None
  578. code = marshal.loads(data[16:])
  579. if not isinstance(code, _code_type):
  580. raise TypeError(f'compiled module {pathname!r} is not a code object')
  581. return code
  582. _code_type = type(_unmarshal_code.__code__)
  583. # Replace any occurrences of '\r\n?' in the input string with '\n'.
  584. # This converts DOS and Mac line endings to Unix line endings.
  585. def _normalize_line_endings(source):
  586. source = source.replace(b'\r\n', b'\n')
  587. source = source.replace(b'\r', b'\n')
  588. return source
  589. # Given a string buffer containing Python source code, compile it
  590. # and return a code object.
  591. def _compile_source(pathname, source):
  592. source = _normalize_line_endings(source)
  593. return compile(source, pathname, 'exec', dont_inherit=True)
  594. # Convert the date/time values found in the Zip archive to a value
  595. # that's compatible with the time stamp stored in .pyc files.
  596. def _parse_dostime(d, t):
  597. return time.mktime((
  598. (d >> 9) + 1980, # bits 9..15: year
  599. (d >> 5) & 0xF, # bits 5..8: month
  600. d & 0x1F, # bits 0..4: day
  601. t >> 11, # bits 11..15: hours
  602. (t >> 5) & 0x3F, # bits 8..10: minutes
  603. (t & 0x1F) * 2, # bits 0..7: seconds / 2
  604. -1, -1, -1))
  605. # Given a path to a .pyc file in the archive, return the
  606. # modification time of the matching .py file and its size,
  607. # or (0, 0) if no source is available.
  608. def _get_mtime_and_size_of_source(self, path):
  609. try:
  610. # strip 'c' or 'o' from *.py[co]
  611. assert path[-1:] in ('c', 'o')
  612. path = path[:-1]
  613. toc_entry = self._files[path]
  614. # fetch the time stamp of the .py file for comparison
  615. # with an embedded pyc time stamp
  616. time = toc_entry[5]
  617. date = toc_entry[6]
  618. uncompressed_size = toc_entry[3]
  619. return _parse_dostime(date, time), uncompressed_size
  620. except (KeyError, IndexError, TypeError):
  621. return 0, 0
  622. # Given a path to a .pyc file in the archive, return the
  623. # contents of the matching .py file, or None if no source
  624. # is available.
  625. def _get_pyc_source(self, path):
  626. # strip 'c' or 'o' from *.py[co]
  627. assert path[-1:] in ('c', 'o')
  628. path = path[:-1]
  629. try:
  630. toc_entry = self._files[path]
  631. except KeyError:
  632. return None
  633. else:
  634. return _get_data(self.archive, toc_entry)
  635. # Get the code object associated with the module specified by
  636. # 'fullname'.
  637. def _get_module_code(self, fullname):
  638. path = _get_module_path(self, fullname)
  639. import_error = None
  640. for suffix, isbytecode, ispackage in _zip_searchorder:
  641. fullpath = path + suffix
  642. _bootstrap._verbose_message('trying {}{}{}', self.archive, path_sep, fullpath, verbosity=2)
  643. try:
  644. toc_entry = self._files[fullpath]
  645. except KeyError:
  646. pass
  647. else:
  648. modpath = toc_entry[0]
  649. data = _get_data(self.archive, toc_entry)
  650. code = None
  651. if isbytecode:
  652. try:
  653. code = _unmarshal_code(self, modpath, fullpath, fullname, data)
  654. except ImportError as exc:
  655. import_error = exc
  656. else:
  657. code = _compile_source(modpath, data)
  658. if code is None:
  659. # bad magic number or non-matching mtime
  660. # in byte code, try next
  661. continue
  662. modpath = toc_entry[0]
  663. return code, ispackage, modpath
  664. else:
  665. if import_error:
  666. msg = f"module load failed: {import_error}"
  667. raise ZipImportError(msg, name=fullname) from import_error
  668. else:
  669. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)