Ws.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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\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->context->handshakeStep)) {
  46. Worker::safeEcho("recv data before handshake. Buffer:" . \bin2hex($buffer) . "\n");
  47. return false;
  48. }
  49. // Recv handshake response
  50. if ($connection->context->handshakeStep === 1) {
  51. return self::dealHandshake($buffer, $connection);
  52. }
  53. $recvLen = \strlen($buffer);
  54. if ($recvLen < 2) {
  55. return 0;
  56. }
  57. // Buffer websocket frame data.
  58. if ($connection->context->websocketCurrentFrameLength) {
  59. // We need more frame data.
  60. if ($connection->context->websocketCurrentFrameLength > $recvLen) {
  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. $dataLen = $secondbyte & 127;
  68. $isFinFrame = $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. // Blob type.
  79. case 0x1:
  80. // Arraybuffer type.
  81. case 0x2:
  82. // Ping package.
  83. case 0x9:
  84. // Pong package.
  85. case 0xa:
  86. break;
  87. // Close package.
  88. case 0x8:
  89. // Try to emit onWebSocketClose callback.
  90. if (isset($connection->onWebSocketClose)) {
  91. try {
  92. ($connection->onWebSocketClose)($connection);
  93. } catch (\Throwable $e) {
  94. Worker::stopAll(250, $e);
  95. }
  96. } // Close connection.
  97. else {
  98. $connection->close();
  99. }
  100. return 0;
  101. // Wrong opcode.
  102. default :
  103. Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . $buffer . "\n");
  104. $connection->close();
  105. return 0;
  106. }
  107. // Calculate packet length.
  108. if ($dataLen === 126) {
  109. if (\strlen($buffer) < 4) {
  110. return 0;
  111. }
  112. $pack = \unpack('nn/ntotal_len', $buffer);
  113. $currentFrameLength = $pack['total_len'] + 4;
  114. } else if ($dataLen === 127) {
  115. if (\strlen($buffer) < 10) {
  116. return 0;
  117. }
  118. $arr = \unpack('n/N2c', $buffer);
  119. $currentFrameLength = $arr['c1'] * 4294967296 + $arr['c2'] + 10;
  120. } else {
  121. $currentFrameLength = $dataLen + 2;
  122. }
  123. $totalPackageSize = \strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
  124. if ($totalPackageSize > $connection->maxPackageSize) {
  125. Worker::safeEcho("error package. package_length=$totalPackageSize\n");
  126. $connection->close();
  127. return 0;
  128. }
  129. if ($isFinFrame) {
  130. if ($opcode === 0x9) {
  131. if ($recvLen >= $currentFrameLength) {
  132. $pingData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
  133. $connection->consumeRecvBuffer($currentFrameLength);
  134. $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  135. $connection->websocketType = "\x8a";
  136. if (isset($connection->onWebSocketPing)) {
  137. try {
  138. ($connection->onWebSocketPing)($connection, $pingData);
  139. } catch (\Throwable $e) {
  140. Worker::stopAll(250, $e);
  141. }
  142. } else {
  143. $connection->send($pingData);
  144. }
  145. $connection->websocketType = $tmpConnectionType;
  146. if ($recvLen > $currentFrameLength) {
  147. return static::input(\substr($buffer, $currentFrameLength), $connection);
  148. }
  149. }
  150. return 0;
  151. } else if ($opcode === 0xa) {
  152. if ($recvLen >= $currentFrameLength) {
  153. $pongData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
  154. $connection->consumeRecvBuffer($currentFrameLength);
  155. $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  156. $connection->websocketType = "\x8a";
  157. // Try to emit onWebSocketPong callback.
  158. if (isset($connection->onWebSocketPong)) {
  159. try {
  160. ($connection->onWebSocketPong)($connection, $pongData);
  161. } catch (\Throwable $e) {
  162. Worker::stopAll(250, $e);
  163. }
  164. }
  165. $connection->websocketType = $tmpConnectionType;
  166. if ($recvLen > $currentFrameLength) {
  167. return static::input(\substr($buffer, $currentFrameLength), $connection);
  168. }
  169. }
  170. return 0;
  171. }
  172. return $currentFrameLength;
  173. } else {
  174. $connection->context->websocketCurrentFrameLength = $currentFrameLength;
  175. }
  176. }
  177. // Received just a frame length data.
  178. if ($connection->context->websocketCurrentFrameLength === $recvLen) {
  179. self::decode($buffer, $connection);
  180. $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
  181. $connection->context->websocketCurrentFrameLength = 0;
  182. return 0;
  183. } // The length of the received data is greater than the length of a frame.
  184. elseif ($connection->context->websocketCurrentFrameLength < $recvLen) {
  185. self::decode(\substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
  186. $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
  187. $currentFrameLength = $connection->context->websocketCurrentFrameLength;
  188. $connection->context->websocketCurrentFrameLength = 0;
  189. // Continue to read next frame.
  190. return self::input(\substr($buffer, $currentFrameLength), $connection);
  191. } // The length of the received data is less than the length of a frame.
  192. else {
  193. return 0;
  194. }
  195. }
  196. /**
  197. * Websocket encode.
  198. *
  199. * @param string $buffer
  200. * @param ConnectionInterface $connection
  201. * @return string
  202. */
  203. public static function encode($payload, ConnectionInterface $connection)
  204. {
  205. if (empty($connection->websocketType)) {
  206. $connection->websocketType = self::BINARY_TYPE_BLOB;
  207. }
  208. $payload = (string)$payload;
  209. if (empty($connection->context->handshakeStep)) {
  210. static::sendHandshake($connection);
  211. }
  212. $mask = 1;
  213. $maskKey = "\x00\x00\x00\x00";
  214. $pack = '';
  215. $length = $lengthFlag = \strlen($payload);
  216. if (65535 < $length) {
  217. $pack = \pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
  218. $lengthFlag = 127;
  219. } else if (125 < $length) {
  220. $pack = \pack('n*', $length);
  221. $lengthFlag = 126;
  222. }
  223. $head = ($mask << 7) | $lengthFlag;
  224. $head = $connection->websocketType . \chr($head) . $pack;
  225. $frame = $head . $maskKey;
  226. // append payload to frame:
  227. $maskKey = \str_repeat($maskKey, \floor($length / 4)) . \substr($maskKey, 0, $length % 4);
  228. $frame .= $payload ^ $maskKey;
  229. if ($connection->context->handshakeStep === 1) {
  230. // If buffer has already full then discard the current package.
  231. if (\strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
  232. if ($connection->onError) {
  233. try {
  234. ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
  235. } catch (\Throwable $e) {
  236. Worker::stopAll(250, $e);
  237. }
  238. }
  239. return '';
  240. }
  241. $connection->context->tmpWebsocketData = $connection->context->tmpWebsocketData . $frame;
  242. // Check buffer is full.
  243. if ($connection->maxSendBufferSize <= \strlen($connection->context->tmpWebsocketData)) {
  244. if ($connection->onBufferFull) {
  245. try {
  246. ($connection->onBufferFull)($connection);
  247. } catch (\Throwable $e) {
  248. Worker::stopAll(250, $e);
  249. }
  250. }
  251. }
  252. return '';
  253. }
  254. return $frame;
  255. }
  256. /**
  257. * Websocket decode.
  258. *
  259. * @param string $buffer
  260. * @param ConnectionInterface $connection
  261. * @return string
  262. */
  263. public static function decode($bytes, ConnectionInterface $connection)
  264. {
  265. $dataLength = \ord($bytes[1]);
  266. if ($dataLength === 126) {
  267. $decodedData = \substr($bytes, 4);
  268. } else if ($dataLength === 127) {
  269. $decodedData = \substr($bytes, 10);
  270. } else {
  271. $decodedData = \substr($bytes, 2);
  272. }
  273. if ($connection->context->websocketCurrentFrameLength) {
  274. $connection->context->websocketDataBuffer .= $decodedData;
  275. return $connection->context->websocketDataBuffer;
  276. } else {
  277. if ($connection->context->websocketDataBuffer !== '') {
  278. $decodedData = $connection->context->websocketDataBuffer . $decodedData;
  279. $connection->context->websocketDataBuffer = '';
  280. }
  281. return $decodedData;
  282. }
  283. }
  284. /**
  285. * Send websocket handshake data.
  286. *
  287. * @return void
  288. */
  289. public static function onConnect($connection)
  290. {
  291. static::sendHandshake($connection);
  292. }
  293. /**
  294. * Clean
  295. *
  296. * @param TcpConnection $connection
  297. */
  298. public static function onClose($connection)
  299. {
  300. $connection->context->handshakeStep = null;
  301. $connection->context->websocketCurrentFrameLength = 0;
  302. $connection->context->tmpWebsocketData = '';
  303. $connection->context->websocketDataBuffer = '';
  304. if (!empty($connection->context->websocketPingTimer)) {
  305. Timer::del($connection->context->websocketPingTimer);
  306. $connection->context->websocketPingTimer = null;
  307. }
  308. }
  309. /**
  310. * Send websocket handshake.
  311. *
  312. * @param TcpConnection $connection
  313. * @return void
  314. */
  315. public static function sendHandshake(ConnectionInterface $connection)
  316. {
  317. if (!empty($connection->context->handshakeStep)) {
  318. return;
  319. }
  320. // Get Host.
  321. $port = $connection->getRemotePort();
  322. $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
  323. // Handshake header.
  324. $connection->context->websocketSecKey = \base64_encode(random_bytes(16));
  325. $userHeader = $connection->headers ?? null;
  326. $userHeaderStr = '';
  327. if (!empty($userHeader)) {
  328. if (\is_array($userHeader)) {
  329. foreach ($userHeader as $k => $v) {
  330. $userHeaderStr .= "$k: $v\r\n";
  331. }
  332. } else {
  333. $userHeaderStr .= $userHeader;
  334. }
  335. $userHeaderStr = "\r\n" . \trim($userHeaderStr);
  336. }
  337. $header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n" .
  338. (!\preg_match("/\nHost:/i", $userHeaderStr) ? "Host: $host\r\n" : '') .
  339. "Connection: Upgrade\r\n" .
  340. "Upgrade: websocket\r\n" .
  341. (isset($connection->websocketOrigin) ? "Origin: " . $connection->websocketOrigin . "\r\n" : '') .
  342. (isset($connection->websocketClientProtocol) ? "Sec-WebSocket-Protocol: " . $connection->websocketClientProtocol . "\r\n" : '') .
  343. "Sec-WebSocket-Version: 13\r\n" .
  344. "Sec-WebSocket-Key: " . $connection->context->websocketSecKey . $userHeaderStr . "\r\n\r\n";
  345. $connection->send($header, true);
  346. $connection->context->handshakeStep = 1;
  347. $connection->context->websocketCurrentFrameLength = 0;
  348. $connection->context->websocketDataBuffer = '';
  349. $connection->context->tmpWebsocketData = '';
  350. }
  351. /**
  352. * Websocket handshake.
  353. *
  354. * @param string $buffer
  355. * @param TcpConnection $connection
  356. * @return int
  357. */
  358. public static function dealHandshake($buffer, ConnectionInterface $connection)
  359. {
  360. $pos = \strpos($buffer, "\r\n\r\n");
  361. if ($pos) {
  362. //checking Sec-WebSocket-Accept
  363. if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
  364. if ($match[1] !== \base64_encode(\sha1($connection->context->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
  365. Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
  366. $connection->close();
  367. return 0;
  368. }
  369. } else {
  370. Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . \substr($buffer, 0, $pos) . "\n");
  371. $connection->close();
  372. return 0;
  373. }
  374. // handshake complete
  375. // Get WebSocket subprotocol (if specified by server)
  376. if (\preg_match("/Sec-WebSocket-Protocol: *(.*?)\r\n/i", $buffer, $match)) {
  377. $connection->websocketServerProtocol = \trim($match[1]);
  378. }
  379. $connection->context->handshakeStep = 2;
  380. $handshakeResponseLength = $pos + 4;
  381. // Try to emit onWebSocketConnect callback.
  382. if (isset($connection->onWebSocketConnect)) {
  383. try {
  384. ($connection->onWebSocketConnect)($connection, \substr($buffer, 0, $handshakeResponseLength));
  385. } catch (\Throwable $e) {
  386. Worker::stopAll(250, $e);
  387. }
  388. }
  389. // Headbeat.
  390. if (!empty($connection->websocketPingInterval)) {
  391. $connection->context->websocketPingTimer = Timer::add($connection->websocketPingInterval, function () use ($connection) {
  392. if (false === $connection->send(\pack('H*', '898000000000'), true)) {
  393. Timer::del($connection->context->websocketPingTimer);
  394. $connection->context->websocketPingTimer = null;
  395. }
  396. });
  397. }
  398. $connection->consumeRecvBuffer($handshakeResponseLength);
  399. if (!empty($connection->context->tmpWebsocketData)) {
  400. $connection->send($connection->context->tmpWebsocketData, true);
  401. $connection->context->tmpWebsocketData = '';
  402. }
  403. if (\strlen($buffer) > $handshakeResponseLength) {
  404. return self::input(\substr($buffer, $handshakeResponseLength), $connection);
  405. }
  406. }
  407. return 0;
  408. }
  409. }