Websocket.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. namespace Workerman\Protocols;
  3. /**
  4. * WebSocket 协议服务端解包和打包
  5. * @author walkor <walkor@workerman.net>
  6. */
  7. use Workerman\Connection\ConnectionInterface;
  8. class Websocket implements \Workerman\Protocols\ProtocolInterface
  9. {
  10. /**
  11. * websocket头部最小长度
  12. * @var int
  13. */
  14. const MIN_HEAD_LEN = 6;
  15. /**
  16. * websocket blob类型
  17. * @var char
  18. */
  19. const BINARY_TYPE_BLOB = "\x81";
  20. /**
  21. * websocket arraybuffer类型
  22. * @var char
  23. */
  24. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  25. /**
  26. * 检查包的完整性
  27. * @param string $buffer
  28. */
  29. public static function input($buffer, ConnectionInterface $connection)
  30. {
  31. // 数据长度
  32. $recv_len = strlen($buffer);
  33. // 长度不够
  34. if($recv_len < self::MIN_HEAD_LEN)
  35. {
  36. return 0;
  37. }
  38. // 还没有握手
  39. if(empty($connection->handshake))
  40. {
  41. return self::dealHandshake($buffer, $connection);
  42. }
  43. $data_len = ord($buffer[1]) & 127;
  44. $opcode = ord($buffer[0]) & 0xf;
  45. switch($opcode)
  46. {
  47. // 附加数据帧 @todo 实现附加数据帧
  48. case 0x0:
  49. break;
  50. // 文本数据帧
  51. case 0x1:
  52. break;
  53. // 二进制数据帧
  54. case 0x2:
  55. break;
  56. // 关闭的包
  57. case 0x8:
  58. // 如果有设置onWebSocketClose回调,尝试执行
  59. if(isset($connection->onWebSocketClose))
  60. {
  61. call_user_func($connection->onWebSocketClose, $connection);
  62. }
  63. // 默认行为是关闭连接
  64. else
  65. {
  66. $connection->close();
  67. }
  68. return 0;
  69. // ping的包
  70. case 0x9:
  71. // 如果有设置onWebSocketPing回调,尝试执行
  72. if(isset($connection->onWebSocketPing))
  73. {
  74. call_user_func($connection->onWebSocketPing, $connection);
  75. }
  76. // 默认发送pong
  77. else
  78. {
  79. $connection->send(pack('H*', '8a00'), true);
  80. }
  81. // 从接受缓冲区中消费掉该数据包
  82. if(!$data_len)
  83. {
  84. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  85. return 0;
  86. }
  87. break;
  88. // pong的包
  89. case 0xa:
  90. // 如果有设置onWebSocketPong回调,尝试执行
  91. if(isset($connection->onWebSocketPong))
  92. {
  93. call_user_func($connection->onWebSocketPong, $connection);
  94. }
  95. // 从接受缓冲区中消费掉该数据包
  96. if(!$data_len)
  97. {
  98. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  99. return 0;
  100. }
  101. break;
  102. // 错误的opcode
  103. default :
  104. $connection->close();
  105. return 0;
  106. }
  107. // websocket二进制数据
  108. $head_len = self::MIN_HEAD_LEN;
  109. if ($data_len === 126) {
  110. $pack = unpack('ntotal_len', substr($buffer, 2, 2));
  111. $data_len = $pack['total_len'];
  112. $head_len = 8;
  113. } else if ($data_len === 127) {
  114. $arr = unpack('N2', substr($buffer, 2, 8));
  115. $data_len = $arr[1]*4294967296 + $arr[2];
  116. $head_len = 14;
  117. }
  118. return $head_len + $data_len;
  119. }
  120. /**
  121. * 打包
  122. * @param string $buffer
  123. * @return string
  124. */
  125. public static function encode($buffer, ConnectionInterface $connection)
  126. {
  127. $len = strlen($buffer);
  128. $first_byte = $connection->protocolData['binaryType'];
  129. if($len<=125)
  130. {
  131. return $first_byte.chr($len).$buffer;
  132. }
  133. else if($len<=65535)
  134. {
  135. return $first_byte.chr(126).pack("n", $len).$buffer;
  136. }
  137. else
  138. {
  139. return $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  140. }
  141. }
  142. /**
  143. * 解包
  144. * @param string $buffer
  145. * @return string
  146. */
  147. public static function decode($buffer, ConnectionInterface $connection)
  148. {
  149. $len = $masks = $data = $decoded = null;
  150. $len = ord($buffer[1]) & 127;
  151. if ($len === 126) {
  152. $masks = substr($buffer, 4, 4);
  153. $data = substr($buffer, 8);
  154. } else if ($len === 127) {
  155. $masks = substr($buffer, 10, 4);
  156. $data = substr($buffer, 14);
  157. } else {
  158. $masks = substr($buffer, 2, 4);
  159. $data = substr($buffer, 6);
  160. }
  161. for ($index = 0; $index < strlen($data); $index++) {
  162. $decoded .= $data[$index] ^ $masks[$index % 4];
  163. }
  164. return $decoded;
  165. }
  166. /**
  167. * 处理websocket握手
  168. * @param string $buffer
  169. * @param TcpConnection $connection
  170. * @return int
  171. */
  172. protected static function dealHandshake($buffer, $connection)
  173. {
  174. // 握手阶段客户端发送HTTP协议
  175. if(0 === strpos($buffer, 'GET'))
  176. {
  177. // 判断\r\n\r\n边界
  178. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  179. if(!$heder_end_pos)
  180. {
  181. return 0;
  182. }
  183. // 解析Sec-WebSocket-Key
  184. $Sec_WebSocket_Key = '';
  185. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $buffer, $match))
  186. {
  187. $Sec_WebSocket_Key = $match[1];
  188. }
  189. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  190. // 握手返回的数据
  191. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  192. $new_message .= "Upgrade: websocket\r\n";
  193. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  194. $new_message .= "Connection: Upgrade\r\n";
  195. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  196. $connection->handshake = true;
  197. $connection->consumeRecvBuffer(strlen($buffer));
  198. $connection->send($new_message, true);
  199. $connection->protocolData = array(
  200. 'binaryType' => self::BINARY_TYPE_BLOB, // blob or arraybuffer
  201. );
  202. // 如果有设置onWebSocketConnect回调,尝试执行
  203. if(isset($connection->onWebSocketConnect))
  204. {
  205. self::parseHttpHeader($buffer);
  206. try
  207. {
  208. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  209. }
  210. catch(\Exception $e)
  211. {
  212. echo $e;
  213. }
  214. $_GET = $_COOKIE = $_SERVER = array();
  215. }
  216. return 0;
  217. }
  218. // 如果是flash的policy-file-request
  219. elseif(0 === strpos($buffer,'<polic'))
  220. {
  221. if('>' != $buffer[strlen($buffer) - 1])
  222. {
  223. return 0;
  224. }
  225. $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";
  226. $connection->send($policy_xml, true);
  227. $connection->consumeRecvBuffer(strlen($buffer));
  228. return 0;
  229. }
  230. // 出错
  231. $connection->close();
  232. return 0;
  233. }
  234. /**
  235. * 从header中获取
  236. * @param string $buffer
  237. * @return void
  238. */
  239. protected function parseHttpHeader($buffer)
  240. {
  241. $header_data = explode("\r\n", $buffer);
  242. $_SERVER = array();
  243. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  244. unset($header_data[0]);
  245. foreach($header_data as $content)
  246. {
  247. // \r\n\r\n
  248. if(empty($content))
  249. {
  250. continue;
  251. }
  252. list($key, $value) = explode(':', $content, 2);
  253. $key = strtolower($key);
  254. $value = trim($value);
  255. switch($key)
  256. {
  257. // HTTP_HOST
  258. case 'host':
  259. $_SERVER['HTTP_HOST'] = $value;
  260. $tmp = explode(':', $value);
  261. $_SERVER['SERVER_NAME'] = $tmp[0];
  262. if(isset($tmp[1]))
  263. {
  264. $_SERVER['SERVER_PORT'] = $tmp[1];
  265. }
  266. break;
  267. // HTTP_COOKIE
  268. case 'cookie':
  269. $_SERVER['HTTP_COOKIE'] = $value;
  270. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  271. break;
  272. // HTTP_USER_AGENT
  273. case 'user-agent':
  274. $_SERVER['HTTP_USER_AGENT'] = $value;
  275. break;
  276. // HTTP_REFERER
  277. case 'referer':
  278. $_SERVER['HTTP_REFERER'] = $value;
  279. break;
  280. }
  281. }
  282. // QUERY_STRING
  283. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  284. if($_SERVER['QUERY_STRING'])
  285. {
  286. // $GET
  287. parse_str($_SERVER['QUERY_STRING'], $_GET);
  288. }
  289. else
  290. {
  291. $_SERVER['QUERY_STRING'] = '';
  292. }
  293. }
  294. }