PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/demo/scalr_newui/app/src/api/class.ScalrAPICore.php

https://github.com/kennethjiang/Wolke
PHP | 361 lines | 322 code | 31 blank | 8 comment | 16 complexity | d2240384d9d64704a876a9d41967e0f1 MD5 | raw file
  1. <?php
  2. define("API_SERVER_IP", "174.132.108.66");
  3. abstract class ScalrAPICore
  4. {
  5. const HASH_ALGO = 'SHA256';
  6. protected $Request;
  7. /**
  8. *
  9. * @var Client
  10. */
  11. protected $Client;
  12. /**
  13. *
  14. * @var Scalr_Environment
  15. */
  16. protected $Environment;
  17. protected $DB;
  18. protected $Logger;
  19. public $Version;
  20. protected $debug = array();
  21. protected $LastTransactionID;
  22. function __construct($version)
  23. {
  24. $this->DB = Core::GetDBInstance();
  25. $this->Logger = Logger::getLogger(__CLASS__);
  26. $this->Version = $version;
  27. }
  28. protected function insensitiveUksort($a,$b) {
  29. return strtolower($a)>strtolower($b);
  30. }
  31. private function AuthenticateRESTv3($request)
  32. {
  33. if (!$request['Signature'])
  34. throw new Exception("Signature is missing");
  35. if (!$request['KeyID'])
  36. throw new Exception("KeyID is missing");
  37. if (!$request['Timestamp'] && !$request['TimeStamp'])
  38. throw new Exception("Timestamp is missing");
  39. if ($request['Timestamp'])
  40. $request['TimeStamp'] = $request['Timestamp'];
  41. $string_to_sign = "{$request['Action']}:{$request['KeyID']}:{$request['TimeStamp']}";
  42. $this->debug['stringToSign'] = $string_to_sign;
  43. $this->Environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadByApiKeyId($request['KeyID']);
  44. $auth_key = $this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ACCESS_KEY, false);
  45. $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, trim($string_to_sign), $auth_key, 1));
  46. $request['Signature'] = str_replace(" ", "+", $request['Signature']);
  47. $this->debug['reqSignature'] = $request['Signature'];
  48. $this->debug['validSignature'] = $valid_sign;
  49. $this->debug['usedAuthVersion'] = 3;
  50. $this->debug['md5AccessKey'] = md5($auth_key);
  51. if ($valid_sign != $request['Signature'])
  52. throw new Exception("Signature doesn't match");
  53. }
  54. private function AuthenticateRESTv2($request)
  55. {
  56. if (!$request['Signature'])
  57. throw new Exception("Signature is missing");
  58. if (!$request['KeyID'])
  59. throw new Exception("KeyID is missing");
  60. if (!$request['Timestamp'] && !$request['TimeStamp'])
  61. throw new Exception("Timestamp is missing");
  62. foreach ($request as $k=>$v)
  63. {
  64. if (is_array($v))
  65. {
  66. foreach ($v as $kk => $vv)
  67. $request["{$k}[{$kk}]"] = $vv;
  68. unset($request[$k]);
  69. }
  70. }
  71. uksort($request, array($this, 'insensitiveUksort'));
  72. $string_to_sign = "";
  73. foreach ($request as $k=>$v)
  74. {
  75. if (!in_array($k, array("Signature", "SysDebug"))) {
  76. if (is_array($v)) {
  77. foreach ($v as $kk => $vv) {
  78. $string_to_sign.= "{$k}[{$kk}]{$vv}";
  79. }
  80. }
  81. else {
  82. $string_to_sign.= "{$k}{$v}";
  83. }
  84. }
  85. }
  86. $this->debug['stringToSign'] = $string_to_sign;
  87. $this->Environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadByApiKeyId($request['KeyID']);
  88. $this->Client = Client::Load($this->Environment->clientId);
  89. $auth_key = $this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ACCESS_KEY, false);
  90. $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, trim($string_to_sign), $auth_key, 1));
  91. $request['Signature'] = str_replace(" ", "+", $request['Signature']);
  92. $this->debug['reqSignature'] = $request['Signature'];
  93. $this->debug['validSignature'] = $valid_sign;
  94. if ($valid_sign != $request['Signature'])
  95. throw new Exception("Signature doesn't match");
  96. }
  97. private function AuthenticateREST($request)
  98. {
  99. if (!$request['Signature'])
  100. throw new Exception("Signature is missing");
  101. if (!$request['KeyID'])
  102. throw new Exception("KeyID is missing");
  103. if (!$request['Timestamp'] && !$request['TimeStamp'])
  104. throw new Exception("Timestamp is missing");
  105. ksort($request);
  106. $string_to_sign = "";
  107. foreach ($request as $k=>$v) {
  108. if (!in_array($k, array("Signature"))) {
  109. if (is_array($v)) {
  110. foreach ($v as $kk => $vv) {
  111. $string_to_sign.= "{$k}[{$kk}]{$vv}";
  112. }
  113. }
  114. else {
  115. $string_to_sign.= "{$k}{$v}";
  116. }
  117. }
  118. }
  119. $this->debug['stringToSign'] = $string_to_sign;
  120. $this->Environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadByApiKeyId($request['KeyID']);
  121. $this->Client = Client::Load($this->Environment->clientId);
  122. $auth_key = $this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ACCESS_KEY, false);
  123. $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, trim($string_to_sign), $auth_key, 1));
  124. if ($valid_sign != $request['Signature'])
  125. throw new Exception("Signature doesn't match " . $string_to_sign );
  126. }
  127. public function BuildRestServer($request)
  128. {
  129. try
  130. {
  131. $Reflect = new ReflectionObject($this);
  132. if ($Reflect->hasMethod($request['Action']))
  133. {
  134. //Authenticate
  135. if ($request['AuthVersion'] == 2)
  136. $this->AuthenticateRESTv2($request);
  137. elseif ($request['AuthVersion'] == 3)
  138. $this->AuthenticateRESTv3($request);
  139. else
  140. $this->AuthenticateREST($request);
  141. if ($this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ENABLED) != 1)
  142. throw new Exception(_("API disabled for you. You can enable it at 'Settings -> Environments'"));
  143. //Check IP Addresses
  144. if ($this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ALLOWED_IPS))
  145. {
  146. $ips = explode(",", $this->Environment->getPlatformConfigValue(ENVIRONMENT_SETTINGS::API_ALLOWED_IPS));
  147. if (!$this->IPAccessCheck($ips) && $_SERVER['REMOTE_ADDR'] != API_SERVER_IP)
  148. throw new Exception(sprintf(_("Access to the API is not allowed from your IP '%s'"), $_SERVER['REMOTE_ADDR']));
  149. }
  150. //Execute API call
  151. $ReflectMethod = $Reflect->getMethod($request['Action']);
  152. $args = array();
  153. foreach ($ReflectMethod->getParameters() as $param)
  154. {
  155. if (!$param->isOptional() && !isset($request[$param->getName()]))
  156. throw new Exception(sprintf("Missing required parameter '%s'", $param->getName()));
  157. else
  158. $args[$param->getName()] = $request[$param->getName()];
  159. }
  160. $result = $ReflectMethod->invokeArgs($this, $args);
  161. $this->LastTransactionID = $result->TransactionID;
  162. // Create response
  163. $DOMDocument = new DOMDocument('1.0', 'UTF-8');
  164. $DOMDocument->loadXML("<{$request['Action']}Response></{$request['Action']}Response>");
  165. $this->ObjectToXML($result, $DOMDocument->documentElement, $DOMDocument);
  166. $retval = $DOMDocument->saveXML();
  167. }
  168. else
  169. throw new Exception(sprintf("Action '%s' is not defined", $request['Action']));
  170. }
  171. catch(Exception $e)
  172. {
  173. if (!$this->LastTransactionID)
  174. $this->LastTransactionID = Scalr::GenerateUID();
  175. if ($request['SysDebug'])
  176. {
  177. $debugInfo = "<StringToSign>{$this->debug['stringToSign']}</StringToSign>";
  178. $debugInfo .= "<reqSignature>{$this->debug['reqSignature']}</reqSignature>";
  179. $debugInfo .= "<validSignature>{$this->debug['validSignature']}</validSignature>";
  180. }
  181. $retval = "<?xml version=\"1.0\"?>\n".
  182. "<Error>\n".
  183. "\t<TransactionID>{$this->LastTransactionID}</TransactionID>\n".
  184. "\t<Message>{$e->getMessage()}</Message>\n".
  185. $debugInfo.
  186. "</Error>\n";
  187. }
  188. $this->LogRequest(
  189. $this->LastTransactionID,
  190. $request['Action'],
  191. (($_SERVER['REMOTE_ADDR'] == API_SERVER_IP) ? 'Mobile app' : $_SERVER['REMOTE_ADDR']),
  192. $request,
  193. $retval
  194. );
  195. header("Content-type: text/xml");
  196. header("Content-length: ".strlen($retval));
  197. print $retval;
  198. }
  199. protected function LogRequest($trans_id, $action, $ipaddr, $request, $response)
  200. {
  201. if ($request['debug'] == 1 || $request['Debug'] == 1)
  202. {
  203. try
  204. {
  205. $this->DB->Execute("INSERT INTO api_log SET
  206. transaction_id = ?,
  207. dtadded = ?,
  208. action = ?,
  209. ipaddress = ?,
  210. request = ?,
  211. response = ?,
  212. clientid = ?,
  213. env_id = ?
  214. ",array(
  215. $trans_id,
  216. time(),
  217. $action,
  218. $ipaddr,
  219. http_build_query($request),
  220. $response,
  221. $this->Client->ID,
  222. $this->Environment->id
  223. ));
  224. }
  225. catch(Exception $e) {}
  226. }
  227. }
  228. protected function IPAccessCheck($allowed_ips)
  229. {
  230. $current_ip = $_SERVER['REMOTE_ADDR'];
  231. $current_ip_parts = explode(".", $current_ip);
  232. foreach ($allowed_ips as $allowed_ip)
  233. {
  234. $allowedhost = trim($allowed_ip);
  235. if ($allowedhost == '')
  236. continue;
  237. if (preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/si", $allowedhost))
  238. {
  239. if (ip2long($allowedhost) == ip2long($current_ip))
  240. return true;
  241. }
  242. elseif (stristr($allowedhost, "*"))
  243. {
  244. $ip_parts = explode(".", trim($allowedhost));
  245. if (
  246. ($ip_parts[0] == "*" || $ip_parts[0] == $current_ip_parts[0]) &&
  247. ($ip_parts[1] == "*" || $ip_parts[1] == $current_ip_parts[1]) &&
  248. ($ip_parts[2] == "*" || $ip_parts[2] == $current_ip_parts[2]) &&
  249. ($ip_parts[3] == "*" || $ip_parts[3] == $current_ip_parts[3])
  250. )
  251. return true;
  252. }
  253. else
  254. {
  255. $ip = @gethostbyname($allowedhost);
  256. if ($ip != $allowedhost)
  257. {
  258. if (ip2long($ip) == ip2long($current_ip))
  259. return true;
  260. }
  261. }
  262. }
  263. return false;
  264. }
  265. protected function ObjectToXML($obj, &$DOMElement, &$DOMDocument)
  266. {
  267. if (is_object($obj) || is_array($obj))
  268. {
  269. foreach ($obj as $k=>$v)
  270. {
  271. if (is_object($v))
  272. $this->ObjectToXML($v, $DOMElement->appendChild($DOMDocument->createElement($k)), $DOMDocument);
  273. elseif (is_array($v))
  274. foreach ($v as $vv)
  275. {
  276. $e = &$DOMElement->appendChild($DOMDocument->createElement($k));
  277. $this->ObjectToXML($vv, $e, $DOMDocument);
  278. }
  279. else
  280. $DOMElement->appendChild($DOMDocument->createElement($k, $v));
  281. }
  282. }
  283. else
  284. $DOMElement->appendChild($DOMDocument->createTextNode($obj));
  285. }
  286. protected function CreateInitialResponse()
  287. {
  288. $response = new stdClass();
  289. $response->{"TransactionID"} = Scalr::GenerateUID();
  290. return $response;
  291. }
  292. }
  293. ?>