Socket.php 9.4 KB

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