PageRenderTime 35ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/1.1.0/src/api/class.ScalrAPICore.php

http://scalr.googlecode.com/
PHP | 265 lines | 239 code | 15 blank | 11 comment | 7 complexity | ca0e97a71e4d6d09e21f895ed06dfa0e MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0
  1. <?php
  2. abstract class ScalrAPICore
  3. {
  4. const HASH_ALGO = 'SHA256';
  5. protected $Request;
  6. protected $Client;
  7. protected $DB;
  8. protected $Logger;
  9. public $Version;
  10. protected $LastTransactionID;
  11. function __construct($version)
  12. {
  13. $this->DB = Core::GetDBInstance();
  14. $this->Logger = Logger::getLogger(__CLASS__);
  15. $this->Version = $version;
  16. }
  17. private function AuthenticateREST($request)
  18. {
  19. if (!$request['Signature'])
  20. throw new Exception("Signature is missing");
  21. if (!$request['KeyID'])
  22. throw new Exception("KeyID is missing");
  23. if (!$request['Timestamp'])
  24. throw new Exception("Timestamp is missing");
  25. //TODO: Validate TimeStamp
  26. ksort($request);
  27. $string_to_sign = "";
  28. foreach ($request as $k=>$v)
  29. {
  30. if (!in_array($k, array("Signature")))
  31. $string_to_sign.= "{$k}{$v}";
  32. }
  33. $this->Client = Client::LoadByScalrKeyID($request['KeyID']);
  34. $auth_key = $this->Client->GetScalrAPIKey();
  35. $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, $string_to_sign, $auth_key, 1));
  36. if ($valid_sign != $request['Signature'])
  37. throw new Exception("Signature doesn't match");
  38. }
  39. public function BuildRestServer($request)
  40. {
  41. try
  42. {
  43. $Reflect = new ReflectionObject($this);
  44. if ($Reflect->hasMethod($request['Action']))
  45. {
  46. //Authenticate
  47. $this->AuthenticateREST($request);
  48. if ($this->Client->GetSettingValue(CLIENT_SETTINGS::API_ENABLED) != 1)
  49. throw new Exception(_("API disabled for you. You can enable it at 'Settings -> System settings'"));
  50. //Check IP Addresses
  51. $ips = explode(",", $this->Client->GetSettingValue(CLIENT_SETTINGS::API_ALLOWED_IPS));
  52. if (!$this->IPAccessCheck($ips))
  53. throw new Exception(sprintf(_("Access to the API is not allowed from your IP '%s'"), $_SERVER['REMOTE_ADDR']));
  54. //Execute API call
  55. $ReflectMethod = $Reflect->getMethod($request['Action']);
  56. $args = array();
  57. foreach ($ReflectMethod->getParameters() as $param)
  58. {
  59. if (!$param->isOptional() && !$request[$param->getName()])
  60. throw new Exception(sprintf("Missing required parameter '%s'", $param->getName()));
  61. else
  62. $args[$param->getName()] = $request[$param->getName()];
  63. }
  64. $result = $ReflectMethod->invokeArgs($this, $args);
  65. // Create response
  66. $DOMDocument = new DOMDocument('1.0', 'UTF-8');
  67. $DOMDocument->loadXML("<{$request['Action']}Response></{$request['Action']}Response>");
  68. $this->ObjectToXML($result, $DOMDocument->documentElement, $DOMDocument);
  69. $retval = $DOMDocument->saveXML();
  70. }
  71. else
  72. throw new Exception(sprintf("Action '%s' is not defined", $request['Action']));
  73. }
  74. catch(Exception $e)
  75. {
  76. if (!$this->LastTransactionID)
  77. $this->LastTransactionID = $this->GenerateTransactionID();
  78. $retval = "<?xml version=\"1.0\"?>\n".
  79. "<Error>\n".
  80. "\t<TransactionID>{$this->LastTransactionID}</TransactionID>\n".
  81. "\t<Message>{$e->getMessage()}</Message>\n".
  82. "</Error>\n";
  83. }
  84. $this->LogRequest(
  85. $this->LastTransactionID,
  86. $request['Action'],
  87. $_SERVER['REMOTE_ADDR'],
  88. $request,
  89. $retval
  90. );
  91. header("Content-type: text/xml");
  92. header("Content-length: ".strlen($retval));
  93. print $retval;
  94. }
  95. protected function LogRequest($trans_id, $action, $ipaddr, $request, $response)
  96. {
  97. try
  98. {
  99. $this->DB->Execute("INSERT INTO api_log SET
  100. transaction_id = ?,
  101. dtadded = ?,
  102. action = ?,
  103. ipaddress = ?,
  104. request = ?,
  105. response = ?,
  106. clientid = ?
  107. ",array(
  108. $trans_id,
  109. time(),
  110. $action,
  111. $ipaddr,
  112. http_build_query($request),
  113. $response,
  114. $this->Client->ID
  115. ));
  116. }
  117. catch(Exception $e) {}
  118. }
  119. protected function IPAccessCheck($allowed_ips)
  120. {
  121. $current_ip = $_SERVER['REMOTE_ADDR'];
  122. $current_ip_parts = explode(".", $current_ip);
  123. foreach ($allowed_ips as $allowed_ip)
  124. {
  125. $allowedhost = trim($allowed_ip);
  126. if ($allowedhost == '')
  127. continue;
  128. if (preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/si", $allowedhost))
  129. {
  130. if (ip2long($allowedhost) == ip2long($current_ip))
  131. return true;
  132. }
  133. elseif (stristr($allowedhost, "*"))
  134. {
  135. $ip_parts = explode(".", trim($allowedhost));
  136. if (
  137. ($ip_parts[0] == "*" || $ip_parts[0] == $current_ip_parts[0]) &&
  138. ($ip_parts[1] == "*" || $ip_parts[1] == $current_ip_parts[1]) &&
  139. ($ip_parts[2] == "*" || $ip_parts[2] == $current_ip_parts[2]) &&
  140. ($ip_parts[3] == "*" || $ip_parts[3] == $current_ip_parts[3])
  141. )
  142. return true;
  143. }
  144. else
  145. {
  146. $ip = @gethostbyname($allowedhost);
  147. if ($ip != $allowedhost)
  148. {
  149. if (ip2long($ip) == ip2long($current_ip))
  150. return true;
  151. }
  152. }
  153. }
  154. return false;
  155. }
  156. protected function ObjectToXML($obj, &$DOMElement, &$DOMDocument)
  157. {
  158. if (is_object($obj) || is_array($obj))
  159. {
  160. foreach ($obj as $k=>$v)
  161. {
  162. if (is_object($v))
  163. $this->ObjectToXML($v, $DOMElement->appendChild($DOMDocument->createElement($k)), $DOMDocument);
  164. elseif (is_array($v))
  165. foreach ($v as $vv)
  166. {
  167. $e = &$DOMElement->appendChild($DOMDocument->createElement($k));
  168. $this->ObjectToXML($vv, $e, $DOMDocument);
  169. }
  170. else
  171. $DOMElement->appendChild($DOMDocument->createElement($k, $v));
  172. }
  173. }
  174. else
  175. $DOMElement->appendChild($DOMDocument->createTextNode($obj));
  176. }
  177. protected function CreateInitialResponse()
  178. {
  179. $response = new stdClass();
  180. $response->{"TransactionID"} = $this->GenerateTransactionID();
  181. return $response;
  182. }
  183. private function GenerateTransactionID()
  184. {
  185. $pr_bits = false;
  186. if (is_a ( $this, 'uuid' )) {
  187. if (is_resource ( $this->urand )) {
  188. $pr_bits .= @fread ( $this->urand, 16 );
  189. }
  190. }
  191. if (! $pr_bits) {
  192. $fp = @fopen ( '/dev/urandom', 'rb' );
  193. if ($fp !== false) {
  194. $pr_bits .= @fread ( $fp, 16 );
  195. @fclose ( $fp );
  196. } else {
  197. // If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
  198. $pr_bits = "";
  199. for($cnt = 0; $cnt < 16; $cnt ++) {
  200. $pr_bits .= chr ( mt_rand ( 0, 255 ) );
  201. }
  202. }
  203. }
  204. $time_low = bin2hex ( substr ( $pr_bits, 0, 4 ) );
  205. $time_mid = bin2hex ( substr ( $pr_bits, 4, 2 ) );
  206. $time_hi_and_version = bin2hex ( substr ( $pr_bits, 6, 2 ) );
  207. $clock_seq_hi_and_reserved = bin2hex ( substr ( $pr_bits, 8, 2 ) );
  208. $node = bin2hex ( substr ( $pr_bits, 10, 6 ) );
  209. /**
  210. * Set the four most significant bits (bits 12 through 15) of the
  211. * time_hi_and_version field to the 4-bit version number from
  212. * Section 4.1.3.
  213. * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
  214. */
  215. $time_hi_and_version = hexdec ( $time_hi_and_version );
  216. $time_hi_and_version = $time_hi_and_version >> 4;
  217. $time_hi_and_version = $time_hi_and_version | 0x4000;
  218. /**
  219. * Set the two most significant bits (bits 6 and 7) of the
  220. * clock_seq_hi_and_reserved to zero and one, respectively.
  221. */
  222. $clock_seq_hi_and_reserved = hexdec ( $clock_seq_hi_and_reserved );
  223. $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
  224. $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;
  225. $this->LastTransactionID = sprintf ( '%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node );
  226. return $this->LastTransactionID;
  227. }
  228. }
  229. ?>