Websocket.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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\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. $len = strlen($buffer);
  208. if (empty($connection->websocketType)) {
  209. $connection->websocketType = self::BINARY_TYPE_BLOB;
  210. }
  211. $first_byte = $connection->websocketType;
  212. if ($len <= 125) {
  213. $encode_buffer = $first_byte . chr($len) . $buffer;
  214. } else {
  215. if ($len <= 65535) {
  216. $encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
  217. } else {
  218. $encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
  219. }
  220. }
  221. // Handshake not completed so temporary buffer websocket data waiting for send.
  222. if (empty($connection->websocketHandshake)) {
  223. if (empty($connection->tmpWebsocketData)) {
  224. $connection->tmpWebsocketData = '';
  225. }
  226. $connection->tmpWebsocketData .= $encode_buffer;
  227. // Return empty string.
  228. return '';
  229. }
  230. return $encode_buffer;
  231. }
  232. /**
  233. * Websocket decode.
  234. *
  235. * @param string $buffer
  236. * @param ConnectionInterface $connection
  237. * @return string
  238. */
  239. public static function decode($buffer, ConnectionInterface $connection)
  240. {
  241. $len = $masks = $data = $decoded = null;
  242. $len = ord($buffer[1]) & 127;
  243. if ($len === 126) {
  244. $masks = substr($buffer, 4, 4);
  245. $data = substr($buffer, 8);
  246. } else {
  247. if ($len === 127) {
  248. $masks = substr($buffer, 10, 4);
  249. $data = substr($buffer, 14);
  250. } else {
  251. $masks = substr($buffer, 2, 4);
  252. $data = substr($buffer, 6);
  253. }
  254. }
  255. for ($index = 0; $index < strlen($data); $index++) {
  256. $decoded .= $data[$index] ^ $masks[$index % 4];
  257. }
  258. if ($connection->websocketCurrentFrameLength) {
  259. $connection->websocketDataBuffer .= $decoded;
  260. return $connection->websocketDataBuffer;
  261. } else {
  262. if ($connection->websocketDataBuffer !== '') {
  263. $decoded = $connection->websocketDataBuffer . $decoded;
  264. $connection->websocketDataBuffer = '';
  265. }
  266. return $decoded;
  267. }
  268. }
  269. /**
  270. * Websocket handshake.
  271. *
  272. * @param string $buffer
  273. * @param \Workerman\Connection\TcpConnection $connection
  274. * @return int
  275. */
  276. protected static function dealHandshake($buffer, $connection)
  277. {
  278. // HTTP protocol.
  279. if (0 === strpos($buffer, 'GET')) {
  280. // Find \r\n\r\n.
  281. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  282. if (!$heder_end_pos) {
  283. return 0;
  284. }
  285. $header_length = $heder_end_pos + 4;
  286. // Get Sec-WebSocket-Key.
  287. $Sec_WebSocket_Key = '';
  288. if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
  289. $Sec_WebSocket_Key = $match[1];
  290. } else {
  291. $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.",
  292. true);
  293. $connection->close();
  294. return 0;
  295. }
  296. // Calculation websocket key.
  297. $new_key = base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
  298. // Handshake response data.
  299. $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
  300. $handshake_message .= "Upgrade: websocket\r\n";
  301. $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
  302. $handshake_message .= "Connection: Upgrade\r\n";
  303. $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  304. // Mark handshake complete..
  305. $connection->websocketHandshake = true;
  306. // Websocket data buffer.
  307. $connection->websocketDataBuffer = '';
  308. // Current websocket frame length.
  309. $connection->websocketCurrentFrameLength = 0;
  310. // Current websocket frame data.
  311. $connection->websocketCurrentFrameBuffer = '';
  312. // Consume handshake data.
  313. $connection->consumeRecvBuffer($header_length);
  314. // Send handshake response.
  315. $connection->send($handshake_message, true);
  316. // There are data waiting to be sent.
  317. if (!empty($connection->tmpWebsocketData)) {
  318. $connection->send($connection->tmpWebsocketData, true);
  319. $connection->tmpWebsocketData = '';
  320. }
  321. // blob or arraybuffer
  322. if (empty($connection->websocketType)) {
  323. $connection->websocketType = self::BINARY_TYPE_BLOB;
  324. }
  325. // Try to emit onWebSocketConnect callback.
  326. if (isset($connection->onWebSocketConnect)) {
  327. self::parseHttpHeader($buffer);
  328. try {
  329. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  330. } catch (\Exception $e) {
  331. Worker::log($e);
  332. exit(250);
  333. } catch (\Error $e) {
  334. Worker::log($e);
  335. exit(250);
  336. }
  337. $_GET = $_COOKIE = $_SERVER = array();
  338. }
  339. if (strlen($buffer) > $header_length) {
  340. return self::input(substr($buffer, $header_length), $connection);
  341. }
  342. return 0;
  343. } // Is flash policy-file-request.
  344. elseif (0 === strpos($buffer, '<polic')) {
  345. $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";
  346. $connection->send($policy_xml, true);
  347. $connection->consumeRecvBuffer(strlen($buffer));
  348. return 0;
  349. }
  350. // Bad websocket handshake request.
  351. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ",
  352. true);
  353. $connection->close();
  354. return 0;
  355. }
  356. /**
  357. * Parse http header.
  358. *
  359. * @param string $buffer
  360. * @return void
  361. */
  362. protected static function parseHttpHeader($buffer)
  363. {
  364. $header_data = explode("\r\n", $buffer);
  365. $_SERVER = array();
  366. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
  367. $header_data[0]);
  368. unset($header_data[0]);
  369. foreach ($header_data as $content) {
  370. // \r\n\r\n
  371. if (empty($content)) {
  372. continue;
  373. }
  374. list($key, $value) = explode(':', $content, 2);
  375. $key = strtolower($key);
  376. $value = trim($value);
  377. switch ($key) {
  378. // HTTP_HOST
  379. case 'host':
  380. $_SERVER['HTTP_HOST'] = $value;
  381. $tmp = explode(':', $value);
  382. $_SERVER['SERVER_NAME'] = $tmp[0];
  383. if (isset($tmp[1])) {
  384. $_SERVER['SERVER_PORT'] = $tmp[1];
  385. }
  386. break;
  387. // HTTP_COOKIE
  388. case 'cookie':
  389. $_SERVER['HTTP_COOKIE'] = $value;
  390. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  391. break;
  392. // HTTP_USER_AGENT
  393. case 'user-agent':
  394. $_SERVER['HTTP_USER_AGENT'] = $value;
  395. break;
  396. // HTTP_REFERER
  397. case 'referer':
  398. $_SERVER['HTTP_REFERER'] = $value;
  399. break;
  400. case 'origin':
  401. $_SERVER['HTTP_ORIGIN'] = $value;
  402. break;
  403. }
  404. }
  405. // QUERY_STRING
  406. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  407. if ($_SERVER['QUERY_STRING']) {
  408. // $GET
  409. parse_str($_SERVER['QUERY_STRING'], $_GET);
  410. } else {
  411. $_SERVER['QUERY_STRING'] = '';
  412. }
  413. }
  414. }