blob: 9ff1105c2e65b03007c50a90d513d6d6185a8984 [file] [log] [blame]
Paul Stewarte6927402012-01-23 16:11:30 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Paul Stewartc2350ee2011-10-19 12:28:40 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "shill/dns_client.h"
6
7#include <arpa/inet.h>
8#include <netdb.h>
9#include <netinet/in.h>
10#include <sys/socket.h>
11
12#include <map>
13#include <set>
14#include <string>
15#include <tr1/memory>
16#include <vector>
17
Eric Shienbrood3e20a232012-02-16 11:35:56 -050018#include <base/bind.h>
19#include <base/bind_helpers.h>
20#include <base/stl_util.h>
Paul Stewartbdb02e62012-02-22 16:24:33 -080021#include <base/string_number_conversions.h>
Paul Stewartc2350ee2011-10-19 12:28:40 -070022
Christopher Wileyb691efd2012-08-09 13:51:51 -070023#include "shill/logging.h"
Darin Petkov89593a92012-02-21 10:59:48 +010024#include "shill/shill_ares.h"
25#include "shill/shill_time.h"
Paul Stewartc2350ee2011-10-19 12:28:40 -070026
Eric Shienbrood3e20a232012-02-16 11:35:56 -050027using base::Bind;
28using base::Unretained;
Paul Stewartc2350ee2011-10-19 12:28:40 -070029using std::map;
30using std::set;
31using std::string;
32using std::vector;
33
34namespace shill {
35
Paul Stewartc2350ee2011-10-19 12:28:40 -070036const char DNSClient::kErrorNoData[] = "The query response contains no answers";
37const char DNSClient::kErrorFormErr[] = "The server says the query is bad";
38const char DNSClient::kErrorServerFail[] = "The server says it had a failure";
39const char DNSClient::kErrorNotFound[] = "The queried-for domain was not found";
40const char DNSClient::kErrorNotImp[] = "The server doesn't implement operation";
41const char DNSClient::kErrorRefused[] = "The server replied, refused the query";
42const char DNSClient::kErrorBadQuery[] = "Locally we could not format a query";
43const char DNSClient::kErrorNetRefused[] = "The network connection was refused";
44const char DNSClient::kErrorTimedOut[] = "The network connection was timed out";
45const char DNSClient::kErrorUnknown[] = "DNS Resolver unknown internal error";
46
47// Private to the implementation of resolver so callers don't include ares.h
48struct DNSClientState {
Darin Petkove636c692012-05-31 10:22:17 +020049 DNSClientState() : channel(NULL), start_time((struct timeval){0}) {}
50
Paul Stewartc2350ee2011-10-19 12:28:40 -070051 ares_channel channel;
52 map< ares_socket_t, std::tr1::shared_ptr<IOHandler> > read_handlers;
53 map< ares_socket_t, std::tr1::shared_ptr<IOHandler> > write_handlers;
Darin Petkove636c692012-05-31 10:22:17 +020054 struct timeval start_time;
Paul Stewartc2350ee2011-10-19 12:28:40 -070055};
56
57DNSClient::DNSClient(IPAddress::Family family,
58 const string &interface_name,
59 const vector<string> &dns_servers,
60 int timeout_ms,
61 EventDispatcher *dispatcher,
Eric Shienbrood3e20a232012-02-16 11:35:56 -050062 const ClientCallback &callback)
Paul Stewartc2350ee2011-10-19 12:28:40 -070063 : address_(IPAddress(family)),
64 interface_name_(interface_name),
65 dns_servers_(dns_servers),
66 dispatcher_(dispatcher),
67 callback_(callback),
68 timeout_ms_(timeout_ms),
69 running_(false),
70 resolver_state_(NULL),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050071 weak_ptr_factory_(this),
Paul Stewartc2350ee2011-10-19 12:28:40 -070072 ares_(Ares::GetInstance()),
73 time_(Time::GetInstance()) {}
74
75DNSClient::~DNSClient() {
76 Stop();
77}
78
Paul Stewartbdb02e62012-02-22 16:24:33 -080079bool DNSClient::Start(const string &hostname, Error *error) {
Paul Stewartc2350ee2011-10-19 12:28:40 -070080 if (running_) {
Paul Stewartbdb02e62012-02-22 16:24:33 -080081 Error::PopulateAndLog(error, Error::kInProgress,
82 "Only one DNS request is allowed at a time");
Paul Stewartc2350ee2011-10-19 12:28:40 -070083 return false;
84 }
85
86 if (!resolver_state_.get()) {
87 struct ares_options options;
88 memset(&options, 0, sizeof(options));
89
90 vector<struct in_addr> server_addresses;
91 for (vector<string>::iterator it = dns_servers_.begin();
92 it != dns_servers_.end();
93 ++it) {
94 struct in_addr addr;
95 if (inet_aton(it->c_str(), &addr) != 0) {
96 server_addresses.push_back(addr);
97 }
98 }
99
100 if (server_addresses.empty()) {
Paul Stewartbdb02e62012-02-22 16:24:33 -0800101 Error::PopulateAndLog(error, Error::kInvalidArguments,
102 "No valid DNS server addresses");
Paul Stewartc2350ee2011-10-19 12:28:40 -0700103 return false;
104 }
105
106 options.servers = server_addresses.data();
107 options.nservers = server_addresses.size();
108 options.timeout = timeout_ms_;
109
110 resolver_state_.reset(new DNSClientState);
111 int status = ares_->InitOptions(&resolver_state_->channel,
112 &options,
113 ARES_OPT_SERVERS | ARES_OPT_TIMEOUTMS);
114 if (status != ARES_SUCCESS) {
Paul Stewartbdb02e62012-02-22 16:24:33 -0800115 Error::PopulateAndLog(error, Error::kOperationFailed,
116 "ARES initialization returns error code: " +
117 base::IntToString(status));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700118 resolver_state_.reset();
119 return false;
120 }
121
122 ares_->SetLocalDev(resolver_state_->channel, interface_name_.c_str());
123 }
124
125 running_ = true;
Darin Petkove636c692012-05-31 10:22:17 +0200126 time_->GetTimeMonotonic(&resolver_state_->start_time);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700127 ares_->GetHostByName(resolver_state_->channel, hostname.c_str(),
128 address_.family(), ReceiveDNSReplyCB, this);
129
130 if (!RefreshHandles()) {
131 LOG(ERROR) << "Impossibly short timeout.";
Paul Stewartbdb02e62012-02-22 16:24:33 -0800132 error->CopyFrom(error_);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700133 Stop();
134 return false;
135 }
136
137 return true;
138}
139
140void DNSClient::Stop() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700141 SLOG(DNS, 3) << "In " << __func__;
Paul Stewartc2350ee2011-10-19 12:28:40 -0700142 if (!resolver_state_.get()) {
143 return;
144 }
145
146 running_ = false;
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500147 weak_ptr_factory_.InvalidateWeakPtrs();
Paul Stewartbdb02e62012-02-22 16:24:33 -0800148 error_.Reset();
149 address_.SetAddressToDefault();
Paul Stewartc2350ee2011-10-19 12:28:40 -0700150 ares_->Destroy(resolver_state_->channel);
151 resolver_state_.reset();
152}
153
Paul Stewartbdb02e62012-02-22 16:24:33 -0800154// We delay our call to completion so that we exit all IOHandlers, and
155// can clean up all of our local state before calling the callback, or
156// during the process of the execution of the callee (which is free to
157// call our destructor safely).
158void DNSClient::HandleCompletion() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700159 SLOG(DNS, 3) << "In " << __func__;
Paul Stewartbdb02e62012-02-22 16:24:33 -0800160 Error error;
161 error.CopyFrom(error_);
162 IPAddress address(address_);
163 if (!error.IsSuccess()) {
164 // If the DNS request did not succeed, do not trust it for future
165 // attempts.
166 Stop();
167 } else {
168 // Prepare our state for the next request without destroying the
169 // current ARES state.
170 error_.Reset();
171 address_.SetAddressToDefault();
172 }
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500173 callback_.Run(error, address);
Paul Stewartbdb02e62012-02-22 16:24:33 -0800174}
175
Paul Stewartc2350ee2011-10-19 12:28:40 -0700176void DNSClient::HandleDNSRead(int fd) {
177 ares_->ProcessFd(resolver_state_->channel, fd, ARES_SOCKET_BAD);
178 RefreshHandles();
179}
180
181void DNSClient::HandleDNSWrite(int fd) {
182 ares_->ProcessFd(resolver_state_->channel, ARES_SOCKET_BAD, fd);
183 RefreshHandles();
184}
185
186void DNSClient::HandleTimeout() {
187 ares_->ProcessFd(resolver_state_->channel, ARES_SOCKET_BAD, ARES_SOCKET_BAD);
Paul Stewartbdb02e62012-02-22 16:24:33 -0800188 RefreshHandles();
Paul Stewartc2350ee2011-10-19 12:28:40 -0700189}
190
191void DNSClient::ReceiveDNSReply(int status, struct hostent *hostent) {
192 if (!running_) {
193 // We can be called during ARES shutdown -- ignore these events.
194 return;
195 }
Ben Chanfad4a0b2012-04-18 15:49:59 -0700196 SLOG(DNS, 3) << "In " << __func__;
Paul Stewartc2350ee2011-10-19 12:28:40 -0700197 running_ = false;
Paul Stewartf582b502012-04-04 21:39:22 -0700198 timeout_closure_.Cancel();
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500199 dispatcher_->PostTask(Bind(&DNSClient::HandleCompletion,
200 weak_ptr_factory_.GetWeakPtr()));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700201
202 if (status == ARES_SUCCESS &&
203 hostent != NULL &&
204 hostent->h_addrtype == address_.family() &&
Eric Shienbroodc74cf9c2012-03-02 15:00:35 -0500205 static_cast<size_t>(hostent->h_length) ==
206 IPAddress::GetAddressLength(address_.family()) &&
Paul Stewartc2350ee2011-10-19 12:28:40 -0700207 hostent->h_addr_list != NULL &&
208 hostent->h_addr_list[0] != NULL) {
209 address_ = IPAddress(address_.family(),
210 ByteString(reinterpret_cast<unsigned char *>(
211 hostent->h_addr_list[0]), hostent->h_length));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700212 } else {
213 switch (status) {
214 case ARES_ENODATA:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800215 error_.Populate(Error::kOperationFailed, kErrorNoData);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700216 break;
217 case ARES_EFORMERR:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800218 error_.Populate(Error::kOperationFailed, kErrorFormErr);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700219 break;
220 case ARES_ESERVFAIL:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800221 error_.Populate(Error::kOperationFailed, kErrorServerFail);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700222 break;
223 case ARES_ENOTFOUND:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800224 error_.Populate(Error::kOperationFailed, kErrorNotFound);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700225 break;
226 case ARES_ENOTIMP:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800227 error_.Populate(Error::kOperationFailed, kErrorNotImp);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700228 break;
229 case ARES_EREFUSED:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800230 error_.Populate(Error::kOperationFailed, kErrorRefused);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700231 break;
232 case ARES_EBADQUERY:
233 case ARES_EBADNAME:
234 case ARES_EBADFAMILY:
235 case ARES_EBADRESP:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800236 error_.Populate(Error::kOperationFailed, kErrorBadQuery);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700237 break;
238 case ARES_ECONNREFUSED:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800239 error_.Populate(Error::kOperationFailed, kErrorNetRefused);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700240 break;
241 case ARES_ETIMEOUT:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800242 error_.Populate(Error::kOperationTimeout, kErrorTimedOut);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700243 break;
244 default:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800245 error_.Populate(Error::kOperationFailed, kErrorUnknown);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700246 if (status == ARES_SUCCESS) {
247 LOG(ERROR) << "ARES returned success but hostent was invalid!";
248 } else {
249 LOG(ERROR) << "ARES returned unhandled error status " << status;
250 }
251 break;
252 }
Paul Stewartc2350ee2011-10-19 12:28:40 -0700253 }
254}
255
256void DNSClient::ReceiveDNSReplyCB(void *arg, int status,
257 int /*timeouts*/,
258 struct hostent *hostent) {
259 DNSClient *res = static_cast<DNSClient *>(arg);
260 res->ReceiveDNSReply(status, hostent);
261}
262
263bool DNSClient::RefreshHandles() {
264 map< ares_socket_t, std::tr1::shared_ptr<IOHandler> > old_read =
265 resolver_state_->read_handlers;
266 map< ares_socket_t, std::tr1::shared_ptr<IOHandler> > old_write =
267 resolver_state_->write_handlers;
268
269 resolver_state_->read_handlers.clear();
270 resolver_state_->write_handlers.clear();
271
272 ares_socket_t sockets[ARES_GETSOCK_MAXNUM];
273 int action_bits = ares_->GetSock(resolver_state_->channel, sockets,
Paul Stewartbdb02e62012-02-22 16:24:33 -0800274 ARES_GETSOCK_MAXNUM);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700275
Paul Stewartf582b502012-04-04 21:39:22 -0700276 base::Callback<void(int)> read_callback(
277 Bind(&DNSClient::HandleDNSRead, weak_ptr_factory_.GetWeakPtr()));
278 base::Callback<void(int)> write_callback(
279 Bind(&DNSClient::HandleDNSWrite, weak_ptr_factory_.GetWeakPtr()));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700280 for (int i = 0; i < ARES_GETSOCK_MAXNUM; i++) {
281 if (ARES_GETSOCK_READABLE(action_bits, i)) {
282 if (ContainsKey(old_read, sockets[i])) {
283 resolver_state_->read_handlers[sockets[i]] = old_read[sockets[i]];
284 } else {
285 resolver_state_->read_handlers[sockets[i]] =
286 std::tr1::shared_ptr<IOHandler> (
287 dispatcher_->CreateReadyHandler(sockets[i],
288 IOHandler::kModeInput,
Paul Stewartf582b502012-04-04 21:39:22 -0700289 read_callback));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700290 }
291 }
292 if (ARES_GETSOCK_WRITABLE(action_bits, i)) {
293 if (ContainsKey(old_write, sockets[i])) {
294 resolver_state_->write_handlers[sockets[i]] = old_write[sockets[i]];
295 } else {
296 resolver_state_->write_handlers[sockets[i]] =
297 std::tr1::shared_ptr<IOHandler> (
298 dispatcher_->CreateReadyHandler(sockets[i],
299 IOHandler::kModeOutput,
Paul Stewartf582b502012-04-04 21:39:22 -0700300 write_callback));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700301 }
302 }
303 }
304
305 if (!running_) {
Paul Stewartbdb02e62012-02-22 16:24:33 -0800306 // We are here just to clean up socket handles, and the ARES state was
307 // cleaned up during the last call to ares_->ProcessFd().
Paul Stewartc2350ee2011-10-19 12:28:40 -0700308 return false;
309 }
310
311 // Schedule timer event for the earlier of our timeout or one requested by
312 // the resolver library.
313 struct timeval now, elapsed_time, timeout_tv;
Paul Stewarte6927402012-01-23 16:11:30 -0800314 time_->GetTimeMonotonic(&now);
Darin Petkove636c692012-05-31 10:22:17 +0200315 timersub(&now, &resolver_state_->start_time, &elapsed_time);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700316 timeout_tv.tv_sec = timeout_ms_ / 1000;
317 timeout_tv.tv_usec = (timeout_ms_ % 1000) * 1000;
Paul Stewartf582b502012-04-04 21:39:22 -0700318 timeout_closure_.Cancel();
Paul Stewartbdb02e62012-02-22 16:24:33 -0800319
Paul Stewartc2350ee2011-10-19 12:28:40 -0700320 if (timercmp(&elapsed_time, &timeout_tv, >=)) {
321 // There are 3 cases of interest:
Paul Stewartbdb02e62012-02-22 16:24:33 -0800322 // - If we got here from Start(), when we return, Stop() will be
323 // called, so our cleanup task will not run, so we will not have the
324 // side-effect of both invoking the callback and returning False
325 // in Start().
326 // - If we got here from the tail of an IO event, we can't call
327 // Stop() since that will blow away the IOHandler we are running
328 // in. We will perform the cleanup in the posted task below.
329 // - If we got here from a timeout handler, we will perform cleanup
330 // in the posted task.
Paul Stewartc2350ee2011-10-19 12:28:40 -0700331 running_ = false;
Paul Stewartbdb02e62012-02-22 16:24:33 -0800332 error_.Populate(Error::kOperationTimeout, kErrorTimedOut);
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500333 dispatcher_->PostTask(Bind(&DNSClient::HandleCompletion,
334 weak_ptr_factory_.GetWeakPtr()));
Paul Stewartc2350ee2011-10-19 12:28:40 -0700335 return false;
336 } else {
337 struct timeval max, ret_tv;
338 timersub(&timeout_tv, &elapsed_time, &max);
339 struct timeval *tv = ares_->Timeout(resolver_state_->channel,
340 &max, &ret_tv);
Paul Stewartf582b502012-04-04 21:39:22 -0700341 timeout_closure_.Reset(
342 Bind(&DNSClient::HandleTimeout, weak_ptr_factory_.GetWeakPtr()));
343 dispatcher_->PostDelayedTask(timeout_closure_.callback(),
344 tv->tv_sec * 1000 + tv->tv_usec / 1000);
Paul Stewartc2350ee2011-10-19 12:28:40 -0700345 }
346
347 return true;
348}
349
350} // namespace shill