link.py 18 KB

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