CakeSocket.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. /**
  3. * CakePHP 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 http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('Validation', 'Utility');
  21. /**
  22. * CakePHP 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 integer $code
  167. * @param string $message
  168. * @return void
  169. */
  170. protected function _connectionErrorHandler($code, $message) {
  171. $this->_connectionErrors[] = $message;
  172. }
  173. /**
  174. * Get the connection context.
  175. *
  176. * @return null|array Null when there is no connection, an array when there is.
  177. */
  178. public function context() {
  179. if (!$this->connection) {
  180. return;
  181. }
  182. return stream_context_get_options($this->connection);
  183. }
  184. /**
  185. * Get the host name of the current connection.
  186. *
  187. * @return string Host name
  188. */
  189. public function host() {
  190. if (Validation::ip($this->config['host'])) {
  191. return gethostbyaddr($this->config['host']);
  192. }
  193. return gethostbyaddr($this->address());
  194. }
  195. /**
  196. * Get the IP address of the current connection.
  197. *
  198. * @return string IP address
  199. */
  200. public function address() {
  201. if (Validation::ip($this->config['host'])) {
  202. return $this->config['host'];
  203. }
  204. return gethostbyname($this->config['host']);
  205. }
  206. /**
  207. * Get all IP addresses associated with the current connection.
  208. *
  209. * @return array IP addresses
  210. */
  211. public function addresses() {
  212. if (Validation::ip($this->config['host'])) {
  213. return array($this->config['host']);
  214. }
  215. return gethostbynamel($this->config['host']);
  216. }
  217. /**
  218. * Get the last error as a string.
  219. *
  220. * @return string Last error
  221. */
  222. public function lastError() {
  223. if (!empty($this->lastError)) {
  224. return $this->lastError['num'] . ': ' . $this->lastError['str'];
  225. }
  226. return null;
  227. }
  228. /**
  229. * Set the last error.
  230. *
  231. * @param integer $errNum Error code
  232. * @param string $errStr Error string
  233. * @return void
  234. */
  235. public function setLastError($errNum, $errStr) {
  236. $this->lastError = array('num' => $errNum, 'str' => $errStr);
  237. }
  238. /**
  239. * Write data to the socket.
  240. *
  241. * @param string $data The data to write to the socket
  242. * @return boolean Success
  243. */
  244. public function write($data) {
  245. if (!$this->connected) {
  246. if (!$this->connect()) {
  247. return false;
  248. }
  249. }
  250. $totalBytes = strlen($data);
  251. for ($written = 0, $rv = 0; $written < $totalBytes; $written += $rv) {
  252. $rv = fwrite($this->connection, substr($data, $written));
  253. if ($rv === false || $rv === 0) {
  254. return $written;
  255. }
  256. }
  257. return $written;
  258. }
  259. /**
  260. * Read data from the socket. Returns false if no data is available or no connection could be
  261. * established.
  262. *
  263. * @param integer $length Optional buffer length to read; defaults to 1024
  264. * @return mixed Socket data
  265. */
  266. public function read($length = 1024) {
  267. if (!$this->connected) {
  268. if (!$this->connect()) {
  269. return false;
  270. }
  271. }
  272. if (!feof($this->connection)) {
  273. $buffer = fread($this->connection, $length);
  274. $info = stream_get_meta_data($this->connection);
  275. if ($info['timed_out']) {
  276. $this->setLastError(E_WARNING, __d('cake_dev', 'Connection timed out'));
  277. return false;
  278. }
  279. return $buffer;
  280. }
  281. return false;
  282. }
  283. /**
  284. * Disconnect the socket from the current connection.
  285. *
  286. * @return boolean Success
  287. */
  288. public function disconnect() {
  289. if (!is_resource($this->connection)) {
  290. $this->connected = false;
  291. return true;
  292. }
  293. $this->connected = !fclose($this->connection);
  294. if (!$this->connected) {
  295. $this->connection = null;
  296. }
  297. return !$this->connected;
  298. }
  299. /**
  300. * Destructor, used to disconnect from current connection.
  301. *
  302. */
  303. public function __destruct() {
  304. $this->disconnect();
  305. }
  306. /**
  307. * Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
  308. *
  309. * @param array $state Array with key and values to reset
  310. * @return boolean True on success
  311. */
  312. public function reset($state = null) {
  313. if (empty($state)) {
  314. static $initalState = array();
  315. if (empty($initalState)) {
  316. $initalState = get_class_vars(__CLASS__);
  317. }
  318. $state = $initalState;
  319. }
  320. foreach ($state as $property => $value) {
  321. $this->{$property} = $value;
  322. }
  323. return true;
  324. }
  325. /**
  326. * Encrypts current stream socket, using one of the defined encryption methods
  327. *
  328. * @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
  329. * @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
  330. * @param boolean $enable enable or disable encryption. Default is true (enable)
  331. * @return boolean True on success
  332. * @throws InvalidArgumentException When an invalid encryption scheme is chosen.
  333. * @throws SocketException When attempting to enable SSL/TLS fails
  334. * @see stream_socket_enable_crypto
  335. */
  336. public function enableCrypto($type, $clientOrServer = 'client', $enable = true) {
  337. if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
  338. throw new InvalidArgumentException(__d('cake_dev', 'Invalid encryption scheme chosen'));
  339. }
  340. $enableCryptoResult = false;
  341. try {
  342. $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $this->_encryptMethods[$type . '_' . $clientOrServer]);
  343. } catch (Exception $e) {
  344. $this->setLastError(null, $e->getMessage());
  345. throw new SocketException($e->getMessage());
  346. }
  347. if ($enableCryptoResult === true) {
  348. $this->encrypted = $enable;
  349. return true;
  350. }
  351. $errorMessage = __d('cake_dev', 'Unable to perform enableCrypto operation on CakeSocket');
  352. $this->setLastError(null, $errorMessage);
  353. throw new SocketException($errorMessage);
  354. }
  355. }