Websocket.php 15 KB

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