Websocket.php 16 KB

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