connection.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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. if not self.headers.get('User-Agent'):
  321. self.headers['User-Agent'] = UserAgent
  322. connection._auth_handler.add_auth(self, **kwargs)
  323. # I'm not sure if this is still needed, now that add_auth is
  324. # setting the content-length for POST requests.
  325. if 'Content-Length' not in self.headers:
  326. if 'Transfer-Encoding' not in self.headers or \
  327. self.headers['Transfer-Encoding'] != 'chunked':
  328. self.headers['Content-Length'] = str(len(self.body))
  329. class HTTPResponse(http_client.HTTPResponse):
  330. def __init__(self, *args, **kwargs):
  331. http_client.HTTPResponse.__init__(self, *args, **kwargs)
  332. self._cached_response = ''
  333. def read(self, amt=None):
  334. """Read the response.
  335. This method does not have the same behavior as
  336. http_client.HTTPResponse.read. Instead, if this method is called with
  337. no ``amt`` arg, then the response body will be cached. Subsequent
  338. calls to ``read()`` with no args **will return the cached response**.
  339. """
  340. if amt is None:
  341. # The reason for doing this is that many places in boto call
  342. # response.read() and except to get the response body that they
  343. # can then process. To make sure this always works as they expect
  344. # we're caching the response so that multiple calls to read()
  345. # will return the full body. Note that this behavior only
  346. # happens if the amt arg is not specified.
  347. if not self._cached_response:
  348. self._cached_response = http_client.HTTPResponse.read(self)
  349. return self._cached_response
  350. else:
  351. return http_client.HTTPResponse.read(self, amt)
  352. class AWSAuthConnection(object):
  353. def __init__(self, host, aws_access_key_id=None,
  354. aws_secret_access_key=None,
  355. is_secure=True, port=None, proxy=None, proxy_port=None,
  356. proxy_user=None, proxy_pass=None, debug=0,
  357. https_connection_factory=None, path='/',
  358. provider='aws', security_token=None,
  359. suppress_consec_slashes=True,
  360. validate_certs=True, profile_name=None):
  361. """
  362. :type host: str
  363. :param host: The host to make the connection to
  364. :keyword str aws_access_key_id: Your AWS Access Key ID (provided by
  365. Amazon). If none is specified, the value in your
  366. ``AWS_ACCESS_KEY_ID`` environmental variable is used.
  367. :keyword str aws_secret_access_key: Your AWS Secret Access Key
  368. (provided by Amazon). If none is specified, the value in your
  369. ``AWS_SECRET_ACCESS_KEY`` environmental variable is used.
  370. :keyword str security_token: The security token associated with
  371. temporary credentials issued by STS. Optional unless using
  372. temporary credentials. If none is specified, the environment
  373. variable ``AWS_SECURITY_TOKEN`` is used if defined.
  374. :type is_secure: boolean
  375. :param is_secure: Whether the connection is over SSL
  376. :type https_connection_factory: list or tuple
  377. :param https_connection_factory: A pair of an HTTP connection
  378. factory and the exceptions to catch. The factory should have
  379. a similar interface to L{http_client.HTTPSConnection}.
  380. :param str proxy: Address/hostname for a proxy server
  381. :type proxy_port: int
  382. :param proxy_port: The port to use when connecting over a proxy
  383. :type proxy_user: str
  384. :param proxy_user: The username to connect with on the proxy
  385. :type proxy_pass: str
  386. :param proxy_pass: The password to use when connection over a proxy.
  387. :type port: int
  388. :param port: The port to use to connect
  389. :type suppress_consec_slashes: bool
  390. :param suppress_consec_slashes: If provided, controls whether
  391. consecutive slashes will be suppressed in key paths.
  392. :type validate_certs: bool
  393. :param validate_certs: Controls whether SSL certificates
  394. will be validated or not. Defaults to True.
  395. :type profile_name: str
  396. :param profile_name: Override usual Credentials section in config
  397. file to use a named set of keys instead.
  398. """
  399. self.suppress_consec_slashes = suppress_consec_slashes
  400. self.num_retries = 6
  401. # Override passed-in is_secure setting if value was defined in config.
  402. if config.has_option('Boto', 'is_secure'):
  403. is_secure = config.getboolean('Boto', 'is_secure')
  404. self.is_secure = is_secure
  405. # Whether or not to validate server certificates.
  406. # The default is now to validate certificates. This can be
  407. # overridden in the boto config file are by passing an
  408. # explicit validate_certs parameter to the class constructor.
  409. self.https_validate_certificates = config.getbool(
  410. 'Boto', 'https_validate_certificates',
  411. validate_certs)
  412. if self.https_validate_certificates and not HAVE_HTTPS_CONNECTION:
  413. raise BotoClientError(
  414. "SSL server certificate validation is enabled in boto "
  415. "configuration, but Python dependencies required to "
  416. "support this feature are not available. Certificate "
  417. "validation is only supported when running under Python "
  418. "2.6 or later.")
  419. certs_file = config.get_value(
  420. 'Boto', 'ca_certificates_file', DEFAULT_CA_CERTS_FILE)
  421. if certs_file == 'system':
  422. certs_file = None
  423. self.ca_certificates_file = certs_file
  424. if port:
  425. self.port = port
  426. else:
  427. self.port = PORTS_BY_SECURITY[is_secure]
  428. self.handle_proxy(proxy, proxy_port, proxy_user, proxy_pass)
  429. # define exceptions from http_client that we want to catch and retry
  430. self.http_exceptions = (http_client.HTTPException, socket.error,
  431. socket.gaierror, http_client.BadStatusLine)
  432. # define subclasses of the above that are not retryable.
  433. self.http_unretryable_exceptions = []
  434. if HAVE_HTTPS_CONNECTION:
  435. self.http_unretryable_exceptions.append(
  436. https_connection.InvalidCertificateException)
  437. # define values in socket exceptions we don't want to catch
  438. self.socket_exception_values = (errno.EINTR,)
  439. if https_connection_factory is not None:
  440. self.https_connection_factory = https_connection_factory[0]
  441. self.http_exceptions += https_connection_factory[1]
  442. else:
  443. self.https_connection_factory = None
  444. if (is_secure):
  445. self.protocol = 'https'
  446. else:
  447. self.protocol = 'http'
  448. self.host = host
  449. self.path = path
  450. # if the value passed in for debug
  451. if not isinstance(debug, six.integer_types):
  452. debug = 0
  453. self.debug = config.getint('Boto', 'debug', debug)
  454. self.host_header = None
  455. # Timeout used to tell http_client how long to wait for socket timeouts.
  456. # Default is to leave timeout unchanged, which will in turn result in
  457. # the socket's default global timeout being used. To specify a
  458. # timeout, set http_socket_timeout in Boto config. Regardless,
  459. # timeouts will only be applied if Python is 2.6 or greater.
  460. self.http_connection_kwargs = {}
  461. if (sys.version_info[0], sys.version_info[1]) >= (2, 6):
  462. # If timeout isn't defined in boto config file, use 70 second
  463. # default as recommended by
  464. # http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForActivityTask.html
  465. self.http_connection_kwargs['timeout'] = config.getint(
  466. 'Boto', 'http_socket_timeout', 70)
  467. if isinstance(provider, Provider):
  468. # Allow overriding Provider
  469. self.provider = provider
  470. else:
  471. self._provider_type = provider
  472. self.provider = Provider(self._provider_type,
  473. aws_access_key_id,
  474. aws_secret_access_key,
  475. security_token,
  476. profile_name)
  477. # Allow config file to override default host, port, and host header.
  478. if self.provider.host:
  479. self.host = self.provider.host
  480. if self.provider.port:
  481. self.port = self.provider.port
  482. if self.provider.host_header:
  483. self.host_header = self.provider.host_header
  484. self._pool = ConnectionPool()
  485. self._connection = (self.host, self.port, self.is_secure)
  486. self._last_rs = None
  487. self._auth_handler = auth.get_auth_handler(
  488. host, config, self.provider, self._required_auth_capability())
  489. if getattr(self, 'AuthServiceName', None) is not None:
  490. self.auth_service_name = self.AuthServiceName
  491. self.request_hook = None
  492. def __repr__(self):
  493. return '%s:%s' % (self.__class__.__name__, self.host)
  494. def _required_auth_capability(self):
  495. return []
  496. def _get_auth_service_name(self):
  497. return getattr(self._auth_handler, 'service_name')
  498. # For Sigv4, the auth_service_name/auth_region_name properties allow
  499. # the service_name/region_name to be explicitly set instead of being
  500. # derived from the endpoint url.
  501. def _set_auth_service_name(self, value):
  502. self._auth_handler.service_name = value
  503. auth_service_name = property(_get_auth_service_name, _set_auth_service_name)
  504. def _get_auth_region_name(self):
  505. return getattr(self._auth_handler, 'region_name')
  506. def _set_auth_region_name(self, value):
  507. self._auth_handler.region_name = value
  508. auth_region_name = property(_get_auth_region_name, _set_auth_region_name)
  509. def connection(self):
  510. return self.get_http_connection(*self._connection)
  511. connection = property(connection)
  512. def aws_access_key_id(self):
  513. return self.provider.access_key
  514. aws_access_key_id = property(aws_access_key_id)
  515. gs_access_key_id = aws_access_key_id
  516. access_key = aws_access_key_id
  517. def aws_secret_access_key(self):
  518. return self.provider.secret_key
  519. aws_secret_access_key = property(aws_secret_access_key)
  520. gs_secret_access_key = aws_secret_access_key
  521. secret_key = aws_secret_access_key
  522. def profile_name(self):
  523. return self.provider.profile_name
  524. profile_name = property(profile_name)
  525. def get_path(self, path='/'):
  526. # The default behavior is to suppress consecutive slashes for reasons
  527. # discussed at
  528. # https://groups.google.com/forum/#!topic/boto-dev/-ft0XPUy0y8
  529. # You can override that behavior with the suppress_consec_slashes param.
  530. if not self.suppress_consec_slashes:
  531. return self.path + re.sub('^(/*)/', "\\1", path)
  532. pos = path.find('?')
  533. if pos >= 0:
  534. params = path[pos:]
  535. path = path[:pos]
  536. else:
  537. params = None
  538. if path[-1] == '/':
  539. need_trailing = True
  540. else:
  541. need_trailing = False
  542. path_elements = self.path.split('/')
  543. path_elements.extend(path.split('/'))
  544. path_elements = [p for p in path_elements if p]
  545. path = '/' + '/'.join(path_elements)
  546. if path[-1] != '/' and need_trailing:
  547. path += '/'
  548. if params:
  549. path = path + params
  550. return path
  551. def server_name(self, port=None):
  552. if not port:
  553. port = self.port
  554. if port == 80:
  555. signature_host = self.host
  556. else:
  557. # This unfortunate little hack can be attributed to
  558. # a difference in the 2.6 version of http_client. In old
  559. # versions, it would append ":443" to the hostname sent
  560. # in the Host header and so we needed to make sure we
  561. # did the same when calculating the V2 signature. In 2.6
  562. # (and higher!)
  563. # it no longer does that. Hence, this kludge.
  564. if ((ON_APP_ENGINE and sys.version[:3] == '2.5') or
  565. sys.version[:3] in ('2.6', '2.7')) and port == 443:
  566. signature_host = self.host
  567. else:
  568. signature_host = '%s:%d' % (self.host, port)
  569. return signature_host
  570. def handle_proxy(self, proxy, proxy_port, proxy_user, proxy_pass):
  571. self.proxy = proxy
  572. self.proxy_port = proxy_port
  573. self.proxy_user = proxy_user
  574. self.proxy_pass = proxy_pass
  575. if 'http_proxy' in os.environ and not self.proxy:
  576. pattern = re.compile(
  577. '(?:http://)?'
  578. '(?:(?P<user>[\w\-\.]+):(?P<pass>.*)@)?'
  579. '(?P<host>[\w\-\.]+)'
  580. '(?::(?P<port>\d+))?'
  581. )
  582. match = pattern.match(os.environ['http_proxy'])
  583. if match:
  584. self.proxy = match.group('host')
  585. self.proxy_port = match.group('port')
  586. self.proxy_user = match.group('user')
  587. self.proxy_pass = match.group('pass')
  588. else:
  589. if not self.proxy:
  590. self.proxy = config.get_value('Boto', 'proxy', None)
  591. if not self.proxy_port:
  592. self.proxy_port = config.get_value('Boto', 'proxy_port', None)
  593. if not self.proxy_user:
  594. self.proxy_user = config.get_value('Boto', 'proxy_user', None)
  595. if not self.proxy_pass:
  596. self.proxy_pass = config.get_value('Boto', 'proxy_pass', None)
  597. if not self.proxy_port and self.proxy:
  598. print("http_proxy environment variable does not specify "
  599. "a port, using default")
  600. self.proxy_port = self.port
  601. self.no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '')
  602. self.use_proxy = (self.proxy is not None)
  603. def get_http_connection(self, host, port, is_secure):
  604. conn = self._pool.get_http_connection(host, port, is_secure)
  605. if conn is not None:
  606. return conn
  607. else:
  608. return self.new_http_connection(host, port, is_secure)
  609. def skip_proxy(self, host):
  610. if not self.no_proxy:
  611. return False
  612. if self.no_proxy == "*":
  613. return True
  614. hostonly = host
  615. hostonly = host.split(':')[0]
  616. for name in self.no_proxy.split(','):
  617. if name and (hostonly.endswith(name) or host.endswith(name)):
  618. return True
  619. return False
  620. def new_http_connection(self, host, port, is_secure):
  621. if host is None:
  622. host = self.server_name()
  623. # Make sure the host is really just the host, not including
  624. # the port number
  625. host = boto.utils.parse_host(host)
  626. http_connection_kwargs = self.http_connection_kwargs.copy()
  627. # Connection factories below expect a port keyword argument
  628. http_connection_kwargs['port'] = port
  629. # Override host with proxy settings if needed
  630. if self.use_proxy and not is_secure and \
  631. not self.skip_proxy(host):
  632. host = self.proxy
  633. http_connection_kwargs['port'] = int(self.proxy_port)
  634. if is_secure:
  635. boto.log.debug(
  636. 'establishing HTTPS connection: host=%s, kwargs=%s',
  637. host, http_connection_kwargs)
  638. if self.use_proxy and not self.skip_proxy(host):
  639. connection = self.proxy_ssl(host, is_secure and 443 or 80)
  640. elif self.https_connection_factory:
  641. connection = self.https_connection_factory(host)
  642. elif self.https_validate_certificates and HAVE_HTTPS_CONNECTION:
  643. connection = https_connection.CertValidatingHTTPSConnection(
  644. host, ca_certs=self.ca_certificates_file,
  645. **http_connection_kwargs)
  646. else:
  647. connection = http_client.HTTPSConnection(
  648. host, **http_connection_kwargs)
  649. else:
  650. boto.log.debug('establishing HTTP connection: kwargs=%s' %
  651. http_connection_kwargs)
  652. if self.https_connection_factory:
  653. # even though the factory says https, this is too handy
  654. # to not be able to allow overriding for http also.
  655. connection = self.https_connection_factory(
  656. host, **http_connection_kwargs)
  657. else:
  658. connection = http_client.HTTPConnection(
  659. host, **http_connection_kwargs)
  660. if self.debug > 1:
  661. connection.set_debuglevel(self.debug)
  662. # self.connection must be maintained for backwards-compatibility
  663. # however, it must be dynamically pulled from the connection pool
  664. # set a private variable which will enable that
  665. if host.split(':')[0] == self.host and is_secure == self.is_secure:
  666. self._connection = (host, port, is_secure)
  667. # Set the response class of the http connection to use our custom
  668. # class.
  669. connection.response_class = HTTPResponse
  670. return connection
  671. def put_http_connection(self, host, port, is_secure, connection):
  672. self._pool.put_http_connection(host, port, is_secure, connection)
  673. def proxy_ssl(self, host=None, port=None):
  674. if host and port:
  675. host = '%s:%d' % (host, port)
  676. else:
  677. host = '%s:%d' % (self.host, self.port)
  678. # Seems properly to use timeout for connect too
  679. timeout = self.http_connection_kwargs.get("timeout")
  680. if timeout is not None:
  681. sock = socket.create_connection((self.proxy,
  682. int(self.proxy_port)), timeout)
  683. else:
  684. sock = socket.create_connection((self.proxy, int(self.proxy_port)))
  685. boto.log.debug("Proxy connection: CONNECT %s HTTP/1.0\r\n", host)
  686. sock.sendall("CONNECT %s HTTP/1.0\r\n" % host)
  687. sock.sendall("User-Agent: %s\r\n" % UserAgent)
  688. if self.proxy_user and self.proxy_pass:
  689. for k, v in self.get_proxy_auth_header().items():
  690. sock.sendall("%s: %s\r\n" % (k, v))
  691. # See discussion about this config option at
  692. # https://groups.google.com/forum/?fromgroups#!topic/boto-dev/teenFvOq2Cc
  693. if config.getbool('Boto', 'send_crlf_after_proxy_auth_headers', False):
  694. sock.sendall("\r\n")
  695. else:
  696. sock.sendall("\r\n")
  697. resp = http_client.HTTPResponse(sock, strict=True, debuglevel=self.debug)
  698. resp.begin()
  699. if resp.status != 200:
  700. # Fake a socket error, use a code that make it obvious it hasn't
  701. # been generated by the socket library
  702. raise socket.error(-71,
  703. "Error talking to HTTP proxy %s:%s: %s (%s)" %
  704. (self.proxy, self.proxy_port,
  705. resp.status, resp.reason))
  706. # We can safely close the response, it duped the original socket
  707. resp.close()
  708. h = http_client.HTTPConnection(host)
  709. if self.https_validate_certificates and HAVE_HTTPS_CONNECTION:
  710. msg = "wrapping ssl socket for proxied connection; "
  711. if self.ca_certificates_file:
  712. msg += "CA certificate file=%s" % self.ca_certificates_file
  713. else:
  714. msg += "using system provided SSL certs"
  715. boto.log.debug(msg)
  716. key_file = self.http_connection_kwargs.get('key_file', None)
  717. cert_file = self.http_connection_kwargs.get('cert_file', None)
  718. sslSock = ssl.wrap_socket(sock, keyfile=key_file,
  719. certfile=cert_file,
  720. cert_reqs=ssl.CERT_REQUIRED,
  721. ca_certs=self.ca_certificates_file)
  722. cert = sslSock.getpeercert()
  723. hostname = self.host.split(':', 0)[0]
  724. if not https_connection.ValidateCertificateHostname(cert, hostname):
  725. raise https_connection.InvalidCertificateException(
  726. hostname, cert, 'hostname mismatch')
  727. else:
  728. # Fallback for old Python without ssl.wrap_socket
  729. if hasattr(http_client, 'ssl'):
  730. sslSock = http_client.ssl.SSLSocket(sock)
  731. else:
  732. sslSock = socket.ssl(sock, None, None)
  733. sslSock = http_client.FakeSocket(sock, sslSock)
  734. # This is a bit unclean
  735. h.sock = sslSock
  736. return h
  737. def prefix_proxy_to_path(self, path, host=None):
  738. path = self.protocol + '://' + (host or self.server_name()) + path
  739. return path
  740. def get_proxy_auth_header(self):
  741. auth = encodebytes(self.proxy_user + ':' + self.proxy_pass)
  742. return {'Proxy-Authorization': 'Basic %s' % auth}
  743. # For passing proxy information to other connection libraries, e.g. cloudsearch2
  744. def get_proxy_url_with_auth(self):
  745. if not self.use_proxy:
  746. return None
  747. if self.proxy_user or self.proxy_pass:
  748. if self.proxy_pass:
  749. login_info = '%s:%s@' % (self.proxy_user, self.proxy_pass)
  750. else:
  751. login_info = '%s@' % self.proxy_user
  752. else:
  753. login_info = ''
  754. return 'http://%s%s:%s' % (login_info, self.proxy, str(self.proxy_port or self.port))
  755. def set_host_header(self, request):
  756. try:
  757. request.headers['Host'] = \
  758. self._auth_handler.host_header(self.host, request)
  759. except AttributeError:
  760. request.headers['Host'] = self.host.split(':', 1)[0]
  761. def set_request_hook(self, hook):
  762. self.request_hook = hook
  763. def _mexe(self, request, sender=None, override_num_retries=None,
  764. retry_handler=None):
  765. """
  766. mexe - Multi-execute inside a loop, retrying multiple times to handle
  767. transient Internet errors by simply trying again.
  768. Also handles redirects.
  769. This code was inspired by the S3Utils classes posted to the boto-users
  770. Google group by Larry Bates. Thanks!
  771. """
  772. boto.log.debug('Method: %s' % request.method)
  773. boto.log.debug('Path: %s' % request.path)
  774. boto.log.debug('Data: %s' % request.body)
  775. boto.log.debug('Headers: %s' % request.headers)
  776. boto.log.debug('Host: %s' % request.host)
  777. boto.log.debug('Port: %s' % request.port)
  778. boto.log.debug('Params: %s' % request.params)
  779. response = None
  780. body = None
  781. ex = None
  782. if override_num_retries is None:
  783. num_retries = config.getint('Boto', 'num_retries', self.num_retries)
  784. else:
  785. num_retries = override_num_retries
  786. i = 0
  787. connection = self.get_http_connection(request.host, request.port,
  788. self.is_secure)
  789. # Convert body to bytes if needed
  790. if not isinstance(request.body, bytes) and hasattr(request.body,
  791. 'encode'):
  792. request.body = request.body.encode('utf-8')
  793. while i <= num_retries:
  794. # Use binary exponential backoff to desynchronize client requests.
  795. next_sleep = min(random.random() * (2 ** i),
  796. boto.config.get('Boto', 'max_retry_delay', 60))
  797. try:
  798. # we now re-sign each request before it is retried
  799. boto.log.debug('Token: %s' % self.provider.security_token)
  800. request.authorize(connection=self)
  801. # Only force header for non-s3 connections, because s3 uses
  802. # an older signing method + bucket resource URLs that include
  803. # the port info. All others should be now be up to date and
  804. # not include the port.
  805. if 's3' not in self._required_auth_capability():
  806. if not getattr(self, 'anon', False):
  807. if not request.headers.get('Host'):
  808. self.set_host_header(request)
  809. boto.log.debug('Final headers: %s' % request.headers)
  810. request.start_time = datetime.now()
  811. if callable(sender):
  812. response = sender(connection, request.method, request.path,
  813. request.body, request.headers)
  814. else:
  815. connection.request(request.method, request.path,
  816. request.body, request.headers)
  817. response = connection.getresponse()
  818. boto.log.debug('Response headers: %s' % response.getheaders())
  819. location = response.getheader('location')
  820. # -- gross hack --
  821. # http_client gets confused with chunked responses to HEAD requests
  822. # so I have to fake it out
  823. if request.method == 'HEAD' and getattr(response,
  824. 'chunked', False):
  825. response.chunked = 0
  826. if callable(retry_handler):
  827. status = retry_handler(response, i, next_sleep)
  828. if status:
  829. msg, i, next_sleep = status
  830. if msg:
  831. boto.log.debug(msg)
  832. time.sleep(next_sleep)
  833. continue
  834. if response.status in [500, 502, 503, 504]:
  835. msg = 'Received %d response. ' % response.status
  836. msg += 'Retrying in %3.1f seconds' % next_sleep
  837. boto.log.debug(msg)
  838. body = response.read()
  839. if isinstance(body, bytes):
  840. body = body.decode('utf-8')
  841. elif response.status < 300 or response.status >= 400 or \
  842. not location:
  843. # don't return connection to the pool if response contains
  844. # Connection:close header, because the connection has been
  845. # closed and default reconnect behavior may do something
  846. # different than new_http_connection. Also, it's probably
  847. # less efficient to try to reuse a closed connection.
  848. conn_header_value = response.getheader('connection')
  849. if conn_header_value == 'close':
  850. connection.close()
  851. else:
  852. self.put_http_connection(request.host, request.port,
  853. self.is_secure, connection)
  854. if self.request_hook is not None:
  855. self.request_hook.handle_request_data(request, response)
  856. return response
  857. else:
  858. scheme, request.host, request.path, \
  859. params, query, fragment = urlparse(location)
  860. if query:
  861. request.path += '?' + query
  862. # urlparse can return both host and port in netloc, so if
  863. # that's the case we need to split them up properly
  864. if ':' in request.host:
  865. request.host, request.port = request.host.split(':', 1)
  866. msg = 'Redirecting: %s' % scheme + '://'
  867. msg += request.host + request.path
  868. boto.log.debug(msg)
  869. connection = self.get_http_connection(request.host,
  870. request.port,
  871. scheme == 'https')
  872. response = None
  873. continue
  874. except PleaseRetryException as e:
  875. boto.log.debug('encountered a retry exception: %s' % e)
  876. connection = self.new_http_connection(request.host, request.port,
  877. self.is_secure)
  878. response = e.response
  879. ex = e
  880. except self.http_exceptions as e:
  881. for unretryable in self.http_unretryable_exceptions:
  882. if isinstance(e, unretryable):
  883. boto.log.debug(
  884. 'encountered unretryable %s exception, re-raising' %
  885. e.__class__.__name__)
  886. raise
  887. boto.log.debug('encountered %s exception, reconnecting' %
  888. e.__class__.__name__)
  889. connection = self.new_http_connection(request.host, request.port,
  890. self.is_secure)
  891. ex = e
  892. time.sleep(next_sleep)
  893. i += 1
  894. # If we made it here, it's because we have exhausted our retries
  895. # and stil haven't succeeded. So, if we have a response object,
  896. # use it to raise an exception.
  897. # Otherwise, raise the exception that must have already happened.
  898. if self.request_hook is not None:
  899. self.request_hook.handle_request_data(request, response, error=True)
  900. if response:
  901. raise BotoServerError(response.status, response.reason, body)
  902. elif ex:
  903. raise ex
  904. else:
  905. msg = 'Please report this exception as a Boto Issue!'
  906. raise BotoClientError(msg)
  907. def build_base_http_request(self, method, path, auth_path,
  908. params=None, headers=None, data='', host=None):
  909. path = self.get_path(path)
  910. if auth_path is not None:
  911. auth_path = self.get_path(auth_path)
  912. if params is None:
  913. params = {}
  914. else:
  915. params = params.copy()
  916. if headers is None:
  917. headers = {}
  918. else:
  919. headers = headers.copy()
  920. if self.host_header and not boto.utils.find_matching_headers('host', headers):
  921. headers['host'] = self.host_header
  922. host = host or self.host
  923. if self.use_proxy and not self.skip_proxy(host):
  924. if not auth_path:
  925. auth_path = path
  926. path = self.prefix_proxy_to_path(path, host)
  927. if self.proxy_user and self.proxy_pass and not self.is_secure:
  928. # If is_secure, we don't have to set the proxy authentication
  929. # header here, we did that in the CONNECT to the proxy.
  930. headers.update(self.get_proxy_auth_header())
  931. return HTTPRequest(method, self.protocol, host, self.port,
  932. path, auth_path, params, headers, data)
  933. def make_request(self, method, path, headers=None, data='', host=None,
  934. auth_path=None, sender=None, override_num_retries=None,
  935. params=None, retry_handler=None):
  936. """Makes a request to the server, with stock multiple-retry logic."""
  937. if params is None:
  938. params = {}
  939. http_request = self.build_base_http_request(method, path, auth_path,
  940. params, headers, data, host)
  941. return self._mexe(http_request, sender, override_num_retries,
  942. retry_handler=retry_handler)
  943. def close(self):
  944. """(Optional) Close any open HTTP connections. This is non-destructive,
  945. and making a new request will open a connection again."""
  946. boto.log.debug('closing all HTTP connections')
  947. self._connection = None # compat field
  948. class AWSQueryConnection(AWSAuthConnection):
  949. APIVersion = ''
  950. ResponseError = BotoServerError
  951. def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
  952. is_secure=True, port=None, proxy=None, proxy_port=None,
  953. proxy_user=None, proxy_pass=None, host=None, debug=0,
  954. https_connection_factory=None, path='/', security_token=None,
  955. validate_certs=True, profile_name=None, provider='aws'):
  956. super(AWSQueryConnection, self).__init__(
  957. host, aws_access_key_id,
  958. aws_secret_access_key,
  959. is_secure, port, proxy,
  960. proxy_port, proxy_user, proxy_pass,
  961. debug, https_connection_factory, path,
  962. security_token=security_token,
  963. validate_certs=validate_certs,
  964. profile_name=profile_name,
  965. provider=provider)
  966. def _required_auth_capability(self):
  967. return []
  968. def get_utf8_value(self, value):
  969. return boto.utils.get_utf8_value(value)
  970. def make_request(self, action, params=None, path='/', verb='GET'):
  971. http_request = self.build_base_http_request(verb, path, None,
  972. params, {}, '',
  973. self.host)
  974. if action:
  975. http_request.params['Action'] = action
  976. if self.APIVersion:
  977. http_request.params['Version'] = self.APIVersion
  978. return self._mexe(http_request)
  979. def build_list_params(self, params, items, label):
  980. if isinstance(items, six.string_types):
  981. items = [items]
  982. for i in range(1, len(items) + 1):
  983. params['%s.%d' % (label, i)] = items[i - 1]
  984. def build_complex_list_params(self, params, items, label, names):
  985. """Serialize a list of structures.
  986. For example::
  987. items = [('foo', 'bar', 'baz'), ('foo2', 'bar2', 'baz2')]
  988. label = 'ParamName.member'
  989. names = ('One', 'Two', 'Three')
  990. self.build_complex_list_params(params, items, label, names)
  991. would result in the params dict being updated with these params::
  992. ParamName.member.1.One = foo
  993. ParamName.member.1.Two = bar
  994. ParamName.member.1.Three = baz
  995. ParamName.member.2.One = foo2
  996. ParamName.member.2.Two = bar2
  997. ParamName.member.2.Three = baz2
  998. :type params: dict
  999. :param params: The params dict. The complex list params
  1000. will be added to this dict.
  1001. :type items: list of tuples
  1002. :param items: The list to serialize.
  1003. :type label: string
  1004. :param label: The prefix to apply to the parameter.
  1005. :type names: tuple of strings
  1006. :param names: The names associated with each tuple element.
  1007. """
  1008. for i, item in enumerate(items, 1):
  1009. current_prefix = '%s.%s' % (label, i)
  1010. for key, value in zip(names, item):
  1011. full_key = '%s.%s' % (current_prefix, key)
  1012. params[full_key] = value
  1013. # generics
  1014. def get_list(self, action, params, markers, path='/',
  1015. parent=None, verb='GET'):
  1016. if not parent:
  1017. parent = self
  1018. response = self.make_request(action, params, path, verb)
  1019. body = response.read()
  1020. boto.log.debug(body)
  1021. if not body:
  1022. boto.log.error('Null body %s' % body)
  1023. raise self.ResponseError(response.status, response.reason, body)
  1024. elif response.status == 200:
  1025. rs = ResultSet(markers)
  1026. h = boto.handler.XmlHandler(rs, parent)
  1027. if isinstance(body, six.text_type):
  1028. body = body.encode('utf-8')
  1029. xml.sax.parseString(body, h)
  1030. return rs
  1031. else:
  1032. boto.log.error('%s %s' % (response.status, response.reason))
  1033. boto.log.error('%s' % body)
  1034. raise self.ResponseError(response.status, response.reason, body)
  1035. def get_object(self, action, params, cls, path='/',
  1036. parent=None, verb='GET'):
  1037. if not parent:
  1038. parent = self
  1039. response = self.make_request(action, params, path, verb)
  1040. body = response.read()
  1041. boto.log.debug(body)
  1042. if not body:
  1043. boto.log.error('Null body %s' % body)
  1044. raise self.ResponseError(response.status, response.reason, body)
  1045. elif response.status == 200:
  1046. obj = cls(parent)
  1047. h = boto.handler.XmlHandler(obj, parent)
  1048. if isinstance(body, six.text_type):
  1049. body = body.encode('utf-8')
  1050. xml.sax.parseString(body, h)
  1051. return obj
  1052. else:
  1053. boto.log.error('%s %s' % (response.status, response.reason))
  1054. boto.log.error('%s' % body)
  1055. raise self.ResponseError(response.status, response.reason, body)
  1056. def get_status(self, action, params, path='/', parent=None, verb='GET'):
  1057. if not parent:
  1058. parent = self
  1059. response = self.make_request(action, params, path, verb)
  1060. body = response.read()
  1061. boto.log.debug(body)
  1062. if not body:
  1063. boto.log.error('Null body %s' % body)
  1064. raise self.ResponseError(response.status, response.reason, body)
  1065. elif response.status == 200:
  1066. rs = ResultSet()
  1067. h = boto.handler.XmlHandler(rs, parent)
  1068. xml.sax.parseString(body, h)
  1069. return rs.status
  1070. else:
  1071. boto.log.error('%s %s' % (response.status, response.reason))
  1072. boto.log.error('%s' % body)
  1073. raise self.ResponseError(response.status, response.reason, body)