utils.py 33 KB

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