_utils.py
This file
Path
httpx/_utils.py
411 lines · 12.4 KiB · Python
Last changed by
Remove .encode("ascii") call from null byte (#1037)Taneli Hukkinenbefore adoptioncfd07cc
History of this fileTake it
1import codecs2import collections3import contextlib4import logging5import mimetypes6import netrc7import os8import re9import sys10import typing11import warnings12from datetime import timedelta13from pathlib import Path14from time import perf_counter15from types import TracebackType16from urllib.request import getproxies1718from ._exceptions import NetworkError19from ._types import PrimitiveData2021if typing.TYPE_CHECKING: # pragma: no cover22 from ._models import URL232425_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}26_HTML5_FORM_ENCODING_REPLACEMENTS.update(27 {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}28)29_HTML5_FORM_ENCODING_RE = re.compile(30 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])31)323334def normalize_header_key(35 value: typing.Union[str, bytes], encoding: str = None36) -> bytes:37 """38 Coerce str/bytes into a strictly byte-wise HTTP header key.39 """40 if isinstance(value, bytes):41 return value.lower()42 return value.encode(encoding or "ascii").lower()434445def normalize_header_value(46 value: typing.Union[str, bytes], encoding: str = None47) -> bytes:48 """49 Coerce str/bytes into a strictly byte-wise HTTP header value.50 """51 if isinstance(value, bytes):52 return value53 return value.encode(encoding or "ascii")545556def str_query_param(value: "PrimitiveData") -> str:57 """58 Coerce a primitive data type into a string value for query params.5960 Note that we prefer JSON-style 'true'/'false' for boolean values here.61 """62 if value is True:63 return "true"64 elif value is False:65 return "false"66 elif value is None:67 return ""68 return str(value)697071def is_known_encoding(encoding: str) -> bool:72 """73 Return `True` if `encoding` is a known codec.74 """75 try:76 codecs.lookup(encoding)77 except LookupError:78 return False79 return True808182def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:83 """84 Encode a name/value pair within a multipart form.85 """86 if isinstance(value, bytes):87 value = value.decode()8889 def replacer(match: typing.Match[str]) -> str:90 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]9192 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)93 return f'{name}="{value}"'.encode()949596# Null bytes; no need to recreate these on each call to guess_json_utf97_null = b"\x00"98_null2 = _null * 299_null3 = _null * 3100101102def guess_json_utf(data: bytes) -> typing.Optional[str]:103 # JSON always starts with two ASCII characters, so detection is as104 # easy as counting the nulls and from their location and count105 # determine the encoding. Also detect a BOM, if present.106 sample = data[:4]107 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):108 return "utf-32" # BOM included109 if sample[:3] == codecs.BOM_UTF8:110 return "utf-8-sig" # BOM included, MS style (discouraged)111 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):112 return "utf-16" # BOM included113 nullcount = sample.count(_null)114 if nullcount == 0:115 return "utf-8"116 if nullcount == 2:117 if sample[::2] == _null2: # 1st and 3rd are null118 return "utf-16-be"119 if sample[1::2] == _null2: # 2nd and 4th are null120 return "utf-16-le"121 # Did not detect 2 valid UTF-16 ascii-range characters122 if nullcount == 3:123 if sample[:3] == _null3:124 return "utf-32-be"125 if sample[1:] == _null3:126 return "utf-32-le"127 # Did not detect a valid UTF-32 ascii-range character128 return None129130131class NetRCInfo:132 def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:133 if files is None:134 files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]135 self.netrc_files = files136137 @property138 def netrc_info(self) -> typing.Optional[netrc.netrc]:139 if not hasattr(self, "_netrc_info"):140 self._netrc_info = None141 for file_path in self.netrc_files:142 expanded_path = Path(file_path).expanduser()143 if expanded_path.is_file():144 self._netrc_info = netrc.netrc(str(expanded_path))145 break146 return self._netrc_info147148 def get_credentials(149 self, authority: str150 ) -> typing.Optional[typing.Tuple[str, str]]:151 if self.netrc_info is None:152 return None153154 auth_info = self.netrc_info.authenticators(authority)155 if auth_info is None or auth_info[2] is None:156 return None157 return (auth_info[0], auth_info[2])158159160def get_ca_bundle_from_env() -> typing.Optional[str]:161 if "SSL_CERT_FILE" in os.environ:162 ssl_file = Path(os.environ["SSL_CERT_FILE"])163 if ssl_file.is_file():164 return str(ssl_file)165 if "SSL_CERT_DIR" in os.environ:166 ssl_path = Path(os.environ["SSL_CERT_DIR"])167 if ssl_path.is_dir():168 return str(ssl_path)169 return None170171172def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:173 """174 Returns a list of parsed link headers, for more info see:175 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link176 The generic syntax of those is:177 Link: < uri-reference >; param1=value1; param2="value2"178 So for instance:179 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'180 would return181 [182 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},183 {"url": "http://.../back.jpeg"},184 ]185 :param value: HTTP Link entity-header field186 :return: list of parsed link headers187 """188 links: typing.List[typing.Dict[str, str]] = []189 replace_chars = " '\""190 value = value.strip(replace_chars)191 if not value:192 return links193 for val in re.split(", *<", value):194 try:195 url, params = val.split(";", 1)196 except ValueError:197 url, params = val, ""198 link = {"url": url.strip("<> '\"")}199 for param in params.split(";"):200 try:201 key, value = param.split("=")202 except ValueError:203 break204 link[key.strip(replace_chars)] = value.strip(replace_chars)205 links.append(link)206 return links207208209SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}210211212def obfuscate_sensitive_headers(213 items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]214) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:215 for k, v in items:216 if to_str(k.lower()) in SENSITIVE_HEADERS:217 v = to_bytes_or_str("[secure]", match_type_of=v)218 yield k, v219220221_LOGGER_INITIALIZED = False222TRACE_LOG_LEVEL = 5223224225class Logger(logging.Logger):226 # Stub for type checkers.227 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:228 ... # pragma: nocover229230231def get_logger(name: str) -> Logger:232 """233 Get a `logging.Logger` instance, and optionally234 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.235 """236 global _LOGGER_INITIALIZED237238 if not _LOGGER_INITIALIZED:239 _LOGGER_INITIALIZED = True240 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")241242 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()243 if log_level in ("DEBUG", "TRACE"):244 logger = logging.getLogger("httpx")245 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)246 handler = logging.StreamHandler(sys.stderr)247 handler.setFormatter(248 logging.Formatter(249 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",250 datefmt="%Y-%m-%d %H:%M:%S",251 )252 )253 logger.addHandler(handler)254255 logger = logging.getLogger(name)256257 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:258 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)259260 logger.trace = trace # type: ignore261262 return typing.cast(Logger, logger)263264265def should_not_be_proxied(url: "URL") -> bool:266 """ Return True if url should not be proxied,267 return False otherwise.268 """269 no_proxy = getproxies().get("no")270 if not no_proxy:271 return False272 no_proxy_list = [host.strip() for host in no_proxy.split(",")]273 for name in no_proxy_list:274 if name == "*":275 return True276 if name:277 name = name.lstrip(".") # ignore leading dots278 name = re.escape(name)279 pattern = r"(.+\.)?%s$" % name280 if re.match(pattern, url.host, re.I) or re.match(281 pattern, url.authority, re.I282 ):283 return True284 return False285286287def get_environment_proxies() -> typing.Dict[str, str]:288 """Gets proxy information from the environment"""289290 # urllib.request.getproxies() falls back on System291 # Registry and Config for proxies on Windows and macOS.292 # We don't want to propagate non-HTTP proxies into293 # our configuration such as 'TRAVIS_APT_PROXY'.294 supported_proxy_schemes = ("http", "https", "all")295 return {296 key: val297 for key, val in getproxies().items()298 if ("://" in key or key in supported_proxy_schemes)299 }300301302def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:303 return value.encode(encoding) if isinstance(value, str) else value304305306def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:307 return value if isinstance(value, str) else value.decode(encoding)308309310def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:311 return value if isinstance(match_type_of, str) else value.encode()312313314def unquote(value: str) -> str:315 return value[1:-1] if value[0] == value[-1] == '"' else value316317318def guess_content_type(filename: typing.Optional[str]) -> typing.Optional[str]:319 if filename:320 return mimetypes.guess_type(filename)[0] or "application/octet-stream"321 return None322323324def peek_filelike_length(stream: typing.IO) -> int:325 """326 Given a file-like stream object, return its length in number of bytes327 without reading it into memory.328 """329 try:330 # Is it an actual file?331 fd = stream.fileno()332 except OSError:333 # No... Maybe it's something that supports random access, like `io.BytesIO`?334 try:335 # Assuming so, go to end of stream to figure out its length,336 # then put it back in place.337 offset = stream.tell()338 length = stream.seek(0, os.SEEK_END)339 stream.seek(offset)340 except OSError:341 # Not even that? Sorry, we're doomed...342 raise343 else:344 return length345 else:346 # Yup, seems to be an actual file.347 return os.fstat(fd).st_size348349350def flatten_queryparams(351 queryparams: typing.Mapping[352 str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]353 ]354) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:355 """356 Convert a mapping of query params into a flat list of two-tuples357 representing each item.358359 Example:360 >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})361 [("q", "httpx), ("tag", "python"), ("tag", "dev")]362 """363 items = []364365 for k, v in queryparams.items():366 if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):367 for u in v:368 items.append((k, u))369 else:370 items.append((k, typing.cast("PrimitiveData", v)))371372 return items373374375class ElapsedTimer:376 def __init__(self) -> None:377 self.start: float = perf_counter()378 self.end: typing.Optional[float] = None379380 def __enter__(self) -> "ElapsedTimer":381 self.start = perf_counter()382 return self383384 def __exit__(385 self,386 exc_type: typing.Type[BaseException] = None,387 exc_value: BaseException = None,388 traceback: TracebackType = None,389 ) -> None:390 self.end = perf_counter()391392 @property393 def elapsed(self) -> timedelta:394 if self.end is None:395 return timedelta(seconds=perf_counter() - self.start)396 return timedelta(seconds=self.end - self.start)397398399@contextlib.contextmanager400def as_network_error(*exception_classes: type) -> typing.Iterator[None]:401 try:402 yield403 except BaseException as exc:404 for cls in exception_classes:405 if isinstance(exc, cls):406 raise NetworkError(exc) from exc407 raise408409410def warn_deprecated(message: str) -> None:411 warnings.warn(message, DeprecationWarning, stacklevel=2)