public function connect()
 {
     // try open socket
     if ($this->getOption('tls')) {
         $this->handler = @stream_socket_client('tcp://' . $this->server . ':' . $this->port, $errno, $errstr, $this->getOption('timeout', 10));
         if ($this->handler) {
             stream_socket_enable_crypto($this->handler, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         }
     } else {
         $this->handler = @fsockopen($this->server, $this->port, $errno, $errstr, $this->getOption('timeout', 10));
     }
     if ($this->handler) {
         // read welcome
         $this->read();
         // auth
         $this->auth();
     } else {
         if (!preg_match('//u', $errstr)) {
             $tmp = @iconv('windows-1251', 'utf-8//ignore', $errstr);
             if ($tmp) {
                 $errstr = $tmp;
             }
         }
         throw new waException($errstr . ' (' . $errno . ')', $errno);
     }
 }
Exemple #2
0
 public function StartTLS()
 {
     $this->error = null;
     # to avoid confusion
     if (!$this->connected()) {
         $this->error = array("error" => "Called StartTLS() without being connected");
         return false;
     }
     fputs($this->smtp_conn, "STARTTLS" . $extra . $this->CRLF);
     $rply = $this->get_lines();
     $code = substr($rply, 0, 3);
     if ($this->do_debug >= 2) {
         echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
     }
     if ($code != 220) {
         $this->error = array("error" => "STARTTLS not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4));
         if ($this->do_debug >= 1) {
             echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF;
         }
         return false;
     }
     //Begin encrypted connection
     if (!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
         return false;
     }
     return true;
 }
 protected function enableSocketEncryption($socket, int $modes, float $timeout = 0) : \Generator
 {
     if ($modes === 0) {
         throw new SocketEncryptionException('No socket client encryption modes available');
     }
     $timed = $timeout;
     try {
         while (true) {
             (yield new AwaitWrite($socket, $timeout));
             $enabled = @\stream_socket_enable_crypto($socket, true, $modes);
             if ($enabled === false) {
                 throw new SocketEncryptionException(\sprintf('Failed to enable socket encryption: %s', \error_get_last()['message'] ?? ''));
             }
             if ($enabled !== 0) {
                 break;
             }
             $timeout = max(0, $timeout - (yield new Pause(0.005, 0.005)));
             if ($timed > 0 && $timeout == 0) {
                 throw new TimeoutException(\sprintf('Socket encryption activation timed out after %.3f seconds', $timed));
             }
         }
     } catch (SocketEncryptionException $e) {
         throw $e;
     } catch (\Throwable $e) {
         throw new SocketEncryptionException('Failed to enable socket encryption', 0, $e);
     }
 }
 public function handleConnectedSocket($callback, $socket)
 {
     $loop = $this->loop;
     $enableCrypto = function () use($callback, $socket, $loop) {
         $result = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         if (true === $result) {
             // crypto was successfully enabled
             $loop->removeWriteStream($socket);
             $loop->removeReadStream($socket);
             call_user_func($callback, new Stream($socket, $loop));
         } else {
             if (false === $result) {
                 // an error occured
                 $loop->removeWriteStream($socket);
                 $loop->removeReadStream($socket);
                 call_user_func($callback, null);
             } else {
                 // need more data, will retry
             }
         }
     };
     $this->loop->addWriteStream($socket, $enableCrypto);
     $this->loop->addReadStream($socket, $enableCrypto);
     $enableCrypto();
 }
Exemple #5
0
 /**
  * {@inheritdoc}
  */
 public function enableCrypto($enable, $cryptoType = STREAM_CRYPTO_METHOD_TLS_CLIENT)
 {
     if (!stream_socket_enable_crypto($this->stream, $enable, $cryptoType)) {
         throw new SocketException();
     }
     return $this;
 }
Exemple #6
0
 /**
  * Open connection to IMAP server
  *
  * @param  string      $host  hostname or IP address of IMAP server
  * @param  int|null    $port  of IMAP server, default is 143 (993 for ssl)
  * @param  string|bool $ssl   use 'SSL', 'TLS' or false
  * @throws Exception\RuntimeException
  * @return string welcome message
  */
 public function connect($host, $port = null, $ssl = false)
 {
     if ($ssl == 'SSL') {
         $host = 'ssl://' . $host;
     }
     if ($port === null) {
         $port = $ssl === 'SSL' ? 993 : 143;
     }
     $errno = 0;
     $errstr = '';
     $this->_socket = @fsockopen($host, $port, $errno, $errstr, self::TIMEOUT_CONNECTION);
     if (!$this->_socket) {
         throw new Exception\RuntimeException('cannot connect to host; error = ' . $errstr . ' (errno = ' . $errno . ' )');
     }
     if (!$this->_assumedNextLine('* OK')) {
         throw new Exception\RuntimeException('host doesn\'t allow connection');
     }
     if ($ssl === 'TLS') {
         $result = $this->requestAndResponse('STARTTLS');
         $result = $result && stream_socket_enable_crypto($this->_socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         if (!$result) {
             throw new Exception\RuntimeException('cannot enable TLS');
         }
     }
 }
Exemple #7
0
 /**
  * Open connection to IMAP server
  *
  * @param  string      $host  hostname or IP address of IMAP server
  * @param  int|null    $port  of IMAP server, default is 143 (993 for ssl)
  * @param  string|bool $ssl   use 'SSL', 'TLS' or false
  * @throws Exception\RuntimeException
  * @return string welcome message
  */
 public function connect($host, $port = null, $ssl = false)
 {
     if ($ssl == 'SSL') {
         $host = 'ssl://' . $host;
     }
     if ($port === null) {
         $port = $ssl === 'SSL' ? 993 : 143;
     }
     ErrorHandler::start();
     $this->socket = fsockopen($host, $port, $errno, $errstr, self::TIMEOUT_CONNECTION);
     $error = ErrorHandler::stop();
     if (!$this->socket) {
         throw new Exception\RuntimeException(sprintf('cannot connect to host%s', $error ? sprintf('; error = %s (errno = %d )', $error->getMessage(), $error->getCode()) : ''), 0, $error);
     }
     if (!$this->_assumedNextLine('* OK')) {
         throw new Exception\RuntimeException('host doesn\'t allow connection');
     }
     if ($ssl === 'TLS') {
         $result = $this->requestAndResponse('STARTTLS');
         $result = $result && stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         if (!$result) {
             throw new Exception\RuntimeException('cannot enable TLS');
         }
     }
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function enableCrypto(int $method, float $timeout = 0) : \Generator
 {
     $resource = $this->getResource();
     if ($method & 1 || 0 === $method) {
         yield from $this->await($timeout);
     } else {
         yield from $this->poll($timeout);
         $raw = stream_socket_recvfrom($resource, 11, STREAM_PEEK);
         if (11 > strlen($raw)) {
             throw new FailureException('Failed to read crypto handshake.');
         }
         $data = unpack('ctype/nversion/nlength/Nembed/nmax-version', $raw);
         if (0x16 !== $data['type']) {
             throw new FailureException('Invalid crypto handshake.');
         }
         $version = $this->selectCryptoVersion($data['max-version']);
         if ($method & $version) {
             // Check if version was available in $method.
             $method = $version;
         }
     }
     do {
         // Error reporting suppressed since stream_socket_enable_crypto() emits E_WARNING on failure.
         $result = @stream_socket_enable_crypto($resource, (bool) $method, $method);
     } while (0 === $result && !(yield from $this->poll($timeout)));
     if ($result) {
         $this->crypto = $method;
         return;
     }
     $message = 'Failed to enable crypto.';
     if ($error = error_get_last()) {
         $message .= sprintf(' Errno: %d; %s', $error['type'], $error['message']);
     }
     throw new FailureException($message);
 }
Exemple #9
0
 /**
  * Аутентификация пользователя
  *
  * @param   String    $login
  * @param   String    $password
  * @param   Bool      $admin
  * @return  Bool
  */
 protected function _auth($login, $password, $admin)
 {
     $packet = $this->packet();
     while (!feof($this->_socket)) {
         $packet->clean();
         $this->read($packet);
         switch ($this->_code) {
             case 192:
                 $digest = $packet->_attr[6]['data'];
                 $ctx = hash_init('md5');
                 hash_update($ctx, $digest);
                 hash_update($ctx, $password);
                 $hash = hash_final($ctx, true);
                 $packet->clean();
                 $this->_code = 193;
                 $packet->set_attr_string($login, 2);
                 $packet->set_attr_string($digest, 8);
                 $packet->set_attr_string($hash, 9);
                 $packet->set_attr_int($admin ? 4 : 2, 10);
                 $packet->set_attr_int(2, 1);
                 $this->write($packet);
                 break;
             case 194:
                 if ($packet->get_attr_int(10)) {
                     stream_socket_enable_crypto($this->_socket, TRUE, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
                 }
                 return TRUE;
             case 195:
                 return FALSE;
         }
     }
 }
Exemple #10
0
 /**
  * SMTP Connect
  *
  * @access  protected
  * @return  string
  */
 protected function _smtp_connect()
 {
     $ssl = NULL;
     if ($this->smtp_crypto == 'ssl') {
         $ssl = 'ssl://';
     }
     $CI =& get_instance();
     if (!empty($this->proxy)) {
         $context = stream_context_create(['http' => ['proxy' => 'tcp://' . $this->proxy]]);
         $this->_smtp_connect = stream_socket_client($ssl . $this->smtp_host . ':' . $this->smtp_port, $errno, $errstr, $this->smtp_timeout, STREAM_CLIENT_CONNECT, $context);
     } else {
         $this->_smtp_connect = fsockopen($ssl . $this->smtp_host, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);
     }
     if (!is_resource($this->_smtp_connect)) {
         $this->_set_error_message('lang:email_smtp_error', $errno . " " . $errstr);
         return FALSE;
     }
     $this->_set_error_message($this->_get_smtp_data());
     if ($this->smtp_crypto == 'tls') {
         $this->_send_command('hello');
         $this->_send_command('starttls');
         stream_socket_enable_crypto($this->_smtp_connect, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);
     }
     return $this->_send_command('hello');
 }
Exemple #11
0
 protected function auth()
 {
     fputs($this->conn, 'HELO ' . $this->localhost . $this->newline);
     $this->getServerResponse();
     if ($this->secure == 'tls') {
         fputs($this->conn, 'STARTTLS' . $this->newline);
         if (substr($this->getServerResponse(), 0, 3) != '220') {
             return false;
         }
         stream_socket_enable_crypto($this->conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
         fputs($this->conn, 'HELO ' . $this->localhost . $this->newline);
         if (substr($this->getServerResponse(), 0, 3) != '250') {
             return false;
         }
     }
     if ($this->server != 'localhost') {
         fputs($this->conn, 'AUTH LOGIN' . $this->newline);
         if (substr($this->getServerResponse(), 0, 3) != '334') {
             return false;
         }
         fputs($this->conn, base64_encode($this->username) . $this->newline);
         if (substr($this->getServerResponse(), 0, 3) != '334') {
             return false;
         }
         fputs($this->conn, base64_encode($this->password) . $this->newline);
         if (substr($this->getServerResponse(), 0, 3) != '235') {
             return false;
         }
     }
     return true;
 }
 public function handleData($stream)
 {
     if (!$this->isSecure) {
         $enabled = @stream_socket_enable_crypto($stream, true, $this->protocolNumber);
         if ($enabled === false) {
             $this->err('Failed to complete a secure handshake with the client.')->end();
             return;
         } elseif ($enabled === 0) {
             return;
         }
         $this->isSecure = true;
         $this->emit('connection', array($this));
         $scope = $this;
         $this->on('close', function () use($scope, $stream) {
             if (false === stream_socket_enable_crypto($stream, false)) {
                 $scope->err('Failed to gracefully shutdown a secure connection.');
             }
         });
     }
     $data = fread($stream, $this->bufferSize);
     if ('' !== $data && false !== $data) {
         $this->emit('data', array($data, $this));
     }
     if (false === $data || !is_resource($stream) || feof($stream)) {
         $this->end();
     }
 }
 /**
  * Connect, then enable crypto
  * 
  * @param   float $timeout
  * @return  bool
  * @throws  peer.SSLUnverifiedPeerException if peer verification fails
  * @throws  peer.SSLHandshakeException if handshake fails for any other reasons
  * @throws  peer.ConnectException for all other reasons
  */
 public function connect($timeout = 2.0)
 {
     if ($this->isConnected()) {
         return true;
     }
     parent::connect($timeout);
     if (stream_socket_enable_crypto($this->_sock, true, $this->cryptoImpl)) {
         return true;
     }
     // Parse OpenSSL errors:
     if (preg_match('/error:(\\d+):(.+)/', key(end(\xp::$errors[__FILE__])), $matches)) {
         switch ($matches[1]) {
             case '14090086':
                 $e = new SSLUnverifiedPeerException($matches[2]);
                 break;
             default:
                 $e = new SSLHandshakeException($matches[2]);
                 break;
         }
     } else {
         $e = new SSLHandshakeException('Unable to enable crypto.');
     }
     $this->close();
     throw $e;
 }
Exemple #14
0
 /**
  * Start TLS encryption on the buffer.
  */
 public function startTLS()
 {
     if (isset($this->_stream)) {
         return stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
     } else {
         return false;
     }
 }
function do_enable_crypto_test($url, $context)
{
    $fh = stream_socket_client($url, $errno, $errstr, ini_get("default_socket_timeout"), STREAM_CLIENT_CONNECT, $context);
    assert($fh);
    $r = stream_socket_enable_crypto($fh, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
    assert($r);
    var_dump(get_CN($context));
}
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 protected function prepareSocket(StreamSocket $socket)
 {
     $socket->block(true);
     if (false === stream_socket_enable_crypto($socket->getRaw(), true, STREAM_CRYPTO_METHOD_SSLv23_SERVER)) {
         throw new Exception('SSL negotiation failed');
     }
     $socket->block(false);
 }
Exemple #17
0
 /**
  * {@inheritdocs}
  */
 public function execute()
 {
     if ($this->perform('STARTTLS', 220)) {
         if (@stream_socket_enable_crypto($this->smtp->getStream(), true, STREAM_CRYPTO_METHOD_TLS_CLIENT) === false) {
             throw new RuntimeException('Cannot encrypt the connection.');
         }
     }
 }
 /**
  * Enable cryptography on a given socket
  *
  * @param  peer.Socket $s
  * @param  [:int] $methods
  * @return void
  * @throws io.IOException
  */
 protected function enable($s, $methods)
 {
     foreach ($methods as $name => $method) {
         if (stream_socket_enable_crypto($s->getHandle(), true, $method)) {
             $this->cat && $this->cat->debug('@@@ Enabling', $name, 'cryptography');
             return;
         }
     }
     throw new \io\IOException('Cannot establish secure connection, tried ' . \xp::stringOf($methods));
 }
Exemple #19
0
 public function __construct($host, $port, $security, $timeout = 30)
 {
     stream_set_timeout($this->socket = fsockopen($security === 'ssl' ? "ssl://{$host}" : $host, $port, $errno, $errstr, $timeout), $timeout);
     $this->get();
     $this->hello();
     if ($security === 'tls') {
         if ($this->set('STARTTLS') == 220 && stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
             $this->hello();
         } else {
             $this->set('RSET', 250);
         }
     }
 }
 /** {@inheritdoc} */
 protected function handleOperation(RequestDescriptor $descriptor, RequestExecutorInterface $executor, EventHandlerInterface $eventHandler)
 {
     $operation = $descriptor->getOperation();
     $socket = $descriptor->getSocket();
     /** @var SslHandshakeOperation $operation */
     $resource = $descriptor->getSocket()->getStreamResource();
     $result = stream_socket_enable_crypto($resource, true, $operation->getCipher());
     if ($result === true) {
         return $operation->getNextOperation();
     } elseif ($result === false) {
         throw new SslHandshakeException($socket, 'SSL handshake failed.');
     }
     return $operation;
 }
Exemple #21
0
 /**
  * Send message via smtp protocol
  *
  * @param Message $message
  * @param array $config
  * @return bool
  * @throws MailerException
  */
 public function send(Message $message, array $config)
 {
     $this->config = $config;
     if (!$message->mailTo) {
         throw new MailerException("Error mail send: 'RCPT TO' isn\\'t defined");
     }
     $errno = $errstr = '';
     if (!($this->connect = fsockopen($config['host'], $config['port'], $errno, $errstr, 30))) {
         return false;
     } else {
         // expectedResult = 220 smtp43.i.mail.ru ESMTP ready
         $this->getLines();
         $this->echoInfo($this->lastLines . '<br>');
         if (substr($this->lastLines, 0, 3) != '220') {
             return false;
         }
         // expectedResult = 220 2.0.0 Start TLS
         if (substr($this->sendCommand('STARTTLS'), 0, 3) != '220') {
             return false;
         }
         stream_socket_enable_crypto($this->connect, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
         // HELO/EHLO  command for greeting with server  HELO = SMTP, EHLO = ESMTP.  EHLO is better.
         $this->sendCommand('EHLO ' . $_SERVER["SERVER_NAME"]);
         $this->sendCommand('AUTH LOGIN');
         $this->echoInfo(substr($this->lastLines, 0, 4) . base64_decode(substr($this->lastLines, 3)) . '<br>');
         // username send in base64
         $this->sendCommand(base64_encode($config['smtp_username']));
         $this->echoInfo(substr($this->lastLines, 0, 4) . base64_decode(substr($this->lastLines, 3)) . '<br>');
         // password send in base64
         $this->sendCommand(base64_encode($config['smtp_password']));
         $this->sendCommand('MAIL FROM: <' . $config['mailFrom'] . '>');
         // Return-Path
         $this->sendCommand('RCPT TO: <' . $message->mailTo . '>');
         $this->sendCommand('DATA');
         foreach ($message->headers as $key => $header) {
             $this->sendCommand($key . ': ' . $header);
         }
         $this->sendCommand('');
         // empty line to separate headers from body
         $this->sendCommand($message->body);
         // expectedResult = 250 OK id=1aOrwv-00040C-2x
         if (substr($this->sendCommand('.'), 0, 3) != '250') {
             return false;
         }
         $this->sendCommand('QUIT');
         fclose($this->connect);
         return true;
     }
 }
function sock_open(&$sock, $host, $port)
{
    global $TOTAL_SOCKETS;
    $TOTAL_SOCKETS++;
    $sock->error = "";
    $sock->errno = 0;
    if (substr($host, 0, 7) != 'unix://') {
        $host = "tcp://{$host}:{$port}";
    }
    $sock->socket = @stream_socket_client($host, $sock->errno, $sock->error, 1, STREAM_CLIENT_CONNECT);
    if ($sock->socket !== false) {
        stream_set_timeout($sock->socket, $sock->timeout);
        if ($sock->ssl_enabled) {
            if ($sock->ssl_ca !== false) {
                stream_context_set_option($sock->socket, 'ssl', 'verify_peer', true);
                stream_context_set_option($sock->socket, 'ssl', 'cafile', $sock->ssl_ca);
            }
            if ($sock->ssl_cn !== false) {
                // only PHP 5.6 provides common name validation, so lets do this by ourselves
                stream_context_set_option($sock->socket, 'ssl', 'capture_peer_cert', true);
            }
            if (stream_socket_enable_crypto($sock->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT)) {
                if ($sock->ssl_cn !== false) {
                    $parameters = stream_context_get_params($sock->socket);
                    $certificate = openssl_x509_parse($parameters["options"]["ssl"]["peer_certificate"]);
                    $common_name = $certificate["subject"]["CN"];
                    if (fnmatch($common_name, $sock->ssl_cn, FNM_CASEFOLD) || fnmatch($sock->ssl_cn, $common_name, FNM_CASEFOLD)) {
                        return true;
                    } else {
                        sock_close($sock);
                        $sock->error = "SSL handshake error";
                        $sock->errno = 0;
                        return false;
                    }
                }
                return true;
            } else {
                sock_close($sock);
                $sock->error = "SSL handshake error";
                $sock->errno = 0;
                return false;
            }
        } else {
            return true;
        }
    } else {
        return false;
    }
}
Exemple #23
0
 /**
  * Set an individual param on the buffer (e.g. switching to SSL).
  * @param string $param
  * @param mixed $value
  */
 public function setParam($param, $value)
 {
     if (isset($this->_stream)) {
         switch ($param) {
             case 'protocol':
                 if (!array_key_exists('protocol', $this->_params) || $value != $this->_params['protocol']) {
                     if ('tls' == $value) {
                         stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                     }
                 }
                 break;
         }
     }
     $this->_params[$param] = $value;
 }
 /**
  * Create the socket to write request and read response on it
  *
  * @param RequestInterface $request Request for
  * @param string           $remote  Entrypoint for the connection
  * @param boolean          $useSsl  Whether to use ssl or not
  *
  * @throws NetworkException
  *
  * @return resource
  */
 protected function createSocket(RequestInterface $request, $remote, $useSsl)
 {
     $errNo = null;
     $errMsg = null;
     $socket = @stream_socket_client($remote, $errNo, $errMsg, $this->config['timeout'], STREAM_CLIENT_CONNECT, $this->config['stream_context']);
     if (false === $socket) {
         throw new NetworkException($errMsg, $request);
     }
     if ($useSsl) {
         if (false === @stream_socket_enable_crypto($socket, true, $this->config['ssl_method'])) {
             throw new NetworkException(sprintf('Cannot enable tls: %s', error_get_last()['message']), $request);
         }
     }
     return $socket;
 }
Exemple #25
0
 public function enableEncryption()
 {
     $crypto_method = STREAM_CRYPTO_METHOD_TLS_SERVER;
     if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_SERVER')) {
         $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_SERVER;
         $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_SERVER;
     }
     stream_set_blocking($this->getHandle(), true);
     $result = @stream_socket_enable_crypto($this->getHandle(), true, $crypto_method);
     stream_set_blocking($this->getHandle(), false);
     if ($result === false) {
         throw new RuntimeException('TLS negotiation has failed');
     }
     return true;
 }
Exemple #26
0
 /**
  * {@inheritdoc}
  */
 protected function openConnection()
 {
     parent::openConnection();
     if ($this->destinationSsl) {
         $headers = ['Host' => $this->destinationHost . ':' . $this->destinationPort, 'Proxy-Connection' => 'Keep-Alive'];
         $response = $this->writeRequest('CONNECT', $this->destinationHost . ':' . $this->destinationPort, $headers);
         if (!$response->isOk()) {
             throw new rex_socket_exception(sprintf('Couldn\'t connect to proxy server, server responds with "%s %s"'), $response->getStatusCode(), $response->getStatusMessage());
         }
         stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
     } else {
         unset($this->headers['Connection']);
         $this->addHeader('Proxy-Connection', 'Close');
         $this->path = 'http://' . $this->destinationHost . ':' . $this->destinationPort . $this->path;
     }
 }
Exemple #27
0
 /**
  * @return bool
  */
 public function Connect()
 {
     $sLine = '';
     $bResult = false;
     if (parent::Connect()) {
         $sLine = $this->GetNextLine();
         $aTokens = $this->parseLine($sLine);
         if ($aTokens && isset($aTokens[0], $aTokens[1]) && 'IMPLEMENTATION' === $aTokens[0]) {
             while (true) {
                 if (false === $sLine || !isset($aTokens[0]) || in_array(substr($sLine, 0, 2), array('OK', 'NO'))) {
                     break;
                 }
                 $sLine = trim($sLine);
                 if (in_array($aTokens[0], array('IMPLEMENTATION', 'VERSION'))) {
                     $this->aData[$aTokens[0]] = $aTokens[1];
                 } else {
                     if ('STARTTLS' === $aTokens[0]) {
                         $this->aData['STARTTLS'] = true;
                     } else {
                         if (isset($aTokens[1]) && in_array($aTokens[0], array('SIEVE', 'SASL'))) {
                             $this->aData['TYPE'] = 'SASL' === $aTokens[0] ? 'AUTH' : 'MODULES';
                             $this->aData[$this->aData['TYPE']] = explode(' ', $aTokens[1]);
                         } else {
                             $this->aData['UNDEFINED'] = isset($this->aData['UNDEFINED']) ? $this->aData['UNDEFINED'] : array();
                             $this->aData['UNDEFINED'][] = $sLine;
                         }
                     }
                 }
                 $sLine = $this->GetNextLine();
                 $aTokens = $this->parseLine($sLine);
             }
         }
     }
     if ('OK' === substr($sLine, 0, 2)) {
         $bResult = true;
     }
     if (CApi::GetConf('labs.sieve.use-starttls', false) && $bResult && isset($this->aData['STARTTLS']) && $this->aData['STARTTLS']) {
         $rConnect = $this->GetConnectResource();
         if (is_resource($rConnect) && function_exists('stream_socket_enable_crypto')) {
             if ($this->SendLine('STARTTLS') && $this->CheckResponse($this->GetResponse())) {
                 @stream_socket_enable_crypto($rConnect, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                 $this->CheckResponse($this->GetResponse());
             }
         }
     }
     return $bResult;
 }
Exemple #28
0
 private function executeStreamServer($socket)
 {
     $exit = false;
     while ($exit === false) {
         $forkedSocket = stream_socket_accept($socket, '-1', $remoteIp);
         stream_set_blocking($forkedSocket, true);
         stream_socket_enable_crypto($forkedSocket, true, STREAM_CRYPTO_METHOD_SSLv3_SERVER);
         $data = fread($forkedSocket, 8192);
         if (substr($data, 0, 16) === 'GET /stop-server') {
             $exit = true;
         }
         stream_set_blocking($forkedSocket, false);
         fwrite($forkedSocket, 'Response!');
         fclose($forkedSocket);
     }
     exit(0);
 }
 public function enableCrypto($socket, ResolverInterface $resolver)
 {
     $result = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
     if (true === $result) {
         $this->loop->removeWriteStream($socket);
         $this->loop->removeReadStream($socket);
         $resolver->resolve(new Stream($socket, $this->loop));
     } else {
         if (false === $result) {
             $this->loop->removeWriteStream($socket);
             $this->loop->removeReadStream($socket);
             $resolver->reject();
         } else {
             // need more data, will retry
         }
     }
 }
Exemple #30
0
function setup_server($pem_file, $pem_passphrase, $ip, $port)
{
    $context = stream_context_create();
    stream_context_set_option($context, 'ssl', 'local_cert', $pem_file);
    // Our SSL Cert in PEM format
    stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);
    // Private key Password
    stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
    stream_context_set_option($context, 'ssl', 'verify_peer', false);
    $socket = stream_socket_server("tcp://{$ip}:{$port}", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
    if ($socket === false) {
        echo "stream_socket_server() failure: {$errstr} ({$errno})\n";
        return false;
    }
    stream_socket_enable_crypto($socket, false);
    return $socket;
}