Websocket.php 9.8 KB

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