You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1227 lines
50 KiB

4 years ago
  1. # Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/
  2. # Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
  3. # Copyright (c) 2010 Google
  4. # Copyright (c) 2008 rPath, Inc.
  5. # Copyright (c) 2009 The Echo Nest Corporation
  6. # Copyright (c) 2010, Eucalyptus Systems, Inc.
  7. # Copyright (c) 2011, Nexenta Systems Inc.
  8. # All rights reserved.
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining a
  11. # copy of this software and associated documentation files (the
  12. # "Software"), to deal in the Software without restriction, including
  13. # without limitation the rights to use, copy, modify, merge, publish, dis-
  14. # tribute, sublicense, and/or sell copies of the Software, and to permit
  15. # persons to whom the Software is furnished to do so, subject to the fol-
  16. # lowing conditions:
  17. #
  18. # The above copyright notice and this permission notice shall be included
  19. # in all copies or substantial portions of the Software.
  20. #
  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  23. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  24. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  25. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  27. # IN THE SOFTWARE.
  28. #
  29. # Parts of this code were copied or derived from sample code supplied by AWS.
  30. # The following notice applies to that code.
  31. #
  32. # This software code is made available "AS IS" without warranties of any
  33. # kind. You may copy, display, modify and redistribute the software
  34. # code either by itself or as incorporated into your code; provided that
  35. # you do not remove any proprietary notices. Your use of this software
  36. # code is at your own risk and you waive any claim against Amazon
  37. # Digital Services, Inc. or its affiliates with respect to your use of
  38. # this software code. (c) 2006 Amazon Digital Services, Inc. or its
  39. # affiliates.
  40. """
  41. Handles basic connections to AWS
  42. """
  43. from datetime import datetime
  44. import errno
  45. import os
  46. import random
  47. import re
  48. import socket
  49. import sys
  50. import time
  51. import xml.sax
  52. import copy
  53. from boto import auth
  54. from boto import auth_handler
  55. import boto
  56. import boto.utils
  57. import boto.handler
  58. import boto.cacerts
  59. from boto import config, UserAgent
  60. from boto.compat import six, http_client, urlparse, quote, encodebytes
  61. from boto.exception import AWSConnectionError
  62. from boto.exception import BotoClientError
  63. from boto.exception import BotoServerError
  64. from boto.exception import PleaseRetryException
  65. from boto.provider import Provider
  66. from boto.resultset import ResultSet
  67. HAVE_HTTPS_CONNECTION = False
  68. try:
  69. import ssl
  70. from boto import https_connection
  71. # Google App Engine runs on Python 2.5 so doesn't have ssl.SSLError.
  72. if hasattr(ssl, 'SSLError'):
  73. HAVE_HTTPS_CONNECTION = True
  74. except ImportError:
  75. pass
  76. try:
  77. import threading
  78. except ImportError:
  79. import dummy_threading as threading
  80. ON_APP_ENGINE = all(key in os.environ for key in (
  81. 'USER_IS_ADMIN', 'CURRENT_VERSION_ID', 'APPLICATION_ID'))
  82. PORTS_BY_SECURITY = {True: 443,
  83. False: 80}
  84. DEFAULT_CA_CERTS_FILE = os.path.join(os.path.dirname(os.path.abspath(boto.cacerts.__file__)), "cacerts.txt")
  85. class HostConnectionPool(object):
  86. """
  87. A pool of connections for one remote (host,port,is_secure).
  88. When connections are added to the pool, they are put into a
  89. pending queue. The _mexe method returns connections to the pool
  90. before the response body has been read, so they connections aren't
  91. ready to send another request yet. They stay in the pending queue
  92. until they are ready for another request, at which point they are
  93. returned to the pool of ready connections.
  94. The pool of ready connections is an ordered list of
  95. (connection,time) pairs, where the time is the time the connection
  96. was returned from _mexe. After a certain period of time,
  97. connections are considered stale, and discarded rather than being
  98. reused. This saves having to wait for the connection to time out
  99. if AWS has decided to close it on the other end because of
  100. inactivity.
  101. Thread Safety:
  102. This class is used only from ConnectionPool while it's mutex
  103. is held.
  104. """
  105. def __init__(self):
  106. self.queue = []
  107. def size(self):
  108. """
  109. Returns the number of connections in the pool for this host.
  110. Some of the connections may still be in use, and may not be
  111. ready to be returned by get().
  112. """
  113. return len(self.queue)
  114. def put(self, conn):
  115. """
  116. Adds a connection to the pool, along with the time it was
  117. added.
  118. """
  119. self.queue.append((conn, time.time()))
  120. def get(self):
  121. """
  122. Returns the next connection in this pool that is ready to be
  123. reused. Returns None if there aren't any.
  124. """
  125. # Discard ready connections that are too old.
  126. self.clean()
  127. # Return the first connection that is ready, and remove it
  128. # from the queue. Connections that aren't ready are returned
  129. # to the end of the queue with an updated time, on the
  130. # assumption that somebody is actively reading the response.
  131. for _ in range(len(self.queue)):
  132. (conn, _) = self.queue.pop(0)
  133. if self._conn_ready(conn):
  134. return conn
  135. else:
  136. self.put(conn)
  137. return None
  138. def _conn_ready(self, conn):
  139. """
  140. There is a nice state diagram at the top of http_client.py. It
  141. indicates that once the response headers have been read (which
  142. _mexe does before adding the connection to the pool), a
  143. response is attached to the connection, and it stays there
  144. until it's done reading. This isn't entirely true: even after
  145. the client is done reading, the response may be closed, but
  146. not removed from the connection yet.
  147. This is ugly, reading a private instance variable, but the
  148. state we care about isn't available in any public methods.
  149. """
  150. if ON_APP_ENGINE:
  151. # Google AppEngine implementation of HTTPConnection doesn't contain
  152. # _HTTPConnection__response attribute. Moreover, it's not possible
  153. # to determine if given connection is ready. Reusing connections
  154. # simply doesn't make sense with App Engine urlfetch service.
  155. return False
  156. else:
  157. response = getattr(conn, '_HTTPConnection__response', None)
  158. return (response is None) or response.isclosed()
  159. def clean(self):
  160. """
  161. Get rid of stale connections.
  162. """
  163. # Note that we do not close the connection here -- somebody
  164. # may still be reading from it.
  165. while len(self.queue) > 0 and self._pair_stale(self.queue[0]):
  166. self.queue.pop(0)
  167. def _pair_stale(self, pair):
  168. """
  169. Returns true of the (connection,time) pair is too old to be
  170. used.
  171. """
  172. (_conn, return_time) = pair
  173. now = time.time()
  174. return return_time + ConnectionPool.STALE_DURATION < now
  175. class ConnectionPool(object):
  176. """
  177. A connection pool that expires connections after a fixed period of
  178. time. This saves time spent waiting for a connection that AWS has
  179. timed out on the other end.
  180. This class is thread-safe.
  181. """
  182. #
  183. # The amout of time between calls to clean.
  184. #
  185. CLEAN_INTERVAL = 5.0
  186. #
  187. # How long before a connection becomes "stale" and won't be reused
  188. # again. The intention is that this time is less that the timeout
  189. # period that AWS uses, so we'll never try to reuse a connection
  190. # and find that AWS is timing it out.
  191. #
  192. # Experimentation in July 2011 shows that AWS starts timing things
  193. # out after three minutes. The 60 seconds here is conservative so
  194. # we should never hit that 3-minute timout.
  195. #
  196. STALE_DURATION = 60.0
  197. def __init__(self):
  198. # Mapping from (host,port,is_secure) to HostConnectionPool.
  199. # If a pool becomes empty, it is removed.
  200. self.host_to_pool = {}
  201. # The last time the pool was cleaned.
  202. self.last_clean_time = 0.0
  203. self.mutex = threading.Lock()
  204. ConnectionPool.STALE_DURATION = \
  205. config.getfloat('Boto', 'connection_stale_duration',
  206. ConnectionPool.STALE_DURATION)
  207. def __getstate__(self):
  208. pickled_dict = copy.copy(self.__dict__)
  209. pickled_dict['host_to_pool'] = {}
  210. del pickled_dict['mutex']
  211. return pickled_dict
  212. def __setstate__(self, dct):
  213. self.__init__()
  214. def size(self):
  215. """
  216. Returns the number of connections in the pool.
  217. """
  218. return sum(pool.size() for pool in self.host_to_pool.values())
  219. def get_http_connection(self, host, port, is_secure):
  220. """
  221. Gets a connection from the pool for the named host. Returns
  222. None if there is no connection that can be reused. It's the caller's
  223. responsibility to call close() on the connection when it's no longer
  224. needed.
  225. """
  226. self.clean()
  227. with self.mutex:
  228. key = (host, port, is_secure)
  229. if key not in self.host_to_pool:
  230. return None
  231. return self.host_to_pool[key].get()
  232. def put_http_connection(self, host, port, is_secure, conn):
  233. """
  234. Adds a connection to the pool of connections that can be
  235. reused for the named host.
  236. """
  237. with self.mutex:
  238. key = (host, port, is_secure)
  239. if key not in self.host_to_pool:
  240. self.host_to_pool[key] = HostConnectionPool()
  241. self.host_to_pool[key].put(conn)
  242. def clean(self):
  243. """
  244. Clean up the stale connections in all of the pools, and then
  245. get rid of empty pools. Pools clean themselves every time a
  246. connection is fetched; this cleaning takes care of pools that
  247. aren't being used any more, so nothing is being gotten from
  248. them.
  249. """
  250. with self.mutex:
  251. now = time.time()
  252. if self.last_clean_time + self.CLEAN_INTERVAL < now:
  253. to_remove = []
  254. for (host, pool) in self.host_to_pool.items():
  255. pool.clean()
  256. if pool.size() == 0:
  257. to_remove.append(host)
  258. for host in to_remove:
  259. del self.host_to_pool[host]
  260. self.last_clean_time = now
  261. class HTTPRequest(object):
  262. def __init__(self, method, protocol, host, port, path, auth_path,
  263. params, headers, body):
  264. """Represents an HTTP request.
  265. :type method: string
  266. :param method: The HTTP method name, 'GET', 'POST', 'PUT' etc.
  267. :type protocol: string
  268. :param protocol: The http protocol used, 'http' or 'https'.
  269. :type host: string
  270. :param host: Host to which the request is addressed. eg. abc.com
  271. :type port: int
  272. :param port: port on which the request is being sent. Zero means unset,
  273. in which case default port will be chosen.
  274. :type path: string
  275. :param path: URL path that is being accessed.
  276. :type auth_path: string
  277. :param path: The part of the URL path used when creating the
  278. authentication string.
  279. :type params: dict
  280. :param params: HTTP url query parameters, with key as name of
  281. the param, and value as value of param.
  282. :type headers: dict
  283. :param headers: HTTP headers, with key as name of the header and value
  284. as value of header.
  285. :type body: string
  286. :param body: Body of the HTTP request. If not present, will be None or
  287. empty string ('').
  288. """
  289. self.method = method
  290. self.protocol = protocol
  291. self.host = host
  292. self.port = port
  293. self.path = path
  294. if auth_path is None:
  295. auth_path = path
  296. self.auth_path = auth_path
  297. self.params = params
  298. # chunked Transfer-Encoding should act only on PUT request.
  299. if headers and 'Transfer-Encoding' in headers and \
  300. headers['Transfer-Encoding'] == 'chunked' and \
  301. self.method != 'PUT':
  302. self.headers = headers.copy()
  303. del self.headers['Transfer-Encoding']
  304. else:
  305. self.headers = headers
  306. self.body = body
  307. def __str__(self):
  308. return (('method:(%s) protocol:(%s) host(%s) port(%s) path(%s) '
  309. 'params(%s) headers(%s) body(%s)') % (self.method,
  310. self.protocol, self.host, self.port, self.path, self.params,
  311. self.headers, self.body))
  312. def authorize(self, connection, **kwargs):
  313. if not getattr(self, '_headers_quoted', False):
  314. for key in self.headers:
  315. val = self.headers[key]
  316. if isinstance(val, six.text_type):
  317. safe = '!"#$%&\'()*+,/:;<=>?@[\\]^`{|}~ '
  318. self.headers[key] = quote(val.encode('utf-8'), safe)
  319. setattr(self, '_headers_quoted', True)
  320. self.headers['User-Agent'] = UserAgent
  321. connection._auth_handler.add_auth(self, **kwargs)
  322. # I'm not sure if this is still needed, now that add_auth is
  323. # setting the content-length for POST requests.
  324. if 'Content-Length' not in self.headers:
  325. if 'Transfer-Encoding' not in self.headers or \
  326. self.headers['Transfer-Encoding'] != 'chunked':
  327. self.headers['Content-Length'] = str(len(self.body))
  328. class HTTPResponse(http_client.HTTPResponse):
  329. def __init__(self, *args, **kwargs):
  330. http_client.HTTPResponse.__init__(self, *args, **kwargs)
  331. self._cached_response = ''
  332. def read(self, amt=None):
  333. """Read the response.
  334. This method does not have the same behavior as
  335. http_client.HTTPResponse.read. Instead, if this method is called with
  336. no ``amt`` arg, then the response body will be cached. Subsequent
  337. calls to ``read()`` with no args **will return the cached response**.
  338. """
  339. if amt is None:
  340. # The reason for doing this is that many places in boto call
  341. # response.read() and except to get the response body that they
  342. # can then process. To make sure this always works as they expect
  343. # we're caching the response so that multiple calls to read()
  344. # will return the full body. Note that this behavior only
  345. # happens if the amt arg is not specified.
  346. if not self._cached_response:
  347. self._cached_response = http_client.HTTPResponse.read(self)
  348. return self._cached_response
  349. else:
  350. return http_client.HTTPResponse.read(self, amt)
  351. class AWSAuthConnection(object):
  352. def __init__(self, host, aws_access_key_id=None,
  353. aws_secret_access_key=None,
  354. is_secure=True, port=None, proxy=None, proxy_port=None,
  355. proxy_user=None, proxy_pass=None, debug=0,
  356. https_connection_factory=None, path='/',
  357. provider='aws', security_token=None,
  358. suppress_consec_slashes=True,
  359. validate_certs=True, profile_name=None):
  360. """
  361. :type host: str
  362. :param host: The host to make the connection to
  363. :keyword str aws_access_key_id: Your AWS Access Key ID (provided by
  364. Amazon). If none is specified, the value in your
  365. ``AWS_ACCESS_KEY_ID`` environmental variable is used.
  366. :keyword str aws_secret_access_key: Your AWS Secret Access Key
  367. (provided by Amazon). If none is specified, the value in your
  368. ``AWS_SECRET_ACCESS_KEY`` environmental variable is used.
  369. :keyword str security_token: The security token associated with
  370. temporary credentials issued by STS. Optional unless using
  371. temporary credentials. If none is specified, the environment
  372. variable ``AWS_SECURITY_TOKEN`` is used if defined.
  373. :type is_secure: boolean
  374. :param is_secure: Whether the connection is over SSL
  375. :type https_connection_factory: list or tuple
  376. :param https_connection_factory: A pair of an HTTP connection
  377. factory and the exceptions to catch. The factory should have
  378. a similar interface to L{http_client.HTTPSConnection}.
  379. :param str proxy: Address/hostname for a proxy server
  380. :type proxy_port: int
  381. :param proxy_port: The port to use when connecting over a proxy
  382. :type proxy_user: str
  383. :param proxy_user: The username to connect with on the proxy
  384. :type proxy_pass: str
  385. :param proxy_pass: The password to use when connection over a proxy.
  386. :type port: int
  387. :param port: The port to use to connect
  388. :type suppress_consec_slashes: bool
  389. :param suppress_consec_slashes: If provided, controls whether
  390. consecutive slashes will be suppressed in key paths.
  391. :type validate_certs: bool
  392. :param validate_certs: Controls whether SSL certificates
  393. will be validated or not. Defaults to True.
  394. :type profile_name: str
  395. :param profile_name: Override usual Credentials section in config
  396. file to use a named set of keys instead.
  397. """
  398. self.suppress_consec_slashes = suppress_consec_slashes
  399. self.num_retries = 6
  400. # Override passed-in is_secure setting if value was defined in config.
  401. if config.has_option('Boto', 'is_secure'):
  402. is_secure = config.getboolean('Boto', 'is_secure')
  403. self.is_secure = is_secure
  404. # Whether or not to validate server certificates.
  405. # The default is now to validate certificates. This can be
  406. # overridden in the boto config file are by passing an
  407. # explicit validate_certs parameter to the class constructor.
  408. self.https_validate_certificates = config.getbool(
  409. 'Boto', 'https_validate_certificates',
  410. validate_certs)
  411. if self.https_validate_certificates and not HAVE_HTTPS_CONNECTION:
  412. raise BotoClientError(
  413. "SSL server certificate validation is enabled in boto "
  414. "configuration, but Python dependencies required to "
  415. "support this feature are not available. Certificate "
  416. "validation is only supported when running under Python "
  417. "2.6 or later.")
  418. certs_file = config.get_value(
  419. 'Boto', 'ca_certificates_file', DEFAULT_CA_CERTS_FILE)
  420. if certs_file == 'system':
  421. certs_file = None
  422. self.ca_certificates_file = certs_file
  423. if port:
  424. self.port = port
  425. else:
  426. self.port = PORTS_BY_SECURITY[is_secure]
  427. self.handle_proxy(proxy, proxy_port, proxy_user, proxy_pass)
  428. # define exceptions from http_client that we want to catch and retry
  429. self.http_exceptions = (http_client.HTTPException, socket.error,
  430. socket.gaierror, http_client.BadStatusLine)
  431. # define subclasses of the above that are not retryable.
  432. self.http_unretryable_exceptions = []
  433. if HAVE_HTTPS_CONNECTION:
  434. self.http_unretryable_exceptions.append(
  435. https_connection.InvalidCertificateException)
  436. # define values in socket exceptions we don't want to catch
  437. self.socket_exception_values = (errno.EINTR,)
  438. if https_connection_factory is not None:
  439. self.https_connection_factory = https_connection_factory[0]
  440. self.http_exceptions += https_connection_factory[1]
  441. else:
  442. self.https_connection_factory = None
  443. if (is_secure):
  444. self.protocol = 'https'
  445. else:
  446. self.protocol = 'http'
  447. self.host = host
  448. self.path = path
  449. # if the value passed in for debug
  450. if not isinstance(debug, six.integer_types):
  451. debug = 0
  452. self.debug = config.getint('Boto', 'debug', debug)
  453. self.host_header = None
  454. # Timeout used to tell http_client how long to wait for socket timeouts.
  455. # Default is to leave timeout unchanged, which will in turn result in
  456. # the socket's default global timeout being used. To specify a
  457. # timeout, set http_socket_timeout in Boto config. Regardless,
  458. # timeouts will only be applied if Python is 2.6 or greater.
  459. self.http_connection_kwargs = {}
  460. if (sys.version_info[0], sys.version_info[1]) >= (2, 6):
  461. # If timeout isn't defined in boto config file, use 70 second
  462. # default as recommended by
  463. # http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForActivityTask.html
  464. self.http_connection_kwargs['timeout'] = config.getint(
  465. 'Boto', 'http_socket_timeout', 70)
  466. if isinstance(provider, Provider):
  467. # Allow overriding Provider
  468. self.provider = provider
  469. else:
  470. self._provider_type = provider
  471. self.provider = Provider(self._provider_type,
  472. aws_access_key_id,
  473. aws_secret_access_key,
  474. security_token,
  475. profile_name)
  476. # Allow config file to override default host, port, and host header.
  477. if self.provider.host:
  478. self.host = self.provider.host
  479. if self.provider.port:
  480. self.port = self.provider.port
  481. if self.provider.host_header:
  482. self.host_header = self.provider.host_header
  483. self._pool = ConnectionPool()
  484. self._connection = (self.host, self.port, self.is_secure)
  485. self._last_rs = None
  486. self._auth_handler = auth.get_auth_handler(
  487. host, config, self.provider, self._required_auth_capability())
  488. if getattr(self, 'AuthServiceName', None) is not None:
  489. self.auth_service_name = self.AuthServiceName
  490. self.request_hook = None
  491. def __repr__(self):
  492. return '%s:%s' % (self.__class__.__name__, self.host)
  493. def _required_auth_capability(self):
  494. return []
  495. def _get_auth_service_name(self):
  496. return getattr(self._auth_handler, 'service_name')
  497. # For Sigv4, the auth_service_name/auth_region_name properties allow
  498. # the service_name/region_name to be explicitly set instead of being
  499. # derived from the endpoint url.
  500. def _set_auth_service_name(self, value):
  501. self._auth_handler.service_name = value
  502. auth_service_name = property(_get_auth_service_name, _set_auth_service_name)
  503. def _get_auth_region_name(self):
  504. return getattr(self._auth_handler, 'region_name')
  505. def _set_auth_region_name(self, value):
  506. self._auth_handler.region_name = value
  507. auth_region_name = property(_get_auth_region_name, _set_auth_region_name)
  508. def connection(self):
  509. return self.get_http_connection(*self._connection)
  510. connection = property(connection)
  511. def aws_access_key_id(self):
  512. return self.provider.access_key
  513. aws_access_key_id = property(aws_access_key_id)
  514. gs_access_key_id = aws_access_key_id
  515. access_key = aws_access_key_id
  516. def aws_secret_access_key(self):
  517. return self.provider.secret_key
  518. aws_secret_access_key = property(aws_secret_access_key)
  519. gs_secret_access_key = aws_secret_access_key
  520. secret_key = aws_secret_access_key
  521. def profile_name(self):
  522. return self.provider.profile_name
  523. profile_name = property(profile_name)
  524. def get_path(self, path='/'):
  525. # The default behavior is to suppress consecutive slashes for reasons
  526. # discussed at
  527. # https://groups.google.com/forum/#!topic/boto-dev/-ft0XPUy0y8
  528. # You can override that behavior with the suppress_consec_slashes param.
  529. if not self.suppress_consec_slashes:
  530. return self.path + re.sub('^(/*)/', "\\1", path)
  531. pos = path.find('?')
  532. if pos >= 0:
  533. params = path[pos:]
  534. path = path[:pos]
  535. else:
  536. params = None
  537. if path[-1] == '/':
  538. need_trailing = True
  539. else:
  540. need_trailing = False
  541. path_elements = self.path.split('/')
  542. path_elements.extend(path.split('/'))
  543. path_elements = [p for p in path_elements if p]
  544. path = '/' + '/'.join(path_elements)
  545. if path[-1] != '/' and need_trailing:
  546. path += '/'
  547. if params:
  548. path = path + params
  549. return path
  550. def server_name(self, port=None):
  551. if not port:
  552. port = self.port
  553. if port == 80:
  554. signature_host = self.host
  555. else:
  556. # This unfortunate little hack can be attributed to
  557. # a difference in the 2.6 version of http_client. In old
  558. # versions, it would append ":443" to the hostname sent
  559. # in the Host header and so we needed to make sure we
  560. # did the same when calculating the V2 signature. In 2.6
  561. # (and higher!)
  562. # it no longer does that. Hence, this kludge.
  563. if ((ON_APP_ENGINE and sys.version[:3] == '2.5') or
  564. sys.version[:3] in ('2.6', '2.7')) and port == 443:
  565. signature_host = self.host
  566. else:
  567. signature_host = '%s:%d' % (self.host, port)
  568. return signature_host
  569. def handle_proxy(self, proxy, proxy_port, proxy_user, proxy_pass):
  570. self.proxy = proxy
  571. self.proxy_port = proxy_port
  572. self.proxy_user = proxy_user
  573. self.proxy_pass = proxy_pass
  574. if 'http_proxy' in os.environ and not self.proxy:
  575. pattern = re.compile(
  576. '(?:http://)?'
  577. '(?:(?P<user>[\w\-\.]+):(?P<pass>.*)@)?'
  578. '(?P<host>[\w\-\.]+)'
  579. '(?::(?P<port>\d+))?'
  580. )
  581. match = pattern.match(os.environ['http_proxy'])
  582. if match:
  583. self.proxy = match.group('host')
  584. self.proxy_port = match.group('port')
  585. self.proxy_user = match.group('user')
  586. self.proxy_pass = match.group('pass')
  587. else:
  588. if not self.proxy:
  589. self.proxy = config.get_value('Boto', 'proxy', None)
  590. if not self.proxy_port:
  591. self.proxy_port = config.get_value('Boto', 'proxy_port', None)
  592. if not self.proxy_user:
  593. self.proxy_user = config.get_value('Boto', 'proxy_user', None)
  594. if not self.proxy_pass:
  595. self.proxy_pass = config.get_value('Boto', 'proxy_pass', None)
  596. if not self.proxy_port and self.proxy:
  597. print("http_proxy environment variable does not specify "
  598. "a port, using default")
  599. self.proxy_port = self.port
  600. self.no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
  601. self.use_proxy = (self.proxy is not None)
  602. def get_http_connection(self, host, port, is_secure):
  603. conn = self._pool.get_http_connection(host, port, is_secure)
  604. if conn is not None:
  605. return conn
  606. else:
  607. return self.new_http_connection(host, port, is_secure)
  608. def skip_proxy(self, host):
  609. if not self.no_proxy:
  610. return False
  611. if self.no_proxy == "*":
  612. return True
  613. hostonly = host
  614. hostonly = host.split(':')[0]
  615. for name in self.no_proxy.split(','):
  616. if name and (hostonly.endswith(name) or host.endswith(name)):
  617. return True
  618. return False
  619. def new_http_connection(self, host, port, is_secure):
  620. if host is None:
  621. host = self.server_name()
  622. # Make sure the host is really just the host, not including
  623. # the port number
  624. host = boto.utils.parse_host(host)
  625. http_connection_kwargs = self.http_connection_kwargs.copy()
  626. # Connection factories below expect a port keyword argument
  627. http_connection_kwargs['port'] = port
  628. # Override host with proxy settings if needed
  629. if self.use_proxy and not is_secure and \
  630. not self.skip_proxy(host):
  631. host = self.proxy
  632. http_connection_kwargs['port'] = int(self.proxy_port)
  633. if is_secure:
  634. boto.log.debug(
  635. 'establishing HTTPS connection: host=%s, kwargs=%s',
  636. host, http_connection_kwargs)
  637. if self.use_proxy and not self.skip_proxy(host):
  638. connection = self.proxy_ssl(host, is_secure and 443 or 80)
  639. elif self.https_connection_factory:
  640. connection = self.https_connection_factory(host)
  641. elif self.https_validate_certificates and HAVE_HTTPS_CONNECTION:
  642. connection = https_connection.CertValidatingHTTPSConnection(
  643. host, ca_certs=self.ca_certificates_file,
  644. **http_connection_kwargs)
  645. else:
  646. connection = http_client.HTTPSConnection(
  647. host, **http_connection_kwargs)
  648. else:
  649. boto.log.debug('establishing HTTP connection: kwargs=%s' %
  650. http_connection_kwargs)
  651. if self.https_connection_factory:
  652. # even though the factory says https, this is too handy
  653. # to not be able to allow overriding for http also.
  654. connection = self.https_connection_factory(
  655. host, **http_connection_kwargs)
  656. else:
  657. connection = http_client.HTTPConnection(
  658. host, **http_connection_kwargs)
  659. if self.debug > 1:
  660. connection.set_debuglevel(self.debug)
  661. # self.connection must be maintained for backwards-compatibility
  662. # however, it must be dynamically pulled from the connection pool
  663. # set a private variable which will enable that
  664. if host.split(':')[0] == self.host and is_secure == self.is_secure:
  665. self._connection = (host, port, is_secure)
  666. # Set the response class of the http connection to use our custom
  667. # class.
  668. connection.response_class = HTTPResponse
  669. return connection
  670. def put_http_connection(self, host, port, is_secure, connection):
  671. self._pool.put_http_connection(host, port, is_secure, connection)
  672. def proxy_ssl(self, host=None, port=None):
  673. if host and port:
  674. host = '%s:%d' % (host, port)
  675. else:
  676. host = '%s:%d' % (self.host, self.port)
  677. # Seems properly to use timeout for connect too
  678. timeout = self.http_connection_kwargs.get("timeout")
  679. if timeout is not None:
  680. sock = socket.create_connection((self.proxy,
  681. int(self.proxy_port)), timeout)
  682. else:
  683. sock = socket.create_connection((self.proxy, int(self.proxy_port)))
  684. boto.log.debug("Proxy connection: CONNECT %s HTTP/1.0\r\n", host)
  685. sock.sendall("CONNECT %s HTTP/1.0\r\n" % host)
  686. sock.sendall("User-Agent: %s\r\n" % UserAgent)
  687. if self.proxy_user and self.proxy_pass:
  688. for k, v in self.get_proxy_auth_header().items():
  689. sock.sendall("%s: %s\r\n" % (k, v))
  690. # See discussion about this config option at
  691. # https://groups.google.com/forum/?fromgroups#!topic/boto-dev/teenFvOq2Cc
  692. if config.getbool('Boto', 'send_crlf_after_proxy_auth_headers', False):
  693. sock.sendall("\r\n")
  694. else:
  695. sock.sendall("\r\n")
  696. resp = http_client.HTTPResponse(sock, strict=True, debuglevel=self.debug)
  697. resp.begin()
  698. if resp.status != 200:
  699. # Fake a socket error, use a code that make it obvious it hasn't
  700. # been generated by the socket library
  701. raise socket.error(-71,
  702. "Error talking to HTTP proxy %s:%s: %s (%s)" %
  703. (self.proxy, self.proxy_port,
  704. resp.status, resp.reason))
  705. # We can safely close the response, it duped the original socket
  706. resp.close()
  707. h = http_client.HTTPConnection(host)
  708. if self.https_validate_certificates and HAVE_HTTPS_CONNECTION:
  709. msg = "wrapping ssl socket for proxied connection; "
  710. if self.ca_certificates_file:
  711. msg += "CA certificate file=%s" % self.ca_certificates_file
  712. else:
  713. msg += "using system provided SSL certs"
  714. boto.log.debug(msg)
  715. key_file = self.http_connection_kwargs.get('key_file', None)
  716. cert_file = self.http_connection_kwargs.get('cert_file', None)
  717. sslSock = ssl.wrap_socket(sock, keyfile=key_file,
  718. certfile=cert_file,
  719. cert_reqs=ssl.CERT_REQUIRED,
  720. ca_certs=self.ca_certificates_file)
  721. cert = sslSock.getpeercert()
  722. hostname = self.host.split(':', 0)[0]
  723. if not https_connection.ValidateCertificateHostname(cert, hostname):
  724. raise https_connection.InvalidCertificateException(
  725. hostname, cert, 'hostname mismatch')
  726. else:
  727. # Fallback for old Python without ssl.wrap_socket
  728. if hasattr(http_client, 'ssl'):
  729. sslSock = http_client.ssl.SSLSocket(sock)
  730. else:
  731. sslSock = socket.ssl(sock, None, None)
  732. sslSock = http_client.FakeSocket(sock, sslSock)
  733. # This is a bit unclean
  734. h.sock = sslSock
  735. return h
  736. def prefix_proxy_to_path(self, path, host=None):
  737. path = self.protocol + '://' + (host or self.server_name()) + path
  738. return path
  739. def get_proxy_auth_header(self):
  740. auth = encodebytes(self.proxy_user + ':' + self.proxy_pass)
  741. return {'Proxy-Authorization': 'Basic %s' % auth}
  742. # For passing proxy information to other connection libraries, e.g. cloudsearch2
  743. def get_proxy_url_with_auth(self):
  744. if not self.use_proxy:
  745. return None
  746. if self.proxy_user or self.proxy_pass:
  747. if self.proxy_pass:
  748. login_info = '%s:%s@' % (self.proxy_user, self.proxy_pass)
  749. else:
  750. login_info = '%s@' % self.proxy_user
  751. else:
  752. login_info = ''
  753. return 'http://%s%s:%s' % (login_info, self.proxy, str(self.proxy_port or self.port))
  754. def set_host_header(self, request):
  755. try:
  756. request.headers['Host'] = \
  757. self._auth_handler.host_header(self.host, request)
  758. except AttributeError:
  759. request.headers['Host'] = self.host.split(':', 1)[0]
  760. def set_request_hook(self, hook):
  761. self.request_hook = hook
  762. def _mexe(self, request, sender=None, override_num_retries=None,
  763. retry_handler=None):
  764. """
  765. mexe - Multi-execute inside a loop, retrying multiple times to handle
  766. transient Internet errors by simply trying again.
  767. Also handles redirects.
  768. This code was inspired by the S3Utils classes posted to the boto-users
  769. Google group by Larry Bates. Thanks!
  770. """
  771. boto.log.debug('Method: %s' % request.method)
  772. boto.log.debug('Path: %s' % request.path)
  773. boto.log.debug('Data: %s' % request.body)
  774. boto.log.debug('Headers: %s' % request.headers)
  775. boto.log.debug('Host: %s' % request.host)
  776. boto.log.debug('Port: %s' % request.port)
  777. boto.log.debug('Params: %s' % request.params)
  778. response = None
  779. body = None
  780. ex = None
  781. if override_num_retries is None:
  782. num_retries = config.getint('Boto', 'num_retries', self.num_retries)
  783. else:
  784. num_retries = override_num_retries
  785. i = 0
  786. connection = self.get_http_connection(request.host, request.port,
  787. self.is_secure)
  788. # Convert body to bytes if needed
  789. if not isinstance(request.body, bytes) and hasattr(request.body,
  790. 'encode'):
  791. request.body = request.body.encode('utf-8')
  792. while i <= num_retries:
  793. # Use binary exponential backoff to desynchronize client requests.
  794. next_sleep = min(random.random() * (2 ** i),
  795. boto.config.get('Boto', 'max_retry_delay', 60))
  796. try:
  797. # we now re-sign each request before it is retried
  798. boto.log.debug('Token: %s' % self.provider.security_token)
  799. request.authorize(connection=self)
  800. # Only force header for non-s3 connections, because s3 uses
  801. # an older signing method + bucket resource URLs that include
  802. # the port info. All others should be now be up to date and
  803. # not include the port.
  804. if 's3' not in self._required_auth_capability():
  805. if not getattr(self, 'anon', False):
  806. if not request.headers.get('Host'):
  807. self.set_host_header(request)
  808. boto.log.debug('Final headers: %s' % request.headers)
  809. request.start_time = datetime.now()
  810. if callable(sender):
  811. response = sender(connection, request.method, request.path,
  812. request.body, request.headers)
  813. else:
  814. connection.request(request.method, request.path,
  815. request.body, request.headers)
  816. response = connection.getresponse()
  817. boto.log.debug('Response headers: %s' % response.getheaders())
  818. location = response.getheader('location')
  819. # -- gross hack --
  820. # http_client gets confused with chunked responses to HEAD requests
  821. # so I have to fake it out
  822. if request.method == 'HEAD' and getattr(response,
  823. 'chunked', False):
  824. response.chunked = 0
  825. if callable(retry_handler):
  826. status = retry_handler(response, i, next_sleep)
  827. if status:
  828. msg, i, next_sleep = status
  829. if msg:
  830. boto.log.debug(msg)
  831. time.sleep(next_sleep)
  832. continue
  833. if response.status in [500, 502, 503, 504]:
  834. msg = 'Received %d response. ' % response.status
  835. msg += 'Retrying in %3.1f seconds' % next_sleep
  836. boto.log.debug(msg)
  837. body = response.read()
  838. if isinstance(body, bytes):
  839. body = body.decode('utf-8')
  840. elif response.status < 300 or response.status >= 400 or \
  841. not location:
  842. # don't return connection to the pool if response contains
  843. # Connection:close header, because the connection has been
  844. # closed and default reconnect behavior may do something
  845. # different than new_http_connection. Also, it's probably
  846. # less efficient to try to reuse a closed connection.
  847. conn_header_value = response.getheader('connection')
  848. if conn_header_value == 'close':
  849. connection.close()
  850. else:
  851. self.put_http_connection(request.host, request.port,
  852. self.is_secure, connection)
  853. if self.request_hook is not None:
  854. self.request_hook.handle_request_data(request, response)
  855. return response
  856. else:
  857. scheme, request.host, request.path, \
  858. params, query, fragment = urlparse(location)
  859. if query:
  860. request.path += '?' + query
  861. # urlparse can return both host and port in netloc, so if
  862. # that's the case we need to split them up properly
  863. if ':' in request.host:
  864. request.host, request.port = request.host.split(':', 1)
  865. msg = 'Redirecting: %s' % scheme + '://'
  866. msg += request.host + request.path
  867. boto.log.debug(msg)
  868. connection = self.get_http_connection(request.host,
  869. request.port,
  870. scheme == 'https')
  871. response = None
  872. continue
  873. except PleaseRetryException as e:
  874. boto.log.debug('encountered a retry exception: %s' % e)
  875. connection = self.new_http_connection(request.host, request.port,
  876. self.is_secure)
  877. response = e.response
  878. ex = e
  879. except self.http_exceptions as e:
  880. for unretryable in self.http_unretryable_exceptions:
  881. if isinstance(e, unretryable):
  882. boto.log.debug(
  883. 'encountered unretryable %s exception, re-raising' %
  884. e.__class__.__name__)
  885. raise
  886. boto.log.debug('encountered %s exception, reconnecting' %
  887. e.__class__.__name__)
  888. connection = self.new_http_connection(request.host, request.port,
  889. self.is_secure)
  890. ex = e
  891. time.sleep(next_sleep)
  892. i += 1
  893. # If we made it here, it's because we have exhausted our retries
  894. # and stil haven't succeeded. So, if we have a response object,
  895. # use it to raise an exception.
  896. # Otherwise, raise the exception that must have already happened.
  897. if self.request_hook is not None:
  898. self.request_hook.handle_request_data(request, response, error=True)
  899. if response:
  900. raise BotoServerError(response.status, response.reason, body)
  901. elif ex:
  902. raise ex
  903. else:
  904. msg = 'Please report this exception as a Boto Issue!'
  905. raise BotoClientError(msg)
  906. def build_base_http_request(self, method, path, auth_path,
  907. params=None, headers=None, data='', host=None):
  908. path = self.get_path(path)
  909. if auth_path is not None:
  910. auth_path = self.get_path(auth_path)
  911. if params is None:
  912. params = {}
  913. else:
  914. params = params.copy()
  915. if headers is None:
  916. headers = {}
  917. else:
  918. headers = headers.copy()
  919. if self.host_header and not boto.utils.find_matching_headers('host', headers):
  920. headers['host'] = self.host_header
  921. host = host or self.host
  922. if self.use_proxy and not self.skip_proxy(host):
  923. if not auth_path:
  924. auth_path = path
  925. path = self.prefix_proxy_to_path(path, host)
  926. if self.proxy_user and self.proxy_pass and not self.is_secure:
  927. # If is_secure, we don't have to set the proxy authentication
  928. # header here, we did that in the CONNECT to the proxy.
  929. headers.update(self.get_proxy_auth_header())
  930. return HTTPRequest(method, self.protocol, host, self.port,
  931. path, auth_path, params, headers, data)
  932. def make_request(self, method, path, headers=None, data='', host=None,
  933. auth_path=None, sender=None, override_num_retries=None,
  934. params=None, retry_handler=None):
  935. """Makes a request to the server, with stock multiple-retry logic."""
  936. if params is None:
  937. params = {}
  938. http_request = self.build_base_http_request(method, path, auth_path,
  939. params, headers, data, host)
  940. return self._mexe(http_request, sender, override_num_retries,
  941. retry_handler=retry_handler)
  942. def close(self):
  943. """(Optional) Close any open HTTP connections. This is non-destructive,
  944. and making a new request will open a connection again."""
  945. boto.log.debug('closing all HTTP connections')
  946. self._connection = None # compat field
  947. class AWSQueryConnection(AWSAuthConnection):
  948. APIVersion = ''
  949. ResponseError = BotoServerError
  950. def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
  951. is_secure=True, port=None, proxy=None, proxy_port=None,
  952. proxy_user=None, proxy_pass=None, host=None, debug=0,
  953. https_connection_factory=None, path='/', security_token=None,
  954. validate_certs=True, profile_name=None, provider='aws'):
  955. super(AWSQueryConnection, self).__init__(
  956. host, aws_access_key_id,
  957. aws_secret_access_key,
  958. is_secure, port, proxy,
  959. proxy_port, proxy_user, proxy_pass,
  960. debug, https_connection_factory, path,
  961. security_token=security_token,
  962. validate_certs=validate_certs,
  963. profile_name=profile_name,
  964. provider=provider)
  965. def _required_auth_capability(self):
  966. return []
  967. def get_utf8_value(self, value):
  968. return boto.utils.get_utf8_value(value)
  969. def make_request(self, action, params=None, path='/', verb='GET'):
  970. http_request = self.build_base_http_request(verb, path, None,
  971. params, {}, '',
  972. self.host)
  973. if action:
  974. http_request.params['Action'] = action
  975. if self.APIVersion:
  976. http_request.params['Version'] = self.APIVersion
  977. return self._mexe(http_request)
  978. def build_list_params(self, params, items, label):
  979. if isinstance(items, six.string_types):
  980. items = [items]
  981. for i in range(1, len(items) + 1):
  982. params['%s.%d' % (label, i)] = items[i - 1]
  983. def build_complex_list_params(self, params, items, label, names):
  984. """Serialize a list of structures.
  985. For example::
  986. items = [('foo', 'bar', 'baz'), ('foo2', 'bar2', 'baz2')]
  987. label = 'ParamName.member'
  988. names = ('One', 'Two', 'Three')
  989. self.build_complex_list_params(params, items, label, names)
  990. would result in the params dict being updated with these params::
  991. ParamName.member.1.One = foo
  992. ParamName.member.1.Two = bar
  993. ParamName.member.1.Three = baz
  994. ParamName.member.2.One = foo2
  995. ParamName.member.2.Two = bar2
  996. ParamName.member.2.Three = baz2
  997. :type params: dict
  998. :param params: The params dict. The complex list params
  999. will be added to this dict.
  1000. :type items: list of tuples
  1001. :param items: The list to serialize.
  1002. :type label: string
  1003. :param label: The prefix to apply to the parameter.
  1004. :type names: tuple of strings
  1005. :param names: The names associated with each tuple element.
  1006. """
  1007. for i, item in enumerate(items, 1):
  1008. current_prefix = '%s.%s' % (label, i)
  1009. for key, value in zip(names, item):
  1010. full_key = '%s.%s' % (current_prefix, key)
  1011. params[full_key] = value
  1012. # generics
  1013. def get_list(self, action, params, markers, path='/',
  1014. parent=None, verb='GET'):
  1015. if not parent:
  1016. parent = self
  1017. response = self.make_request(action, params, path, verb)
  1018. body = response.read()
  1019. boto.log.debug(body)
  1020. if not body:
  1021. boto.log.error('Null body %s' % body)
  1022. raise self.ResponseError(response.status, response.reason, body)
  1023. elif response.status == 200:
  1024. rs = ResultSet(markers)
  1025. h = boto.handler.XmlHandler(rs, parent)
  1026. if isinstance(body, six.text_type):
  1027. body = body.encode('utf-8')
  1028. xml.sax.parseString(body, h)
  1029. return rs
  1030. else:
  1031. boto.log.error('%s %s' % (response.status, response.reason))
  1032. boto.log.error('%s' % body)
  1033. raise self.ResponseError(response.status, response.reason, body)
  1034. def get_object(self, action, params, cls, path='/',
  1035. parent=None, verb='GET'):
  1036. if not parent:
  1037. parent = self
  1038. response = self.make_request(action, params, path, verb)
  1039. body = response.read()
  1040. boto.log.debug(body)
  1041. if not body:
  1042. boto.log.error('Null body %s' % body)
  1043. raise self.ResponseError(response.status, response.reason, body)
  1044. elif response.status == 200:
  1045. obj = cls(parent)
  1046. h = boto.handler.XmlHandler(obj, parent)
  1047. if isinstance(body, six.text_type):
  1048. body = body.encode('utf-8')
  1049. xml.sax.parseString(body, h)
  1050. return obj
  1051. else:
  1052. boto.log.error('%s %s' % (response.status, response.reason))
  1053. boto.log.error('%s' % body)
  1054. raise self.ResponseError(response.status, response.reason, body)
  1055. def get_status(self, action, params, path='/', parent=None, verb='GET'):
  1056. if not parent:
  1057. parent = self
  1058. response = self.make_request(action, params, path, verb)
  1059. body = response.read()
  1060. boto.log.debug(body)
  1061. if not body:
  1062. boto.log.error('Null body %s' % body)
  1063. raise self.ResponseError(response.status, response.reason, body)
  1064. elif response.status == 200:
  1065. rs = ResultSet()
  1066. h = boto.handler.XmlHandler(rs, parent)
  1067. xml.sax.parseString(body, h)
  1068. return rs.status
  1069. else:
  1070. boto.log.error('%s %s' % (response.status, response.reason))
  1071. boto.log.error('%s' % body)
  1072. raise self.ResponseError(response.status, response.reason, body)