Websocket.php 16 KB

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