wheelfile.py 7.5 KB

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