url.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. from __future__ import annotations
  2. import re
  3. import typing
  4. from functools import partial
  5. from urllib.parse import unquote as _unquote
  6. from ..exceptions import LocationParseError
  7. from .util import to_str
  8. # We only want to normalize urls with an HTTP(S) scheme.
  9. # urllib3 infers URLs without a scheme (None) to be http.
  10. _NORMALIZABLE_SCHEMES = ("http", "https", None)
  11. # Almost all of these patterns were derived from the
  12. # 'rfc3986' module: https://github.com/python-hyper/rfc3986
  13. _PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}")
  14. _HOST_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}|%")
  15. _SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)")
  16. _HOST_INVALID_CHAR_RE = re.compile(r"[\x00-\x20\x7f]")
  17. _URI_RE = re.compile(
  18. r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?"
  19. r"(?://([^\\/?#]*))?"
  20. r"([^?#]*)"
  21. r"(?:\?([^#]*))?"
  22. r"(?:#(.*))?$",
  23. re.UNICODE | re.DOTALL,
  24. )
  25. _IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
  26. _HEX_PAT = "[0-9A-Fa-f]{1,4}"
  27. _LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT)
  28. _subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT}
  29. _variations = [
  30. # 6( h16 ":" ) ls32
  31. "(?:%(hex)s:){6}%(ls32)s",
  32. # "::" 5( h16 ":" ) ls32
  33. "::(?:%(hex)s:){5}%(ls32)s",
  34. # [ h16 ] "::" 4( h16 ":" ) ls32
  35. "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s",
  36. # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
  37. "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s",
  38. # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
  39. "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s",
  40. # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
  41. "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s",
  42. # [ *4( h16 ":" ) h16 ] "::" ls32
  43. "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s",
  44. # [ *5( h16 ":" ) h16 ] "::" h16
  45. "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s",
  46. # [ *6( h16 ":" ) h16 ] "::"
  47. "(?:(?:%(hex)s:){0,6}%(hex)s)?::",
  48. ]
  49. _UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~"
  50. _IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")"
  51. _ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+"
  52. _IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]"
  53. _REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*"
  54. _TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$")
  55. _IPV4_RE = re.compile(
  56. r"^(?:0[xX][0-9a-fA-F]+|[0-9]+)(?:\.(?:0[xX][0-9a-fA-F]+|[0-9]+)){0,3}$"
  57. )
  58. _IPV6_RE = re.compile("^" + _IPV6_PAT + "$")
  59. _IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$")
  60. _BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$")
  61. _ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$")
  62. _HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % (
  63. _REG_NAME_PAT,
  64. _IPV4_PAT,
  65. _IPV6_ADDRZ_PAT,
  66. )
  67. _HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)
  68. _UNRESERVED_CHARS = set(
  69. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~"
  70. )
  71. _SUB_DELIM_CHARS = set("!$&'()*+,;=")
  72. _USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"}
  73. _PATH_CHARS = _USERINFO_CHARS | {"@", "/"}
  74. _QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"}
  75. class Url(
  76. typing.NamedTuple(
  77. "Url",
  78. [
  79. ("scheme", typing.Optional[str]),
  80. ("auth", typing.Optional[str]),
  81. ("host", typing.Optional[str]),
  82. ("port", typing.Optional[int]),
  83. ("path", typing.Optional[str]),
  84. ("query", typing.Optional[str]),
  85. ("fragment", typing.Optional[str]),
  86. ],
  87. )
  88. ):
  89. """
  90. Data structure for representing an HTTP URL. Used as a return value for
  91. :func:`parse_url`. Both the scheme and host are normalized as they are
  92. both case-insensitive according to RFC 3986.
  93. :param auth: User information as defined in RFC 3986 3.2.1. This
  94. component is kept percent-encoded. Use :attr:`auth_decoded` or
  95. :attr:`auth_decoded_joined` to get the decoded form.
  96. """
  97. def __new__( # type: ignore[no-untyped-def]
  98. cls,
  99. scheme: str | None = None,
  100. auth: str | None = None,
  101. host: str | None = None,
  102. port: int | None = None,
  103. path: str | None = None,
  104. query: str | None = None,
  105. fragment: str | None = None,
  106. ):
  107. if path and not path.startswith("/"):
  108. path = "/" + path
  109. if scheme is not None:
  110. scheme = scheme.lower()
  111. return super().__new__(cls, scheme, auth, host, port, path, query, fragment)
  112. @property
  113. def auth_decoded(self) -> tuple[None, None] | tuple[str, str | None]:
  114. """
  115. User information with %-escapes decoded as UTF-8, returned as a
  116. ``(username, password)`` tuple.
  117. Both values are ``None`` if ``auth`` is ``None``.
  118. ``password`` is ``None`` if not present in the auth component.
  119. """
  120. if self.auth is None:
  121. return None, None
  122. username, sep, password = self.auth.partition(":")
  123. return (
  124. _unquote(username, encoding="utf-8"),
  125. _unquote(password, encoding="utf-8") if sep else None,
  126. )
  127. @property
  128. def auth_decoded_joined(self) -> str | None:
  129. """
  130. User information with %-escapes decoded as UTF-8, as a string
  131. prepared for encoding into an 'authorization: basic ...' header.
  132. This property does not choose the encoding used for an
  133. 'authorization: basic ...' header. Use the ``basic_auth_encoding`` or
  134. ``proxy_basic_auth_encoding`` parameters of
  135. :func:`urllib3.util.make_headers` when converting the returned string
  136. into Basic authentication bytes.
  137. This is a convenience property that joins the username and
  138. password with a colon, if both are present.
  139. If only the username is present, a trailing colon is still
  140. appended.
  141. If ``auth`` is ``None``, this returns ``None``.
  142. """
  143. username, password = self.auth_decoded
  144. if username is None:
  145. return None
  146. return f"{username}:{password or ''}"
  147. @property
  148. def hostname(self) -> str | None:
  149. """For backwards-compatibility with urlparse. We're nice like that."""
  150. return self.host
  151. @property
  152. def request_uri(self) -> str:
  153. """Absolute path including the query string."""
  154. uri = self.path or "/"
  155. if self.query is not None:
  156. uri += "?" + self.query
  157. return uri
  158. @property
  159. def authority(self) -> str | None:
  160. """
  161. Authority component as defined in RFC 3986 3.2.
  162. This includes userinfo (auth), host and port.
  163. i.e.
  164. userinfo@host:port
  165. """
  166. userinfo = self.auth
  167. netloc = self.netloc
  168. if netloc is None or userinfo is None:
  169. return netloc
  170. else:
  171. return f"{userinfo}@{netloc}"
  172. @property
  173. def netloc(self) -> str | None:
  174. """
  175. Network location including host and port.
  176. If you need the equivalent of urllib.parse's ``netloc``,
  177. use the ``authority`` property instead.
  178. """
  179. if self.host is None:
  180. return None
  181. if self.port is not None:
  182. return f"{self.host}:{self.port}"
  183. return self.host
  184. @property
  185. def url(self) -> str:
  186. """
  187. Convert self into a url
  188. This function should more or less round-trip with :func:`.parse_url`. The
  189. returned url may not be exactly the same as the url inputted to
  190. :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
  191. with a blank port will have : removed).
  192. Example:
  193. .. code-block:: python
  194. import urllib3
  195. U = urllib3.util.parse_url("https://google.com/mail/")
  196. print(U.url)
  197. # "https://google.com/mail/"
  198. print( urllib3.util.Url("https", "username:password",
  199. "host.com", 80, "/path", "query", "fragment"
  200. ).url
  201. )
  202. # "https://username:password@host.com:80/path?query#fragment"
  203. """
  204. scheme, auth, host, port, path, query, fragment = self
  205. url = ""
  206. # We use "is not None" we want things to happen with empty strings (or 0 port)
  207. if scheme is not None:
  208. url += scheme + "://"
  209. if auth is not None:
  210. url += auth + "@"
  211. if host is not None:
  212. url += host
  213. if port is not None:
  214. url += ":" + str(port)
  215. if path is not None:
  216. url += path
  217. if query is not None:
  218. url += "?" + query
  219. if fragment is not None:
  220. url += "#" + fragment
  221. return url
  222. def __str__(self) -> str:
  223. return self.url
  224. @typing.overload
  225. def _encode_invalid_chars(
  226. component: str, allowed_chars: typing.Container[str]
  227. ) -> str: # Abstract
  228. ...
  229. @typing.overload
  230. def _encode_invalid_chars(
  231. component: None, allowed_chars: typing.Container[str]
  232. ) -> None: # Abstract
  233. ...
  234. def _encode_invalid_chars(
  235. component: str | None, allowed_chars: typing.Container[str]
  236. ) -> str | None:
  237. """Percent-encodes a URI component without reapplying
  238. onto an already percent-encoded component.
  239. """
  240. if component is None:
  241. return component
  242. component = to_str(component)
  243. # Fast path: an ASCII component that consists only of allowed characters
  244. # and contains no '%' needs neither encoding nor percent-normalization.
  245. # Components containing '%' always take the general path below because
  246. # how '%' is treated depends on whether the whole component is already
  247. # percent-encoded.
  248. if (
  249. "%" not in component
  250. and component.isascii()
  251. and all(map(allowed_chars.__contains__, component))
  252. ):
  253. return component
  254. # Normalize existing percent-encoded bytes.
  255. # Try to see if the component we're encoding is already percent-encoded
  256. # so we can skip all '%' characters but still encode all others.
  257. component, percent_encodings = _PERCENT_RE.subn(
  258. lambda match: match.group(0).upper(), component
  259. )
  260. uri_bytes = component.encode("utf-8", "surrogatepass")
  261. is_percent_encoded = percent_encodings == uri_bytes.count(b"%")
  262. encoded_component = bytearray()
  263. # Iterating over bytes yields integers; 0x25 is '%'.
  264. for byte_ord in uri_bytes:
  265. if (is_percent_encoded and byte_ord == 0x25) or (
  266. byte_ord < 128 and chr(byte_ord) in allowed_chars
  267. ):
  268. encoded_component.append(byte_ord)
  269. else:
  270. encoded_component += b"%%%02X" % byte_ord
  271. return encoded_component.decode()
  272. def _remove_path_dot_segments(path: str) -> str:
  273. # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code
  274. segments = path.split("/") # Turn the path into a list of segments
  275. output = [] # Initialize the variable to use to store output
  276. for segment in segments:
  277. # '.' is the current directory, so ignore it, it is superfluous
  278. if segment == ".":
  279. continue
  280. # Anything other than '..', should be appended to the output
  281. if segment != "..":
  282. output.append(segment)
  283. # In this case segment == '..', if we can, we should pop the last
  284. # element
  285. elif output:
  286. output.pop()
  287. # If the path starts with '/' and the output is empty or the first string
  288. # is non-empty
  289. if path.startswith("/") and (not output or output[0]):
  290. output.insert(0, "")
  291. # If the path starts with '/.' or '/..' ensure we add one more empty
  292. # string to add a trailing '/'
  293. if path.endswith(("/.", "/..")):
  294. output.append("")
  295. return "/".join(output)
  296. @typing.overload
  297. def _normalize_host(host: None, scheme: str | None) -> None: ...
  298. @typing.overload
  299. def _normalize_host(host: str, scheme: str | None) -> str: ...
  300. def _normalize_host(host: str | None, scheme: str | None) -> str | None:
  301. if host:
  302. invalid_host_char = _HOST_INVALID_CHAR_RE.search(host)
  303. if invalid_host_char:
  304. raise LocationParseError(
  305. f"Host {host!r} contains invalid character "
  306. f"{invalid_host_char.group()!r}"
  307. )
  308. if scheme in _NORMALIZABLE_SCHEMES:
  309. is_ipv6 = _IPV6_ADDRZ_RE.match(host)
  310. if is_ipv6:
  311. # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as
  312. # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID
  313. # separator as necessary to return a valid RFC 4007 scoped IP.
  314. match = _ZONE_ID_RE.search(host)
  315. if match:
  316. start, end = match.span(1)
  317. zone_id = host[start:end]
  318. if zone_id.startswith("%25") and zone_id != "%25":
  319. zone_id = zone_id[3:]
  320. else:
  321. zone_id = zone_id[1:]
  322. zone_id = _PERCENT_RE.sub(
  323. partial(_normalize_zone_id_percent_encoding, error_host=host),
  324. zone_id,
  325. )
  326. zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS)
  327. return f"{host[:start].lower()}%{zone_id}{host[end:]}"
  328. else:
  329. return host.lower()
  330. elif not _IPV4_RE.match(host):
  331. if "%" in host:
  332. host = _HOST_PERCENT_RE.sub(_normalize_host_percent_encoding, host)
  333. return to_str(
  334. b".".join([_idna_encode(label) for label in host.split(".")]),
  335. "ascii",
  336. )
  337. return host
  338. def _decode_percent_encoding(match: re.Match[str], *, error_host: str) -> str:
  339. percent_encoded_octet = match.group(0)
  340. decoded_octet = chr(int(percent_encoded_octet[1:], 16))
  341. # Keep this narrower than _HOST_INVALID_CHAR_RE because "%20" is valid
  342. # percent-encoding and remains encoded.
  343. if decoded_octet < "\x20" or decoded_octet == "\x7f":
  344. raise LocationParseError(
  345. f"Host {error_host!r} contains invalid percent-encoded "
  346. f"control character {percent_encoded_octet!r}"
  347. )
  348. return decoded_octet
  349. def _normalize_host_percent_encoding(match: re.Match[str]) -> str:
  350. # Reject invalid percent encodings
  351. if match.group(0) == "%":
  352. raise LocationParseError(f"{match.string!r} is not a valid host")
  353. decoded_octet = _decode_percent_encoding(match, error_host=match.string)
  354. if decoded_octet in _UNRESERVED_CHARS:
  355. return decoded_octet
  356. return match.group(0).upper()
  357. def _normalize_zone_id_percent_encoding(
  358. match: re.Match[str], *, error_host: str
  359. ) -> str:
  360. _decode_percent_encoding(match, error_host=error_host)
  361. return match.group(0).upper()
  362. def _idna_encode(name: str) -> bytes:
  363. if not name.isascii():
  364. try:
  365. import idna
  366. except ImportError:
  367. raise LocationParseError(
  368. "Unable to parse URL without the 'idna' module"
  369. ) from None
  370. try:
  371. return idna.encode(name.lower(), strict=True, std3_rules=True)
  372. except idna.IDNAError:
  373. raise LocationParseError(
  374. f"Name '{name}' is not a valid IDNA label"
  375. ) from None
  376. return _PERCENT_RE.sub(lambda match: match.group(0).upper(), name.lower()).encode(
  377. "ascii"
  378. )
  379. def _encode_target(target: str) -> str:
  380. """Percent-encodes a request target so that there are no invalid characters
  381. Pre-condition for this function is that 'target' must start with '/'.
  382. If that is the case then _TARGET_RE will always produce a match.
  383. """
  384. match = _TARGET_RE.match(target)
  385. if not match: # Defensive:
  386. raise LocationParseError(f"{target!r} is not a valid request URI")
  387. path, query = match.groups()
  388. encoded_target = _encode_invalid_chars(path, _PATH_CHARS)
  389. if query is not None:
  390. query = _encode_invalid_chars(query, _QUERY_CHARS)
  391. encoded_target += "?" + query
  392. return encoded_target
  393. def parse_url(url: str) -> Url:
  394. """
  395. Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
  396. performed to parse incomplete urls. Fields not provided will be None.
  397. This parser is RFC 3986 and RFC 6874 compliant.
  398. The parser logic and helper functions are based heavily on
  399. work done in the ``rfc3986`` module.
  400. :param str url: URL to parse into a :class:`.Url` namedtuple.
  401. Partly backwards-compatible with :mod:`urllib.parse`.
  402. Example:
  403. .. code-block:: python
  404. import urllib3
  405. print( urllib3.util.parse_url('http://google.com/mail/'))
  406. # Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
  407. print( urllib3.util.parse_url('google.com:80'))
  408. # Url(scheme=None, host='google.com', port=80, path=None, ...)
  409. print( urllib3.util.parse_url('/foo?bar'))
  410. # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
  411. """
  412. if not url:
  413. # Empty
  414. return Url()
  415. if not _SCHEME_RE.search(url):
  416. url = "//" + url
  417. scheme: str | None
  418. authority: str | None
  419. auth: str | None
  420. host: str | None
  421. port: str | None
  422. port_int: int | None
  423. path: str | None
  424. query: str | None
  425. fragment: str | None
  426. scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr]
  427. normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES
  428. if scheme:
  429. scheme = scheme.lower()
  430. if authority:
  431. auth, _, host_port = authority.rpartition("@")
  432. auth = auth or None
  433. host_port_match = _HOST_PORT_RE.fullmatch(host_port)
  434. if not host_port_match:
  435. invalid_host_char = _HOST_INVALID_CHAR_RE.search(host_port)
  436. if invalid_host_char:
  437. raise LocationParseError(
  438. f"Host {host_port!r} contains invalid character "
  439. f"{invalid_host_char.group()!r}"
  440. )
  441. raise LocationParseError(f"{host_port!r} is not a valid host or port")
  442. host, port = host_port_match.groups()
  443. if auth and normalize_uri:
  444. auth = _encode_invalid_chars(auth, _USERINFO_CHARS)
  445. if port == "":
  446. port = None
  447. else:
  448. auth, host, port = None, None, None
  449. if port is not None:
  450. port_int = int(port)
  451. if not (0 <= port_int <= 65535):
  452. raise LocationParseError(url)
  453. else:
  454. port_int = None
  455. host = _normalize_host(host, scheme)
  456. if normalize_uri and path:
  457. path = _remove_path_dot_segments(path)
  458. path = _encode_invalid_chars(path, _PATH_CHARS)
  459. if normalize_uri and query:
  460. query = _encode_invalid_chars(query, _QUERY_CHARS)
  461. if normalize_uri and fragment:
  462. fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS)
  463. # For the sake of backwards compatibility we put empty
  464. # string values for path if there are any defined values
  465. # beyond the path in the URL.
  466. # TODO: Remove this when we break backwards compatibility.
  467. if not path:
  468. if query is not None or fragment is not None:
  469. path = ""
  470. else:
  471. path = None
  472. return Url(
  473. scheme=scheme,
  474. auth=auth,
  475. host=host,
  476. port=port_int,
  477. path=path,
  478. query=query,
  479. fragment=fragment,
  480. )