Ws.php 18 KB

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