link.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import functools
  2. import itertools
  3. import logging
  4. import os
  5. import posixpath
  6. import re
  7. import urllib.parse
  8. from dataclasses import dataclass
  9. from typing import (
  10. TYPE_CHECKING,
  11. Any,
  12. Dict,
  13. List,
  14. Mapping,
  15. NamedTuple,
  16. Optional,
  17. Tuple,
  18. Union,
  19. )
  20. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  21. from pip._internal.utils.hashes import Hashes
  22. from pip._internal.utils.misc import (
  23. pairwise,
  24. redact_auth_from_url,
  25. split_auth_from_netloc,
  26. splitext,
  27. )
  28. from pip._internal.utils.models import KeyBasedCompareMixin
  29. from pip._internal.utils.urls import path_to_url, url_to_path
  30. if TYPE_CHECKING:
  31. from pip._internal.index.collector import IndexContent
  32. logger = logging.getLogger(__name__)
  33. # Order matters, earlier hashes have a precedence over later hashes for what
  34. # we will pick to use.
  35. _SUPPORTED_HASHES = ("sha512", "sha384", "sha256", "sha224", "sha1", "md5")
  36. @dataclass(frozen=True)
  37. class LinkHash:
  38. """Links to content may have embedded hash values. This class parses those.
  39. `name` must be any member of `_SUPPORTED_HASHES`.
  40. This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to
  41. be JSON-serializable to conform to PEP 610, this class contains the logic for
  42. parsing a hash name and value for correctness, and then checking whether that hash
  43. conforms to a schema with `.is_hash_allowed()`."""
  44. name: str
  45. value: str
  46. _hash_re = re.compile(
  47. # NB: we do not validate that the second group (.*) is a valid hex
  48. # digest. Instead, we simply keep that string in this class, and then check it
  49. # against Hashes when hash-checking is needed. This is easier to debug than
  50. # proactively discarding an invalid hex digest, as we handle incorrect hashes
  51. # and malformed hashes in the same place.
  52. r"({choices})=(.*)".format(
  53. choices="|".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES)
  54. ),
  55. )
  56. def __post_init__(self) -> None:
  57. assert self._hash_re.match(f"{self.name}={self.value}")
  58. @classmethod
  59. @functools.lru_cache(maxsize=None)
  60. def split_hash_name_and_value(cls, url: str) -> Optional["LinkHash"]:
  61. """Search a string for a checksum algorithm name and encoded output value."""
  62. match = cls._hash_re.search(url)
  63. if match is None:
  64. return None
  65. name, value = match.groups()
  66. return cls(name=name, value=value)
  67. def as_hashes(self) -> Hashes:
  68. """Return a Hashes instance which checks only for the current hash."""
  69. return Hashes({self.name: [self.value]})
  70. def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
  71. """
  72. Return True if the current hash is allowed by `hashes`.
  73. """
  74. if hashes is None:
  75. return False
  76. return hashes.is_hash_allowed(self.name, hex_digest=self.value)
  77. def _clean_url_path_part(part: str) -> str:
  78. """
  79. Clean a "part" of a URL path (i.e. after splitting on "@" characters).
  80. """
  81. # We unquote prior to quoting to make sure nothing is double quoted.
  82. return urllib.parse.quote(urllib.parse.unquote(part))
  83. def _clean_file_url_path(part: str) -> str:
  84. """
  85. Clean the first part of a URL path that corresponds to a local
  86. filesystem path (i.e. the first part after splitting on "@" characters).
  87. """
  88. # We unquote prior to quoting to make sure nothing is double quoted.
  89. # Also, on Windows the path part might contain a drive letter which
  90. # should not be quoted. On Linux where drive letters do not
  91. # exist, the colon should be quoted. We rely on urllib.request
  92. # to do the right thing here.
  93. return urllib.request.pathname2url(urllib.request.url2pathname(part))
  94. # percent-encoded: /
  95. _reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE)
  96. def _clean_url_path(path: str, is_local_path: bool) -> str:
  97. """
  98. Clean the path portion of a URL.
  99. """
  100. if is_local_path:
  101. clean_func = _clean_file_url_path
  102. else:
  103. clean_func = _clean_url_path_part
  104. # Split on the reserved characters prior to cleaning so that
  105. # revision strings in VCS URLs are properly preserved.
  106. parts = _reserved_chars_re.split(path)
  107. cleaned_parts = []
  108. for to_clean, reserved in pairwise(itertools.chain(parts, [""])):
  109. cleaned_parts.append(clean_func(to_clean))
  110. # Normalize %xx escapes (e.g. %2f -> %2F)
  111. cleaned_parts.append(reserved.upper())
  112. return "".join(cleaned_parts)
  113. def _ensure_quoted_url(url: str) -> str:
  114. """
  115. Make sure a link is fully quoted.
  116. For example, if ' ' occurs in the URL, it will be replaced with "%20",
  117. and without double-quoting other characters.
  118. """
  119. # Split the URL into parts according to the general structure
  120. # `scheme://netloc/path;parameters?query#fragment`.
  121. result = urllib.parse.urlparse(url)
  122. # If the netloc is empty, then the URL refers to a local filesystem path.
  123. is_local_path = not result.netloc
  124. path = _clean_url_path(result.path, is_local_path=is_local_path)
  125. return urllib.parse.urlunparse(result._replace(path=path))
  126. class Link(KeyBasedCompareMixin):
  127. """Represents a parsed link from a Package Index's simple URL"""
  128. __slots__ = [
  129. "_parsed_url",
  130. "_url",
  131. "_hashes",
  132. "comes_from",
  133. "requires_python",
  134. "yanked_reason",
  135. "dist_info_metadata",
  136. "link_hash",
  137. "cache_link_parsing",
  138. ]
  139. def __init__(
  140. self,
  141. url: str,
  142. comes_from: Optional[Union[str, "IndexContent"]] = None,
  143. requires_python: Optional[str] = None,
  144. yanked_reason: Optional[str] = None,
  145. dist_info_metadata: Optional[str] = None,
  146. link_hash: Optional[LinkHash] = None,
  147. cache_link_parsing: bool = True,
  148. hashes: Optional[Mapping[str, str]] = None,
  149. ) -> None:
  150. """
  151. :param url: url of the resource pointed to (href of the link)
  152. :param comes_from: instance of IndexContent where the link was found,
  153. or string.
  154. :param requires_python: String containing the `Requires-Python`
  155. metadata field, specified in PEP 345. This may be specified by
  156. a data-requires-python attribute in the HTML link tag, as
  157. described in PEP 503.
  158. :param yanked_reason: the reason the file has been yanked, if the
  159. file has been yanked, or None if the file hasn't been yanked.
  160. This is the value of the "data-yanked" attribute, if present, in
  161. a simple repository HTML link. If the file has been yanked but
  162. no reason was provided, this should be the empty string. See
  163. PEP 592 for more information and the specification.
  164. :param dist_info_metadata: the metadata attached to the file, or None if no such
  165. metadata is provided. This is the value of the "data-dist-info-metadata"
  166. attribute, if present, in a simple repository HTML link. This may be parsed
  167. into its own `Link` by `self.metadata_link()`. See PEP 658 for more
  168. information and the specification.
  169. :param link_hash: a checksum for the content the link points to. If not
  170. provided, this will be extracted from the link URL, if the URL has
  171. any checksum.
  172. :param cache_link_parsing: A flag that is used elsewhere to determine
  173. whether resources retrieved from this link
  174. should be cached. PyPI index urls should
  175. generally have this set to False, for
  176. example.
  177. :param hashes: A mapping of hash names to digests to allow us to
  178. determine the validity of a download.
  179. """
  180. # url can be a UNC windows share
  181. if url.startswith("\\\\"):
  182. url = path_to_url(url)
  183. self._parsed_url = urllib.parse.urlsplit(url)
  184. # Store the url as a private attribute to prevent accidentally
  185. # trying to set a new value.
  186. self._url = url
  187. self._hashes = hashes if hashes is not None else {}
  188. self.comes_from = comes_from
  189. self.requires_python = requires_python if requires_python else None
  190. self.yanked_reason = yanked_reason
  191. self.dist_info_metadata = dist_info_metadata
  192. self.link_hash = link_hash or LinkHash.split_hash_name_and_value(self._url)
  193. super().__init__(key=url, defining_class=Link)
  194. self.cache_link_parsing = cache_link_parsing
  195. @classmethod
  196. def from_json(
  197. cls,
  198. file_data: Dict[str, Any],
  199. page_url: str,
  200. ) -> Optional["Link"]:
  201. """
  202. Convert an pypi json document from a simple repository page into a Link.
  203. """
  204. file_url = file_data.get("url")
  205. if file_url is None:
  206. return None
  207. url = _ensure_quoted_url(urllib.parse.urljoin(page_url, file_url))
  208. pyrequire = file_data.get("requires-python")
  209. yanked_reason = file_data.get("yanked")
  210. dist_info_metadata = file_data.get("dist-info-metadata")
  211. hashes = file_data.get("hashes", {})
  212. # The Link.yanked_reason expects an empty string instead of a boolean.
  213. if yanked_reason and not isinstance(yanked_reason, str):
  214. yanked_reason = ""
  215. # The Link.yanked_reason expects None instead of False.
  216. elif not yanked_reason:
  217. yanked_reason = None
  218. return cls(
  219. url,
  220. comes_from=page_url,
  221. requires_python=pyrequire,
  222. yanked_reason=yanked_reason,
  223. hashes=hashes,
  224. dist_info_metadata=dist_info_metadata,
  225. )
  226. @classmethod
  227. def from_element(
  228. cls,
  229. anchor_attribs: Dict[str, Optional[str]],
  230. page_url: str,
  231. base_url: str,
  232. ) -> Optional["Link"]:
  233. """
  234. Convert an anchor element's attributes in a simple repository page to a Link.
  235. """
  236. href = anchor_attribs.get("href")
  237. if not href:
  238. return None
  239. url = _ensure_quoted_url(urllib.parse.urljoin(base_url, href))
  240. pyrequire = anchor_attribs.get("data-requires-python")
  241. yanked_reason = anchor_attribs.get("data-yanked")
  242. dist_info_metadata = anchor_attribs.get("data-dist-info-metadata")
  243. return cls(
  244. url,
  245. comes_from=page_url,
  246. requires_python=pyrequire,
  247. yanked_reason=yanked_reason,
  248. dist_info_metadata=dist_info_metadata,
  249. )
  250. def __str__(self) -> str:
  251. if self.requires_python:
  252. rp = f" (requires-python:{self.requires_python})"
  253. else:
  254. rp = ""
  255. if self.comes_from:
  256. return "{} (from {}){}".format(
  257. redact_auth_from_url(self._url), self.comes_from, rp
  258. )
  259. else:
  260. return redact_auth_from_url(str(self._url))
  261. def __repr__(self) -> str:
  262. return f"<Link {self}>"
  263. @property
  264. def url(self) -> str:
  265. return self._url
  266. @property
  267. def filename(self) -> str:
  268. path = self.path.rstrip("/")
  269. name = posixpath.basename(path)
  270. if not name:
  271. # Make sure we don't leak auth information if the netloc
  272. # includes a username and password.
  273. netloc, user_pass = split_auth_from_netloc(self.netloc)
  274. return netloc
  275. name = urllib.parse.unquote(name)
  276. assert name, f"URL {self._url!r} produced no filename"
  277. return name
  278. @property
  279. def file_path(self) -> str:
  280. return url_to_path(self.url)
  281. @property
  282. def scheme(self) -> str:
  283. return self._parsed_url.scheme
  284. @property
  285. def netloc(self) -> str:
  286. """
  287. This can contain auth information.
  288. """
  289. return self._parsed_url.netloc
  290. @property
  291. def path(self) -> str:
  292. return urllib.parse.unquote(self._parsed_url.path)
  293. def splitext(self) -> Tuple[str, str]:
  294. return splitext(posixpath.basename(self.path.rstrip("/")))
  295. @property
  296. def ext(self) -> str:
  297. return self.splitext()[1]
  298. @property
  299. def url_without_fragment(self) -> str:
  300. scheme, netloc, path, query, fragment = self._parsed_url
  301. return urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
  302. _egg_fragment_re = re.compile(r"[#&]egg=([^&]*)")
  303. @property
  304. def egg_fragment(self) -> Optional[str]:
  305. match = self._egg_fragment_re.search(self._url)
  306. if not match:
  307. return None
  308. return match.group(1)
  309. _subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)")
  310. @property
  311. def subdirectory_fragment(self) -> Optional[str]:
  312. match = self._subdirectory_fragment_re.search(self._url)
  313. if not match:
  314. return None
  315. return match.group(1)
  316. def metadata_link(self) -> Optional["Link"]:
  317. """Implementation of PEP 658 parsing."""
  318. # Note that Link.from_element() parsing the "data-dist-info-metadata" attribute
  319. # from an HTML anchor tag is typically how the Link.dist_info_metadata attribute
  320. # gets set.
  321. if self.dist_info_metadata is None:
  322. return None
  323. metadata_url = f"{self.url_without_fragment}.metadata"
  324. link_hash: Optional[LinkHash] = None
  325. # If data-dist-info-metadata="true" is set, then the metadata file exists,
  326. # but there is no information about its checksum or anything else.
  327. if self.dist_info_metadata != "true":
  328. link_hash = LinkHash.split_hash_name_and_value(self.dist_info_metadata)
  329. return Link(metadata_url, link_hash=link_hash)
  330. def as_hashes(self) -> Optional[Hashes]:
  331. if self.link_hash is not None:
  332. return self.link_hash.as_hashes()
  333. return None
  334. @property
  335. def hash(self) -> Optional[str]:
  336. if self.link_hash is not None:
  337. return self.link_hash.value
  338. return None
  339. @property
  340. def hash_name(self) -> Optional[str]:
  341. if self.link_hash is not None:
  342. return self.link_hash.name
  343. return None
  344. @property
  345. def show_url(self) -> str:
  346. return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0])
  347. @property
  348. def is_file(self) -> bool:
  349. return self.scheme == "file"
  350. def is_existing_dir(self) -> bool:
  351. return self.is_file and os.path.isdir(self.file_path)
  352. @property
  353. def is_wheel(self) -> bool:
  354. return self.ext == WHEEL_EXTENSION
  355. @property
  356. def is_vcs(self) -> bool:
  357. from pip._internal.vcs import vcs
  358. return self.scheme in vcs.all_schemes
  359. @property
  360. def is_yanked(self) -> bool:
  361. return self.yanked_reason is not None
  362. @property
  363. def has_hash(self) -> bool:
  364. return self.link_hash is not None
  365. def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
  366. """
  367. Return True if the link has a hash and it is allowed by `hashes`.
  368. """
  369. if self.link_hash is None:
  370. return False
  371. return self.link_hash.is_hash_allowed(hashes)
  372. class _CleanResult(NamedTuple):
  373. """Convert link for equivalency check.
  374. This is used in the resolver to check whether two URL-specified requirements
  375. likely point to the same distribution and can be considered equivalent. This
  376. equivalency logic avoids comparing URLs literally, which can be too strict
  377. (e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users.
  378. Currently this does three things:
  379. 1. Drop the basic auth part. This is technically wrong since a server can
  380. serve different content based on auth, but if it does that, it is even
  381. impossible to guarantee two URLs without auth are equivalent, since
  382. the user can input different auth information when prompted. So the
  383. practical solution is to assume the auth doesn't affect the response.
  384. 2. Parse the query to avoid the ordering issue. Note that ordering under the
  385. same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are
  386. still considered different.
  387. 3. Explicitly drop most of the fragment part, except ``subdirectory=`` and
  388. hash values, since it should have no impact the downloaded content. Note
  389. that this drops the "egg=" part historically used to denote the requested
  390. project (and extras), which is wrong in the strictest sense, but too many
  391. people are supplying it inconsistently to cause superfluous resolution
  392. conflicts, so we choose to also ignore them.
  393. """
  394. parsed: urllib.parse.SplitResult
  395. query: Dict[str, List[str]]
  396. subdirectory: str
  397. hashes: Dict[str, str]
  398. def _clean_link(link: Link) -> _CleanResult:
  399. parsed = link._parsed_url
  400. netloc = parsed.netloc.rsplit("@", 1)[-1]
  401. # According to RFC 8089, an empty host in file: means localhost.
  402. if parsed.scheme == "file" and not netloc:
  403. netloc = "localhost"
  404. fragment = urllib.parse.parse_qs(parsed.fragment)
  405. if "egg" in fragment:
  406. logger.debug("Ignoring egg= fragment in %s", link)
  407. try:
  408. # If there are multiple subdirectory values, use the first one.
  409. # This matches the behavior of Link.subdirectory_fragment.
  410. subdirectory = fragment["subdirectory"][0]
  411. except (IndexError, KeyError):
  412. subdirectory = ""
  413. # If there are multiple hash values under the same algorithm, use the
  414. # first one. This matches the behavior of Link.hash_value.
  415. hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}
  416. return _CleanResult(
  417. parsed=parsed._replace(netloc=netloc, query="", fragment=""),
  418. query=urllib.parse.parse_qs(parsed.query),
  419. subdirectory=subdirectory,
  420. hashes=hashes,
  421. )
  422. @functools.lru_cache(maxsize=None)
  423. def links_equivalent(link1: Link, link2: Link) -> bool:
  424. return _clean_link(link1) == _clean_link(link2)