_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import codecs
  2. import email.message
  3. import ipaddress
  4. import mimetypes
  5. import os
  6. import re
  7. import time
  8. import typing
  9. from pathlib import Path
  10. from urllib.request import getproxies
  11. import sniffio
  12. from ._types import PrimitiveData
  13. if typing.TYPE_CHECKING: # pragma: no cover
  14. from ._urls import URL
  15. _HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}
  16. _HTML5_FORM_ENCODING_REPLACEMENTS.update(
  17. {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}
  18. )
  19. _HTML5_FORM_ENCODING_RE = re.compile(
  20. r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])
  21. )
  22. def normalize_header_key(
  23. value: typing.Union[str, bytes],
  24. lower: bool,
  25. encoding: typing.Optional[str] = None,
  26. ) -> bytes:
  27. """
  28. Coerce str/bytes into a strictly byte-wise HTTP header key.
  29. """
  30. if isinstance(value, bytes):
  31. bytes_value = value
  32. else:
  33. bytes_value = value.encode(encoding or "ascii")
  34. return bytes_value.lower() if lower else bytes_value
  35. def normalize_header_value(
  36. value: typing.Union[str, bytes], encoding: typing.Optional[str] = None
  37. ) -> bytes:
  38. """
  39. Coerce str/bytes into a strictly byte-wise HTTP header value.
  40. """
  41. if isinstance(value, bytes):
  42. return value
  43. return value.encode(encoding or "ascii")
  44. def primitive_value_to_str(value: "PrimitiveData") -> str:
  45. """
  46. Coerce a primitive data type into a string value.
  47. Note that we prefer JSON-style 'true'/'false' for boolean values here.
  48. """
  49. if value is True:
  50. return "true"
  51. elif value is False:
  52. return "false"
  53. elif value is None:
  54. return ""
  55. return str(value)
  56. def is_known_encoding(encoding: str) -> bool:
  57. """
  58. Return `True` if `encoding` is a known codec.
  59. """
  60. try:
  61. codecs.lookup(encoding)
  62. except LookupError:
  63. return False
  64. return True
  65. def format_form_param(name: str, value: str) -> bytes:
  66. """
  67. Encode a name/value pair within a multipart form.
  68. """
  69. def replacer(match: typing.Match[str]) -> str:
  70. return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]
  71. value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)
  72. return f'{name}="{value}"'.encode()
  73. def get_ca_bundle_from_env() -> typing.Optional[str]:
  74. if "SSL_CERT_FILE" in os.environ:
  75. ssl_file = Path(os.environ["SSL_CERT_FILE"])
  76. if ssl_file.is_file():
  77. return str(ssl_file)
  78. if "SSL_CERT_DIR" in os.environ:
  79. ssl_path = Path(os.environ["SSL_CERT_DIR"])
  80. if ssl_path.is_dir():
  81. return str(ssl_path)
  82. return None
  83. def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:
  84. """
  85. Returns a list of parsed link headers, for more info see:
  86. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
  87. The generic syntax of those is:
  88. Link: < uri-reference >; param1=value1; param2="value2"
  89. So for instance:
  90. Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'
  91. would return
  92. [
  93. {"url": "http:/.../front.jpeg", "type": "image/jpeg"},
  94. {"url": "http://.../back.jpeg"},
  95. ]
  96. :param value: HTTP Link entity-header field
  97. :return: list of parsed link headers
  98. """
  99. links: typing.List[typing.Dict[str, str]] = []
  100. replace_chars = " '\""
  101. value = value.strip(replace_chars)
  102. if not value:
  103. return links
  104. for val in re.split(", *<", value):
  105. try:
  106. url, params = val.split(";", 1)
  107. except ValueError:
  108. url, params = val, ""
  109. link = {"url": url.strip("<> '\"")}
  110. for param in params.split(";"):
  111. try:
  112. key, value = param.split("=")
  113. except ValueError:
  114. break
  115. link[key.strip(replace_chars)] = value.strip(replace_chars)
  116. links.append(link)
  117. return links
  118. def parse_content_type_charset(content_type: str) -> typing.Optional[str]:
  119. # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.
  120. # See: https://peps.python.org/pep-0594/#cgi
  121. msg = email.message.Message()
  122. msg["content-type"] = content_type
  123. return msg.get_content_charset(failobj=None)
  124. SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
  125. def obfuscate_sensitive_headers(
  126. items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]],
  127. ) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:
  128. for k, v in items:
  129. if to_str(k.lower()) in SENSITIVE_HEADERS:
  130. v = to_bytes_or_str("[secure]", match_type_of=v)
  131. yield k, v
  132. def port_or_default(url: "URL") -> typing.Optional[int]:
  133. if url.port is not None:
  134. return url.port
  135. return {"http": 80, "https": 443}.get(url.scheme)
  136. def same_origin(url: "URL", other: "URL") -> bool:
  137. """
  138. Return 'True' if the given URLs share the same origin.
  139. """
  140. return (
  141. url.scheme == other.scheme
  142. and url.host == other.host
  143. and port_or_default(url) == port_or_default(other)
  144. )
  145. def is_https_redirect(url: "URL", location: "URL") -> bool:
  146. """
  147. Return 'True' if 'location' is a HTTPS upgrade of 'url'
  148. """
  149. if url.host != location.host:
  150. return False
  151. return (
  152. url.scheme == "http"
  153. and port_or_default(url) == 80
  154. and location.scheme == "https"
  155. and port_or_default(location) == 443
  156. )
  157. def get_environment_proxies() -> typing.Dict[str, typing.Optional[str]]:
  158. """Gets proxy information from the environment"""
  159. # urllib.request.getproxies() falls back on System
  160. # Registry and Config for proxies on Windows and macOS.
  161. # We don't want to propagate non-HTTP proxies into
  162. # our configuration such as 'TRAVIS_APT_PROXY'.
  163. proxy_info = getproxies()
  164. mounts: typing.Dict[str, typing.Optional[str]] = {}
  165. for scheme in ("http", "https", "all"):
  166. if proxy_info.get(scheme):
  167. hostname = proxy_info[scheme]
  168. mounts[f"{scheme}://"] = (
  169. hostname if "://" in hostname else f"http://{hostname}"
  170. )
  171. no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]
  172. for hostname in no_proxy_hosts:
  173. # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details
  174. # on how names in `NO_PROXY` are handled.
  175. if hostname == "*":
  176. # If NO_PROXY=* is used or if "*" occurs as any one of the comma
  177. # separated hostnames, then we should just bypass any information
  178. # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore
  179. # proxies.
  180. return {}
  181. elif hostname:
  182. # NO_PROXY=.google.com is marked as "all://*.google.com,
  183. # which disables "www.google.com" but not "google.com"
  184. # NO_PROXY=google.com is marked as "all://*google.com,
  185. # which disables "www.google.com" and "google.com".
  186. # (But not "wwwgoogle.com")
  187. # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost"
  188. # NO_PROXY=example.com,::1,localhost,192.168.0.0/16
  189. if "://" in hostname:
  190. mounts[hostname] = None
  191. elif is_ipv4_hostname(hostname):
  192. mounts[f"all://{hostname}"] = None
  193. elif is_ipv6_hostname(hostname):
  194. mounts[f"all://[{hostname}]"] = None
  195. elif hostname.lower() == "localhost":
  196. mounts[f"all://{hostname}"] = None
  197. else:
  198. mounts[f"all://*{hostname}"] = None
  199. return mounts
  200. def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:
  201. return value.encode(encoding) if isinstance(value, str) else value
  202. def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:
  203. return value if isinstance(value, str) else value.decode(encoding)
  204. def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:
  205. return value if isinstance(match_type_of, str) else value.encode()
  206. def unquote(value: str) -> str:
  207. return value[1:-1] if value[0] == value[-1] == '"' else value
  208. def guess_content_type(filename: typing.Optional[str]) -> typing.Optional[str]:
  209. if filename:
  210. return mimetypes.guess_type(filename)[0] or "application/octet-stream"
  211. return None
  212. def peek_filelike_length(stream: typing.Any) -> typing.Optional[int]:
  213. """
  214. Given a file-like stream object, return its length in number of bytes
  215. without reading it into memory.
  216. """
  217. try:
  218. # Is it an actual file?
  219. fd = stream.fileno()
  220. # Yup, seems to be an actual file.
  221. length = os.fstat(fd).st_size
  222. except (AttributeError, OSError):
  223. # No... Maybe it's something that supports random access, like `io.BytesIO`?
  224. try:
  225. # Assuming so, go to end of stream to figure out its length,
  226. # then put it back in place.
  227. offset = stream.tell()
  228. length = stream.seek(0, os.SEEK_END)
  229. stream.seek(offset)
  230. except (AttributeError, OSError):
  231. # Not even that? Sorry, we're doomed...
  232. return None
  233. return length
  234. class Timer:
  235. async def _get_time(self) -> float:
  236. library = sniffio.current_async_library()
  237. if library == "trio":
  238. import trio
  239. return trio.current_time()
  240. else:
  241. import asyncio
  242. return asyncio.get_event_loop().time()
  243. def sync_start(self) -> None:
  244. self.started = time.perf_counter()
  245. async def async_start(self) -> None:
  246. self.started = await self._get_time()
  247. def sync_elapsed(self) -> float:
  248. now = time.perf_counter()
  249. return now - self.started
  250. async def async_elapsed(self) -> float:
  251. now = await self._get_time()
  252. return now - self.started
  253. class URLPattern:
  254. """
  255. A utility class currently used for making lookups against proxy keys...
  256. # Wildcard matching...
  257. >>> pattern = URLPattern("all://")
  258. >>> pattern.matches(httpx.URL("http://example.com"))
  259. True
  260. # Witch scheme matching...
  261. >>> pattern = URLPattern("https://")
  262. >>> pattern.matches(httpx.URL("https://example.com"))
  263. True
  264. >>> pattern.matches(httpx.URL("http://example.com"))
  265. False
  266. # With domain matching...
  267. >>> pattern = URLPattern("https://example.com")
  268. >>> pattern.matches(httpx.URL("https://example.com"))
  269. True
  270. >>> pattern.matches(httpx.URL("http://example.com"))
  271. False
  272. >>> pattern.matches(httpx.URL("https://other.com"))
  273. False
  274. # Wildcard scheme, with domain matching...
  275. >>> pattern = URLPattern("all://example.com")
  276. >>> pattern.matches(httpx.URL("https://example.com"))
  277. True
  278. >>> pattern.matches(httpx.URL("http://example.com"))
  279. True
  280. >>> pattern.matches(httpx.URL("https://other.com"))
  281. False
  282. # With port matching...
  283. >>> pattern = URLPattern("https://example.com:1234")
  284. >>> pattern.matches(httpx.URL("https://example.com:1234"))
  285. True
  286. >>> pattern.matches(httpx.URL("https://example.com"))
  287. False
  288. """
  289. def __init__(self, pattern: str) -> None:
  290. from ._urls import URL
  291. if pattern and ":" not in pattern:
  292. raise ValueError(
  293. f"Proxy keys should use proper URL forms rather "
  294. f"than plain scheme strings. "
  295. f'Instead of "{pattern}", use "{pattern}://"'
  296. )
  297. url = URL(pattern)
  298. self.pattern = pattern
  299. self.scheme = "" if url.scheme == "all" else url.scheme
  300. self.host = "" if url.host == "*" else url.host
  301. self.port = url.port
  302. if not url.host or url.host == "*":
  303. self.host_regex: typing.Optional[typing.Pattern[str]] = None
  304. elif url.host.startswith("*."):
  305. # *.example.com should match "www.example.com", but not "example.com"
  306. domain = re.escape(url.host[2:])
  307. self.host_regex = re.compile(f"^.+\\.{domain}$")
  308. elif url.host.startswith("*"):
  309. # *example.com should match "www.example.com" and "example.com"
  310. domain = re.escape(url.host[1:])
  311. self.host_regex = re.compile(f"^(.+\\.)?{domain}$")
  312. else:
  313. # example.com should match "example.com" but not "www.example.com"
  314. domain = re.escape(url.host)
  315. self.host_regex = re.compile(f"^{domain}$")
  316. def matches(self, other: "URL") -> bool:
  317. if self.scheme and self.scheme != other.scheme:
  318. return False
  319. if (
  320. self.host
  321. and self.host_regex is not None
  322. and not self.host_regex.match(other.host)
  323. ):
  324. return False
  325. if self.port is not None and self.port != other.port:
  326. return False
  327. return True
  328. @property
  329. def priority(self) -> typing.Tuple[int, int, int]:
  330. """
  331. The priority allows URLPattern instances to be sortable, so that
  332. we can match from most specific to least specific.
  333. """
  334. # URLs with a port should take priority over URLs without a port.
  335. port_priority = 0 if self.port is not None else 1
  336. # Longer hostnames should match first.
  337. host_priority = -len(self.host)
  338. # Longer schemes should match first.
  339. scheme_priority = -len(self.scheme)
  340. return (port_priority, host_priority, scheme_priority)
  341. def __hash__(self) -> int:
  342. return hash(self.pattern)
  343. def __lt__(self, other: "URLPattern") -> bool:
  344. return self.priority < other.priority
  345. def __eq__(self, other: typing.Any) -> bool:
  346. return isinstance(other, URLPattern) and self.pattern == other.pattern
  347. def is_ipv4_hostname(hostname: str) -> bool:
  348. try:
  349. ipaddress.IPv4Address(hostname.split("/")[0])
  350. except Exception:
  351. return False
  352. return True
  353. def is_ipv6_hostname(hostname: str) -> bool:
  354. try:
  355. ipaddress.IPv6Address(hostname.split("/")[0])
  356. except Exception:
  357. return False
  358. return True