Android HttpDns:我的域名我做主

作者: JackMeGo | 来源:发表于2016-12-23 16:59 被阅读0次
    域名劫持

    之前公司的产品遇到了用户忽然无法登陆使用的问题,后来查明是因为在用户发布的内容里有一张被判定为黄图的图片,导致我们的域名被运营商封锁。还有一种情况,部分地区的用户使用我们的产品时页面上被莫名插入了广告,后来发现也是运营商搞的鬼,劫持了我们的网站数据,并私自插入了广告。这里暴露出了依赖网络运营商进行域名解析的一些问题,总结如下:

    1. 域名封锁。运营商可以因为各种理由封锁你的域名,导致所有请求你的网站的请求都因为无法解析域名而失败。
    2. 域名劫持。运营商可以根据你访问的域名进行有针对性的广告注入,有损产品的用户体验。

    为了避免自己的命运被其他人操纵的局面,我们采用了HttpDns技术来绕开运营商的控制,解决这类问题。

    HttpDns是一种通过Http服务器提供域名解析功能的技术,通过向Http服务器的80端口进行请求,代替传统的DNS服务器的53端口进行请求。利用这种技术,我们直接向我们信赖的Http服务器(我们自己搭建的,或是第三方提供的)询问我们要访问的域名对应的IP,而不再依赖网络运营商进行域名解析,从而解决了上面两个问题。接下来介绍一下HttpDns技术的使用。

    HttpDns第三方服务主要有两个提供商:
    DNSPod D+
    阿里云 HttpDns

    以DNSPod D+为例介绍HttpDns的使用。数据请求和应答均使用 http 协议。
    请求格式为:

    http://119.29.29.29/d?dn=www.chunyuyisheng.com

    dn表示要查询的域名。该请求返回以分号分隔的ip地址,如下:

    106.75.8.170;106.75.28.177

    如果查询失败返回空结果。

    我们发送网络请求使用的是OkHttp库,可以通过OkHttpClient的setDns方法实现默认Dns的替换,代码如下:
    首先继承默认的Dns,重写lookup方法:

    public class HttpDns implements Dns {    
        // 需要进行httpdns处理转换的host列表,这里我们只对部分跟我们公司服务相关的域名
        // 利用HttpDns进行解析,其他的还是用默认的域名解析方式    
        private CopyOnWriteArrayList<String> mHostList;    
        public HttpDns(List<String> hostList) {        
            mHostList = new CopyOnWriteArrayList<>();        
            mHostList.addAll(hostList);    
        }    
    
        @Override    
        public List<InetAddress> lookup(String hostname) throws UnknownHostException {        
            if (hostname == null) {            
                throw new UnknownHostException("host == null");        
            } else {            
                if (mHostList != null && mHostList.contains(hostname)) {                
                    try {                    
                        String ipAddr = HttpDnsHelper.getInstance().getIpStrForHost(hostname);                    
                        if (!TextUtils.isEmpty(ipAddr)) {                        
                            List<InetAddress> addresses = new ArrayList<>();                        
                            addresses.add(InetAddress.getByName(ipAddr));                        
                            Log.d("httpdns", "HttpDns hint, host:" + hostname + "  ip:" + ipAddr);                        
                            return addresses;                    
                        }                
                    } catch (Exception ignored) {}            
                  }            
    
                //未能从httpdns获取ip地址,使用系统dns获取            
                return SYSTEM.lookup(hostname);        
            }    
        }
    }
    

    在lookup代码中,我们先判断要查找的hostname是不是在指定列表中,如果在里面,我们就通过HttpDns请求其ip地址,否则用默认的dns进行解析。HttpDns请求的过程通过函数getIpStrForHost实现,该函数如下:

    private Map<String, DnsInfo> mDnsMap;
    public String getIpStrForHost(String host) {    
        if (!TextUtils.isEmpty(host)) {        
            DnsInfo dnsInfo = mDnsMap.get(host);        
            if (dnsInfo != null && dnsInfo.isIpValid() && !dnsInfo.isExpired()) {            
                //如果可以获得合法的dns info,返回ip str            
                return dnsInfo.getIpStr();        
            } else {            
                //无法获得合法的dns info, 异步更新host对应的cache            
                updateCacheForHost(host);        
            }
        }    
    return null;
    }
    

    这里对HttpDns的结果使用了缓存机制,首先判断是否已经缓存了该host的ip地址,如果是,并且没过期,直接从缓存获取;否则重新获取并更新缓存。进行HttpDns请求并更新缓存的代码在updateCacheForHost中:

    public void updateCacheForHost(final String host) {
        String url = String.format("http://119.29.29.29/d?dn=%s&ttl=1", host);      
        Request request = new Request.Builder().url(url).build();    
        mOkHttpClient.newCall(request).enqueue(new Callback() {        
            @Override        
            public void onFailure(Request request, IOException e) {            
                Log.d("httpdns", "get ip for host(" + host + ") failed");        
            }        
            @Override        
            public void onResponse(Response response) throws IOException {            
                InputStream inputStream = response.body().byteStream();            
                String data = readInputStream(inputStream);            
                Log.d("httpdns", "get ip for host(" + host + ") success :" + data);            
                DnsInfo dnsInfo = parseResponseString(host, data);            
                if (dnsInfo != null) {                
                    mDnsMap.put(host, dnsInfo);                
                }
            }
        });
    }
    

    通过一个异步请求,发送Http请求到HttpDns服务器,返回ip地址,得到域名对应的ip地址,完成Dns过程,并更新本地缓存。

    最后将这个改进后的HttpDns替换掉OkHttpClient默认的dns,完成OkHttp新dns的设置:

    okHttpClient.setDns(new HttpDns(getHttpDnsHost(context)));
    

    参考:
    http://blog.csdn.net/sbsujjbcy/article/details/50532797
    http://mp.weixin.qq.com/s?__biz=MzA3ODgyNzcwMw==&mid=201837080&idx=1&sn=b2a152b84df1c7dbd294ea66037cf262&scene=2&from=timeline&isappinstalled=0&utm_source=tuicool
    http://blog.csdn.net/charleslei/article/details/41154139

    相关文章

      网友评论

        本文标题:Android HttpDns:我的域名我做主

        本文链接:https://www.haomeiwen.com/subject/clptvttx.html