| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470 |
- <?php
- declare(strict_types=1);
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 1.2.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Network;
- use Cake\Core\InstanceConfigTrait;
- use Cake\Network\Exception\SocketException;
- use Cake\Validation\Validation;
- use Composer\CaBundle\CaBundle;
- use Exception;
- use InvalidArgumentException;
- /**
- * CakePHP network socket connection class.
- *
- * Core base class for network communication.
- *
- * @mixin \Cake\Core\InstanceConfigTrait
- */
- class Socket
- {
- use InstanceConfigTrait;
- /**
- * Object description
- *
- * @var string
- */
- public $description = 'Remote DataSource Network Socket Interface';
- /**
- * Default configuration settings for the socket connection
- *
- * @var array
- */
- protected $_defaultConfig = [
- 'persistent' => false,
- 'host' => 'localhost',
- 'protocol' => 'tcp',
- 'port' => 80,
- 'timeout' => 30,
- ];
- /**
- * Reference to socket connection resource
- *
- * @var resource|null
- */
- public $connection;
- /**
- * This boolean contains the current state of the Socket class
- *
- * @var bool
- */
- public $connected = false;
- /**
- * This variable contains an array with the last error number (num) and string (str)
- *
- * @var array
- */
- public $lastError = [];
- /**
- * True if the socket stream is encrypted after a Cake\Network\Socket::enableCrypto() call
- *
- * @var bool
- */
- public $encrypted = false;
- /**
- * Contains all the encryption methods available
- *
- *
- * @var array
- */
- protected $_encryptMethods = [
- // @codingStandardsIgnoreStart
- 'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
- 'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
- 'tlsv10_client' => STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT,
- 'tlsv11_client' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT,
- 'tlsv12_client' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
- 'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
- 'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER,
- 'tlsv10_server' => STREAM_CRYPTO_METHOD_TLSv1_0_SERVER,
- 'tlsv11_server' => STREAM_CRYPTO_METHOD_TLSv1_1_SERVER,
- 'tlsv12_server' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
- // @codingStandardsIgnoreEnd
- ];
- /**
- * Used to capture connection warnings which can happen when there are
- * SSL errors for example.
- *
- * @var array
- */
- protected $_connectionErrors = [];
- /**
- * Constructor.
- *
- * @param array $config Socket configuration, which will be merged with the base configuration
- * @see \Cake\Network\Socket::$_baseConfig
- */
- public function __construct(array $config = [])
- {
- $this->setConfig($config);
- }
- /**
- * Connect the socket to the given host and port.
- *
- * @return bool Success
- * @throws \Cake\Network\Exception\SocketException
- */
- public function connect(): bool
- {
- if ($this->connection) {
- $this->disconnect();
- }
- $hasProtocol = strpos($this->_config['host'], '://') !== false;
- if ($hasProtocol) {
- list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
- }
- $scheme = null;
- if (!empty($this->_config['protocol'])) {
- $scheme = $this->_config['protocol'] . '://';
- }
- $this->_setSslContext($this->_config['host']);
- if (!empty($this->_config['context'])) {
- $context = stream_context_create($this->_config['context']);
- } else {
- $context = stream_context_create();
- }
- $connectAs = STREAM_CLIENT_CONNECT;
- if ($this->_config['persistent']) {
- $connectAs |= STREAM_CLIENT_PERSISTENT;
- }
- set_error_handler([$this, '_connectionErrorHandler']);
- $this->connection = stream_socket_client(
- $scheme . $this->_config['host'] . ':' . $this->_config['port'],
- $errNum,
- $errStr,
- $this->_config['timeout'],
- $connectAs,
- $context
- );
- restore_error_handler();
- if (!empty($errNum) || !empty($errStr)) {
- $this->setLastError($errNum, $errStr);
- throw new SocketException($errStr, $errNum);
- }
- if (!$this->connection && $this->_connectionErrors) {
- $message = implode("\n", $this->_connectionErrors);
- throw new SocketException($message, E_WARNING);
- }
- $this->connected = is_resource($this->connection);
- if ($this->connected) {
- stream_set_timeout($this->connection, $this->_config['timeout']);
- }
- return $this->connected;
- }
- /**
- * Configure the SSL context options.
- *
- * @param string $host The host name being connected to.
- * @return void
- */
- protected function _setSslContext(string $host): void
- {
- foreach ($this->_config as $key => $value) {
- if (substr($key, 0, 4) !== 'ssl_') {
- continue;
- }
- $contextKey = substr($key, 4);
- if (empty($this->_config['context']['ssl'][$contextKey])) {
- $this->_config['context']['ssl'][$contextKey] = $value;
- }
- unset($this->_config[$key]);
- }
- if (!isset($this->_config['context']['ssl']['SNI_enabled'])) {
- $this->_config['context']['ssl']['SNI_enabled'] = true;
- }
- if (empty($this->_config['context']['ssl']['peer_name'])) {
- $this->_config['context']['ssl']['peer_name'] = $host;
- }
- if (empty($this->_config['context']['ssl']['cafile'])) {
- $this->_config['context']['ssl']['cafile'] = CaBundle::getBundledCaBundlePath();
- }
- if (!empty($this->_config['context']['ssl']['verify_host'])) {
- $this->_config['context']['ssl']['CN_match'] = $host;
- }
- unset($this->_config['context']['ssl']['verify_host']);
- }
- /**
- * socket_stream_client() does not populate errNum, or $errStr when there are
- * connection errors, as in the case of SSL verification failure.
- *
- * Instead we need to handle those errors manually.
- *
- * @param int $code Code number.
- * @param string $message Message.
- * @return void
- */
- protected function _connectionErrorHandler(int $code, string $message): void
- {
- $this->_connectionErrors[] = $message;
- }
- /**
- * Get the connection context.
- *
- * @return null|array Null when there is no connection, an array when there is.
- */
- public function context(): ?array
- {
- if (!$this->connection) {
- return null;
- }
- return stream_context_get_options($this->connection);
- }
- /**
- * Get the host name of the current connection.
- *
- * @return string Host name
- */
- public function host(): string
- {
- if (Validation::ip($this->_config['host'])) {
- return gethostbyaddr($this->_config['host']);
- }
- return gethostbyaddr($this->address());
- }
- /**
- * Get the IP address of the current connection.
- *
- * @return string IP address
- */
- public function address(): string
- {
- if (Validation::ip($this->_config['host'])) {
- return $this->_config['host'];
- }
- return gethostbyname($this->_config['host']);
- }
- /**
- * Get all IP addresses associated with the current connection.
- *
- * @return array IP addresses
- */
- public function addresses(): array
- {
- if (Validation::ip($this->_config['host'])) {
- return [$this->_config['host']];
- }
- return gethostbynamel($this->_config['host']);
- }
- /**
- * Get the last error as a string.
- *
- * @return string|null Last error
- */
- public function lastError(): ?string
- {
- if (!empty($this->lastError)) {
- return $this->lastError['num'] . ': ' . $this->lastError['str'];
- }
- return null;
- }
- /**
- * Set the last error.
- *
- * @param int|null $errNum Error code
- * @param string $errStr Error string
- * @return void
- */
- public function setLastError(?int $errNum, string $errStr): void
- {
- $this->lastError = ['num' => $errNum, 'str' => $errStr];
- }
- /**
- * Write data to the socket.
- *
- * @param string $data The data to write to the socket.
- * @return int Bytes written.
- */
- public function write(string $data): int
- {
- if (!$this->connected && !$this->connect()) {
- return 0;
- }
- $totalBytes = strlen($data);
- $written = 0;
- while ($written < $totalBytes) {
- $rv = fwrite($this->connection, substr($data, $written));
- if ($rv === false || $rv === 0) {
- return $written;
- }
- $written += $rv;
- }
- return $written;
- }
- /**
- * Read data from the socket. Returns null if no data is available or no connection could be
- * established.
- *
- * @param int $length Optional buffer length to read; defaults to 1024
- * @return string|null Socket data
- */
- public function read(int $length = 1024): ?string
- {
- if (!$this->connected && !$this->connect()) {
- return null;
- }
- if (!feof($this->connection)) {
- $buffer = fread($this->connection, $length);
- $info = stream_get_meta_data($this->connection);
- if ($info['timed_out']) {
- $this->setLastError(E_WARNING, 'Connection timed out');
- return null;
- }
- return $buffer;
- }
- return null;
- }
- /**
- * Disconnect the socket from the current connection.
- *
- * @return bool Success
- */
- public function disconnect(): bool
- {
- if (!is_resource($this->connection)) {
- $this->connected = false;
- return true;
- }
- $this->connected = !fclose($this->connection);
- if (!$this->connected) {
- $this->connection = null;
- }
- return !$this->connected;
- }
- /**
- * Destructor, used to disconnect from current connection.
- */
- public function __destruct()
- {
- $this->disconnect();
- }
- /**
- * Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
- *
- * @param array|null $state Array with key and values to reset
- * @return bool True on success
- */
- public function reset(?array $state = null): bool
- {
- if (empty($state)) {
- static $initalState = [];
- if (empty($initalState)) {
- $initalState = get_class_vars(__CLASS__);
- }
- $state = $initalState;
- }
- foreach ($state as $property => $value) {
- $this->{$property} = $value;
- }
- return true;
- }
- /**
- * Encrypts current stream socket, using one of the defined encryption methods
- *
- * @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
- * @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
- * @param bool $enable enable or disable encryption. Default is true (enable)
- * @return bool True on success
- * @throws \InvalidArgumentException When an invalid encryption scheme is chosen.
- * @throws \Cake\Network\Exception\SocketException When attempting to enable SSL/TLS fails
- * @see stream_socket_enable_crypto
- */
- public function enableCrypto(string $type, string $clientOrServer = 'client', bool $enable = true): bool
- {
- if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
- throw new InvalidArgumentException('Invalid encryption scheme chosen');
- }
- $method = $this->_encryptMethods[$type . '_' . $clientOrServer];
- // Prior to PHP 5.6.7 TLS_CLIENT was any version of TLS. This was changed in 5.6.7
- // to fix backwards compatibility issues, and now only resolves to TLS1.0
- //
- // See https://github.com/php/php-src/commit/10bc5fd4c4c8e1dd57bd911b086e9872a56300a0
- if (version_compare(PHP_VERSION, '5.6.7', '>=')) {
- if ($method === STREAM_CRYPTO_METHOD_TLS_CLIENT) {
- // @codingStandardsIgnoreStart
- $method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
- // @codingStandardsIgnoreEnd
- }
- if ($method === STREAM_CRYPTO_METHOD_TLS_SERVER) {
- // @codingStandardsIgnoreStart
- $method |= STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER;
- // @codingStandardsIgnoreEnd
- }
- }
- try {
- $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $method);
- } catch (Exception $e) {
- $this->setLastError(null, $e->getMessage());
- throw new SocketException($e->getMessage(), null, $e);
- }
- if ($enableCryptoResult === true) {
- $this->encrypted = $enable;
- return true;
- }
- $errorMessage = 'Unable to perform enableCrypto operation on the current socket';
- $this->setLastError(null, $errorMessage);
- throw new SocketException($errorMessage);
- }
- }
|