utils.py 32 KB

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