Websocket.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 协议服务端解包和打包
  18. */
  19. class Websocket implements \Workerman\Protocols\ProtocolInterface
  20. {
  21. /**
  22. * websocket头部最小长度
  23. * @var int
  24. */
  25. const MIN_HEAD_LEN = 6;
  26. /**
  27. * websocket blob类型
  28. * @var char
  29. */
  30. const BINARY_TYPE_BLOB = "\x81";
  31. /**
  32. * websocket arraybuffer类型
  33. * @var char
  34. */
  35. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  36. /**
  37. * 检查包的完整性
  38. * @param string $buffer
  39. */
  40. public static function input($buffer, ConnectionInterface $connection)
  41. {
  42. // 数据长度
  43. $recv_len = strlen($buffer);
  44. // 长度不够
  45. if($recv_len < self::MIN_HEAD_LEN)
  46. {
  47. return 0;
  48. }
  49. // 还没有握手
  50. if(empty($connection->websocketHandshake))
  51. {
  52. return self::dealHandshake($buffer, $connection);
  53. }
  54. // $connection->websocketCurrentFrameLength有值说明当前fin为0,则缓冲websocket帧数据
  55. if($connection->websocketCurrentFrameLength)
  56. {
  57. // 如果当前帧数据未收全,则继续收
  58. if($connection->websocketCurrentFrameLength > $recv_len)
  59. {
  60. // 返回0,因为不清楚完整的数据包长度,需要等待fin=1的帧
  61. return 0;
  62. }
  63. }
  64. else
  65. {
  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. {
  72. // 附加数据帧 @todo 实现附加数据帧
  73. case 0x0:
  74. break;
  75. // 文本数据帧
  76. case 0x1:
  77. break;
  78. // 二进制数据帧
  79. case 0x2:
  80. break;
  81. // 关闭的包
  82. case 0x8:
  83. // 如果有设置onWebSocketClose回调,尝试执行
  84. if(isset($connection->onWebSocketClose))
  85. {
  86. try
  87. {
  88. call_user_func($connection->onWebSocketClose, $connection);
  89. }
  90. catch(\Exception $e)
  91. {
  92. echo $e;
  93. exit(250);
  94. }
  95. }
  96. // 默认行为是关闭连接
  97. else
  98. {
  99. $connection->close();
  100. }
  101. return 0;
  102. // ping的包
  103. case 0x9:
  104. // 如果有设置onWebSocketPing回调,尝试执行
  105. if(isset($connection->onWebSocketPing))
  106. {
  107. try
  108. {
  109. call_user_func($connection->onWebSocketPing, $connection);
  110. }
  111. catch(\Exception $e)
  112. {
  113. echo $e;
  114. exit(250);
  115. }
  116. }
  117. // 默认发送pong
  118. else
  119. {
  120. $connection->send(pack('H*', '8a00'), true);
  121. }
  122. // 从接受缓冲区中消费掉该数据包
  123. if(!$data_len)
  124. {
  125. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  126. return 0;
  127. }
  128. break;
  129. // pong的包
  130. case 0xa:
  131. // 如果有设置onWebSocketPong回调,尝试执行
  132. if(isset($connection->onWebSocketPong))
  133. {
  134. try
  135. {
  136. call_user_func($connection->onWebSocketPong, $connection);
  137. }
  138. catch(\Exception $e)
  139. {
  140. echo $e;
  141. exit(250);
  142. }
  143. }
  144. // 从接受缓冲区中消费掉该数据包
  145. if(!$data_len)
  146. {
  147. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  148. return 0;
  149. }
  150. break;
  151. // 错误的opcode
  152. default :
  153. echo "error opcode $opcode and close websocket connection\n";
  154. $connection->close();
  155. return 0;
  156. }
  157. // websocket二进制数据
  158. $head_len = self::MIN_HEAD_LEN;
  159. if ($data_len === 126) {
  160. $head_len = 8;
  161. if($head_len > $recv_len)
  162. {
  163. return 0;
  164. }
  165. $pack = unpack('ntotal_len', substr($buffer, 2, 2));
  166. $data_len = $pack['total_len'];
  167. } else if ($data_len === 127) {
  168. $head_len = 14;
  169. if($head_len > $recv_len)
  170. {
  171. return 0;
  172. }
  173. $arr = unpack('N2', substr($buffer, 2, 8));
  174. $data_len = $arr[1]*4294967296 + $arr[2];
  175. }
  176. $current_frame_length = $head_len + $data_len;
  177. if($is_fin_frame)
  178. {
  179. return $current_frame_length;
  180. }
  181. else
  182. {
  183. $connection->websocketCurrentFrameLength = $current_frame_length;
  184. }
  185. }
  186. // 收到的数据刚好是一个frame
  187. if($connection->websocketCurrentFrameLength == $recv_len)
  188. {
  189. self::decode($buffer, $connection);
  190. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  191. $connection->websocketCurrentFrameLength = 0;
  192. return 0;
  193. }
  194. // 收到的数据大于一个frame
  195. elseif($connection->websocketCurrentFrameLength < $recv_len)
  196. {
  197. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  198. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  199. $current_frame_length = $connection->websocketCurrentFrameLength;
  200. $connection->websocketCurrentFrameLength = 0;
  201. // 继续读取下一个frame
  202. return self::input(substr($buffer, $current_frame_length), $connection);
  203. }
  204. // 收到的数据不足一个frame
  205. else
  206. {
  207. return 0;
  208. }
  209. }
  210. /**
  211. * 打包
  212. * @param string $buffer
  213. * @return string
  214. */
  215. public static function encode($buffer, ConnectionInterface $connection)
  216. {
  217. $len = strlen($buffer);
  218. if(empty($connection->websocketType))
  219. {
  220. // 默认是utf8文本格式
  221. $connection->websocketType = self::BINARY_TYPE_BLOB;
  222. }
  223. $first_byte = $connection->websocketType;
  224. if($len<=125)
  225. {
  226. $encode_buffer = $first_byte.chr($len).$buffer;
  227. }
  228. else if($len<=65535)
  229. {
  230. $encode_buffer = $first_byte.chr(126).pack("n", $len).$buffer;
  231. }
  232. else
  233. {
  234. $encode_buffer = $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  235. }
  236. // 还没握手不能发数据,先将数据缓冲起来,等握手完毕后发送
  237. if(empty($connection->websocketHandshake))
  238. {
  239. if(empty($connection->tmpWebsocketData))
  240. {
  241. // 临时数据缓冲
  242. $connection->tmpWebsocketData = '';
  243. }
  244. $connection->tmpWebsocketData .= $encode_buffer;
  245. // 返回空,阻止发送
  246. return '';
  247. }
  248. return $encode_buffer;
  249. }
  250. /**
  251. * 解包
  252. * @param string $buffer
  253. * @return string
  254. */
  255. public static function decode($buffer, ConnectionInterface $connection)
  256. {
  257. $len = $masks = $data = $decoded = null;
  258. $len = ord($buffer[1]) & 127;
  259. if ($len === 126) {
  260. $masks = substr($buffer, 4, 4);
  261. $data = substr($buffer, 8);
  262. } else if ($len === 127) {
  263. $masks = substr($buffer, 10, 4);
  264. $data = substr($buffer, 14);
  265. } else {
  266. $masks = substr($buffer, 2, 4);
  267. $data = substr($buffer, 6);
  268. }
  269. for ($index = 0; $index < strlen($data); $index++) {
  270. $decoded .= $data[$index] ^ $masks[$index % 4];
  271. }
  272. if($connection->websocketCurrentFrameLength)
  273. {
  274. $connection->websocketDataBuffer .= $decoded;
  275. return $connection->websocketDataBuffer;
  276. }
  277. else
  278. {
  279. $decoded = $connection->websocketDataBuffer . $decoded;
  280. $connection->websocketDataBuffer = '';
  281. return $decoded;
  282. }
  283. }
  284. /**
  285. * 处理websocket握手
  286. * @param string $buffer
  287. * @param TcpConnection $connection
  288. * @return int
  289. */
  290. protected static function dealHandshake($buffer, $connection)
  291. {
  292. // 握手阶段客户端发送HTTP协议
  293. if(0 === strpos($buffer, 'GET'))
  294. {
  295. // 判断\r\n\r\n边界
  296. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  297. if(!$heder_end_pos)
  298. {
  299. return 0;
  300. }
  301. // 解析Sec-WebSocket-Key
  302. $Sec_WebSocket_Key = '';
  303. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match))
  304. {
  305. $Sec_WebSocket_Key = $match[1];
  306. }
  307. else
  308. {
  309. $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);
  310. $connection->close();
  311. return 0;
  312. }
  313. // 握手的key
  314. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  315. // 握手返回的数据
  316. $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
  317. $handshake_message .= "Upgrade: websocket\r\n";
  318. $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
  319. $handshake_message .= "Connection: Upgrade\r\n";
  320. $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  321. // 标记已经握手
  322. $connection->websocketHandshake = true;
  323. // 缓冲fin为0的包,直到fin为1
  324. $connection->websocketDataBuffer = '';
  325. // 当前数据帧的长度,可能是fin为0的帧,也可能是fin为1的帧
  326. $connection->websocketCurrentFrameLength = 0;
  327. // 当前帧的数据缓冲
  328. $connection->websocketCurrentFrameBuffer = '';
  329. // 消费掉握手数据,不触发onMessage
  330. $connection->consumeRecvBuffer(strlen($buffer));
  331. // 发送握手数据
  332. $connection->send($handshake_message, true);
  333. // 握手后有数据要发送
  334. if(!empty($connection->tmpWebsocketData))
  335. {
  336. $connection->send($connection->tmpWebsocketData, true);
  337. $connection->tmpWebsocketData = '';
  338. }
  339. // blob or arraybuffer
  340. if(empty($connection->websocketType))
  341. {
  342. $connection->websocketType = self::BINARY_TYPE_BLOB;
  343. }
  344. // 如果有设置onWebSocketConnect回调,尝试执行
  345. if(isset($connection->onWebSocketConnect))
  346. {
  347. self::parseHttpHeader($buffer);
  348. try
  349. {
  350. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  351. }
  352. catch(\Exception $e)
  353. {
  354. echo $e;
  355. exit(250);
  356. }
  357. $_GET = $_COOKIE = $_SERVER = array();
  358. }
  359. return 0;
  360. }
  361. // 如果是flash的policy-file-request
  362. elseif(0 === strpos($buffer,'<polic'))
  363. {
  364. $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";
  365. $connection->send($policy_xml, true);
  366. $connection->consumeRecvBuffer(strlen($buffer));
  367. return 0;
  368. }
  369. // 出错
  370. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
  371. $connection->close();
  372. return 0;
  373. }
  374. /**
  375. * 从header中获取
  376. * @param string $buffer
  377. * @return void
  378. */
  379. protected static function parseHttpHeader($buffer)
  380. {
  381. $header_data = explode("\r\n", $buffer);
  382. $_SERVER = array();
  383. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  384. unset($header_data[0]);
  385. foreach($header_data as $content)
  386. {
  387. // \r\n\r\n
  388. if(empty($content))
  389. {
  390. continue;
  391. }
  392. list($key, $value) = explode(':', $content, 2);
  393. $key = strtolower($key);
  394. $value = trim($value);
  395. switch($key)
  396. {
  397. // HTTP_HOST
  398. case 'host':
  399. $_SERVER['HTTP_HOST'] = $value;
  400. $tmp = explode(':', $value);
  401. $_SERVER['SERVER_NAME'] = $tmp[0];
  402. if(isset($tmp[1]))
  403. {
  404. $_SERVER['SERVER_PORT'] = $tmp[1];
  405. }
  406. break;
  407. // HTTP_COOKIE
  408. case 'cookie':
  409. $_SERVER['HTTP_COOKIE'] = $value;
  410. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  411. break;
  412. // HTTP_USER_AGENT
  413. case 'user-agent':
  414. $_SERVER['HTTP_USER_AGENT'] = $value;
  415. break;
  416. // HTTP_REFERER
  417. case 'referer':
  418. $_SERVER['HTTP_REFERER'] = $value;
  419. break;
  420. case 'origin':
  421. $_SERVER['HTTP_ORIGIN'] = $value;
  422. break;
  423. }
  424. }
  425. // QUERY_STRING
  426. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  427. if($_SERVER['QUERY_STRING'])
  428. {
  429. // $GET
  430. parse_str($_SERVER['QUERY_STRING'], $_GET);
  431. }
  432. else
  433. {
  434. $_SERVER['QUERY_STRING'] = '';
  435. }
  436. }
  437. }