utils.py 32 KB

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