Ws.php 17 KB

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