unpacking.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """Utilities related archives.
  2. """
  3. import logging
  4. import os
  5. import shutil
  6. import stat
  7. import tarfile
  8. import zipfile
  9. from typing import Iterable, List, Optional
  10. from zipfile import ZipInfo
  11. from pip._internal.exceptions import InstallationError
  12. from pip._internal.utils.filetypes import (
  13. BZ2_EXTENSIONS,
  14. TAR_EXTENSIONS,
  15. XZ_EXTENSIONS,
  16. ZIP_EXTENSIONS,
  17. )
  18. from pip._internal.utils.misc import ensure_dir
  19. logger = logging.getLogger(__name__)
  20. SUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS
  21. try:
  22. import bz2 # noqa
  23. SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS
  24. except ImportError:
  25. logger.debug("bz2 module is not available")
  26. try:
  27. # Only for Python 3.3+
  28. import lzma # noqa
  29. SUPPORTED_EXTENSIONS += XZ_EXTENSIONS
  30. except ImportError:
  31. logger.debug("lzma module is not available")
  32. def current_umask() -> int:
  33. """Get the current umask which involves having to set it temporarily."""
  34. mask = os.umask(0)
  35. os.umask(mask)
  36. return mask
  37. def split_leading_dir(path: str) -> List[str]:
  38. path = path.lstrip("/").lstrip("\\")
  39. if "/" in path and (
  40. ("\\" in path and path.find("/") < path.find("\\")) or "\\" not in path
  41. ):
  42. return path.split("/", 1)
  43. elif "\\" in path:
  44. return path.split("\\", 1)
  45. else:
  46. return [path, ""]
  47. def has_leading_dir(paths: Iterable[str]) -> bool:
  48. """Returns true if all the paths have the same leading path name
  49. (i.e., everything is in one subdirectory in an archive)"""
  50. common_prefix = None
  51. for path in paths:
  52. prefix, rest = split_leading_dir(path)
  53. if not prefix:
  54. return False
  55. elif common_prefix is None:
  56. common_prefix = prefix
  57. elif prefix != common_prefix:
  58. return False
  59. return True
  60. def is_within_directory(directory: str, target: str) -> bool:
  61. """
  62. Return true if the absolute path of target is within the directory
  63. """
  64. abs_directory = os.path.abspath(directory)
  65. abs_target = os.path.abspath(target)
  66. prefix = os.path.commonprefix([abs_directory, abs_target])
  67. return prefix == abs_directory
  68. def set_extracted_file_to_default_mode_plus_executable(path: str) -> None:
  69. """
  70. Make file present at path have execute for user/group/world
  71. (chmod +x) is no-op on windows per python docs
  72. """
  73. os.chmod(path, (0o777 & ~current_umask() | 0o111))
  74. def zip_item_is_executable(info: ZipInfo) -> bool:
  75. mode = info.external_attr >> 16
  76. # if mode and regular file and any execute permissions for
  77. # user/group/world?
  78. return bool(mode and stat.S_ISREG(mode) and mode & 0o111)
  79. def unzip_file(filename: str, location: str, flatten: bool = True) -> None:
  80. """
  81. Unzip the file (with path `filename`) to the destination `location`. All
  82. files are written based on system defaults and umask (i.e. permissions are
  83. not preserved), except that regular file members with any execute
  84. permissions (user, group, or world) have "chmod +x" applied after being
  85. written. Note that for windows, any execute changes using os.chmod are
  86. no-ops per the python docs.
  87. """
  88. ensure_dir(location)
  89. zipfp = open(filename, "rb")
  90. try:
  91. zip = zipfile.ZipFile(zipfp, allowZip64=True)
  92. leading = has_leading_dir(zip.namelist()) and flatten
  93. for info in zip.infolist():
  94. name = info.filename
  95. fn = name
  96. if leading:
  97. fn = split_leading_dir(name)[1]
  98. fn = os.path.join(location, fn)
  99. dir = os.path.dirname(fn)
  100. if not is_within_directory(location, fn):
  101. message = (
  102. "The zip file ({}) has a file ({}) trying to install "
  103. "outside target directory ({})"
  104. )
  105. raise InstallationError(message.format(filename, fn, location))
  106. if fn.endswith("/") or fn.endswith("\\"):
  107. # A directory
  108. ensure_dir(fn)
  109. else:
  110. ensure_dir(dir)
  111. # Don't use read() to avoid allocating an arbitrarily large
  112. # chunk of memory for the file's content
  113. fp = zip.open(name)
  114. try:
  115. with open(fn, "wb") as destfp:
  116. shutil.copyfileobj(fp, destfp)
  117. finally:
  118. fp.close()
  119. if zip_item_is_executable(info):
  120. set_extracted_file_to_default_mode_plus_executable(fn)
  121. finally:
  122. zipfp.close()
  123. def untar_file(filename: str, location: str) -> None:
  124. """
  125. Untar the file (with path `filename`) to the destination `location`.
  126. All files are written based on system defaults and umask (i.e. permissions
  127. are not preserved), except that regular file members with any execute
  128. permissions (user, group, or world) have "chmod +x" applied after being
  129. written. Note that for windows, any execute changes using os.chmod are
  130. no-ops per the python docs.
  131. """
  132. ensure_dir(location)
  133. if filename.lower().endswith(".gz") or filename.lower().endswith(".tgz"):
  134. mode = "r:gz"
  135. elif filename.lower().endswith(BZ2_EXTENSIONS):
  136. mode = "r:bz2"
  137. elif filename.lower().endswith(XZ_EXTENSIONS):
  138. mode = "r:xz"
  139. elif filename.lower().endswith(".tar"):
  140. mode = "r"
  141. else:
  142. logger.warning(
  143. "Cannot determine compression type for file %s",
  144. filename,
  145. )
  146. mode = "r:*"
  147. tar = tarfile.open(filename, mode, encoding="utf-8")
  148. try:
  149. leading = has_leading_dir([member.name for member in tar.getmembers()])
  150. for member in tar.getmembers():
  151. fn = member.name
  152. if leading:
  153. fn = split_leading_dir(fn)[1]
  154. path = os.path.join(location, fn)
  155. if not is_within_directory(location, path):
  156. message = (
  157. "The tar file ({}) has a file ({}) trying to install "
  158. "outside target directory ({})"
  159. )
  160. raise InstallationError(message.format(filename, path, location))
  161. if member.isdir():
  162. ensure_dir(path)
  163. elif member.issym():
  164. try:
  165. # https://github.com/python/typeshed/issues/2673
  166. tar._extract_member(member, path) # type: ignore
  167. except Exception as exc:
  168. # Some corrupt tar files seem to produce this
  169. # (specifically bad symlinks)
  170. logger.warning(
  171. "In the tar file %s the member %s is invalid: %s",
  172. filename,
  173. member.name,
  174. exc,
  175. )
  176. continue
  177. else:
  178. try:
  179. fp = tar.extractfile(member)
  180. except (KeyError, AttributeError) as exc:
  181. # Some corrupt tar files seem to produce this
  182. # (specifically bad symlinks)
  183. logger.warning(
  184. "In the tar file %s the member %s is invalid: %s",
  185. filename,
  186. member.name,
  187. exc,
  188. )
  189. continue
  190. ensure_dir(os.path.dirname(path))
  191. assert fp is not None
  192. with open(path, "wb") as destfp:
  193. shutil.copyfileobj(fp, destfp)
  194. fp.close()
  195. # Update the timestamp (useful for cython compiled files)
  196. tar.utime(member, path)
  197. # member have any execute permissions for user/group/world?
  198. if member.mode & 0o111:
  199. set_extracted_file_to_default_mode_plus_executable(path)
  200. finally:
  201. tar.close()
  202. def unpack_file(
  203. filename: str,
  204. location: str,
  205. content_type: Optional[str] = None,
  206. ) -> None:
  207. filename = os.path.realpath(filename)
  208. if (
  209. content_type == "application/zip"
  210. or filename.lower().endswith(ZIP_EXTENSIONS)
  211. or zipfile.is_zipfile(filename)
  212. ):
  213. unzip_file(filename, location, flatten=not filename.endswith(".whl"))
  214. elif (
  215. content_type == "application/x-gzip"
  216. or tarfile.is_tarfile(filename)
  217. or filename.lower().endswith(TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS)
  218. ):
  219. untar_file(filename, location)
  220. else:
  221. # FIXME: handle?
  222. # FIXME: magic signatures?
  223. logger.critical(
  224. "Cannot unpack file %s (downloaded from %s, content-type: %s); "
  225. "cannot detect archive format",
  226. filename,
  227. location,
  228. content_type,
  229. )
  230. raise InstallationError(f"Cannot determine archive format of {location}")