If there are no local credentials for a locked profile, show sign in button
[chromium-blink-merge.git] / net / dns / mdns_client_impl.cc
blob49fdd54d1685a422fa5ecb07dfce3a29c48bb549
1 // 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.
5 #include "net/dns/mdns_client_impl.h"
7 #include <algorithm>
8 #include <queue>
10 #include "base/bind.h"
11 #include "base/location.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/stl_util.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "base/time/clock.h"
16 #include "base/time/default_clock.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "net/base/dns_util.h"
20 #include "net/base/net_errors.h"
21 #include "net/base/rand_callback.h"
22 #include "net/dns/dns_protocol.h"
23 #include "net/dns/record_rdata.h"
24 #include "net/log/net_log.h"
25 #include "net/udp/datagram_socket.h"
27 // TODO(gene): Remove this temporary method of disabling NSEC support once it
28 // becomes clear whether this feature should be
29 // supported. http://crbug.com/255232
30 #define ENABLE_NSEC
32 namespace net {
34 namespace {
36 const unsigned MDnsTransactionTimeoutSeconds = 3;
37 // 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.
41 const double kListenerRefreshRatio1 = 0.85;
42 const double kListenerRefreshRatio2 = 0.95;
44 } // namespace
46 void MDnsSocketFactoryImpl::CreateSockets(
47 ScopedVector<DatagramServerSocket>* sockets) {
48 InterfaceIndexFamilyList interfaces(GetMDnsInterfacesToBind());
49 for (size_t i = 0; i < interfaces.size(); ++i) {
50 DCHECK(interfaces[i].second == ADDRESS_FAMILY_IPV4 ||
51 interfaces[i].second == ADDRESS_FAMILY_IPV6);
52 scoped_ptr<DatagramServerSocket> socket(
53 CreateAndBindMDnsSocket(interfaces[i].second, interfaces[i].first));
54 if (socket)
55 sockets->push_back(socket.Pass());
59 MDnsConnection::SocketHandler::SocketHandler(
60 scoped_ptr<DatagramServerSocket> socket,
61 MDnsConnection* connection)
62 : socket_(socket.Pass()),
63 connection_(connection),
64 response_(dns_protocol::kMaxMulticastSize),
65 send_in_progress_(false) {
68 MDnsConnection::SocketHandler::~SocketHandler() {
71 int MDnsConnection::SocketHandler::Start() {
72 IPEndPoint end_point;
73 int rv = socket_->GetLocalAddress(&end_point);
74 if (rv != OK)
75 return rv;
76 DCHECK(end_point.GetFamily() == ADDRESS_FAMILY_IPV4 ||
77 end_point.GetFamily() == ADDRESS_FAMILY_IPV6);
78 multicast_addr_ = GetMDnsIPEndPoint(end_point.GetFamily());
79 return DoLoop(0);
82 int MDnsConnection::SocketHandler::DoLoop(int rv) {
83 do {
84 if (rv > 0)
85 connection_->OnDatagramReceived(&response_, recv_addr_, rv);
87 rv = socket_->RecvFrom(
88 response_.io_buffer(), response_.io_buffer()->size(), &recv_addr_,
89 base::Bind(&MDnsConnection::SocketHandler::OnDatagramReceived,
90 base::Unretained(this)));
91 } while (rv > 0);
93 if (rv != ERR_IO_PENDING)
94 return rv;
96 return OK;
99 void MDnsConnection::SocketHandler::OnDatagramReceived(int rv) {
100 if (rv >= OK)
101 rv = DoLoop(rv);
103 if (rv != OK)
104 connection_->PostOnError(this, rv);
107 void MDnsConnection::SocketHandler::Send(const scoped_refptr<IOBuffer>& buffer,
108 unsigned size) {
109 if (send_in_progress_) {
110 send_queue_.push(std::make_pair(buffer, size));
111 return;
113 int rv = socket_->SendTo(buffer.get(),
114 size,
115 multicast_addr_,
116 base::Bind(&MDnsConnection::SocketHandler::SendDone,
117 base::Unretained(this)));
118 if (rv == ERR_IO_PENDING) {
119 send_in_progress_ = true;
120 } else if (rv < OK) {
121 connection_->PostOnError(this, rv);
125 void MDnsConnection::SocketHandler::SendDone(int rv) {
126 DCHECK(send_in_progress_);
127 send_in_progress_ = false;
128 if (rv != OK)
129 connection_->PostOnError(this, rv);
130 while (!send_in_progress_ && !send_queue_.empty()) {
131 std::pair<scoped_refptr<IOBuffer>, unsigned> buffer = send_queue_.front();
132 send_queue_.pop();
133 Send(buffer.first, buffer.second);
137 MDnsConnection::MDnsConnection(MDnsConnection::Delegate* delegate)
138 : delegate_(delegate), weak_ptr_factory_(this) {
141 MDnsConnection::~MDnsConnection() {
144 bool MDnsConnection::Init(MDnsSocketFactory* socket_factory) {
145 ScopedVector<DatagramServerSocket> sockets;
146 socket_factory->CreateSockets(&sockets);
148 for (size_t i = 0; i < sockets.size(); ++i) {
149 socket_handlers_.push_back(
150 new MDnsConnection::SocketHandler(make_scoped_ptr(sockets[i]), this));
152 sockets.weak_clear();
154 // All unbound sockets need to be bound before processing untrusted input.
155 // This is done for security reasons, so that an attacker can't get an unbound
156 // socket.
157 for (size_t i = 0; i < socket_handlers_.size();) {
158 int rv = socket_handlers_[i]->Start();
159 if (rv != OK) {
160 socket_handlers_.erase(socket_handlers_.begin() + i);
161 VLOG(1) << "Start failed, socket=" << i << ", error=" << rv;
162 } else {
163 ++i;
166 VLOG(1) << "Sockets ready:" << socket_handlers_.size();
167 return !socket_handlers_.empty();
170 void MDnsConnection::Send(const scoped_refptr<IOBuffer>& buffer,
171 unsigned size) {
172 for (size_t i = 0; i < socket_handlers_.size(); ++i)
173 socket_handlers_[i]->Send(buffer, size);
176 void MDnsConnection::PostOnError(SocketHandler* loop, int rv) {
177 VLOG(1) << "Socket error. id="
178 << std::find(socket_handlers_.begin(), socket_handlers_.end(), loop) -
179 socket_handlers_.begin() << ", error=" << rv;
180 // Post to allow deletion of this object by delegate.
181 base::ThreadTaskRunnerHandle::Get()->PostTask(
182 FROM_HERE,
183 base::Bind(&MDnsConnection::OnError, weak_ptr_factory_.GetWeakPtr(), rv));
186 void MDnsConnection::OnError(int rv) {
187 // TODO(noamsml): Specific handling of intermittent errors that can be handled
188 // in the connection.
189 delegate_->OnConnectionError(rv);
192 void MDnsConnection::OnDatagramReceived(
193 DnsResponse* response,
194 const IPEndPoint& recv_addr,
195 int bytes_read) {
196 // TODO(noamsml): More sophisticated error handling.
197 DCHECK_GT(bytes_read, 0);
198 delegate_->HandlePacket(response, bytes_read);
201 MDnsClientImpl::Core::Core(base::Clock* clock, base::Timer* timer)
202 : clock_(clock),
203 cleanup_timer_(timer),
204 connection_(new MDnsConnection(this)) {
207 MDnsClientImpl::Core::~Core() {
208 STLDeleteValues(&listeners_);
211 bool MDnsClientImpl::Core::Init(MDnsSocketFactory* socket_factory) {
212 return connection_->Init(socket_factory);
215 bool MDnsClientImpl::Core::SendQuery(uint16 rrtype, std::string name) {
216 std::string name_dns;
217 if (!DNSDomainFromDot(name, &name_dns))
218 return false;
220 DnsQuery query(0, name_dns, rrtype);
221 query.set_flags(0); // Remove the RD flag from the query. It is unneeded.
223 connection_->Send(query.io_buffer(), query.io_buffer()->size());
224 return true;
227 void MDnsClientImpl::Core::HandlePacket(DnsResponse* response,
228 int bytes_read) {
229 unsigned offset;
230 // Note: We store cache keys rather than record pointers to avoid
231 // erroneous behavior in case a packet contains multiple exclusive
232 // records with the same type and name.
233 std::map<MDnsCache::Key, MDnsCache::UpdateType> update_keys;
235 if (!response->InitParseWithoutQuery(bytes_read)) {
236 DVLOG(1) << "Could not understand an mDNS packet.";
237 return; // Message is unreadable.
240 // TODO(noamsml): duplicate query suppression.
241 if (!(response->flags() & dns_protocol::kFlagResponse))
242 return; // Message is a query. ignore it.
244 DnsRecordParser parser = response->Parser();
245 unsigned answer_count = response->answer_count() +
246 response->additional_answer_count();
248 for (unsigned i = 0; i < answer_count; i++) {
249 offset = parser.GetOffset();
250 scoped_ptr<const RecordParsed> record =
251 RecordParsed::CreateFrom(&parser, clock_->Now());
253 if (!record) {
254 DVLOG(1) << "Could not understand an mDNS record.";
256 if (offset == parser.GetOffset()) {
257 DVLOG(1) << "Abandoned parsing the rest of the packet.";
258 return; // The parser did not advance, abort reading the packet.
259 } else {
260 continue; // We may be able to extract other records from the packet.
264 if ((record->klass() & dns_protocol::kMDnsClassMask) !=
265 dns_protocol::kClassIN) {
266 DVLOG(1) << "Received an mDNS record with non-IN class. Ignoring.";
267 continue; // Ignore all records not in the IN class.
270 MDnsCache::Key update_key = MDnsCache::Key::CreateFor(record.get());
271 MDnsCache::UpdateType update = cache_.UpdateDnsRecord(record.Pass());
273 // Cleanup time may have changed.
274 ScheduleCleanup(cache_.next_expiration());
276 update_keys.insert(std::make_pair(update_key, update));
279 for (std::map<MDnsCache::Key, MDnsCache::UpdateType>::iterator i =
280 update_keys.begin(); i != update_keys.end(); i++) {
281 const RecordParsed* record = cache_.LookupKey(i->first);
282 if (!record)
283 continue;
285 if (record->type() == dns_protocol::kTypeNSEC) {
286 #if defined(ENABLE_NSEC)
287 NotifyNsecRecord(record);
288 #endif
289 } else {
290 AlertListeners(i->second, ListenerKey(record->name(), record->type()),
291 record);
296 void MDnsClientImpl::Core::NotifyNsecRecord(const RecordParsed* record) {
297 DCHECK_EQ(dns_protocol::kTypeNSEC, record->type());
298 const NsecRecordRdata* rdata = record->rdata<NsecRecordRdata>();
299 DCHECK(rdata);
301 // Remove all cached records matching the nonexistent RR types.
302 std::vector<const RecordParsed*> records_to_remove;
304 cache_.FindDnsRecords(0, record->name(), &records_to_remove, clock_->Now());
306 for (std::vector<const RecordParsed*>::iterator i = records_to_remove.begin();
307 i != records_to_remove.end(); i++) {
308 if ((*i)->type() == dns_protocol::kTypeNSEC)
309 continue;
310 if (!rdata->GetBit((*i)->type())) {
311 scoped_ptr<const RecordParsed> record_removed = cache_.RemoveRecord((*i));
312 DCHECK(record_removed);
313 OnRecordRemoved(record_removed.get());
317 // Alert all listeners waiting for the nonexistent RR types.
318 ListenerMap::iterator i =
319 listeners_.upper_bound(ListenerKey(record->name(), 0));
320 for (; i != listeners_.end() && i->first.first == record->name(); i++) {
321 if (!rdata->GetBit(i->first.second)) {
322 FOR_EACH_OBSERVER(MDnsListenerImpl, *i->second, AlertNsecRecord());
327 void MDnsClientImpl::Core::OnConnectionError(int error) {
328 // TODO(noamsml): On connection error, recreate connection and flush cache.
331 void MDnsClientImpl::Core::AlertListeners(
332 MDnsCache::UpdateType update_type,
333 const ListenerKey& key,
334 const RecordParsed* record) {
335 ListenerMap::iterator listener_map_iterator = listeners_.find(key);
336 if (listener_map_iterator == listeners_.end()) return;
338 FOR_EACH_OBSERVER(MDnsListenerImpl, *listener_map_iterator->second,
339 HandleRecordUpdate(update_type, record));
342 void MDnsClientImpl::Core::AddListener(
343 MDnsListenerImpl* listener) {
344 ListenerKey key(listener->GetName(), listener->GetType());
345 std::pair<ListenerMap::iterator, bool> observer_insert_result =
346 listeners_.insert(make_pair(
347 key, static_cast<base::ObserverList<MDnsListenerImpl>*>(NULL)));
349 // If an equivalent key does not exist, actually create the observer list.
350 if (observer_insert_result.second)
351 observer_insert_result.first->second =
352 new base::ObserverList<MDnsListenerImpl>();
354 base::ObserverList<MDnsListenerImpl>* observer_list =
355 observer_insert_result.first->second;
357 observer_list->AddObserver(listener);
360 void MDnsClientImpl::Core::RemoveListener(MDnsListenerImpl* listener) {
361 ListenerKey key(listener->GetName(), listener->GetType());
362 ListenerMap::iterator observer_list_iterator = listeners_.find(key);
364 DCHECK(observer_list_iterator != listeners_.end());
365 DCHECK(observer_list_iterator->second->HasObserver(listener));
367 observer_list_iterator->second->RemoveObserver(listener);
369 // Remove the observer list from the map if it is empty
370 if (!observer_list_iterator->second->might_have_observers()) {
371 // Schedule the actual removal for later in case the listener removal
372 // happens while iterating over the observer list.
373 base::ThreadTaskRunnerHandle::Get()->PostTask(
374 FROM_HERE, base::Bind(&MDnsClientImpl::Core::CleanupObserverList,
375 AsWeakPtr(), key));
379 void MDnsClientImpl::Core::CleanupObserverList(const ListenerKey& key) {
380 ListenerMap::iterator found = listeners_.find(key);
381 if (found != listeners_.end() && !found->second->might_have_observers()) {
382 delete found->second;
383 listeners_.erase(found);
387 void MDnsClientImpl::Core::ScheduleCleanup(base::Time cleanup) {
388 // Cleanup is already scheduled, no need to do anything.
389 if (cleanup == scheduled_cleanup_) {
390 return;
392 scheduled_cleanup_ = cleanup;
394 // This cancels the previously scheduled cleanup.
395 cleanup_timer_->Stop();
397 // If |cleanup| is empty, then no cleanup necessary.
398 if (cleanup != base::Time()) {
399 cleanup_timer_->Start(
400 FROM_HERE, std::max(base::TimeDelta(), cleanup - clock_->Now()),
401 base::Bind(&MDnsClientImpl::Core::DoCleanup, base::Unretained(this)));
405 void MDnsClientImpl::Core::DoCleanup() {
406 cache_.CleanupRecords(clock_->Now(),
407 base::Bind(&MDnsClientImpl::Core::OnRecordRemoved,
408 base::Unretained(this)));
410 ScheduleCleanup(cache_.next_expiration());
413 void MDnsClientImpl::Core::OnRecordRemoved(
414 const RecordParsed* record) {
415 AlertListeners(MDnsCache::RecordRemoved,
416 ListenerKey(record->name(), record->type()), record);
419 void MDnsClientImpl::Core::QueryCache(
420 uint16 rrtype, const std::string& name,
421 std::vector<const RecordParsed*>* records) const {
422 cache_.FindDnsRecords(rrtype, name, records, clock_->Now());
425 MDnsClientImpl::MDnsClientImpl()
426 : clock_(new base::DefaultClock),
427 cleanup_timer_(new base::Timer(false, false)) {
430 MDnsClientImpl::MDnsClientImpl(scoped_ptr<base::Clock> clock,
431 scoped_ptr<base::Timer> timer)
432 : clock_(clock.Pass()), cleanup_timer_(timer.Pass()) {
435 MDnsClientImpl::~MDnsClientImpl() {
438 bool MDnsClientImpl::StartListening(MDnsSocketFactory* socket_factory) {
439 DCHECK(!core_.get());
440 core_.reset(new Core(clock_.get(), cleanup_timer_.get()));
441 if (!core_->Init(socket_factory)) {
442 core_.reset();
443 return false;
445 return true;
448 void MDnsClientImpl::StopListening() {
449 core_.reset();
452 bool MDnsClientImpl::IsListening() const {
453 return core_.get() != NULL;
456 scoped_ptr<MDnsListener> MDnsClientImpl::CreateListener(
457 uint16 rrtype,
458 const std::string& name,
459 MDnsListener::Delegate* delegate) {
460 return scoped_ptr<MDnsListener>(
461 new MDnsListenerImpl(rrtype, name, clock_.get(), delegate, this));
464 scoped_ptr<MDnsTransaction> MDnsClientImpl::CreateTransaction(
465 uint16 rrtype,
466 const std::string& name,
467 int flags,
468 const MDnsTransaction::ResultCallback& callback) {
469 return scoped_ptr<MDnsTransaction>(
470 new MDnsTransactionImpl(rrtype, name, flags, callback, this));
473 MDnsListenerImpl::MDnsListenerImpl(uint16 rrtype,
474 const std::string& name,
475 base::Clock* clock,
476 MDnsListener::Delegate* delegate,
477 MDnsClientImpl* client)
478 : rrtype_(rrtype),
479 name_(name),
480 clock_(clock),
481 client_(client),
482 delegate_(delegate),
483 started_(false),
484 active_refresh_(false) {
487 MDnsListenerImpl::~MDnsListenerImpl() {
488 if (started_) {
489 DCHECK(client_->core());
490 client_->core()->RemoveListener(this);
494 bool MDnsListenerImpl::Start() {
495 DCHECK(!started_);
497 started_ = true;
499 DCHECK(client_->core());
500 client_->core()->AddListener(this);
502 return true;
505 void MDnsListenerImpl::SetActiveRefresh(bool active_refresh) {
506 active_refresh_ = active_refresh;
508 if (started_) {
509 if (!active_refresh_) {
510 next_refresh_.Cancel();
511 } else if (last_update_ != base::Time()) {
512 ScheduleNextRefresh();
517 const std::string& MDnsListenerImpl::GetName() const {
518 return name_;
521 uint16 MDnsListenerImpl::GetType() const {
522 return rrtype_;
525 void MDnsListenerImpl::HandleRecordUpdate(MDnsCache::UpdateType update_type,
526 const RecordParsed* record) {
527 DCHECK(started_);
529 if (update_type != MDnsCache::RecordRemoved) {
530 ttl_ = record->ttl();
531 last_update_ = record->time_created();
533 ScheduleNextRefresh();
536 if (update_type != MDnsCache::NoChange) {
537 MDnsListener::UpdateType update_external;
539 switch (update_type) {
540 case MDnsCache::RecordAdded:
541 update_external = MDnsListener::RECORD_ADDED;
542 break;
543 case MDnsCache::RecordChanged:
544 update_external = MDnsListener::RECORD_CHANGED;
545 break;
546 case MDnsCache::RecordRemoved:
547 update_external = MDnsListener::RECORD_REMOVED;
548 break;
549 case MDnsCache::NoChange:
550 default:
551 NOTREACHED();
552 // Dummy assignment to suppress compiler warning.
553 update_external = MDnsListener::RECORD_CHANGED;
554 break;
557 delegate_->OnRecordUpdate(update_external, record);
561 void MDnsListenerImpl::AlertNsecRecord() {
562 DCHECK(started_);
563 delegate_->OnNsecRecord(name_, rrtype_);
566 void MDnsListenerImpl::ScheduleNextRefresh() {
567 DCHECK(last_update_ != base::Time());
569 if (!active_refresh_)
570 return;
572 // A zero TTL is a goodbye packet and should not be refreshed.
573 if (ttl_ == 0) {
574 next_refresh_.Cancel();
575 return;
578 next_refresh_.Reset(base::Bind(&MDnsListenerImpl::DoRefresh,
579 AsWeakPtr()));
581 // Schedule refreshes at both 85% and 95% of the original TTL. These will both
582 // be canceled and rescheduled if the record's TTL is updated due to a
583 // response being received.
584 base::Time next_refresh1 = last_update_ + base::TimeDelta::FromMilliseconds(
585 static_cast<int>(base::Time::kMillisecondsPerSecond *
586 kListenerRefreshRatio1 * ttl_));
588 base::Time next_refresh2 = last_update_ + base::TimeDelta::FromMilliseconds(
589 static_cast<int>(base::Time::kMillisecondsPerSecond *
590 kListenerRefreshRatio2 * ttl_));
592 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
593 FROM_HERE, next_refresh_.callback(), next_refresh1 - clock_->Now());
595 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
596 FROM_HERE, next_refresh_.callback(), next_refresh2 - clock_->Now());
599 void MDnsListenerImpl::DoRefresh() {
600 client_->core()->SendQuery(rrtype_, name_);
603 MDnsTransactionImpl::MDnsTransactionImpl(
604 uint16 rrtype,
605 const std::string& name,
606 int flags,
607 const MDnsTransaction::ResultCallback& callback,
608 MDnsClientImpl* client)
609 : rrtype_(rrtype), name_(name), callback_(callback), client_(client),
610 started_(false), flags_(flags) {
611 DCHECK((flags_ & MDnsTransaction::FLAG_MASK) == flags_);
612 DCHECK(flags_ & MDnsTransaction::QUERY_CACHE ||
613 flags_ & MDnsTransaction::QUERY_NETWORK);
616 MDnsTransactionImpl::~MDnsTransactionImpl() {
617 timeout_.Cancel();
620 bool MDnsTransactionImpl::Start() {
621 DCHECK(!started_);
622 started_ = true;
624 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
625 if (flags_ & MDnsTransaction::QUERY_CACHE) {
626 ServeRecordsFromCache();
628 if (!weak_this || !is_active()) return true;
631 if (flags_ & MDnsTransaction::QUERY_NETWORK) {
632 return QueryAndListen();
635 // If this is a cache only query, signal that the transaction is over
636 // immediately.
637 SignalTransactionOver();
638 return true;
641 const std::string& MDnsTransactionImpl::GetName() const {
642 return name_;
645 uint16 MDnsTransactionImpl::GetType() const {
646 return rrtype_;
649 void MDnsTransactionImpl::CacheRecordFound(const RecordParsed* record) {
650 DCHECK(started_);
651 OnRecordUpdate(MDnsListener::RECORD_ADDED, record);
654 void MDnsTransactionImpl::TriggerCallback(MDnsTransaction::Result result,
655 const RecordParsed* record) {
656 DCHECK(started_);
657 if (!is_active()) return;
659 // Ensure callback is run after touching all class state, so that
660 // the callback can delete the transaction.
661 MDnsTransaction::ResultCallback callback = callback_;
663 // Reset the transaction if it expects a single result, or if the result
664 // is a final one (everything except for a record).
665 if (flags_ & MDnsTransaction::SINGLE_RESULT ||
666 result != MDnsTransaction::RESULT_RECORD) {
667 Reset();
670 callback.Run(result, record);
673 void MDnsTransactionImpl::Reset() {
674 callback_.Reset();
675 listener_.reset();
676 timeout_.Cancel();
679 void MDnsTransactionImpl::OnRecordUpdate(MDnsListener::UpdateType update,
680 const RecordParsed* record) {
681 DCHECK(started_);
682 if (update == MDnsListener::RECORD_ADDED ||
683 update == MDnsListener::RECORD_CHANGED)
684 TriggerCallback(MDnsTransaction::RESULT_RECORD, record);
687 void MDnsTransactionImpl::SignalTransactionOver() {
688 DCHECK(started_);
689 if (flags_ & MDnsTransaction::SINGLE_RESULT) {
690 TriggerCallback(MDnsTransaction::RESULT_NO_RESULTS, NULL);
691 } else {
692 TriggerCallback(MDnsTransaction::RESULT_DONE, NULL);
696 void MDnsTransactionImpl::ServeRecordsFromCache() {
697 std::vector<const RecordParsed*> records;
698 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
700 if (client_->core()) {
701 client_->core()->QueryCache(rrtype_, name_, &records);
702 for (std::vector<const RecordParsed*>::iterator i = records.begin();
703 i != records.end() && weak_this; ++i) {
704 weak_this->TriggerCallback(MDnsTransaction::RESULT_RECORD, *i);
707 #if defined(ENABLE_NSEC)
708 if (records.empty()) {
709 DCHECK(weak_this);
710 client_->core()->QueryCache(dns_protocol::kTypeNSEC, name_, &records);
711 if (!records.empty()) {
712 const NsecRecordRdata* rdata =
713 records.front()->rdata<NsecRecordRdata>();
714 DCHECK(rdata);
715 if (!rdata->GetBit(rrtype_))
716 weak_this->TriggerCallback(MDnsTransaction::RESULT_NSEC, NULL);
719 #endif
723 bool MDnsTransactionImpl::QueryAndListen() {
724 listener_ = client_->CreateListener(rrtype_, name_, this);
725 if (!listener_->Start())
726 return false;
728 DCHECK(client_->core());
729 if (!client_->core()->SendQuery(rrtype_, name_))
730 return false;
732 timeout_.Reset(base::Bind(&MDnsTransactionImpl::SignalTransactionOver,
733 AsWeakPtr()));
734 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
735 FROM_HERE, timeout_.callback(),
736 base::TimeDelta::FromSeconds(MDnsTransactionTimeoutSeconds));
738 return true;
741 void MDnsTransactionImpl::OnNsecRecord(const std::string& name, unsigned type) {
742 TriggerCallback(RESULT_NSEC, NULL);
745 void MDnsTransactionImpl::OnCachePurged() {
746 // TODO(noamsml): Cache purge situations not yet implemented
749 } // namespace net