_utils.py
This file
Path
httpx/_utils.py
531 lines · 16.8 KiB · Python
Last changed by
Replace cgi which will be deprecated in Python 3.11 (#2309)Florimond Mancabefore adoptionf13ab4d
History of this fileTake it
1import codecs2import email.message3import logging4import mimetypes5import netrc6import os7import re8import sys9import time10import typing11from pathlib import Path12from urllib.request import getproxies1314import sniffio1516from ._types import PrimitiveData1718if typing.TYPE_CHECKING: # pragma: no cover19 from ._models import URL202122_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}23_HTML5_FORM_ENCODING_REPLACEMENTS.update(24 {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}25)26_HTML5_FORM_ENCODING_RE = re.compile(27 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])28)293031def normalize_header_key(32 value: typing.Union[str, bytes],33 lower: bool,34 encoding: typing.Optional[str] = None,35) -> bytes:36 """37 Coerce str/bytes into a strictly byte-wise HTTP header key.38 """39 if isinstance(value, bytes):40 bytes_value = value41 else:42 bytes_value = value.encode(encoding or "ascii")4344 return bytes_value.lower() if lower else bytes_value454647def normalize_header_value(48 value: typing.Union[str, bytes], encoding: typing.Optional[str] = None49) -> bytes:50 """51 Coerce str/bytes into a strictly byte-wise HTTP header value.52 """53 if isinstance(value, bytes):54 return value55 return value.encode(encoding or "ascii")565758def primitive_value_to_str(value: "PrimitiveData") -> str:59 """60 Coerce a primitive data type into a string value.6162 Note that we prefer JSON-style 'true'/'false' for boolean values here.63 """64 if value is True:65 return "true"66 elif value is False:67 return "false"68 elif value is None:69 return ""70 return str(value)717273def is_known_encoding(encoding: str) -> bool:74 """75 Return `True` if `encoding` is a known codec.76 """77 try:78 codecs.lookup(encoding)79 except LookupError:80 return False81 return True828384def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:85 """86 Encode a name/value pair within a multipart form.87 """88 if isinstance(value, bytes):89 value = value.decode()9091 def replacer(match: typing.Match[str]) -> str:92 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]9394 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)95 return f'{name}="{value}"'.encode()969798# Null bytes; no need to recreate these on each call to guess_json_utf99_null = b"\x00"100_null2 = _null * 2101_null3 = _null * 3102103104def guess_json_utf(data: bytes) -> typing.Optional[str]:105 # JSON always starts with two ASCII characters, so detection is as106 # easy as counting the nulls and from their location and count107 # determine the encoding. Also detect a BOM, if present.108 sample = data[:4]109 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):110 return "utf-32" # BOM included111 if sample[:3] == codecs.BOM_UTF8:112 return "utf-8-sig" # BOM included, MS style (discouraged)113 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):114 return "utf-16" # BOM included115 nullcount = sample.count(_null)116 if nullcount == 0:117 return "utf-8"118 if nullcount == 2:119 if sample[::2] == _null2: # 1st and 3rd are null120 return "utf-16-be"121 if sample[1::2] == _null2: # 2nd and 4th are null122 return "utf-16-le"123 # Did not detect 2 valid UTF-16 ascii-range characters124 if nullcount == 3:125 if sample[:3] == _null3:126 return "utf-32-be"127 if sample[1:] == _null3:128 return "utf-32-le"129 # Did not detect a valid UTF-32 ascii-range character130 return None131132133class NetRCInfo:134 def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:135 if files is None:136 files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]137 self.netrc_files = files138139 @property140 def netrc_info(self) -> typing.Optional[netrc.netrc]:141 if not hasattr(self, "_netrc_info"):142 self._netrc_info = None143 for file_path in self.netrc_files:144 expanded_path = Path(file_path).expanduser()145 try:146 if expanded_path.is_file():147 self._netrc_info = netrc.netrc(str(expanded_path))148 break149 except (netrc.NetrcParseError, IOError): # pragma: nocover150 # Issue while reading the netrc file, ignore...151 pass152 return self._netrc_info153154 def get_credentials(self, host: str) -> typing.Optional[typing.Tuple[str, str]]:155 if self.netrc_info is None:156 return None157158 auth_info = self.netrc_info.authenticators(host)159 if auth_info is None or auth_info[2] is None:160 return None161 return (auth_info[0], auth_info[2])162163164def get_ca_bundle_from_env() -> typing.Optional[str]:165 if "SSL_CERT_FILE" in os.environ:166 ssl_file = Path(os.environ["SSL_CERT_FILE"])167 if ssl_file.is_file():168 return str(ssl_file)169 if "SSL_CERT_DIR" in os.environ:170 ssl_path = Path(os.environ["SSL_CERT_DIR"])171 if ssl_path.is_dir():172 return str(ssl_path)173 return None174175176def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:177 """178 Returns a list of parsed link headers, for more info see:179 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link180 The generic syntax of those is:181 Link: < uri-reference >; param1=value1; param2="value2"182 So for instance:183 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'184 would return185 [186 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},187 {"url": "http://.../back.jpeg"},188 ]189 :param value: HTTP Link entity-header field190 :return: list of parsed link headers191 """192 links: typing.List[typing.Dict[str, str]] = []193 replace_chars = " '\""194 value = value.strip(replace_chars)195 if not value:196 return links197 for val in re.split(", *<", value):198 try:199 url, params = val.split(";", 1)200 except ValueError:201 url, params = val, ""202 link = {"url": url.strip("<> '\"")}203 for param in params.split(";"):204 try:205 key, value = param.split("=")206 except ValueError:207 break208 link[key.strip(replace_chars)] = value.strip(replace_chars)209 links.append(link)210 return links211212213def parse_content_type_charset(content_type: str) -> typing.Optional[str]:214 # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.215 # See: https://peps.python.org/pep-0594/#cgi216 msg = email.message.Message()217 msg["content-type"] = content_type218 return msg.get_content_charset(failobj=None)219220221SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}222223224def obfuscate_sensitive_headers(225 items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]226) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:227 for k, v in items:228 if to_str(k.lower()) in SENSITIVE_HEADERS:229 v = to_bytes_or_str("[secure]", match_type_of=v)230 yield k, v231232233_LOGGER_INITIALIZED = False234TRACE_LOG_LEVEL = 5235236237class Logger(logging.Logger):238 # Stub for type checkers.239 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:240 ... # pragma: nocover241242243def get_logger(name: str) -> Logger:244 """245 Get a `logging.Logger` instance, and optionally246 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.247 """248 global _LOGGER_INITIALIZED249250 if not _LOGGER_INITIALIZED:251 _LOGGER_INITIALIZED = True252 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")253254 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()255 if log_level in ("DEBUG", "TRACE"):256 logger = logging.getLogger("httpx")257 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)258 handler = logging.StreamHandler(sys.stderr)259 handler.setFormatter(260 logging.Formatter(261 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",262 datefmt="%Y-%m-%d %H:%M:%S",263 )264 )265 logger.addHandler(handler)266267 logger = logging.getLogger(name)268269 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:270 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)271272 logger.trace = trace # type: ignore273274 return typing.cast(Logger, logger)275276277def port_or_default(url: "URL") -> typing.Optional[int]:278 if url.port is not None:279 return url.port280 return {"http": 80, "https": 443}.get(url.scheme)281282283def same_origin(url: "URL", other: "URL") -> bool:284 """285 Return 'True' if the given URLs share the same origin.286 """287 return (288 url.scheme == other.scheme289 and url.host == other.host290 and port_or_default(url) == port_or_default(other)291 )292293294def is_https_redirect(url: "URL", location: "URL") -> bool:295 """296 Return 'True' if 'location' is a HTTPS upgrade of 'url'297 """298 if url.host != location.host:299 return False300301 return (302 url.scheme == "http"303 and port_or_default(url) == 80304 and location.scheme == "https"305 and port_or_default(location) == 443306 )307308309def get_environment_proxies() -> typing.Dict[str, typing.Optional[str]]:310 """Gets proxy information from the environment"""311312 # urllib.request.getproxies() falls back on System313 # Registry and Config for proxies on Windows and macOS.314 # We don't want to propagate non-HTTP proxies into315 # our configuration such as 'TRAVIS_APT_PROXY'.316 proxy_info = getproxies()317 mounts: typing.Dict[str, typing.Optional[str]] = {}318319 for scheme in ("http", "https", "all"):320 if proxy_info.get(scheme):321 hostname = proxy_info[scheme]322 mounts[f"{scheme}://"] = (323 hostname if "://" in hostname else f"http://{hostname}"324 )325326 no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]327 for hostname in no_proxy_hosts:328 # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details329 # on how names in `NO_PROXY` are handled.330 if hostname == "*":331 # If NO_PROXY=* is used or if "*" occurs as any one of the comma332 # separated hostnames, then we should just bypass any information333 # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore334 # proxies.335 return {}336 elif hostname:337 # NO_PROXY=.google.com is marked as "all://*.google.com,338 # which disables "www.google.com" but not "google.com"339 # NO_PROXY=google.com is marked as "all://*google.com,340 # which disables "www.google.com" and "google.com".341 # (But not "wwwgoogle.com")342 mounts[f"all://*{hostname}"] = None343344 return mounts345346347def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:348 return value.encode(encoding) if isinstance(value, str) else value349350351def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:352 return value if isinstance(value, str) else value.decode(encoding)353354355def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:356 return value if isinstance(match_type_of, str) else value.encode()357358359def unquote(value: str) -> str:360 return value[1:-1] if value[0] == value[-1] == '"' else value361362363def guess_content_type(filename: typing.Optional[str]) -> typing.Optional[str]:364 if filename:365 return mimetypes.guess_type(filename)[0] or "application/octet-stream"366 return None367368369def peek_filelike_length(stream: typing.Any) -> typing.Optional[int]:370 """371 Given a file-like stream object, return its length in number of bytes372 without reading it into memory.373 """374 try:375 # Is it an actual file?376 fd = stream.fileno()377 # Yup, seems to be an actual file.378 length = os.fstat(fd).st_size379 except (AttributeError, OSError):380 # No... Maybe it's something that supports random access, like `io.BytesIO`?381 try:382 # Assuming so, go to end of stream to figure out its length,383 # then put it back in place.384 offset = stream.tell()385 length = stream.seek(0, os.SEEK_END)386 stream.seek(offset)387 except (AttributeError, OSError):388 # Not even that? Sorry, we're doomed...389 return None390391 return length392393394class Timer:395 async def _get_time(self) -> float:396 library = sniffio.current_async_library()397 if library == "trio":398 import trio399400 return trio.current_time()401 elif library == "curio": # pragma: nocover402 import curio403404 return await curio.clock()405406 import asyncio407408 return asyncio.get_event_loop().time()409410 def sync_start(self) -> None:411 self.started = time.perf_counter()412413 async def async_start(self) -> None:414 self.started = await self._get_time()415416 def sync_elapsed(self) -> float:417 now = time.perf_counter()418 return now - self.started419420 async def async_elapsed(self) -> float:421 now = await self._get_time()422 return now - self.started423424425class URLPattern:426 """427 A utility class currently used for making lookups against proxy keys...428429 # Wildcard matching...430 >>> pattern = URLPattern("all")431 >>> pattern.matches(httpx.URL("http://example.com"))432 True433434 # Witch scheme matching...435 >>> pattern = URLPattern("https")436 >>> pattern.matches(httpx.URL("https://example.com"))437 True438 >>> pattern.matches(httpx.URL("http://example.com"))439 False440441 # With domain matching...442 >>> pattern = URLPattern("https://example.com")443 >>> pattern.matches(httpx.URL("https://example.com"))444 True445 >>> pattern.matches(httpx.URL("http://example.com"))446 False447 >>> pattern.matches(httpx.URL("https://other.com"))448 False449450 # Wildcard scheme, with domain matching...451 >>> pattern = URLPattern("all://example.com")452 >>> pattern.matches(httpx.URL("https://example.com"))453 True454 >>> pattern.matches(httpx.URL("http://example.com"))455 True456 >>> pattern.matches(httpx.URL("https://other.com"))457 False458459 # With port matching...460 >>> pattern = URLPattern("https://example.com:1234")461 >>> pattern.matches(httpx.URL("https://example.com:1234"))462 True463 >>> pattern.matches(httpx.URL("https://example.com"))464 False465 """466467 def __init__(self, pattern: str) -> None:468 from ._models import URL469470 if pattern and ":" not in pattern:471 raise ValueError(472 f"Proxy keys should use proper URL forms rather "473 f"than plain scheme strings. "474 f'Instead of "{pattern}", use "{pattern}://"'475 )476477 url = URL(pattern)478 self.pattern = pattern479 self.scheme = "" if url.scheme == "all" else url.scheme480 self.host = "" if url.host == "*" else url.host481 self.port = url.port482 if not url.host or url.host == "*":483 self.host_regex: typing.Optional[typing.Pattern[str]] = None484 elif url.host.startswith("*."):485 # *.example.com should match "www.example.com", but not "example.com"486 domain = re.escape(url.host[2:])487 self.host_regex = re.compile(f"^.+\\.{domain}$")488 elif url.host.startswith("*"):489 # *example.com should match "www.example.com" and "example.com"490 domain = re.escape(url.host[1:])491 self.host_regex = re.compile(f"^(.+\\.)?{domain}$")492 else:493 # example.com should match "example.com" but not "www.example.com"494 domain = re.escape(url.host)495 self.host_regex = re.compile(f"^{domain}$")496497 def matches(self, other: "URL") -> bool:498 if self.scheme and self.scheme != other.scheme:499 return False500 if (501 self.host502 and self.host_regex is not None503 and not self.host_regex.match(other.host)504 ):505 return False506 if self.port is not None and self.port != other.port:507 return False508 return True509510 @property511 def priority(self) -> tuple:512 """513 The priority allows URLPattern instances to be sortable, so that514 we can match from most specific to least specific.515 """516 # URLs with a port should take priority over URLs without a port.517 port_priority = 0 if self.port is not None else 1518 # Longer hostnames should match first.519 host_priority = -len(self.host)520 # Longer schemes should match first.521 scheme_priority = -len(self.scheme)522 return (port_priority, host_priority, scheme_priority)523524 def __hash__(self) -> int:525 return hash(self.pattern)526527 def __lt__(self, other: "URLPattern") -> bool:528 return self.priority < other.priority529530 def __eq__(self, other: typing.Any) -> bool:531 return isinstance(other, URLPattern) and self.pattern == other.pattern