Websocket.php 16 KB

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