Websocket.php 18 KB

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