Websocket.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. // 还没握手不能发数据
  195. if(empty($connection->websocketHandshake))
  196. {
  197. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Send data before handshake. ", true);
  198. $connection->close();
  199. return false;
  200. }
  201. $first_byte = $connection->websocketType;
  202. if($len<=125)
  203. {
  204. return $first_byte.chr($len).$buffer;
  205. }
  206. else if($len<=65535)
  207. {
  208. return $first_byte.chr(126).pack("n", $len).$buffer;
  209. }
  210. else
  211. {
  212. return $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  213. }
  214. }
  215. /**
  216. * 解包
  217. * @param string $buffer
  218. * @return string
  219. */
  220. public static function decode($buffer, ConnectionInterface $connection)
  221. {
  222. $len = $masks = $data = $decoded = null;
  223. $len = ord($buffer[1]) & 127;
  224. if ($len === 126) {
  225. $masks = substr($buffer, 4, 4);
  226. $data = substr($buffer, 8);
  227. } else if ($len === 127) {
  228. $masks = substr($buffer, 10, 4);
  229. $data = substr($buffer, 14);
  230. } else {
  231. $masks = substr($buffer, 2, 4);
  232. $data = substr($buffer, 6);
  233. }
  234. for ($index = 0; $index < strlen($data); $index++) {
  235. $decoded .= $data[$index] ^ $masks[$index % 4];
  236. }
  237. if($connection->websocketCurrentFrameLength)
  238. {
  239. $connection->websocketDataBuffer .= $decoded;
  240. return $connection->websocketDataBuffer;
  241. }
  242. else
  243. {
  244. $decoded = $connection->websocketDataBuffer . $decoded;
  245. $connection->websocketDataBuffer = '';
  246. return $decoded;
  247. }
  248. }
  249. /**
  250. * 处理websocket握手
  251. * @param string $buffer
  252. * @param TcpConnection $connection
  253. * @return int
  254. */
  255. protected static function dealHandshake($buffer, $connection)
  256. {
  257. // 握手阶段客户端发送HTTP协议
  258. if(0 === strpos($buffer, 'GET'))
  259. {
  260. // 判断\r\n\r\n边界
  261. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  262. if(!$heder_end_pos)
  263. {
  264. return 0;
  265. }
  266. // 解析Sec-WebSocket-Key
  267. $Sec_WebSocket_Key = '';
  268. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $buffer, $match))
  269. {
  270. $Sec_WebSocket_Key = $match[1];
  271. }
  272. else
  273. {
  274. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found", true);
  275. $connection->close();
  276. return 0;
  277. }
  278. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  279. // 握手返回的数据
  280. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  281. $new_message .= "Upgrade: websocket\r\n";
  282. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  283. $new_message .= "Connection: Upgrade\r\n";
  284. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  285. $connection->websocketHandshake = true;
  286. $connection->websocketDataBuffer = '';
  287. $connection->websocketCurrentFrameLength = 0;
  288. $connection->websocketCurrentFrameBuffer = '';
  289. $connection->consumeRecvBuffer(strlen($buffer));
  290. $connection->send($new_message, true);
  291. // blob or arraybuffer
  292. $connection->websocketType = self::BINARY_TYPE_BLOB;
  293. // 如果有设置onWebSocketConnect回调,尝试执行
  294. if(isset($connection->onWebSocketConnect))
  295. {
  296. self::parseHttpHeader($buffer);
  297. try
  298. {
  299. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  300. }
  301. catch(\Exception $e)
  302. {
  303. echo $e;
  304. }
  305. $_GET = $_COOKIE = $_SERVER = array();
  306. }
  307. return 0;
  308. }
  309. // 如果是flash的policy-file-request
  310. elseif(0 === strpos($buffer,'<polic'))
  311. {
  312. $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";
  313. $connection->send($policy_xml, true);
  314. $connection->consumeRecvBuffer(strlen($buffer));
  315. return 0;
  316. }
  317. // 出错
  318. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
  319. $connection->close();
  320. return 0;
  321. }
  322. /**
  323. * 从header中获取
  324. * @param string $buffer
  325. * @return void
  326. */
  327. protected static function parseHttpHeader($buffer)
  328. {
  329. $header_data = explode("\r\n", $buffer);
  330. $_SERVER = array();
  331. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  332. unset($header_data[0]);
  333. foreach($header_data as $content)
  334. {
  335. // \r\n\r\n
  336. if(empty($content))
  337. {
  338. continue;
  339. }
  340. list($key, $value) = explode(':', $content, 2);
  341. $key = strtolower($key);
  342. $value = trim($value);
  343. switch($key)
  344. {
  345. // HTTP_HOST
  346. case 'host':
  347. $_SERVER['HTTP_HOST'] = $value;
  348. $tmp = explode(':', $value);
  349. $_SERVER['SERVER_NAME'] = $tmp[0];
  350. if(isset($tmp[1]))
  351. {
  352. $_SERVER['SERVER_PORT'] = $tmp[1];
  353. }
  354. break;
  355. // HTTP_COOKIE
  356. case 'cookie':
  357. $_SERVER['HTTP_COOKIE'] = $value;
  358. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  359. break;
  360. // HTTP_USER_AGENT
  361. case 'user-agent':
  362. $_SERVER['HTTP_USER_AGENT'] = $value;
  363. break;
  364. // HTTP_REFERER
  365. case 'referer':
  366. $_SERVER['HTTP_REFERER'] = $value;
  367. break;
  368. case 'origin':
  369. $_SERVER['HTTP_ORIGIN'] = $value;
  370. break;
  371. }
  372. }
  373. // QUERY_STRING
  374. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  375. if($_SERVER['QUERY_STRING'])
  376. {
  377. // $GET
  378. parse_str($_SERVER['QUERY_STRING'], $_GET);
  379. }
  380. else
  381. {
  382. $_SERVER['QUERY_STRING'] = '';
  383. }
  384. }
  385. }