Socket.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Network;
  17. use Cake\Core\InstanceConfigTrait;
  18. use Cake\Network\Exception\SocketException;
  19. use Cake\Validation\Validation;
  20. use Composer\CaBundle\CaBundle;
  21. use Exception;
  22. use InvalidArgumentException;
  23. /**
  24. * CakePHP network socket connection class.
  25. *
  26. * Core base class for network communication.
  27. *
  28. * @mixin \Cake\Core\InstanceConfigTrait
  29. */
  30. class Socket
  31. {
  32. use InstanceConfigTrait;
  33. /**
  34. * Object description
  35. *
  36. * @var string
  37. */
  38. public $description = 'Remote DataSource Network Socket Interface';
  39. /**
  40. * Default configuration settings for the socket connection
  41. *
  42. * @var array
  43. */
  44. protected $_defaultConfig = [
  45. 'persistent' => false,
  46. 'host' => 'localhost',
  47. 'protocol' => 'tcp',
  48. 'port' => 80,
  49. 'timeout' => 30,
  50. ];
  51. /**
  52. * Reference to socket connection resource
  53. *
  54. * @var resource|null
  55. */
  56. public $connection;
  57. /**
  58. * This boolean contains the current state of the Socket class
  59. *
  60. * @var bool
  61. */
  62. public $connected = false;
  63. /**
  64. * This variable contains an array with the last error number (num) and string (str)
  65. *
  66. * @var array
  67. */
  68. public $lastError = [];
  69. /**
  70. * True if the socket stream is encrypted after a Cake\Network\Socket::enableCrypto() call
  71. *
  72. * @var bool
  73. */
  74. public $encrypted = false;
  75. /**
  76. * Contains all the encryption methods available
  77. *
  78. *
  79. * @var array
  80. */
  81. protected $_encryptMethods = [
  82. // @codingStandardsIgnoreStart
  83. 'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
  84. 'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
  85. 'tlsv10_client' => STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT,
  86. 'tlsv11_client' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT,
  87. 'tlsv12_client' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
  88. 'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
  89. 'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER,
  90. 'tlsv10_server' => STREAM_CRYPTO_METHOD_TLSv1_0_SERVER,
  91. 'tlsv11_server' => STREAM_CRYPTO_METHOD_TLSv1_1_SERVER,
  92. 'tlsv12_server' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
  93. // @codingStandardsIgnoreEnd
  94. ];
  95. /**
  96. * Used to capture connection warnings which can happen when there are
  97. * SSL errors for example.
  98. *
  99. * @var array
  100. */
  101. protected $_connectionErrors = [];
  102. /**
  103. * Constructor.
  104. *
  105. * @param array $config Socket configuration, which will be merged with the base configuration
  106. * @see \Cake\Network\Socket::$_baseConfig
  107. */
  108. public function __construct(array $config = [])
  109. {
  110. $this->setConfig($config);
  111. }
  112. /**
  113. * Connect the socket to the given host and port.
  114. *
  115. * @return bool Success
  116. * @throws \Cake\Network\Exception\SocketException
  117. */
  118. public function connect(): bool
  119. {
  120. if ($this->connection) {
  121. $this->disconnect();
  122. }
  123. $hasProtocol = strpos($this->_config['host'], '://') !== false;
  124. if ($hasProtocol) {
  125. list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
  126. }
  127. $scheme = null;
  128. if (!empty($this->_config['protocol'])) {
  129. $scheme = $this->_config['protocol'] . '://';
  130. }
  131. $this->_setSslContext($this->_config['host']);
  132. if (!empty($this->_config['context'])) {
  133. $context = stream_context_create($this->_config['context']);
  134. } else {
  135. $context = stream_context_create();
  136. }
  137. $connectAs = STREAM_CLIENT_CONNECT;
  138. if ($this->_config['persistent']) {
  139. $connectAs |= STREAM_CLIENT_PERSISTENT;
  140. }
  141. set_error_handler([$this, '_connectionErrorHandler']);
  142. $this->connection = stream_socket_client(
  143. $scheme . $this->_config['host'] . ':' . $this->_config['port'],
  144. $errNum,
  145. $errStr,
  146. $this->_config['timeout'],
  147. $connectAs,
  148. $context
  149. );
  150. restore_error_handler();
  151. if (!empty($errNum) || !empty($errStr)) {
  152. $this->setLastError($errNum, $errStr);
  153. throw new SocketException($errStr, $errNum);
  154. }
  155. if (!$this->connection && $this->_connectionErrors) {
  156. $message = implode("\n", $this->_connectionErrors);
  157. throw new SocketException($message, E_WARNING);
  158. }
  159. $this->connected = is_resource($this->connection);
  160. if ($this->connected) {
  161. stream_set_timeout($this->connection, $this->_config['timeout']);
  162. }
  163. return $this->connected;
  164. }
  165. /**
  166. * Configure the SSL context options.
  167. *
  168. * @param string $host The host name being connected to.
  169. * @return void
  170. */
  171. protected function _setSslContext(string $host): void
  172. {
  173. foreach ($this->_config as $key => $value) {
  174. if (substr($key, 0, 4) !== 'ssl_') {
  175. continue;
  176. }
  177. $contextKey = substr($key, 4);
  178. if (empty($this->_config['context']['ssl'][$contextKey])) {
  179. $this->_config['context']['ssl'][$contextKey] = $value;
  180. }
  181. unset($this->_config[$key]);
  182. }
  183. if (!isset($this->_config['context']['ssl']['SNI_enabled'])) {
  184. $this->_config['context']['ssl']['SNI_enabled'] = true;
  185. }
  186. if (empty($this->_config['context']['ssl']['peer_name'])) {
  187. $this->_config['context']['ssl']['peer_name'] = $host;
  188. }
  189. if (empty($this->_config['context']['ssl']['cafile'])) {
  190. $this->_config['context']['ssl']['cafile'] = CaBundle::getBundledCaBundlePath();
  191. }
  192. if (!empty($this->_config['context']['ssl']['verify_host'])) {
  193. $this->_config['context']['ssl']['CN_match'] = $host;
  194. }
  195. unset($this->_config['context']['ssl']['verify_host']);
  196. }
  197. /**
  198. * socket_stream_client() does not populate errNum, or $errStr when there are
  199. * connection errors, as in the case of SSL verification failure.
  200. *
  201. * Instead we need to handle those errors manually.
  202. *
  203. * @param int $code Code number.
  204. * @param string $message Message.
  205. * @return void
  206. */
  207. protected function _connectionErrorHandler(int $code, string $message): void
  208. {
  209. $this->_connectionErrors[] = $message;
  210. }
  211. /**
  212. * Get the connection context.
  213. *
  214. * @return null|array Null when there is no connection, an array when there is.
  215. */
  216. public function context(): ?array
  217. {
  218. if (!$this->connection) {
  219. return null;
  220. }
  221. return stream_context_get_options($this->connection);
  222. }
  223. /**
  224. * Get the host name of the current connection.
  225. *
  226. * @return string Host name
  227. */
  228. public function host(): string
  229. {
  230. if (Validation::ip($this->_config['host'])) {
  231. return gethostbyaddr($this->_config['host']);
  232. }
  233. return gethostbyaddr($this->address());
  234. }
  235. /**
  236. * Get the IP address of the current connection.
  237. *
  238. * @return string IP address
  239. */
  240. public function address(): string
  241. {
  242. if (Validation::ip($this->_config['host'])) {
  243. return $this->_config['host'];
  244. }
  245. return gethostbyname($this->_config['host']);
  246. }
  247. /**
  248. * Get all IP addresses associated with the current connection.
  249. *
  250. * @return array IP addresses
  251. */
  252. public function addresses(): array
  253. {
  254. if (Validation::ip($this->_config['host'])) {
  255. return [$this->_config['host']];
  256. }
  257. return gethostbynamel($this->_config['host']);
  258. }
  259. /**
  260. * Get the last error as a string.
  261. *
  262. * @return string|null Last error
  263. */
  264. public function lastError(): ?string
  265. {
  266. if (!empty($this->lastError)) {
  267. return $this->lastError['num'] . ': ' . $this->lastError['str'];
  268. }
  269. return null;
  270. }
  271. /**
  272. * Set the last error.
  273. *
  274. * @param int|null $errNum Error code
  275. * @param string $errStr Error string
  276. * @return void
  277. */
  278. public function setLastError(?int $errNum, string $errStr): void
  279. {
  280. $this->lastError = ['num' => $errNum, 'str' => $errStr];
  281. }
  282. /**
  283. * Write data to the socket.
  284. *
  285. * @param string $data The data to write to the socket.
  286. * @return int Bytes written.
  287. */
  288. public function write(string $data): int
  289. {
  290. if (!$this->connected && !$this->connect()) {
  291. return 0;
  292. }
  293. $totalBytes = strlen($data);
  294. $written = 0;
  295. while ($written < $totalBytes) {
  296. $rv = fwrite($this->connection, substr($data, $written));
  297. if ($rv === false || $rv === 0) {
  298. return $written;
  299. }
  300. $written += $rv;
  301. }
  302. return $written;
  303. }
  304. /**
  305. * Read data from the socket. Returns null if no data is available or no connection could be
  306. * established.
  307. *
  308. * @param int $length Optional buffer length to read; defaults to 1024
  309. * @return string|null Socket data
  310. */
  311. public function read(int $length = 1024): ?string
  312. {
  313. if (!$this->connected && !$this->connect()) {
  314. return null;
  315. }
  316. if (!feof($this->connection)) {
  317. $buffer = fread($this->connection, $length);
  318. $info = stream_get_meta_data($this->connection);
  319. if ($info['timed_out']) {
  320. $this->setLastError(E_WARNING, 'Connection timed out');
  321. return null;
  322. }
  323. return $buffer;
  324. }
  325. return null;
  326. }
  327. /**
  328. * Disconnect the socket from the current connection.
  329. *
  330. * @return bool Success
  331. */
  332. public function disconnect(): bool
  333. {
  334. if (!is_resource($this->connection)) {
  335. $this->connected = false;
  336. return true;
  337. }
  338. $this->connected = !fclose($this->connection);
  339. if (!$this->connected) {
  340. $this->connection = null;
  341. }
  342. return !$this->connected;
  343. }
  344. /**
  345. * Destructor, used to disconnect from current connection.
  346. */
  347. public function __destruct()
  348. {
  349. $this->disconnect();
  350. }
  351. /**
  352. * Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
  353. *
  354. * @param array|null $state Array with key and values to reset
  355. * @return bool True on success
  356. */
  357. public function reset(?array $state = null): bool
  358. {
  359. if (empty($state)) {
  360. static $initalState = [];
  361. if (empty($initalState)) {
  362. $initalState = get_class_vars(__CLASS__);
  363. }
  364. $state = $initalState;
  365. }
  366. foreach ($state as $property => $value) {
  367. $this->{$property} = $value;
  368. }
  369. return true;
  370. }
  371. /**
  372. * Encrypts current stream socket, using one of the defined encryption methods
  373. *
  374. * @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
  375. * @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
  376. * @param bool $enable enable or disable encryption. Default is true (enable)
  377. * @return bool True on success
  378. * @throws \InvalidArgumentException When an invalid encryption scheme is chosen.
  379. * @throws \Cake\Network\Exception\SocketException When attempting to enable SSL/TLS fails
  380. * @see stream_socket_enable_crypto
  381. */
  382. public function enableCrypto(string $type, string $clientOrServer = 'client', bool $enable = true): bool
  383. {
  384. if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
  385. throw new InvalidArgumentException('Invalid encryption scheme chosen');
  386. }
  387. $method = $this->_encryptMethods[$type . '_' . $clientOrServer];
  388. // Prior to PHP 5.6.7 TLS_CLIENT was any version of TLS. This was changed in 5.6.7
  389. // to fix backwards compatibility issues, and now only resolves to TLS1.0
  390. //
  391. // See https://github.com/php/php-src/commit/10bc5fd4c4c8e1dd57bd911b086e9872a56300a0
  392. if (version_compare(PHP_VERSION, '5.6.7', '>=')) {
  393. if ($method === STREAM_CRYPTO_METHOD_TLS_CLIENT) {
  394. // @codingStandardsIgnoreStart
  395. $method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
  396. // @codingStandardsIgnoreEnd
  397. }
  398. if ($method === STREAM_CRYPTO_METHOD_TLS_SERVER) {
  399. // @codingStandardsIgnoreStart
  400. $method |= STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER;
  401. // @codingStandardsIgnoreEnd
  402. }
  403. }
  404. try {
  405. $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $method);
  406. } catch (Exception $e) {
  407. $this->setLastError(null, $e->getMessage());
  408. throw new SocketException($e->getMessage(), null, $e);
  409. }
  410. if ($enableCryptoResult === true) {
  411. $this->encrypted = $enable;
  412. return true;
  413. }
  414. $errorMessage = 'Unable to perform enableCrypto operation on the current socket';
  415. $this->setLastError(null, $errorMessage);
  416. throw new SocketException($errorMessage);
  417. }
  418. }