Ejemplo n.º 1
0
/**
 *  Send a synchronous request to the  server.
 *  This function manages timeout then will not block if one of the server is down
 *
 * @param url                 The url to get
 * @param response_code       The response code
 *
 * @return The body of the response or "" in case of error
 * @access private
 */
function Swekey_HttpGet($url, &$response_code)
{
    global $gSwekeyLastError;
    $gSwekeyLastError = 0;
    global $gSwekeyLastResult;
    $gSwekeyLastResult = "<not set>";
    // use curl if available
    if (function_exists('curl_init')) {
        $sess = curl_init($url);
        if (substr($url, 0, 8) == "https://") {
            global $gSwekeyCA;
            if (!empty($gSwekeyCA)) {
                if (file_exists($gSwekeyCA)) {
                    if (!curl_setopt($sess, CURLOPT_CAINFO, $gSwekeyCA)) {
                        error_log("SWEKEY_ERROR:Could not set CA file : " . curl_error($sess));
                    } else {
                        $caFileOk = true;
                    }
                } else {
                    error_log("SWEKEY_ERROR:Could not find CA file {$gSwekeyCA} getting {$url}");
                }
            }
            curl_setopt($sess, CURLOPT_SSL_VERIFYHOST, '2');
            curl_setopt($sess, CURLOPT_SSL_VERIFYPEER, '2');
            curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '20');
            curl_setopt($sess, CURLOPT_TIMEOUT, '20');
        } else {
            curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '3');
            curl_setopt($sess, CURLOPT_TIMEOUT, '5');
        }
        curl_setopt($sess, CURLOPT_RETURNTRANSFER, '1');
        $res = curl_exec($sess);
        $response_code = curl_getinfo($sess, CURLINFO_HTTP_CODE);
        $curlerr = curl_error($sess);
        curl_close($sess);
        if ($response_code == 200) {
            $gSwekeyLastResult = $res;
            return $res;
        }
        if (!empty($response_code)) {
            $gSwekeyLastError = $response_code;
            error_log("SWEKEY_ERROR:Error {$gSwekeyLastError} ({$curlerr}) getting {$url}");
            return "";
        }
        $response_code = 408;
        // Request Timeout
        $gSwekeyLastError = $response_code;
        error_log("SWEKEY_ERROR:Error {$curlerr} getting {$url}");
        return "";
    }
    // use pecl_http if available
    if (class_exists('HttpRequest')) {
        // retry if one of the server is down
        for ($num = 1; $num <= 3; $num++) {
            $r = new HttpRequest($url);
            $options = array('timeout' => '3');
            if (substr($url, 0, 6) == "https:") {
                $sslOptions = array();
                $sslOptions['verifypeer'] = true;
                $sslOptions['verifyhost'] = true;
                $capath = __FILE__;
                $name = strrchr($capath, '/');
                // windows
                if (empty($name)) {
                    $name = strrchr($capath, '\\');
                }
                $capath = substr($capath, 0, strlen($capath) - strlen($name) + 1) . 'musbe-ca.crt';
                if (!empty($gSwekeyCA)) {
                    $sslOptions['cainfo'] = $gSwekeyCA;
                }
                $options['ssl'] = $sslOptions;
            }
            $r->setOptions($options);
            $reply = $r->send();
            $res = $reply->getBody();
            $info = $r->getResponseInfo();
            $response_code = $info['response_code'];
            if ($response_code != 200) {
                $gSwekeyLastError = $response_code;
                error_log("SWEKEY_ERROR:Error " . $gSwekeyLastError . " getting " . $url);
                return "";
            }
            $gSwekeyLastResult = $res;
            return $res;
            //           catch (HttpException $e)
            //           {
            //               error_log("SWEKEY_WARNING:HttpException ".$e." getting ".$url);
            //           }
        }
        $response_code = 408;
        // Request Timeout
        $gSwekeyLastError = $response_code;
        error_log("SWEKEY_ERROR:Error " . $gSwekeyLastError . " getting " . $url);
        return "";
    }
    global $http_response_header;
    $res = @file_get_contents($url);
    $response_code = substr($http_response_header[0], 9, 3);
    //HTTP/1.0
    if ($response_code == 200) {
        $gSwekeyLastResult = $res;
        return $res;
    }
    $gSwekeyLastError = $response_code;
    error_log("SWEKEY_ERROR:Error " . $response_code . " getting " . $url);
    return "";
}
Ejemplo n.º 2
0
 public function ajaxAction()
 {
     $this->view = new Lupin_View();
     $method = strtolower($this->_request->getParam('method'));
     $query_uri = trim($this->_request->getParam('query_uri'), '/ ');
     $url = $this->_request->getParam('url');
     $extraParams = $this->_request->getParam('param');
     $params = array('format' => $this->_request->getParam('format'));
     if (!empty($extraParams)) {
         foreach ($extraParams as $newParam) {
             $parms = explode('=', $newParam, 2);
             if (count($parms) > 1) {
                 list($key, $value) = $parms;
                 $params[$key] = $value;
             }
         }
     }
     $newMethod = HTTP_METH_GET;
     switch ($method) {
         case 'get':
             $newMethod = HTTP_METH_GET;
             break;
         case 'post':
             $newMethod = HTTP_METH_POST;
             break;
         case 'put':
             $newMethod = HTTP_METH_PUT;
             break;
         case 'delete':
             $newMethod = HTTP_METH_DELETE;
             break;
         case 'head':
             $newMethod = HTTP_METH_HEAD;
             break;
     }
     $email = $this->_request->getParam('email');
     $pass = $this->_request->getParam('secretKey');
     $request_url = 'http://' . $url . '/' . $query_uri;
     $request = new HttpRequest($request_url, $newMethod);
     if ($email && $pass) {
         $encoded_auth = base64_encode($email . ':' . $pass);
         $request->addHeaders(array('Authorization' => 'Basic ' . $encoded_auth));
     }
     if ("post" == $method) {
         $request->addPostFields($params);
     } else {
         $request->addQueryData($params);
     }
     $res = $request->send();
     function collapseHeaders($headers)
     {
         $header_string = "";
         foreach ($headers as $name => $value) {
             $header_string .= $name . ": " . wordwrap($value, 45, "\n\t") . "\n";
         }
         return $header_string;
     }
     $responseInfo = $request->getResponseInfo();
     $response = array('request_url' => $responseInfo['effective_url'], 'response_headers' => collapseHeaders($res->getHeaders()), 'content' => $res->getBody(), 'status' => $res->getResponseCode(), 'method' => strtoupper($method), 'request_post_fields' => http_build_query(!is_null($postFields = $request->getPostFields()) ? $postFields : array()));
     $this->view->renderJson($response);
 }
Ejemplo n.º 3
0
 /**
  * The CreateBucket operation creates a bucket. Not every string is an acceptable bucket name.
  *
  * @param string $bucket_name
  * @return string 
  */
 public function CreateBucket($bucket_name, $region = 'us-east-1')
 {
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)"));
     $timestamp = $this->GetTimestamp(true);
     switch ($region) {
         case "us-east-1":
             $request = "";
             break;
         case "us-west-1":
             $request = "<CreateBucketConfiguration><LocationConstraint>us-west-1</LocationConstraint></CreateBucketConfiguration>";
             break;
         case "eu-west-1":
             $request = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>";
             break;
     }
     $data_to_sign = array("PUT", "", "", $timestamp, "/{$bucket_name}/");
     $signature = $this->GetRESTSignature($data_to_sign);
     $HttpRequest->setUrl("https://{$bucket_name}.s3.amazonaws.com/");
     $HttpRequest->setMethod(constant("HTTP_METH_PUT"));
     $headers = array("Content-length" => strlen($request), "Date" => $timestamp, "Authorization" => "AWS {$this->AWSAccessKeyId}:{$signature}");
     $HttpRequest->addHeaders($headers);
     if ($request != '') {
         $HttpRequest->setPutData($request);
     }
     try {
         $HttpRequest->send();
         $info = $HttpRequest->getResponseInfo();
         if ($info['response_code'] == 200) {
             return true;
         } else {
             if ($HttpRequest->getResponseBody()) {
                 $xml = @simplexml_load_string($HttpRequest->getResponseBody());
                 throw new Exception((string) $xml->Message);
             } else {
                 throw new Exception(_("Cannot create S3 bucket at this time. Please try again later."));
             }
         }
     } catch (HttpException $e) {
         throw new Exception($e->__toString());
     }
 }
Ejemplo n.º 4
0
 private function Request($method, $uri, $args)
 {
     //timeout , connecttimeout , dns_cache_timeout
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)", "timeout" => 30, "connecttimeout" => 10, "dns_cache_timeout" => 5));
     $timestamp = $this->GetTimestamp();
     //$URL = "{$this->Region}.elasticloadbalancing.amazonaws.com";
     $URL = "rds.amazonaws.com";
     $args['Version'] = self::API_VERSION;
     $args['SignatureVersion'] = 2;
     $args['SignatureMethod'] = "HmacSHA256";
     $args['Expires'] = $timestamp;
     $args['AWSAccessKeyId'] = $this->AWSAccessKeyId;
     ksort($args);
     foreach ($args as $k => $v) {
         $CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v);
     }
     $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&");
     $args['Signature'] = $this->GetRESTSignature(array($method, $URL, $uri, $CanonicalizedQueryString));
     $HttpRequest->setUrl("https://{$URL}{$uri}");
     $HttpRequest->setMethod(constant("HTTP_METH_{$method}"));
     if ($args) {
         $HttpRequest->addQueryData($args);
     }
     try {
         $HttpRequest->send();
         $info = $HttpRequest->getResponseInfo();
         $data = $HttpRequest->getResponseData();
         $this->LastResponseHeaders = $data['headers'];
         $response = simplexml_load_string($data['body']);
         if ($response->Error) {
             throw new Exception($response->Error->Message);
         } else {
             return $response;
         }
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
 }
Ejemplo n.º 5
0
		/**
		 * Create new object on S3 Bucket
		 *
		 * @param string $object_path
		 * @param string $bucket_name
		 * @param string $filename
		 * @param string $object_content_type
		 * @param string $object_permissions
		 * @return bool
		 */
		public function CreateObject($object_path, $bucket_name, $filename, $object_content_type, $object_permissions = "public-read")
		{
			if (!file_exists($filename))
			{
				Core::RaiseWarning("{$filename} - no such file.");
				return false;
			}
			
			$HttpRequest = new HttpRequest();
			
			$HttpRequest->setOptions(array(    "redirect" => 10, 
			                                         "useragent" => "LibWebta AWS Client (http://webta.net)"
			                                    )
			                              );
						
			$timestamp = $this->GetTimestamp(true);
			
			$data_to_sign = array("PUT", "", $object_content_type, $timestamp, "x-amz-acl:{$object_permissions}","/{$bucket_name}/{$object_path}");
			$signature = $this->GetRESTSignature($data_to_sign);
			
			$HttpRequest->setUrl("http://{$bucket_name}.s3.amazonaws.com/{$object_path}");
		    $HttpRequest->setMethod(constant("HTTP_METH_PUT"));
		   	 
		    $headers["Content-type"] = $object_content_type;
		    $headers["x-amz-acl"] = $object_permissions;
		    $headers["Date"] = $timestamp;
            $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}";
			                
            $HttpRequest->addHeaders($headers);
            
            $HttpRequest->setPutFile($filename);
            
            try 
            {
                $HttpRequest->send();
                
                $info = $HttpRequest->getResponseInfo();
                
                if ($info['response_code'] == 200)
                	return true;
                else
                {
                	$xml = @simplexml_load_string($HttpRequest->getResponseBody());                	
                	return $xml->Message;
                }
            }
            catch (HttpException $e)
            {
                Core::RaiseWarning($e->__toString(), E_ERROR);
		        return false;
            }
		}
Ejemplo n.º 6
0
 /**
  * Test an action
  *
  * This is the test action method. It test a specific action.
  *
  * @return void
  */
 public function testAction()
 {
     $this->_helper->viewRenderer->setViewSuffix('txt');
     // The options we are accepting for adding
     $options = new Zend_Console_Getopt(array('name|n=s' => 'Name of the action to call.', 'parameters|p=s' => 'Paramters to use. For example var1=val1&var2=val2', 'format|f=s' => 'Format to return. Defaults to XML.', 'method|m=s' => 'Method to use. Defaults to GET.', 'email|e=s' => 'Email or username to use.', 'secretkey|sk=s' => 'Secret key associated with email passed.', 'domain|d=s' => 'Domain to use, if not included will use default', 'query-uri|u=s' => 'Query uri to use. For example /testing/1', 'https|h' => 'Use https.'));
     try {
         $options->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         $this->view->message = $e->getUsageMessage();
         return;
     }
     if ($options->name == '') {
         $this->view->message = $options->getUsageMessage();
         return;
     }
     $confModel = new Default_Model_Configuration();
     if (!$confModel->getKey('api_url')) {
         $this->view->message = 'Remember you can set the default API domain name in your admin configuration.' . PHP_EOL;
     }
     if (!class_exists('HttpRequest')) {
         $this->view->message = 'HttpRequest class was not found the pecl_http (http://pecl.php.net/package/pecl_http) package is required to use the tester.' . PHP_EOL;
         return;
     }
     $action_name = $options->name;
     $params = $options->parameters;
     $format = $options->format;
     $method = $options->method;
     $email = $options->email;
     $password = $options->secretkey;
     $url = $options->domain;
     $ssl = $options->https;
     $query_uri = $options->getOption('query-uri');
     if ($url == '') {
         $url = $confModel->getKey('api_url');
     }
     if ($query_uri == '') {
         $actionModel = new Default_Model_Action();
         $actions = $actionModel->getAll();
         foreach ($actions as $action_details) {
             if ($action_details['name'] == $action_name) {
                 $query_uri = $action_details['route'];
             }
         }
     }
     $newMethod = HTTP_METH_GET;
     switch (strtolower($method)) {
         case 'get':
             $newMethod = HTTP_METH_GET;
             break;
         case 'post':
             $newMethod = HTTP_METH_POST;
             break;
         case 'put':
             $newMethod = HTTP_METH_PUT;
             break;
         case 'delete':
             $newMethod = HTTP_METH_DELETE;
             break;
         case 'head':
             $newMethod = HTTP_METH_HEAD;
             break;
     }
     $request_url = 'http' . ($ssl !== null ? 's' : '') . '://' . $url . '/' . $query_uri . '.' . strtolower($format);
     $httpOptions = array();
     if ($email && $password) {
         $httpOptions = array('headers' => array('Accept' => '*/*'), 'httpauth' => $email . ':' . $password, 'httpauthtype' => HTTP_AUTH_DIGEST);
     }
     $request = new HttpRequest($request_url, $newMethod, $httpOptions);
     if ("POST" == strtoupper($method)) {
         $request->setBody($params);
     } else {
         $request->setQueryData($params);
     }
     $res = $request->send();
     $responseInfo = $request->getResponseInfo();
     $this->view->request_url = $responseInfo['effective_url'];
     $this->view->response_header = $this->collapseHeaders($res->getHeaders());
     $this->view->content = $res->getBody();
     $this->view->status = $res->getResponseCode();
     $this->view->method = isset($method) ? strtoupper($method) : 'GET';
     $this->view->request_post_fields = $newMethod == HTTP_METH_POST ? $params : '';
 }
Ejemplo n.º 7
0
 public function ajaxAction()
 {
     $this->view = new Lupin_View();
     $method = strtolower($this->_request->getParam('method'));
     $query_uri = trim($this->_request->getParam('query_uri'), '/ ');
     $url = $this->_request->getParam('url');
     $ssl = $this->_request->getParam('ssl');
     $extraParams = $this->_request->getParam('param');
     $params = array();
     if (!empty($extraParams)) {
         foreach ($extraParams as $newParam) {
             $parms = explode('=', $newParam, 2);
             if (count($parms) > 1) {
                 list($key, $value) = $parms;
                 $params[$key] = $value;
             }
         }
     }
     $newMethod = HTTP_METH_GET;
     switch ($method) {
         case 'get':
             $newMethod = HTTP_METH_GET;
             break;
         case 'post':
             $newMethod = HTTP_METH_POST;
             break;
         case 'put':
             $newMethod = HTTP_METH_PUT;
             break;
         case 'delete':
             $newMethod = HTTP_METH_DELETE;
             break;
         case 'head':
             $newMethod = HTTP_METH_HEAD;
             break;
     }
     $email = $this->_request->getParam('email');
     $pass = $this->_request->getParam('secretKey');
     $request_url = 'http' . ($ssl !== null ? 's' : '') . '://' . $url . '/' . $query_uri;
     $httpOptions = array();
     if ($email && $pass) {
         $httpOptions = array('headers' => array('Accept' => '*/*'), 'httpauth' => $email . ':' . $pass, 'httpauthtype' => HTTP_AUTH_DIGEST);
     }
     $request = new HttpRequest($request_url, $newMethod, $httpOptions);
     if ("post" == $method) {
         $request->addPostFields($params);
     } else {
         $request->addQueryData($params);
     }
     $res = $request->send();
     $responseInfo = $request->getResponseInfo();
     $response = array('request_url' => $responseInfo['effective_url'], 'response_headers' => $this->collapseHeaders($res->getHeaders()), 'content' => $res->getBody(), 'status' => $res->getResponseCode(), 'method' => strtoupper($method), 'request_post_fields' => http_build_query(!is_null($postFields = $request->getPostFields()) ? $postFields : array()));
     $this->view->renderJson($response);
 }
Ejemplo n.º 8
0
 protected function assertLocation($expected)
 {
     self::assertEquals($expected, $this->request->getResponseInfo('effective_url'));
 }