link.py 21 KB

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