forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhost_resolver_impl.cc
2361 lines (2007 loc) · 79.5 KB
/
host_resolver_impl.cc
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/host_resolver_impl.h"
#if defined(OS_WIN)
#include <Winsock2.h>
#elif defined(OS_POSIX)
#include <netdb.h>
#endif
#include <cmath>
#include <utility>
#include <vector>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/address_family.h"
#include "net/base/address_list.h"
#include "net/base/dns_reloader.h"
#include "net/base/dns_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_util.h"
#include "net/dns/address_sorter.h"
#include "net/dns/dns_client.h"
#include "net/dns/dns_config_service.h"
#include "net/dns/dns_protocol.h"
#include "net/dns/dns_response.h"
#include "net/dns/dns_transaction.h"
#include "net/dns/host_resolver_proc.h"
#include "net/socket/client_socket_factory.h"
#include "net/udp/datagram_client_socket.h"
#if defined(OS_WIN)
#include "net/base/winsock_init.h"
#endif
namespace net {
namespace {
// Limit the size of hostnames that will be resolved to combat issues in
// some platform's resolvers.
const size_t kMaxHostLength = 4096;
// Default TTL for successful resolutions with ProcTask.
const unsigned kCacheEntryTTLSeconds = 60;
// Default TTL for unsuccessful resolutions with ProcTask.
const unsigned kNegativeCacheEntryTTLSeconds = 0;
// Minimum TTL for successful resolutions with DnsTask.
const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
// We use a separate histogram name for each platform to facilitate the
// display of error codes by their symbolic name (since each platform has
// different mappings).
const char kOSErrorsForGetAddrinfoHistogramName[] =
#if defined(OS_WIN)
"Net.OSErrorsForGetAddrinfo_Win";
#elif defined(OS_MACOSX)
"Net.OSErrorsForGetAddrinfo_Mac";
#elif defined(OS_LINUX)
"Net.OSErrorsForGetAddrinfo_Linux";
#else
"Net.OSErrorsForGetAddrinfo";
#endif
// Gets a list of the likely error codes that getaddrinfo() can return
// (non-exhaustive). These are the error codes that we will track via
// a histogram.
std::vector<int> GetAllGetAddrinfoOSErrors() {
int os_errors[] = {
#if defined(OS_POSIX)
#if !defined(OS_FREEBSD)
#if !defined(OS_ANDROID)
// EAI_ADDRFAMILY has been declared obsolete in Android's and
// FreeBSD's netdb.h.
EAI_ADDRFAMILY,
#endif
// EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
EAI_NODATA,
#endif
EAI_AGAIN,
EAI_BADFLAGS,
EAI_FAIL,
EAI_FAMILY,
EAI_MEMORY,
EAI_NONAME,
EAI_SERVICE,
EAI_SOCKTYPE,
EAI_SYSTEM,
#elif defined(OS_WIN)
// See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
WSA_NOT_ENOUGH_MEMORY,
WSAEAFNOSUPPORT,
WSAEINVAL,
WSAESOCKTNOSUPPORT,
WSAHOST_NOT_FOUND,
WSANO_DATA,
WSANO_RECOVERY,
WSANOTINITIALISED,
WSATRY_AGAIN,
WSATYPE_NOT_FOUND,
// The following are not in doc, but might be to appearing in results :-(.
WSA_INVALID_HANDLE,
#endif
};
// Ensure all errors are positive, as histogram only tracks positive values.
for (size_t i = 0; i < arraysize(os_errors); ++i) {
os_errors[i] = std::abs(os_errors[i]);
}
return base::CustomHistogram::ArrayToCustomRanges(os_errors,
arraysize(os_errors));
}
enum DnsResolveStatus {
RESOLVE_STATUS_DNS_SUCCESS = 0,
RESOLVE_STATUS_PROC_SUCCESS,
RESOLVE_STATUS_FAIL,
RESOLVE_STATUS_SUSPECT_NETBIOS,
RESOLVE_STATUS_MAX
};
void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
result,
RESOLVE_STATUS_MAX);
}
bool ResemblesNetBIOSName(const std::string& hostname) {
return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
}
// True if |hostname| ends with either ".local" or ".local.".
bool ResemblesMulticastDNSName(const std::string& hostname) {
DCHECK(!hostname.empty());
const char kSuffix[] = ".local.";
const size_t kSuffixLen = sizeof(kSuffix) - 1;
const size_t kSuffixLenTrimmed = kSuffixLen - 1;
if (hostname[hostname.size() - 1] == '.') {
return hostname.size() > kSuffixLen &&
!hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
}
return hostname.size() > kSuffixLenTrimmed &&
!hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
kSuffix, kSuffixLenTrimmed);
}
// Attempts to connect a UDP socket to |dest|:53.
bool IsGloballyReachable(const IPAddressNumber& dest,
const BoundNetLog& net_log) {
scoped_ptr<DatagramClientSocket> socket(
ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
DatagramSocket::DEFAULT_BIND,
RandIntCallback(),
net_log.net_log(),
net_log.source()));
int rv = socket->Connect(IPEndPoint(dest, 53));
if (rv != OK)
return false;
IPEndPoint endpoint;
rv = socket->GetLocalAddress(&endpoint);
if (rv != OK)
return false;
DCHECK(endpoint.GetFamily() == ADDRESS_FAMILY_IPV6);
const IPAddressNumber& address = endpoint.address();
bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
if (is_link_local)
return false;
const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
bool is_teredo = std::equal(kTeredoPrefix,
kTeredoPrefix + arraysize(kTeredoPrefix),
address.begin());
if (is_teredo)
return false;
return true;
}
// Provide a common macro to simplify code and readability. We must use a
// macro as the underlying HISTOGRAM macro creates static variables.
#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
// A macro to simplify code and readability.
#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
do { \
switch (priority) { \
case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
default: NOTREACHED(); break; \
} \
DNS_HISTOGRAM(basename, time); \
} while (0)
// Record time from Request creation until a valid DNS response.
void RecordTotalTime(bool had_dns_config,
bool speculative,
base::TimeDelta duration) {
if (had_dns_config) {
if (speculative) {
DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
} else {
DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
}
} else {
if (speculative) {
DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
} else {
DNS_HISTOGRAM("DNS.TotalTime", duration);
}
}
}
void RecordTTL(base::TimeDelta ttl) {
UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
base::TimeDelta::FromSeconds(1),
base::TimeDelta::FromDays(1), 100);
}
bool ConfigureAsyncDnsNoFallbackFieldTrial() {
const bool kDefault = false;
// Configure the AsyncDns field trial as follows:
// groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
// groups AsyncDnsA and AsyncDnsB: return false,
// groups SystemDnsA and SystemDnsB: return false,
// otherwise (trial absent): return default.
std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
if (!group_name.empty())
return StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
return kDefault;
}
//-----------------------------------------------------------------------------
AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
if (list.empty() || list.front().port() == port)
return list;
return AddressList::CopyWithPort(list, port);
}
// Returns true if |addresses| contains only IPv4 loopback addresses.
bool IsAllIPv4Loopback(const AddressList& addresses) {
for (unsigned i = 0; i < addresses.size(); ++i) {
const IPAddressNumber& address = addresses[i].address();
switch (addresses[i].GetFamily()) {
case ADDRESS_FAMILY_IPV4:
if (address[0] != 127)
return false;
break;
case ADDRESS_FAMILY_IPV6:
return false;
default:
NOTREACHED();
return false;
}
}
return true;
}
// Creates NetLog parameters when the resolve failed.
base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
int net_error,
int os_error,
NetLog::LogLevel /* log_level */) {
base::DictionaryValue* dict = new base::DictionaryValue();
if (attempt_number)
dict->SetInteger("attempt_number", attempt_number);
dict->SetInteger("net_error", net_error);
if (os_error) {
dict->SetInteger("os_error", os_error);
#if defined(OS_POSIX)
dict->SetString("os_error_string", gai_strerror(os_error));
#elif defined(OS_WIN)
// Map the error code to a human-readable string.
LPWSTR error_string = NULL;
int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
0, // Use the internal message table.
os_error,
0, // Use default language.
(LPWSTR)&error_string,
0, // Buffer size.
0); // Arguments (unused).
dict->SetString("os_error_string", base::WideToUTF8(error_string));
LocalFree(error_string);
#endif
}
return dict;
}
// Creates NetLog parameters when the DnsTask failed.
base::Value* NetLogDnsTaskFailedCallback(int net_error,
int dns_error,
NetLog::LogLevel /* log_level */) {
base::DictionaryValue* dict = new base::DictionaryValue();
dict->SetInteger("net_error", net_error);
if (dns_error)
dict->SetInteger("dns_error", dns_error);
return dict;
};
// Creates NetLog parameters containing the information in a RequestInfo object,
// along with the associated NetLog::Source.
base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
const HostResolver::RequestInfo* info,
NetLog::LogLevel /* log_level */) {
base::DictionaryValue* dict = new base::DictionaryValue();
source.AddToEventParameters(dict);
dict->SetString("host", info->host_port_pair().ToString());
dict->SetInteger("address_family",
static_cast<int>(info->address_family()));
dict->SetBoolean("allow_cached_response", info->allow_cached_response());
dict->SetBoolean("is_speculative", info->is_speculative());
return dict;
}
// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
const std::string* host,
NetLog::LogLevel /* log_level */) {
base::DictionaryValue* dict = new base::DictionaryValue();
source.AddToEventParameters(dict);
dict->SetString("host", *host);
return dict;
}
// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
RequestPriority priority,
NetLog::LogLevel /* log_level */) {
base::DictionaryValue* dict = new base::DictionaryValue();
source.AddToEventParameters(dict);
dict->SetString("priority", RequestPriorityToString(priority));
return dict;
}
// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
NetLog::LogLevel /* log_level */) {
return config->ToValue();
}
// The logging routines are defined here because some requests are resolved
// without a Request object.
// Logs when a request has just been started.
void LogStartRequest(const BoundNetLog& source_net_log,
const BoundNetLog& request_net_log,
const HostResolver::RequestInfo& info) {
source_net_log.BeginEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL,
request_net_log.source().ToEventParametersCallback());
request_net_log.BeginEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
}
// Logs when a request has just completed (before its callback is run).
void LogFinishRequest(const BoundNetLog& source_net_log,
const BoundNetLog& request_net_log,
const HostResolver::RequestInfo& info,
int net_error) {
request_net_log.EndEventWithNetErrorCode(
NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
}
// Logs when a request has been cancelled.
void LogCancelRequest(const BoundNetLog& source_net_log,
const BoundNetLog& request_net_log,
const HostResolverImpl::RequestInfo& info) {
request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
}
//-----------------------------------------------------------------------------
// Keeps track of the highest priority.
class PriorityTracker {
public:
explicit PriorityTracker(RequestPriority initial_priority)
: highest_priority_(initial_priority), total_count_(0) {
memset(counts_, 0, sizeof(counts_));
}
RequestPriority highest_priority() const {
return highest_priority_;
}
size_t total_count() const {
return total_count_;
}
void Add(RequestPriority req_priority) {
++total_count_;
++counts_[req_priority];
if (highest_priority_ < req_priority)
highest_priority_ = req_priority;
}
void Remove(RequestPriority req_priority) {
DCHECK_GT(total_count_, 0u);
DCHECK_GT(counts_[req_priority], 0u);
--total_count_;
--counts_[req_priority];
size_t i;
for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
highest_priority_ = static_cast<RequestPriority>(i);
// In absence of requests, default to MINIMUM_PRIORITY.
if (total_count_ == 0)
DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
}
private:
RequestPriority highest_priority_;
size_t total_count_;
size_t counts_[NUM_PRIORITIES];
};
} // namespace
//-----------------------------------------------------------------------------
const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
// Holds the data for a request that could not be completed synchronously.
// It is owned by a Job. Canceled Requests are only marked as canceled rather
// than removed from the Job's |requests_| list.
class HostResolverImpl::Request {
public:
Request(const BoundNetLog& source_net_log,
const BoundNetLog& request_net_log,
const RequestInfo& info,
RequestPriority priority,
const CompletionCallback& callback,
AddressList* addresses)
: source_net_log_(source_net_log),
request_net_log_(request_net_log),
info_(info),
priority_(priority),
job_(NULL),
callback_(callback),
addresses_(addresses),
request_time_(base::TimeTicks::Now()) {}
// Mark the request as canceled.
void MarkAsCanceled() {
job_ = NULL;
addresses_ = NULL;
callback_.Reset();
}
bool was_canceled() const {
return callback_.is_null();
}
void set_job(Job* job) {
DCHECK(job);
// Identify which job the request is waiting on.
job_ = job;
}
// Prepare final AddressList and call completion callback.
void OnComplete(int error, const AddressList& addr_list) {
DCHECK(!was_canceled());
if (error == OK)
*addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
CompletionCallback callback = callback_;
MarkAsCanceled();
callback.Run(error);
}
Job* job() const {
return job_;
}
// NetLog for the source, passed in HostResolver::Resolve.
const BoundNetLog& source_net_log() {
return source_net_log_;
}
// NetLog for this request.
const BoundNetLog& request_net_log() {
return request_net_log_;
}
const RequestInfo& info() const {
return info_;
}
RequestPriority priority() const { return priority_; }
base::TimeTicks request_time() const { return request_time_; }
private:
BoundNetLog source_net_log_;
BoundNetLog request_net_log_;
// The request info that started the request.
const RequestInfo info_;
// TODO(akalin): Support reprioritization.
const RequestPriority priority_;
// The resolve job that this request is dependent on.
Job* job_;
// The user's callback to invoke when the request completes.
CompletionCallback callback_;
// The address list to save result into.
AddressList* addresses_;
const base::TimeTicks request_time_;
DISALLOW_COPY_AND_ASSIGN(Request);
};
//------------------------------------------------------------------------------
// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
//
// Whenever we try to resolve the host, we post a delayed task to check if host
// resolution (OnLookupComplete) is completed or not. If the original attempt
// hasn't completed, then we start another attempt for host resolution. We take
// the results from the first attempt that finishes and ignore the results from
// all other attempts.
//
// TODO(szym): Move to separate source file for testing and mocking.
//
class HostResolverImpl::ProcTask
: public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
public:
typedef base::Callback<void(int net_error,
const AddressList& addr_list)> Callback;
ProcTask(const Key& key,
const ProcTaskParams& params,
const Callback& callback,
const BoundNetLog& job_net_log)
: key_(key),
params_(params),
callback_(callback),
origin_loop_(base::MessageLoopProxy::current()),
attempt_number_(0),
completed_attempt_number_(0),
completed_attempt_error_(ERR_UNEXPECTED),
had_non_speculative_request_(false),
net_log_(job_net_log) {
if (!params_.resolver_proc.get())
params_.resolver_proc = HostResolverProc::GetDefault();
// If default is unset, use the system proc.
if (!params_.resolver_proc.get())
params_.resolver_proc = new SystemHostResolverProc();
}
void Start() {
DCHECK(origin_loop_->BelongsToCurrentThread());
net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
StartLookupAttempt();
}
// Cancels this ProcTask. It will be orphaned. Any outstanding resolve
// attempts running on worker threads will continue running. Only once all the
// attempts complete will the final reference to this ProcTask be released.
void Cancel() {
DCHECK(origin_loop_->BelongsToCurrentThread());
if (was_canceled() || was_completed())
return;
callback_.Reset();
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
}
void set_had_non_speculative_request() {
DCHECK(origin_loop_->BelongsToCurrentThread());
had_non_speculative_request_ = true;
}
bool was_canceled() const {
DCHECK(origin_loop_->BelongsToCurrentThread());
return callback_.is_null();
}
bool was_completed() const {
DCHECK(origin_loop_->BelongsToCurrentThread());
return completed_attempt_number_ > 0;
}
private:
friend class base::RefCountedThreadSafe<ProcTask>;
~ProcTask() {}
void StartLookupAttempt() {
DCHECK(origin_loop_->BelongsToCurrentThread());
base::TimeTicks start_time = base::TimeTicks::Now();
++attempt_number_;
// Dispatch the lookup attempt to a worker thread.
if (!base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
true)) {
NOTREACHED();
// Since we could be running within Resolve() right now, we can't just
// call OnLookupComplete(). Instead we must wait until Resolve() has
// returned (IO_PENDING).
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
start_time, attempt_number_, ERR_UNEXPECTED, 0));
return;
}
net_log_.AddEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
NetLog::IntegerCallback("attempt_number", attempt_number_));
// If we don't get the results within a given time, RetryIfNotComplete
// will start a new attempt on a different worker thread if none of our
// outstanding attempts have completed yet.
if (attempt_number_ <= params_.max_retry_attempts) {
origin_loop_->PostDelayedTask(
FROM_HERE,
base::Bind(&ProcTask::RetryIfNotComplete, this),
params_.unresponsive_delay);
}
}
// WARNING: This code runs inside a worker pool. The shutdown code cannot
// wait for it to finish, so we must be very careful here about using other
// objects (like MessageLoops, Singletons, etc). During shutdown these objects
// may no longer exist. Multiple DoLookups() could be running in parallel, so
// any state inside of |this| must not mutate .
void DoLookup(const base::TimeTicks& start_time,
const uint32 attempt_number) {
AddressList results;
int os_error = 0;
// Running on the worker thread
int error = params_.resolver_proc->Resolve(key_.hostname,
key_.address_family,
key_.host_resolver_flags,
&results,
&os_error);
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
attempt_number, error, os_error));
}
// Makes next attempt if DoLookup() has not finished (runs on origin thread).
void RetryIfNotComplete() {
DCHECK(origin_loop_->BelongsToCurrentThread());
if (was_completed() || was_canceled())
return;
params_.unresponsive_delay *= params_.retry_factor;
StartLookupAttempt();
}
// Callback for when DoLookup() completes (runs on origin thread).
void OnLookupComplete(const AddressList& results,
const base::TimeTicks& start_time,
const uint32 attempt_number,
int error,
const int os_error) {
DCHECK(origin_loop_->BelongsToCurrentThread());
// If results are empty, we should return an error.
bool empty_list_on_ok = (error == OK && results.empty());
UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
if (empty_list_on_ok)
error = ERR_NAME_NOT_RESOLVED;
bool was_retry_attempt = attempt_number > 1;
// Ideally the following code would be part of host_resolver_proc.cc,
// however it isn't safe to call NetworkChangeNotifier from worker threads.
// So we do it here on the IO thread instead.
if (error != OK && NetworkChangeNotifier::IsOffline())
error = ERR_INTERNET_DISCONNECTED;
// If this is the first attempt that is finishing later, then record data
// for the first attempt. Won't contaminate with retry attempt's data.
if (!was_retry_attempt)
RecordPerformanceHistograms(start_time, error, os_error);
RecordAttemptHistograms(start_time, attempt_number, error, os_error);
if (was_canceled())
return;
NetLog::ParametersCallback net_log_callback;
if (error != OK) {
net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
attempt_number,
error,
os_error);
} else {
net_log_callback = NetLog::IntegerCallback("attempt_number",
attempt_number);
}
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
net_log_callback);
if (was_completed())
return;
// Copy the results from the first worker thread that resolves the host.
results_ = results;
completed_attempt_number_ = attempt_number;
completed_attempt_error_ = error;
if (was_retry_attempt) {
// If retry attempt finishes before 1st attempt, then get stats on how
// much time is saved by having spawned an extra attempt.
retry_attempt_finished_time_ = base::TimeTicks::Now();
}
if (error != OK) {
net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
0, error, os_error);
} else {
net_log_callback = results_.CreateNetLogCallback();
}
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
net_log_callback);
callback_.Run(error, results_);
}
void RecordPerformanceHistograms(const base::TimeTicks& start_time,
const int error,
const int os_error) const {
DCHECK(origin_loop_->BelongsToCurrentThread());
enum Category { // Used in HISTOGRAM_ENUMERATION.
RESOLVE_SUCCESS,
RESOLVE_FAIL,
RESOLVE_SPECULATIVE_SUCCESS,
RESOLVE_SPECULATIVE_FAIL,
RESOLVE_MAX, // Bounding value.
};
int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (error == OK) {
if (had_non_speculative_request_) {
category = RESOLVE_SUCCESS;
DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
} else {
category = RESOLVE_SPECULATIVE_SUCCESS;
DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
}
// Log DNS lookups based on |address_family|. This will help us determine
// if IPv4 or IPv4/6 lookups are faster or slower.
switch(key_.address_family) {
case ADDRESS_FAMILY_IPV4:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
break;
case ADDRESS_FAMILY_IPV6:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
break;
case ADDRESS_FAMILY_UNSPECIFIED:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
break;
}
} else {
if (had_non_speculative_request_) {
category = RESOLVE_FAIL;
DNS_HISTOGRAM("DNS.ResolveFail", duration);
} else {
category = RESOLVE_SPECULATIVE_FAIL;
DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
}
// Log DNS lookups based on |address_family|. This will help us determine
// if IPv4 or IPv4/6 lookups are faster or slower.
switch(key_.address_family) {
case ADDRESS_FAMILY_IPV4:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
break;
case ADDRESS_FAMILY_IPV6:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
break;
case ADDRESS_FAMILY_UNSPECIFIED:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
break;
}
UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
std::abs(os_error),
GetAllGetAddrinfoOSErrors());
}
DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
}
void RecordAttemptHistograms(const base::TimeTicks& start_time,
const uint32 attempt_number,
const int error,
const int os_error) const {
DCHECK(origin_loop_->BelongsToCurrentThread());
bool first_attempt_to_complete =
completed_attempt_number_ == attempt_number;
bool is_first_attempt = (attempt_number == 1);
if (first_attempt_to_complete) {
// If this was first attempt to complete, then record the resolution
// status of the attempt.
if (completed_attempt_error_ == OK) {
UMA_HISTOGRAM_ENUMERATION(
"DNS.AttemptFirstSuccess", attempt_number, 100);
} else {
UMA_HISTOGRAM_ENUMERATION(
"DNS.AttemptFirstFailure", attempt_number, 100);
}
}
if (error == OK)
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
else
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
// If first attempt didn't finish before retry attempt, then calculate stats
// on how much time is saved by having spawned an extra attempt.
if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
base::TimeTicks::Now() - retry_attempt_finished_time_);
}
if (was_canceled() || !first_attempt_to_complete) {
// Count those attempts which completed after the job was already canceled
// OR after the job was already completed by an earlier attempt (so in
// effect).
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
// Record if job is canceled.
if (was_canceled())
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
}
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (error == OK)
DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
else
DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
}
// Set on the origin thread, read on the worker thread.
Key key_;
// Holds an owning reference to the HostResolverProc that we are going to use.
// This may not be the current resolver procedure by the time we call
// ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
// reference ensures that it remains valid until we are done.
ProcTaskParams params_;
// The listener to the results of this ProcTask.
Callback callback_;
// Used to post ourselves onto the origin thread.
scoped_refptr<base::MessageLoopProxy> origin_loop_;
// Keeps track of the number of attempts we have made so far to resolve the
// host. Whenever we start an attempt to resolve the host, we increase this
// number.
uint32 attempt_number_;
// The index of the attempt which finished first (or 0 if the job is still in
// progress).
uint32 completed_attempt_number_;
// The result (a net error code) from the first attempt to complete.
int completed_attempt_error_;
// The time when retry attempt was finished.
base::TimeTicks retry_attempt_finished_time_;
// True if a non-speculative request was ever attached to this job
// (regardless of whether or not it was later canceled.
// This boolean is used for histogramming the duration of jobs used to
// service non-speculative requests.
bool had_non_speculative_request_;
AddressList results_;
BoundNetLog net_log_;
DISALLOW_COPY_AND_ASSIGN(ProcTask);
};
//-----------------------------------------------------------------------------
// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
// it takes 40-100ms and should not block initialization.
class HostResolverImpl::LoopbackProbeJob {
public:
explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
: resolver_(resolver),
result_(false) {
DCHECK(resolver.get());
const bool kIsSlow = true;
base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
kIsSlow);
}
virtual ~LoopbackProbeJob() {}
private:
// Runs on worker thread.
void DoProbe() {
result_ = HaveOnlyLoopbackAddresses();
}
void OnProbeComplete() {
if (!resolver_.get())
return;
resolver_->SetHaveOnlyLoopbackAddresses(result_);
}
// Used/set only on origin thread.
base::WeakPtr<HostResolverImpl> resolver_;
bool result_;
DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
};
//-----------------------------------------------------------------------------
// Resolves the hostname using DnsTransaction.
// TODO(szym): This could be moved to separate source file as well.
class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
public:
class Delegate {
public:
virtual void OnDnsTaskComplete(base::TimeTicks start_time,
int net_error,
const AddressList& addr_list,
base::TimeDelta ttl) = 0;
// Called when the first of two jobs succeeds. If the first completed
// transaction fails, this is not called. Also not called when the DnsTask
// only needs to run one transaction.
virtual void OnFirstDnsTransactionComplete() = 0;
protected:
Delegate() {}
virtual ~Delegate() {}
};
DnsTask(DnsClient* client,
const Key& key,
Delegate* delegate,
const BoundNetLog& job_net_log)
: client_(client),
key_(key),
delegate_(delegate),
net_log_(job_net_log),
num_completed_transactions_(0),
task_start_time_(base::TimeTicks::Now()) {
DCHECK(client);
DCHECK(delegate_);
}