Websocket.php 15 KB

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