Websocket.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. // 还没握手不能发数据
  129. if(empty($connection->handshake))
  130. {
  131. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Send data before handshake. ", true);
  132. $connection->close();
  133. return false;
  134. }
  135. $first_byte = $connection->websocketType;
  136. if($len<=125)
  137. {
  138. return $first_byte.chr($len).$buffer;
  139. }
  140. else if($len<=65535)
  141. {
  142. return $first_byte.chr(126).pack("n", $len).$buffer;
  143. }
  144. else
  145. {
  146. return $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  147. }
  148. }
  149. /**
  150. * 解包
  151. * @param string $buffer
  152. * @return string
  153. */
  154. public static function decode($buffer, ConnectionInterface $connection)
  155. {
  156. $len = $masks = $data = $decoded = null;
  157. $len = ord($buffer[1]) & 127;
  158. if ($len === 126) {
  159. $masks = substr($buffer, 4, 4);
  160. $data = substr($buffer, 8);
  161. } else if ($len === 127) {
  162. $masks = substr($buffer, 10, 4);
  163. $data = substr($buffer, 14);
  164. } else {
  165. $masks = substr($buffer, 2, 4);
  166. $data = substr($buffer, 6);
  167. }
  168. for ($index = 0; $index < strlen($data); $index++) {
  169. $decoded .= $data[$index] ^ $masks[$index % 4];
  170. }
  171. return $decoded;
  172. }
  173. /**
  174. * 处理websocket握手
  175. * @param string $buffer
  176. * @param TcpConnection $connection
  177. * @return int
  178. */
  179. protected static function dealHandshake($buffer, $connection)
  180. {
  181. // 握手阶段客户端发送HTTP协议
  182. if(0 === strpos($buffer, 'GET'))
  183. {
  184. // 判断\r\n\r\n边界
  185. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  186. if(!$heder_end_pos)
  187. {
  188. return 0;
  189. }
  190. // 解析Sec-WebSocket-Key
  191. $Sec_WebSocket_Key = '';
  192. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $buffer, $match))
  193. {
  194. $Sec_WebSocket_Key = $match[1];
  195. }
  196. else
  197. {
  198. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found", true);
  199. $connection->close();
  200. return 0;
  201. }
  202. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  203. // 握手返回的数据
  204. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  205. $new_message .= "Upgrade: websocket\r\n";
  206. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  207. $new_message .= "Connection: Upgrade\r\n";
  208. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  209. $connection->handshake = true;
  210. $connection->consumeRecvBuffer(strlen($buffer));
  211. $connection->send($new_message, true);
  212. // blob or arraybuffer
  213. $connection->websocketType = self::BINARY_TYPE_BLOB;
  214. // 如果有设置onWebSocketConnect回调,尝试执行
  215. if(isset($connection->onWebSocketConnect))
  216. {
  217. self::parseHttpHeader($buffer);
  218. try
  219. {
  220. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  221. }
  222. catch(\Exception $e)
  223. {
  224. echo $e;
  225. }
  226. $_GET = $_COOKIE = $_SERVER = array();
  227. }
  228. return 0;
  229. }
  230. // 如果是flash的policy-file-request
  231. elseif(0 === strpos($buffer,'<polic'))
  232. {
  233. $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";
  234. $connection->send($policy_xml, true);
  235. $connection->consumeRecvBuffer(strlen($buffer));
  236. return 0;
  237. }
  238. // 出错
  239. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
  240. $connection->close();
  241. return 0;
  242. }
  243. /**
  244. * 从header中获取
  245. * @param string $buffer
  246. * @return void
  247. */
  248. protected static function parseHttpHeader($buffer)
  249. {
  250. $header_data = explode("\r\n", $buffer);
  251. $_SERVER = array();
  252. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  253. unset($header_data[0]);
  254. foreach($header_data as $content)
  255. {
  256. // \r\n\r\n
  257. if(empty($content))
  258. {
  259. continue;
  260. }
  261. list($key, $value) = explode(':', $content, 2);
  262. $key = strtolower($key);
  263. $value = trim($value);
  264. switch($key)
  265. {
  266. // HTTP_HOST
  267. case 'host':
  268. $_SERVER['HTTP_HOST'] = $value;
  269. $tmp = explode(':', $value);
  270. $_SERVER['SERVER_NAME'] = $tmp[0];
  271. if(isset($tmp[1]))
  272. {
  273. $_SERVER['SERVER_PORT'] = $tmp[1];
  274. }
  275. break;
  276. // HTTP_COOKIE
  277. case 'cookie':
  278. $_SERVER['HTTP_COOKIE'] = $value;
  279. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  280. break;
  281. // HTTP_USER_AGENT
  282. case 'user-agent':
  283. $_SERVER['HTTP_USER_AGENT'] = $value;
  284. break;
  285. // HTTP_REFERER
  286. case 'referer':
  287. $_SERVER['HTTP_REFERER'] = $value;
  288. break;
  289. case 'origin':
  290. $_SERVER['HTTP_ORIGIN'] = $value;
  291. break;
  292. }
  293. }
  294. // QUERY_STRING
  295. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  296. if($_SERVER['QUERY_STRING'])
  297. {
  298. // $GET
  299. parse_str($_SERVER['QUERY_STRING'], $_GET);
  300. }
  301. else
  302. {
  303. $_SERVER['QUERY_STRING'] = '';
  304. }
  305. }
  306. }