1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "ResolverController"
18 #define DBG 0
19 
20 #include <algorithm>
21 #include <cstdlib>
22 #include <string>
23 #include <vector>
24 #include <cutils/log.h>
25 #include <net/if.h>
26 #include <sys/socket.h>
27 #include <netdb.h>
28 
29 // NOTE: <resolv_netid.h> is a private C library header that provides
30 //       declarations for _resolv_set_nameservers_for_net and
31 //       _resolv_flush_cache_for_net
32 #include <resolv_netid.h>
33 #include <resolv_params.h>
34 #include <resolv_stats.h>
35 
36 #include <android-base/strings.h>
37 #include <android/net/INetd.h>
38 
39 #include "DumpWriter.h"
40 #include "ResolverController.h"
41 #include "ResolverStats.h"
42 
setDnsServers(unsigned netId,const char * searchDomains,const char ** servers,int numservers,const __res_params * params)43 int ResolverController::setDnsServers(unsigned netId, const char* searchDomains,
44         const char** servers, int numservers, const __res_params* params) {
45     if (DBG) {
46         ALOGD("setDnsServers netId = %u\n", netId);
47     }
48     return -_resolv_set_nameservers_for_net(netId, servers, numservers, searchDomains, params);
49 }
50 
clearDnsServers(unsigned netId)51 int ResolverController::clearDnsServers(unsigned netId) {
52     _resolv_set_nameservers_for_net(netId, NULL, 0, "", NULL);
53     if (DBG) {
54         ALOGD("clearDnsServers netId = %u\n", netId);
55     }
56     return 0;
57 }
58 
flushDnsCache(unsigned netId)59 int ResolverController::flushDnsCache(unsigned netId) {
60     if (DBG) {
61         ALOGD("flushDnsCache netId = %u\n", netId);
62     }
63 
64     _resolv_flush_cache_for_net(netId);
65 
66     return 0;
67 }
68 
getDnsInfo(unsigned netId,std::vector<std::string> * servers,std::vector<std::string> * domains,__res_params * params,std::vector<android::net::ResolverStats> * stats)69 int ResolverController::getDnsInfo(unsigned netId, std::vector<std::string>* servers,
70         std::vector<std::string>* domains, __res_params* params,
71         std::vector<android::net::ResolverStats>* stats) {
72     using android::net::ResolverStats;
73     using android::net::INetd;
74     static_assert(ResolverStats::STATS_SUCCESSES == INetd::RESOLVER_STATS_SUCCESSES &&
75             ResolverStats::STATS_ERRORS == INetd::RESOLVER_STATS_ERRORS &&
76             ResolverStats::STATS_TIMEOUTS == INetd::RESOLVER_STATS_TIMEOUTS &&
77             ResolverStats::STATS_INTERNAL_ERRORS == INetd::RESOLVER_STATS_INTERNAL_ERRORS &&
78             ResolverStats::STATS_RTT_AVG == INetd::RESOLVER_STATS_RTT_AVG &&
79             ResolverStats::STATS_LAST_SAMPLE_TIME == INetd::RESOLVER_STATS_LAST_SAMPLE_TIME &&
80             ResolverStats::STATS_USABLE == INetd::RESOLVER_STATS_USABLE &&
81             ResolverStats::STATS_COUNT == INetd::RESOLVER_STATS_COUNT,
82             "AIDL and ResolverStats.h out of sync");
83     int nscount = -1;
84     sockaddr_storage res_servers[MAXNS];
85     int dcount = -1;
86     char res_domains[MAXDNSRCH][MAXDNSRCHPATH];
87     __res_stats res_stats[MAXNS];
88     servers->clear();
89     domains->clear();
90     *params = __res_params{};
91     stats->clear();
92     int revision_id = android_net_res_stats_get_info_for_net(netId, &nscount, res_servers, &dcount,
93             res_domains, params, res_stats);
94 
95     // If the netId is unknown (which can happen for valid net IDs for which no DNS servers have
96     // yet been configured), there is no revision ID. In this case there is no data to return.
97     if (revision_id < 0) {
98         return 0;
99     }
100 
101     // Verify that the returned data is sane.
102     if (nscount < 0 || nscount > MAXNS || dcount < 0 || dcount > MAXDNSRCH) {
103         ALOGE("%s: nscount=%d, dcount=%d", __FUNCTION__, nscount, dcount);
104         return -ENOTRECOVERABLE;
105     }
106 
107     // Determine which servers are considered usable by the resolver.
108     bool valid_servers[MAXNS];
109     std::fill_n(valid_servers, MAXNS, false);
110     android_net_res_stats_get_usable_servers(params, res_stats, nscount, valid_servers);
111 
112     // Convert the server sockaddr structures to std::string.
113     stats->resize(nscount);
114     for (int i = 0 ; i < nscount ; ++i) {
115         char hbuf[NI_MAXHOST];
116         int rv = getnameinfo(reinterpret_cast<const sockaddr*>(&res_servers[i]),
117                 sizeof(res_servers[i]), hbuf, sizeof(hbuf), nullptr, 0, NI_NUMERICHOST);
118         std::string server_str;
119         if (rv == 0) {
120             server_str.assign(hbuf);
121         } else {
122             ALOGE("getnameinfo() failed for server #%d: %s", i, gai_strerror(rv));
123             server_str.assign("<invalid>");
124         }
125         servers->push_back(std::move(server_str));
126         android::net::ResolverStats& cur_stats = (*stats)[i];
127         android_net_res_stats_aggregate(&res_stats[i], &cur_stats.successes, &cur_stats.errors,
128                 &cur_stats.timeouts, &cur_stats.internal_errors, &cur_stats.rtt_avg,
129                 &cur_stats.last_sample_time);
130         cur_stats.usable = valid_servers[i];
131     }
132 
133     // Convert the stack-allocated search domain strings to std::string.
134     for (int i = 0 ; i < dcount ; ++i) {
135         domains->push_back(res_domains[i]);
136     }
137     return 0;
138 }
139 
setResolverConfiguration(int32_t netId,const std::vector<std::string> & servers,const std::vector<std::string> & domains,const std::vector<int32_t> & params)140 int ResolverController::setResolverConfiguration(int32_t netId,
141         const std::vector<std::string>& servers, const std::vector<std::string>& domains,
142         const std::vector<int32_t>& params) {
143     using android::net::INetd;
144     if (params.size() != INetd::RESOLVER_PARAMS_COUNT) {
145         ALOGE("%s: params.size()=%zu", __FUNCTION__, params.size());
146         return -EINVAL;
147     }
148 
149     auto server_count = std::min<size_t>(MAXNS, servers.size());
150     std::vector<const char*> server_ptrs;
151     for (size_t i = 0 ; i < server_count ; ++i) {
152         server_ptrs.push_back(servers[i].c_str());
153     }
154 
155     std::string domains_str;
156     if (!domains.empty()) {
157         domains_str = domains[0];
158         for (size_t i = 1 ; i < domains.size() ; ++i) {
159             domains_str += " " + domains[i];
160         }
161     }
162 
163     __res_params res_params;
164     res_params.sample_validity = params[INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY];
165     res_params.success_threshold = params[INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD];
166     res_params.min_samples = params[INetd::RESOLVER_PARAMS_MIN_SAMPLES];
167     res_params.max_samples = params[INetd::RESOLVER_PARAMS_MAX_SAMPLES];
168 
169     return setDnsServers(netId, domains_str.c_str(), server_ptrs.data(), server_ptrs.size(),
170             &res_params);
171 }
172 
getResolverInfo(int32_t netId,std::vector<std::string> * servers,std::vector<std::string> * domains,std::vector<int32_t> * params,std::vector<int32_t> * stats)173 int ResolverController::getResolverInfo(int32_t netId, std::vector<std::string>* servers,
174         std::vector<std::string>* domains, std::vector<int32_t>* params,
175         std::vector<int32_t>* stats) {
176     using android::net::ResolverStats;
177     using android::net::INetd;
178     __res_params res_params;
179     std::vector<ResolverStats> res_stats;
180     int ret = getDnsInfo(netId, servers, domains, &res_params, &res_stats);
181     if (ret != 0) {
182         return ret;
183     }
184 
185     // Serialize the information for binder.
186     ResolverStats::encodeAll(res_stats, stats);
187 
188     params->resize(INetd::RESOLVER_PARAMS_COUNT);
189     (*params)[INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY] = res_params.sample_validity;
190     (*params)[INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD] = res_params.success_threshold;
191     (*params)[INetd::RESOLVER_PARAMS_MIN_SAMPLES] = res_params.min_samples;
192     (*params)[INetd::RESOLVER_PARAMS_MAX_SAMPLES] = res_params.max_samples;
193     return 0;
194 }
195 
dump(DumpWriter & dw,unsigned netId)196 void ResolverController::dump(DumpWriter& dw, unsigned netId) {
197     // No lock needed since Bionic's resolver locks all accessed data structures internally.
198     using android::net::ResolverStats;
199     std::vector<std::string> servers;
200     std::vector<std::string> domains;
201     __res_params params;
202     std::vector<ResolverStats> stats;
203     time_t now = time(nullptr);
204     int rv = getDnsInfo(netId, &servers, &domains, &params, &stats);
205     dw.incIndent();
206     if (rv != 0) {
207         dw.println("getDnsInfo() failed for netid %u", netId);
208     } else {
209         if (servers.empty()) {
210             dw.println("No DNS servers defined");
211         } else {
212             dw.println("DNS servers: # IP (total, successes, errors, timeouts, internal errors, "
213                     "RTT avg, last sample)");
214             dw.incIndent();
215             for (size_t i = 0 ; i < servers.size() ; ++i) {
216                 if (i < stats.size()) {
217                     const ResolverStats& s = stats[i];
218                     int total = s.successes + s.errors + s.timeouts + s.internal_errors;
219                     if (total > 0) {
220                         int time_delta = (s.last_sample_time > 0) ? now - s.last_sample_time : -1;
221                         dw.println("%s (%d, %d, %d, %d, %d, %dms, %ds)%s", servers[i].c_str(),
222                                 total, s.successes, s.errors, s.timeouts, s.internal_errors,
223                                 s.rtt_avg, time_delta, s.usable ? "" : " BROKEN");
224                     } else {
225                         dw.println("%s <no data>", servers[i].c_str());
226                     }
227                 } else {
228                     dw.println("%s <no stats>", servers[i].c_str());
229                 }
230             }
231             dw.decIndent();
232         }
233         if (domains.empty()) {
234             dw.println("No search domains defined");
235         } else {
236             std::string domains_str = android::base::Join(domains, ", ");
237             dw.println("search domains: %s", domains_str.c_str());
238         }
239         if (params.sample_validity != 0) {
240             dw.println("DNS parameters: sample validity = %us, success threshold = %u%%, "
241                     "samples (min, max) = (%u, %u)", params.sample_validity,
242                     static_cast<unsigned>(params.success_threshold),
243                     static_cast<unsigned>(params.min_samples),
244                     static_cast<unsigned>(params.max_samples));
245         }
246     }
247     dw.decIndent();
248 }
249