Roll src/third_party/skia ff271c2:b679ca8
[chromium-blink-merge.git] / net / dns / mdns_client_impl.cc
blob1c313d81bdc543794493dfa24257d8d30bc048af
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/message_loop/message_loop_proxy.h"
12 #include "base/stl_util.h"
13 #include "base/time/clock.h"
14 #include "base/time/default_clock.h"
15 #include "base/time/time.h"
16 #include "base/timer/timer.h"
17 #include "net/base/dns_util.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/rand_callback.h"
20 #include "net/dns/dns_protocol.h"
21 #include "net/dns/record_rdata.h"
22 #include "net/log/net_log.h"
23 #include "net/udp/datagram_socket.h"
25 // TODO(gene): Remove this temporary method of disabling NSEC support once it
26 // becomes clear whether this feature should be
27 // supported. http://crbug.com/255232
28 #define ENABLE_NSEC
30 namespace net {
32 namespace {
34 const unsigned MDnsTransactionTimeoutSeconds = 3;
35 // The fractions of the record's original TTL after which an active listener
36 // (one that had |SetActiveRefresh(true)| called) will send a query to refresh
37 // its cache. This happens both at 85% of the original TTL and again at 95% of
38 // the original TTL.
39 const double kListenerRefreshRatio1 = 0.85;
40 const double kListenerRefreshRatio2 = 0.95;
42 } // namespace
44 void MDnsSocketFactoryImpl::CreateSockets(
45 ScopedVector<DatagramServerSocket>* sockets) {
46 InterfaceIndexFamilyList interfaces(GetMDnsInterfacesToBind());
47 for (size_t i = 0; i < interfaces.size(); ++i) {
48 DCHECK(interfaces[i].second == net::ADDRESS_FAMILY_IPV4 ||
49 interfaces[i].second == net::ADDRESS_FAMILY_IPV6);
50 scoped_ptr<DatagramServerSocket> socket(
51 CreateAndBindMDnsSocket(interfaces[i].second, interfaces[i].first));
52 if (socket)
53 sockets->push_back(socket.release());
57 MDnsConnection::SocketHandler::SocketHandler(
58 scoped_ptr<DatagramServerSocket> socket,
59 MDnsConnection* connection)
60 : socket_(socket.Pass()),
61 connection_(connection),
62 response_(dns_protocol::kMaxMulticastSize),
63 send_in_progress_(false) {
66 MDnsConnection::SocketHandler::~SocketHandler() {
69 int MDnsConnection::SocketHandler::Start() {
70 IPEndPoint end_point;
71 int rv = socket_->GetLocalAddress(&end_point);
72 if (rv != OK)
73 return rv;
74 DCHECK(end_point.GetFamily() == ADDRESS_FAMILY_IPV4 ||
75 end_point.GetFamily() == ADDRESS_FAMILY_IPV6);
76 multicast_addr_ = GetMDnsIPEndPoint(end_point.GetFamily());
77 return DoLoop(0);
80 int MDnsConnection::SocketHandler::DoLoop(int rv) {
81 do {
82 if (rv > 0)
83 connection_->OnDatagramReceived(&response_, recv_addr_, rv);
85 rv = socket_->RecvFrom(
86 response_.io_buffer(), response_.io_buffer()->size(), &recv_addr_,
87 base::Bind(&MDnsConnection::SocketHandler::OnDatagramReceived,
88 base::Unretained(this)));
89 } while (rv > 0);
91 if (rv != ERR_IO_PENDING)
92 return rv;
94 return OK;
97 void MDnsConnection::SocketHandler::OnDatagramReceived(int rv) {
98 if (rv >= OK)
99 rv = DoLoop(rv);
101 if (rv != OK)
102 connection_->PostOnError(this, rv);
105 void 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;
111 int rv = socket_->SendTo(buffer.get(),
112 size,
113 multicast_addr_,
114 base::Bind(&MDnsConnection::SocketHandler::SendDone,
115 base::Unretained(this)));
116 if (rv == ERR_IO_PENDING) {
117 send_in_progress_ = true;
118 } else if (rv < OK) {
119 connection_->PostOnError(this, rv);
123 void MDnsConnection::SocketHandler::SendDone(int rv) {
124 DCHECK(send_in_progress_);
125 send_in_progress_ = false;
126 if (rv != OK)
127 connection_->PostOnError(this, rv);
128 while (!send_in_progress_ && !send_queue_.empty()) {
129 std::pair<scoped_refptr<IOBuffer>, unsigned> buffer = send_queue_.front();
130 send_queue_.pop();
131 Send(buffer.first, buffer.second);
135 MDnsConnection::MDnsConnection(MDnsConnection::Delegate* delegate)
136 : delegate_(delegate), weak_ptr_factory_(this) {
139 MDnsConnection::~MDnsConnection() {
142 bool MDnsConnection::Init(MDnsSocketFactory* socket_factory) {
143 ScopedVector<DatagramServerSocket> sockets;
144 socket_factory->CreateSockets(&sockets);
146 for (size_t i = 0; i < sockets.size(); ++i) {
147 socket_handlers_.push_back(
148 new MDnsConnection::SocketHandler(make_scoped_ptr(sockets[i]), this));
150 sockets.weak_clear();
152 // All unbound sockets need to be bound before processing untrusted input.
153 // This is done for security reasons, so that an attacker can't get an unbound
154 // socket.
155 for (size_t i = 0; i < socket_handlers_.size();) {
156 int rv = socket_handlers_[i]->Start();
157 if (rv != OK) {
158 socket_handlers_.erase(socket_handlers_.begin() + i);
159 VLOG(1) << "Start failed, socket=" << i << ", error=" << rv;
160 } else {
161 ++i;
164 VLOG(1) << "Sockets ready:" << socket_handlers_.size();
165 return !socket_handlers_.empty();
168 void MDnsConnection::Send(const scoped_refptr<IOBuffer>& buffer,
169 unsigned size) {
170 for (size_t i = 0; i < socket_handlers_.size(); ++i)
171 socket_handlers_[i]->Send(buffer, size);
174 void MDnsConnection::PostOnError(SocketHandler* loop, int rv) {
175 VLOG(1) << "Socket error. id="
176 << std::find(socket_handlers_.begin(), socket_handlers_.end(), loop) -
177 socket_handlers_.begin() << ", error=" << rv;
178 // Post to allow deletion of this object by delegate.
179 base::MessageLoop::current()->PostTask(
180 FROM_HERE,
181 base::Bind(&MDnsConnection::OnError, weak_ptr_factory_.GetWeakPtr(), rv));
184 void MDnsConnection::OnError(int rv) {
185 // TODO(noamsml): Specific handling of intermittent errors that can be handled
186 // in the connection.
187 delegate_->OnConnectionError(rv);
190 void MDnsConnection::OnDatagramReceived(
191 DnsResponse* response,
192 const IPEndPoint& recv_addr,
193 int bytes_read) {
194 // TODO(noamsml): More sophisticated error handling.
195 DCHECK_GT(bytes_read, 0);
196 delegate_->HandlePacket(response, bytes_read);
199 MDnsClientImpl::Core::Core(base::Clock* clock, base::Timer* timer)
200 : clock_(clock),
201 cleanup_timer_(timer),
202 connection_(new MDnsConnection(this)) {
205 MDnsClientImpl::Core::~Core() {
206 STLDeleteValues(&listeners_);
209 bool MDnsClientImpl::Core::Init(MDnsSocketFactory* socket_factory) {
210 return connection_->Init(socket_factory);
213 bool MDnsClientImpl::Core::SendQuery(uint16 rrtype, std::string name) {
214 std::string name_dns;
215 if (!DNSDomainFromDot(name, &name_dns))
216 return false;
218 DnsQuery query(0, name_dns, rrtype);
219 query.set_flags(0); // Remove the RD flag from the query. It is unneeded.
221 connection_->Send(query.io_buffer(), query.io_buffer()->size());
222 return true;
225 void MDnsClientImpl::Core::HandlePacket(DnsResponse* response,
226 int bytes_read) {
227 unsigned offset;
228 // Note: We store cache keys rather than record pointers to avoid
229 // erroneous behavior in case a packet contains multiple exclusive
230 // records with the same type and name.
231 std::map<MDnsCache::Key, MDnsCache::UpdateType> update_keys;
233 if (!response->InitParseWithoutQuery(bytes_read)) {
234 DVLOG(1) << "Could not understand an mDNS packet.";
235 return; // Message is unreadable.
238 // TODO(noamsml): duplicate query suppression.
239 if (!(response->flags() & dns_protocol::kFlagResponse))
240 return; // Message is a query. ignore it.
242 DnsRecordParser parser = response->Parser();
243 unsigned answer_count = response->answer_count() +
244 response->additional_answer_count();
246 for (unsigned i = 0; i < answer_count; i++) {
247 offset = parser.GetOffset();
248 scoped_ptr<const RecordParsed> record =
249 RecordParsed::CreateFrom(&parser, clock_->Now());
251 if (!record) {
252 DVLOG(1) << "Could not understand an mDNS record.";
254 if (offset == parser.GetOffset()) {
255 DVLOG(1) << "Abandoned parsing the rest of the packet.";
256 return; // The parser did not advance, abort reading the packet.
257 } else {
258 continue; // We may be able to extract other records from the packet.
262 if ((record->klass() & dns_protocol::kMDnsClassMask) !=
263 dns_protocol::kClassIN) {
264 DVLOG(1) << "Received an mDNS record with non-IN class. Ignoring.";
265 continue; // Ignore all records not in the IN class.
268 MDnsCache::Key update_key = MDnsCache::Key::CreateFor(record.get());
269 MDnsCache::UpdateType update = cache_.UpdateDnsRecord(record.Pass());
271 // Cleanup time may have changed.
272 ScheduleCleanup(cache_.next_expiration());
274 update_keys.insert(std::make_pair(update_key, update));
277 for (std::map<MDnsCache::Key, MDnsCache::UpdateType>::iterator i =
278 update_keys.begin(); i != update_keys.end(); i++) {
279 const RecordParsed* record = cache_.LookupKey(i->first);
280 if (!record)
281 continue;
283 if (record->type() == dns_protocol::kTypeNSEC) {
284 #if defined(ENABLE_NSEC)
285 NotifyNsecRecord(record);
286 #endif
287 } else {
288 AlertListeners(i->second, ListenerKey(record->name(), record->type()),
289 record);
294 void MDnsClientImpl::Core::NotifyNsecRecord(const RecordParsed* record) {
295 DCHECK_EQ(dns_protocol::kTypeNSEC, record->type());
296 const NsecRecordRdata* rdata = record->rdata<NsecRecordRdata>();
297 DCHECK(rdata);
299 // Remove all cached records matching the nonexistent RR types.
300 std::vector<const RecordParsed*> records_to_remove;
302 cache_.FindDnsRecords(0, record->name(), &records_to_remove, clock_->Now());
304 for (std::vector<const RecordParsed*>::iterator i = records_to_remove.begin();
305 i != records_to_remove.end(); i++) {
306 if ((*i)->type() == dns_protocol::kTypeNSEC)
307 continue;
308 if (!rdata->GetBit((*i)->type())) {
309 scoped_ptr<const RecordParsed> record_removed = cache_.RemoveRecord((*i));
310 DCHECK(record_removed);
311 OnRecordRemoved(record_removed.get());
315 // Alert all listeners waiting for the nonexistent RR types.
316 ListenerMap::iterator i =
317 listeners_.upper_bound(ListenerKey(record->name(), 0));
318 for (; i != listeners_.end() && i->first.first == record->name(); i++) {
319 if (!rdata->GetBit(i->first.second)) {
320 FOR_EACH_OBSERVER(MDnsListenerImpl, *i->second, AlertNsecRecord());
325 void MDnsClientImpl::Core::OnConnectionError(int error) {
326 // TODO(noamsml): On connection error, recreate connection and flush cache.
329 void MDnsClientImpl::Core::AlertListeners(
330 MDnsCache::UpdateType update_type,
331 const ListenerKey& key,
332 const RecordParsed* record) {
333 ListenerMap::iterator listener_map_iterator = listeners_.find(key);
334 if (listener_map_iterator == listeners_.end()) return;
336 FOR_EACH_OBSERVER(MDnsListenerImpl, *listener_map_iterator->second,
337 HandleRecordUpdate(update_type, record));
340 void MDnsClientImpl::Core::AddListener(
341 MDnsListenerImpl* listener) {
342 ListenerKey key(listener->GetName(), listener->GetType());
343 std::pair<ListenerMap::iterator, bool> observer_insert_result =
344 listeners_.insert(
345 make_pair(key, static_cast<ObserverList<MDnsListenerImpl>*>(NULL)));
347 // If an equivalent key does not exist, actually create the observer list.
348 if (observer_insert_result.second)
349 observer_insert_result.first->second = new ObserverList<MDnsListenerImpl>();
351 ObserverList<MDnsListenerImpl>* observer_list =
352 observer_insert_result.first->second;
354 observer_list->AddObserver(listener);
357 void MDnsClientImpl::Core::RemoveListener(MDnsListenerImpl* listener) {
358 ListenerKey key(listener->GetName(), listener->GetType());
359 ListenerMap::iterator observer_list_iterator = listeners_.find(key);
361 DCHECK(observer_list_iterator != listeners_.end());
362 DCHECK(observer_list_iterator->second->HasObserver(listener));
364 observer_list_iterator->second->RemoveObserver(listener);
366 // Remove the observer list from the map if it is empty
367 if (!observer_list_iterator->second->might_have_observers()) {
368 // Schedule the actual removal for later in case the listener removal
369 // happens while iterating over the observer list.
370 base::MessageLoop::current()->PostTask(
371 FROM_HERE, base::Bind(
372 &MDnsClientImpl::Core::CleanupObserverList, AsWeakPtr(), key));
376 void MDnsClientImpl::Core::CleanupObserverList(const ListenerKey& key) {
377 ListenerMap::iterator found = listeners_.find(key);
378 if (found != listeners_.end() && !found->second->might_have_observers()) {
379 delete found->second;
380 listeners_.erase(found);
384 void MDnsClientImpl::Core::ScheduleCleanup(base::Time cleanup) {
385 // Cleanup is already scheduled, no need to do anything.
386 if (cleanup == scheduled_cleanup_) {
387 return;
389 scheduled_cleanup_ = cleanup;
391 // This cancels the previously scheduled cleanup.
392 cleanup_timer_->Stop();
394 // If |cleanup| is empty, then no cleanup necessary.
395 if (cleanup != base::Time()) {
396 cleanup_timer_->Start(
397 FROM_HERE, std::max(base::TimeDelta(), cleanup - clock_->Now()),
398 base::Bind(&MDnsClientImpl::Core::DoCleanup, base::Unretained(this)));
402 void MDnsClientImpl::Core::DoCleanup() {
403 cache_.CleanupRecords(clock_->Now(),
404 base::Bind(&MDnsClientImpl::Core::OnRecordRemoved,
405 base::Unretained(this)));
407 ScheduleCleanup(cache_.next_expiration());
410 void MDnsClientImpl::Core::OnRecordRemoved(
411 const RecordParsed* record) {
412 AlertListeners(MDnsCache::RecordRemoved,
413 ListenerKey(record->name(), record->type()), record);
416 void MDnsClientImpl::Core::QueryCache(
417 uint16 rrtype, const std::string& name,
418 std::vector<const RecordParsed*>* records) const {
419 cache_.FindDnsRecords(rrtype, name, records, clock_->Now());
422 MDnsClientImpl::MDnsClientImpl()
423 : clock_(new base::DefaultClock),
424 cleanup_timer_(new base::Timer(false, false)) {
427 MDnsClientImpl::MDnsClientImpl(scoped_ptr<base::Clock> clock,
428 scoped_ptr<base::Timer> timer)
429 : clock_(clock.Pass()), cleanup_timer_(timer.Pass()) {
432 MDnsClientImpl::~MDnsClientImpl() {
435 bool MDnsClientImpl::StartListening(MDnsSocketFactory* socket_factory) {
436 DCHECK(!core_.get());
437 core_.reset(new Core(clock_.get(), cleanup_timer_.get()));
438 if (!core_->Init(socket_factory)) {
439 core_.reset();
440 return false;
442 return true;
445 void MDnsClientImpl::StopListening() {
446 core_.reset();
449 bool MDnsClientImpl::IsListening() const {
450 return core_.get() != NULL;
453 scoped_ptr<MDnsListener> MDnsClientImpl::CreateListener(
454 uint16 rrtype,
455 const std::string& name,
456 MDnsListener::Delegate* delegate) {
457 return scoped_ptr<net::MDnsListener>(
458 new MDnsListenerImpl(rrtype, name, clock_.get(), delegate, this));
461 scoped_ptr<MDnsTransaction> MDnsClientImpl::CreateTransaction(
462 uint16 rrtype,
463 const std::string& name,
464 int flags,
465 const MDnsTransaction::ResultCallback& callback) {
466 return scoped_ptr<MDnsTransaction>(
467 new MDnsTransactionImpl(rrtype, name, flags, callback, this));
470 MDnsListenerImpl::MDnsListenerImpl(uint16 rrtype,
471 const std::string& name,
472 base::Clock* clock,
473 MDnsListener::Delegate* delegate,
474 MDnsClientImpl* client)
475 : rrtype_(rrtype),
476 name_(name),
477 clock_(clock),
478 client_(client),
479 delegate_(delegate),
480 started_(false),
481 active_refresh_(false) {
484 MDnsListenerImpl::~MDnsListenerImpl() {
485 if (started_) {
486 DCHECK(client_->core());
487 client_->core()->RemoveListener(this);
491 bool MDnsListenerImpl::Start() {
492 DCHECK(!started_);
494 started_ = true;
496 DCHECK(client_->core());
497 client_->core()->AddListener(this);
499 return true;
502 void MDnsListenerImpl::SetActiveRefresh(bool active_refresh) {
503 active_refresh_ = active_refresh;
505 if (started_) {
506 if (!active_refresh_) {
507 next_refresh_.Cancel();
508 } else if (last_update_ != base::Time()) {
509 ScheduleNextRefresh();
514 const std::string& MDnsListenerImpl::GetName() const {
515 return name_;
518 uint16 MDnsListenerImpl::GetType() const {
519 return rrtype_;
522 void MDnsListenerImpl::HandleRecordUpdate(MDnsCache::UpdateType update_type,
523 const RecordParsed* record) {
524 DCHECK(started_);
526 if (update_type != MDnsCache::RecordRemoved) {
527 ttl_ = record->ttl();
528 last_update_ = record->time_created();
530 ScheduleNextRefresh();
533 if (update_type != MDnsCache::NoChange) {
534 MDnsListener::UpdateType update_external;
536 switch (update_type) {
537 case MDnsCache::RecordAdded:
538 update_external = MDnsListener::RECORD_ADDED;
539 break;
540 case MDnsCache::RecordChanged:
541 update_external = MDnsListener::RECORD_CHANGED;
542 break;
543 case MDnsCache::RecordRemoved:
544 update_external = MDnsListener::RECORD_REMOVED;
545 break;
546 case MDnsCache::NoChange:
547 default:
548 NOTREACHED();
549 // Dummy assignment to suppress compiler warning.
550 update_external = MDnsListener::RECORD_CHANGED;
551 break;
554 delegate_->OnRecordUpdate(update_external, record);
558 void MDnsListenerImpl::AlertNsecRecord() {
559 DCHECK(started_);
560 delegate_->OnNsecRecord(name_, rrtype_);
563 void MDnsListenerImpl::ScheduleNextRefresh() {
564 DCHECK(last_update_ != base::Time());
566 if (!active_refresh_)
567 return;
569 // A zero TTL is a goodbye packet and should not be refreshed.
570 if (ttl_ == 0) {
571 next_refresh_.Cancel();
572 return;
575 next_refresh_.Reset(base::Bind(&MDnsListenerImpl::DoRefresh,
576 AsWeakPtr()));
578 // Schedule refreshes at both 85% and 95% of the original TTL. These will both
579 // be canceled and rescheduled if the record's TTL is updated due to a
580 // response being received.
581 base::Time next_refresh1 = last_update_ + base::TimeDelta::FromMilliseconds(
582 static_cast<int>(base::Time::kMillisecondsPerSecond *
583 kListenerRefreshRatio1 * ttl_));
585 base::Time next_refresh2 = last_update_ + base::TimeDelta::FromMilliseconds(
586 static_cast<int>(base::Time::kMillisecondsPerSecond *
587 kListenerRefreshRatio2 * ttl_));
589 base::MessageLoop::current()->PostDelayedTask(
590 FROM_HERE, next_refresh_.callback(), next_refresh1 - clock_->Now());
592 base::MessageLoop::current()->PostDelayedTask(
593 FROM_HERE, next_refresh_.callback(), next_refresh2 - clock_->Now());
596 void MDnsListenerImpl::DoRefresh() {
597 client_->core()->SendQuery(rrtype_, name_);
600 MDnsTransactionImpl::MDnsTransactionImpl(
601 uint16 rrtype,
602 const std::string& name,
603 int flags,
604 const MDnsTransaction::ResultCallback& callback,
605 MDnsClientImpl* client)
606 : rrtype_(rrtype), name_(name), callback_(callback), client_(client),
607 started_(false), flags_(flags) {
608 DCHECK((flags_ & MDnsTransaction::FLAG_MASK) == flags_);
609 DCHECK(flags_ & MDnsTransaction::QUERY_CACHE ||
610 flags_ & MDnsTransaction::QUERY_NETWORK);
613 MDnsTransactionImpl::~MDnsTransactionImpl() {
614 timeout_.Cancel();
617 bool MDnsTransactionImpl::Start() {
618 DCHECK(!started_);
619 started_ = true;
621 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
622 if (flags_ & MDnsTransaction::QUERY_CACHE) {
623 ServeRecordsFromCache();
625 if (!weak_this || !is_active()) return true;
628 if (flags_ & MDnsTransaction::QUERY_NETWORK) {
629 return QueryAndListen();
632 // If this is a cache only query, signal that the transaction is over
633 // immediately.
634 SignalTransactionOver();
635 return true;
638 const std::string& MDnsTransactionImpl::GetName() const {
639 return name_;
642 uint16 MDnsTransactionImpl::GetType() const {
643 return rrtype_;
646 void MDnsTransactionImpl::CacheRecordFound(const RecordParsed* record) {
647 DCHECK(started_);
648 OnRecordUpdate(MDnsListener::RECORD_ADDED, record);
651 void MDnsTransactionImpl::TriggerCallback(MDnsTransaction::Result result,
652 const RecordParsed* record) {
653 DCHECK(started_);
654 if (!is_active()) return;
656 // Ensure callback is run after touching all class state, so that
657 // the callback can delete the transaction.
658 MDnsTransaction::ResultCallback callback = callback_;
660 // Reset the transaction if it expects a single result, or if the result
661 // is a final one (everything except for a record).
662 if (flags_ & MDnsTransaction::SINGLE_RESULT ||
663 result != MDnsTransaction::RESULT_RECORD) {
664 Reset();
667 callback.Run(result, record);
670 void MDnsTransactionImpl::Reset() {
671 callback_.Reset();
672 listener_.reset();
673 timeout_.Cancel();
676 void MDnsTransactionImpl::OnRecordUpdate(MDnsListener::UpdateType update,
677 const RecordParsed* record) {
678 DCHECK(started_);
679 if (update == MDnsListener::RECORD_ADDED ||
680 update == MDnsListener::RECORD_CHANGED)
681 TriggerCallback(MDnsTransaction::RESULT_RECORD, record);
684 void MDnsTransactionImpl::SignalTransactionOver() {
685 DCHECK(started_);
686 if (flags_ & MDnsTransaction::SINGLE_RESULT) {
687 TriggerCallback(MDnsTransaction::RESULT_NO_RESULTS, NULL);
688 } else {
689 TriggerCallback(MDnsTransaction::RESULT_DONE, NULL);
693 void MDnsTransactionImpl::ServeRecordsFromCache() {
694 std::vector<const RecordParsed*> records;
695 base::WeakPtr<MDnsTransactionImpl> weak_this = AsWeakPtr();
697 if (client_->core()) {
698 client_->core()->QueryCache(rrtype_, name_, &records);
699 for (std::vector<const RecordParsed*>::iterator i = records.begin();
700 i != records.end() && weak_this; ++i) {
701 weak_this->TriggerCallback(MDnsTransaction::RESULT_RECORD, *i);
704 #if defined(ENABLE_NSEC)
705 if (records.empty()) {
706 DCHECK(weak_this);
707 client_->core()->QueryCache(dns_protocol::kTypeNSEC, name_, &records);
708 if (!records.empty()) {
709 const NsecRecordRdata* rdata =
710 records.front()->rdata<NsecRecordRdata>();
711 DCHECK(rdata);
712 if (!rdata->GetBit(rrtype_))
713 weak_this->TriggerCallback(MDnsTransaction::RESULT_NSEC, NULL);
716 #endif
720 bool MDnsTransactionImpl::QueryAndListen() {
721 listener_ = client_->CreateListener(rrtype_, name_, this);
722 if (!listener_->Start())
723 return false;
725 DCHECK(client_->core());
726 if (!client_->core()->SendQuery(rrtype_, name_))
727 return false;
729 timeout_.Reset(base::Bind(&MDnsTransactionImpl::SignalTransactionOver,
730 AsWeakPtr()));
731 base::MessageLoop::current()->PostDelayedTask(
732 FROM_HERE,
733 timeout_.callback(),
734 base::TimeDelta::FromSeconds(MDnsTransactionTimeoutSeconds));
736 return true;
739 void MDnsTransactionImpl::OnNsecRecord(const std::string& name, unsigned type) {
740 TriggerCallback(RESULT_NSEC, NULL);
743 void MDnsTransactionImpl::OnCachePurged() {
744 // TODO(noamsml): Cache purge situations not yet implemented
747 } // namespace net