1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/mdns_client_impl.h"
#include <algorithm>
#include <cstdint>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "base/containers/fixed_flat_set.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/observer_list.h"
#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "net/base/net_errors.h"
#include "net/base/rand_callback.h"
#include "net/dns/dns_names_util.h"
#include "net/dns/public/dns_protocol.h"
#include "net/dns/public/util.h"
#include "net/dns/record_rdata.h"
#include "net/socket/datagram_socket.h"
#include "third_party/re2/src/re2/re2.h"
// TODO(gene): Remove this temporary method of disabling NSEC support once it
// becomes clear whether this feature should be
// supported. http://crbug.com/255232
#define ENABLE_NSEC
namespace net {
namespace {
// The fractions of the record's original TTL after which an active listener
// (one that had |SetActiveRefresh(true)| called) will send a query to refresh
// its cache. This happens both at 85% of the original TTL and again at 95% of
// the original TTL.
const double kListenerRefreshRatio1 = 0.85;
const double kListenerRefreshRatio2 = 0.95;
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class mdnsQueryType {
kInitial = 0, // Initial mDNS query sent.
kRefresh = 1, // Refresh mDNS query sent.
kMaxValue = kRefresh,
};
void RecordQueryMetric(mdnsQueryType query_type, std::string_view host) {
constexpr auto kPrintScanServices = base::MakeFixedFlatSet<std::string_view>({
"_ipps._tcp.local",
"_ipp._tcp.local",
"_pdl-datastream._tcp.local",
"_printer._tcp.local",
"_print._sub._ipps._tcp.local",
"_print._sub._ipp._tcp.local",
"_scanner._tcp.local",
"_uscans._tcp.local",
"_uscan._tcp.local",
});
if (host.ends_with("_googlecast._tcp.local")) {
base::UmaHistogramEnumeration("Network.Mdns.Googlecast", query_type);
} else if (std::ranges::any_of(kPrintScanServices,
[&host](std::string_view service) {
return host.ends_with(service);
})) {
base::UmaHistogramEnumeration("Network.Mdns.PrintScan", query_type);
} else if (RE2::FullMatch(host,
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\.local$")) {
base::UmaHistogramEnumeration("Network.Mdns.UUID", query_type);
} else {
base::UmaHistogramEnumeration("Network.Mdns.Other", query_type);
}
}
} // namespace
void MDnsSocketFactoryImpl::CreateSockets(
std::vector<std::unique_ptr<DatagramServerSocket>>* sockets) {
InterfaceIndexFamilyList interfaces(GetMDnsInterfacesToBind());
for (const auto& interface : interfaces) {
DCHECK(interface.second == ADDRESS_FAMILY_IPV4 ||
interface.second == ADDRESS_FAMILY_IPV6);
std::unique_ptr<DatagramServerSocket> socket(
CreateAndBindMDnsSocket(interface.second, interface.first, net_log_));
if (socket)
sockets->push_back(std::move(socket));
}
}
MDnsConnection::SocketHandler::SocketHandler(
std::unique_ptr<DatagramServerSocket> socket,
MDnsConnection* connection)
: socket_(std::move(socket)),
connection_(connection),
response_(dns_protocol::kMaxMulticastSize) {}
MDnsConnection::SocketHandler::~SocketHandler() = default;
int MDnsConnection::SocketHandler::Start() {
IPEndPoint end_point;
int rv = socket_->GetLocalAddress(&end_point);
if (rv != OK)
return rv;
DCHECK(end_point.GetFamily() == ADDRESS_FAMILY_IPV4 ||
end_point.GetFamily() == ADDRESS_FAMILY_IPV6);
multicast_addr_ = dns_util::GetMdnsGroupEndPoint(end_point.GetFamily());
return DoLoop(0);
}
int MDnsConnection::SocketHandler::DoLoop(int rv) {
do {
if (rv > 0)
connection_->OnDatagramReceived(&response_, recv_addr_, rv);
rv = socket_->RecvFrom(
response_.io_buffer(), response_.io_buffer_size(), &recv_addr_,
base::BindOnce(&MDnsConnection::SocketHandler::OnDatagramReceived,
base::Unretained(this)));
} while (rv > 0);
if (rv != ERR_IO_PENDING)
return rv;
return OK;
}
void MDnsConnection::SocketHandler::OnDatagramReceived(int rv) {
if (rv >= OK)
rv = DoLoop(rv);
if (rv != OK)
connection_->PostOnError(this, rv);
}
void MDnsConnection::SocketHandler::Send(const scoped_refptr<IOBuffer>& buffer,
unsigned size) {
if (send_in_progress_) {
send_queue_.emplace(buffer, size);
return;
}
int rv =
socket_->SendTo(buffer.get(), size, multicast_addr_,
base::BindOnce(&MDnsConnection::SocketHandler::SendDone,
base::Unretained(this)));
if (rv == ERR_IO_PENDING) {
send_in_progress_ = true;
} else if (rv < OK) {
connection_->PostOnError(this, rv);
}
}
void MDnsConnection::SocketHandler::SendDone(int rv) {
DCHECK(send_in_progress_);
send_in_progress_ = false;
if (rv != OK)
connection_->PostOnError(this, rv);
while (!send_in_progress_ && !send_queue_.empty()) {
std::pair<scoped_refptr<IOBuffer>, unsigned> buffer = send_queue_.front();
send_queue_.pop();
Send(buffer.first, buffer.second);
}
}
MDnsConnection::MDnsConnection(MDnsConnection::Delegate* delegate)
: delegate_(delegate) {}
MDnsConnection::~MDnsConnection() = default;
int MDnsConnection::Init(MDnsSocketFactory* socket_factory) {
std::vector<std::unique_ptr<DatagramServerSocket>> sockets;
socket_factory->CreateSockets(&sockets);
for (std::unique_ptr<DatagramServerSocket>& socket : sockets) {
socket_handlers_.push_back(std::make_unique<MDnsConnection::SocketHandler>(
std::move(socket), this));
}
// All unbound sockets need to be bound before processing untrusted input.
// This is done for security reasons, so that an attacker can't get an unbound
// socket.
int last_failure = ERR_FAILED;
for (size_t i = 0; i < socket_handlers_.size();) {
int rv = socket_handlers_[i]->Start();
if (rv != OK) {
last_failure = rv;
socket_handlers_.erase(socket_handlers_.begin() + i);
VLOG(1) << "Start failed, socket=" << i << ", error=" << rv;
} else {
++i;
}
}
VLOG(1) << "Sockets ready:" << socket_handlers_.size();
DCHECK_NE(ERR_IO_PENDING, last_failure);
return socket_handlers_.empty() ? last_failure : OK;
}
void MDnsConnection::Send(const scoped_refptr<IOBuffer>& buffer,
unsigned size) {
for (std::unique_ptr<SocketHandler>& handler : socket_handlers_)
handler->Send(buffer, size);
}
void MDnsConnection::PostOnError(SocketHandler* loop, int rv) {
int id = 0;
for (const auto& it : socket_handlers_) {
if (it.get() == loop)
break;
id++;
}
VLOG(1) << "Socket error. id=" << id << ", error=" << rv;
// Post to allow deletion of this object by delegate.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&MDnsConnection::OnError,
weak_ptr_factory_.GetWeakPtr(), rv));
}
void MDnsConnection::OnError(int rv) {
// TODO(noamsml): Specific handling of intermittent errors that can be handled
// in the connection.
delegate_->OnConnectionError(rv);
}
void MDnsConnection::OnDatagramReceived(
DnsResponse* response,
const IPEndPoint& recv_addr,
int bytes_read) {
// TODO(noamsml): More sophisticated error handling.
DCHECK_GT(bytes_read, 0);
delegate_->HandlePacket(response, bytes_read);
}
MDnsClientImpl::Core::Core(base::Clock* clock, base::OneShotTimer* timer)
: clock_(clock),
cleanup_timer_(timer),
connection_(
std::make_unique<MDnsConnection>((MDnsConnection::Delegate*)this)) {
DCHECK(cleanup_timer_);
DCHECK(!cleanup_timer_->IsRunning());
}
MDnsClientImpl::Core::~Core() {
cleanup_timer_->Stop();
}
int MDnsClientImpl::Core::Init(MDnsSocketFactory* socket_factory) {
CHECK(!cleanup_timer_->IsRunning());
return connection_->Init(socket_factory);
}
bool MDnsClientImpl::Core::SendQuery(uint16_t rrtype, const std::string& name) {
std::optional<std::vector<uint8_t>> name_dns =
dns_names_util::DottedNameToNetwork(name);
if (!name_dns.has_value())
return false;
DnsQuery query(0, name_dns.value(), rrtype);
query.set_flags(0); // Remove the RD flag from the query. It is unneeded.
connection_->Send(query.io_buffer(), query.io_buffer()->size());
return true;
}
void MDnsClientImpl::Core::HandlePacket(DnsResponse* response,
int bytes_read) {
unsigned offset;
// Note: We store cache keys rather than record pointers to avoid
// erroneous behavior in case a packet contains multiple exclusive
// records with the same type and name.
std::map<MDnsCache::Key, MDnsCache::UpdateType> update_keys;
DCHECK_GT(bytes_read, 0);
if (!response->InitParseWithoutQuery(bytes_read)) {
DVLOG(1) << "Could not understand an mDNS packet.";
return; // Message is unreadable.
}
// TODO(noamsml): duplicate query suppression.
if (!(response->flags() & dns_protocol::kFlagResponse))
return; // Message is a query. ignore it.
DnsRecordParser parser = response->Parser();
unsigned answer_count = response->answer_count() +
response->additional_answer_count();
for (unsigned i = 0; i < answer_count; i++) {
offset = parser.GetOffset();
std::unique_ptr<const RecordParsed> record =
RecordParsed::CreateFrom(&parser, clock_->Now());
if (!record) {
DVLOG(1) << "Could not understand an mDNS record.";
if (offset == parser.GetOffset()) {
DVLOG(1) << "Abandoned parsing the rest of the packet.";
return; // The parser did not advance, abort reading the packet.
} else {
continue; // We may be able to extract other records from the packet.
}
}
if ((record->klass() & dns_protocol::kMDnsClassMask) !=
dns_protocol::kClassIN) {
DVLOG(1) << "Received an mDNS record with non-IN class. Ignoring.";
continue; // Ignore all records not in the IN class.
}
MDnsCache::Key update_key = MDnsCache::Key::CreateFor(record.get());
MDnsCache::UpdateType update = cache_.UpdateDnsRecord(std::move(record));
// Cleanup time may have changed.
ScheduleCleanup(cache_.next_expiration());
update_keys.emplace(update_key, update);
}
for (const auto& update_key : update_keys) {
const RecordParsed* record = cache_.LookupKey(update_key.first);
if (!record)
continue;
if (record->type() == dns_protocol::kTypeNSEC) {
#if defined(ENABLE_NSEC)
NotifyNsecRecord(record);
#endif
} else {
AlertListeners(update_key.second,
ListenerKey(record->name(), record->type()), record);
}
}
}
void MDnsClientImpl::Core::NotifyNsecRecord(const RecordParsed* record) {
DCHECK_EQ(dns_protocol::kTypeNSEC, record->type());
const NsecRecordRdata* rdata = record->rdata<NsecRecordRdata>();
DCHECK(rdata);
// Remove all cached records matching the nonexistent RR types.
std::vector<const RecordParsed*> records_to_remove;
cache_.FindDnsRecords(0, record->name(), &records_to_remove, clock_->Now());
for (const auto* record_to_remove : records_to_remove) {
if (record_to_remove->type() == dns_protocol::kTypeNSEC)
continue;
if (!rdata->GetBit(record_to_remove->type())) {
std::unique_ptr<const RecordParsed> record_removed =
cache_.RemoveRecord(record_to_remove);
DCHECK(record_removed);
OnRecordRemoved(record_removed.get());
}
}
// Alert all listeners waiting for the nonexistent RR types.
ListenerKey key(record->name(), 0);
auto i = listeners_.upper_bound(key);
for (; i != listeners_.end() &&
i->first.name_lowercase() == key.name_lowercase();
i++) {
if (!rdata->GetBit(i->first.type())) {
for (auto& observer : *i->second)
observer.AlertNsecRecord();
}
}
}
void MDnsClientImpl::Core::OnConnectionError(int error) {
// TODO(noamsml): On connection error, recreate connection and flush cache.
VLOG(1) << "MDNS OnConnectionError (code: " << error << ")";
}
MDnsClientImpl::Core::ListenerKey::ListenerKey(const std::string& name,
uint16_t type)
: name_lowercase_(base::ToLowerASCII(name)), type_(type) {}
bool MDnsClientImpl::Core::ListenerKey::operator<(
const MDnsClientImpl::Core::ListenerKey& key) const {
if (name_lowercase_ == key.name_lowercase_)
return type_ < key.type_;
return name_lowercase_ < key.name_lowercase_;
}
void MDnsClientImpl::Core::AlertListeners(
MDnsCache::UpdateType update_type,
const ListenerKey& key,
const RecordParsed* record) {
auto listener_map_iterator = listeners_.find(key);
if (listener_map_iterator == listeners_.end()) return;
for (auto& observer : *listener_map_iterator->second)
observer.HandleRecordUpdate(update_type, record);
}
void MDnsClientImpl::Core::AddListener(
MDnsListenerImpl* listener) {
ListenerKey key(listener->GetName(), listener->GetType());
auto& observer_list = listeners_[key];
if (!observer_list)
observer_list = std::make_unique<ObserverListType>();
observer_list->AddObserver(listener);
}
void MDnsClientImpl::Core::RemoveListener(MDnsListenerImpl* listener) {
ListenerKey key(listener->GetName(), listener->GetType());
auto observer_list_iterator = listeners_.find(key);
CHECK(observer_list_iterator != listeners_.end());
DCHECK(observer_list_iterator->second->HasObserver(listener));
observer_list_iterator->second->RemoveObserver(listener);
// Remove the observer list from the map if it is empty
if (observer_list_iterator->second->empty()) {
// Schedule the actual removal for later in case the listener removal
// happens while iterating over the observer list.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&MDnsClientImpl::Core::CleanupObserverList,
weak_ptr_factory_.GetWeakPtr(), key));
}
}
void MDnsClientImpl::Core::CleanupObserverList(const ListenerKey& key) {
auto found = listeners_.find(key);
if (found != listeners_.end() && found->second->empty()) {
listeners_.erase(found);
}
}
void MDnsClientImpl::Core::ScheduleCleanup(base::Time cleanup) {
// If cache is overfilled. Force an immediate cleanup.
if (cache_.IsCacheOverfilled())
cleanup = clock_->Now();
// Cleanup is already scheduled, no need to do anything.
if (cleanup == scheduled_cleanup_) {
return;
}
scheduled_cleanup_ = cleanup;
// This cancels the previously scheduled cleanup.
cleanup_timer_->Stop();
// If |cleanup| is empty, then no cleanup necessary.
if (cleanup != base::Time()) {
cleanup_timer_->Start(FROM_HERE,
std::max(base::TimeDelta(), cleanup - clock_->Now()),
base::BindOnce(&MDnsClientImpl::Core::DoCleanup,
base::Unretained(this)));
}
}
void MDnsClientImpl::Core::DoCleanup() {
cache_.CleanupRecords(
clock_->Now(), base::BindRepeating(&MDnsClientImpl::Core::OnRecordRemoved,
base::Unretained(this)));
ScheduleCleanup(cache_.next_expiration());
}
void MDnsClientImpl::Core::OnRecordRemoved(
const RecordParsed* record) {
AlertListeners(MDnsCache::RecordRemoved,
ListenerKey(record->name(), record->type()), record);
}
void MDnsClientImpl::Core::QueryCache(
uint16_t rrtype,
const std::string& name,
std::vector<const RecordParsed*>* records) const {
cache_.FindDnsRecords(rrtype, name, records, clock_->Now());
}
MDnsClientImpl::MDnsClientImpl()
: clock_(base::DefaultClock::GetInstance()),
cleanup_timer_(std::make_unique<base::OneShotTimer>()) {}
MDnsClientImpl::MDnsClientImpl(base::Clock* clock,
std::unique_ptr<base::OneShotTimer> timer)
: clock_(clock), cleanup_timer_(std::move(timer)) {}
MDnsClientImpl::~MDnsClientImpl() {
StopListening();
}
int MDnsClientImpl::StartListening(MDnsSocketFactory* socket_factory) {
DCHECK(!core_.get());
core_ = std::make_unique<Core>(clock_, cleanup_timer_.get());
int rv = core_->Init(socket_factory);
if (rv != OK) {
DCHECK_NE(ERR_IO_PENDING, rv);
core_.reset();
}
return rv;
}
void MDnsClientImpl::StopListening() {
core_.reset();
}
bool MDnsClientImpl::IsListening() const {
return core_.get() != nullptr;
}
std::unique_ptr<MDnsListener> MDnsClientImpl::CreateListener(
uint16_t rrtype,
const std::string& name,
MDnsListener::Delegate* delegate) {
return std::make_unique<MDnsListenerImpl>(rrtype, name, clock_, delegate,
this);
}
std::unique_ptr<MDnsTransaction> MDnsClientImpl::CreateTransaction(
uint16_t rrtype,
const std::string& name,
int flags,
const MDnsTransaction::ResultCallback& callback) {
return std::make_unique<MDnsTransactionImpl>(rrtype, name, flags, callback,
this);
}
MDnsListenerImpl::MDnsListenerImpl(uint16_t rrtype,
const std::string& name,
base::Clock* clock,
MDnsListener::Delegate* delegate,
MDnsClientImpl* client)
: rrtype_(rrtype),
name_(name),
clock_(clock),
client_(client),
delegate_(delegate) {}
MDnsListenerImpl::~MDnsListenerImpl() {
if (started_) {
DCHECK(client_->core());
client_->core()->RemoveListener(this);
}
}
bool MDnsListenerImpl::Start() {
DCHECK(!started_);
started_ = true;
DCHECK(client_->core());
client_->core()->AddListener(this);
return true;
}
void MDnsListenerImpl::SetActiveRefresh(bool active_refresh) {
active_refresh_ = active_refresh;
if (started_) {
if (!active_refresh_) {
next_refresh_.Cancel();
} else if (last_update_ != base::Time()) {
ScheduleNextRefresh();
}
}
}
const std::string& MDnsListenerImpl::GetName() const {
return name_;
}
uint16_t MDnsListenerImpl::GetType() const {
return rrtype_;
}
void MDnsListenerImpl::HandleRecordUpdate(MDnsCache::UpdateType update_type,
const RecordParsed* record) {
DCHECK(started_);
if (update_type != MDnsCache::RecordRemoved) {
ttl_ = record->ttl();
last_update_ = record->time_created();
ScheduleNextRefresh();
}
if (update_type != MDnsCache::NoChange) {
MDnsListener::UpdateType update_external;
switch (update_type) {
case MDnsCache::RecordAdded:
update_external = MDnsListener::RECORD_ADDED;
break;
case MDnsCache::RecordChanged:
update_external = MDnsListener::RECORD_CHANGED;
break;
case MDnsCache::RecordRemoved:
update_external = MDnsListener::RECORD_REMOVED;
break;
case MDnsCache::NoChange:
default:
NOTREACHED();
}
delegate_->OnRecordUpdate(update_external, record);
}
}
void MDnsListenerImpl::AlertNsecRecord() {
DCHECK(started_);
delegate_->OnNsecRecord(name_, rrtype_);
}
void MDnsListenerImpl::ScheduleNextRefresh() {
DCHECK(last_update_ != base::Time());
if (!active_refresh_)
return;
// A zero TTL is a goodbye packet and should not be refreshed.
if (ttl_ == 0) {
next_refresh_.Cancel();
return;
}
next_refresh_.Reset(base::BindRepeating(&MDnsListenerImpl::DoRefresh,
weak_ptr_factory_.GetWeakPtr()));
// Schedule refreshes at both 85% and 95% of the original TTL. These will both
// be canceled and rescheduled if the record's TTL is updated due to a
// response being received.
base::Time next_refresh1 =
last_update_ +
base::Milliseconds(static_cast<int>(base::Time::kMillisecondsPerSecond *
kListenerRefreshRatio1 * ttl_));
base::Time next_refresh2 =
last_update_ +
base::Milliseconds(static_cast<int>(base::Time::kMillisecondsPerSecond *
kListenerRefreshRatio2 * ttl_));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, next_refresh_.callback(), next_refresh1 - clock_->Now());
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, next_refresh_.callback(), next_refresh2 - clock_->Now());
}
void MDnsListenerImpl::DoRefresh() {
RecordQueryMetric(mdnsQueryType::kRefresh, name_);
client_->core()->SendQuery(rrtype_, name_);
}
MDnsTransactionImpl::MDnsTransactionImpl(
uint16_t rrtype,
const std::string& name,
int flags,
const MDnsTransaction::ResultCallback& callback,
MDnsClientImpl* client)
: rrtype_(rrtype),
name_(name),
callback_(callback),
client_(client),
flags_(flags) {
DCHECK((flags_ & MDnsTransaction::FLAG_MASK) == flags_);
DCHECK(flags_ & MDnsTransaction::QUERY_CACHE ||
flags_ & MDnsTransaction::QUERY_NETWORK);
}
MDnsTransactionImpl::~MDnsTransactionImpl() {
timeout_.Cancel();
}
bool MDnsTransactionImpl::Start() {
DCHECK(!started_);
started_ = true;
base::WeakPtr<MDnsTransactionImpl> weak_this = weak_ptr_factory_.GetWeakPtr();
if (flags_ & MDnsTransaction::QUERY_CACHE) {
ServeRecordsFromCache();
if (!weak_this || !is_active()) return true;
}
if (flags_ & MDnsTransaction::QUERY_NETWORK) {
return QueryAndListen();
}
// If this is a cache only query, signal that the transaction is over
// immediately.
SignalTransactionOver();
return true;
}
const std::string& MDnsTransactionImpl::GetName() const {
return name_;
}
uint16_t MDnsTransactionImpl::GetType() const {
return rrtype_;
}
void MDnsTransactionImpl::CacheRecordFound(const RecordParsed* record) {
DCHECK(started_);
OnRecordUpdate(MDnsListener::RECORD_ADDED, record);
}
void MDnsTransactionImpl::TriggerCallback(MDnsTransaction::Result result,
const RecordParsed* record) {
DCHECK(started_);
if (!is_active()) return;
// Ensure callback is run after touching all class state, so that
// the callback can delete the transaction.
MDnsTransaction::ResultCallback callback = callback_;
// Reset the transaction if it expects a single result, or if the result
// is a final one (everything except for a record).
if (flags_ & MDnsTransaction::SINGLE_RESULT ||
result != MDnsTransaction::RESULT_RECORD) {
Reset();
}
callback.Run(result, record);
}
void MDnsTransactionImpl::Reset() {
callback_.Reset();
listener_.reset();
timeout_.Cancel();
}
void MDnsTransactionImpl::OnRecordUpdate(MDnsListener::UpdateType update,
const RecordParsed* record) {
DCHECK(started_);
if (update == MDnsListener::RECORD_ADDED ||
update == MDnsListener::RECORD_CHANGED)
TriggerCallback(MDnsTransaction::RESULT_RECORD, record);
}
void MDnsTransactionImpl::SignalTransactionOver() {
DCHECK(started_);
if (flags_ & MDnsTransaction::SINGLE_RESULT) {
TriggerCallback(MDnsTransaction::RESULT_NO_RESULTS, nullptr);
} else {
TriggerCallback(MDnsTransaction::RESULT_DONE, nullptr);
}
}
void MDnsTransactionImpl::ServeRecordsFromCache() {
std::vector<const RecordParsed*> records;
base::WeakPtr<MDnsTransactionImpl> weak_this = weak_ptr_factory_.GetWeakPtr();
if (client_->core()) {
client_->core()->QueryCache(rrtype_, name_, &records);
for (auto i = records.begin(); i != records.end() && weak_this; ++i) {
weak_this->TriggerCallback(MDnsTransaction::RESULT_RECORD, *i);
}
#if defined(ENABLE_NSEC)
if (records.empty()) {
DCHECK(weak_this);
client_->core()->QueryCache(dns_protocol::kTypeNSEC, name_, &records);
if (!records.empty()) {
const NsecRecordRdata* rdata =
records.front()->rdata<NsecRecordRdata>();
DCHECK(rdata);
if (!rdata->GetBit(rrtype_))
weak_this->TriggerCallback(MDnsTransaction::RESULT_NSEC, nullptr);
}
}
#endif
}
}
bool MDnsTransactionImpl::QueryAndListen() {
listener_ = client_->CreateListener(rrtype_, name_, this);
if (!listener_->Start())
return false;
DCHECK(client_->core());
RecordQueryMetric(mdnsQueryType::kInitial, name_);
if (!client_->core()->SendQuery(rrtype_, name_))
return false;
timeout_.Reset(base::BindOnce(&MDnsTransactionImpl::SignalTransactionOver,
weak_ptr_factory_.GetWeakPtr()));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, timeout_.callback(), kTransactionTimeout);
return true;
}
void MDnsTransactionImpl::OnNsecRecord(const std::string& name, unsigned type) {
TriggerCallback(RESULT_NSEC, nullptr);
}
void MDnsTransactionImpl::OnCachePurged() {
// TODO(noamsml): Cache purge situations not yet implemented
}
} // namespace net
|