utils.py 31 KB

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