Websocket.php 19 KB

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