Ws.php 16 KB

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