link.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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.deprecation import deprecated
  21. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  22. from pip._internal.utils.hashes import Hashes
  23. from pip._internal.utils.misc import (
  24. pairwise,
  25. redact_auth_from_url,
  26. split_auth_from_netloc,
  27. splitext,
  28. )
  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_url_fragment_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.name in _SUPPORTED_HASHES
  58. @classmethod
  59. @functools.lru_cache(maxsize=None)
  60. def find_hash_url_fragment(cls, url: str) -> Optional["LinkHash"]:
  61. """Search a string for a checksum algorithm name and encoded output value."""
  62. match = cls._hash_url_fragment_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_dict(self) -> Dict[str, str]:
  68. return {self.name: self.value}
  69. def as_hashes(self) -> Hashes:
  70. """Return a Hashes instance which checks only for the current hash."""
  71. return Hashes({self.name: [self.value]})
  72. def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
  73. """
  74. Return True if the current hash is allowed by `hashes`.
  75. """
  76. if hashes is None:
  77. return False
  78. return hashes.is_hash_allowed(self.name, hex_digest=self.value)
  79. @dataclass(frozen=True)
  80. class MetadataFile:
  81. """Information about a core metadata file associated with a distribution."""
  82. hashes: Optional[Dict[str, str]]
  83. def __post_init__(self) -> None:
  84. if self.hashes is not None:
  85. assert all(name in _SUPPORTED_HASHES for name in self.hashes)
  86. def supported_hashes(hashes: Optional[Dict[str, str]]) -> Optional[Dict[str, str]]:
  87. # Remove any unsupported hash types from the mapping. If this leaves no
  88. # supported hashes, return None
  89. if hashes is None:
  90. return None
  91. hashes = {n: v for n, v in hashes.items() if n in _SUPPORTED_HASHES}
  92. if not hashes:
  93. return None
  94. return hashes
  95. def _clean_url_path_part(part: str) -> str:
  96. """
  97. Clean a "part" of a URL path (i.e. after splitting on "@" characters).
  98. """
  99. # We unquote prior to quoting to make sure nothing is double quoted.
  100. return urllib.parse.quote(urllib.parse.unquote(part))
  101. def _clean_file_url_path(part: str) -> str:
  102. """
  103. Clean the first part of a URL path that corresponds to a local
  104. filesystem path (i.e. the first part after splitting on "@" characters).
  105. """
  106. # We unquote prior to quoting to make sure nothing is double quoted.
  107. # Also, on Windows the path part might contain a drive letter which
  108. # should not be quoted. On Linux where drive letters do not
  109. # exist, the colon should be quoted. We rely on urllib.request
  110. # to do the right thing here.
  111. return urllib.request.pathname2url(urllib.request.url2pathname(part))
  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. return urllib.parse.urlunsplit(result._replace(path=path))
  144. def _absolute_link_url(base_url: str, url: str) -> str:
  145. """
  146. A faster implementation of urllib.parse.urljoin with a shortcut
  147. for absolute http/https URLs.
  148. """
  149. if url.startswith(("https://", "http://")):
  150. return url
  151. else:
  152. return urllib.parse.urljoin(base_url, url)
  153. @functools.total_ordering
  154. class Link:
  155. """Represents a parsed link from a Package Index's simple URL"""
  156. __slots__ = [
  157. "_parsed_url",
  158. "_url",
  159. "_path",
  160. "_hashes",
  161. "comes_from",
  162. "requires_python",
  163. "yanked_reason",
  164. "metadata_file_data",
  165. "cache_link_parsing",
  166. "egg_fragment",
  167. ]
  168. def __init__(
  169. self,
  170. url: str,
  171. comes_from: Optional[Union[str, "IndexContent"]] = None,
  172. requires_python: Optional[str] = None,
  173. yanked_reason: Optional[str] = None,
  174. metadata_file_data: Optional[MetadataFile] = None,
  175. cache_link_parsing: bool = True,
  176. hashes: Optional[Mapping[str, str]] = None,
  177. ) -> None:
  178. """
  179. :param url: url of the resource pointed to (href of the link)
  180. :param comes_from: instance of IndexContent where the link was found,
  181. or string.
  182. :param requires_python: String containing the `Requires-Python`
  183. metadata field, specified in PEP 345. This may be specified by
  184. a data-requires-python attribute in the HTML link tag, as
  185. described in PEP 503.
  186. :param yanked_reason: the reason the file has been yanked, if the
  187. file has been yanked, or None if the file hasn't been yanked.
  188. This is the value of the "data-yanked" attribute, if present, in
  189. a simple repository HTML link. If the file has been yanked but
  190. no reason was provided, this should be the empty string. See
  191. PEP 592 for more information and the specification.
  192. :param metadata_file_data: the metadata attached to the file, or None if
  193. no such metadata is provided. This argument, if not None, indicates
  194. that a separate metadata file exists, and also optionally supplies
  195. hashes for that file.
  196. :param cache_link_parsing: A flag that is used elsewhere to determine
  197. whether resources retrieved from this link should be cached. PyPI
  198. URLs should generally have this set to False, for example.
  199. :param hashes: A mapping of hash names to digests to allow us to
  200. determine the validity of a download.
  201. """
  202. # The comes_from, requires_python, and metadata_file_data arguments are
  203. # only used by classmethods of this class, and are not used in client
  204. # code directly.
  205. # url can be a UNC windows share
  206. if url.startswith("\\\\"):
  207. url = path_to_url(url)
  208. self._parsed_url = urllib.parse.urlsplit(url)
  209. # Store the url as a private attribute to prevent accidentally
  210. # trying to set a new value.
  211. self._url = url
  212. # The .path property is hot, so calculate its value ahead of time.
  213. self._path = urllib.parse.unquote(self._parsed_url.path)
  214. link_hash = LinkHash.find_hash_url_fragment(url)
  215. hashes_from_link = {} if link_hash is None else link_hash.as_dict()
  216. if hashes is None:
  217. self._hashes = hashes_from_link
  218. else:
  219. self._hashes = {**hashes, **hashes_from_link}
  220. self.comes_from = comes_from
  221. self.requires_python = requires_python if requires_python else None
  222. self.yanked_reason = yanked_reason
  223. self.metadata_file_data = metadata_file_data
  224. self.cache_link_parsing = cache_link_parsing
  225. self.egg_fragment = self._egg_fragment()
  226. @classmethod
  227. def from_json(
  228. cls,
  229. file_data: Dict[str, Any],
  230. page_url: str,
  231. ) -> Optional["Link"]:
  232. """
  233. Convert an pypi json document from a simple repository page into a Link.
  234. """
  235. file_url = file_data.get("url")
  236. if file_url is None:
  237. return None
  238. url = _ensure_quoted_url(_absolute_link_url(page_url, file_url))
  239. pyrequire = file_data.get("requires-python")
  240. yanked_reason = file_data.get("yanked")
  241. hashes = file_data.get("hashes", {})
  242. # PEP 714: Indexes must use the name core-metadata, but
  243. # clients should support the old name as a fallback for compatibility.
  244. metadata_info = file_data.get("core-metadata")
  245. if metadata_info is None:
  246. metadata_info = file_data.get("dist-info-metadata")
  247. # The metadata info value may be a boolean, or a dict of hashes.
  248. if isinstance(metadata_info, dict):
  249. # The file exists, and hashes have been supplied
  250. metadata_file_data = MetadataFile(supported_hashes(metadata_info))
  251. elif metadata_info:
  252. # The file exists, but there are no hashes
  253. metadata_file_data = MetadataFile(None)
  254. else:
  255. # False or not present: the file does not exist
  256. metadata_file_data = None
  257. # The Link.yanked_reason expects an empty string instead of a boolean.
  258. if yanked_reason and not isinstance(yanked_reason, str):
  259. yanked_reason = ""
  260. # The Link.yanked_reason expects None instead of False.
  261. elif not yanked_reason:
  262. yanked_reason = None
  263. return cls(
  264. url,
  265. comes_from=page_url,
  266. requires_python=pyrequire,
  267. yanked_reason=yanked_reason,
  268. hashes=hashes,
  269. metadata_file_data=metadata_file_data,
  270. )
  271. @classmethod
  272. def from_element(
  273. cls,
  274. anchor_attribs: Dict[str, Optional[str]],
  275. page_url: str,
  276. base_url: str,
  277. ) -> Optional["Link"]:
  278. """
  279. Convert an anchor element's attributes in a simple repository page to a Link.
  280. """
  281. href = anchor_attribs.get("href")
  282. if not href:
  283. return None
  284. url = _ensure_quoted_url(_absolute_link_url(base_url, href))
  285. pyrequire = anchor_attribs.get("data-requires-python")
  286. yanked_reason = anchor_attribs.get("data-yanked")
  287. # PEP 714: Indexes must use the name data-core-metadata, but
  288. # clients should support the old name as a fallback for compatibility.
  289. metadata_info = anchor_attribs.get("data-core-metadata")
  290. if metadata_info is None:
  291. metadata_info = anchor_attribs.get("data-dist-info-metadata")
  292. # The metadata info value may be the string "true", or a string of
  293. # the form "hashname=hashval"
  294. if metadata_info == "true":
  295. # The file exists, but there are no hashes
  296. metadata_file_data = MetadataFile(None)
  297. elif metadata_info is None:
  298. # The file does not exist
  299. metadata_file_data = None
  300. else:
  301. # The file exists, and hashes have been supplied
  302. hashname, sep, hashval = metadata_info.partition("=")
  303. if sep == "=":
  304. metadata_file_data = MetadataFile(supported_hashes({hashname: hashval}))
  305. else:
  306. # Error - data is wrong. Treat as no hashes supplied.
  307. logger.debug(
  308. "Index returned invalid data-dist-info-metadata value: %s",
  309. metadata_info,
  310. )
  311. metadata_file_data = MetadataFile(None)
  312. return cls(
  313. url,
  314. comes_from=page_url,
  315. requires_python=pyrequire,
  316. yanked_reason=yanked_reason,
  317. metadata_file_data=metadata_file_data,
  318. )
  319. def __str__(self) -> str:
  320. if self.requires_python:
  321. rp = f" (requires-python:{self.requires_python})"
  322. else:
  323. rp = ""
  324. if self.comes_from:
  325. return f"{redact_auth_from_url(self._url)} (from {self.comes_from}){rp}"
  326. else:
  327. return redact_auth_from_url(str(self._url))
  328. def __repr__(self) -> str:
  329. return f"<Link {self}>"
  330. def __hash__(self) -> int:
  331. return hash(self.url)
  332. def __eq__(self, other: Any) -> bool:
  333. if not isinstance(other, Link):
  334. return NotImplemented
  335. return self.url == other.url
  336. def __lt__(self, other: Any) -> bool:
  337. if not isinstance(other, Link):
  338. return NotImplemented
  339. return self.url < other.url
  340. @property
  341. def url(self) -> str:
  342. return self._url
  343. @property
  344. def filename(self) -> str:
  345. path = self.path.rstrip("/")
  346. name = posixpath.basename(path)
  347. if not name:
  348. # Make sure we don't leak auth information if the netloc
  349. # includes a username and password.
  350. netloc, user_pass = split_auth_from_netloc(self.netloc)
  351. return netloc
  352. name = urllib.parse.unquote(name)
  353. assert name, f"URL {self._url!r} produced no filename"
  354. return name
  355. @property
  356. def file_path(self) -> str:
  357. return url_to_path(self.url)
  358. @property
  359. def scheme(self) -> str:
  360. return self._parsed_url.scheme
  361. @property
  362. def netloc(self) -> str:
  363. """
  364. This can contain auth information.
  365. """
  366. return self._parsed_url.netloc
  367. @property
  368. def path(self) -> str:
  369. return self._path
  370. def splitext(self) -> Tuple[str, str]:
  371. return splitext(posixpath.basename(self.path.rstrip("/")))
  372. @property
  373. def ext(self) -> str:
  374. return self.splitext()[1]
  375. @property
  376. def url_without_fragment(self) -> str:
  377. scheme, netloc, path, query, fragment = self._parsed_url
  378. return urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
  379. _egg_fragment_re = re.compile(r"[#&]egg=([^&]*)")
  380. # Per PEP 508.
  381. _project_name_re = re.compile(
  382. r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
  383. )
  384. def _egg_fragment(self) -> Optional[str]:
  385. match = self._egg_fragment_re.search(self._url)
  386. if not match:
  387. return None
  388. # An egg fragment looks like a PEP 508 project name, along with
  389. # an optional extras specifier. Anything else is invalid.
  390. project_name = match.group(1)
  391. if not self._project_name_re.match(project_name):
  392. deprecated(
  393. reason=f"{self} contains an egg fragment with a non-PEP 508 name.",
  394. replacement="to use the req @ url syntax, and remove the egg fragment",
  395. gone_in="25.1",
  396. issue=13157,
  397. )
  398. return project_name
  399. _subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)")
  400. @property
  401. def subdirectory_fragment(self) -> Optional[str]:
  402. match = self._subdirectory_fragment_re.search(self._url)
  403. if not match:
  404. return None
  405. return match.group(1)
  406. def metadata_link(self) -> Optional["Link"]:
  407. """Return a link to the associated core metadata file (if any)."""
  408. if self.metadata_file_data is None:
  409. return None
  410. metadata_url = f"{self.url_without_fragment}.metadata"
  411. if self.metadata_file_data.hashes is None:
  412. return Link(metadata_url)
  413. return Link(metadata_url, hashes=self.metadata_file_data.hashes)
  414. def as_hashes(self) -> Hashes:
  415. return Hashes({k: [v] for k, v in self._hashes.items()})
  416. @property
  417. def hash(self) -> Optional[str]:
  418. return next(iter(self._hashes.values()), None)
  419. @property
  420. def hash_name(self) -> Optional[str]:
  421. return next(iter(self._hashes), None)
  422. @property
  423. def show_url(self) -> str:
  424. return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0])
  425. @property
  426. def is_file(self) -> bool:
  427. return self.scheme == "file"
  428. def is_existing_dir(self) -> bool:
  429. return self.is_file and os.path.isdir(self.file_path)
  430. @property
  431. def is_wheel(self) -> bool:
  432. return self.ext == WHEEL_EXTENSION
  433. @property
  434. def is_vcs(self) -> bool:
  435. from pip._internal.vcs import vcs
  436. return self.scheme in vcs.all_schemes
  437. @property
  438. def is_yanked(self) -> bool:
  439. return self.yanked_reason is not None
  440. @property
  441. def has_hash(self) -> bool:
  442. return bool(self._hashes)
  443. def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:
  444. """
  445. Return True if the link has a hash and it is allowed by `hashes`.
  446. """
  447. if hashes is None:
  448. return False
  449. return any(hashes.is_hash_allowed(k, v) for k, v in self._hashes.items())
  450. class _CleanResult(NamedTuple):
  451. """Convert link for equivalency check.
  452. This is used in the resolver to check whether two URL-specified requirements
  453. likely point to the same distribution and can be considered equivalent. This
  454. equivalency logic avoids comparing URLs literally, which can be too strict
  455. (e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users.
  456. Currently this does three things:
  457. 1. Drop the basic auth part. This is technically wrong since a server can
  458. serve different content based on auth, but if it does that, it is even
  459. impossible to guarantee two URLs without auth are equivalent, since
  460. the user can input different auth information when prompted. So the
  461. practical solution is to assume the auth doesn't affect the response.
  462. 2. Parse the query to avoid the ordering issue. Note that ordering under the
  463. same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are
  464. still considered different.
  465. 3. Explicitly drop most of the fragment part, except ``subdirectory=`` and
  466. hash values, since it should have no impact the downloaded content. Note
  467. that this drops the "egg=" part historically used to denote the requested
  468. project (and extras), which is wrong in the strictest sense, but too many
  469. people are supplying it inconsistently to cause superfluous resolution
  470. conflicts, so we choose to also ignore them.
  471. """
  472. parsed: urllib.parse.SplitResult
  473. query: Dict[str, List[str]]
  474. subdirectory: str
  475. hashes: Dict[str, str]
  476. def _clean_link(link: Link) -> _CleanResult:
  477. parsed = link._parsed_url
  478. netloc = parsed.netloc.rsplit("@", 1)[-1]
  479. # According to RFC 8089, an empty host in file: means localhost.
  480. if parsed.scheme == "file" and not netloc:
  481. netloc = "localhost"
  482. fragment = urllib.parse.parse_qs(parsed.fragment)
  483. if "egg" in fragment:
  484. logger.debug("Ignoring egg= fragment in %s", link)
  485. try:
  486. # If there are multiple subdirectory values, use the first one.
  487. # This matches the behavior of Link.subdirectory_fragment.
  488. subdirectory = fragment["subdirectory"][0]
  489. except (IndexError, KeyError):
  490. subdirectory = ""
  491. # If there are multiple hash values under the same algorithm, use the
  492. # first one. This matches the behavior of Link.hash_value.
  493. hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}
  494. return _CleanResult(
  495. parsed=parsed._replace(netloc=netloc, query="", fragment=""),
  496. query=urllib.parse.parse_qs(parsed.query),
  497. subdirectory=subdirectory,
  498. hashes=hashes,
  499. )
  500. @functools.lru_cache(maxsize=None)
  501. def links_equivalent(link1: Link, link2: Link) -> bool:
  502. return _clean_link(link1) == _clean_link(link2)