Websocket.php 15 KB

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