Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

url.py 15KB

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