Ws.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. /**
  19. * Websocket protocol for client.
  20. */
  21. class Ws
  22. {
  23. /**
  24. * Websocket blob type.
  25. *
  26. * @var string
  27. */
  28. const BINARY_TYPE_BLOB = "\x81";
  29. /**
  30. * Websocket arraybuffer type.
  31. *
  32. * @var string
  33. */
  34. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  35. /**
  36. * Check the integrity of the package.
  37. *
  38. * @param string $buffer
  39. * @param ConnectionInterface $connection
  40. * @return int
  41. */
  42. public static function input($buffer, $connection)
  43. {
  44. if (empty($connection->handshakeStep)) {
  45. Worker::safeEcho("recv data before handshake. Buffer:" . bin2hex($buffer) . "\n");
  46. return false;
  47. }
  48. // Recv handshake response
  49. if ($connection->handshakeStep === 1) {
  50. return self::dealHandshake($buffer, $connection);
  51. }
  52. $recv_len = strlen($buffer);
  53. if ($recv_len < 2) {
  54. return 0;
  55. }
  56. // Buffer websocket frame data.
  57. if ($connection->websocketCurrentFrameLength) {
  58. // We need more frame data.
  59. if ($connection->websocketCurrentFrameLength > $recv_len) {
  60. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  61. return 0;
  62. }
  63. } else {
  64. $firstbyte = ord($buffer[0]);
  65. $secondbyte = ord($buffer[1]);
  66. $data_len = $secondbyte & 127;
  67. $is_fin_frame = $firstbyte >> 7;
  68. $masked = $secondbyte >> 7;
  69. if ($masked) {
  70. Worker::safeEcho("frame masked so close the connection\n");
  71. $connection->close();
  72. return 0;
  73. }
  74. $opcode = $firstbyte & 0xf;
  75. switch ($opcode) {
  76. case 0x0:
  77. break;
  78. // Blob type.
  79. case 0x1:
  80. break;
  81. // Arraybuffer type.
  82. case 0x2:
  83. break;
  84. // Close package.
  85. case 0x8:
  86. // Try to emit onWebSocketClose callback.
  87. if (isset($connection->onWebSocketClose)) {
  88. try {
  89. call_user_func($connection->onWebSocketClose, $connection);
  90. } catch (\Exception $e) {
  91. Worker::log($e);
  92. exit(250);
  93. } catch (\Error $e) {
  94. Worker::log($e);
  95. exit(250);
  96. }
  97. } // Close connection.
  98. else {
  99. $connection->close();
  100. }
  101. return 0;
  102. // Ping package.
  103. case 0x9:
  104. break;
  105. // Pong package.
  106. case 0xa:
  107. break;
  108. // Wrong opcode.
  109. default :
  110. Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . $buffer . "\n");
  111. $connection->close();
  112. return 0;
  113. }
  114. // Calculate packet length.
  115. if ($data_len === 126) {
  116. if (strlen($buffer) < 4) {
  117. return 0;
  118. }
  119. $pack = unpack('nn/ntotal_len', $buffer);
  120. $current_frame_length = $pack['total_len'] + 4;
  121. } else if ($data_len === 127) {
  122. if (strlen($buffer) < 10) {
  123. return 0;
  124. }
  125. $arr = unpack('n/N2c', $buffer);
  126. $current_frame_length = $arr['c1']*4294967296 + $arr['c2'] + 10;
  127. } else {
  128. $current_frame_length = $data_len + 2;
  129. }
  130. $total_package_size = strlen($connection->websocketDataBuffer) + $current_frame_length;
  131. if ($total_package_size > $connection::$maxPackageSize) {
  132. Worker::safeEcho("error package. package_length=$total_package_size\n");
  133. $connection->close();
  134. return 0;
  135. }
  136. if ($is_fin_frame) {
  137. if ($opcode === 0x9) {
  138. if ($recv_len >= $current_frame_length) {
  139. $ping_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
  140. $connection->consumeRecvBuffer($current_frame_length);
  141. $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  142. $connection->websocketType = "\x8a";
  143. if (isset($connection->onWebSocketPing)) {
  144. try {
  145. call_user_func($connection->onWebSocketPing, $connection, $ping_data);
  146. } catch (\Exception $e) {
  147. Worker::log($e);
  148. exit(250);
  149. } catch (\Error $e) {
  150. Worker::log($e);
  151. exit(250);
  152. }
  153. } else {
  154. $connection->send($ping_data);
  155. }
  156. $connection->websocketType = $tmp_connection_type;
  157. if ($recv_len > $current_frame_length) {
  158. return static::input(substr($buffer, $current_frame_length), $connection);
  159. }
  160. }
  161. return 0;
  162. } else if ($opcode === 0xa) {
  163. if ($recv_len >= $current_frame_length) {
  164. $pong_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
  165. $connection->consumeRecvBuffer($current_frame_length);
  166. $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
  167. $connection->websocketType = "\x8a";
  168. // Try to emit onWebSocketPong callback.
  169. if (isset($connection->onWebSocketPong)) {
  170. try {
  171. call_user_func($connection->onWebSocketPong, $connection, $pong_data);
  172. } catch (\Exception $e) {
  173. Worker::log($e);
  174. exit(250);
  175. } catch (\Error $e) {
  176. Worker::log($e);
  177. exit(250);
  178. }
  179. }
  180. $connection->websocketType = $tmp_connection_type;
  181. if ($recv_len > $current_frame_length) {
  182. return static::input(substr($buffer, $current_frame_length), $connection);
  183. }
  184. }
  185. return 0;
  186. }
  187. return $current_frame_length;
  188. } else {
  189. $connection->websocketCurrentFrameLength = $current_frame_length;
  190. }
  191. }
  192. // Received just a frame length data.
  193. if ($connection->websocketCurrentFrameLength === $recv_len) {
  194. self::decode($buffer, $connection);
  195. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  196. $connection->websocketCurrentFrameLength = 0;
  197. return 0;
  198. } // The length of the received data is greater than the length of a frame.
  199. elseif ($connection->websocketCurrentFrameLength < $recv_len) {
  200. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  201. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  202. $current_frame_length = $connection->websocketCurrentFrameLength;
  203. $connection->websocketCurrentFrameLength = 0;
  204. // Continue to read next frame.
  205. return self::input(substr($buffer, $current_frame_length), $connection);
  206. } // The length of the received data is less than the length of a frame.
  207. else {
  208. return 0;
  209. }
  210. }
  211. /**
  212. * Websocket encode.
  213. *
  214. * @param string $buffer
  215. * @param ConnectionInterface $connection
  216. * @return string
  217. */
  218. public static function encode($payload, $connection)
  219. {
  220. if (empty($connection->websocketType)) {
  221. $connection->websocketType = self::BINARY_TYPE_BLOB;
  222. }
  223. $payload = (string)$payload;
  224. if (empty($connection->handshakeStep)) {
  225. self::sendHandshake($connection);
  226. }
  227. $mask = 1;
  228. $mask_key = "\x00\x00\x00\x00";
  229. $pack = '';
  230. $length = $length_flag = strlen($payload);
  231. if (65535 < $length) {
  232. $pack = pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
  233. $length_flag = 127;
  234. } else if (125 < $length) {
  235. $pack = pack('n*', $length);
  236. $length_flag = 126;
  237. }
  238. $head = ($mask << 7) | $length_flag;
  239. $head = $connection->websocketType . chr($head) . $pack;
  240. $frame = $head . $mask_key;
  241. // append payload to frame:
  242. for ($i = 0; $i < $length; $i++) {
  243. $frame .= $payload[$i] ^ $mask_key[$i % 4];
  244. }
  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, $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. self::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 \Workerman\Connection\TcpConnection $connection
  337. * @return void
  338. */
  339. public static function sendHandshake($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. $userHeader = '';
  350. if (!empty($connection->wsHttpHeader)) {
  351. if (is_array($connection->wsHttpHeader)){
  352. foreach($connection->wsHttpHeader as $k=>$v){
  353. $userHeader .= "$k: $v\r\n";
  354. }
  355. }else{
  356. $userHeader .= $connection->wsHttpHeader;
  357. }
  358. $userHeader = "\r\n".trim($userHeader);
  359. }
  360. $header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n".
  361. "Host: $host\r\n".
  362. "Connection: Upgrade\r\n".
  363. "Upgrade: websocket\r\n".
  364. "Origin: ". (isset($connection->websocketOrigin) ? $connection->websocketOrigin : '*') ."\r\n".
  365. (isset($connection->WSClientProtocol)?"Sec-WebSocket-Protocol: ".$connection->WSClientProtocol."\r\n":'').
  366. "Sec-WebSocket-Version: 13\r\n".
  367. "Sec-WebSocket-Key: " . $connection->websocketSecKey . $userHeader . "\r\n\r\n";
  368. $connection->send($header, true);
  369. $connection->handshakeStep = 1;
  370. $connection->websocketCurrentFrameLength = 0;
  371. $connection->websocketDataBuffer = '';
  372. $connection->tmpWebsocketData = '';
  373. }
  374. /**
  375. * Websocket handshake.
  376. *
  377. * @param string $buffer
  378. * @param \Workerman\Connection\TcpConnection $connection
  379. * @return int
  380. */
  381. public static function dealHandshake($buffer, $connection)
  382. {
  383. $pos = strpos($buffer, "\r\n\r\n");
  384. if ($pos) {
  385. //checking Sec-WebSocket-Accept
  386. if (preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
  387. if ($match[1] !== base64_encode(sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
  388. Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . substr($buffer, 0, $pos) . "\n");
  389. $connection->close();
  390. return 0;
  391. }
  392. } else {
  393. Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . substr($buffer, 0, $pos) . "\n");
  394. $connection->close();
  395. return 0;
  396. }
  397. // handshake complete
  398. // Get WebSocket subprotocol (if specified by server)
  399. if (preg_match("/Sec-WebSocket-Protocol: *(.*?)\r\n/i", $buffer, $match)) {
  400. $connection->WSServerProtocol = trim($match[1]);
  401. }
  402. $connection->handshakeStep = 2;
  403. $handshake_response_length = $pos + 4;
  404. // Try to emit onWebSocketConnect callback.
  405. if (isset($connection->onWebSocketConnect)) {
  406. try {
  407. call_user_func($connection->onWebSocketConnect, $connection, substr($buffer, 0, $handshake_response_length));
  408. } catch (\Exception $e) {
  409. Worker::log($e);
  410. exit(250);
  411. } catch (\Error $e) {
  412. Worker::log($e);
  413. exit(250);
  414. }
  415. }
  416. // Headbeat.
  417. if (!empty($connection->websocketPingInterval)) {
  418. $connection->websocketPingTimer = Timer::add($connection->websocketPingInterval, function() use ($connection){
  419. if (false === $connection->send(pack('H*', '898000000000'), true)) {
  420. Timer::del($connection->websocketPingTimer);
  421. $connection->websocketPingTimer = null;
  422. }
  423. });
  424. }
  425. $connection->consumeRecvBuffer($handshake_response_length);
  426. if (!empty($connection->tmpWebsocketData)) {
  427. $connection->send($connection->tmpWebsocketData, true);
  428. $connection->tmpWebsocketData = '';
  429. }
  430. if (strlen($buffer) > $handshake_response_length) {
  431. return self::input(substr($buffer, $handshake_response_length), $connection);
  432. }
  433. }
  434. return 0;
  435. }
  436. public static function WSSetProtocol($connection, $params) {
  437. $connection->WSClientProtocol = $params[0];
  438. }
  439. public static function WSGetServerProtocol($connection) {
  440. return (property_exists($connection, 'WSServerProtocol')?$connection->WSServerProtocol:null);
  441. }
  442. }