Пример #1
0
function get_raw_chain($host, $port = 443)
{
    global $timeout;
    $data = [];
    $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true)));
    $read_stream = stream_socket_client("ssl://{$host}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream);
    if ($read_stream === false) {
        return false;
    } else {
        $context = stream_context_get_params($read_stream);
        $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta'];
        $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);
        $chain_data = $context["options"]["ssl"]["peer_certificate_chain"];
        $chain_length = count($chain_data);
        if (isset($chain_data) && $chain_length < 10) {
            foreach ($chain_data as $key => $value) {
                $data["chain"][$key] = $value;
            }
        } else {
            $data["error"] = ["Chain too long."];
            return $data;
        }
    }
    return $data;
}
Пример #2
0
 function getOptions()
 {
     if (empty($this->_options)) {
         $this->_options->merge(stream_context_get_options($this->_resource));
     }
     return $this->_options;
 }
 /**
  * {@inheritDoc}
  */
 public function getIncomingStream()
 {
     $options = stream_context_get_options($this->context);
     $method = 'GET';
     if (isset($options['http']['method'])) {
         $method = $options['http']['method'];
     }
     $headers = [];
     if (isset($options['http']['header'])) {
         $headerLines = explode("\r\n", $options['http']['header']);
         foreach ($headerLines as $headerLine) {
             list($header, $value) = explode(': ', $headerLine, 2);
             $headers[$header][] = $value;
         }
     }
     $body = null;
     if (isset($options['http']['content'])) {
         $body = $options['http']['content'];
     }
     $protocolVersion = 1.1;
     if (isset($options['http']['protocol_version'])) {
         $protocolVersion = $options['http']['protocol_version'];
     }
     $request = new Request($method, $this->path, $headers, $body, $protocolVersion);
     return \GuzzleHttp\Psr7\stream_for(\GuzzleHttp\Psr7\str($request));
 }
Пример #4
0
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     $context = stream_context_get_options($this->context);
     $this->state = $context['nativesmb']['state'];
     $this->handle = $context['nativesmb']['handle'];
     return true;
 }
Пример #5
0
 /**
  * {@inheritDoc}
  */
 public function __construct()
 {
     $defaults = stream_context_get_options(stream_context_get_default());
     $this->adapter = $defaults[Filesystem::PROTOCOL]['adapter'];
     $this->logger = $defaults[Filesystem::PROTOCOL]['logger'];
     $this->logger->debug(__METHOD__);
 }
Пример #6
0
 public static function applyInitPathHook($url, $context = 'core')
 {
     $params = [];
     $parts = AJXP_Utils::safeParseUrl($url);
     if (!($params = self::getLocalParams(self::CACHE_KEY . $url))) {
         // Nothing in cache
         $repositoryId = $parts["host"];
         $repository = ConfService::getRepositoryById($parts["host"]);
         if ($repository == null) {
             throw new \Exception("Cannot find repository");
         }
         $configHost = $repository->getOption('HOST');
         $configPath = $repository->getOption('PATH');
         $params['path'] = $parts['path'];
         $params['basepath'] = $configPath;
         $params['itemname'] = basename($params['path']);
         // Special case for root dir
         if (empty($params['path']) || $params['path'] == '/') {
             $params['path'] = '/';
         }
         $params['path'] = dirname($params['path']);
         $params['fullpath'] = rtrim($params['path'], '/') . '/' . $params['itemname'];
         $params['base_url'] = $configHost;
         $params['keybase'] = $repositoryId . $params['fullpath'];
         $params['key'] = md5($params['keybase']);
         self::addLocalParams(self::CACHE_KEY . $url, $params);
     }
     $repoData = self::actualRepositoryWrapperData($parts["host"]);
     $repoProtocol = $repoData['protocol'];
     $default = stream_context_get_options(stream_context_get_default());
     $default[$repoProtocol]['path'] = $params;
     $default[$repoProtocol]['client']->setDefaultUrl($configHost);
     stream_context_set_default($default);
 }
Пример #7
0
 private function checkoutExistingSocket($uri, $options)
 {
     if (empty($this->sockets[$uri])) {
         return null;
     }
     $needsRebind = false;
     foreach ($this->sockets[$uri] as $socketId => $poolStruct) {
         if (!$poolStruct->isAvailable) {
             continue;
         } elseif ($this->isSocketDead($poolStruct->resource)) {
             unset($this->sockets[$uri][$socketId]);
         } elseif (($bindToIp = @stream_context_get_options($poolStruct->resource)['socket']['bindto']) && $bindToIp == $options[self::OP_BINDTO]) {
             $poolStruct->isAvailable = false;
             $this->reactor->disable($poolStruct->idleWatcher);
             return $poolStruct->resource;
         } elseif ($bindToIp) {
             $needsRebind = true;
         } else {
             $poolStruct->isAvailable = false;
             $this->reactor->disable($poolStruct->idleWatcher);
             return $poolStruct->resource;
         }
     }
     $this->needsRebind = $needsRebind;
     return null;
 }
Пример #8
0
 function stream_open($path, $mode, $options, &$opened_path)
 {
     if ($this->context) {
         print_r(stream_context_get_options($this->context));
     }
     return false;
 }
Пример #9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->rfs = new RemoteFilesystem($this->getIO());
     $output->write('Checking platform settings: ');
     $this->outputResult($output, $this->checkPlatform());
     $output->write('Checking http connectivity: ');
     $this->outputResult($output, $this->checkHttp());
     $opts = stream_context_get_options(StreamContextFactory::getContext());
     if (!empty($opts['http']['proxy'])) {
         $output->write('Checking HTTP proxy: ');
         $this->outputResult($output, $this->checkHttpProxy());
         $output->write('Checking HTTPS proxy support for request_fulluri: ');
         $this->outputResult($output, $this->checkHttpsProxyFullUriRequestParam());
     }
     $composer = $this->getComposer(false);
     if ($composer) {
         $output->write('Checking composer.json: ');
         $this->outputResult($output, $this->checkComposerSchema());
     }
     if ($composer) {
         $config = $composer->getConfig();
     } else {
         $config = Factory::createConfig();
     }
     if ($oauth = $config->get('github-oauth')) {
         foreach ($oauth as $domain => $token) {
             $output->write('Checking ' . $domain . ' oauth access: ');
             $this->outputResult($output, $this->checkGithubOauth($domain, $token));
         }
     }
     $output->write('Checking composer version: ');
     $this->outputResult($output, $this->checkVersion());
     return $this->failures;
 }
 /**
  * Creates a stream context based on the provided configuration.
  *
  * @param ConfigInterface $config The configuration.
  *
  * @return resource A stream context based on the provided configuration.
  */
 public function create(ConfigInterface $config)
 {
     $options = array();
     $headers = array();
     $proxy = $config->get('proxy');
     if (is_array($proxy)) {
         $options = array('http' => array('proxy' => $proxy['proxy_host'] . ':' . $proxy['proxy_port']));
         if (isset($proxy['proxy_login']) && isset($proxy['proxy_password'])) {
             // Support for proxy authentication is untested. The current implementation is based on
             // http://php.net/manual/en/function.stream-context-create.php#74431.
             $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($proxy['proxy_login'] . ':' . $proxy['proxy_password']);
         }
     }
     $soapOptions = $config->get('soapClientOptions');
     if ((!isset($soapOptions['authentication']) || $soapOptions['authentication'] === SOAP_AUTHENTICATION_BASIC) && isset($soapOptions['login']) && isset($soapOptions['password'])) {
         $headers[] = 'Authorization: Basic ' . base64_encode($soapOptions['login'] . ':' . $soapOptions['password']);
     }
     if (count($headers) > 0) {
         $options['http']['header'] = $headers;
     }
     // If we already created a stream context, make sure we use the same options.
     if (isset($soapOptions['stream_context'])) {
         $options = array_merge($options, stream_context_get_options($soapOptions['stream_context']));
     }
     return stream_context_create($options);
 }
 public function testStreamContext()
 {
     $context = stream_context_get_options($this->context)['swiftfs'];
     $this->assertNotEmpty($context['token']);
     $this->assertNotEmpty($context['swift_endpoint']);
     $this->assertEquals(self::FTYPE, $context['content_type']);
 }
/**
 * Replace file_get_contents()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/function.file_get_contents
 * @author      Aidan Lister <*****@*****.**>
 * @author      Arpad Ray <*****@*****.**>
 * @version     $Revision: 280045 $
 * @internal    resource_context is only supported for PHP 4.3.0+ (stream_context_get_options)
 * @since       PHP 4.3.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_file_get_contents($filename, $incpath = false, $resource_context = null, $offset = -1, $maxlen = -1)
{
    if (is_resource($resource_context) && function_exists('stream_context_get_options')) {
        $opts = stream_context_get_options($resource_context);
    }
    $colon_pos = strpos($filename, '://');
    $wrapper = $colon_pos === false ? 'file' : substr($filename, 0, $colon_pos);
    $opts = empty($opts) || empty($opts[$wrapper]) ? array() : $opts[$wrapper];
    $data = false;
    switch ($wrapper) {
        case 'http':
            $max_redirects = isset($opts[$wrapper]['max_redirects']) ? $opts[$proto]['max_redirects'] : PHP_COMPAT_FILE_GET_CONTENTS_MAX_REDIRECTS;
            for ($i = 0; $i < $max_redirects; $i++) {
                $data = php_compat_http_get_contents_helper($filename, $opts);
                if (is_array($contents)) {
                    // redirected
                    $filename = rtrim($contents[1]);
                    $data = '';
                    continue;
                }
                break 2;
            }
            user_error('redirect limit exceeded', E_USER_WARNING);
            return;
        case 'ftp':
        case 'https':
        case 'ftps':
        case 'socket':
            // tbc
    }
    if (false === $data) {
        if (is_resource($resource_context) && version_compare(PHP_VERSION, '4.3.0', 'ge')) {
            $fh = fopen($filename, 'rb', $incpath, $resource_context);
        } else {
            $fh = fopen($filename, 'rb', $incpath);
        }
        if (false === $fh) {
            user_error('failed to open stream: No such file or directory', E_USER_WARNING);
            return false;
        }
        clearstatcache();
        if ($fsize = @filesize($filename)) {
            $data = fread($fh, $fsize);
        } else {
            $data = '';
            while (!feof($fh)) {
                $data .= fread($fh, 8192);
            }
        }
        fclose($fh);
    }
    if ($offset != -1) {
        $data = substr($data, $offset);
    }
    if ($maxlen != -1) {
        $data = substr($data, 0, $maxlen);
    }
    return $data;
}
Пример #13
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $composer = $this->getComposer(false);
     if ($composer) {
         $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
         $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
         $this->getIO()->write('Checking composer.json: ', false);
         $this->outputResult($this->checkComposerSchema());
     }
     if ($composer) {
         $config = $composer->getConfig();
     } else {
         $config = Factory::createConfig();
     }
     $this->rfs = new RemoteFilesystem($this->getIO(), $config);
     $this->process = new ProcessExecutor($this->getIO());
     $this->getIO()->write('Checking platform settings: ', false);
     $this->outputResult($this->checkPlatform());
     $this->getIO()->write('Checking git settings: ', false);
     $this->outputResult($this->checkGit());
     $this->getIO()->write('Checking http connectivity: ', false);
     $this->outputResult($this->checkHttp());
     $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
     if (!empty($opts['http']['proxy'])) {
         $this->getIO()->write('Checking HTTP proxy: ', false);
         $this->outputResult($this->checkHttpProxy());
         $this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false);
         $this->outputResult($this->checkHttpProxyFullUriRequestParam());
         $this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false);
         $this->outputResult($this->checkHttpsProxyFullUriRequestParam());
     }
     if ($oauth = $config->get('github-oauth')) {
         foreach ($oauth as $domain => $token) {
             $this->getIO()->write('Checking ' . $domain . ' oauth access: ', false);
             $this->outputResult($this->checkGithubOauth($domain, $token));
         }
     } else {
         $this->getIO()->write('Checking github.com rate limit: ', false);
         try {
             $rate = $this->getGithubRateLimit('github.com');
             $this->outputResult(true);
             if (10 > $rate['remaining']) {
                 $this->getIO()->write('<warning>WARNING</warning>');
                 $this->getIO()->write(sprintf('<comment>Github has a rate limit on their API. ' . 'You currently have <options=bold>%u</options=bold> ' . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL . '    https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>', $rate['remaining'], $rate['limit']));
             }
         } catch (\Exception $e) {
             if ($e instanceof TransportException && $e->getCode() === 401) {
                 $this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
             } else {
                 $this->outputResult($e);
             }
         }
     }
     $this->getIO()->write('Checking disk free space: ', false);
     $this->outputResult($this->checkDiskSpace($config));
     $this->getIO()->write('Checking composer version: ', false);
     $this->outputResult($this->checkVersion());
     return $this->failures;
 }
Пример #14
0
 /**
  * Returns HTTP options from current stream context.
  *
  * @see http://php.net/manual/en/context.http.php
  * @return array HTTP options.
  */
 protected static function getHttpOptionsFromContext($context)
 {
     if (!$context) {
         return array();
     }
     $options = stream_context_get_options($context);
     return !empty($options['http']) ? $options['http'] : array();
 }
Пример #15
0
 public static function file_get_contents($url, $flags = null, $context = null, $offset = null, $maxlen = null)
 {
     // Not a URL? Do not handle.
     if (strpos($url, '://') === false) {
         return file_get_contents($url, $flags, $context, $offset, $maxlen);
     }
     if ($url != static::$url) {
         self::$httpstatus = 404;
     }
     global $http_response_header_test;
     if (self::$setHeaders && self::$httpstatus != 404) {
         $http_response_header_test = array('HTTP/1.1 ' . self::$httpstatus);
     } else {
         $http_response_header_test = null;
     }
     if (self::$httpstatus != 200) {
         return '';
     }
     // Get the from/to from the context
     $from = 0;
     $to = 0;
     if (is_resource($context)) {
         $contextOptions = stream_context_get_options($context);
         if (isset($contextOptions['http']) && isset($contextOptions['http']['header'])) {
             $headers = $contextOptions['http']['header'];
             $headers = explode("\r\n", $headers);
             foreach ($headers as $line) {
                 if (substr($line, 0, 13) != 'Range: bytes=') {
                     continue;
                 }
                 $line = substr($line, 13);
                 $line = trim($line, "\r\n=");
                 list($from, $to) = explode('-', $line);
             }
         }
     }
     if (empty($from) && empty($to)) {
         return self::returnBytes(self::$returnSize);
     }
     $buffer = '';
     if (empty($from)) {
         $from = 0;
     }
     if ($from > self::$returnSize - 1) {
         return '';
     }
     if ($from < 0) {
         $from = 0;
     }
     if (empty($to)) {
         $to = self::$returnSize - 1;
     }
     if ($to > self::$returnSize - 1) {
         $to = self::$returnSize - 1;
     }
     $bytes = 1 + $to - $from;
     return self::returnBytes($bytes);
 }
function get_CN($context)
{
    $ary = stream_context_get_options($context);
    assert($ary);
    $cert = $ary['ssl']['peer_certificate'];
    assert($cert);
    $cert_ary = openssl_x509_parse($cert);
    return $cert_ary['subject']['CN'];
}
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     $options = stream_context_get_options($this->context);
     if (!isset($options['guzzle']['stream'])) {
         return false;
     }
     $this->mode = $mode;
     $this->stream = $options['guzzle']['stream'];
     return true;
 }
Пример #18
0
 public function testContextOptionsAreSecureDefaults()
 {
     $context = $this->mozCertData->getStreamContext();
     $opts = stream_context_get_options($context);
     $this->assertSame(true, $opts['ssl']['capture_peer_cert']);
     $this->assertSame(true, $opts['ssl']['verify_peer']);
     $this->assertSame(false, $opts['ssl']['allow_self_signed']);
     $this->assertRegExp('/^.+\\.(pem|crt)$/', $opts['ssl']['cafile']);
     $this->assertSame('mxr.mozilla.org', $opts['ssl']['CN_match']);
 }
Пример #19
0
 public function createConnection($socket)
 {
     $context = stream_context_get_options($socket);
     if (array_key_exists('ssl', $context)) {
         $conn = new SecureConnection($socket, $this->loop);
     } else {
         $conn = new Connection($socket, $this->loop);
     }
     return $conn;
 }
Пример #20
0
 public final function stream_open($path, $mode, $options, &$opened_path)
 {
     $params = stream_context_get_options($this->context);
     if (!isset($params['mock']['object']) || !is_object($params['mock']['object']) || $mode != 'a+t') {
         return false;
     }
     $opened_path = $path;
     $this->mock =& $params['mock']['object'];
     return true;
 }
Пример #21
0
 public function testGetSetTimeout()
 {
     $this->assertEqual(30, $this->socket->timeout());
     $this->assertEqual(25, $this->socket->timeout(25));
     $this->assertEqual(25, $this->socket->timeout());
     $this->socket->open();
     $this->assertEqual(25, $this->socket->timeout());
     $result = stream_context_get_options($this->socket->resource());
     $this->assertEqual(25, $result['http']['timeout']);
 }
Пример #22
0
 /**
  * @param string
  * @param string
  * @param int
  * @param string
  */
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     $options = stream_context_get_options($this->context);
     if (!(isset($options[self::PROTOCOL]['handle']) && isset($options[self::PROTOCOL]['out']))) {
         throw new Error('no handle or out given');
     }
     $this->handle = $options[self::PROTOCOL]['handle'];
     $this->out = $options[self::PROTOCOL]['out'];
     return TRUE;
 }
Пример #23
0
 /**
  * Execute an HTTP Request
  *
  * @param Google_0814_HttpRequest $request the http request to be executed
  * @return Google_0814_HttpRequest http request with the response http code,
  * response headers and response body filled in
  * @throws Google_0814_IO_Exception on curl or IO error
  */
 public function executeRequest(Google_0814_Http_Request $request)
 {
     $default_options = stream_context_get_options(stream_context_get_default());
     $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array();
     if ($request->getPostBody()) {
         $requestHttpContext["content"] = $request->getPostBody();
     }
     $requestHeaders = $request->getRequestHeaders();
     if ($requestHeaders && is_array($requestHeaders)) {
         $headers = "";
         foreach ($requestHeaders as $k => $v) {
             $headers .= "{$k}: {$v}\r\n";
         }
         $requestHttpContext["header"] = $headers;
     }
     $requestHttpContext["method"] = $request->getRequestMethod();
     $requestHttpContext["user_agent"] = $request->getUserAgent();
     $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array();
     if (!array_key_exists("cafile", $requestSslContext)) {
         $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
     }
     $options = array("http" => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext), "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext));
     $context = stream_context_create($options);
     $url = $request->getUrl();
     if ($request->canGzip()) {
         $url = self::ZLIB . $url;
     }
     // We are trapping any thrown errors in this method only and
     // throwing an exception.
     $this->trappedErrorNumber = null;
     $this->trappedErrorString = null;
     // START - error trap.
     set_error_handler(array($this, 'trapError'));
     $fh = fopen($url, 'r', false, $context);
     restore_error_handler();
     // END - error trap.
     if ($this->trappedErrorNumber) {
         throw new Google_0814_IO_Exception(sprintf("HTTP Error: Unable to connect: '%s'", $this->trappedErrorString), $this->trappedErrorNumber);
     }
     $response_data = false;
     $respHttpCode = self::UNKNOWN_CODE;
     if ($fh) {
         if (isset($this->options[self::TIMEOUT])) {
             stream_set_timeout($fh, $this->options[self::TIMEOUT]);
         }
         $response_data = stream_get_contents($fh);
         fclose($fh);
         $respHttpCode = $this->getHttpResponseCode($http_response_header);
     }
     if (false === $response_data) {
         throw new Google_0814_IO_Exception(sprintf("HTTP Error: Unable to connect: '%s'", $respHttpCode), $respHttpCode);
     }
     $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
     return array($response_data, $responseHeaders, $respHttpCode);
 }
Пример #24
0
 /**
  * Execute a apiHttpRequest.
  *
  * @param Google_HttpRequest $request the http request to be executed
  *
  * @throws Google_IOException on curl or IO error
  *
  * @return Google_HttpRequest http request with the response http code,
  *                            response headers and response body filled in
  */
 public function makeRequest(Google_Http_Request $request)
 {
     // First, check to see if we have a valid cached version.
     $cached = $this->getCachedRequest($request);
     if ($cached !== false) {
         if (!$this->checkMustRevalidateCachedRequest($cached, $request)) {
             return $cached;
         }
     }
     $default_options = stream_context_get_options(stream_context_get_default());
     $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : [];
     if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
         $request = $this->processEntityRequest($request);
     }
     if ($request->getPostBody()) {
         $requestHttpContext['content'] = $request->getPostBody();
     }
     $requestHeaders = $request->getRequestHeaders();
     if ($requestHeaders && is_array($requestHeaders)) {
         $headers = '';
         foreach ($requestHeaders as $k => $v) {
             $headers .= "{$k}: {$v}\n";
         }
         $requestHttpContext['header'] = $headers;
     }
     $requestHttpContext['method'] = $request->getRequestMethod();
     $requestHttpContext['user_agent'] = $request->getUserAgent();
     $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : [];
     if (!array_key_exists('cafile', $requestSslContext)) {
         $requestSslContext['cafile'] = dirname(__FILE__) . '/cacerts.pem';
     }
     $options = ['http' => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext), 'ssl' => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)];
     $context = stream_context_create($options);
     $response_data = file_get_contents($request->getUrl(), false, $context);
     if (false === $response_data) {
         throw new Google_IOException('HTTP Error: Unable to connect');
     }
     $respHttpCode = $this->getHttpResponseCode($http_response_header);
     $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
     if ($respHttpCode == 304 && $cached) {
         // If the server responded NOT_MODIFIED, return the cached request.
         $this->updateCachedRequest($cached, $responseHeaders);
         return $cached;
     }
     if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) {
         $responseHeaders['Date'] = date('r');
     }
     $request->setResponseHttpCode($respHttpCode);
     $request->setResponseHeaders($responseHeaders);
     $request->setResponseBody($response_data);
     // Store the request in cache (the function checks to see if the request
     // can actually be cached)
     $this->setCachedRequest($request);
     return $request;
 }
Пример #25
0
function check_json($host, $ip, $port)
{
    global $timeout;
    $data = [];
    $stream = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "capture_peer_cert_chain" => true, "verify_peer" => false, "peer_name" => $host, "verify_peer_name" => false, "allow_self_signed" => true, "capture_session_meta" => true, "sni_enabled" => true)));
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $connect_ip = "[" . $ip . "]";
    } else {
        $connect_ip = $ip;
    }
    $read_stream = stream_socket_client("ssl://{$connect_ip}:{$port}", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $stream);
    if ($read_stream === false) {
        $data["error"] = ["Failed to connect: " . htmlspecialchars($errstr)];
        return $data;
    } else {
        $context = stream_context_get_params($read_stream);
        $context_meta = stream_context_get_options($read_stream)['ssl']['session_meta'];
        $cert_data = openssl_x509_parse($context["options"]["ssl"]["peer_certificate"]);
        $chain_data = $context["options"]["ssl"]["peer_certificate_chain"];
        $chain_length = count($chain_data);
        if (isset($chain_data) && $chain_length < 10) {
            $chain_length = count($chain_data);
            $chain_arr_keys = $chain_data;
            foreach (array_keys($chain_arr_keys) as $key) {
                $curr = $chain_data[$key];
                $next = $chain_data[$key + 1];
                $prev = $chain_data[$key - 1];
                $chain_key = (string) $key + 1;
                if ($key == 0) {
                    $data["connection"] = ssl_conn_metadata_json($host, $ip, $port, $read_stream, $chain_data);
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, $host, $ip, true);
                } else {
                    $data["chain"][$chain_key] = cert_parse_json($curr, $next, null, false);
                }
                // certificate transparency
                $ct_urls = ["https://ct.ws.symantec.com", "https://ct.googleapis.com/pilot", "https://ct.googleapis.com/aviator", "https://ct.googleapis.com/rocketeer", "https://ct1.digicert-ct.com/log", "https://ct.izenpe.com", "https://ctlog.api.venafi.com", "https://log.certly.io"];
                $data["certificate_transparency"] = [];
                foreach ($ct_urls as $ct_url) {
                    $submitToCT = submitCertToCT($data["chain"], $ct_url);
                    $ct_result = json_decode($submitToCT, TRUE);
                    if ($ct_result === null && json_last_error() !== JSON_ERROR_NONE) {
                        $result_ct = array('result' => $submitToCT);
                        $data["certificate_transparency"][$ct_url] = $result_ct;
                    } else {
                        $data["certificate_transparency"][$ct_url] = $ct_result;
                    }
                }
            }
        } else {
            $data["error"] = ["Chain too long."];
            return $data;
        }
    }
    return $data;
}
Пример #26
0
 public function testGetSetTimeout()
 {
     $subject = new Context($this->_testConfig);
     $this->assertEqual(4, $subject->timeout());
     $this->assertEqual(25, $subject->timeout(25));
     $this->assertEqual(25, $subject->timeout());
     $subject->open();
     $this->assertEqual(25, $subject->timeout());
     $result = stream_context_get_options($subject->resource());
     $this->assertEqual(25, $result['http']['timeout']);
 }
Пример #27
0
 /**
  * Initializes observr collections by aliasing
  * stream_context_set_option and stream_context_set_params
  */
 private function initialize()
 {
     $this->options->merge(\stream_context_get_options($this->context));
     $this->options->attach('set', function ($sender, $e) {
         \stream_context_set_option($this->context, $this->wrapper, $e->offset, $e->value);
     });
     $this->data->merge(\stream_context_get_params($this->context));
     $this->data->attach('set', function ($sender, $e) {
         \stream_context_set_params($this->context, $this->data->toArray());
     });
 }
Пример #28
0
 public static function file_get_contents($url, $use_include_path = false, $stream_context = null)
 {
     if (in_array(ini_get('allow_url_fopen'), array('On', 'on', '1')) || !preg_match('/^https?:\\/\\//', $url)) {
         $response = @file_get_contents($url, $use_include_path, $stream_context);
         if (isset($http_response_header)) {
             $matches = array();
             preg_match('#HTTP/\\d+\\.\\d+ (\\d+)#', $http_response_header[0], $matches);
             $http_status_code = $matches[1];
             if ($http_status_code != 200 && $http_status_code != 201) {
                 throw new Exception('', $http_status_code);
             }
         }
         return $response;
     }
     if (function_exists('curl_init')) {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
         curl_setopt($curl, CURLOPT_TIMEOUT, 8);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
         if ($stream_context != null) {
             $opts = stream_context_get_options($stream_context);
             $headers = array();
             //add headers from stream context
             if (isset($opts['http']['header'])) {
                 $_headers = explode("\r\n", $opts['http']['header']);
                 //remove last or empty
                 $_headers = array_filter($_headers, 'strlen');
                 array_merge($headers, $_headers);
             }
             //set POST fields
             if (isset($opts['http']['method']) && Tools::strtolower($opts['http']['method']) == 'post') {
                 curl_setopt($curl, CURLOPT_POST, true);
                 if (isset($opts['http']['content'])) {
                     $jsonData = $opts['http']['content'];
                     curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
                     $headers[] = 'Content-Type: application/json';
                     $headers[] = 'Content-Length: ' . Tools::strlen($jsonData);
                 }
             }
             curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
         }
         $response = curl_exec($curl);
         $http_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
         if ($http_status_code != 200 && $http_status_code != 201) {
             throw new Exception('', $http_status_code);
         }
         curl_close($curl);
         return $response;
     } else {
         return false;
     }
 }
Пример #29
0
 /**
  * @param string $prefix
  */
 public function __construct(S3Client $client)
 {
     $protocol = 'dspace';
     $this->client = $client;
     $default = stream_context_get_options(stream_context_get_default());
     $default[$protocol]['client'] = $client;
     if (!isset($default[$protocol]['cache'])) {
         // Set a default cache adapter.
         $default[$protocol]['cache'] = new LruArrayCache();
     }
     stream_context_set_default($default);
 }
Пример #30
0
 private function generateWriteFailureMessage()
 {
     $sockContext = @stream_context_get_options($this->socket);
     if ($this->bytesWritten === 0 && empty($sockContext['ssl'])) {
         $msg = "Socket connection failed before data could be fully written. This *may* have ";
         $msg .= "occurred because you're attempting to connect via HTTP when the remote server ";
         $msg .= "only supports encrypted HTTPS connections. Try your request using an https:// URI.";
     } else {
         $msg = 'Connection to server severed before the request write could complete.';
     }
     return $msg;
 }