Ws.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Protocols;
  15. use Workerman\Worker;
  16. use Workerman\Lib\Timer;
  17. use Workerman\Connection\TcpConnection;
  18. use Workerman\Connection\ConnectionInterface;
  19. /**
  20. * Websocket protocol for client.
  21. */
  22. class Ws
  23. {
  24. /**
  25. * Websocket blob type.
  26. *
  27. * @var string
  28. */
  29. const BINARY_TYPE_BLOB = "\x81";
  30. /**
  31. * Websocket arraybuffer type.
  32. *
  33. * @var string
  34. */
  35. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  36. /**
  37. * Check the integrity of the package.
  38. *
  39. * @param string $buffer
  40. * @param ConnectionInterface $connection
  41. * @return int
  42. */
  43. public static function input($buffer, ConnectionInterface $connection)
  44. {
  45. if (empty($connection->handshakeStep)) {
  46. Worker::safeEcho("recv data before handshake. Buffer:" . \bin2hex($buffer) . "\n");
  47. return false;
  48. }
  49. // Recv handshake response
  50. if ($connection->handshakeStep === 1) {
  51. return self::dealHandshake($buffer, $connection);
  52. }
  53. $recv_len = \strlen($buffer);
  54. if ($recv_len < 2) {
  55. return 0;
  56. }
  57. // Buffer websocket frame data.
  58. if ($connection->websocketCurrentFrameLength) {
  59. // We need more frame data.
  60. if ($connection->websocketCurrentFrameLength > $recv_len) {
  61. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  62. return 0;
  63. }
  64. } else {
  65. $firstbyte = \ord($buffer[0]);
  66. $secondbyte = \ord($buffer[1]);
  67. $data_len = $secondbyte & 127;
  68. $is_fin_frame = $firstbyte >> 7;
  69. $masked = $secondbyte >> 7;
  70. if ($masked) {
  71. Worker::safeEcho("frame masked so close the connection\n");
  72. $connection->close();
  73. return 0;
  74. }
  75. $opcode = $firstbyte & 0xf;
  76. switch ($opcode) {
  77. case 0x0:
  78. break;
  79. // Blob type.
  80. case 0x1:
  81. break;
  82. // Arraybuffer type.
  83. case 0x2:
  84. break;
  85. // Close package.
  86. case 0x8:
  87. // Try to emit onWebSocketClose callback.
  88. if (isset($connection->onWebSocketClose)) {
  89. try {
  90. \call_user_func($connection->onWebSocketClose, $connection);
  91. } catch (\Exception $e) {
  92. Worker::stopAll(250, $e);
  93. } catch (\Error $e) {
  94. Worker::stopAll(250, $e);
  95. }
  96. } // Close connection.
  97. else {
  98. $connection->close();
  99. }
  100. return 0;
  101. // Ping package.
  102. case 0x9:
  103. break;
  104. // Pong package.
  105. case 0xa:
  106. break;
  107. // Wrong opcode.
  108. default :
  109. Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . $buffer . "\n");
  110. $connection->close();
  111. return 0;
  112. }
  113. // Calculate packet length.
  114. if ($data_len === 126) {
  115. if (\strlen($buffer) < 4) {
  116. return 0;
  117. }
  118. $pack = \unpack('nn/ntotal_len', $buffer);
  119. $current_frame_length = $pack['total_len'] + 4;
  120. } else if ($data_len === 127) {
  121. if (\strlen($buffer) < 10) {
  122. return 0;
  123. }
  124. $arr = \unpack('n/N2c', $buffer);
  125. $current_frame_length = $arr['c1']*4294967296 + $arr['c2'] + 10;
  126. } else {
  127. $current_frame_length = $data_len + 2;
  128. }
  129. $total_package_size = \strlen($connection->websocketDataBuffer) + $current_frame_length;
  130. if ($total_package_size > $connection->maxPackageSize) {
  131. Worker::safeEcho("error package. package_length=$total_package_size\n");
  132. $connection->close();
  133. return 0;
  134. }
  135. if ($is_fin_frame) {
  136. if ($opcode === 0x9) {
  137. if ($recv_len >= $current_frame_length) {
  138. $ping_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
  139. $connection->consumeRecvBuffer($current_frame_length);
  140. $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  141. $connection->websocketType = "\x8a";
  142. if (isset($connection->onWebSocketPing)) {
  143. try {
  144. \call_user_func($connection->onWebSocketPing, $connection, $ping_data);
  145. } catch (\Exception $e) {
  146. Worker::stopAll(250, $e);
  147. } catch (\Error $e) {
  148. Worker::stopAll(250, $e);
  149. }
  150. } else {
  151. $connection->send($ping_data);
  152. }
  153. $connection->websocketType = $tmp_connection_type;
  154. if ($recv_len > $current_frame_length) {
  155. return static::input(\substr($buffer, $current_frame_length), $connection);
  156. }
  157. }
  158. return 0;
  159. } else if ($opcode === 0xa) {
  160. if ($recv_len >= $current_frame_length) {
  161. $pong_data = static::decode(\substr($buffer, 0, $current_frame_length), $connection);
  162. $connection->consumeRecvBuffer($current_frame_length);
  163. $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  164. $connection->websocketType = "\x8a";
  165. // Try to emit onWebSocketPong callback.
  166. if (isset($connection->onWebSocketPong)) {
  167. try {
  168. \call_user_func($connection->onWebSocketPong, $connection, $pong_data);
  169. } catch (\Exception $e) {
  170. Worker::stopAll(250, $e);
  171. } catch (\Error $e) {
  172. Worker::stopAll(250, $e);
  173. }
  174. }
  175. $connection->websocketType = $tmp_connection_type;
  176. if ($recv_len > $current_frame_length) {
  177. return static::input(\substr($buffer, $current_frame_length), $connection);
  178. }
  179. }
  180. return 0;
  181. }
  182. return $current_frame_length;
  183. } else {
  184. $connection->websocketCurrentFrameLength = $current_frame_length;
  185. }
  186. }
  187. // Received just a frame length data.
  188. if ($connection->websocketCurrentFrameLength === $recv_len) {
  189. self::decode($buffer, $connection);
  190. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  191. $connection->websocketCurrentFrameLength = 0;
  192. return 0;
  193. } // The length of the received data is greater than the length of a frame.
  194. elseif ($connection->websocketCurrentFrameLength < $recv_len) {
  195. self::decode(\substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  196. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  197. $current_frame_length = $connection->websocketCurrentFrameLength;
  198. $connection->websocketCurrentFrameLength = 0;
  199. // Continue to read next frame.
  200. return self::input(\substr($buffer, $current_frame_length), $connection);
  201. } // The length of the received data is less than the length of a frame.
  202. else {
  203. return 0;
  204. }
  205. }
  206. /**
  207. * Websocket encode.
  208. *
  209. * @param string $buffer
  210. * @param ConnectionInterface $connection
  211. * @return string
  212. */
  213. public static function encode($payload, ConnectionInterface $connection)
  214. {
  215. if (empty($connection->websocketType)) {
  216. $connection->websocketType = self::BINARY_TYPE_BLOB;
  217. }
  218. $payload = (string)$payload;
  219. if (empty($connection->handshakeStep)) {
  220. static::sendHandshake($connection);
  221. }
  222. $mask = 1;
  223. $mask_key = "\x00\x00\x00\x00";
  224. $pack = '';
  225. $length = $length_flag = \strlen($payload);
  226. if (65535 < $length) {
  227. $pack = \pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
  228. $length_flag = 127;
  229. } else if (125 < $length) {
  230. $pack = \pack('n*', $length);
  231. $length_flag = 126;
  232. }
  233. $head = ($mask << 7) | $length_flag;
  234. $head = $connection->websocketType . \chr($head) . $pack;
  235. $frame = $head . $mask_key;
  236. // append payload to frame:
  237. $mask_key = \str_repeat($mask_key, \floor($length / 4)) . \substr($mask_key, 0, $length % 4);
  238. $frame .= $payload ^ $mask_key;
  239. if ($connection->handshakeStep === 1) {
  240. // If buffer has already full then discard the current package.
  241. if (\strlen($connection->tmpWebsocketData) > $connection->maxSendBufferSize) {
  242. if ($connection->onError) {
  243. try {
  244. \call_user_func($connection->onError, $connection, \WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  245. } catch (\Exception $e) {
  246. Worker::stopAll(250, $e);
  247. } catch (\Error $e) {
  248. Worker::stopAll(250, $e);
  249. }
  250. }
  251. return '';
  252. }
  253. $connection->tmpWebsocketData = $connection->tmpWebsocketData . $frame;
  254. // Check buffer is full.
  255. if ($connection->maxSendBufferSize <= \strlen($connection->tmpWebsocketData)) {
  256. if ($connection->onBufferFull) {
  257. try {
  258. \call_user_func($connection->onBufferFull, $connection);
  259. } catch (\Exception $e) {
  260. Worker::stopAll(250, $e);
  261. } catch (\Error $e) {
  262. Worker::stopAll(250, $e);
  263. }
  264. }
  265. }
  266. return '';
  267. }
  268. return $frame;
  269. }
  270. /**
  271. * Websocket decode.
  272. *
  273. * @param string $buffer
  274. * @param ConnectionInterface $connection
  275. * @return string
  276. */
  277. public static function decode($bytes, ConnectionInterface $connection)
  278. {
  279. $data_length = \ord($bytes[1]);
  280. if ($data_length === 126) {
  281. $decoded_data = \substr($bytes, 4);
  282. } else if ($data_length === 127) {
  283. $decoded_data = \substr($bytes, 10);
  284. } else {
  285. $decoded_data = \substr($bytes, 2);
  286. }
  287. if ($connection->websocketCurrentFrameLength) {
  288. $connection->websocketDataBuffer .= $decoded_data;
  289. return $connection->websocketDataBuffer;
  290. } else {
  291. if ($connection->websocketDataBuffer !== '') {
  292. $decoded_data = $connection->websocketDataBuffer . $decoded_data;
  293. $connection->websocketDataBuffer = '';
  294. }
  295. return $decoded_data;
  296. }
  297. }
  298. /**
  299. * Send websocket handshake data.
  300. *
  301. * @return void
  302. */
  303. public static function onConnect($connection)
  304. {
  305. static::sendHandshake($connection);
  306. }
  307. /**
  308. * Clean
  309. *
  310. * @param TcpConnection $connection
  311. */
  312. public static function onClose($connection)
  313. {
  314. $connection->handshakeStep = null;
  315. $connection->websocketCurrentFrameLength = 0;
  316. $connection->tmpWebsocketData = '';
  317. $connection->websocketDataBuffer = '';
  318. if (!empty($connection->websocketPingTimer)) {
  319. Timer::del($connection->websocketPingTimer);
  320. $connection->websocketPingTimer = null;
  321. }
  322. }
  323. /**
  324. * Send websocket handshake.
  325. *
  326. * @param TcpConnection $connection
  327. * @return void
  328. */
  329. public static function sendHandshake(TcpConnection $connection)
  330. {
  331. if (!empty($connection->handshakeStep)) {
  332. return;
  333. }
  334. // Get Host.
  335. $port = $connection->getRemotePort();
  336. $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
  337. // Handshake header.
  338. $connection->websocketSecKey = \base64_encode(\md5(\mt_rand(), true));
  339. $user_header = isset($connection->headers) ? $connection->headers :
  340. (isset($connection->wsHttpHeader) ? $connection->wsHttpHeader : null);
  341. $user_header_str = '';
  342. if (!empty($user_header)) {
  343. if (\is_array($user_header)){
  344. foreach($user_header as $k=>$v){
  345. $user_header_str .= "$k: $v\r\n";
  346. }
  347. } else {
  348. $user_header_str .= $user_header;
  349. }
  350. $user_header_str = "\r\n".\trim($user_header_str);
  351. }
  352. $header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n".
  353. (!\preg_match("/\nHost:/i", $user_header_str) ? "Host: $host\r\n" : '').
  354. "Connection: Upgrade\r\n".
  355. "Upgrade: websocket\r\n".
  356. (isset($connection->websocketOrigin) ? "Origin: ".$connection->websocketOrigin."\r\n":'').
  357. (isset($connection->WSClientProtocol)?"Sec-WebSocket-Protocol: ".$connection->WSClientProtocol."\r\n":'').
  358. "Sec-WebSocket-Version: 13\r\n".
  359. "Sec-WebSocket-Key: " . $connection->websocketSecKey . $user_header_str . "\r\n\r\n";
  360. $connection->send($header, true);
  361. $connection->handshakeStep = 1;
  362. $connection->websocketCurrentFrameLength = 0;
  363. $connection->websocketDataBuffer = '';
  364. $connection->tmpWebsocketData = '';
  365. }
  366. /**
  367. * Websocket handshake.
  368. *
  369. * @param string $buffer
  370. * @param TcpConnection $connection
  371. * @return int
  372. */
  373. public static function dealHandshake($buffer, TcpConnection $connection)
  374. {
  375. $pos = \strpos($buffer, "\r\n\r\n");
  376. if ($pos) {
  377. //checking Sec-WebSocket-Accept
  378. if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
  379. if ($match[1] !== \base64_encode(\sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
  380. Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
  381. $connection->close();
  382. return 0;
  383. }
  384. } else {
  385. Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . \substr($buffer, 0, $pos) . "\n");
  386. $connection->close();
  387. return 0;
  388. }
  389. // handshake complete
  390. // Get WebSocket subprotocol (if specified by server)
  391. if (\preg_match("/Sec-WebSocket-Protocol: *(.*?)\r\n/i", $buffer, $match)) {
  392. $connection->WSServerProtocol = \trim($match[1]);
  393. }
  394. $connection->handshakeStep = 2;
  395. $handshake_response_length = $pos + 4;
  396. // Try to emit onWebSocketConnect callback.
  397. if (isset($connection->onWebSocketConnect)) {
  398. try {
  399. \call_user_func($connection->onWebSocketConnect, $connection, \substr($buffer, 0, $handshake_response_length));
  400. } catch (\Exception $e) {
  401. Worker::stopAll(250, $e);
  402. } catch (\Error $e) {
  403. Worker::stopAll(250, $e);
  404. }
  405. }
  406. // Headbeat.
  407. if (!empty($connection->websocketPingInterval)) {
  408. $connection->websocketPingTimer = Timer::add($connection->websocketPingInterval, function() use ($connection){
  409. if (false === $connection->send(\pack('H*', '898000000000'), true)) {
  410. Timer::del($connection->websocketPingTimer);
  411. $connection->websocketPingTimer = null;
  412. }
  413. });
  414. }
  415. $connection->consumeRecvBuffer($handshake_response_length);
  416. if (!empty($connection->tmpWebsocketData)) {
  417. $connection->send($connection->tmpWebsocketData, true);
  418. $connection->tmpWebsocketData = '';
  419. }
  420. if (\strlen($buffer) > $handshake_response_length) {
  421. return self::input(\substr($buffer, $handshake_response_length), $connection);
  422. }
  423. }
  424. return 0;
  425. }
  426. public static function WSSetProtocol($connection, $params) {
  427. $connection->WSClientProtocol = $params[0];
  428. }
  429. public static function WSGetServerProtocol($connection) {
  430. return (\property_exists($connection, 'WSServerProtocol') ? $connection->WSServerProtocol : null);
  431. }
  432. }