CakeSocket.php 9.6 KB

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