Websocket.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. else
  190. {
  191. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found", true);
  192. $connection->close();
  193. return 0;
  194. }
  195. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  196. // 握手返回的数据
  197. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  198. $new_message .= "Upgrade: websocket\r\n";
  199. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  200. $new_message .= "Connection: Upgrade\r\n";
  201. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  202. $connection->handshake = true;
  203. $connection->consumeRecvBuffer(strlen($buffer));
  204. $connection->send($new_message, true);
  205. $connection->protocolData = array(
  206. 'binaryType' => self::BINARY_TYPE_BLOB, // blob or arraybuffer
  207. );
  208. // 如果有设置onWebSocketConnect回调,尝试执行
  209. if(isset($connection->onWebSocketConnect))
  210. {
  211. self::parseHttpHeader($buffer);
  212. try
  213. {
  214. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  215. }
  216. catch(\Exception $e)
  217. {
  218. echo $e;
  219. }
  220. $_GET = $_COOKIE = $_SERVER = array();
  221. }
  222. return 0;
  223. }
  224. // 如果是flash的policy-file-request
  225. elseif(0 === strpos($buffer,'<polic'))
  226. {
  227. $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";
  228. $connection->send($policy_xml, true);
  229. $connection->consumeRecvBuffer(strlen($buffer));
  230. return 0;
  231. }
  232. // 出错
  233. $connection->close();
  234. return 0;
  235. }
  236. /**
  237. * 从header中获取
  238. * @param string $buffer
  239. * @return void
  240. */
  241. protected static function parseHttpHeader($buffer)
  242. {
  243. $header_data = explode("\r\n", $buffer);
  244. $_SERVER = array();
  245. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  246. unset($header_data[0]);
  247. foreach($header_data as $content)
  248. {
  249. // \r\n\r\n
  250. if(empty($content))
  251. {
  252. continue;
  253. }
  254. list($key, $value) = explode(':', $content, 2);
  255. $key = strtolower($key);
  256. $value = trim($value);
  257. switch($key)
  258. {
  259. // HTTP_HOST
  260. case 'host':
  261. $_SERVER['HTTP_HOST'] = $value;
  262. $tmp = explode(':', $value);
  263. $_SERVER['SERVER_NAME'] = $tmp[0];
  264. if(isset($tmp[1]))
  265. {
  266. $_SERVER['SERVER_PORT'] = $tmp[1];
  267. }
  268. break;
  269. // HTTP_COOKIE
  270. case 'cookie':
  271. $_SERVER['HTTP_COOKIE'] = $value;
  272. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  273. break;
  274. // HTTP_USER_AGENT
  275. case 'user-agent':
  276. $_SERVER['HTTP_USER_AGENT'] = $value;
  277. break;
  278. // HTTP_REFERER
  279. case 'referer':
  280. $_SERVER['HTTP_REFERER'] = $value;
  281. break;
  282. case 'origin':
  283. $_SERVER['HTTP_ORIGIN'] = $value;
  284. break;
  285. }
  286. }
  287. // QUERY_STRING
  288. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  289. if($_SERVER['QUERY_STRING'])
  290. {
  291. // $GET
  292. parse_str($_SERVER['QUERY_STRING'], $_GET);
  293. }
  294. else
  295. {
  296. $_SERVER['QUERY_STRING'] = '';
  297. }
  298. }
  299. }