wheelfile.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from __future__ import annotations
  2. import csv
  3. import hashlib
  4. import os.path
  5. import re
  6. import stat
  7. import time
  8. from io import StringIO, TextIOWrapper
  9. from typing import IO, TYPE_CHECKING, Literal
  10. from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
  11. from wheel.cli import WheelError
  12. from wheel.util import log, urlsafe_b64decode, urlsafe_b64encode
  13. if TYPE_CHECKING:
  14. from typing import Protocol, Sized, Union
  15. from typing_extensions import Buffer
  16. StrPath = Union[str, os.PathLike[str]]
  17. class SizedBuffer(Sized, Buffer, Protocol): ...
  18. # Non-greedy matching of an optional build number may be too clever (more
  19. # invalid wheel filenames will match). Separate regex for .dist-info?
  20. WHEEL_INFO_RE = re.compile(
  21. r"""^(?P<namever>(?P<name>[^\s-]+?)-(?P<ver>[^\s-]+?))(-(?P<build>\d[^\s-]*))?
  22. -(?P<pyver>[^\s-]+?)-(?P<abi>[^\s-]+?)-(?P<plat>\S+)\.whl$""",
  23. re.VERBOSE,
  24. )
  25. MINIMUM_TIMESTAMP = 315532800 # 1980-01-01 00:00:00 UTC
  26. def get_zipinfo_datetime(timestamp: float | None = None):
  27. # Some applications need reproducible .whl files, but they can't do this without
  28. # forcing the timestamp of the individual ZipInfo objects. See issue #143.
  29. timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time()))
  30. timestamp = max(timestamp, MINIMUM_TIMESTAMP)
  31. return time.gmtime(timestamp)[0:6]
  32. class WheelFile(ZipFile):
  33. """A ZipFile derivative class that also reads SHA-256 hashes from
  34. .dist-info/RECORD and checks any read files against those.
  35. """
  36. _default_algorithm = hashlib.sha256
  37. def __init__(
  38. self,
  39. file: StrPath,
  40. mode: Literal["r", "w", "x", "a"] = "r",
  41. compression: int = ZIP_DEFLATED,
  42. ):
  43. basename = os.path.basename(file)
  44. self.parsed_filename = WHEEL_INFO_RE.match(basename)
  45. if not basename.endswith(".whl") or self.parsed_filename is None:
  46. raise WheelError(f"Bad wheel filename {basename!r}")
  47. ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True)
  48. self.dist_info_path = "{}.dist-info".format(
  49. self.parsed_filename.group("namever")
  50. )
  51. self.record_path = self.dist_info_path + "/RECORD"
  52. self._file_hashes: dict[str, tuple[None, None] | tuple[int, bytes]] = {}
  53. self._file_sizes = {}
  54. if mode == "r":
  55. # Ignore RECORD and any embedded wheel signatures
  56. self._file_hashes[self.record_path] = None, None
  57. self._file_hashes[self.record_path + ".jws"] = None, None
  58. self._file_hashes[self.record_path + ".p7s"] = None, None
  59. # Fill in the expected hashes by reading them from RECORD
  60. try:
  61. record = self.open(self.record_path)
  62. except KeyError:
  63. raise WheelError(f"Missing {self.record_path} file") from None
  64. with record:
  65. for line in csv.reader(
  66. TextIOWrapper(record, newline="", encoding="utf-8")
  67. ):
  68. path, hash_sum, size = line
  69. if not hash_sum:
  70. continue
  71. algorithm, hash_sum = hash_sum.split("=")
  72. try:
  73. hashlib.new(algorithm)
  74. except ValueError:
  75. raise WheelError(
  76. f"Unsupported hash algorithm: {algorithm}"
  77. ) from None
  78. if algorithm.lower() in {"md5", "sha1"}:
  79. raise WheelError(
  80. f"Weak hash algorithm ({algorithm}) is not permitted by "
  81. f"PEP 427"
  82. )
  83. self._file_hashes[path] = (
  84. algorithm,
  85. urlsafe_b64decode(hash_sum.encode("ascii")),
  86. )
  87. def open(
  88. self,
  89. name_or_info: str | ZipInfo,
  90. mode: Literal["r", "w"] = "r",
  91. pwd: bytes | None = None,
  92. ) -> IO[bytes]:
  93. def _update_crc(newdata: bytes) -> None:
  94. eof = ef._eof
  95. update_crc_orig(newdata)
  96. running_hash.update(newdata)
  97. if eof and running_hash.digest() != expected_hash:
  98. raise WheelError(f"Hash mismatch for file '{ef_name}'")
  99. ef_name = (
  100. name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info
  101. )
  102. if (
  103. mode == "r"
  104. and not ef_name.endswith("/")
  105. and ef_name not in self._file_hashes
  106. ):
  107. raise WheelError(f"No hash found for file '{ef_name}'")
  108. ef = ZipFile.open(self, name_or_info, mode, pwd)
  109. if mode == "r" and not ef_name.endswith("/"):
  110. algorithm, expected_hash = self._file_hashes[ef_name]
  111. if expected_hash is not None:
  112. # Monkey patch the _update_crc method to also check for the hash from
  113. # RECORD
  114. running_hash = hashlib.new(algorithm)
  115. update_crc_orig, ef._update_crc = ef._update_crc, _update_crc
  116. return ef
  117. def write_files(self, base_dir: str):
  118. log.info(f"creating '{self.filename}' and adding '{base_dir}' to it")
  119. deferred: list[tuple[str, str]] = []
  120. for root, dirnames, filenames in os.walk(base_dir):
  121. # Sort the directory names so that `os.walk` will walk them in a
  122. # defined order on the next iteration.
  123. dirnames.sort()
  124. for name in sorted(filenames):
  125. path = os.path.normpath(os.path.join(root, name))
  126. if os.path.isfile(path):
  127. arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/")
  128. if arcname == self.record_path:
  129. pass
  130. elif root.endswith(".dist-info"):
  131. deferred.append((path, arcname))
  132. else:
  133. self.write(path, arcname)
  134. deferred.sort()
  135. for path, arcname in deferred:
  136. self.write(path, arcname)
  137. def write(
  138. self,
  139. filename: str,
  140. arcname: str | None = None,
  141. compress_type: int | None = None,
  142. ) -> None:
  143. with open(filename, "rb") as f:
  144. st = os.fstat(f.fileno())
  145. data = f.read()
  146. zinfo = ZipInfo(
  147. arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime)
  148. )
  149. zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16
  150. zinfo.compress_type = compress_type or self.compression
  151. self.writestr(zinfo, data, compress_type)
  152. def writestr(
  153. self,
  154. zinfo_or_arcname: str | ZipInfo,
  155. data: SizedBuffer | str,
  156. compress_type: int | None = None,
  157. ):
  158. if isinstance(zinfo_or_arcname, str):
  159. zinfo_or_arcname = ZipInfo(
  160. zinfo_or_arcname, date_time=get_zipinfo_datetime()
  161. )
  162. zinfo_or_arcname.compress_type = self.compression
  163. zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16
  164. if isinstance(data, str):
  165. data = data.encode("utf-8")
  166. ZipFile.writestr(self, zinfo_or_arcname, data, compress_type)
  167. fname = (
  168. zinfo_or_arcname.filename
  169. if isinstance(zinfo_or_arcname, ZipInfo)
  170. else zinfo_or_arcname
  171. )
  172. log.info(f"adding '{fname}'")
  173. if fname != self.record_path:
  174. hash_ = self._default_algorithm(data)
  175. self._file_hashes[fname] = (
  176. hash_.name,
  177. urlsafe_b64encode(hash_.digest()).decode("ascii"),
  178. )
  179. self._file_sizes[fname] = len(data)
  180. def close(self):
  181. # Write RECORD
  182. if self.fp is not None and self.mode == "w" and self._file_hashes:
  183. data = StringIO()
  184. writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n")
  185. writer.writerows(
  186. (
  187. (fname, algorithm + "=" + hash_, self._file_sizes[fname])
  188. for fname, (algorithm, hash_) in self._file_hashes.items()
  189. )
  190. )
  191. writer.writerow((format(self.record_path), "", ""))
  192. self.writestr(self.record_path, data.getvalue())
  193. ZipFile.close(self)