jpayne@68: """ jpayne@68: requests.utils jpayne@68: ~~~~~~~~~~~~~~ jpayne@68: jpayne@68: This module provides utility functions that are used within Requests jpayne@68: that are also useful for external consumption. jpayne@68: """ jpayne@68: jpayne@68: import codecs jpayne@68: import contextlib jpayne@68: import io jpayne@68: import os jpayne@68: import re jpayne@68: import socket jpayne@68: import struct jpayne@68: import sys jpayne@68: import tempfile jpayne@68: import warnings jpayne@68: import zipfile jpayne@68: from collections import OrderedDict jpayne@68: jpayne@68: from urllib3.util import make_headers, parse_url jpayne@68: jpayne@68: from . import certs jpayne@68: from .__version__ import __version__ jpayne@68: jpayne@68: # to_native_string is unused here, but imported here for backwards compatibility jpayne@68: from ._internal_utils import ( # noqa: F401 jpayne@68: _HEADER_VALIDATORS_BYTE, jpayne@68: _HEADER_VALIDATORS_STR, jpayne@68: HEADER_VALIDATORS, jpayne@68: to_native_string, jpayne@68: ) jpayne@68: from .compat import ( jpayne@68: Mapping, jpayne@68: basestring, jpayne@68: bytes, jpayne@68: getproxies, jpayne@68: getproxies_environment, jpayne@68: integer_types, jpayne@68: ) jpayne@68: from .compat import parse_http_list as _parse_list_header jpayne@68: from .compat import ( jpayne@68: proxy_bypass, jpayne@68: proxy_bypass_environment, jpayne@68: quote, jpayne@68: str, jpayne@68: unquote, jpayne@68: urlparse, jpayne@68: urlunparse, jpayne@68: ) jpayne@68: from .cookies import cookiejar_from_dict jpayne@68: from .exceptions import ( jpayne@68: FileModeWarning, jpayne@68: InvalidHeader, jpayne@68: InvalidURL, jpayne@68: UnrewindableBodyError, jpayne@68: ) jpayne@68: from .structures import CaseInsensitiveDict jpayne@68: jpayne@68: NETRC_FILES = (".netrc", "_netrc") jpayne@68: jpayne@68: DEFAULT_CA_BUNDLE_PATH = certs.where() jpayne@68: jpayne@68: DEFAULT_PORTS = {"http": 80, "https": 443} jpayne@68: jpayne@68: # Ensure that ', ' is used to preserve previous delimiter behavior. jpayne@68: DEFAULT_ACCEPT_ENCODING = ", ".join( jpayne@68: re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: if sys.platform == "win32": jpayne@68: # provide a proxy_bypass version on Windows without DNS lookups jpayne@68: jpayne@68: def proxy_bypass_registry(host): jpayne@68: try: jpayne@68: import winreg jpayne@68: except ImportError: jpayne@68: return False jpayne@68: jpayne@68: try: jpayne@68: internetSettings = winreg.OpenKey( jpayne@68: winreg.HKEY_CURRENT_USER, jpayne@68: r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", jpayne@68: ) jpayne@68: # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it jpayne@68: proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) jpayne@68: # ProxyOverride is almost always a string jpayne@68: proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] jpayne@68: except (OSError, ValueError): jpayne@68: return False jpayne@68: if not proxyEnable or not proxyOverride: jpayne@68: return False jpayne@68: jpayne@68: # make a check value list from the registry entry: replace the jpayne@68: # '' string by the localhost entry and the corresponding jpayne@68: # canonical entry. jpayne@68: proxyOverride = proxyOverride.split(";") jpayne@68: # filter out empty strings to avoid re.match return true in the following code. jpayne@68: proxyOverride = filter(None, proxyOverride) jpayne@68: # now check if we match one of the registry values. jpayne@68: for test in proxyOverride: jpayne@68: if test == "": jpayne@68: if "." not in host: jpayne@68: return True jpayne@68: test = test.replace(".", r"\.") # mask dots jpayne@68: test = test.replace("*", r".*") # change glob sequence jpayne@68: test = test.replace("?", r".") # change glob char jpayne@68: if re.match(test, host, re.I): jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: def proxy_bypass(host): # noqa jpayne@68: """Return True, if the host should be bypassed. jpayne@68: jpayne@68: Checks proxy settings gathered from the environment, if specified, jpayne@68: or the registry. jpayne@68: """ jpayne@68: if getproxies_environment(): jpayne@68: return proxy_bypass_environment(host) jpayne@68: else: jpayne@68: return proxy_bypass_registry(host) jpayne@68: jpayne@68: jpayne@68: def dict_to_sequence(d): jpayne@68: """Returns an internal sequence dictionary update.""" jpayne@68: jpayne@68: if hasattr(d, "items"): jpayne@68: d = d.items() jpayne@68: jpayne@68: return d jpayne@68: jpayne@68: jpayne@68: def super_len(o): jpayne@68: total_length = None jpayne@68: current_position = 0 jpayne@68: jpayne@68: if isinstance(o, str): jpayne@68: o = o.encode("utf-8") jpayne@68: jpayne@68: if hasattr(o, "__len__"): jpayne@68: total_length = len(o) jpayne@68: jpayne@68: elif hasattr(o, "len"): jpayne@68: total_length = o.len jpayne@68: jpayne@68: elif hasattr(o, "fileno"): jpayne@68: try: jpayne@68: fileno = o.fileno() jpayne@68: except (io.UnsupportedOperation, AttributeError): jpayne@68: # AttributeError is a surprising exception, seeing as how we've just checked jpayne@68: # that `hasattr(o, 'fileno')`. It happens for objects obtained via jpayne@68: # `Tarfile.extractfile()`, per issue 5229. jpayne@68: pass jpayne@68: else: jpayne@68: total_length = os.fstat(fileno).st_size jpayne@68: jpayne@68: # Having used fstat to determine the file length, we need to jpayne@68: # confirm that this file was opened up in binary mode. jpayne@68: if "b" not in o.mode: jpayne@68: warnings.warn( jpayne@68: ( jpayne@68: "Requests has determined the content-length for this " jpayne@68: "request using the binary size of the file: however, the " jpayne@68: "file has been opened in text mode (i.e. without the 'b' " jpayne@68: "flag in the mode). This may lead to an incorrect " jpayne@68: "content-length. In Requests 3.0, support will be removed " jpayne@68: "for files in text mode." jpayne@68: ), jpayne@68: FileModeWarning, jpayne@68: ) jpayne@68: jpayne@68: if hasattr(o, "tell"): jpayne@68: try: jpayne@68: current_position = o.tell() jpayne@68: except OSError: jpayne@68: # This can happen in some weird situations, such as when the file jpayne@68: # is actually a special file descriptor like stdin. In this jpayne@68: # instance, we don't know what the length is, so set it to zero and jpayne@68: # let requests chunk it instead. jpayne@68: if total_length is not None: jpayne@68: current_position = total_length jpayne@68: else: jpayne@68: if hasattr(o, "seek") and total_length is None: jpayne@68: # StringIO and BytesIO have seek but no usable fileno jpayne@68: try: jpayne@68: # seek to end of file jpayne@68: o.seek(0, 2) jpayne@68: total_length = o.tell() jpayne@68: jpayne@68: # seek back to current position to support jpayne@68: # partially read file-like objects jpayne@68: o.seek(current_position or 0) jpayne@68: except OSError: jpayne@68: total_length = 0 jpayne@68: jpayne@68: if total_length is None: jpayne@68: total_length = 0 jpayne@68: jpayne@68: return max(0, total_length - current_position) jpayne@68: jpayne@68: jpayne@68: def get_netrc_auth(url, raise_errors=False): jpayne@68: """Returns the Requests tuple auth for a given url from netrc.""" jpayne@68: jpayne@68: netrc_file = os.environ.get("NETRC") jpayne@68: if netrc_file is not None: jpayne@68: netrc_locations = (netrc_file,) jpayne@68: else: jpayne@68: netrc_locations = (f"~/{f}" for f in NETRC_FILES) jpayne@68: jpayne@68: try: jpayne@68: from netrc import NetrcParseError, netrc jpayne@68: jpayne@68: netrc_path = None jpayne@68: jpayne@68: for f in netrc_locations: jpayne@68: try: jpayne@68: loc = os.path.expanduser(f) jpayne@68: except KeyError: jpayne@68: # os.path.expanduser can fail when $HOME is undefined and jpayne@68: # getpwuid fails. See https://bugs.python.org/issue20164 & jpayne@68: # https://github.com/psf/requests/issues/1846 jpayne@68: return jpayne@68: jpayne@68: if os.path.exists(loc): jpayne@68: netrc_path = loc jpayne@68: break jpayne@68: jpayne@68: # Abort early if there isn't one. jpayne@68: if netrc_path is None: jpayne@68: return jpayne@68: jpayne@68: ri = urlparse(url) jpayne@68: jpayne@68: # Strip port numbers from netloc. This weird `if...encode`` dance is jpayne@68: # used for Python 3.2, which doesn't support unicode literals. jpayne@68: splitstr = b":" jpayne@68: if isinstance(url, str): jpayne@68: splitstr = splitstr.decode("ascii") jpayne@68: host = ri.netloc.split(splitstr)[0] jpayne@68: jpayne@68: try: jpayne@68: _netrc = netrc(netrc_path).authenticators(host) jpayne@68: if _netrc: jpayne@68: # Return with login / password jpayne@68: login_i = 0 if _netrc[0] else 1 jpayne@68: return (_netrc[login_i], _netrc[2]) jpayne@68: except (NetrcParseError, OSError): jpayne@68: # If there was a parsing error or a permissions issue reading the file, jpayne@68: # we'll just skip netrc auth unless explicitly asked to raise errors. jpayne@68: if raise_errors: jpayne@68: raise jpayne@68: jpayne@68: # App Engine hackiness. jpayne@68: except (ImportError, AttributeError): jpayne@68: pass jpayne@68: jpayne@68: jpayne@68: def guess_filename(obj): jpayne@68: """Tries to guess the filename of the given object.""" jpayne@68: name = getattr(obj, "name", None) jpayne@68: if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": jpayne@68: return os.path.basename(name) jpayne@68: jpayne@68: jpayne@68: def extract_zipped_paths(path): jpayne@68: """Replace nonexistent paths that look like they refer to a member of a zip jpayne@68: archive with the location of an extracted copy of the target, or else jpayne@68: just return the provided path unchanged. jpayne@68: """ jpayne@68: if os.path.exists(path): jpayne@68: # this is already a valid path, no need to do anything further jpayne@68: return path jpayne@68: jpayne@68: # find the first valid part of the provided path and treat that as a zip archive jpayne@68: # assume the rest of the path is the name of a member in the archive jpayne@68: archive, member = os.path.split(path) jpayne@68: while archive and not os.path.exists(archive): jpayne@68: archive, prefix = os.path.split(archive) jpayne@68: if not prefix: jpayne@68: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), jpayne@68: # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users jpayne@68: break jpayne@68: member = "/".join([prefix, member]) jpayne@68: jpayne@68: if not zipfile.is_zipfile(archive): jpayne@68: return path jpayne@68: jpayne@68: zip_file = zipfile.ZipFile(archive) jpayne@68: if member not in zip_file.namelist(): jpayne@68: return path jpayne@68: jpayne@68: # we have a valid zip archive and a valid member of that archive jpayne@68: tmp = tempfile.gettempdir() jpayne@68: extracted_path = os.path.join(tmp, member.split("/")[-1]) jpayne@68: if not os.path.exists(extracted_path): jpayne@68: # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition jpayne@68: with atomic_open(extracted_path) as file_handler: jpayne@68: file_handler.write(zip_file.read(member)) jpayne@68: return extracted_path jpayne@68: jpayne@68: jpayne@68: @contextlib.contextmanager jpayne@68: def atomic_open(filename): jpayne@68: """Write a file to the disk in an atomic fashion""" jpayne@68: tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) jpayne@68: try: jpayne@68: with os.fdopen(tmp_descriptor, "wb") as tmp_handler: jpayne@68: yield tmp_handler jpayne@68: os.replace(tmp_name, filename) jpayne@68: except BaseException: jpayne@68: os.remove(tmp_name) jpayne@68: raise jpayne@68: jpayne@68: jpayne@68: def from_key_val_list(value): jpayne@68: """Take an object and test to see if it can be represented as a jpayne@68: dictionary. Unless it can not be represented as such, return an jpayne@68: OrderedDict, e.g., jpayne@68: jpayne@68: :: jpayne@68: jpayne@68: >>> from_key_val_list([('key', 'val')]) jpayne@68: OrderedDict([('key', 'val')]) jpayne@68: >>> from_key_val_list('string') jpayne@68: Traceback (most recent call last): jpayne@68: ... jpayne@68: ValueError: cannot encode objects that are not 2-tuples jpayne@68: >>> from_key_val_list({'key': 'val'}) jpayne@68: OrderedDict([('key', 'val')]) jpayne@68: jpayne@68: :rtype: OrderedDict jpayne@68: """ jpayne@68: if value is None: jpayne@68: return None jpayne@68: jpayne@68: if isinstance(value, (str, bytes, bool, int)): jpayne@68: raise ValueError("cannot encode objects that are not 2-tuples") jpayne@68: jpayne@68: return OrderedDict(value) jpayne@68: jpayne@68: jpayne@68: def to_key_val_list(value): jpayne@68: """Take an object and test to see if it can be represented as a jpayne@68: dictionary. If it can be, return a list of tuples, e.g., jpayne@68: jpayne@68: :: jpayne@68: jpayne@68: >>> to_key_val_list([('key', 'val')]) jpayne@68: [('key', 'val')] jpayne@68: >>> to_key_val_list({'key': 'val'}) jpayne@68: [('key', 'val')] jpayne@68: >>> to_key_val_list('string') jpayne@68: Traceback (most recent call last): jpayne@68: ... jpayne@68: ValueError: cannot encode objects that are not 2-tuples jpayne@68: jpayne@68: :rtype: list jpayne@68: """ jpayne@68: if value is None: jpayne@68: return None jpayne@68: jpayne@68: if isinstance(value, (str, bytes, bool, int)): jpayne@68: raise ValueError("cannot encode objects that are not 2-tuples") jpayne@68: jpayne@68: if isinstance(value, Mapping): jpayne@68: value = value.items() jpayne@68: jpayne@68: return list(value) jpayne@68: jpayne@68: jpayne@68: # From mitsuhiko/werkzeug (used with permission). jpayne@68: def parse_list_header(value): jpayne@68: """Parse lists as described by RFC 2068 Section 2. jpayne@68: jpayne@68: In particular, parse comma-separated lists where the elements of jpayne@68: the list may include quoted-strings. A quoted-string could jpayne@68: contain a comma. A non-quoted string could have quotes in the jpayne@68: middle. Quotes are removed automatically after parsing. jpayne@68: jpayne@68: It basically works like :func:`parse_set_header` just that items jpayne@68: may appear multiple times and case sensitivity is preserved. jpayne@68: jpayne@68: The return value is a standard :class:`list`: jpayne@68: jpayne@68: >>> parse_list_header('token, "quoted value"') jpayne@68: ['token', 'quoted value'] jpayne@68: jpayne@68: To create a header from the :class:`list` again, use the jpayne@68: :func:`dump_header` function. jpayne@68: jpayne@68: :param value: a string with a list header. jpayne@68: :return: :class:`list` jpayne@68: :rtype: list jpayne@68: """ jpayne@68: result = [] jpayne@68: for item in _parse_list_header(value): jpayne@68: if item[:1] == item[-1:] == '"': jpayne@68: item = unquote_header_value(item[1:-1]) jpayne@68: result.append(item) jpayne@68: return result jpayne@68: jpayne@68: jpayne@68: # From mitsuhiko/werkzeug (used with permission). jpayne@68: def parse_dict_header(value): jpayne@68: """Parse lists of key, value pairs as described by RFC 2068 Section 2 and jpayne@68: convert them into a python dict: jpayne@68: jpayne@68: >>> d = parse_dict_header('foo="is a fish", bar="as well"') jpayne@68: >>> type(d) is dict jpayne@68: True jpayne@68: >>> sorted(d.items()) jpayne@68: [('bar', 'as well'), ('foo', 'is a fish')] jpayne@68: jpayne@68: If there is no value for a key it will be `None`: jpayne@68: jpayne@68: >>> parse_dict_header('key_without_value') jpayne@68: {'key_without_value': None} jpayne@68: jpayne@68: To create a header from the :class:`dict` again, use the jpayne@68: :func:`dump_header` function. jpayne@68: jpayne@68: :param value: a string with a dict header. jpayne@68: :return: :class:`dict` jpayne@68: :rtype: dict jpayne@68: """ jpayne@68: result = {} jpayne@68: for item in _parse_list_header(value): jpayne@68: if "=" not in item: jpayne@68: result[item] = None jpayne@68: continue jpayne@68: name, value = item.split("=", 1) jpayne@68: if value[:1] == value[-1:] == '"': jpayne@68: value = unquote_header_value(value[1:-1]) jpayne@68: result[name] = value jpayne@68: return result jpayne@68: jpayne@68: jpayne@68: # From mitsuhiko/werkzeug (used with permission). jpayne@68: def unquote_header_value(value, is_filename=False): jpayne@68: r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). jpayne@68: This does not use the real unquoting but what browsers are actually jpayne@68: using for quoting. jpayne@68: jpayne@68: :param value: the header value to unquote. jpayne@68: :rtype: str jpayne@68: """ jpayne@68: if value and value[0] == value[-1] == '"': jpayne@68: # this is not the real unquoting, but fixing this so that the jpayne@68: # RFC is met will result in bugs with internet explorer and jpayne@68: # probably some other browsers as well. IE for example is jpayne@68: # uploading files with "C:\foo\bar.txt" as filename jpayne@68: value = value[1:-1] jpayne@68: jpayne@68: # if this is a filename and the starting characters look like jpayne@68: # a UNC path, then just return the value without quotes. Using the jpayne@68: # replace sequence below on a UNC path has the effect of turning jpayne@68: # the leading double slash into a single slash and then jpayne@68: # _fix_ie_filename() doesn't work correctly. See #458. jpayne@68: if not is_filename or value[:2] != "\\\\": jpayne@68: return value.replace("\\\\", "\\").replace('\\"', '"') jpayne@68: return value jpayne@68: jpayne@68: jpayne@68: def dict_from_cookiejar(cj): jpayne@68: """Returns a key/value dictionary from a CookieJar. jpayne@68: jpayne@68: :param cj: CookieJar object to extract cookies from. jpayne@68: :rtype: dict jpayne@68: """ jpayne@68: jpayne@68: cookie_dict = {cookie.name: cookie.value for cookie in cj} jpayne@68: return cookie_dict jpayne@68: jpayne@68: jpayne@68: def add_dict_to_cookiejar(cj, cookie_dict): jpayne@68: """Returns a CookieJar from a key/value dictionary. jpayne@68: jpayne@68: :param cj: CookieJar to insert cookies into. jpayne@68: :param cookie_dict: Dict of key/values to insert into CookieJar. jpayne@68: :rtype: CookieJar jpayne@68: """ jpayne@68: jpayne@68: return cookiejar_from_dict(cookie_dict, cj) jpayne@68: jpayne@68: jpayne@68: def get_encodings_from_content(content): jpayne@68: """Returns encodings from given content string. jpayne@68: jpayne@68: :param content: bytestring to extract encodings from. jpayne@68: """ jpayne@68: warnings.warn( jpayne@68: ( jpayne@68: "In requests 3.0, get_encodings_from_content will be removed. For " jpayne@68: "more information, please see the discussion on issue #2266. (This" jpayne@68: " warning should only appear once.)" jpayne@68: ), jpayne@68: DeprecationWarning, jpayne@68: ) jpayne@68: jpayne@68: charset_re = re.compile(r']', flags=re.I) jpayne@68: pragma_re = re.compile(r']', flags=re.I) jpayne@68: xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') jpayne@68: jpayne@68: return ( jpayne@68: charset_re.findall(content) jpayne@68: + pragma_re.findall(content) jpayne@68: + xml_re.findall(content) jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def _parse_content_type_header(header): jpayne@68: """Returns content type and parameters from given header jpayne@68: jpayne@68: :param header: string jpayne@68: :return: tuple containing content type and dictionary of jpayne@68: parameters jpayne@68: """ jpayne@68: jpayne@68: tokens = header.split(";") jpayne@68: content_type, params = tokens[0].strip(), tokens[1:] jpayne@68: params_dict = {} jpayne@68: items_to_strip = "\"' " jpayne@68: jpayne@68: for param in params: jpayne@68: param = param.strip() jpayne@68: if param: jpayne@68: key, value = param, True jpayne@68: index_of_equals = param.find("=") jpayne@68: if index_of_equals != -1: jpayne@68: key = param[:index_of_equals].strip(items_to_strip) jpayne@68: value = param[index_of_equals + 1 :].strip(items_to_strip) jpayne@68: params_dict[key.lower()] = value jpayne@68: return content_type, params_dict jpayne@68: jpayne@68: jpayne@68: def get_encoding_from_headers(headers): jpayne@68: """Returns encodings from given HTTP Header Dict. jpayne@68: jpayne@68: :param headers: dictionary to extract encoding from. jpayne@68: :rtype: str jpayne@68: """ jpayne@68: jpayne@68: content_type = headers.get("content-type") jpayne@68: jpayne@68: if not content_type: jpayne@68: return None jpayne@68: jpayne@68: content_type, params = _parse_content_type_header(content_type) jpayne@68: jpayne@68: if "charset" in params: jpayne@68: return params["charset"].strip("'\"") jpayne@68: jpayne@68: if "text" in content_type: jpayne@68: return "ISO-8859-1" jpayne@68: jpayne@68: if "application/json" in content_type: jpayne@68: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset jpayne@68: return "utf-8" jpayne@68: jpayne@68: jpayne@68: def stream_decode_response_unicode(iterator, r): jpayne@68: """Stream decodes an iterator.""" jpayne@68: jpayne@68: if r.encoding is None: jpayne@68: yield from iterator jpayne@68: return jpayne@68: jpayne@68: decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") jpayne@68: for chunk in iterator: jpayne@68: rv = decoder.decode(chunk) jpayne@68: if rv: jpayne@68: yield rv jpayne@68: rv = decoder.decode(b"", final=True) jpayne@68: if rv: jpayne@68: yield rv jpayne@68: jpayne@68: jpayne@68: def iter_slices(string, slice_length): jpayne@68: """Iterate over slices of a string.""" jpayne@68: pos = 0 jpayne@68: if slice_length is None or slice_length <= 0: jpayne@68: slice_length = len(string) jpayne@68: while pos < len(string): jpayne@68: yield string[pos : pos + slice_length] jpayne@68: pos += slice_length jpayne@68: jpayne@68: jpayne@68: def get_unicode_from_response(r): jpayne@68: """Returns the requested content back in unicode. jpayne@68: jpayne@68: :param r: Response object to get unicode content from. jpayne@68: jpayne@68: Tried: jpayne@68: jpayne@68: 1. charset from content-type jpayne@68: 2. fall back and replace all unicode characters jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: warnings.warn( jpayne@68: ( jpayne@68: "In requests 3.0, get_unicode_from_response will be removed. For " jpayne@68: "more information, please see the discussion on issue #2266. (This" jpayne@68: " warning should only appear once.)" jpayne@68: ), jpayne@68: DeprecationWarning, jpayne@68: ) jpayne@68: jpayne@68: tried_encodings = [] jpayne@68: jpayne@68: # Try charset from content-type jpayne@68: encoding = get_encoding_from_headers(r.headers) jpayne@68: jpayne@68: if encoding: jpayne@68: try: jpayne@68: return str(r.content, encoding) jpayne@68: except UnicodeError: jpayne@68: tried_encodings.append(encoding) jpayne@68: jpayne@68: # Fall back: jpayne@68: try: jpayne@68: return str(r.content, encoding, errors="replace") jpayne@68: except TypeError: jpayne@68: return r.content jpayne@68: jpayne@68: jpayne@68: # The unreserved URI characters (RFC 3986) jpayne@68: UNRESERVED_SET = frozenset( jpayne@68: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def unquote_unreserved(uri): jpayne@68: """Un-escape any percent-escape sequences in a URI that are unreserved jpayne@68: characters. This leaves all reserved, illegal and non-ASCII bytes encoded. jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: parts = uri.split("%") jpayne@68: for i in range(1, len(parts)): jpayne@68: h = parts[i][0:2] jpayne@68: if len(h) == 2 and h.isalnum(): jpayne@68: try: jpayne@68: c = chr(int(h, 16)) jpayne@68: except ValueError: jpayne@68: raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") jpayne@68: jpayne@68: if c in UNRESERVED_SET: jpayne@68: parts[i] = c + parts[i][2:] jpayne@68: else: jpayne@68: parts[i] = f"%{parts[i]}" jpayne@68: else: jpayne@68: parts[i] = f"%{parts[i]}" jpayne@68: return "".join(parts) jpayne@68: jpayne@68: jpayne@68: def requote_uri(uri): jpayne@68: """Re-quote the given URI. jpayne@68: jpayne@68: This function passes the given URI through an unquote/quote cycle to jpayne@68: ensure that it is fully and consistently quoted. jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: safe_with_percent = "!#$%&'()*+,/:;=?@[]~" jpayne@68: safe_without_percent = "!#$&'()*+,/:;=?@[]~" jpayne@68: try: jpayne@68: # Unquote only the unreserved characters jpayne@68: # Then quote only illegal characters (do not quote reserved, jpayne@68: # unreserved, or '%') jpayne@68: return quote(unquote_unreserved(uri), safe=safe_with_percent) jpayne@68: except InvalidURL: jpayne@68: # We couldn't unquote the given URI, so let's try quoting it, but jpayne@68: # there may be unquoted '%'s in the URI. We need to make sure they're jpayne@68: # properly quoted so they do not cause issues elsewhere. jpayne@68: return quote(uri, safe=safe_without_percent) jpayne@68: jpayne@68: jpayne@68: def address_in_network(ip, net): jpayne@68: """This function allows you to check if an IP belongs to a network subnet jpayne@68: jpayne@68: Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 jpayne@68: returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 jpayne@68: jpayne@68: :rtype: bool jpayne@68: """ jpayne@68: ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] jpayne@68: netaddr, bits = net.split("/") jpayne@68: netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] jpayne@68: network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask jpayne@68: return (ipaddr & netmask) == (network & netmask) jpayne@68: jpayne@68: jpayne@68: def dotted_netmask(mask): jpayne@68: """Converts mask from /xx format to xxx.xxx.xxx.xxx jpayne@68: jpayne@68: Example: if mask is 24 function returns 255.255.255.0 jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 jpayne@68: return socket.inet_ntoa(struct.pack(">I", bits)) jpayne@68: jpayne@68: jpayne@68: def is_ipv4_address(string_ip): jpayne@68: """ jpayne@68: :rtype: bool jpayne@68: """ jpayne@68: try: jpayne@68: socket.inet_aton(string_ip) jpayne@68: except OSError: jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: jpayne@68: def is_valid_cidr(string_network): jpayne@68: """ jpayne@68: Very simple check of the cidr format in no_proxy variable. jpayne@68: jpayne@68: :rtype: bool jpayne@68: """ jpayne@68: if string_network.count("/") == 1: jpayne@68: try: jpayne@68: mask = int(string_network.split("/")[1]) jpayne@68: except ValueError: jpayne@68: return False jpayne@68: jpayne@68: if mask < 1 or mask > 32: jpayne@68: return False jpayne@68: jpayne@68: try: jpayne@68: socket.inet_aton(string_network.split("/")[0]) jpayne@68: except OSError: jpayne@68: return False jpayne@68: else: jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: jpayne@68: @contextlib.contextmanager jpayne@68: def set_environ(env_name, value): jpayne@68: """Set the environment variable 'env_name' to 'value' jpayne@68: jpayne@68: Save previous value, yield, and then restore the previous value stored in jpayne@68: the environment variable 'env_name'. jpayne@68: jpayne@68: If 'value' is None, do nothing""" jpayne@68: value_changed = value is not None jpayne@68: if value_changed: jpayne@68: old_value = os.environ.get(env_name) jpayne@68: os.environ[env_name] = value jpayne@68: try: jpayne@68: yield jpayne@68: finally: jpayne@68: if value_changed: jpayne@68: if old_value is None: jpayne@68: del os.environ[env_name] jpayne@68: else: jpayne@68: os.environ[env_name] = old_value jpayne@68: jpayne@68: jpayne@68: def should_bypass_proxies(url, no_proxy): jpayne@68: """ jpayne@68: Returns whether we should bypass proxies or not. jpayne@68: jpayne@68: :rtype: bool jpayne@68: """ jpayne@68: jpayne@68: # Prioritize lowercase environment variables over uppercase jpayne@68: # to keep a consistent behaviour with other http projects (curl, wget). jpayne@68: def get_proxy(key): jpayne@68: return os.environ.get(key) or os.environ.get(key.upper()) jpayne@68: jpayne@68: # First check whether no_proxy is defined. If it is, check that the URL jpayne@68: # we're getting isn't in the no_proxy list. jpayne@68: no_proxy_arg = no_proxy jpayne@68: if no_proxy is None: jpayne@68: no_proxy = get_proxy("no_proxy") jpayne@68: parsed = urlparse(url) jpayne@68: jpayne@68: if parsed.hostname is None: jpayne@68: # URLs don't always have hostnames, e.g. file:/// urls. jpayne@68: return True jpayne@68: jpayne@68: if no_proxy: jpayne@68: # We need to check whether we match here. We need to see if we match jpayne@68: # the end of the hostname, both with and without the port. jpayne@68: no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) jpayne@68: jpayne@68: if is_ipv4_address(parsed.hostname): jpayne@68: for proxy_ip in no_proxy: jpayne@68: if is_valid_cidr(proxy_ip): jpayne@68: if address_in_network(parsed.hostname, proxy_ip): jpayne@68: return True jpayne@68: elif parsed.hostname == proxy_ip: jpayne@68: # If no_proxy ip was defined in plain IP notation instead of cidr notation & jpayne@68: # matches the IP of the index jpayne@68: return True jpayne@68: else: jpayne@68: host_with_port = parsed.hostname jpayne@68: if parsed.port: jpayne@68: host_with_port += f":{parsed.port}" jpayne@68: jpayne@68: for host in no_proxy: jpayne@68: if parsed.hostname.endswith(host) or host_with_port.endswith(host): jpayne@68: # The URL does match something in no_proxy, so we don't want jpayne@68: # to apply the proxies on this URL. jpayne@68: return True jpayne@68: jpayne@68: with set_environ("no_proxy", no_proxy_arg): jpayne@68: # parsed.hostname can be `None` in cases such as a file URI. jpayne@68: try: jpayne@68: bypass = proxy_bypass(parsed.hostname) jpayne@68: except (TypeError, socket.gaierror): jpayne@68: bypass = False jpayne@68: jpayne@68: if bypass: jpayne@68: return True jpayne@68: jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: def get_environ_proxies(url, no_proxy=None): jpayne@68: """ jpayne@68: Return a dict of environment proxies. jpayne@68: jpayne@68: :rtype: dict jpayne@68: """ jpayne@68: if should_bypass_proxies(url, no_proxy=no_proxy): jpayne@68: return {} jpayne@68: else: jpayne@68: return getproxies() jpayne@68: jpayne@68: jpayne@68: def select_proxy(url, proxies): jpayne@68: """Select a proxy for the url, if applicable. jpayne@68: jpayne@68: :param url: The url being for the request jpayne@68: :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs jpayne@68: """ jpayne@68: proxies = proxies or {} jpayne@68: urlparts = urlparse(url) jpayne@68: if urlparts.hostname is None: jpayne@68: return proxies.get(urlparts.scheme, proxies.get("all")) jpayne@68: jpayne@68: proxy_keys = [ jpayne@68: urlparts.scheme + "://" + urlparts.hostname, jpayne@68: urlparts.scheme, jpayne@68: "all://" + urlparts.hostname, jpayne@68: "all", jpayne@68: ] jpayne@68: proxy = None jpayne@68: for proxy_key in proxy_keys: jpayne@68: if proxy_key in proxies: jpayne@68: proxy = proxies[proxy_key] jpayne@68: break jpayne@68: jpayne@68: return proxy jpayne@68: jpayne@68: jpayne@68: def resolve_proxies(request, proxies, trust_env=True): jpayne@68: """This method takes proxy information from a request and configuration jpayne@68: input to resolve a mapping of target proxies. This will consider settings jpayne@68: such as NO_PROXY to strip proxy configurations. jpayne@68: jpayne@68: :param request: Request or PreparedRequest jpayne@68: :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs jpayne@68: :param trust_env: Boolean declaring whether to trust environment configs jpayne@68: jpayne@68: :rtype: dict jpayne@68: """ jpayne@68: proxies = proxies if proxies is not None else {} jpayne@68: url = request.url jpayne@68: scheme = urlparse(url).scheme jpayne@68: no_proxy = proxies.get("no_proxy") jpayne@68: new_proxies = proxies.copy() jpayne@68: jpayne@68: if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): jpayne@68: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) jpayne@68: jpayne@68: proxy = environ_proxies.get(scheme, environ_proxies.get("all")) jpayne@68: jpayne@68: if proxy: jpayne@68: new_proxies.setdefault(scheme, proxy) jpayne@68: return new_proxies jpayne@68: jpayne@68: jpayne@68: def default_user_agent(name="python-requests"): jpayne@68: """ jpayne@68: Return a string representing the default user agent. jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: return f"{name}/{__version__}" jpayne@68: jpayne@68: jpayne@68: def default_headers(): jpayne@68: """ jpayne@68: :rtype: requests.structures.CaseInsensitiveDict jpayne@68: """ jpayne@68: return CaseInsensitiveDict( jpayne@68: { jpayne@68: "User-Agent": default_user_agent(), jpayne@68: "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, jpayne@68: "Accept": "*/*", jpayne@68: "Connection": "keep-alive", jpayne@68: } jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def parse_header_links(value): jpayne@68: """Return a list of parsed link headers proxies. jpayne@68: jpayne@68: i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" jpayne@68: jpayne@68: :rtype: list jpayne@68: """ jpayne@68: jpayne@68: links = [] jpayne@68: jpayne@68: replace_chars = " '\"" jpayne@68: jpayne@68: value = value.strip(replace_chars) jpayne@68: if not value: jpayne@68: return links jpayne@68: jpayne@68: for val in re.split(", *<", value): jpayne@68: try: jpayne@68: url, params = val.split(";", 1) jpayne@68: except ValueError: jpayne@68: url, params = val, "" jpayne@68: jpayne@68: link = {"url": url.strip("<> '\"")} jpayne@68: jpayne@68: for param in params.split(";"): jpayne@68: try: jpayne@68: key, value = param.split("=") jpayne@68: except ValueError: jpayne@68: break jpayne@68: jpayne@68: link[key.strip(replace_chars)] = value.strip(replace_chars) jpayne@68: jpayne@68: links.append(link) jpayne@68: jpayne@68: return links jpayne@68: jpayne@68: jpayne@68: # Null bytes; no need to recreate these on each call to guess_json_utf jpayne@68: _null = "\x00".encode("ascii") # encoding to ASCII for Python 3 jpayne@68: _null2 = _null * 2 jpayne@68: _null3 = _null * 3 jpayne@68: jpayne@68: jpayne@68: def guess_json_utf(data): jpayne@68: """ jpayne@68: :rtype: str jpayne@68: """ jpayne@68: # JSON always starts with two ASCII characters, so detection is as jpayne@68: # easy as counting the nulls and from their location and count jpayne@68: # determine the encoding. Also detect a BOM, if present. jpayne@68: sample = data[:4] jpayne@68: if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): jpayne@68: return "utf-32" # BOM included jpayne@68: if sample[:3] == codecs.BOM_UTF8: jpayne@68: return "utf-8-sig" # BOM included, MS style (discouraged) jpayne@68: if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): jpayne@68: return "utf-16" # BOM included jpayne@68: nullcount = sample.count(_null) jpayne@68: if nullcount == 0: jpayne@68: return "utf-8" jpayne@68: if nullcount == 2: jpayne@68: if sample[::2] == _null2: # 1st and 3rd are null jpayne@68: return "utf-16-be" jpayne@68: if sample[1::2] == _null2: # 2nd and 4th are null jpayne@68: return "utf-16-le" jpayne@68: # Did not detect 2 valid UTF-16 ascii-range characters jpayne@68: if nullcount == 3: jpayne@68: if sample[:3] == _null3: jpayne@68: return "utf-32-be" jpayne@68: if sample[1:] == _null3: jpayne@68: return "utf-32-le" jpayne@68: # Did not detect a valid UTF-32 ascii-range character jpayne@68: return None jpayne@68: jpayne@68: jpayne@68: def prepend_scheme_if_needed(url, new_scheme): jpayne@68: """Given a URL that may or may not have a scheme, prepend the given scheme. jpayne@68: Does not replace a present scheme with the one provided as an argument. jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: parsed = parse_url(url) jpayne@68: scheme, auth, host, port, path, query, fragment = parsed jpayne@68: jpayne@68: # A defect in urlparse determines that there isn't a netloc present in some jpayne@68: # urls. We previously assumed parsing was overly cautious, and swapped the jpayne@68: # netloc and path. Due to a lack of tests on the original defect, this is jpayne@68: # maintained with parse_url for backwards compatibility. jpayne@68: netloc = parsed.netloc jpayne@68: if not netloc: jpayne@68: netloc, path = path, netloc jpayne@68: jpayne@68: if auth: jpayne@68: # parse_url doesn't provide the netloc with auth jpayne@68: # so we'll add it ourselves. jpayne@68: netloc = "@".join([auth, netloc]) jpayne@68: if scheme is None: jpayne@68: scheme = new_scheme jpayne@68: if path is None: jpayne@68: path = "" jpayne@68: jpayne@68: return urlunparse((scheme, netloc, path, "", query, fragment)) jpayne@68: jpayne@68: jpayne@68: def get_auth_from_url(url): jpayne@68: """Given a url with authentication components, extract them into a tuple of jpayne@68: username,password. jpayne@68: jpayne@68: :rtype: (str,str) jpayne@68: """ jpayne@68: parsed = urlparse(url) jpayne@68: jpayne@68: try: jpayne@68: auth = (unquote(parsed.username), unquote(parsed.password)) jpayne@68: except (AttributeError, TypeError): jpayne@68: auth = ("", "") jpayne@68: jpayne@68: return auth jpayne@68: jpayne@68: jpayne@68: def check_header_validity(header): jpayne@68: """Verifies that header parts don't contain leading whitespace jpayne@68: reserved characters, or return characters. jpayne@68: jpayne@68: :param header: tuple, in the format (name, value). jpayne@68: """ jpayne@68: name, value = header jpayne@68: _validate_header_part(header, name, 0) jpayne@68: _validate_header_part(header, value, 1) jpayne@68: jpayne@68: jpayne@68: def _validate_header_part(header, header_part, header_validator_index): jpayne@68: if isinstance(header_part, str): jpayne@68: validator = _HEADER_VALIDATORS_STR[header_validator_index] jpayne@68: elif isinstance(header_part, bytes): jpayne@68: validator = _HEADER_VALIDATORS_BYTE[header_validator_index] jpayne@68: else: jpayne@68: raise InvalidHeader( jpayne@68: f"Header part ({header_part!r}) from {header} " jpayne@68: f"must be of type str or bytes, not {type(header_part)}" jpayne@68: ) jpayne@68: jpayne@68: if not validator.match(header_part): jpayne@68: header_kind = "name" if header_validator_index == 0 else "value" jpayne@68: raise InvalidHeader( jpayne@68: f"Invalid leading whitespace, reserved character(s), or return " jpayne@68: f"character(s) in header {header_kind}: {header_part!r}" jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def urldefragauth(url): jpayne@68: """ jpayne@68: Given a url remove the fragment and the authentication part. jpayne@68: jpayne@68: :rtype: str jpayne@68: """ jpayne@68: scheme, netloc, path, params, query, fragment = urlparse(url) jpayne@68: jpayne@68: # see func:`prepend_scheme_if_needed` jpayne@68: if not netloc: jpayne@68: netloc, path = path, netloc jpayne@68: jpayne@68: netloc = netloc.rsplit("@", 1)[-1] jpayne@68: jpayne@68: return urlunparse((scheme, netloc, path, params, query, "")) jpayne@68: jpayne@68: jpayne@68: def rewind_body(prepared_request): jpayne@68: """Move file pointer back to its recorded starting position jpayne@68: so it can be read again on redirect. jpayne@68: """ jpayne@68: body_seek = getattr(prepared_request.body, "seek", None) jpayne@68: if body_seek is not None and isinstance( jpayne@68: prepared_request._body_position, integer_types jpayne@68: ): jpayne@68: try: jpayne@68: body_seek(prepared_request._body_position) jpayne@68: except OSError: jpayne@68: raise UnrewindableBodyError( jpayne@68: "An error occurred when rewinding request body for redirect." jpayne@68: ) jpayne@68: else: jpayne@68: raise UnrewindableBodyError("Unable to rewind request body for redirect.")