compat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import copy
  14. import datetime
  15. import sys
  16. import inspect
  17. import warnings
  18. import hashlib
  19. import logging
  20. import shlex
  21. import os
  22. from math import floor
  23. from botocore.vendored import six
  24. from botocore.exceptions import MD5UnavailableError
  25. from dateutil.tz import tzlocal
  26. from urllib3 import exceptions
  27. logger = logging.getLogger(__name__)
  28. if six.PY3:
  29. from botocore.vendored.six.moves import http_client
  30. class HTTPHeaders(http_client.HTTPMessage):
  31. pass
  32. from urllib.parse import quote
  33. from urllib.parse import urlencode
  34. from urllib.parse import unquote
  35. from urllib.parse import unquote_plus
  36. from urllib.parse import urlparse
  37. from urllib.parse import urlsplit
  38. from urllib.parse import urlunsplit
  39. from urllib.parse import urljoin
  40. from urllib.parse import parse_qsl
  41. from urllib.parse import parse_qs
  42. from http.client import HTTPResponse
  43. from io import IOBase as _IOBase
  44. from base64 import encodebytes
  45. from email.utils import formatdate
  46. from itertools import zip_longest
  47. file_type = _IOBase
  48. zip = zip
  49. # In python3, unquote takes a str() object, url decodes it,
  50. # then takes the bytestring and decodes it to utf-8.
  51. # Python2 we'll have to do this ourself (see below).
  52. unquote_str = unquote_plus
  53. def set_socket_timeout(http_response, timeout):
  54. """Set the timeout of the socket from an HTTPResponse.
  55. :param http_response: An instance of ``httplib.HTTPResponse``
  56. """
  57. http_response._fp.fp.raw._sock.settimeout(timeout)
  58. def accepts_kwargs(func):
  59. # In python3.4.1, there's backwards incompatible
  60. # changes when using getargspec with functools.partials.
  61. return inspect.getfullargspec(func)[2]
  62. def ensure_unicode(s, encoding=None, errors=None):
  63. # NOOP in Python 3, because every string is already unicode
  64. return s
  65. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  66. if isinstance(s, str):
  67. return s.encode(encoding, errors)
  68. if isinstance(s, bytes):
  69. return s
  70. raise ValueError("Expected str or bytes, received %s." % type(s))
  71. else:
  72. from urllib import quote
  73. from urllib import urlencode
  74. from urllib import unquote
  75. from urllib import unquote_plus
  76. from urlparse import urlparse
  77. from urlparse import urlsplit
  78. from urlparse import urlunsplit
  79. from urlparse import urljoin
  80. from urlparse import parse_qsl
  81. from urlparse import parse_qs
  82. from email.message import Message
  83. from email.Utils import formatdate
  84. file_type = file
  85. from itertools import izip as zip
  86. from itertools import izip_longest as zip_longest
  87. from httplib import HTTPResponse
  88. from base64 import encodestring as encodebytes
  89. class HTTPHeaders(Message):
  90. # The __iter__ method is not available in python2.x, so we have
  91. # to port the py3 version.
  92. def __iter__(self):
  93. for field, value in self._headers:
  94. yield field
  95. def unquote_str(value, encoding='utf-8'):
  96. # In python2, unquote() gives us a string back that has the urldecoded
  97. # bits, but not the unicode parts. We need to decode this manually.
  98. # unquote has special logic in which if it receives a unicode object it
  99. # will decode it to latin1. This is hard coded. To avoid this, we'll
  100. # encode the string with the passed in encoding before trying to
  101. # unquote it.
  102. byte_string = value.encode(encoding)
  103. return unquote_plus(byte_string).decode(encoding)
  104. def set_socket_timeout(http_response, timeout):
  105. """Set the timeout of the socket from an HTTPResponse.
  106. :param http_response: An instance of ``httplib.HTTPResponse``
  107. """
  108. http_response._fp.fp._sock.settimeout(timeout)
  109. def accepts_kwargs(func):
  110. return inspect.getargspec(func)[2]
  111. def ensure_unicode(s, encoding='utf-8', errors='strict'):
  112. if isinstance(s, six.text_type):
  113. return s
  114. return unicode(s, encoding, errors)
  115. def ensure_bytes(s, encoding='utf-8', errors='strict'):
  116. if isinstance(s, unicode):
  117. return s.encode(encoding, errors)
  118. if isinstance(s, str):
  119. return s
  120. raise ValueError("Expected str or unicode, received %s." % type(s))
  121. from collections import OrderedDict
  122. try:
  123. import xml.etree.cElementTree as ETree
  124. except ImportError:
  125. # cElementTree does not exist from Python3.9+
  126. import xml.etree.ElementTree as ETree
  127. XMLParseError = ETree.ParseError
  128. import json
  129. def filter_ssl_warnings():
  130. # Ignore warnings related to SNI as it is not being used in validations.
  131. warnings.filterwarnings(
  132. 'ignore',
  133. message="A true SSLContext object is not available.*",
  134. category=exceptions.InsecurePlatformWarning,
  135. module=r".*urllib3\.util\.ssl_")
  136. @classmethod
  137. def from_dict(cls, d):
  138. new_instance = cls()
  139. for key, value in d.items():
  140. new_instance[key] = value
  141. return new_instance
  142. @classmethod
  143. def from_pairs(cls, pairs):
  144. new_instance = cls()
  145. for key, value in pairs:
  146. new_instance[key] = value
  147. return new_instance
  148. HTTPHeaders.from_dict = from_dict
  149. HTTPHeaders.from_pairs = from_pairs
  150. def copy_kwargs(kwargs):
  151. """
  152. This used to be a compat shim for 2.6 but is now just an alias.
  153. """
  154. copy_kwargs = copy.copy(kwargs)
  155. return copy_kwargs
  156. def total_seconds(delta):
  157. """
  158. Returns the total seconds in a ``datetime.timedelta``.
  159. This used to be a compat shim for 2.6 but is now just an alias.
  160. :param delta: The timedelta object
  161. :type delta: ``datetime.timedelta``
  162. """
  163. return delta.total_seconds()
  164. # Checks to see if md5 is available on this system. A given system might not
  165. # have access to it for various reasons, such as FIPS mode being enabled.
  166. try:
  167. hashlib.md5()
  168. MD5_AVAILABLE = True
  169. except ValueError:
  170. MD5_AVAILABLE = False
  171. def get_md5(*args, **kwargs):
  172. """
  173. Attempts to get an md5 hashing object.
  174. :param raise_error_if_unavailable: raise an error if md5 is unavailable on
  175. this system. If False, None will be returned if it is unavailable.
  176. :type raise_error_if_unavailable: bool
  177. :param args: Args to pass to the MD5 constructor
  178. :param kwargs: Key word arguments to pass to the MD5 constructor
  179. :return: An MD5 hashing object if available. If it is unavailable, None
  180. is returned if raise_error_if_unavailable is set to False.
  181. """
  182. if MD5_AVAILABLE:
  183. return hashlib.md5(*args, **kwargs)
  184. else:
  185. raise MD5UnavailableError()
  186. def compat_shell_split(s, platform=None):
  187. if platform is None:
  188. platform = sys.platform
  189. if platform == "win32":
  190. return _windows_shell_split(s)
  191. else:
  192. return shlex.split(s)
  193. def _windows_shell_split(s):
  194. """Splits up a windows command as the built-in command parser would.
  195. Windows has potentially bizarre rules depending on where you look. When
  196. spawning a process via the Windows C runtime (which is what python does
  197. when you call popen) the rules are as follows:
  198. https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
  199. To summarize:
  200. * Only space and tab are valid delimiters
  201. * Double quotes are the only valid quotes
  202. * Backslash is interpreted literally unless it is part of a chain that
  203. leads up to a double quote. Then the backslashes escape the backslashes,
  204. and if there is an odd number the final backslash escapes the quote.
  205. :param s: The command string to split up into parts.
  206. :return: A list of command components.
  207. """
  208. if not s:
  209. return []
  210. components = []
  211. buff = []
  212. is_quoted = False
  213. num_backslashes = 0
  214. for character in s:
  215. if character == '\\':
  216. # We can't simply append backslashes because we don't know if
  217. # they are being used as escape characters or not. Instead we
  218. # keep track of how many we've encountered and handle them when
  219. # we encounter a different character.
  220. num_backslashes += 1
  221. elif character == '"':
  222. if num_backslashes > 0:
  223. # The backslashes are in a chain leading up to a double
  224. # quote, so they are escaping each other.
  225. buff.append('\\' * int(floor(num_backslashes / 2)))
  226. remainder = num_backslashes % 2
  227. num_backslashes = 0
  228. if remainder == 1:
  229. # The number of backslashes is uneven, so they are also
  230. # escaping the double quote, so it needs to be added to
  231. # the current component buffer.
  232. buff.append('"')
  233. continue
  234. # We've encountered a double quote that is not escaped,
  235. # so we toggle is_quoted.
  236. is_quoted = not is_quoted
  237. # If there are quotes, then we may want an empty string. To be
  238. # safe, we add an empty string to the buffer so that we make
  239. # sure it sticks around if there's nothing else between quotes.
  240. # If there is other stuff between quotes, the empty string will
  241. # disappear during the joining process.
  242. buff.append('')
  243. elif character in [' ', '\t'] and not is_quoted:
  244. # Since the backslashes aren't leading up to a quote, we put in
  245. # the exact number of backslashes.
  246. if num_backslashes > 0:
  247. buff.append('\\' * num_backslashes)
  248. num_backslashes = 0
  249. # Excess whitespace is ignored, so only add the components list
  250. # if there is anything in the buffer.
  251. if buff:
  252. components.append(''.join(buff))
  253. buff = []
  254. else:
  255. # Since the backslashes aren't leading up to a quote, we put in
  256. # the exact number of backslashes.
  257. if num_backslashes > 0:
  258. buff.append('\\' * num_backslashes)
  259. num_backslashes = 0
  260. buff.append(character)
  261. # Quotes must be terminated.
  262. if is_quoted:
  263. raise ValueError('No closing quotation in string: %s' % s)
  264. # There may be some leftover backslashes, so we need to add them in.
  265. # There's no quote so we add the exact number.
  266. if num_backslashes > 0:
  267. buff.append('\\' * num_backslashes)
  268. # Add the final component in if there is anything in the buffer.
  269. if buff:
  270. components.append(''.join(buff))
  271. return components
  272. def get_tzinfo_options():
  273. # Due to dateutil/dateutil#197, Windows may fail to parse times in the past
  274. # with the system clock. We can alternatively fallback to tzwininfo when
  275. # this happens, which will get time info from the Windows registry.
  276. if sys.platform == 'win32':
  277. from dateutil.tz import tzwinlocal
  278. return (tzlocal, tzwinlocal)
  279. else:
  280. return (tzlocal,)
  281. try:
  282. from collections.abc import MutableMapping
  283. except ImportError:
  284. from collections import MutableMapping
  285. # Detect if CRT is available for use
  286. try:
  287. import awscrt.auth
  288. # Allow user opt-out if needed
  289. disabled = os.environ.get('BOTO_DISABLE_CRT', "false")
  290. HAS_CRT = not disabled.lower() == 'true'
  291. except ImportError:
  292. HAS_CRT = False