Websocket.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. declare(strict_types=1);
  15. namespace Workerman\Protocols;
  16. use Exception;
  17. use Throwable;
  18. use Workerman\Connection\ConnectionInterface;
  19. use Workerman\Connection\TcpConnection;
  20. use Workerman\Protocols\Http\Request;
  21. use Workerman\Worker;
  22. use function base64_encode;
  23. use function chr;
  24. use function floor;
  25. use function gettype;
  26. use function is_scalar;
  27. use function ord;
  28. use function pack;
  29. use function preg_match;
  30. use function sha1;
  31. use function str_repeat;
  32. use function stripos;
  33. use function strlen;
  34. use function strpos;
  35. use function substr;
  36. use function unpack;
  37. /**
  38. * WebSocket protocol.
  39. */
  40. class Websocket
  41. {
  42. /**
  43. * Websocket blob type.
  44. *
  45. * @var string
  46. */
  47. public const BINARY_TYPE_BLOB = "\x81";
  48. /**
  49. * Websocket blob type.
  50. *
  51. * @var string
  52. */
  53. const BINARY_TYPE_BLOB_DEFLATE = "\xc1";
  54. /**
  55. * Websocket arraybuffer type.
  56. *
  57. * @var string
  58. */
  59. public const BINARY_TYPE_ARRAYBUFFER = "\x82";
  60. /**
  61. * Websocket arraybuffer type.
  62. *
  63. * @var string
  64. */
  65. const BINARY_TYPE_ARRAYBUFFER_DEFLATE = "\xc2";
  66. /**
  67. * Check the integrity of the package.
  68. *
  69. * @param string $buffer
  70. * @param TcpConnection $connection
  71. * @return int
  72. * @throws Throwable
  73. */
  74. public static function input(string $buffer, TcpConnection $connection): int
  75. {
  76. // Receive length.
  77. $recvLen = strlen($buffer);
  78. // We need more data.
  79. if ($recvLen < 6) {
  80. return 0;
  81. }
  82. // Has not yet completed the handshake.
  83. if (empty($connection->context->websocketHandshake)) {
  84. return static::dealHandshake($buffer, $connection);
  85. }
  86. // Buffer websocket frame data.
  87. if ($connection->context->websocketCurrentFrameLength) {
  88. // We need more frame data.
  89. if ($connection->context->websocketCurrentFrameLength > $recvLen) {
  90. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  91. return 0;
  92. }
  93. } else {
  94. $firstByte = ord($buffer[0]);
  95. $secondByte = ord($buffer[1]);
  96. $dataLen = $secondByte & 127;
  97. $isFinFrame = $firstByte >> 7;
  98. $masked = $secondByte >> 7;
  99. if (!$masked) {
  100. Worker::safeEcho("frame not masked so close the connection\n");
  101. $connection->close();
  102. return 0;
  103. }
  104. $opcode = $firstByte & 0xf;
  105. switch ($opcode) {
  106. case 0x0:
  107. // Blob type.
  108. case 0x1:
  109. // Arraybuffer type.
  110. case 0x2:
  111. // Ping package.
  112. case 0x9:
  113. // Pong package.
  114. case 0xa:
  115. break;
  116. // Close package.
  117. case 0x8:
  118. // Try to emit onWebSocketClose callback.
  119. $closeCb = $connection->onWebSocketClose ?? $connection->worker->onWebSocketClose ?? false;
  120. if ($closeCb) {
  121. try {
  122. $closeCb($connection);
  123. } catch (Throwable $e) {
  124. Worker::stopAll(250, $e);
  125. }
  126. } // Close connection.
  127. else {
  128. $connection->close("\x88\x02\x03\xe8", true);
  129. }
  130. return 0;
  131. // Wrong opcode.
  132. default :
  133. Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . bin2hex($buffer) . "\n");
  134. $connection->close();
  135. return 0;
  136. }
  137. // Calculate packet length.
  138. $headLen = 6;
  139. if ($dataLen === 126) {
  140. $headLen = 8;
  141. if ($headLen > $recvLen) {
  142. return 0;
  143. }
  144. $pack = unpack('nn/ntotal_len', $buffer);
  145. $dataLen = $pack['total_len'];
  146. } else {
  147. if ($dataLen === 127) {
  148. $headLen = 14;
  149. if ($headLen > $recvLen) {
  150. return 0;
  151. }
  152. $arr = unpack('n/N2c', $buffer);
  153. $dataLen = $arr['c1'] * 4294967296 + $arr['c2'];
  154. }
  155. }
  156. $currentFrameLength = $headLen + $dataLen;
  157. $totalPackageSize = strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
  158. if ($totalPackageSize > $connection->maxPackageSize) {
  159. Worker::safeEcho("error package. package_length=$totalPackageSize\n");
  160. $connection->close();
  161. return 0;
  162. }
  163. if ($isFinFrame) {
  164. if ($opcode === 0x9) {
  165. if ($recvLen >= $currentFrameLength) {
  166. $pingData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
  167. $connection->consumeRecvBuffer($currentFrameLength);
  168. $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
  169. $connection->websocketType = "\x8a";
  170. $pingCb = $connection->onWebSocketPing ?? $connection->worker->onWebSocketPing ?? false;
  171. if ($pingCb) {
  172. try {
  173. $pingCb($connection, $pingData);
  174. } catch (Throwable $e) {
  175. Worker::stopAll(250, $e);
  176. }
  177. } else {
  178. $connection->send($pingData);
  179. }
  180. $connection->websocketType = $tmpConnectionType;
  181. if ($recvLen > $currentFrameLength) {
  182. return static::input(substr($buffer, $currentFrameLength), $connection);
  183. }
  184. }
  185. return 0;
  186. }
  187. if ($opcode === 0xa) {
  188. if ($recvLen >= $currentFrameLength) {
  189. $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
  190. $connection->consumeRecvBuffer($currentFrameLength);
  191. $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
  192. $connection->websocketType = "\x8a";
  193. // Try to emit onWebSocketPong callback.
  194. $pongCb = $connection->onWebSocketPong ?? $connection->worker->onWebSocketPong ?? false;
  195. if ($pongCb) {
  196. try {
  197. $pongCb($connection, $pongData);
  198. } catch (Throwable $e) {
  199. Worker::stopAll(250, $e);
  200. }
  201. }
  202. $connection->websocketType = $tmpConnectionType;
  203. if ($recvLen > $currentFrameLength) {
  204. return static::input(substr($buffer, $currentFrameLength), $connection);
  205. }
  206. }
  207. return 0;
  208. }
  209. return $currentFrameLength;
  210. }
  211. $connection->context->websocketCurrentFrameLength = $currentFrameLength;
  212. }
  213. // Received just a frame length data.
  214. if ($connection->context->websocketCurrentFrameLength === $recvLen) {
  215. static::decode($buffer, $connection);
  216. $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
  217. $connection->context->websocketCurrentFrameLength = 0;
  218. return 0;
  219. }
  220. // The length of the received data is greater than the length of a frame.
  221. if ($connection->context->websocketCurrentFrameLength < $recvLen) {
  222. static::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
  223. $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
  224. $currentFrameLength = $connection->context->websocketCurrentFrameLength;
  225. $connection->context->websocketCurrentFrameLength = 0;
  226. // Continue to read next frame.
  227. return static::input(substr($buffer, $currentFrameLength), $connection);
  228. }
  229. // The length of the received data is less than the length of a frame.
  230. return 0;
  231. }
  232. /**
  233. * Websocket encode.
  234. *
  235. * @param mixed $buffer
  236. * @param TcpConnection $connection
  237. * @return string
  238. * @throws Throwable
  239. */
  240. public static function encode(mixed $buffer, TcpConnection $connection): string
  241. {
  242. if (!is_scalar($buffer)) {
  243. throw new Exception("You can't send(" . gettype($buffer) . ") to client, you need to convert it to string. ");
  244. }
  245. if (empty($connection->websocketType)) {
  246. $connection->websocketType = static::BINARY_TYPE_BLOB;
  247. }
  248. if (\ord($connection->websocketType) & 64) {
  249. $buffer = static::deflate($connection, $buffer);
  250. }
  251. $firstByte = $connection->websocketType;
  252. $len = strlen($buffer);
  253. if ($len <= 125) {
  254. $encodeBuffer = $firstByte . chr($len) . $buffer;
  255. } else {
  256. if ($len <= 65535) {
  257. $encodeBuffer = $firstByte . chr(126) . pack("n", $len) . $buffer;
  258. } else {
  259. $encodeBuffer = $firstByte . chr(127) . pack("xxxxN", $len) . $buffer;
  260. }
  261. }
  262. // Handshake not completed so temporary buffer websocket data waiting for send.
  263. if (empty($connection->context->websocketHandshake)) {
  264. if (empty($connection->context->tmpWebsocketData)) {
  265. $connection->context->tmpWebsocketData = '';
  266. }
  267. // If buffer has already full then discard the current package.
  268. if (strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
  269. if ($connection->onError) {
  270. try {
  271. ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
  272. } catch (Throwable $e) {
  273. Worker::stopAll(250, $e);
  274. }
  275. }
  276. return '';
  277. }
  278. $connection->context->tmpWebsocketData .= $encodeBuffer;
  279. // Check buffer is full.
  280. if ($connection->onBufferFull && $connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
  281. try {
  282. ($connection->onBufferFull)($connection);
  283. } catch (Throwable $e) {
  284. Worker::stopAll(250, $e);
  285. }
  286. }
  287. // Return empty string.
  288. return '';
  289. }
  290. return $encodeBuffer;
  291. }
  292. /**
  293. * Websocket decode.
  294. *
  295. * @param string $buffer
  296. * @param TcpConnection $connection
  297. * @return string
  298. */
  299. public static function decode(string $buffer, TcpConnection $connection): string
  300. {
  301. $firstByte = ord($buffer[0]);
  302. $secondByte = ord($buffer[1]);
  303. $len = $secondByte & 127;
  304. $isFinFrame = (bool)($firstByte >> 7);
  305. $rsv1 = 64 === ($firstByte & 64);
  306. if ($len === 126) {
  307. $masks = substr($buffer, 4, 4);
  308. $data = substr($buffer, 8);
  309. } else {
  310. if ($len === 127) {
  311. $masks = substr($buffer, 10, 4);
  312. $data = substr($buffer, 14);
  313. } else {
  314. $masks = substr($buffer, 2, 4);
  315. $data = substr($buffer, 6);
  316. }
  317. }
  318. $dataLength = strlen($data);
  319. $masks = str_repeat($masks, (int)floor($dataLength / 4)) . substr($masks, 0, $dataLength % 4);
  320. $decoded = $data ^ $masks;
  321. if ($connection->context->websocketCurrentFrameLength) {
  322. $connection->context->websocketDataBuffer .= $decoded;
  323. if ($rsv1) {
  324. return static::inflate($connection, $connection->context->websocketDataBuffer, $isFinFrame);
  325. }
  326. return $connection->context->websocketDataBuffer;
  327. }
  328. if ($connection->context->websocketDataBuffer !== '') {
  329. $decoded = $connection->context->websocketDataBuffer . $decoded;
  330. $connection->context->websocketDataBuffer = '';
  331. }
  332. if ($rsv1) {
  333. return static::inflate($connection, $decoded, $isFinFrame);
  334. }
  335. return $decoded;
  336. }
  337. /**
  338. * Inflate.
  339. *
  340. * @param TcpConnection $connection
  341. * @param string $buffer
  342. * @param bool $isFinFrame
  343. * @return false|string
  344. */
  345. protected static function inflate(TcpConnection $connection, string $buffer, bool $isFinFrame)
  346. {
  347. if (!isset($connection->context->inflator)) {
  348. $connection->context->inflator = \inflate_init(
  349. \ZLIB_ENCODING_RAW,
  350. [
  351. 'level' => -1,
  352. 'memory' => 8,
  353. 'window' => 15,
  354. 'strategy' => \ZLIB_DEFAULT_STRATEGY
  355. ]
  356. );
  357. }
  358. if ($isFinFrame) {
  359. $buffer .= "\x00\x00\xff\xff";
  360. }
  361. return \inflate_add($connection->context->inflator, $buffer);
  362. }
  363. /**
  364. * Deflate.
  365. *
  366. * @param TcpConnection $connection
  367. * @param string $buffer
  368. * @return false|string
  369. */
  370. protected static function deflate(TcpConnection $connection, string $buffer)
  371. {
  372. if (!isset($connection->context->deflator)) {
  373. $connection->context->deflator = \deflate_init(
  374. \ZLIB_ENCODING_RAW,
  375. [
  376. 'level' => -1,
  377. 'memory' => 8,
  378. 'window' => 15,
  379. 'strategy' => \ZLIB_DEFAULT_STRATEGY
  380. ]
  381. );
  382. }
  383. return \substr(\deflate_add($connection->context->deflator, $buffer), 0, -4);
  384. }
  385. /**
  386. * Websocket handshake.
  387. *
  388. * @param string $buffer
  389. * @param TcpConnection $connection
  390. * @return int
  391. * @throws Throwable
  392. */
  393. public static function dealHandshake(string $buffer, TcpConnection $connection): int
  394. {
  395. // HTTP protocol.
  396. if (str_starts_with($buffer, 'GET')) {
  397. // Find \r\n\r\n.
  398. $headerEndPos = strpos($buffer, "\r\n\r\n");
  399. if (!$headerEndPos) {
  400. return 0;
  401. }
  402. $headerLength = $headerEndPos + 4;
  403. // Get Sec-WebSocket-Key.
  404. if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
  405. $SecWebSocketKey = $match[1];
  406. } else {
  407. $connection->close(
  408. "HTTP/1.0 400 Bad Request\r\nServer: workerman\r\n\r\n<div style=\"text-align:center\"><h1>WebSocket</h1><hr>workerman</div>", true);
  409. return 0;
  410. }
  411. // Calculation websocket key.
  412. $newKey = base64_encode(sha1($SecWebSocketKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
  413. // Handshake response data.
  414. $handshakeMessage = "HTTP/1.1 101 Switching Protocol\r\n"
  415. . "Upgrade: websocket\r\n"
  416. . "Sec-WebSocket-Version: 13\r\n"
  417. . "Connection: Upgrade\r\n"
  418. . "Sec-WebSocket-Accept: " . $newKey . "\r\n";
  419. // Websocket data buffer.
  420. $connection->context->websocketDataBuffer = '';
  421. // Current websocket frame length.
  422. $connection->context->websocketCurrentFrameLength = 0;
  423. // Current websocket frame data.
  424. $connection->context->websocketCurrentFrameBuffer = '';
  425. // Consume handshake data.
  426. $connection->consumeRecvBuffer($headerLength);
  427. // Try to emit onWebSocketConnect callback.
  428. $onWebsocketConnect = $connection->onWebSocketConnect ?? $connection->worker->onWebSocketConnect ?? false;
  429. if ($onWebsocketConnect) {
  430. try {
  431. $onWebsocketConnect($connection, new Request($buffer));
  432. } catch (Throwable $e) {
  433. Worker::stopAll(250, $e);
  434. }
  435. }
  436. // blob or arraybuffer
  437. if (empty($connection->websocketType)) {
  438. $connection->websocketType = static::BINARY_TYPE_BLOB;
  439. }
  440. $hasServerHeader = false;
  441. if ($connection->headers) {
  442. foreach ($connection->headers as $header) {
  443. if (stripos($header, 'Server:') === 0) {
  444. $hasServerHeader = true;
  445. }
  446. $handshakeMessage .= "$header\r\n";
  447. }
  448. }
  449. if (!$hasServerHeader) {
  450. $handshakeMessage .= "Server: workerman\r\n";
  451. }
  452. $handshakeMessage .= "\r\n";
  453. // Send handshake response.
  454. $connection->send($handshakeMessage, true);
  455. // Mark handshake complete.
  456. $connection->context->websocketHandshake = true;
  457. // There are data waiting to be sent.
  458. if (!empty($connection->context->tmpWebsocketData)) {
  459. $connection->send($connection->context->tmpWebsocketData, true);
  460. $connection->context->tmpWebsocketData = '';
  461. }
  462. if (strlen($buffer) > $headerLength) {
  463. return static::input(substr($buffer, $headerLength), $connection);
  464. }
  465. return 0;
  466. }
  467. // Bad websocket handshake request.
  468. $connection->close(
  469. "HTTP/1.0 400 Bad Request\r\nServer: workerman\r\n\r\n<div style=\"text-align:center\"><h1>400 Bad Request</h1><hr>workerman</div>", true);
  470. return 0;
  471. }
  472. }