CakeSocket.php 9.6 KB

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