PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Service/Amazon/Ec2/AbstractService.php

https://github.com/Exercise/zf2
PHP | 266 lines | 94 code | 32 blank | 140 comment | 7 complexity | e305b7e1d6c8558c44fc9b57dede707e MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Service_Amazon
  17. * @subpackage Ec2
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * Provides the basic functionality to send a request to the Amazon Ec2 Query API
  24. *
  25. * @uses DOMXPath
  26. * @uses Zend_Crypt_Hmac
  27. * @uses Zend_Http_Client
  28. * @uses Zend_Service_Amazon_Abstract
  29. * @uses Zend_Service_Amazon_Exception
  30. * @uses Zend_Service_Amazon_Ec2_Exception
  31. * @uses Zend_Service_Amazon_Ec2_Response
  32. * @category Zend
  33. * @package Zend_Service_Amazon
  34. * @subpackage Ec2
  35. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  36. * @license http://framework.zend.com/license/new-bsd New BSD License
  37. */
  38. abstract class Zend_Service_Amazon_Ec2_AbstractService extends Zend_Service_Amazon_AbstractService
  39. {
  40. /**
  41. * The HTTP query server
  42. */
  43. protected $_ec2Endpoint = 'ec2.amazonaws.com';
  44. /**
  45. * The API version to use
  46. */
  47. protected $_ec2ApiVersion = '2009-04-04';
  48. /**
  49. * Signature Version
  50. */
  51. protected $_ec2SignatureVersion = '2';
  52. /**
  53. * Signature Encoding Method
  54. */
  55. protected $_ec2SignatureMethod = 'HmacSHA256';
  56. /**
  57. * Period after which HTTP request will timeout in seconds
  58. */
  59. protected $_httpTimeout = 10;
  60. /**
  61. * @var string Amazon Region
  62. */
  63. protected static $_defaultRegion = null;
  64. /**
  65. * @var string Amazon Region
  66. */
  67. protected $_region;
  68. /**
  69. * An array that contains all the valid Amazon Ec2 Regions.
  70. *
  71. * @var array
  72. */
  73. protected static $_validEc2Regions = array('eu-west-1', 'us-east-1');
  74. /**
  75. * Create Amazon client.
  76. *
  77. * @param string $access_key Override the default Access Key
  78. * @param string $secret_key Override the default Secret Key
  79. * @param string $region Sets the AWS Region
  80. * @return void
  81. */
  82. public function __construct($accessKey=null, $secretKey=null, $region=null)
  83. {
  84. if(!$region) {
  85. $region = self::$_defaultRegion;
  86. } else {
  87. // make rue the region is valid
  88. if(!empty($region) && !in_array(strtolower($region), self::$_validEc2Regions, true)) {
  89. throw new Zend_Service_Amazon_Exception('Invalid Amazon Ec2 Region');
  90. }
  91. }
  92. $this->_region = $region;
  93. parent::__construct($accessKey, $secretKey);
  94. }
  95. /**
  96. * Set which region you are working in. It will append the
  97. * end point automaticly
  98. *
  99. * @param string $region
  100. */
  101. public static function setRegion($region)
  102. {
  103. if(in_array(strtolower($region), self::$_validEc2Regions, true)) {
  104. self::$_defaultRegion = $region;
  105. } else {
  106. throw new Zend_Service_Amazon_Exception('Invalid Amazon Ec2 Region');
  107. }
  108. }
  109. /**
  110. * Method to fetch the AWS Region
  111. *
  112. * @return string
  113. */
  114. protected function _getRegion()
  115. {
  116. return (!empty($this->_region)) ? $this->_region . '.' : '';
  117. }
  118. /**
  119. * Sends a HTTP request to the queue service using Zend_Http_Client
  120. *
  121. * @param array $params List of parameters to send with the request
  122. * @return Zend_Service_Amazon_Ec2_Response
  123. * @throws Zend_Service_Amazon_Ec2_Exception
  124. */
  125. protected function sendRequest(array $params = array())
  126. {
  127. $url = 'https://' . $this->_getRegion() . $this->_ec2Endpoint . '/';
  128. $params = $this->addRequiredParameters($params);
  129. try {
  130. /* @var $request Zend_Http_Client */
  131. $request = $this->getHttpClient();
  132. $request->resetParameters();
  133. $request->setConfig(array(
  134. 'timeout' => $this->_httpTimeout
  135. ));
  136. $request->setUri($url);
  137. $request->setMethod(Zend_Http_Client::POST);
  138. $request->setParameterPost($params);
  139. $httpResponse = $request->request();
  140. } catch (Zend_Http_Client_Exception $zhce) {
  141. $message = 'Error in request to AWS service: ' . $zhce->getMessage();
  142. throw new Zend_Service_Amazon_Ec2_Exception($message, $zhce->getCode(), $zhce);
  143. }
  144. $response = new Zend_Service_Amazon_Ec2_Response($httpResponse);
  145. $this->checkForErrors($response);
  146. return $response;
  147. }
  148. /**
  149. * Adds required authentication and version parameters to an array of
  150. * parameters
  151. *
  152. * The required parameters are:
  153. * - AWSAccessKey
  154. * - SignatureVersion
  155. * - Timestamp
  156. * - Version and
  157. * - Signature
  158. *
  159. * If a required parameter is already set in the <tt>$parameters</tt> array,
  160. * it is overwritten.
  161. *
  162. * @param array $parameters the array to which to add the required
  163. * parameters.
  164. *
  165. * @return array
  166. */
  167. protected function addRequiredParameters(array $parameters)
  168. {
  169. $parameters['AWSAccessKeyId'] = $this->_getAccessKey();
  170. $parameters['SignatureVersion'] = $this->_ec2SignatureVersion;
  171. $parameters['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
  172. $parameters['Version'] = $this->_ec2ApiVersion;
  173. $parameters['SignatureMethod'] = $this->_ec2SignatureMethod;
  174. $parameters['Signature'] = $this->signParameters($parameters);
  175. return $parameters;
  176. }
  177. /**
  178. * Computes the RFC 2104-compliant HMAC signature for request parameters
  179. *
  180. * This implements the Amazon Web Services signature, as per the following
  181. * specification:
  182. *
  183. * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  184. * excluding <tt>Signature</tt>, the value of which is being created),
  185. * ignoring case.
  186. *
  187. * 2. Iterate over the sorted list and append the parameter name (in its
  188. * original case) and then its value. Do not URL-encode the parameter
  189. * values before constructing this string. Do not use any separator
  190. * characters when appending strings.
  191. *
  192. * @param array $parameters the parameters for which to get the signature.
  193. * @param string $secretKey the secret key to use to sign the parameters.
  194. *
  195. * @return string the signed data.
  196. */
  197. protected function signParameters(array $paramaters)
  198. {
  199. $data = "POST\n";
  200. $data .= $this->_getRegion() . $this->_ec2Endpoint . "\n";
  201. $data .= "/\n";
  202. uksort($paramaters, 'strcmp');
  203. unset($paramaters['Signature']);
  204. $arrData = array();
  205. foreach($paramaters as $key => $value) {
  206. $arrData[] = $key . '=' . str_replace("%7E", "~", rawurlencode($value));
  207. }
  208. $data .= implode('&', $arrData);
  209. $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
  210. return base64_encode($hmac);
  211. }
  212. /**
  213. * Checks for errors responses from Amazon
  214. *
  215. * @param Zend_Service_Amazon_Ec2_Response $response the response object to
  216. * check.
  217. *
  218. * @return void
  219. *
  220. * @throws Zend_Service_Amazon_Ec2_Exception if one or more errors are
  221. * returned from Amazon.
  222. */
  223. private function checkForErrors(Zend_Service_Amazon_Ec2_Response $response)
  224. {
  225. $xpath = new DOMXPath($response->getDocument());
  226. $list = $xpath->query('//Error');
  227. if ($list->length > 0) {
  228. $node = $list->item(0);
  229. $code = $xpath->evaluate('string(Code/text())', $node);
  230. $message = $xpath->evaluate('string(Message/text())', $node);
  231. throw new Zend_Service_Amazon_Ec2_Exception($message, 0, $code);
  232. }
  233. }
  234. }