Client.php 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. /**
  3. * Hoa
  4. *
  5. *
  6. * @license
  7. *
  8. * New BSD License
  9. *
  10. * Copyright © 2007-2017, Hoa community. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions are met:
  14. * * Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * * Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * * Neither the name of the Hoa nor the names of its contributors may be
  20. * used to endorse or promote products derived from this software without
  21. * specific prior written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  24. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  25. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  26. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
  27. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  28. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  29. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  30. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  31. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  32. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. namespace Hoa\Websocket;
  36. use Hoa\Consistency;
  37. use Hoa\Event;
  38. use Hoa\Http;
  39. use Hoa\Socket as HoaSocket;
  40. /**
  41. * Class \Hoa\Websocket\Client.
  42. *
  43. * A cross-protocol Websocket client.
  44. *
  45. * @copyright Copyright © 2007-2017 Hoa community
  46. * @license New BSD License
  47. */
  48. class Client extends Connection
  49. {
  50. /**
  51. * Endpoint.
  52. *
  53. * @var string
  54. */
  55. protected $_endPoint = null;
  56. /**
  57. * Host name.
  58. *
  59. * @var string
  60. */
  61. protected $_host = null;
  62. /**
  63. * Response (mainly parser).
  64. *
  65. * @var \Hoa\Http\Response
  66. */
  67. protected $_response = null;
  68. /**
  69. * Create a Websocket client.
  70. *
  71. * @param \Hoa\Socket\Client $client Client.
  72. * @param string $endPoint End-point.
  73. * @param \Hoa\Http\Response $request Response parser.
  74. * @throws \Hoa\Socket\Exception
  75. */
  76. public function __construct(
  77. HoaSocket\Client $client,
  78. $endPoint = null,
  79. Http\Response $response = null
  80. ) {
  81. parent::__construct($client);
  82. if (null === $endPoint) {
  83. $endPoint = '/';
  84. $socket = $client->getSocket();
  85. if ($socket instanceof Socket) {
  86. $endPoint = $socket->getEndPoint();
  87. }
  88. }
  89. $this->setEndPoint($endPoint);
  90. if (null === $response) {
  91. $response = new Http\Response(false);
  92. }
  93. $this->setResponse($response);
  94. return;
  95. }
  96. /**
  97. * Connect, i.e. open the connection and do handshake.
  98. *
  99. * @return void
  100. */
  101. public function connect()
  102. {
  103. return $this->doHandshake();
  104. }
  105. /**
  106. * Override the parent run() method to open the connection.
  107. *
  108. * @return void
  109. */
  110. public function run()
  111. {
  112. $this->connect();
  113. return parent::run();
  114. }
  115. /**
  116. * Receive data. Fire listeners.
  117. *
  118. * @return void
  119. */
  120. public function receive()
  121. {
  122. $connection = $this->getConnection();
  123. $node = $connection->getCurrentNode();
  124. do {
  125. $this->_run($node);
  126. } while (
  127. false === $connection->isDisconnected() &&
  128. true !== $node->isMessageComplete()
  129. );
  130. }
  131. /**
  132. * Try the handshake by trying different protocol implementation.
  133. *
  134. * @return void
  135. * @throws \Hoa\Websocket\Exception
  136. * @throws \Hoa\Websocket\Exception\BadProtocol
  137. */
  138. protected function doHandshake()
  139. {
  140. $connection = $this->getConnection();
  141. $connection->connect();
  142. if (true === $connection->getSocket()->isSecured()) {
  143. $connection->enableEncryption(true, $connection::ENCRYPTION_TLS);
  144. }
  145. $connection->setStreamBlocking(true);
  146. $key = $this->getNewChallenge();
  147. $expected = base64_encode(sha1($key . Protocol\Rfc6455::GUID, true));
  148. if (null === $host = $this->getHost()) {
  149. throw new Exception(
  150. 'Host name is null. Please, use the %s::setHost() method.',
  151. 0,
  152. __CLASS__
  153. );
  154. }
  155. $connection->writeAll(
  156. $request =
  157. 'GET ' . $this->getEndPoint() . ' HTTP/1.1' . CRLF .
  158. 'Host: ' . $host . CRLF .
  159. 'User-Agent: Hoa' . CRLF .
  160. 'Upgrade: WebSocket' . CRLF .
  161. 'Connection: Upgrade' . CRLF .
  162. 'Pragma: no-cache' . CRLF .
  163. 'Cache-Control: no-cache' . CRLF .
  164. 'Sec-WebSocket-Key: ' . $key . CRLF .
  165. 'Sec-WebSocket-Version: 13' . CRLF . CRLF
  166. );
  167. $buffer = $connection->read(2048);
  168. $response = $this->getResponse();
  169. $response->parse($buffer);
  170. if ($response::STATUS_SWITCHING_PROTOCOLS !== $response['status'] ||
  171. 'websocket' !== strtolower($response['upgrade']) ||
  172. 'upgrade' !== strtolower($response['connection']) ||
  173. $expected !== $response['sec-websocket-accept']) {
  174. throw new Exception\BadProtocol(
  175. 'Handshake has failed, the server did not return a valid ' .
  176. 'response.' . "\n\n" .
  177. 'Client:' . "\n" . ' %s' . "\n" .
  178. 'Server:' . "\n" . ' %s',
  179. 0,
  180. [
  181. str_replace("\n", "\n" . ' ', $request),
  182. str_replace("\n", "\n" . ' ', $buffer)
  183. ]
  184. );
  185. }
  186. $currentNode = $connection->getCurrentNode();
  187. $currentNode->setHandshake(SUCCEED);
  188. $currentNode->setProtocolImplementation(new Protocol\Rfc6455($connection));
  189. $this->getListener()->fire(
  190. 'open',
  191. new Event\Bucket()
  192. );
  193. return;
  194. }
  195. /**
  196. * Generate a challenge.
  197. *
  198. * @return string
  199. */
  200. public function getNewChallenge()
  201. {
  202. static $_tail = ['A', 'Q', 'g', 'w'];
  203. return
  204. substr(base64_encode(Consistency::uuid()), 0, 21) .
  205. $_tail[mt_rand(0, 3)] . '==';
  206. }
  207. /**
  208. * Close a specific node/connection.
  209. *
  210. * @param int $code Code (please, see
  211. * self::CLOSE_* constants).
  212. * @param string $reason Reason.
  213. * @return void
  214. */
  215. public function close($code = self::CLOSE_NORMAL, $reason = null)
  216. {
  217. $connection = $this->getConnection();
  218. $protocol = $connection->getCurrentNode()->getProtocolImplementation();
  219. if (null !== $protocol) {
  220. $protocol->close($code, $reason, true);
  221. }
  222. $connection->mute();
  223. $connection->setStreamTimeout(0, 2 * 15000); // 2 * MLS (on FreeBSD)
  224. $connection->read(1);
  225. return $connection->disconnect();
  226. }
  227. /**
  228. * Set end-point.
  229. *
  230. * @param string $endPoint End-point.
  231. * @return string
  232. */
  233. protected function setEndPoint($endPoint)
  234. {
  235. $old = $this->_endPoint;
  236. $this->_endPoint = $endPoint;
  237. return $old;
  238. }
  239. /**
  240. * Get end-point.
  241. *
  242. * @return string
  243. */
  244. public function getEndPoint()
  245. {
  246. return $this->_endPoint;
  247. }
  248. /**
  249. * Set response (mainly parser).
  250. *
  251. * @param \Hoa\Http\Response $response Response.
  252. * @return \Hoa\Http\Response
  253. */
  254. public function setResponse(Http\Response $response)
  255. {
  256. $old = $this->_response;
  257. $this->_response = $response;
  258. return $old;
  259. }
  260. /**
  261. * Get response.
  262. *
  263. * @return \Hoa\Http\Response
  264. */
  265. public function getResponse()
  266. {
  267. return $this->_response;
  268. }
  269. /**
  270. * Set host.
  271. *
  272. * @param string $host Host.
  273. * @return string
  274. */
  275. public function setHost($host)
  276. {
  277. $old = $this->_host;
  278. $this->_host = $host;
  279. return $old;
  280. }
  281. /**
  282. * Get host.
  283. *
  284. * @return string
  285. */
  286. public function getHost()
  287. {
  288. return
  289. null !== $this->_host
  290. ? $this->_host
  291. : (isset($_SERVER['HTTP_HOST'])
  292. ? $_SERVER['HTTP_HOST']
  293. : null);
  294. }
  295. }