Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / dns / mdns_client_impl.cc
blob053d4fe3861a4f57fcc38d7d57cb01e39538ae70
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, const 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.
329 VLOG(1) << "MDNS OnConnectionError (code: " << error << ")";
332 void MDnsClientImpl::Core::AlertListeners(
333 MDnsCache::UpdateType update_type,
334 const ListenerKey& key,
335 const RecordParsed* record) {
336 ListenerMap::iterator listener_map_iterator = listeners_.find(key);
337 if (listener_map_iterator == listeners_.end()) return;
339 FOR_EACH_OBSERVER(MDnsListenerImpl, *listener_map_iterator->second,
340 HandleRecordUpdate(update_type, record));
343 void MDnsClientImpl::Core::AddListener(
344 MDnsListenerImpl* listener) {
345 ListenerKey key(listener->GetName(), listener->GetType());
346 std::pair<ListenerMap::iterator, bool> observer_insert_result =
347 listeners_.insert(make_pair(
348 key, static_cast<base::ObserverList<MDnsListenerImpl>*>(NULL)));
350 // If an equivalent key does not exist, actually create the observer list.
351 if (observer_insert_result.second)
352 observer_insert_result.first->second =
353 new base::ObserverList<MDnsListenerImpl>();
355 base::ObserverList<MDnsListenerImpl>* observer_list =
356 observer_insert_result.first->second;
358 observer_list->AddObserver(listener);
361 void MDnsClientImpl::Core::RemoveListener(MDnsListenerImpl* listener) {
362 ListenerKey key(listener->GetName(), listener->GetType());
363 ListenerMap::iterator observer_list_iterator = listeners_.find(key);
365 DCHECK(observer_list_iterator != listeners_.end());
366 DCHECK(observer_list_iterator->second->HasObserver(listener));
368 observer_list_iterator->second->RemoveObserver(listener);
370 // Remove the observer list from the map if it is empty
371 if (!observer_list_iterator->second->might_have_observers()) {
372 // Schedule the actual removal for later in case the listener removal
373 // happens while iterating over the observer list.
374 base::ThreadTaskRunnerHandle::Get()->PostTask(
375 FROM_HERE, base::Bind(&MDnsClientImpl::Core::CleanupObserverList,
376 AsWeakPtr(), key));
380 void MDnsClientImpl::Core::CleanupObserverList(const ListenerKey& key) {
381 ListenerMap::iterator found = listeners_.find(key);
382 if (found != listeners_.end() && !found->second->might_have_observers()) {
383 delete found->second;
384 listeners_.erase(found);
388 void MDnsClientImpl::Core::ScheduleCleanup(base::Time cleanup) {
389 // Cleanup is already scheduled, no need to do anything.
390 if (cleanup == scheduled_cleanup_) {
391 return;
393 scheduled_cleanup_ = cleanup;
395 // This cancels the previously scheduled cleanup.
396 cleanup_timer_->Stop();
398 // If |cleanup| is empty, then no cleanup necessary.
399 if (cleanup != base::Time()) {
400 cleanup_timer_->Start(
401 FROM_HERE, std::max(base::TimeDelta(), cleanup - clock_->Now()),
402 base::Bind(&MDnsClientImpl::Core::DoCleanup, base::Unretained(this)));
406 void MDnsClientImpl::Core::DoCleanup() {
407 cache_.CleanupRecords(clock_->Now(),
408 base::Bind(&MDnsClientImpl::Core::OnRecordRemoved,
409 base::Unretained(this)));
411 ScheduleCleanup(cache_.next_expiration());
414 void MDnsClientImpl::Core::OnRecordRemoved(
415 const RecordParsed* record) {
416 AlertListeners(MDnsCache::RecordRemoved,
417 ListenerKey(record->name(), record->type()), record);
420 void MDnsClientImpl::Core::QueryCache(
421 uint16 rrtype, const std::string& name,
422 std::vector<const RecordParsed*>* records) const {
423 cache_.FindDnsRecords(rrtype, name, records, clock_->Now());
426 MDnsClientImpl::MDnsClientImpl()
427 : clock_(new base::DefaultClock),
428 cleanup_timer_(new base::Timer(false, false)) {
431 MDnsClientImpl::MDnsClientImpl(scoped_ptr<base::Clock> clock,
432 scoped_ptr<base::Timer> timer)
433 : clock_(clock.Pass()), cleanup_timer_(timer.Pass()) {
436 MDnsClientImpl::~MDnsClientImpl() {
439 bool MDnsClientImpl::StartListening(MDnsSocketFactory* socket_factory) {
440 DCHECK(!core_.get());
441 core_.reset(new Core(clock_.get(), cleanup_timer_.get()));
442 if (!core_->Init(socket_factory)) {
443 core_.reset();
444 return false;
446 return true;
449 void MDnsClientImpl::StopListening() {
450 core_.reset();
453 bool MDnsClientImpl::IsListening() const {
454 return core_.get() != NULL;
457 scoped_ptr<MDnsListener> MDnsClientImpl::CreateListener(
458 uint16 rrtype,
459 const std::string& name,
460 MDnsListener::Delegate* delegate) {
461 return scoped_ptr<MDnsListener>(
462 new MDnsListenerImpl(rrtype, name, clock_.get(), delegate, this));
465 scoped_ptr<MDnsTransaction> MDnsClientImpl::CreateTransaction(
466 uint16 rrtype,
467 const std::string& name,
468 int flags,
469 const MDnsTransaction::ResultCallback& callback) {
470 return scoped_ptr<MDnsTransaction>(
471 new MDnsTransactionImpl(rrtype, name, flags, callback, this));
474 MDnsListenerImpl::MDnsListenerImpl(uint16 rrtype,
475 const std::string& name,
476 base::Clock* clock,
477 MDnsListener::Delegate* delegate,
478 MDnsClientImpl* client)
479 : rrtype_(rrtype),
480 name_(name),
481 clock_(clock),
482 client_(client),
483 delegate_(delegate),
484 started_(false),
485 active_refresh_(false) {
488 MDnsListenerImpl::~MDnsListenerImpl() {
489 if (started_) {
490 DCHECK(client_->core());
491 client_->core()->RemoveListener(this);
495 bool MDnsListenerImpl::Start() {
496 DCHECK(!started_);
498 started_ = true;
500 DCHECK(client_->core());
501 client_->core()->AddListener(this);
503 return true;
506 void MDnsListenerImpl::SetActiveRefresh(bool active_refresh) {
507 active_refresh_ = active_refresh;
509 if (started_) {
510 if (!active_refresh_) {
511 next_refresh_.Cancel();
512 } else if (last_update_ != base::Time()) {
513 ScheduleNextRefresh();
518 const std::string& MDnsListenerImpl::GetName() const {
519 return name_;
522 uint16 MDnsListenerImpl::GetType() const {
523 return rrtype_;
526 void MDnsListenerImpl::HandleRecordUpdate(MDnsCache::UpdateType update_type,
527 const RecordParsed* record) {
528 DCHECK(started_);
530 if (update_type != MDnsCache::RecordRemoved) {
531 ttl_ = record->ttl();
532 last_update_ = record->time_created();
534 ScheduleNextRefresh();
537 if (update_type != MDnsCache::NoChange) {
538 MDnsListener::UpdateType update_external;
540 switch (update_type) {
541 case MDnsCache::RecordAdded:
542 update_external = MDnsListener::RECORD_ADDED;
543 break;
544 case MDnsCache::RecordChanged:
545 update_external = MDnsListener::RECORD_CHANGED;
546 break;
547 case MDnsCache::RecordRemoved:
548 update_external = MDnsListener::RECORD_REMOVED;
549 break;
550 case MDnsCache::NoChange:
551 default:
552 NOTREACHED();
553 // Dummy assignment to suppress compiler warning.
554 update_external = MDnsListener::RECORD_CHANGED;
555 break;
558 delegate_->OnRecordUpdate(update_external, record);
562 void MDnsListenerImpl::AlertNsecRecord() {
563 DCHECK(started_);
564 delegate_->OnNsecRecord(name_, rrtype_);
567 void MDnsListenerImpl::ScheduleNextRefresh() {
568 DCHECK(last_update_ != base::Time());
570 if (!active_refresh_)
571 return;
573 // A zero TTL is a goodbye packet and should not be refreshed.
574 if (ttl_ == 0) {
575 next_refresh_.Cancel();
576 return;
579 next_refresh_.Reset(base::Bind(&MDnsListenerImpl::DoRefresh,
580 AsWeakPtr()));
582 // Schedule refreshes at both 85% and 95% of the original TTL. These will both
583 // be canceled and rescheduled if the record's TTL is updated due to a
584 // response being received.
585 base::Time next_refresh1 = last_update_ + base::TimeDelta::FromMilliseconds(
586 static_cast<int>(base::Time::kMillisecondsPerSecond *
587 kListenerRefreshRatio1 * ttl_));
589 base::Time next_refresh2 = last_update_ + base::TimeDelta::FromMilliseconds(
590 static_cast<int>(base::Time::kMillisecondsPerSecond *
591 kListenerRefreshRatio2 * ttl_));
593 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
594 FROM_HERE, next_refresh_.callback(), next_refresh1 - clock_->Now());
596 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
597 FROM_HERE, next_refresh_.callback(), next_refresh2 - clock_->Now());
600 void MDnsListenerImpl::DoRefresh() {
601 client_->core()->SendQuery(rrtype_, name_);
604 MDnsTransactionImpl::MDnsTransactionImpl(
605 uint16 rrtype,
606 const std::string& name,
607 int flags,
608 const MDnsTransaction::ResultCallback& callback,
609 MDnsClientImpl* client)
610 : rrtype_(rrtype), name_(name), callback_(callback), client_(client),
611 started_(false), flags_(flags) {
612 DCHECK((flags_ & MDnsTransaction::FLAG_MASK) == flags_);
613 DCHECK(flags_ & MDnsTransaction::QUERY_CACHE ||
614 flags_ & MDnsTransaction::QUERY_NETWORK);
617 MDnsTransactionImpl::~MDnsTransactionImpl() {
618 timeout_.Cancel();
621 bool MDnsTransactionImpl::Start() {
622 DCHECK(!started_);
623 started_ = true;
625 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
626 if (flags_ & MDnsTransaction::QUERY_CACHE) {
627 ServeRecordsFromCache();
629 if (!weak_this || !is_active()) return true;
632 if (flags_ & MDnsTransaction::QUERY_NETWORK) {
633 return QueryAndListen();
636 // If this is a cache only query, signal that the transaction is over
637 // immediately.
638 SignalTransactionOver();
639 return true;
642 const std::string& MDnsTransactionImpl::GetName() const {
643 return name_;
646 uint16 MDnsTransactionImpl::GetType() const {
647 return rrtype_;
650 void MDnsTransactionImpl::CacheRecordFound(const RecordParsed* record) {
651 DCHECK(started_);
652 OnRecordUpdate(MDnsListener::RECORD_ADDED, record);
655 void MDnsTransactionImpl::TriggerCallback(MDnsTransaction::Result result,
656 const RecordParsed* record) {
657 DCHECK(started_);
658 if (!is_active()) return;
660 // Ensure callback is run after touching all class state, so that
661 // the callback can delete the transaction.
662 MDnsTransaction::ResultCallback callback = callback_;
664 // Reset the transaction if it expects a single result, or if the result
665 // is a final one (everything except for a record).
666 if (flags_ & MDnsTransaction::SINGLE_RESULT ||
667 result != MDnsTransaction::RESULT_RECORD) {
668 Reset();
671 callback.Run(result, record);
674 void MDnsTransactionImpl::Reset() {
675 callback_.Reset();
676 listener_.reset();
677 timeout_.Cancel();
680 void MDnsTransactionImpl::OnRecordUpdate(MDnsListener::UpdateType update,
681 const RecordParsed* record) {
682 DCHECK(started_);
683 if (update == MDnsListener::RECORD_ADDED ||
684 update == MDnsListener::RECORD_CHANGED)
685 TriggerCallback(MDnsTransaction::RESULT_RECORD, record);
688 void MDnsTransactionImpl::SignalTransactionOver() {
689 DCHECK(started_);
690 if (flags_ & MDnsTransaction::SINGLE_RESULT) {
691 TriggerCallback(MDnsTransaction::RESULT_NO_RESULTS, NULL);
692 } else {
693 TriggerCallback(MDnsTransaction::RESULT_DONE, NULL);
697 void MDnsTransactionImpl::ServeRecordsFromCache() {
698 std::vector<const RecordParsed*> records;
699 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
701 if (client_->core()) {
702 client_->core()->QueryCache(rrtype_, name_, &records);
703 for (std::vector<const RecordParsed*>::iterator i = records.begin();
704 i != records.end() && weak_this; ++i) {
705 weak_this->TriggerCallback(MDnsTransaction::RESULT_RECORD, *i);
708 #if defined(ENABLE_NSEC)
709 if (records.empty()) {
710 DCHECK(weak_this);
711 client_->core()->QueryCache(dns_protocol::kTypeNSEC, name_, &records);
712 if (!records.empty()) {
713 const NsecRecordRdata* rdata =
714 records.front()->rdata<NsecRecordRdata>();
715 DCHECK(rdata);
716 if (!rdata->GetBit(rrtype_))
717 weak_this->TriggerCallback(MDnsTransaction::RESULT_NSEC, NULL);
720 #endif
724 bool MDnsTransactionImpl::QueryAndListen() {
725 listener_ = client_->CreateListener(rrtype_, name_, this);
726 if (!listener_->Start())
727 return false;
729 DCHECK(client_->core());
730 if (!client_->core()->SendQuery(rrtype_, name_))
731 return false;
733 timeout_.Reset(base::Bind(&MDnsTransactionImpl::SignalTransactionOver,
734 AsWeakPtr()));
735 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
736 FROM_HERE, timeout_.callback(),
737 base::TimeDelta::FromSeconds(MDnsTransactionTimeoutSeconds));
739 return true;
742 void MDnsTransactionImpl::OnNsecRecord(const std::string& name, unsigned type) {
743 TriggerCallback(RESULT_NSEC, NULL);
746 void MDnsTransactionImpl::OnCachePurged() {
747 // TODO(noamsml): Cache purge situations not yet implemented
750 } // namespace net