Base for a static organization website

CakeSocket.php 12KB

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