blob: 809f42832327a9db14bcec52872121ac9c4e55c9 [file] [log] [blame]
[email protected]245b164e2013-06-13 22:31:421// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/dns/mdns_client_impl.h"
6
kmarshall3e740be2015-03-02 21:30:447#include <algorithm>
Peter Boström8a7540692021-04-05 20:48:208#include <memory>
dchengc7eeda422015-12-26 03:56:489#include <utility>
vitalybuka20859742014-09-22 23:42:3010
[email protected]245b164e2013-06-13 22:31:4211#include "base/bind.h"
skyostil4891b25b2015-06-11 11:43:4512#include "base/location.h"
Piotr Pawliczek3318cc92020-07-25 05:10:1313#include "base/strings/string_util.h"
Patrick Monette643cdf62021-10-15 19:13:4214#include "base/task/single_thread_task_runner.h"
gabf767595f2016-05-11 18:50:3515#include "base/threading/thread_task_runner_handle.h"
kmarshall3e740be2015-03-02 21:30:4416#include "base/time/clock.h"
[email protected]245b164e2013-06-13 22:31:4217#include "base/time/default_clock.h"
prashhird22b4a82014-09-17 17:27:2718#include "base/time/time.h"
kmarshall3e740be2015-03-02 21:30:4419#include "base/timer/timer.h"
[email protected]245b164e2013-06-13 22:31:4220#include "net/base/net_errors.h"
[email protected]245b164e2013-06-13 22:31:4221#include "net/base/rand_callback.h"
tfarina77021d62015-10-11 20:19:0322#include "net/dns/dns_util.h"
Eric Orth8afaf152018-11-07 21:01:2623#include "net/dns/public/dns_protocol.h"
Eric Orth1556c382018-11-08 06:05:0224#include "net/dns/public/util.h"
[email protected]21df16962013-07-01 17:39:5325#include "net/dns/record_rdata.h"
tfarina5dd13c22016-11-16 12:08:2626#include "net/socket/datagram_socket.h"
[email protected]245b164e2013-06-13 22:31:4227
[email protected]21df16962013-07-01 17:39:5328// TODO(gene): Remove this temporary method of disabling NSEC support once it
29// becomes clear whether this feature should be
30// supported. http://crbug.com/255232
31#define ENABLE_NSEC
32
[email protected]245b164e2013-06-13 22:31:4233namespace net {
34
35namespace {
[email protected]95b331b42013-12-02 06:26:3136
[email protected]bdd6c3d2014-01-30 08:07:4237// The fractions of the record's original TTL after which an active listener
38// (one that had |SetActiveRefresh(true)| called) will send a query to refresh
39// its cache. This happens both at 85% of the original TTL and again at 95% of
40// the original TTL.
41const double kListenerRefreshRatio1 = 0.85;
42const double kListenerRefreshRatio2 = 0.95;
[email protected]95b331b42013-12-02 06:26:3143
[email protected]95b331b42013-12-02 06:26:3144} // namespace
45
Qingsi Wang5410ef0b2019-03-05 20:26:4746void MDnsSocketFactoryImpl::CreateSockets(
47 std::vector<std::unique_ptr<DatagramServerSocket>>* sockets) {
[email protected]90d32142013-12-10 10:53:0648 InterfaceIndexFamilyList interfaces(GetMDnsInterfacesToBind());
49 for (size_t i = 0; i < interfaces.size(); ++i) {
ttuttle859dc7a2015-04-23 19:42:2950 DCHECK(interfaces[i].second == ADDRESS_FAMILY_IPV4 ||
51 interfaces[i].second == ADDRESS_FAMILY_IPV6);
Qingsi Wang5410ef0b2019-03-05 20:26:4752 std::unique_ptr<DatagramServerSocket> socket(CreateAndBindMDnsSocket(
Eric Orth9871aafa2018-10-02 19:59:1853 interfaces[i].second, interfaces[i].first, net_log_));
Qingsi Wang5410ef0b2019-03-05 20:26:4754 if (socket)
55 sockets->push_back(std::move(socket));
[email protected]90d32142013-12-10 10:53:0656 }
[email protected]95b331b42013-12-02 06:26:3157}
58
Qingsi Wang5410ef0b2019-03-05 20:26:4759MDnsConnection::SocketHandler::SocketHandler(
60 std::unique_ptr<DatagramServerSocket> socket,
61 MDnsConnection* connection)
62 : socket_(std::move(socket)),
[email protected]95b331b42013-12-02 06:26:3163 connection_(connection),
vitalybuka20859742014-09-22 23:42:3064 response_(dns_protocol::kMaxMulticastSize),
Qingsi Wang5410ef0b2019-03-05 20:26:4765 send_in_progress_(false) {}
[email protected]245b164e2013-06-13 22:31:4266
Chris Watkins68b15032017-12-01 03:07:1367MDnsConnection::SocketHandler::~SocketHandler() = default;
[email protected]245b164e2013-06-13 22:31:4268
69int MDnsConnection::SocketHandler::Start() {
[email protected]95b331b42013-12-02 06:26:3170 IPEndPoint end_point;
Qingsi Wang5410ef0b2019-03-05 20:26:4771 int rv = socket_->GetLocalAddress(&end_point);
[email protected]95b331b42013-12-02 06:26:3172 if (rv != OK)
73 return rv;
Qingsi Wang5410ef0b2019-03-05 20:26:4774 DCHECK(end_point.GetFamily() == ADDRESS_FAMILY_IPV4 ||
75 end_point.GetFamily() == ADDRESS_FAMILY_IPV6);
76 multicast_addr_ = dns_util::GetMdnsGroupEndPoint(end_point.GetFamily());
[email protected]245b164e2013-06-13 22:31:4277 return DoLoop(0);
78}
79
80int MDnsConnection::SocketHandler::DoLoop(int rv) {
81 do {
82 if (rv > 0)
[email protected]95b331b42013-12-02 06:26:3183 connection_->OnDatagramReceived(&response_, recv_addr_, rv);
[email protected]245b164e2013-06-13 22:31:4284
Qingsi Wang5410ef0b2019-03-05 20:26:4785 rv = socket_->RecvFrom(
Brad Lassey786929ad2018-02-21 20:54:2786 response_.io_buffer(), response_.io_buffer_size(), &recv_addr_,
Yannic Bonenberger922f6012019-09-07 16:20:1287 base::BindOnce(&MDnsConnection::SocketHandler::OnDatagramReceived,
88 base::Unretained(this)));
[email protected]245b164e2013-06-13 22:31:4289 } while (rv > 0);
90
91 if (rv != ERR_IO_PENDING)
92 return rv;
93
94 return OK;
95}
96
97void MDnsConnection::SocketHandler::OnDatagramReceived(int rv) {
98 if (rv >= OK)
99 rv = DoLoop(rv);
100
101 if (rv != OK)
vitalybuka20859742014-09-22 23:42:30102 connection_->PostOnError(this, rv);
[email protected]245b164e2013-06-13 22:31:42103}
104
vitalybuka20859742014-09-22 23:42:30105void MDnsConnection::SocketHandler::Send(const scoped_refptr<IOBuffer>& buffer,
106 unsigned size) {
107 if (send_in_progress_) {
108 send_queue_.push(std::make_pair(buffer, size));
109 return;
110 }
Yannic Bonenberger922f6012019-09-07 16:20:12111 int rv =
112 socket_->SendTo(buffer.get(), size, multicast_addr_,
113 base::BindOnce(&MDnsConnection::SocketHandler::SendDone,
114 base::Unretained(this)));
vitalybuka20859742014-09-22 23:42:30115 if (rv == ERR_IO_PENDING) {
116 send_in_progress_ = true;
117 } else if (rv < OK) {
118 connection_->PostOnError(this, rv);
119 }
[email protected]245b164e2013-06-13 22:31:42120}
121
122void MDnsConnection::SocketHandler::SendDone(int rv) {
vitalybuka20859742014-09-22 23:42:30123 DCHECK(send_in_progress_);
124 send_in_progress_ = false;
125 if (rv != OK)
126 connection_->PostOnError(this, rv);
127 while (!send_in_progress_ && !send_queue_.empty()) {
128 std::pair<scoped_refptr<IOBuffer>, unsigned> buffer = send_queue_.front();
129 send_queue_.pop();
130 Send(buffer.first, buffer.second);
131 }
[email protected]245b164e2013-06-13 22:31:42132}
133
vitalybuka20859742014-09-22 23:42:30134MDnsConnection::MDnsConnection(MDnsConnection::Delegate* delegate)
Jeremy Romand54000b22019-07-08 18:40:16135 : delegate_(delegate) {}
[email protected]245b164e2013-06-13 22:31:42136
Chris Watkins68b15032017-12-01 03:07:13137MDnsConnection::~MDnsConnection() = default;
[email protected]245b164e2013-06-13 22:31:42138
Eric Orthe857ebb2019-03-13 23:02:07139int MDnsConnection::Init(MDnsSocketFactory* socket_factory) {
Qingsi Wang5410ef0b2019-03-05 20:26:47140 std::vector<std::unique_ptr<DatagramServerSocket>> sockets;
141 socket_factory->CreateSockets(&sockets);
[email protected]e4411fbe2013-09-26 21:10:11142
Qingsi Wang5410ef0b2019-03-05 20:26:47143 for (std::unique_ptr<DatagramServerSocket>& socket : sockets) {
Bence Béky8f9d7d3952017-10-09 19:58:04144 socket_handlers_.push_back(std::make_unique<MDnsConnection::SocketHandler>(
Qingsi Wang5410ef0b2019-03-05 20:26:47145 std::move(socket), this));
[email protected]e4411fbe2013-09-26 21:10:11146 }
147
[email protected]03dd94252013-09-01 23:25:31148 // All unbound sockets need to be bound before processing untrusted input.
149 // This is done for security reasons, so that an attacker can't get an unbound
150 // socket.
Eric Orthe857ebb2019-03-13 23:02:07151 int last_failure = ERR_FAILED;
[email protected]e4411fbe2013-09-26 21:10:11152 for (size_t i = 0; i < socket_handlers_.size();) {
[email protected]9ac0c57a2013-10-02 23:00:54153 int rv = socket_handlers_[i]->Start();
154 if (rv != OK) {
Eric Orthe857ebb2019-03-13 23:02:07155 last_failure = rv;
[email protected]e4411fbe2013-09-26 21:10:11156 socket_handlers_.erase(socket_handlers_.begin() + i);
[email protected]9ac0c57a2013-10-02 23:00:54157 VLOG(1) << "Start failed, socket=" << i << ", error=" << rv;
[email protected]e4411fbe2013-09-26 21:10:11158 } else {
159 ++i;
160 }
161 }
[email protected]9ac0c57a2013-10-02 23:00:54162 VLOG(1) << "Sockets ready:" << socket_handlers_.size();
Eric Orthe857ebb2019-03-13 23:02:07163 DCHECK_NE(ERR_IO_PENDING, last_failure);
164 return socket_handlers_.empty() ? last_failure : OK;
[email protected]245b164e2013-06-13 22:31:42165}
166
vitalybuka20859742014-09-22 23:42:30167void MDnsConnection::Send(const scoped_refptr<IOBuffer>& buffer,
168 unsigned size) {
danakj22f90e72016-04-16 01:55:40169 for (std::unique_ptr<SocketHandler>& handler : socket_handlers_)
olli.raulad8734f2c72015-12-03 12:36:34170 handler->Send(buffer, size);
[email protected]245b164e2013-06-13 22:31:42171}
172
vitalybuka20859742014-09-22 23:42:30173void MDnsConnection::PostOnError(SocketHandler* loop, int rv) {
olli.raulad8734f2c72015-12-03 12:36:34174 int id = 0;
175 for (const auto& it : socket_handlers_) {
176 if (it.get() == loop)
177 break;
178 id++;
179 }
180 VLOG(1) << "Socket error. id=" << id << ", error=" << rv;
vitalybuka20859742014-09-22 23:42:30181 // Post to allow deletion of this object by delegate.
skyostil4891b25b2015-06-11 11:43:45182 base::ThreadTaskRunnerHandle::Get()->PostTask(
kylecharf4fe5172019-02-15 18:53:49183 FROM_HERE, base::BindOnce(&MDnsConnection::OnError,
184 weak_ptr_factory_.GetWeakPtr(), rv));
vitalybuka20859742014-09-22 23:42:30185}
186
187void MDnsConnection::OnError(int rv) {
[email protected]245b164e2013-06-13 22:31:42188 // TODO(noamsml): Specific handling of intermittent errors that can be handled
189 // in the connection.
vitalybuka20859742014-09-22 23:42:30190 delegate_->OnConnectionError(rv);
[email protected]245b164e2013-06-13 22:31:42191}
192
[email protected]245b164e2013-06-13 22:31:42193void MDnsConnection::OnDatagramReceived(
194 DnsResponse* response,
195 const IPEndPoint& recv_addr,
196 int bytes_read) {
197 // TODO(noamsml): More sophisticated error handling.
198 DCHECK_GT(bytes_read, 0);
199 delegate_->HandlePacket(response, bytes_read);
200}
201
tzik08d8d6e2018-07-09 04:11:47202MDnsClientImpl::Core::Core(base::Clock* clock, base::OneShotTimer* timer)
kmarshall3e740be2015-03-02 21:30:44203 : clock_(clock),
204 cleanup_timer_(timer),
Eric Orth6cb27ea2019-05-03 16:31:04205 connection_(new MDnsConnection(this)) {
206 DCHECK(cleanup_timer_);
207 DCHECK(!cleanup_timer_->IsRunning());
208}
[email protected]245b164e2013-06-13 22:31:42209
Eric Orth6cb27ea2019-05-03 16:31:04210MDnsClientImpl::Core::~Core() {
211 cleanup_timer_->Stop();
212}
[email protected]245b164e2013-06-13 22:31:42213
Eric Orthe857ebb2019-03-13 23:02:07214int MDnsClientImpl::Core::Init(MDnsSocketFactory* socket_factory) {
Eric Orth6cb27ea2019-05-03 16:31:04215 CHECK(!cleanup_timer_->IsRunning());
[email protected]e4411fbe2013-09-26 21:10:11216 return connection_->Init(socket_factory);
[email protected]245b164e2013-06-13 22:31:42217}
218
Avi Drissman13fc8932015-12-20 04:40:46219bool MDnsClientImpl::Core::SendQuery(uint16_t rrtype, const std::string& name) {
[email protected]245b164e2013-06-13 22:31:42220 std::string name_dns;
Bailey Berroe70f06c2019-03-11 22:22:46221 if (!DNSDomainFromUnrestrictedDot(name, &name_dns))
[email protected]245b164e2013-06-13 22:31:42222 return false;
223
224 DnsQuery query(0, name_dns, rrtype);
225 query.set_flags(0); // Remove the RD flag from the query. It is unneeded.
226
vitalybuka20859742014-09-22 23:42:30227 connection_->Send(query.io_buffer(), query.io_buffer()->size());
228 return true;
[email protected]245b164e2013-06-13 22:31:42229}
230
231void MDnsClientImpl::Core::HandlePacket(DnsResponse* response,
232 int bytes_read) {
233 unsigned offset;
[email protected]5e6f42732013-06-19 03:43:31234 // Note: We store cache keys rather than record pointers to avoid
235 // erroneous behavior in case a packet contains multiple exclusive
236 // records with the same type and name.
[email protected]bdd6c3d2014-01-30 08:07:42237 std::map<MDnsCache::Key, MDnsCache::UpdateType> update_keys;
Brad Lassey786929ad2018-02-21 20:54:27238 DCHECK_GT(bytes_read, 0);
[email protected]245b164e2013-06-13 22:31:42239 if (!response->InitParseWithoutQuery(bytes_read)) {
[email protected]423a4d42014-03-05 21:55:06240 DVLOG(1) << "Could not understand an mDNS packet.";
[email protected]245b164e2013-06-13 22:31:42241 return; // Message is unreadable.
242 }
243
244 // TODO(noamsml): duplicate query suppression.
245 if (!(response->flags() & dns_protocol::kFlagResponse))
246 return; // Message is a query. ignore it.
247
248 DnsRecordParser parser = response->Parser();
249 unsigned answer_count = response->answer_count() +
250 response->additional_answer_count();
251
252 for (unsigned i = 0; i < answer_count; i++) {
253 offset = parser.GetOffset();
danakj22f90e72016-04-16 01:55:40254 std::unique_ptr<const RecordParsed> record =
kmarshall3e740be2015-03-02 21:30:44255 RecordParsed::CreateFrom(&parser, clock_->Now());
[email protected]245b164e2013-06-13 22:31:42256
[email protected]5e6f42732013-06-19 03:43:31257 if (!record) {
[email protected]423a4d42014-03-05 21:55:06258 DVLOG(1) << "Could not understand an mDNS record.";
[email protected]245b164e2013-06-13 22:31:42259
260 if (offset == parser.GetOffset()) {
[email protected]423a4d42014-03-05 21:55:06261 DVLOG(1) << "Abandoned parsing the rest of the packet.";
[email protected]245b164e2013-06-13 22:31:42262 return; // The parser did not advance, abort reading the packet.
263 } else {
264 continue; // We may be able to extract other records from the packet.
265 }
266 }
267
[email protected]5e6f42732013-06-19 03:43:31268 if ((record->klass() & dns_protocol::kMDnsClassMask) !=
[email protected]245b164e2013-06-13 22:31:42269 dns_protocol::kClassIN) {
[email protected]423a4d42014-03-05 21:55:06270 DVLOG(1) << "Received an mDNS record with non-IN class. Ignoring.";
[email protected]245b164e2013-06-13 22:31:42271 continue; // Ignore all records not in the IN class.
272 }
273
[email protected]5e6f42732013-06-19 03:43:31274 MDnsCache::Key update_key = MDnsCache::Key::CreateFor(record.get());
dchengc7eeda422015-12-26 03:56:48275 MDnsCache::UpdateType update = cache_.UpdateDnsRecord(std::move(record));
[email protected]245b164e2013-06-13 22:31:42276
277 // Cleanup time may have changed.
278 ScheduleCleanup(cache_.next_expiration());
279
[email protected]bdd6c3d2014-01-30 08:07:42280 update_keys.insert(std::make_pair(update_key, update));
[email protected]5e6f42732013-06-19 03:43:31281 }
282
jdoerrie22a91d8b92018-10-05 08:43:26283 for (auto i = update_keys.begin(); i != update_keys.end(); i++) {
[email protected]5e6f42732013-06-19 03:43:31284 const RecordParsed* record = cache_.LookupKey(i->first);
[email protected]21df16962013-07-01 17:39:53285 if (!record)
286 continue;
287
288 if (record->type() == dns_protocol::kTypeNSEC) {
289#if defined(ENABLE_NSEC)
290 NotifyNsecRecord(record);
291#endif
292 } else {
293 AlertListeners(i->second, ListenerKey(record->name(), record->type()),
[email protected]5e6f42732013-06-19 03:43:31294 record);
[email protected]21df16962013-07-01 17:39:53295 }
296 }
297}
298
299void MDnsClientImpl::Core::NotifyNsecRecord(const RecordParsed* record) {
300 DCHECK_EQ(dns_protocol::kTypeNSEC, record->type());
301 const NsecRecordRdata* rdata = record->rdata<NsecRecordRdata>();
302 DCHECK(rdata);
303
304 // Remove all cached records matching the nonexistent RR types.
305 std::vector<const RecordParsed*> records_to_remove;
306
kmarshall3e740be2015-03-02 21:30:44307 cache_.FindDnsRecords(0, record->name(), &records_to_remove, clock_->Now());
[email protected]21df16962013-07-01 17:39:53308
jdoerrie22a91d8b92018-10-05 08:43:26309 for (auto i = records_to_remove.begin(); i != records_to_remove.end(); i++) {
[email protected]21df16962013-07-01 17:39:53310 if ((*i)->type() == dns_protocol::kTypeNSEC)
311 continue;
312 if (!rdata->GetBit((*i)->type())) {
danakj22f90e72016-04-16 01:55:40313 std::unique_ptr<const RecordParsed> record_removed =
314 cache_.RemoveRecord((*i));
[email protected]21df16962013-07-01 17:39:53315 DCHECK(record_removed);
316 OnRecordRemoved(record_removed.get());
317 }
318 }
319
320 // Alert all listeners waiting for the nonexistent RR types.
Piotr Pawliczek3318cc92020-07-25 05:10:13321 ListenerKey key(record->name(), 0);
322 auto i = listeners_.upper_bound(key);
323 for (; i != listeners_.end() &&
324 i->first.name_lowercase() == key.name_lowercase();
325 i++) {
326 if (!rdata->GetBit(i->first.type())) {
ericwilligers9d64a5f2016-10-18 00:28:49327 for (auto& observer : *i->second)
328 observer.AlertNsecRecord();
[email protected]245b164e2013-06-13 22:31:42329 }
330 }
331}
332
333void MDnsClientImpl::Core::OnConnectionError(int error) {
334 // TODO(noamsml): On connection error, recreate connection and flush cache.
kmarshall73a89b12015-09-01 22:18:13335 VLOG(1) << "MDNS OnConnectionError (code: " << error << ")";
[email protected]245b164e2013-06-13 22:31:42336}
337
Piotr Pawliczek3318cc92020-07-25 05:10:13338MDnsClientImpl::Core::ListenerKey::ListenerKey(const std::string& name,
339 uint16_t type)
340 : name_lowercase_(base::ToLowerASCII(name)), type_(type) {}
341
342bool MDnsClientImpl::Core::ListenerKey::operator<(
343 const MDnsClientImpl::Core::ListenerKey& key) const {
344 if (name_lowercase_ == key.name_lowercase_)
345 return type_ < key.type_;
346 return name_lowercase_ < key.name_lowercase_;
347}
348
[email protected]245b164e2013-06-13 22:31:42349void MDnsClientImpl::Core::AlertListeners(
[email protected]bdd6c3d2014-01-30 08:07:42350 MDnsCache::UpdateType update_type,
[email protected]245b164e2013-06-13 22:31:42351 const ListenerKey& key,
352 const RecordParsed* record) {
jdoerrie22a91d8b92018-10-05 08:43:26353 auto listener_map_iterator = listeners_.find(key);
[email protected]245b164e2013-06-13 22:31:42354 if (listener_map_iterator == listeners_.end()) return;
355
ericwilligers9d64a5f2016-10-18 00:28:49356 for (auto& observer : *listener_map_iterator->second)
357 observer.HandleRecordUpdate(update_type, record);
[email protected]245b164e2013-06-13 22:31:42358}
359
360void MDnsClientImpl::Core::AddListener(
361 MDnsListenerImpl* listener) {
[email protected]21df16962013-07-01 17:39:53362 ListenerKey key(listener->GetName(), listener->GetType());
[email protected]245b164e2013-06-13 22:31:42363
Trent Apteda250ec3ab2018-08-19 08:52:19364 auto& observer_list = listeners_[key];
avi9e72eb482016-12-09 21:10:54365 if (!observer_list)
Trent Apteda250ec3ab2018-08-19 08:52:19366 observer_list = std::make_unique<ObserverListType>();
[email protected]245b164e2013-06-13 22:31:42367
368 observer_list->AddObserver(listener);
369}
370
371void MDnsClientImpl::Core::RemoveListener(MDnsListenerImpl* listener) {
[email protected]21df16962013-07-01 17:39:53372 ListenerKey key(listener->GetName(), listener->GetType());
jdoerrie22a91d8b92018-10-05 08:43:26373 auto observer_list_iterator = listeners_.find(key);
[email protected]245b164e2013-06-13 22:31:42374
375 DCHECK(observer_list_iterator != listeners_.end());
376 DCHECK(observer_list_iterator->second->HasObserver(listener));
377
378 observer_list_iterator->second->RemoveObserver(listener);
379
380 // Remove the observer list from the map if it is empty
Mitsuru Oshima8bc2746e82021-01-15 07:01:13381 if (observer_list_iterator->second->empty()) {
[email protected]21df16962013-07-01 17:39:53382 // Schedule the actual removal for later in case the listener removal
383 // happens while iterating over the observer list.
skyostil4891b25b2015-06-11 11:43:45384 base::ThreadTaskRunnerHandle::Get()->PostTask(
kylecharf4fe5172019-02-15 18:53:49385 FROM_HERE, base::BindOnce(&MDnsClientImpl::Core::CleanupObserverList,
386 AsWeakPtr(), key));
[email protected]21df16962013-07-01 17:39:53387 }
388}
389
390void MDnsClientImpl::Core::CleanupObserverList(const ListenerKey& key) {
jdoerrie22a91d8b92018-10-05 08:43:26391 auto found = listeners_.find(key);
Mitsuru Oshima8bc2746e82021-01-15 07:01:13392 if (found != listeners_.end() && found->second->empty()) {
[email protected]21df16962013-07-01 17:39:53393 listeners_.erase(found);
[email protected]245b164e2013-06-13 22:31:42394 }
395}
396
397void MDnsClientImpl::Core::ScheduleCleanup(base::Time cleanup) {
Eric Orthacdd8ae2019-03-29 22:07:19398 // If cache is overfilled. Force an immediate cleanup.
399 if (cache_.IsCacheOverfilled())
400 cleanup = clock_->Now();
401
[email protected]245b164e2013-06-13 22:31:42402 // Cleanup is already scheduled, no need to do anything.
kmarshall3e740be2015-03-02 21:30:44403 if (cleanup == scheduled_cleanup_) {
404 return;
405 }
[email protected]245b164e2013-06-13 22:31:42406 scheduled_cleanup_ = cleanup;
407
408 // This cancels the previously scheduled cleanup.
kmarshall3e740be2015-03-02 21:30:44409 cleanup_timer_->Stop();
[email protected]245b164e2013-06-13 22:31:42410
411 // If |cleanup| is empty, then no cleanup necessary.
412 if (cleanup != base::Time()) {
Yannic Bonenberger922f6012019-09-07 16:20:12413 cleanup_timer_->Start(FROM_HERE,
414 std::max(base::TimeDelta(), cleanup - clock_->Now()),
415 base::BindOnce(&MDnsClientImpl::Core::DoCleanup,
416 base::Unretained(this)));
[email protected]245b164e2013-06-13 22:31:42417 }
418}
419
420void MDnsClientImpl::Core::DoCleanup() {
Anna Malova9b2095b2020-03-04 15:41:18421 cache_.CleanupRecords(
422 clock_->Now(), base::BindRepeating(&MDnsClientImpl::Core::OnRecordRemoved,
423 base::Unretained(this)));
[email protected]245b164e2013-06-13 22:31:42424
425 ScheduleCleanup(cache_.next_expiration());
426}
427
428void MDnsClientImpl::Core::OnRecordRemoved(
429 const RecordParsed* record) {
[email protected]bdd6c3d2014-01-30 08:07:42430 AlertListeners(MDnsCache::RecordRemoved,
[email protected]21df16962013-07-01 17:39:53431 ListenerKey(record->name(), record->type()), record);
[email protected]245b164e2013-06-13 22:31:42432}
433
434void MDnsClientImpl::Core::QueryCache(
Avi Drissman13fc8932015-12-20 04:40:46435 uint16_t rrtype,
436 const std::string& name,
[email protected]245b164e2013-06-13 22:31:42437 std::vector<const RecordParsed*>* records) const {
kmarshall3e740be2015-03-02 21:30:44438 cache_.FindDnsRecords(rrtype, name, records, clock_->Now());
[email protected]245b164e2013-06-13 22:31:42439}
440
kmarshall3e740be2015-03-02 21:30:44441MDnsClientImpl::MDnsClientImpl()
tzik26331742017-12-07 07:28:33442 : clock_(base::DefaultClock::GetInstance()),
tzik08d8d6e2018-07-09 04:11:47443 cleanup_timer_(new base::OneShotTimer()) {}
kmarshall3e740be2015-03-02 21:30:44444
tzik26331742017-12-07 07:28:33445MDnsClientImpl::MDnsClientImpl(base::Clock* clock,
tzik08d8d6e2018-07-09 04:11:47446 std::unique_ptr<base::OneShotTimer> timer)
tzik26331742017-12-07 07:28:33447 : clock_(clock), cleanup_timer_(std::move(timer)) {}
[email protected]245b164e2013-06-13 22:31:42448
Eric Orth6cb27ea2019-05-03 16:31:04449MDnsClientImpl::~MDnsClientImpl() {
450 StopListening();
451}
[email protected]245b164e2013-06-13 22:31:42452
Eric Orthe857ebb2019-03-13 23:02:07453int MDnsClientImpl::StartListening(MDnsSocketFactory* socket_factory) {
[email protected]9c61d252013-07-02 23:26:22454 DCHECK(!core_.get());
Peter Boström8a7540692021-04-05 20:48:20455 core_ = std::make_unique<Core>(clock_, cleanup_timer_.get());
Eric Orthe857ebb2019-03-13 23:02:07456 int rv = core_->Init(socket_factory);
457 if (rv != OK) {
458 DCHECK_NE(ERR_IO_PENDING, rv);
[email protected]9c61d252013-07-02 23:26:22459 core_.reset();
[email protected]245b164e2013-06-13 22:31:42460 }
Eric Orthe857ebb2019-03-13 23:02:07461 return rv;
[email protected]245b164e2013-06-13 22:31:42462}
463
[email protected]9c61d252013-07-02 23:26:22464void MDnsClientImpl::StopListening() {
465 core_.reset();
[email protected]245b164e2013-06-13 22:31:42466}
467
[email protected]9c61d252013-07-02 23:26:22468bool MDnsClientImpl::IsListening() const {
Raul Tambre94493c652019-03-11 17:18:35469 return core_.get() != nullptr;
[email protected]245b164e2013-06-13 22:31:42470}
471
danakj22f90e72016-04-16 01:55:40472std::unique_ptr<MDnsListener> MDnsClientImpl::CreateListener(
Avi Drissman13fc8932015-12-20 04:40:46473 uint16_t rrtype,
[email protected]245b164e2013-06-13 22:31:42474 const std::string& name,
475 MDnsListener::Delegate* delegate) {
danakj22f90e72016-04-16 01:55:40476 return std::unique_ptr<MDnsListener>(
tzik26331742017-12-07 07:28:33477 new MDnsListenerImpl(rrtype, name, clock_, delegate, this));
[email protected]245b164e2013-06-13 22:31:42478}
479
danakj22f90e72016-04-16 01:55:40480std::unique_ptr<MDnsTransaction> MDnsClientImpl::CreateTransaction(
Avi Drissman13fc8932015-12-20 04:40:46481 uint16_t rrtype,
[email protected]245b164e2013-06-13 22:31:42482 const std::string& name,
483 int flags,
484 const MDnsTransaction::ResultCallback& callback) {
danakj22f90e72016-04-16 01:55:40485 return std::unique_ptr<MDnsTransaction>(
[email protected]245b164e2013-06-13 22:31:42486 new MDnsTransactionImpl(rrtype, name, flags, callback, this));
487}
488
Avi Drissman13fc8932015-12-20 04:40:46489MDnsListenerImpl::MDnsListenerImpl(uint16_t rrtype,
kmarshall3e740be2015-03-02 21:30:44490 const std::string& name,
491 base::Clock* clock,
492 MDnsListener::Delegate* delegate,
493 MDnsClientImpl* client)
494 : rrtype_(rrtype),
495 name_(name),
496 clock_(clock),
497 client_(client),
498 delegate_(delegate),
499 started_(false),
Avi Drissman13fc8932015-12-20 04:40:46500 active_refresh_(false) {}
[email protected]bdd6c3d2014-01-30 08:07:42501
502MDnsListenerImpl::~MDnsListenerImpl() {
503 if (started_) {
504 DCHECK(client_->core());
505 client_->core()->RemoveListener(this);
506 }
[email protected]245b164e2013-06-13 22:31:42507}
508
509bool MDnsListenerImpl::Start() {
510 DCHECK(!started_);
511
[email protected]245b164e2013-06-13 22:31:42512 started_ = true;
513
514 DCHECK(client_->core());
515 client_->core()->AddListener(this);
516
517 return true;
518}
519
[email protected]bdd6c3d2014-01-30 08:07:42520void MDnsListenerImpl::SetActiveRefresh(bool active_refresh) {
521 active_refresh_ = active_refresh;
522
[email protected]245b164e2013-06-13 22:31:42523 if (started_) {
[email protected]bdd6c3d2014-01-30 08:07:42524 if (!active_refresh_) {
525 next_refresh_.Cancel();
526 } else if (last_update_ != base::Time()) {
527 ScheduleNextRefresh();
528 }
[email protected]245b164e2013-06-13 22:31:42529 }
530}
531
532const std::string& MDnsListenerImpl::GetName() const {
533 return name_;
534}
535
Avi Drissman13fc8932015-12-20 04:40:46536uint16_t MDnsListenerImpl::GetType() const {
[email protected]245b164e2013-06-13 22:31:42537 return rrtype_;
538}
539
[email protected]bdd6c3d2014-01-30 08:07:42540void MDnsListenerImpl::HandleRecordUpdate(MDnsCache::UpdateType update_type,
541 const RecordParsed* record) {
[email protected]245b164e2013-06-13 22:31:42542 DCHECK(started_);
[email protected]bdd6c3d2014-01-30 08:07:42543
544 if (update_type != MDnsCache::RecordRemoved) {
545 ttl_ = record->ttl();
546 last_update_ = record->time_created();
547
548 ScheduleNextRefresh();
549 }
550
551 if (update_type != MDnsCache::NoChange) {
552 MDnsListener::UpdateType update_external;
553
554 switch (update_type) {
555 case MDnsCache::RecordAdded:
556 update_external = MDnsListener::RECORD_ADDED;
557 break;
558 case MDnsCache::RecordChanged:
559 update_external = MDnsListener::RECORD_CHANGED;
560 break;
561 case MDnsCache::RecordRemoved:
562 update_external = MDnsListener::RECORD_REMOVED;
563 break;
564 case MDnsCache::NoChange:
565 default:
566 NOTREACHED();
567 // Dummy assignment to suppress compiler warning.
568 update_external = MDnsListener::RECORD_CHANGED;
569 break;
570 }
571
572 delegate_->OnRecordUpdate(update_external, record);
573 }
[email protected]245b164e2013-06-13 22:31:42574}
575
[email protected]21df16962013-07-01 17:39:53576void MDnsListenerImpl::AlertNsecRecord() {
577 DCHECK(started_);
578 delegate_->OnNsecRecord(name_, rrtype_);
579}
580
[email protected]bdd6c3d2014-01-30 08:07:42581void MDnsListenerImpl::ScheduleNextRefresh() {
582 DCHECK(last_update_ != base::Time());
583
584 if (!active_refresh_)
585 return;
586
587 // A zero TTL is a goodbye packet and should not be refreshed.
588 if (ttl_ == 0) {
589 next_refresh_.Cancel();
590 return;
591 }
592
Steve Kobesf5bea3e2020-07-08 20:15:43593 next_refresh_.Reset(
594 base::BindRepeating(&MDnsListenerImpl::DoRefresh, AsWeakPtr()));
[email protected]bdd6c3d2014-01-30 08:07:42595
596 // Schedule refreshes at both 85% and 95% of the original TTL. These will both
597 // be canceled and rescheduled if the record's TTL is updated due to a
598 // response being received.
Peter Kastinge5a38ed2021-10-02 03:06:35599 base::Time next_refresh1 =
600 last_update_ +
601 base::Milliseconds(static_cast<int>(base::Time::kMillisecondsPerSecond *
602 kListenerRefreshRatio1 * ttl_));
[email protected]bdd6c3d2014-01-30 08:07:42603
Peter Kastinge5a38ed2021-10-02 03:06:35604 base::Time next_refresh2 =
605 last_update_ +
606 base::Milliseconds(static_cast<int>(base::Time::kMillisecondsPerSecond *
607 kListenerRefreshRatio2 * ttl_));
[email protected]bdd6c3d2014-01-30 08:07:42608
skyostil4891b25b2015-06-11 11:43:45609 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
kmarshall3e740be2015-03-02 21:30:44610 FROM_HERE, next_refresh_.callback(), next_refresh1 - clock_->Now());
[email protected]bdd6c3d2014-01-30 08:07:42611
skyostil4891b25b2015-06-11 11:43:45612 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
kmarshall3e740be2015-03-02 21:30:44613 FROM_HERE, next_refresh_.callback(), next_refresh2 - clock_->Now());
[email protected]bdd6c3d2014-01-30 08:07:42614}
615
616void MDnsListenerImpl::DoRefresh() {
617 client_->core()->SendQuery(rrtype_, name_);
618}
619
[email protected]245b164e2013-06-13 22:31:42620MDnsTransactionImpl::MDnsTransactionImpl(
Avi Drissman13fc8932015-12-20 04:40:46621 uint16_t rrtype,
[email protected]245b164e2013-06-13 22:31:42622 const std::string& name,
623 int flags,
624 const MDnsTransaction::ResultCallback& callback,
625 MDnsClientImpl* client)
Avi Drissman13fc8932015-12-20 04:40:46626 : rrtype_(rrtype),
627 name_(name),
628 callback_(callback),
629 client_(client),
630 started_(false),
631 flags_(flags) {
[email protected]245b164e2013-06-13 22:31:42632 DCHECK((flags_ & MDnsTransaction::FLAG_MASK) == flags_);
633 DCHECK(flags_ & MDnsTransaction::QUERY_CACHE ||
634 flags_ & MDnsTransaction::QUERY_NETWORK);
635}
636
637MDnsTransactionImpl::~MDnsTransactionImpl() {
638 timeout_.Cancel();
639}
640
641bool MDnsTransactionImpl::Start() {
642 DCHECK(!started_);
643 started_ = true;
[email protected]f3c09992013-06-25 00:40:48644
[email protected]245b164e2013-06-13 22:31:42645 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
[email protected]245b164e2013-06-13 22:31:42646 if (flags_ & MDnsTransaction::QUERY_CACHE) {
[email protected]f3c09992013-06-25 00:40:48647 ServeRecordsFromCache();
648
649 if (!weak_this || !is_active()) return true;
[email protected]245b164e2013-06-13 22:31:42650 }
651
[email protected]f3c09992013-06-25 00:40:48652 if (flags_ & MDnsTransaction::QUERY_NETWORK) {
653 return QueryAndListen();
[email protected]245b164e2013-06-13 22:31:42654 }
655
[email protected]f3c09992013-06-25 00:40:48656 // If this is a cache only query, signal that the transaction is over
657 // immediately.
658 SignalTransactionOver();
[email protected]245b164e2013-06-13 22:31:42659 return true;
660}
661
662const std::string& MDnsTransactionImpl::GetName() const {
663 return name_;
664}
665
Avi Drissman13fc8932015-12-20 04:40:46666uint16_t MDnsTransactionImpl::GetType() const {
[email protected]245b164e2013-06-13 22:31:42667 return rrtype_;
668}
669
670void MDnsTransactionImpl::CacheRecordFound(const RecordParsed* record) {
671 DCHECK(started_);
672 OnRecordUpdate(MDnsListener::RECORD_ADDED, record);
673}
674
675void MDnsTransactionImpl::TriggerCallback(MDnsTransaction::Result result,
676 const RecordParsed* record) {
677 DCHECK(started_);
678 if (!is_active()) return;
679
680 // Ensure callback is run after touching all class state, so that
681 // the callback can delete the transaction.
682 MDnsTransaction::ResultCallback callback = callback_;
683
[email protected]21df16962013-07-01 17:39:53684 // Reset the transaction if it expects a single result, or if the result
685 // is a final one (everything except for a record).
686 if (flags_ & MDnsTransaction::SINGLE_RESULT ||
687 result != MDnsTransaction::RESULT_RECORD) {
[email protected]245b164e2013-06-13 22:31:42688 Reset();
[email protected]21df16962013-07-01 17:39:53689 }
[email protected]245b164e2013-06-13 22:31:42690
691 callback.Run(result, record);
692}
693
694void MDnsTransactionImpl::Reset() {
695 callback_.Reset();
696 listener_.reset();
697 timeout_.Cancel();
698}
699
700void MDnsTransactionImpl::OnRecordUpdate(MDnsListener::UpdateType update,
701 const RecordParsed* record) {
702 DCHECK(started_);
703 if (update == MDnsListener::RECORD_ADDED ||
704 update == MDnsListener::RECORD_CHANGED)
705 TriggerCallback(MDnsTransaction::RESULT_RECORD, record);
706}
707
708void MDnsTransactionImpl::SignalTransactionOver() {
709 DCHECK(started_);
[email protected]245b164e2013-06-13 22:31:42710 if (flags_ & MDnsTransaction::SINGLE_RESULT) {
Raul Tambre94493c652019-03-11 17:18:35711 TriggerCallback(MDnsTransaction::RESULT_NO_RESULTS, nullptr);
[email protected]245b164e2013-06-13 22:31:42712 } else {
Raul Tambre94493c652019-03-11 17:18:35713 TriggerCallback(MDnsTransaction::RESULT_DONE, nullptr);
[email protected]245b164e2013-06-13 22:31:42714 }
[email protected]245b164e2013-06-13 22:31:42715}
716
[email protected]f3c09992013-06-25 00:40:48717void MDnsTransactionImpl::ServeRecordsFromCache() {
718 std::vector<const RecordParsed*> records;
719 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
720
721 if (client_->core()) {
722 client_->core()->QueryCache(rrtype_, name_, &records);
jdoerrie22a91d8b92018-10-05 08:43:26723 for (auto i = records.begin(); i != records.end() && weak_this; ++i) {
[email protected]63b43f3e2013-08-07 19:21:12724 weak_this->TriggerCallback(MDnsTransaction::RESULT_RECORD, *i);
[email protected]f3c09992013-06-25 00:40:48725 }
[email protected]21df16962013-07-01 17:39:53726
727#if defined(ENABLE_NSEC)
728 if (records.empty()) {
729 DCHECK(weak_this);
730 client_->core()->QueryCache(dns_protocol::kTypeNSEC, name_, &records);
731 if (!records.empty()) {
732 const NsecRecordRdata* rdata =
733 records.front()->rdata<NsecRecordRdata>();
734 DCHECK(rdata);
735 if (!rdata->GetBit(rrtype_))
Raul Tambre94493c652019-03-11 17:18:35736 weak_this->TriggerCallback(MDnsTransaction::RESULT_NSEC, nullptr);
[email protected]21df16962013-07-01 17:39:53737 }
738 }
739#endif
[email protected]f3c09992013-06-25 00:40:48740 }
741}
742
743bool MDnsTransactionImpl::QueryAndListen() {
744 listener_ = client_->CreateListener(rrtype_, name_, this);
745 if (!listener_->Start())
746 return false;
747
748 DCHECK(client_->core());
749 if (!client_->core()->SendQuery(rrtype_, name_))
750 return false;
751
Steve Kobesf5bea3e2020-07-08 20:15:43752 timeout_.Reset(
753 base::BindOnce(&MDnsTransactionImpl::SignalTransactionOver, AsWeakPtr()));
skyostil4891b25b2015-06-11 11:43:45754 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Eric Orth9871aafa2018-10-02 19:59:18755 FROM_HERE, timeout_.callback(), kTransactionTimeout);
[email protected]f3c09992013-06-25 00:40:48756
757 return true;
758}
759
[email protected]245b164e2013-06-13 22:31:42760void MDnsTransactionImpl::OnNsecRecord(const std::string& name, unsigned type) {
Raul Tambre94493c652019-03-11 17:18:35761 TriggerCallback(RESULT_NSEC, nullptr);
[email protected]245b164e2013-06-13 22:31:42762}
763
764void MDnsTransactionImpl::OnCachePurged() {
765 // TODO(noamsml): Cache purge situations not yet implemented
766}
767
768} // namespace net