Websocket.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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\Connection\ConnectionInterface;
  16. use Workerman\Connection\TcpConnection;
  17. use Workerman\Worker;
  18. /**
  19. * WebSocket protocol.
  20. */
  21. class Websocket implements \Workerman\Protocols\ProtocolInterface
  22. {
  23. /**
  24. * Minimum head length of websocket protocol.
  25. *
  26. * @var int
  27. */
  28. const MIN_HEAD_LEN = 2;
  29. /**
  30. * Websocket blob type.
  31. *
  32. * @var string
  33. */
  34. const BINARY_TYPE_BLOB = "\x81";
  35. /**
  36. * Websocket arraybuffer type.
  37. *
  38. * @var string
  39. */
  40. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  41. /**
  42. * Check the integrity of the package.
  43. *
  44. * @param string $buffer
  45. * @param ConnectionInterface $connection
  46. * @return int
  47. */
  48. public static function input($buffer, ConnectionInterface $connection)
  49. {
  50. // Receive length.
  51. $recv_len = strlen($buffer);
  52. // We need more data.
  53. if ($recv_len < self::MIN_HEAD_LEN) {
  54. return 0;
  55. }
  56. // Has not yet completed the handshake.
  57. if (empty($connection->websocketHandshake)) {
  58. return self::dealHandshake($buffer, $connection);
  59. }
  60. // Buffer websocket frame data.
  61. if ($connection->websocketCurrentFrameLength) {
  62. // We need more frame data.
  63. if ($connection->websocketCurrentFrameLength > $recv_len) {
  64. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  65. return 0;
  66. }
  67. } else {
  68. $data_len = ord($buffer[1]) & 127;
  69. $firstbyte = ord($buffer[0]);
  70. $is_fin_frame = $firstbyte >> 7;
  71. $opcode = $firstbyte & 0xf;
  72. switch ($opcode) {
  73. case 0x0:
  74. break;
  75. // Blob type.
  76. case 0x1:
  77. break;
  78. // Arraybuffer type.
  79. case 0x2:
  80. break;
  81. // Close package.
  82. case 0x8:
  83. // Try to emit onWebSocketClose callback.
  84. if (isset($connection->onWebSocketClose)) {
  85. try {
  86. call_user_func($connection->onWebSocketClose, $connection);
  87. } catch (\Exception $e) {
  88. Worker::log($e);
  89. exit(250);
  90. } catch (\Error $e) {
  91. Worker::log($e);
  92. exit(250);
  93. }
  94. } // Close connection.
  95. else {
  96. $connection->close();
  97. }
  98. return 0;
  99. // Ping package.
  100. case 0x9:
  101. // Try to emit onWebSocketPing callback.
  102. if (isset($connection->onWebSocketPing)) {
  103. try {
  104. call_user_func($connection->onWebSocketPing, $connection);
  105. } catch (\Exception $e) {
  106. Worker::log($e);
  107. exit(250);
  108. } catch (\Error $e) {
  109. Worker::log($e);
  110. exit(250);
  111. }
  112. } // Send pong package to client.
  113. else {
  114. $connection->send(pack('H*', '8a00'), true);
  115. }
  116. // Consume data from receive buffer.
  117. if (!$data_len) {
  118. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  119. if ($recv_len > self::MIN_HEAD_LEN) {
  120. return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
  121. }
  122. return 0;
  123. }
  124. break;
  125. // Pong package.
  126. case 0xa:
  127. // Try to emit onWebSocketPong callback.
  128. if (isset($connection->onWebSocketPong)) {
  129. try {
  130. call_user_func($connection->onWebSocketPong, $connection);
  131. } catch (\Exception $e) {
  132. Worker::log($e);
  133. exit(250);
  134. } catch (\Error $e) {
  135. Worker::log($e);
  136. exit(250);
  137. }
  138. }
  139. // Consume data from receive buffer.
  140. if (!$data_len) {
  141. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  142. if ($recv_len > self::MIN_HEAD_LEN) {
  143. return self::input(substr($buffer, self::MIN_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:" . bin2hex($buffer) . "\n";
  151. $connection->close();
  152. return 0;
  153. }
  154. // Calculate packet length.
  155. $head_len = 6;
  156. if ($data_len === 126) {
  157. $head_len = 8;
  158. if ($head_len > $recv_len) {
  159. return 0;
  160. }
  161. $pack = unpack('nn/ntotal_len', $buffer);
  162. $data_len = $pack['total_len'];
  163. } else {
  164. if ($data_len === 127) {
  165. $head_len = 14;
  166. if ($head_len > $recv_len) {
  167. return 0;
  168. }
  169. $arr = unpack('n/N2c', $buffer);
  170. $data_len = $arr['c1']*4294967296 + $arr['c2'];
  171. }
  172. }
  173. $current_frame_length = $head_len + $data_len;
  174. $total_package_size = strlen($connection->websocketDataBuffer) + $current_frame_length;
  175. if ($total_package_size > TcpConnection::$maxPackageSize) {
  176. echo "error package. package_length=$total_package_size\n";
  177. $connection->close();
  178. return 0;
  179. }
  180. if ($is_fin_frame) {
  181. return $current_frame_length;
  182. } else {
  183. $connection->websocketCurrentFrameLength = $current_frame_length;
  184. }
  185. }
  186. // Received just a frame length data.
  187. if ($connection->websocketCurrentFrameLength === $recv_len) {
  188. self::decode($buffer, $connection);
  189. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  190. $connection->websocketCurrentFrameLength = 0;
  191. return 0;
  192. } // The length of the received data is greater than the length of a frame.
  193. elseif ($connection->websocketCurrentFrameLength < $recv_len) {
  194. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  195. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  196. $current_frame_length = $connection->websocketCurrentFrameLength;
  197. $connection->websocketCurrentFrameLength = 0;
  198. // Continue to read next frame.
  199. return self::input(substr($buffer, $current_frame_length), $connection);
  200. } // The length of the received data is less than the length of a frame.
  201. else {
  202. return 0;
  203. }
  204. }
  205. /**
  206. * Websocket encode.
  207. *
  208. * @param string $buffer
  209. * @param ConnectionInterface $connection
  210. * @return string
  211. */
  212. public static function encode($buffer, ConnectionInterface $connection)
  213. {
  214. if (!is_scalar($buffer)) {
  215. throw new \Exception("You can't send(" . gettype($buffer) . ") to client, you need to convert it to a string. ");
  216. }
  217. $len = strlen($buffer);
  218. if (empty($connection->websocketType)) {
  219. $connection->websocketType = self::BINARY_TYPE_BLOB;
  220. }
  221. $first_byte = $connection->websocketType;
  222. if ($len <= 125) {
  223. $encode_buffer = $first_byte . chr($len) . $buffer;
  224. } else {
  225. if ($len <= 65535) {
  226. $encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
  227. } else {
  228. $encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
  229. }
  230. }
  231. // Handshake not completed so temporary buffer websocket data waiting for send.
  232. if (empty($connection->websocketHandshake)) {
  233. if (empty($connection->tmpWebsocketData)) {
  234. $connection->tmpWebsocketData = '';
  235. }
  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 .= $encode_buffer;
  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 empty string.
  267. return '';
  268. }
  269. return $encode_buffer;
  270. }
  271. /**
  272. * Websocket decode.
  273. *
  274. * @param string $buffer
  275. * @param ConnectionInterface $connection
  276. * @return string
  277. */
  278. public static function decode($buffer, ConnectionInterface $connection)
  279. {
  280. $len = $masks = $data = $decoded = null;
  281. $len = ord($buffer[1]) & 127;
  282. if ($len === 126) {
  283. $masks = substr($buffer, 4, 4);
  284. $data = substr($buffer, 8);
  285. } else {
  286. if ($len === 127) {
  287. $masks = substr($buffer, 10, 4);
  288. $data = substr($buffer, 14);
  289. } else {
  290. $masks = substr($buffer, 2, 4);
  291. $data = substr($buffer, 6);
  292. }
  293. }
  294. for ($index = 0; $index < strlen($data); $index++) {
  295. $decoded .= $data[$index] ^ $masks[$index % 4];
  296. }
  297. if ($connection->websocketCurrentFrameLength) {
  298. $connection->websocketDataBuffer .= $decoded;
  299. return $connection->websocketDataBuffer;
  300. } else {
  301. if ($connection->websocketDataBuffer !== '') {
  302. $decoded = $connection->websocketDataBuffer . $decoded;
  303. $connection->websocketDataBuffer = '';
  304. }
  305. return $decoded;
  306. }
  307. }
  308. /**
  309. * Websocket handshake.
  310. *
  311. * @param string $buffer
  312. * @param \Workerman\Connection\TcpConnection $connection
  313. * @return int
  314. */
  315. protected static function dealHandshake($buffer, $connection)
  316. {
  317. // HTTP protocol.
  318. if (0 === strpos($buffer, 'GET')) {
  319. // Find \r\n\r\n.
  320. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  321. if (!$heder_end_pos) {
  322. return 0;
  323. }
  324. $header_length = $heder_end_pos + 4;
  325. // Get Sec-WebSocket-Key.
  326. $Sec_WebSocket_Key = '';
  327. if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
  328. $Sec_WebSocket_Key = $match[1];
  329. } else {
  330. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found.<br>This is a WebSocket service and can not be accessed via HTTP.<br>See <a href=\"http://wiki.workerman.net/Error1\">http://wiki.workerman.net/Error1</a>",
  331. true);
  332. $connection->close();
  333. return 0;
  334. }
  335. // Calculation websocket key.
  336. $new_key = base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
  337. // Handshake response data.
  338. $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
  339. $handshake_message .= "Upgrade: websocket\r\n";
  340. $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
  341. $handshake_message .= "Connection: Upgrade\r\n";
  342. $handshake_message .= "Server: workerman/".Worker::VERSION."\r\n";
  343. $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  344. // Mark handshake complete..
  345. $connection->websocketHandshake = true;
  346. // Websocket data buffer.
  347. $connection->websocketDataBuffer = '';
  348. // Current websocket frame length.
  349. $connection->websocketCurrentFrameLength = 0;
  350. // Current websocket frame data.
  351. $connection->websocketCurrentFrameBuffer = '';
  352. // Consume handshake data.
  353. $connection->consumeRecvBuffer($header_length);
  354. // Send handshake response.
  355. $connection->send($handshake_message, true);
  356. // There are data waiting to be sent.
  357. if (!empty($connection->tmpWebsocketData)) {
  358. $connection->send($connection->tmpWebsocketData, true);
  359. $connection->tmpWebsocketData = '';
  360. }
  361. // blob or arraybuffer
  362. if (empty($connection->websocketType)) {
  363. $connection->websocketType = self::BINARY_TYPE_BLOB;
  364. }
  365. // Try to emit onWebSocketConnect callback.
  366. if (isset($connection->onWebSocketConnect)) {
  367. self::parseHttpHeader($buffer);
  368. try {
  369. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  370. } catch (\Exception $e) {
  371. Worker::log($e);
  372. exit(250);
  373. } catch (\Error $e) {
  374. Worker::log($e);
  375. exit(250);
  376. }
  377. if (!empty($_SESSION) && class_exists('\GatewayWorker\Lib\Context')) {
  378. $connection->session = \GatewayWorker\Lib\Context::sessionEncode($_SESSION);
  379. }
  380. $_GET = $_SERVER = $_SESSION = $_COOKIE = array();
  381. }
  382. if (strlen($buffer) > $header_length) {
  383. return self::input(substr($buffer, $header_length), $connection);
  384. }
  385. return 0;
  386. } // Is flash policy-file-request.
  387. elseif (0 === strpos($buffer, '<polic')) {
  388. $policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>' . "\0";
  389. $connection->send($policy_xml, true);
  390. $connection->consumeRecvBuffer(strlen($buffer));
  391. return 0;
  392. }
  393. // Bad websocket handshake request.
  394. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ",
  395. true);
  396. $connection->close();
  397. return 0;
  398. }
  399. /**
  400. * Parse http header.
  401. *
  402. * @param string $buffer
  403. * @return void
  404. */
  405. protected static function parseHttpHeader($buffer)
  406. {
  407. // Parse headers.
  408. list($http_header, ) = explode("\r\n\r\n", $buffer, 2);
  409. $header_data = explode("\r\n", $http_header);
  410. if ($_SERVER) {
  411. $_SERVER = array();
  412. }
  413. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
  414. $header_data[0]);
  415. unset($header_data[0]);
  416. foreach ($header_data as $content) {
  417. // \r\n\r\n
  418. if (empty($content)) {
  419. continue;
  420. }
  421. list($key, $value) = explode(':', $content, 2);
  422. $key = str_replace('-', '_', strtoupper($key));
  423. $value = trim($value);
  424. $_SERVER['HTTP_' . $key] = $value;
  425. switch ($key) {
  426. // HTTP_HOST
  427. case 'HOST':
  428. $tmp = explode(':', $value);
  429. $_SERVER['SERVER_NAME'] = $tmp[0];
  430. if (isset($tmp[1])) {
  431. $_SERVER['SERVER_PORT'] = $tmp[1];
  432. }
  433. break;
  434. // cookie
  435. case 'COOKIE':
  436. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  437. break;
  438. }
  439. }
  440. // QUERY_STRING
  441. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  442. if ($_SERVER['QUERY_STRING']) {
  443. // $GET
  444. parse_str($_SERVER['QUERY_STRING'], $_GET);
  445. } else {
  446. $_SERVER['QUERY_STRING'] = '';
  447. }
  448. }
  449. }