utils.py 29 KB

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