Websocket.php 15 KB

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