utils.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. """
  2. requests.utils
  3. ~~~~~~~~~~~~~~
  4. This module provides utility functions that are used within Requests
  5. that are also useful for external consumption.
  6. """
  7. from __future__ import annotations
  8. import codecs
  9. import contextlib
  10. import io
  11. import os
  12. import re
  13. import socket
  14. import struct
  15. import sys
  16. import tempfile
  17. import warnings
  18. import zipfile
  19. from collections import OrderedDict
  20. from collections.abc import Generator, Iterable
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. Final,
  25. TypeVar,
  26. cast,
  27. overload,
  28. )
  29. from urllib3.util import make_headers, parse_url
  30. from . import certs
  31. from .__version__ import __version__
  32. # to_native_string is unused here, but imported here for backwards compatibility
  33. from ._internal_utils import ( # noqa: F401
  34. _HEADER_VALIDATORS_BYTE, # type: ignore[reportPrivateUsage]
  35. _HEADER_VALIDATORS_STR, # type: ignore[reportPrivateUsage]
  36. HEADER_VALIDATORS, # type: ignore[reportUnusedImport]
  37. to_native_string, # type: ignore[reportUnusedImport]
  38. )
  39. from ._types import SupportsItems as _SupportsItems
  40. from .compat import (
  41. Mapping,
  42. bytes,
  43. getproxies,
  44. getproxies_environment,
  45. integer_types,
  46. is_urllib3_1,
  47. proxy_bypass,
  48. proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331
  49. quote,
  50. str,
  51. unquote,
  52. urlparse,
  53. urlunparse,
  54. )
  55. from .compat import parse_http_list as _parse_list_header
  56. from .cookies import cookiejar_from_dict
  57. from .exceptions import (
  58. FileModeWarning,
  59. InvalidHeader,
  60. InvalidURL,
  61. UnrewindableBodyError,
  62. )
  63. from .structures import CaseInsensitiveDict
  64. if TYPE_CHECKING:
  65. from http.cookiejar import CookieJar
  66. from io import BufferedWriter
  67. from . import _types as _t
  68. from .models import PreparedRequest, Request, Response
  69. NETRC_FILES: Final = (".netrc", "_netrc")
  70. # Certificate is extracted by certifi when needed.
  71. DEFAULT_CA_BUNDLE_PATH: str = certs.where()
  72. DEFAULT_PORTS: Final = {"http": 80, "https": 443}
  73. _KT = TypeVar("_KT")
  74. _VT = TypeVar("_VT")
  75. # Ensure that ', ' is used to preserve previous delimiter behavior.
  76. DEFAULT_ACCEPT_ENCODING: Final = ", ".join(
  77. re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
  78. )
  79. if sys.platform == "win32":
  80. # provide a proxy_bypass version on Windows without DNS lookups
  81. def proxy_bypass_registry(host: str) -> bool:
  82. try:
  83. import winreg
  84. except ImportError:
  85. return False
  86. try:
  87. internetSettings = winreg.OpenKey(
  88. winreg.HKEY_CURRENT_USER,
  89. r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
  90. )
  91. # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
  92. proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
  93. # ProxyOverride is almost always a string
  94. proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
  95. except (OSError, ValueError):
  96. return False
  97. if not proxyEnable or not proxyOverride:
  98. return False
  99. # make a check value list from the registry entry: replace the
  100. # '<local>' string by the localhost entry and the corresponding
  101. # canonical entry.
  102. proxyOverride = proxyOverride.split(";")
  103. # filter out empty strings to avoid re.match return true in the following code.
  104. proxyOverride = filter(None, proxyOverride)
  105. # now check if we match one of the registry values.
  106. for test in proxyOverride:
  107. if test == "<local>":
  108. if "." not in host:
  109. return True
  110. test = test.replace(".", r"\.") # mask dots
  111. test = test.replace("*", r".*") # change glob sequence
  112. test = test.replace("?", r".") # change glob char
  113. if re.match(test, host, re.I):
  114. return True
  115. return False
  116. def proxy_bypass(host: str) -> bool: # noqa
  117. """Return True, if the host should be bypassed.
  118. Checks proxy settings gathered from the environment, if specified,
  119. or the registry.
  120. """
  121. if getproxies_environment():
  122. return proxy_bypass_environment(host)
  123. else:
  124. return proxy_bypass_registry(host)
  125. def dict_to_sequence(
  126. d: _t.SupportsItems[Any, Any] | Iterable[tuple[Any, Any]],
  127. ) -> Iterable[tuple[Any, Any]]:
  128. """Returns an internal sequence dictionary update."""
  129. if isinstance(d, _SupportsItems):
  130. return d.items()
  131. return d
  132. def super_len(o: Any) -> int:
  133. total_length = None
  134. current_position = 0
  135. if not is_urllib3_1 and isinstance(o, str):
  136. # urllib3 2.x+ treats all strings as utf-8 instead
  137. # of latin-1 (iso-8859-1) like http.client.
  138. o = o.encode("utf-8")
  139. if hasattr(o, "__len__"):
  140. total_length = len(o)
  141. elif hasattr(o, "len"):
  142. total_length = o.len
  143. elif hasattr(o, "fileno"):
  144. try:
  145. fileno = o.fileno()
  146. except (io.UnsupportedOperation, AttributeError):
  147. # AttributeError is a surprising exception, seeing as how we've just checked
  148. # that `hasattr(o, 'fileno')`. It happens for objects obtained via
  149. # `Tarfile.extractfile()`, per issue 5229.
  150. pass
  151. else:
  152. total_length = os.fstat(fileno).st_size
  153. # Having used fstat to determine the file length, we need to
  154. # confirm that this file was opened up in binary mode.
  155. if "b" not in o.mode:
  156. warnings.warn(
  157. (
  158. "Requests has determined the content-length for this "
  159. "request using the binary size of the file: however, the "
  160. "file has been opened in text mode (i.e. without the 'b' "
  161. "flag in the mode). This may lead to an incorrect "
  162. "content-length. In Requests 3.0, support will be removed "
  163. "for files in text mode."
  164. ),
  165. FileModeWarning,
  166. )
  167. if hasattr(o, "tell"):
  168. try:
  169. current_position = o.tell()
  170. except OSError:
  171. # This can happen in some weird situations, such as when the file
  172. # is actually a special file descriptor like stdin. In this
  173. # instance, we don't know what the length is, so set it to zero and
  174. # let requests chunk it instead.
  175. if total_length is not None:
  176. current_position = total_length
  177. else:
  178. if hasattr(o, "seek") and total_length is None:
  179. # StringIO and BytesIO have seek but no usable fileno
  180. try:
  181. # seek to end of file
  182. o.seek(0, 2)
  183. total_length = o.tell()
  184. # seek back to current position to support
  185. # partially read file-like objects
  186. o.seek(current_position or 0)
  187. except OSError:
  188. total_length = 0
  189. if total_length is None:
  190. total_length = 0
  191. return max(0, total_length - current_position)
  192. def get_netrc_auth(
  193. url: _t.UriType, raise_errors: bool = False
  194. ) -> tuple[str, str] | None:
  195. """Returns the Requests tuple auth for a given url from netrc."""
  196. if isinstance(url, bytes):
  197. url = url.decode("utf-8")
  198. netrc_file = os.environ.get("NETRC")
  199. if netrc_file is not None:
  200. netrc_locations = (netrc_file,)
  201. else:
  202. netrc_locations = (f"~/{f}" for f in NETRC_FILES)
  203. try:
  204. from netrc import NetrcParseError, netrc
  205. netrc_path = None
  206. for f in netrc_locations:
  207. loc = os.path.expanduser(f)
  208. if os.path.exists(loc):
  209. netrc_path = loc
  210. break
  211. # Abort early if there isn't one.
  212. if netrc_path is None:
  213. return
  214. ri = urlparse(url)
  215. host = ri.hostname
  216. if host is None:
  217. return
  218. try:
  219. _netrc = netrc(netrc_path).authenticators(host)
  220. if _netrc and any(_netrc):
  221. # Return with login / password
  222. login_i = 0 if _netrc[0] else 1
  223. return (_netrc[login_i] or "", _netrc[2] or "")
  224. except (NetrcParseError, OSError):
  225. # If there was a parsing error or a permissions issue reading the file,
  226. # we'll just skip netrc auth unless explicitly asked to raise errors.
  227. if raise_errors:
  228. raise
  229. # App Engine hackiness.
  230. except (ImportError, AttributeError):
  231. pass
  232. def guess_filename(obj: Any) -> str | None:
  233. """Tries to guess the filename of the given object."""
  234. name = getattr(obj, "name", None)
  235. if name and isinstance(name, (str, bytes)) and name[0] != "<" and name[-1] != ">":
  236. return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only
  237. def extract_zipped_paths(path: str) -> str:
  238. """Replace nonexistent paths that look like they refer to a member of a zip
  239. archive with the location of an extracted copy of the target, or else
  240. just return the provided path unchanged.
  241. """
  242. if os.path.exists(path):
  243. # this is already a valid path, no need to do anything further
  244. return path
  245. # find the first valid part of the provided path and treat that as a zip archive
  246. # assume the rest of the path is the name of a member in the archive
  247. archive, member = os.path.split(path)
  248. while archive and not os.path.exists(archive):
  249. archive, prefix = os.path.split(archive)
  250. if not prefix:
  251. # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
  252. # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
  253. break
  254. member = "/".join([prefix, member])
  255. if not zipfile.is_zipfile(archive):
  256. return path
  257. zip_file = zipfile.ZipFile(archive)
  258. if member not in zip_file.namelist():
  259. return path
  260. # we have a valid zip archive and a valid member of that archive
  261. suffix = os.path.splitext(member.split("/")[-1])[-1]
  262. fd, extracted_path = tempfile.mkstemp(suffix=suffix)
  263. try:
  264. os.write(fd, zip_file.read(member))
  265. finally:
  266. os.close(fd)
  267. return extracted_path
  268. @contextlib.contextmanager
  269. def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]:
  270. """Write a file to the disk in an atomic fashion"""
  271. tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
  272. try:
  273. with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
  274. yield tmp_handler
  275. os.replace(tmp_name, filename)
  276. except BaseException:
  277. os.remove(tmp_name)
  278. raise
  279. def from_key_val_list(
  280. value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None,
  281. ) -> dict[Any, Any] | None:
  282. """Take an object and test to see if it can be represented as a
  283. dictionary. Unless it can not be represented as such, return an
  284. OrderedDict, e.g.,
  285. ::
  286. >>> from_key_val_list([('key', 'val')])
  287. OrderedDict([('key', 'val')])
  288. >>> from_key_val_list('string')
  289. Traceback (most recent call last):
  290. ...
  291. ValueError: cannot encode objects that are not 2-tuples
  292. >>> from_key_val_list({'key': 'val'})
  293. OrderedDict([('key', 'val')])
  294. :rtype: OrderedDict
  295. """
  296. if value is None:
  297. return None
  298. if isinstance(value, (str, bytes, bool, int)):
  299. raise ValueError("cannot encode objects that are not 2-tuples")
  300. return OrderedDict(value)
  301. @overload
  302. def to_key_val_list(value: None) -> None: ...
  303. @overload
  304. def to_key_val_list(
  305. value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]],
  306. ) -> list[tuple[_KT, _VT]]: ...
  307. def to_key_val_list(
  308. value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None,
  309. ) -> list[tuple[_KT, _VT]] | None:
  310. """Take an object and test to see if it can be represented as a
  311. dictionary. If it can be, return a list of tuples, e.g.,
  312. ::
  313. >>> to_key_val_list([('key', 'val')])
  314. [('key', 'val')]
  315. >>> to_key_val_list({'key': 'val'})
  316. [('key', 'val')]
  317. >>> to_key_val_list('string')
  318. Traceback (most recent call last):
  319. ...
  320. ValueError: cannot encode objects that are not 2-tuples
  321. :rtype: list
  322. """
  323. if value is None:
  324. return None
  325. if isinstance(value, (str, bytes, bool, int)):
  326. raise ValueError("cannot encode objects that are not 2-tuples")
  327. if isinstance(value, _SupportsItems):
  328. return list(value.items())
  329. return list(value)
  330. # From mitsuhiko/werkzeug (used with permission).
  331. def parse_list_header(value: str) -> list[str]:
  332. """Parse lists as described by RFC 2068 Section 2.
  333. In particular, parse comma-separated lists where the elements of
  334. the list may include quoted-strings. A quoted-string could
  335. contain a comma. A non-quoted string could have quotes in the
  336. middle. Quotes are removed automatically after parsing.
  337. It basically works like :func:`parse_set_header` just that items
  338. may appear multiple times and case sensitivity is preserved.
  339. The return value is a standard :class:`list`:
  340. >>> parse_list_header('token, "quoted value"')
  341. ['token', 'quoted value']
  342. To create a header from the :class:`list` again, use the
  343. :func:`dump_header` function.
  344. :param value: a string with a list header.
  345. :return: :class:`list`
  346. :rtype: list
  347. """
  348. result: list[str] = []
  349. for item in _parse_list_header(value):
  350. if item[:1] == item[-1:] == '"':
  351. item = unquote_header_value(item[1:-1])
  352. result.append(item)
  353. return result
  354. # From mitsuhiko/werkzeug (used with permission).
  355. def parse_dict_header(value: str) -> dict[str, str | None]:
  356. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  357. convert them into a python dict:
  358. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  359. >>> type(d) is dict
  360. True
  361. >>> sorted(d.items())
  362. [('bar', 'as well'), ('foo', 'is a fish')]
  363. If there is no value for a key it will be `None`:
  364. >>> parse_dict_header('key_without_value')
  365. {'key_without_value': None}
  366. To create a header from the :class:`dict` again, use the
  367. :func:`dump_header` function.
  368. :param value: a string with a dict header.
  369. :return: :class:`dict`
  370. :rtype: dict
  371. """
  372. result: dict[str, str | None] = {}
  373. for item in _parse_list_header(value):
  374. if "=" not in item:
  375. result[item] = None
  376. continue
  377. name, value = item.split("=", 1)
  378. if value[:1] == value[-1:] == '"':
  379. value = unquote_header_value(value[1:-1])
  380. result[name] = value
  381. return result
  382. # From mitsuhiko/werkzeug (used with permission).
  383. def unquote_header_value(value: str, is_filename: bool = False) -> str:
  384. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  385. This does not use the real unquoting but what browsers are actually
  386. using for quoting.
  387. :param value: the header value to unquote.
  388. :rtype: str
  389. """
  390. if value and value[0] == value[-1] == '"':
  391. # this is not the real unquoting, but fixing this so that the
  392. # RFC is met will result in bugs with internet explorer and
  393. # probably some other browsers as well. IE for example is
  394. # uploading files with "C:\foo\bar.txt" as filename
  395. value = value[1:-1]
  396. # if this is a filename and the starting characters look like
  397. # a UNC path, then just return the value without quotes. Using the
  398. # replace sequence below on a UNC path has the effect of turning
  399. # the leading double slash into a single slash and then
  400. # _fix_ie_filename() doesn't work correctly. See #458.
  401. if not is_filename or value[:2] != "\\\\":
  402. return value.replace("\\\\", "\\").replace('\\"', '"')
  403. return value
  404. def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]:
  405. """Returns a key/value dictionary from a CookieJar.
  406. :param cj: CookieJar object to extract cookies from.
  407. :rtype: dict
  408. """
  409. cookie_dict = {cookie.name: cookie.value for cookie in cj}
  410. return cookie_dict
  411. def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar:
  412. """Returns a CookieJar from a key/value dictionary.
  413. :param cj: CookieJar to insert cookies into.
  414. :param cookie_dict: Dict of key/values to insert into CookieJar.
  415. :rtype: CookieJar
  416. """
  417. return cookiejar_from_dict(cookie_dict, cj)
  418. def get_encodings_from_content(content: str) -> list[str]:
  419. """Returns encodings from given content string.
  420. :param content: bytestring to extract encodings from.
  421. """
  422. warnings.warn(
  423. (
  424. "In requests 3.0, get_encodings_from_content will be removed. For "
  425. "more information, please see the discussion on issue #2266. (This"
  426. " warning should only appear once.)"
  427. ),
  428. DeprecationWarning,
  429. )
  430. charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
  431. pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
  432. xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
  433. return (
  434. charset_re.findall(content)
  435. + pragma_re.findall(content)
  436. + xml_re.findall(content)
  437. )
  438. def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]:
  439. """Returns content type and parameters from given header.
  440. :param header: string
  441. :return: tuple containing content type and dictionary of
  442. parameters.
  443. """
  444. tokens = header.split(";")
  445. content_type, params = tokens[0].strip(), tokens[1:]
  446. params_dict: dict[str, str | bool] = {}
  447. strip_chars = "\"' "
  448. for param in params:
  449. param = param.strip()
  450. if param and (idx := param.find("=")) != -1:
  451. key = param[:idx].strip(strip_chars)
  452. value = param[idx + 1 :].strip(strip_chars)
  453. params_dict[key.lower()] = value
  454. return content_type, params_dict
  455. def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None:
  456. """Returns encodings from given HTTP Header Dict.
  457. :param headers: dictionary to extract encoding from.
  458. :rtype: str
  459. """
  460. content_type = headers.get("content-type")
  461. if not content_type:
  462. return None
  463. content_type, params = _parse_content_type_header(content_type)
  464. if "charset" in params:
  465. return params["charset"].strip("'\"")
  466. if "text" in content_type:
  467. return "ISO-8859-1"
  468. if "application/json" in content_type:
  469. # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
  470. return "utf-8"
  471. def stream_decode_response_unicode(
  472. iterator: Iterable[bytes], r: Response
  473. ) -> Generator[str | bytes, None, None]:
  474. """Stream decodes an iterator."""
  475. if r.encoding is None:
  476. yield from iterator
  477. return
  478. decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
  479. for chunk in iterator:
  480. rv = decoder.decode(chunk)
  481. if rv:
  482. yield rv
  483. rv = decoder.decode(b"", final=True)
  484. if rv:
  485. yield rv
  486. @overload
  487. def iter_slices(
  488. string: bytes, slice_length: int | None
  489. ) -> Generator[bytes, None, None]: ...
  490. @overload
  491. def iter_slices(
  492. string: str, slice_length: int | None
  493. ) -> Generator[str, None, None]: ...
  494. def iter_slices(
  495. string: bytes | str, slice_length: int | None
  496. ) -> Generator[bytes | str, None, None]:
  497. """Iterate over slices of a string."""
  498. pos = 0
  499. if slice_length is None or slice_length <= 0:
  500. slice_length = len(string)
  501. while pos < len(string):
  502. yield string[pos : pos + slice_length]
  503. pos += slice_length
  504. def get_unicode_from_response(r: Response) -> str | bytes | None:
  505. """Returns the requested content back in unicode.
  506. :param r: Response object to get unicode content from.
  507. Tried:
  508. 1. charset from content-type
  509. 2. fall back and replace all unicode characters
  510. :rtype: str
  511. """
  512. warnings.warn(
  513. (
  514. "In requests 3.0, get_unicode_from_response will be removed. For "
  515. "more information, please see the discussion on issue #2266. (This"
  516. " warning should only appear once.)"
  517. ),
  518. DeprecationWarning,
  519. )
  520. if r.content is None: # type: ignore[reportUnnecessaryComparison]
  521. return None
  522. tried_encodings: list[str] = []
  523. # Try charset from content-type
  524. encoding = get_encoding_from_headers(r.headers)
  525. if encoding:
  526. try:
  527. return str(r.content, encoding)
  528. except UnicodeError:
  529. tried_encodings.append(encoding)
  530. # Fall back:
  531. try:
  532. return str(r.content, encoding or "utf-8", errors="replace")
  533. except TypeError:
  534. return r.content
  535. # The unreserved URI characters (RFC 3986)
  536. UNRESERVED_SET: Final = frozenset(
  537. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
  538. )
  539. def unquote_unreserved(uri: str) -> str:
  540. """Un-escape any percent-escape sequences in a URI that are unreserved
  541. characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
  542. :rtype: str
  543. """
  544. parts = uri.split("%")
  545. for i in range(1, len(parts)):
  546. h = parts[i][0:2]
  547. if len(h) == 2 and h.isalnum():
  548. try:
  549. c = chr(int(h, 16))
  550. except ValueError:
  551. raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
  552. if c in UNRESERVED_SET:
  553. parts[i] = c + parts[i][2:]
  554. else:
  555. parts[i] = f"%{parts[i]}"
  556. else:
  557. parts[i] = f"%{parts[i]}"
  558. return "".join(parts)
  559. def requote_uri(uri: str) -> str:
  560. """Re-quote the given URI.
  561. This function passes the given URI through an unquote/quote cycle to
  562. ensure that it is fully and consistently quoted.
  563. :rtype: str
  564. """
  565. safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
  566. safe_without_percent = "!#$&'()*+,/:;=?@[]~"
  567. try:
  568. # Unquote only the unreserved characters
  569. # Then quote only illegal characters (do not quote reserved,
  570. # unreserved, or '%')
  571. return quote(unquote_unreserved(uri), safe=safe_with_percent)
  572. except InvalidURL:
  573. # We couldn't unquote the given URI, so let's try quoting it, but
  574. # there may be unquoted '%'s in the URI. We need to make sure they're
  575. # properly quoted so they do not cause issues elsewhere.
  576. return quote(uri, safe=safe_without_percent)
  577. def address_in_network(ip: str, net: str) -> bool:
  578. """This function allows you to check if an IP belongs to a network subnet
  579. Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
  580. returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
  581. :rtype: bool
  582. """
  583. ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
  584. netaddr, bits = net.split("/")
  585. netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
  586. network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
  587. return (ipaddr & netmask) == (network & netmask)
  588. def dotted_netmask(mask: int) -> str:
  589. """Converts mask from /xx format to xxx.xxx.xxx.xxx
  590. Example: if mask is 24 function returns 255.255.255.0
  591. :rtype: str
  592. """
  593. bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
  594. return socket.inet_ntoa(struct.pack(">I", bits))
  595. def is_ipv4_address(string_ip: str) -> bool:
  596. """
  597. :rtype: bool
  598. """
  599. try:
  600. socket.inet_aton(string_ip)
  601. except OSError:
  602. return False
  603. return True
  604. def is_valid_cidr(string_network: str) -> bool:
  605. """
  606. Very simple check of the cidr format in no_proxy variable.
  607. :rtype: bool
  608. """
  609. if string_network.count("/") == 1:
  610. try:
  611. mask = int(string_network.split("/")[1])
  612. except ValueError:
  613. return False
  614. if mask < 1 or mask > 32:
  615. return False
  616. try:
  617. socket.inet_aton(string_network.split("/")[0])
  618. except OSError:
  619. return False
  620. else:
  621. return False
  622. return True
  623. @contextlib.contextmanager
  624. def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]:
  625. """Set the environment variable 'env_name' to 'value'
  626. Save previous value, yield, and then restore the previous value stored in
  627. the environment variable 'env_name'.
  628. If 'value' is None, do nothing"""
  629. value_changed = value is not None
  630. old_value: str | None = None
  631. if value_changed:
  632. old_value = os.environ.get(env_name)
  633. os.environ[env_name] = value
  634. try:
  635. yield
  636. finally:
  637. if value_changed:
  638. if old_value is None:
  639. del os.environ[env_name]
  640. else:
  641. os.environ[env_name] = old_value
  642. def should_bypass_proxies(url: str, no_proxy: str | None) -> bool:
  643. """
  644. Returns whether we should bypass proxies or not.
  645. :rtype: bool
  646. """
  647. # Prioritize lowercase environment variables over uppercase
  648. # to keep a consistent behaviour with other http projects (curl, wget).
  649. def get_proxy(key: str) -> str | None:
  650. return os.environ.get(key) or os.environ.get(key.upper())
  651. # First check whether no_proxy is defined. If it is, check that the URL
  652. # we're getting isn't in the no_proxy list.
  653. no_proxy_arg = no_proxy
  654. if no_proxy is None:
  655. no_proxy = get_proxy("no_proxy")
  656. parsed = urlparse(url)
  657. hostname = parsed.hostname
  658. if hostname is None:
  659. # URLs don't always have hostnames, e.g. file:/// urls.
  660. return True
  661. if no_proxy:
  662. # We need to check whether we match here. We need to see if we match
  663. # the end of the hostname, both with and without the port.
  664. no_proxy_hosts = (host for host in no_proxy.replace(" ", "").split(",") if host)
  665. if is_ipv4_address(hostname):
  666. for proxy_ip in no_proxy_hosts:
  667. if is_valid_cidr(proxy_ip):
  668. if address_in_network(hostname, proxy_ip):
  669. return True
  670. elif hostname == proxy_ip:
  671. # If no_proxy ip was defined in plain IP notation instead of cidr notation &
  672. # matches the IP of the index
  673. return True
  674. else:
  675. host_with_port = hostname
  676. if parsed.port:
  677. host_with_port += f":{parsed.port}"
  678. for host in no_proxy_hosts:
  679. host = host.lstrip(".")
  680. if hostname == host or host_with_port == host:
  681. return True
  682. host = "." + host
  683. if hostname.endswith(host) or host_with_port.endswith(host):
  684. return True
  685. with set_environ("no_proxy", no_proxy_arg):
  686. try:
  687. bypass = proxy_bypass(hostname)
  688. except (TypeError, socket.gaierror):
  689. bypass = False
  690. if bypass:
  691. return True
  692. return False
  693. def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:
  694. """
  695. Return a dict of environment proxies.
  696. :rtype: dict
  697. """
  698. if should_bypass_proxies(url, no_proxy=no_proxy):
  699. return {}
  700. else:
  701. return getproxies()
  702. def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:
  703. """Select a proxy for the url, if applicable.
  704. :param url: The url being for the request
  705. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  706. """
  707. proxies = proxies or {}
  708. urlparts = urlparse(url)
  709. if urlparts.hostname is None:
  710. return proxies.get(urlparts.scheme, proxies.get("all"))
  711. proxy_keys = [
  712. urlparts.scheme + "://" + urlparts.hostname,
  713. urlparts.scheme,
  714. "all://" + urlparts.hostname,
  715. "all",
  716. ]
  717. proxy = None
  718. for proxy_key in proxy_keys:
  719. if proxy_key in proxies:
  720. proxy = proxies[proxy_key]
  721. break
  722. return proxy
  723. def resolve_proxies(
  724. request: Request | PreparedRequest,
  725. proxies: dict[str, str] | None,
  726. trust_env: bool = True,
  727. ) -> dict[str, str]:
  728. """This method takes proxy information from a request and configuration
  729. input to resolve a mapping of target proxies. This will consider settings
  730. such as NO_PROXY to strip proxy configurations.
  731. :param request: Request or PreparedRequest
  732. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  733. :param trust_env: Boolean declaring whether to trust environment configs
  734. :rtype: dict
  735. """
  736. proxies = proxies if proxies is not None else {}
  737. url = cast(str, request.url)
  738. scheme = urlparse(url).scheme
  739. no_proxy = proxies.get("no_proxy")
  740. new_proxies = proxies.copy()
  741. if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
  742. environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  743. proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
  744. if proxy:
  745. new_proxies.setdefault(scheme, proxy)
  746. return new_proxies
  747. def default_user_agent(name: str = "python-requests") -> str:
  748. """
  749. Return a string representing the default user agent.
  750. :rtype: str
  751. """
  752. return f"{name}/{__version__}"
  753. def default_headers() -> CaseInsensitiveDict[str]:
  754. """
  755. :rtype: requests.structures.CaseInsensitiveDict
  756. """
  757. return CaseInsensitiveDict(
  758. {
  759. "User-Agent": default_user_agent(),
  760. "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
  761. "Accept": "*/*",
  762. "Connection": "keep-alive",
  763. }
  764. )
  765. def parse_header_links(value: str) -> list[dict[str, str]]:
  766. """Return a list of parsed link headers proxies.
  767. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
  768. :rtype: list
  769. """
  770. links: list[dict[str, str]] = []
  771. replace_chars = " '\""
  772. value = value.strip(replace_chars)
  773. if not value:
  774. return links
  775. for val in re.split(", *<", value):
  776. try:
  777. url, params = val.split(";", 1)
  778. except ValueError:
  779. url, params = val, ""
  780. link: dict[str, str] = {"url": url.strip("<> '\"")}
  781. for param in params.split(";"):
  782. try:
  783. key, value = param.split("=")
  784. except ValueError:
  785. break
  786. link[key.strip(replace_chars)] = value.strip(replace_chars)
  787. links.append(link)
  788. return links
  789. # Null bytes; no need to recreate these on each call to guess_json_utf
  790. _null = "\x00".encode("ascii") # encoding to ASCII for Python 3
  791. _null2 = _null * 2
  792. _null3 = _null * 3
  793. def guess_json_utf(data: bytes) -> str | None:
  794. """
  795. :rtype: str
  796. """
  797. # JSON always starts with two ASCII characters, so detection is as
  798. # easy as counting the nulls and from their location and count
  799. # determine the encoding. Also detect a BOM, if present.
  800. sample = data[:4]
  801. if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
  802. return "utf-32" # BOM included
  803. if sample[:3] == codecs.BOM_UTF8:
  804. return "utf-8-sig" # BOM included, MS style (discouraged)
  805. if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
  806. return "utf-16" # BOM included
  807. nullcount = sample.count(_null)
  808. if nullcount == 0:
  809. return "utf-8"
  810. if nullcount == 2:
  811. if sample[::2] == _null2: # 1st and 3rd are null
  812. return "utf-16-be"
  813. if sample[1::2] == _null2: # 2nd and 4th are null
  814. return "utf-16-le"
  815. # Did not detect 2 valid UTF-16 ascii-range characters
  816. if nullcount == 3:
  817. if sample[:3] == _null3:
  818. return "utf-32-be"
  819. if sample[1:] == _null3:
  820. return "utf-32-le"
  821. # Did not detect a valid UTF-32 ascii-range character
  822. return None
  823. def prepend_scheme_if_needed(url: str, new_scheme: str) -> str:
  824. """Given a URL that may or may not have a scheme, prepend the given scheme.
  825. Does not replace a present scheme with the one provided as an argument.
  826. :rtype: str
  827. """
  828. parsed = parse_url(url)
  829. scheme, auth, _host, _port, path, query, fragment = parsed
  830. # A defect in urlparse determines that there isn't a netloc present in some
  831. # urls. We previously assumed parsing was overly cautious, and swapped the
  832. # netloc and path. Due to a lack of tests on the original defect, this is
  833. # maintained with parse_url for backwards compatibility.
  834. netloc = parsed.netloc
  835. if not netloc:
  836. netloc, path = path, netloc
  837. if auth:
  838. # parse_url doesn't provide the netloc with auth
  839. # so we'll add it ourselves.
  840. netloc = cast(str, netloc)
  841. netloc = "@".join([auth, netloc])
  842. if scheme is None:
  843. scheme = new_scheme
  844. if path is None:
  845. path = ""
  846. return urlunparse((scheme, netloc, path, "", query, fragment))
  847. def get_auth_from_url(url: str) -> tuple[str, str]:
  848. """Given a url with authentication components, extract them into a tuple of
  849. username,password.
  850. :rtype: (str,str)
  851. """
  852. parsed = urlparse(url)
  853. try:
  854. # except handles parsed.username/password being None
  855. auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type]
  856. except (AttributeError, TypeError):
  857. auth = ("", "")
  858. return auth
  859. def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None:
  860. """Verifies that header parts don't contain leading whitespace
  861. reserved characters, or return characters.
  862. :param header: tuple, in the format (name, value).
  863. """
  864. name, value = header
  865. _validate_header_part(header, name, 0)
  866. _validate_header_part(header, value, 1)
  867. def _validate_header_part(
  868. header: tuple[str | bytes, str | bytes],
  869. header_part: str | bytes,
  870. header_validator_index: int,
  871. ) -> None:
  872. if isinstance(header_part, str):
  873. validator = _HEADER_VALIDATORS_STR[header_validator_index]
  874. elif isinstance(header_part, bytes): # type: ignore[reportUnnecessaryIsInstance]
  875. # runtime guard for non-str/bytes input
  876. validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
  877. else:
  878. raise InvalidHeader(
  879. f"Header part ({header_part!r}) from {header} "
  880. f"must be of type str or bytes, not {type(header_part)}"
  881. )
  882. if not validator.match(header_part): # type: ignore[arg-type]
  883. header_kind = "name" if header_validator_index == 0 else "value"
  884. raise InvalidHeader(
  885. f"Invalid leading whitespace, reserved character(s), or return "
  886. f"character(s) in header {header_kind}: {header_part!r}"
  887. )
  888. def urldefragauth(url: str) -> str:
  889. """
  890. Given a url remove the fragment and the authentication part.
  891. :rtype: str
  892. """
  893. scheme, netloc, path, params, query, _fragment = urlparse(url)
  894. # see func:`prepend_scheme_if_needed`
  895. if not netloc:
  896. netloc, path = path, netloc
  897. netloc = netloc.rsplit("@", 1)[-1]
  898. return urlunparse((scheme, netloc, path, params, query, ""))
  899. def rewind_body(prepared_request: PreparedRequest) -> None:
  900. """Move file pointer back to its recorded starting position
  901. so it can be read again on redirect.
  902. """
  903. body_seek = getattr(prepared_request.body, "seek", None)
  904. if body_seek is not None and isinstance(
  905. prepared_request._body_position, # type: ignore[reportPrivateUsage]
  906. integer_types,
  907. ):
  908. try:
  909. body_seek(prepared_request._body_position) # type: ignore[reportPrivateUsage]
  910. except OSError:
  911. raise UnrewindableBodyError(
  912. "An error occurred when rewinding request body for redirect."
  913. )
  914. else:
  915. raise UnrewindableBodyError("Unable to rewind request body for redirect.")