function checkOpenSSLSupport()
 {
     if (!in_array('ssl', stream_get_transports())) {
         return FALSE;
     }
     return TRUE;
 }
/**
 * Detect SSL stream transport
 * @return boolean|string        If returns string has an problem, returns true if ok
*/
function supportSSL()
{
    if (defined('SOCKET_SSL_STREAM')) {
        return true;
    }
    if (function_exists('stream_get_transports')) {
        /* PHP 5 */
        $ok = in_array('ssl', stream_get_transports());
        if ($ok) {
            defined('SOCKET_SSL_STREAM', '1');
            return true;
        }
    } else {
        /* PHP 4 */
        ob_start();
        phpinfo(1);
        $info = strtolower(ob_get_clean());
        if (preg_match('/socket\\stransports/', $info) !== 0) {
            if (preg_match('/(ssl[,]|ssl [,]|[,] ssl|[,]ssl)/', $info) !== 0) {
                defined('SOCKET_SSL_STREAM', '1');
                return true;
            } else {
                return 'No SSL stream support detected';
            }
        }
    }
    return 'Don\'t detected streams (finder error), no SSL stream support';
}
 /**
  * Setup archive directory and internal migrate data struct.
  *
  * @param array $environment
  *   Environment to migrate to, from NSPI acquia_agent_cloud_migration_environments()
  * @return array $migration
  */
 public function prepare($environment)
 {
     // Internal migration store is an array because objects cannot be stored
     // by Drupal's Batch API.
     $local_env = $this->checkEnv();
     if ($local_env['error'] !== FALSE) {
         return $local_env;
     }
     // Modify environment URL if SSL is available for use.
     if (in_array('ssl', stream_get_transports(), TRUE) && !defined('ACQUIA_DEVELOPMENT_NOSSL')) {
         $uri = parse_url($environment['url']);
         if (isset($uri['host'])) {
             $environment['url'] = $uri['host'];
         }
         $environment['url'] .= isset($uri['port']) ? ':' . $uri['port'] : '';
         $environment['url'] .= isset($uri['path']) && isset($uri['host']) ? $uri['path'] : '';
         $environment['url'] = 'https://' . $environment['url'];
     }
     $time = REQUEST_TIME;
     $date = gmdate('Ymd_his', $time);
     $migration = array('error' => FALSE, 'id' => uniqid() . '_' . $date, 'date' => $date, 'time' => $time, 'compression_ext' => $local_env['compression_ext'], 'request_params' => array('r' => Url::FromRoute('acquia_connector.settings', array(), array('absolute' => TRUE))->toString(), 'y' => 'sar', 'stage' => $environment['stage'], 'nonce' => $environment['nonce']), 'env' => $environment, 'no_data_tables' => array());
     // Set up local storage of archive.
     $this->destination($migration);
     return $migration;
 }
 public function skip()
 {
     $streams = stream_get_transports();
     $this->skipIf(!in_array('ssl', $streams), 'SSL is not configured for your system.  It is not possible to run this test');
     $this->skipIf(!SWIFT_SSL_HOST, 'Cannot run test without an SSL enabled SMTP host to connect to (define ' . 'SWIFT_SSL_HOST in tests/acceptance.conf.php if you wish to run this test)');
     parent::skip();
 }
Beispiel #5
0
 /**
  * Get all enable transports.
  *
  * @return  array
  */
 public static function get()
 {
     static $_ = null;
     if (null === $_) {
         $_ = stream_get_transports();
     }
     return $_;
 }
 public function setUp()
 {
     // skip tests when this PHP has no SSL support
     $transports = stream_get_transports();
     if (!in_array('ssl', $transports)) {
         $this->markTestSkipped('No SSL support available.');
     }
     parent::setUp();
 }
Beispiel #7
0
 /**
  * Validate data.
  *
  * This ensures that unix socket transport is supported by this system.
  *
  * @param string $data
  * @return mixed True on success, else error message.
  */
 public function validate($data)
 {
     if ($data === 'unixsocket') {
         $supportedtransports = stream_get_transports();
         if (!array_search('unix', $supportedtransports)) {
             return get_string('errornounixsocketssupported', 'antivirus_clamav');
         }
     }
     return true;
 }
Beispiel #8
0
 /**
  * Constructor to initialize instance properties.
  *
  * @param int    $port      Port on which the daemon will listen or NULL
  *        to select a port automatically, defaults to NULL
  * @param string $transport Socket transport for the daemon to use,
  *        defaults to 'tcp'
  *
  * @return void
  */
 public function __construct($port = null, $transport = 'tcp')
 {
     if (in_array($transport, stream_get_transports())) {
         $this->transport = $transport;
     } else {
         $this->transport = 'tcp';
     }
     $this->port = $port ? $port : $this->findPort();
     $this->commands = array();
     $this->input = array();
 }
 public function setUp()
 {
     $streams = stream_get_transports();
     if (!in_array('ssl', $streams)) {
         $this->markTestSkipped('SSL is not configured for your system.  It is not possible to run this test');
     }
     if (!defined('SWIFT_SSL_HOST')) {
         $this->markTestSkipped('Cannot run test without an SSL enabled SMTP host to connect to (define ' . 'SWIFT_SSL_HOST in tests/acceptance.conf.php if you wish to run this test)');
     }
     parent::setUp();
 }
 /**
  * Check to make sure all the critical dependencies are available
  *
  * @return boolean
  **/
 public function IsSupported()
 {
     if (function_exists('curl_exec') && defined('CURL_VERSION_SSL')) {
         return true;
     } else {
         if (in_array('ssl', stream_get_transports())) {
             return true;
         } else {
             $this->SetError(GetLang('AuthorizeNetSSLNotAvailable'));
             return false;
         }
     }
 }
Beispiel #11
0
 /**
  * Returns an instance of Swift_Mailer based on the config.s
  * @return \Swift_Mailer
  */
 public function getSwiftMailerFromConfig()
 {
     $encryptionType = $this->getMailConfig('smtp_encryption');
     // Workaround issue where smtp_encryption could == 1 in the past by
     // checking it is a valid transport
     if ($encryptionType && !in_array($encryptionType, stream_get_transports())) {
         $encryptionType = null;
     }
     /** @var \Swift_SmtpTransport $transport */
     $transport = \Swift_SmtpTransport::newInstance($this->getMailConfig('smtp_address'), $this->getMailConfig('smtp_port'), $encryptionType);
     $transport->setUsername($this->getMailConfig('smtp_username'));
     $transport->setPassword($this->getMailConfig('smtp_password'));
     return \Swift_Mailer::newInstance($transport);
 }
 /**
  * Render a selector element that allows to select the encryption method for SMTP
  *
  * @param array $params Field information to be rendered
  *
  * @return string The HTML selector
  */
 public function buildSmtpEncryptSelector(array $params)
 {
     $extConf = GeneralUtility::removeDotsFromTS(unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['mailcopy']));
     $transports = stream_get_transports();
     if (empty($transports)) {
         return '';
     }
     $markup = '<select class="valid" name="' . $params['fieldName'] . '" id=em-' . $params['propertyName'] . '">';
     $active = (string) self::extract($extConf, explode('.', $params['propertyName']));
     foreach ($transports as $transport) {
         $markup .= '<option value="' . $transport . '"' . ($transport === $active ? ' selected="selected"' : '') . '>' . $transport . '</option>';
     }
     $markup .= '</select>';
     return $markup;
 }
 public function __construct()
 {
     if (function_exists('fsockopen')) {
         $this->socketExtension = true;
         $this->xportlist = stream_get_transports();
         if (in_array('ssl', $this->xportlist)) {
             $this->sslAvailable = true;
         } else {
             if (in_array('ss', $this->xportlist)) {
                 array_push($this->xportlist, 'ssl');
                 $this->sslAvailable = true;
             }
         }
     } else {
         $this->setError("This class need 'Sockets' extension!");
     }
 }
Beispiel #14
0
 private function establish()
 {
     $unix = in_array("unix", \stream_get_transports(), true);
     if ($unix) {
         $promise = \Amp\Socket\connect("unix://{$this->path}.sock");
     } else {
         $promise = \Amp\pipe(\Amp\file\get($this->path), 'Amp\\Socket\\connect');
     }
     $promise->when(function ($e, $sock) {
         if ($e) {
             $this->failAll();
             return;
         }
         $this->sock = $sock;
         $this->writeWatcher = \Amp\onWritable($sock, $this->writer);
     });
 }
Beispiel #15
0
 /**
  * Checks if minimum system requirements are met for vivvo_ga to function properly
  *
  * @param	&string	$missing	If function returns false passed variable will hold info about missing component
  * @return	bool
  */
 public static function is_supported(&$missing = null)
 {
     $missing = 'php';
     if (version_compare(PHP_VERSION, '5.1.4', '>=') !== false) {
         $missing = 'curl';
         if (extension_loaded('curl')) {
             return !($missing = false);
         }
         $missing = 'socket';
         if (function_exists('stream_socket_client')) {
             $missing = 'ssl';
             if (in_array('ssl', stream_get_transports())) {
                 return !($missing = false);
             }
         }
     }
     return false;
 }
 /**
  * @param int $iPort
  * @param int $iSecurityType
  *
  * @return bool
  */
 public static function UseSSL($iPort, $iSecurityType)
 {
     $iPort = (int) $iPort;
     $iResult = (int) $iSecurityType;
     if (self::AUTO_DETECT === $iSecurityType) {
         switch (true) {
             case 993 === $iPort:
             case 995 === $iPort:
             case 465 === $iPort:
                 $iResult = self::SSL;
                 break;
         }
     }
     if (self::SSL === $iResult && !\in_array('ssl', \stream_get_transports())) {
         $iResult = self::NONE;
     }
     return self::SSL === $iResult;
 }
 /**
  * Set URL the client connects to.
  * SSL, port and authentication can be set in the URL.
  *
  * examples:
  * http://www.dummy.com/index.php
  * https://www.dummy.com/index.php
  * http://www.dummy.com:8080/index.php
  * http://user:pass@www.dummy.com/index.php
  *
  * @param string $url
  * @throws BillsafeException
  */
 public function __construct($url)
 {
     $parsedUrl = parse_url($url);
     if (!is_array($parsedUrl) || !isset($parsedUrl['host'])) {
         throw new BillsafeException('Invalid url specified');
     }
     $this->_host = $parsedUrl['host'];
     if (!empty($parsedUrl['path'])) {
         $query = empty($parsedUrl['query']) ? '' : '?' . $parsedUrl['query'];
         $this->_path = $parsedUrl['path'] . $query;
     }
     if (!empty($parsedUrl['port'])) {
         $this->_port = $parsedUrl['port'];
     }
     if (!empty($parsedUrl['scheme'])) {
         switch ($parsedUrl['scheme']) {
             case 'http':
                 if (empty($parsedUrl['port'])) {
                     $this->_port = 80;
                 }
                 $this->_protocol = 'tcp://';
                 break;
             case 'https':
                 if (empty($parsedUrl['port'])) {
                     $this->_port = 443;
                 }
                 if (function_exists('stream_get_transports')) {
                     $transports = stream_get_transports();
                     if (!in_array('ssl', $transports)) {
                         throw new BillsafeException('Missing SSL transport support in PHP');
                     }
                 }
                 $this->_protocol = 'ssl://';
                 break;
         }
     }
     if (!empty($parsedUrl['user'])) {
         $this->_user = $parsedUrl['user'];
     }
     if (!empty($parsedUrl['pass'])) {
         $this->_password = $parsedUrl['pass'];
     }
 }
Beispiel #18
0
 public function run()
 {
     $arMods = ['fsockopen' => \Yii::t('skeeks/cms', "Functions to work with sockets"), 'xml_parser_create' => \Yii::t('skeeks/cms', "{p} support", ['p' => 'XML']), 'preg_match' => \Yii::t('skeeks/cms', 'Support for regular expressions') . " (Perl-Compatible)", 'imagettftext' => \Yii::t('skeeks/cms', "Free Type Text"), 'gzcompress' => "Zlib", 'imagecreatetruecolor' => \Yii::t('skeeks/cms', 'GD Library'), 'imagecreatefromjpeg' => \Yii::t('skeeks/cms', "Jpeg support in GD"), 'json_encode' => \Yii::t('skeeks/cms', "{p} support", ['p' => 'JSON']), 'mcrypt_encrypt' => \Yii::t('skeeks/cms', 'The encryption function {mcrypt}', ['mcrypt' => 'MCrypt']), 'highlight_file' => 'PHP Syntax Highlight', 'mb_substr' => \Yii::t('skeeks/cms', "{p} support", ['p' => 'mbstring']), 'curl_init' => \Yii::t('skeeks/cms', "{p} support", ['p' => 'curl'])];
     $strError = '';
     foreach ($arMods as $func => $desc) {
         if (!function_exists($func)) {
             $this->addError($desc);
         } else {
             $this->addSuccess($desc);
         }
     }
     if (!in_array('ssl', stream_get_transports())) {
         $this->addError(\Yii::t('skeeks/cms', "{ssl} support is not configured in {php}", ['ssl' => 'ssl', 'php' => 'php']));
     }
     if (!extension_loaded('fileinfo')) {
         $this->addError(\Yii::t('skeeks/cms', 'Do not set extension {ext}. Do not set extension {ext}. Will not work on the file download link (for those files which can not parse file extension in the url, for example {smpl})', ['ext' => 'fileinfo', 'smpl' => 'https://im3-tub-ru.yandex.net/i?id=7bc5907fe7558cf8f2e97e7a760c6fdd&n=21']));
     } else {
         $this->addSuccess(\Yii::t('skeeks/cms', 'Extension {ext} is installed', ['ext' => 'php fileinfo']));
     }
 }
 public function __construct($server, $port, $timeout)
 {
     $sslAvailable = false;
     $xportlist = stream_get_transports();
     if (in_array('ssl', $xportlist)) {
         $sslAvailable = true;
     } else {
         if (in_array('ss', $xportlist)) {
             // Debian linux fix: missing first letter in transports list
             $sslAvailable = true;
         }
     }
     if (!$sslAvailable) {
         throw new Exception("Error: This server does not support SSL connections.");
     }
     $this->server = $server;
     $this->port = $port;
     $this->timeout = $timeout;
     $this->connection = false;
 }
 /**
  * Creates a new client.
  * @param string $server
  * @param string $path
  * @param int|string $port 'ssl' can be used for https connections, or port number
  * @param string $protocol use 'https' (or bool true, for backward compatibility) to specify https connections
  * @todo add a simplified syntax for constructor, using parse_url and a single string
  */
 function __construct($server, $path = '/', $port = 80, $protocol = null)
 {
     // backward compat with ezsoap client
     if ($protocol === true) {
         $protocol = 'https';
     }
     $this->Login = '';
     $this->Password = '';
     $this->Server = $server;
     if ($path == '' || $path[0] != '/') {
         $path = '/' . $path;
     }
     $this->Path = $path;
     $this->Port = $port;
     // this assumes 0 is a valid port. Weird, but useful for unix domain sockets..
     if (is_numeric($port)) {
         $this->Port = (int) $port;
     } elseif (strtolower($port) == 'ssl' || $protocol == 'https') {
         $this->Port = 443;
     } else {
         $this->Port = 80;
     }
     if ($protocol == null) {
         // lame, but we know no better
         if ($this->Port == 443) {
             $this->Protocol = 'https';
         } else {
             $this->Protocol = 'http';
         }
     } else {
         $this->Protocol = $protocol;
     }
     if ($this->Protocol == 'https' && !in_array('ssl', stream_get_transports())) {
         $this->ForceCURL = true;
     }
     // if ZLIB is enabled, let the client by default accept compressed responses
     if (function_exists('gzinflate') || function_exists('curl_init') && (($info = curl_version()) && (is_string($info) && strpos($info, 'zlib') !== null || isset($info['libz_version'])))) {
         $this->AcceptedCompression = 'gzip, deflate';
     }
 }
 /**
  * @param array $config
  * @return TreasureData_API
  */
 public static function createClient($config = array())
 {
     $default_config = array("endpoint" => TreasureData_API::DEFAULT_ENDPOINT, "authentication" => "TreasureData_API_Authentication_Header", "api_key" => new TreasureData_API_ConfigResolver_HomeConfigResolver(), "api_version" => TreasureData_API::DEFAULT_API_VERSION, "proxy" => getenv("HTTP_PROXY"), "driver" => "TreasureData_API_Driver_StreamSocketDriver", "driver_option" => array());
     $config = array_merge($default_config, $config);
     if ($config['driver'] == "TreasureData_API_Driver_CurlDriver") {
         if (!extension_loaded("curl")) {
             throw new RuntimeException("your php does not support curl. please rebuild php");
         }
     } else {
         if ($config['driver'] == "TreasureData_API_Driver_StreamSocketDriver") {
             if (!in_array("ssl", stream_get_transports())) {
                 throw new RuntimeException("stream socket must support ssl transport. please rebuild php");
             }
             if (ini_get("allow_url_fopen") == false) {
                 throw new RuntimeException("stream socket requires `allow_url_fopen`. please check your php.ini");
             }
         }
     }
     if (!empty($config['proxy'])) {
         $info = parse_url($config['proxy']);
         switch ($info['scheme']) {
             case "http":
                 $proto = 'tcp';
                 break;
             case 'https':
                 $proto = "ssl";
                 break;
             default:
                 $proto = 'tcp';
         }
         $config['proxy'] = sprintf("%s://%s:%d", $proto, $info['host'], $info['port']);
     }
     $authentication_class = $config['authentication'];
     $authentication = new $authentication_class($config['api_key']);
     $driver_class = $config['driver'];
     $driver = new $driver_class();
     $driver->setupOption($config['driver_option']);
     $api = new TreasureData_API($config['endpoint'], $driver, $authentication, $config['api_version'], $config['proxy']);
     return $api;
 }
 function pay($amount, $description, $bank_id)
 {
     require_once 'ideal.class.php';
     //$amount      = 118;    // Het af te rekenen bedrag in centen (!!!)
     //$description = 'Testbetaling'; // Beschrijving die consument op zijn/haar afschrift ziet.
     $return_url = $this->return_url;
     // URL waarnaar de consument teruggestuurd wordt na de betaling
     $report_url = $this->report_url;
     // URL die Mollie aanvraagt (op de achtergrond) na de betaling om de status naar op te sturen
     if (!in_array('ssl', stream_get_transports())) {
         echo "<h1>Foutmelding</h1>";
         echo "<p>Uw PHP installatie heeft geen SSL ondersteuning. SSL is nodig voor de communicatie met de Mollie iDEAL API.</p>";
         exit;
     }
     $iDEAL = new iDEAL_Payment($this->partnerID);
     if ($this->testMode) {
         $iDEAL->setTestMode();
     }
     if (isset($bank_id) and !empty($bank_id)) {
         if ($iDEAL->createPayment($bank_id, $amount, $description, $return_url, $report_url)) {
             /* Hier kunt u de aangemaakte betaling opslaan in uw database, bijv. met het unieke transactie_id
                Het transactie_id kunt u aanvragen door $iDEAL->getTransactionId() te gebruiken. Hierna wordt 
                de consument automatisch doorgestuurd naar de gekozen bank. */
             $data = array('transactionId' => $iDEAL->getTransactionId(), 'bankUrl' => $iDEAL->getBankURL());
             return $data;
             //header("Location: " . $iDEAL->getBankURL());
             //exit;
         } else {
             /* Er is iets mis gegaan bij het aanmaken bij de betaling. U kunt meer informatie 
                vinden over waarom het mis is gegaan door $iDEAL->getErrorMessage() en/of 
                $iDEAL->getErrorCode() te gebruiken. */
             $data = array('error' => true, 'msg' => $iDEAL->getErrorMessage());
             return $data;
         }
     }
 }
Beispiel #23
0
 function __construct($ip = null, $port = null)
 {
     global $default_ip, $default_port;
     $protocol_list = stream_get_transports();
     if (!in_array("ssl", $protocol_list)) {
         die("Don't have ssl support.");
     }
     if (!$ip) {
         $ip = $default_ip;
     }
     if (!$port) {
         $port = $default_port;
     }
     $errno = 0;
     $socket = fsockopen($ip, $port, $errno, $errstr, 30);
     if (!$socket) {
         $this->error = "Web page can't connect to ip={$ip}, port={$port} [{$errno}]  \"" . $errstr . "\"";
         $this->socket = false;
     } else {
         $this->socket = $socket;
         $line1 = $this->read();
         // read and ignore header
     }
 }
Beispiel #24
0
 /**
  * Set SSL parameters (used when a URL in form https:// is used).
  * The params are ssl_ca_cert, path to the the Certificate Authority cert 
  * and ssl_client_cert, which is path to this clients certificate, PEM encoded, without encryption.
  */
 function setSSLparams($ca_cert, $client_cert)
 {
     if (!in_array("sslv3", stream_get_transports())) {
         $this->error = new XMLRPC_Error(XMLRPC_Error::CONNECT_FAILED, "This PHP version does not have SSL support.");
         return false;
     }
     $this->ssl_ca_cert = $ca_cert;
     $this->ssl_client_cert = $client_cert;
     return true;
 }
Beispiel #25
0
 public function case_get_standards_and_vendors()
 {
     $this->given($standardTransports = stream_get_transports(), $vendorTransports = ['foo', 'bar'], SUT::register('foo', function () {
     }), SUT::register('bar', function () {
     }))->when($result = SUT::get())->then->array($result)->isEqualTo(array_merge($standardTransports, $vendorTransports));
 }
Beispiel #26
0
 /**
  * Connects to the remote server
  *
  * @return   bool    whether the connection can be persistent
  * @throws   HTTP_Request2_Exception
  */
 protected function connect()
 {
     $secure = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
     $tunnel = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
     $headers = $this->request->getHeaders();
     $reqHost = $this->request->getUrl()->getHost();
     if (!($reqPort = $this->request->getUrl()->getPort())) {
         $reqPort = $secure ? 443 : 80;
     }
     if ($host = $this->request->getConfig('proxy_host')) {
         if (!($port = $this->request->getConfig('proxy_port'))) {
             throw new HTTP_Request2_LogicException('Proxy port not provided', HTTP_Request2_Exception::MISSING_VALUE);
         }
         $proxy = true;
     } else {
         $host = $reqHost;
         $port = $reqPort;
         $proxy = false;
     }
     if ($tunnel && !$proxy) {
         throw new HTTP_Request2_LogicException("Trying to perform CONNECT request without proxy", HTTP_Request2_Exception::MISSING_VALUE);
     }
     if ($secure && !in_array('ssl', stream_get_transports())) {
         throw new HTTP_Request2_LogicException('Need OpenSSL support for https:// requests', HTTP_Request2_Exception::MISCONFIGURATION);
     }
     // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
     // connection token to a proxy server...
     if ($proxy && !$secure && !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']) {
         $this->request->setHeader('connection');
     }
     $keepAlive = '1.1' == $this->request->getConfig('protocol_version') && empty($headers['connection']) || !empty($headers['connection']) && 'Keep-Alive' == $headers['connection'];
     $host = (!$secure || $proxy ? 'tcp://' : 'ssl://') . $host;
     $options = array();
     if ($secure || $tunnel) {
         foreach ($this->request->getConfig() as $name => $value) {
             if ('ssl_' == substr($name, 0, 4) && null !== $value) {
                 if ('ssl_verify_host' == $name) {
                     if ($value) {
                         $options['CN_match'] = $reqHost;
                     }
                 } else {
                     $options[substr($name, 4)] = $value;
                 }
             }
         }
         ksort($options);
     }
     // Changing SSL context options after connection is established does *not*
     // work, we need a new connection if options change
     $remote = $host . ':' . $port;
     $socketKey = $remote . ($secure && $proxy ? "->{$reqHost}:{$reqPort}" : '') . (empty($options) ? '' : ':' . serialize($options));
     unset($this->socket);
     // We use persistent connections and have a connected socket?
     // Ensure that the socket is still connected, see bug #16149
     if ($keepAlive && !empty(self::$sockets[$socketKey]) && !feof(self::$sockets[$socketKey])) {
         $this->socket =& self::$sockets[$socketKey];
     } elseif ($secure && $proxy && !$tunnel) {
         $this->establishTunnel();
         $this->request->setLastEvent('connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}");
         self::$sockets[$socketKey] =& $this->socket;
     } else {
         // Set SSL context options if doing HTTPS request or creating a tunnel
         $context = stream_context_create();
         foreach ($options as $name => $value) {
             if (!stream_context_set_option($context, 'ssl', $name, $value)) {
                 throw new HTTP_Request2_LogicException("Error setting SSL context option '{$name}'");
             }
         }
         $this->socket = @stream_socket_client($remote, $errno, $errstr, $this->request->getConfig('connect_timeout'), STREAM_CLIENT_CONNECT, $context);
         if (!$this->socket) {
             throw new HTTP_Request2_ConnectionException("Unable to connect to {$remote}. Error: {$errstr}", 0, $errno);
         }
         $this->request->setLastEvent('connect', $remote);
         self::$sockets[$socketKey] =& $this->socket;
     }
     return $keepAlive;
 }
Beispiel #27
0
 function Connect($host_name, $host_port, $ssl, $server_type = 'HTTP')
 {
     $domain = $host_name;
     $port = $host_port;
     if (strlen($error = $this->Resolve($domain, $ip, $server_type))) {
         return $error;
     }
     if (strlen($this->socks_host_name)) {
         switch ($this->socks_version) {
             case '4':
                 $version = 4;
                 break;
             case '5':
                 $version = 5;
                 break;
             default:
                 return 'it was not specified a supported SOCKS protocol version';
                 break;
         }
         $host_ip = $ip;
         $port = $this->socks_host_port;
         $host_server_type = $server_type;
         $server_type = 'SOCKS';
         if (strlen($error = $this->Resolve($this->socks_host_name, $ip, $server_type))) {
             return $error;
         }
     }
     if ($this->debug) {
         $this->OutputDebug('Connecting to ' . $server_type . ' server IP ' . $ip . ' port ' . $port . '...');
     }
     if ($ssl) {
         $ip = "ssl://" . $ip;
     }
     if (($this->connection = $this->timeout ? @fsockopen($ip, $port, $errno, $error, $this->timeout) : @fsockopen($ip, $port, $errno)) == 0) {
         switch ($errno) {
             case -3:
                 return $this->SetError("-3 socket could not be created");
             case -4:
                 return $this->SetError("-4 dns lookup on hostname \"" . $host_name . "\" failed");
             case -5:
                 return $this->SetError("-5 connection refused or timed out");
             case -6:
                 return $this->SetError("-6 fdopen() call failed");
             case -7:
                 return $this->SetError("-7 setvbuf() call failed");
             default:
                 return $this->SetPHPError($errno . " could not connect to the host \"" . $host_name . "\"", $php_errormsg);
         }
     } else {
         if ($this->data_timeout && function_exists("socket_set_timeout")) {
             socket_set_timeout($this->connection, $this->data_timeout, 0);
         }
         if (strlen($this->socks_host_name)) {
             if ($this->debug) {
                 $this->OutputDebug('Connected to the SOCKS server ' . $this->socks_host_name);
             }
             $send_error = 'it was not possible to send data to the SOCKS server';
             $receive_error = 'it was not possible to receive data from the SOCKS server';
             switch ($version) {
                 case 4:
                     $command = 1;
                     if (!fputs($this->connection, chr($version) . chr($command) . pack('nN', $host_port, ip2long($host_ip)) . $this->user . Chr(0))) {
                         $error = $this->SetDataAccessError($send_error);
                     } else {
                         $response = fgets($this->connection, 9);
                         if (strlen($response) != 8) {
                             $error = $this->SetDataAccessError($receive_error);
                         } else {
                             $socks_errors = array("Z" => '', "[" => 'request rejected', "\\" => 'request failed because client is not running identd (or not reachable from the server)', "]" => 'request failed because client\'s identd could not confirm the user ID string in the request');
                             $error_code = $response[1];
                             $error = isset($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown';
                             if (strlen($error)) {
                                 $error = 'SOCKS error: ' . $error;
                             }
                         }
                     }
                     break;
                 case 5:
                     if ($this->debug) {
                         $this->OutputDebug('Negotiating the authentication method ...');
                     }
                     $methods = 1;
                     $method = 0;
                     if (!fputs($this->connection, chr($version) . chr($methods) . chr($method))) {
                         $error = $this->SetDataAccessError($send_error);
                     } else {
                         $response = fgets($this->connection, 3);
                         if (strlen($response) != 2) {
                             $error = $this->SetDataAccessError($receive_error);
                         } elseif (Ord($response[1]) != $method) {
                             $error = 'the SOCKS server requires an authentication method that is not yet supported';
                         } else {
                             if ($this->debug) {
                                 $this->OutputDebug('Connecting to ' . $host_server_type . ' server IP ' . $host_ip . ' port ' . $host_port . '...');
                             }
                             $command = 1;
                             $address_type = 1;
                             if (!fputs($this->connection, chr($version) . chr($command) . "" . chr($address_type) . pack('Nn', ip2long($host_ip), $host_port))) {
                                 $error = $this->SetDataAccessError($send_error);
                             } else {
                                 $response = fgets($this->connection, 11);
                                 if (strlen($response) != 10) {
                                     $error = $this->SetDataAccessError($receive_error);
                                 } else {
                                     $socks_errors = array("" => '', "" => 'general SOCKS server failure', "" => 'connection not allowed by ruleset', "" => 'Network unreachable', "" => 'Host unreachable', "" => 'Connection refused', "" => 'TTL expired', "" => 'Command not supported', "" => 'Address type not supported');
                                     $error_code = $response[1];
                                     $error = isset($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown';
                                     if (strlen($error)) {
                                         $error = 'SOCKS error: ' . $error;
                                     }
                                 }
                             }
                         }
                     }
                     break;
                 default:
                     $error = 'support for SOCKS protocol version ' . $this->socks_version . ' is not yet implemented';
                     break;
             }
             if (strlen($error)) {
                 fclose($this->connection);
                 return $error;
             }
         }
         if ($this->debug) {
             $this->OutputDebug("Connected to {$host_name}");
         }
         if (strlen($this->proxy_host_name) && !strcmp(strtolower($this->protocol), 'https')) {
             if (function_exists('stream_socket_enable_crypto') && in_array('ssl', stream_get_transports())) {
                 $this->state = "ConnectedToProxy";
             } else {
                 $this->OutputDebug("It is not possible to start SSL after connecting to the proxy server. If the proxy refuses to forward the SSL request, you may need to upgrade to PHP 5.1 or later with OpenSSL support enabled.");
                 $this->state = "Connected";
             }
         } else {
             $this->state = "Connected";
         }
         return "";
     }
 }
Beispiel #28
0
 /**
  * @param string $sServerName
  * @param int $iPort
  * @param int $iSecurityType = \MailSo\Net\Enumerations\ConnectionSecurityType::AUTO_DETECT
  * @param bool $bVerifySsl = false
  *
  * @return void
  *
  * @throws \MailSo\Base\Exceptions\InvalidArgumentException
  * @throws \MailSo\Net\Exceptions\SocketAlreadyConnectedException
  * @throws \MailSo\Net\Exceptions\SocketCanNotConnectToHostException
  */
 public function Connect($sServerName, $iPort, $iSecurityType = \MailSo\Net\Enumerations\ConnectionSecurityType::AUTO_DETECT, $bVerifySsl = false)
 {
     if (!\MailSo\Base\Validator::NotEmptyString($sServerName, true) || !\MailSo\Base\Validator::PortInt($iPort)) {
         $this->writeLogException(new \MailSo\Base\Exceptions\InvalidArgumentException(), \MailSo\Log\Enumerations\Type::ERROR, true);
     }
     if ($this->IsConnected()) {
         $this->writeLogException(new Exceptions\SocketAlreadyConnectedException(), \MailSo\Log\Enumerations\Type::ERROR, true);
     }
     $sServerName = \trim($sServerName);
     $sErrorStr = '';
     $iErrorNo = 0;
     $this->sConnectedHost = $sServerName;
     $this->iConnectedPort = $iPort;
     $this->iSecurityType = $iSecurityType;
     $this->bSecure = \MailSo\Net\Enumerations\ConnectionSecurityType::UseSSL($this->iConnectedPort, $this->iSecurityType);
     $this->sConnectedHost = \in_array(\strtolower(\substr($this->sConnectedHost, 0, 6)), array('ssl://', 'tcp://')) ? \substr($this->sConnectedHost, 6) : $this->sConnectedHost;
     $this->sConnectedHost = ($this->bSecure ? 'ssl://' : 'tcp://') . $this->sConnectedHost;
     //		$this->sConnectedHost = ($this->bSecure ? 'ssl://' : '').$this->sConnectedHost;
     if (!$this->bSecure && \MailSo\Net\Enumerations\ConnectionSecurityType::SSL === $this->iSecurityType) {
         $this->writeLogException(new \MailSo\Net\Exceptions\SocketUnsuppoterdSecureConnectionException('SSL isn\'t supported: (' . \implode(', ', \stream_get_transports()) . ')'), \MailSo\Log\Enumerations\Type::ERROR, true);
     }
     $this->iStartConnectTime = \microtime(true);
     $this->writeLog('Start connection to "' . $this->sConnectedHost . ':' . $this->iConnectedPort . '"', \MailSo\Log\Enumerations\Type::NOTE);
     //		$this->rConnect = @\fsockopen($this->sConnectedHost, $this->iConnectedPort,
     //			$iErrorNo, $sErrorStr, $this->iConnectTimeOut);
     $bVerifySsl = !!$bVerifySsl;
     $aStreamContextSettings = array('ssl' => array('verify_host' => $bVerifySsl, 'verify_peer' => $bVerifySsl, 'verify_peer_name' => $bVerifySsl, 'allow_self_signed' => !$bVerifySsl));
     \MailSo\Hooks::Run('Net.NetClient.StreamContextSettings/Filter', array(&$aStreamContextSettings));
     $rStreamContext = \stream_context_create($aStreamContextSettings);
     \set_error_handler(array(&$this, 'capturePhpErrorWithException'));
     try {
         $this->rConnect = \stream_socket_client($this->sConnectedHost . ':' . $this->iConnectedPort, $iErrorNo, $sErrorStr, $this->iConnectTimeOut, STREAM_CLIENT_CONNECT, $rStreamContext);
     } catch (\Exception $oExc) {
         $sErrorStr = $oExc->getMessage();
         $iErrorNo = $oExc->getCode();
     }
     \restore_error_handler();
     if (!\is_resource($this->rConnect)) {
         $this->writeLogException(new Exceptions\SocketCanNotConnectToHostException(\MailSo\Base\Utils::ConvertSystemString($sErrorStr), (int) $iErrorNo, 'Can\'t connect to host "' . $this->sConnectedHost . ':' . $this->iConnectedPort . '"'), \MailSo\Log\Enumerations\Type::NOTICE, true);
     }
     $this->writeLog(\microtime(true) - $this->iStartConnectTime . ' (raw connection)', \MailSo\Log\Enumerations\Type::TIME);
     if ($this->rConnect) {
         if (\MailSo\Base\Utils::FunctionExistsAndEnabled('stream_set_timeout')) {
             @\stream_set_timeout($this->rConnect, $this->iSocketTimeOut);
         }
     }
 }
Beispiel #29
0
 /**
  * Set an option for the stream stream context in the given wrapper.
  *
  * @param String $wrapper The wrapper of the option.
  * @param String $option  The option name
  * @param mixed  $value   The value of the option
  *
  * @return StreamSocket $self Self-reference
  */
 public function set_context_option($wrapper, $option, $value)
 {
     if (!is_string($wrapper)) {
         return $this;
     }
     if (!in_array($wrapper, stream_get_wrappers()) && !in_array($wrapper, stream_get_transports())) {
         return $this;
     }
     if (!array_key_exists($wrapper, $this->context_options)) {
         $this->context_options[$wrapper] = array();
     }
     $this->context_options[$wrapper][$option] = $value;
     return $this;
 }
Beispiel #30
0
function test_stream_misc()
{
    VERIFY(count(stream_get_transports()) > 0);
    $w = stream_get_wrappers();
    VS(in_array("file", $w), true);
    VS(in_array("http", $w), true);
}