forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhost_resolver_manager_unittest.cc
11258 lines (9476 loc) · 485 KB
/
host_resolver_manager_unittest.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_manager.h"
#include <algorithm>
#include <limits>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/numerics/safe_conversions.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/timer/mock_timer.h"
#include "base/values.h"
#include "build/build_config.h"
#include "net/base/address_family.h"
#include "net/base/address_list.h"
#include "net/base/features.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/mock_network_change_notifier.h"
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"
#include "net/base/schemeful_site.h"
#include "net/dns/dns_client.h"
#include "net/dns/dns_config.h"
#include "net/dns/dns_test_util.h"
#include "net/dns/dns_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/mock_mdns_client.h"
#include "net/dns/mock_mdns_socket_factory.h"
#include "net/dns/public/dns_config_overrides.h"
#include "net/dns/public/dns_over_https_server_config.h"
#include "net/dns/public/dns_query_type.h"
#include "net/dns/public/resolve_error_info.h"
#include "net/dns/public/secure_dns_mode.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/dns/resolve_context.h"
#include "net/dns/test_dns_config_service.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/log/net_log_with_source.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_util.h"
#include "net/socket/socket_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#if BUILDFLAG(ENABLE_MDNS)
#include "net/dns/mdns_client_impl.h"
#endif // BUILDFLAG(ENABLE_MDNS)
using net::test::IsError;
using net::test::IsOk;
using ::testing::_;
using ::testing::AllOf;
using ::testing::Between;
using ::testing::ByMove;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Optional;
using ::testing::Pair;
using ::testing::Property;
using ::testing::Return;
using ::testing::UnorderedElementsAre;
namespace net {
namespace {
const size_t kMaxJobs = 10u;
const size_t kMaxRetryAttempts = 4u;
ProcTaskParams DefaultParams(HostResolverProc* resolver_proc) {
return ProcTaskParams(resolver_proc, kMaxRetryAttempts);
}
// A HostResolverProc that pushes each host mapped into a list and allows
// waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
// it never calls SystemHostResolverCall. By default resolves all hostnames to
// "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
class MockHostResolverProc : public HostResolverProc {
public:
struct ResolveKey {
ResolveKey(const std::string& hostname,
AddressFamily address_family,
HostResolverFlags flags)
: hostname(hostname), address_family(address_family), flags(flags) {}
bool operator<(const ResolveKey& other) const {
return std::tie(address_family, hostname, flags) <
std::tie(other.address_family, other.hostname, other.flags);
}
std::string hostname;
AddressFamily address_family;
HostResolverFlags flags;
};
typedef std::vector<ResolveKey> CaptureList;
MockHostResolverProc()
: HostResolverProc(nullptr),
num_requests_waiting_(0),
num_slots_available_(0),
requests_waiting_(&lock_),
slots_available_(&lock_) {}
// Waits until |count| calls to |Resolve| are blocked. Returns false when
// timed out.
bool WaitFor(unsigned count) {
base::AutoLock lock(lock_);
base::Time start_time = base::Time::Now();
while (num_requests_waiting_ < count) {
requests_waiting_.TimedWait(TestTimeouts::action_timeout());
if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
return false;
}
return true;
}
// Signals |count| waiting calls to |Resolve|. First come first served.
void SignalMultiple(unsigned count) {
base::AutoLock lock(lock_);
num_slots_available_ += count;
slots_available_.Broadcast();
}
// Signals all waiting calls to |Resolve|. Beware of races.
void SignalAll() {
base::AutoLock lock(lock_);
num_slots_available_ = num_requests_waiting_;
slots_available_.Broadcast();
}
void AddRule(const std::string& hostname,
AddressFamily family,
const AddressList& result,
HostResolverFlags flags = 0) {
base::AutoLock lock(lock_);
rules_[ResolveKey(hostname, family, flags)] = result;
}
void AddRule(const std::string& hostname,
AddressFamily family,
const std::string& ip_list,
HostResolverFlags flags = 0,
const std::string& canonical_name = "") {
AddressList result;
std::vector<std::string> dns_aliases;
if (canonical_name != "")
dns_aliases = {canonical_name};
int rv = ParseAddressList(ip_list, dns_aliases, &result);
DCHECK_EQ(OK, rv);
AddRule(hostname, family, result, flags);
}
void AddRuleForAllFamilies(const std::string& hostname,
const std::string& ip_list,
HostResolverFlags flags = 0,
const std::string& canonical_name = "") {
AddressList result;
std::vector<std::string> dns_aliases;
if (canonical_name != "")
dns_aliases = {canonical_name};
int rv = ParseAddressList(ip_list, dns_aliases, &result);
DCHECK_EQ(OK, rv);
AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result, flags);
AddRule(hostname, ADDRESS_FAMILY_IPV4, result, flags);
AddRule(hostname, ADDRESS_FAMILY_IPV6, result, flags);
}
int Resolve(const std::string& hostname,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) override {
base::AutoLock lock(lock_);
capture_list_.push_back(
ResolveKey(hostname, address_family, host_resolver_flags));
++num_requests_waiting_;
requests_waiting_.Broadcast();
{
base::ScopedAllowBaseSyncPrimitivesForTesting
scoped_allow_base_sync_primitives;
while (!num_slots_available_)
slots_available_.Wait();
}
DCHECK_GT(num_requests_waiting_, 0u);
--num_slots_available_;
--num_requests_waiting_;
if (rules_.empty()) {
int rv = ParseAddressList("127.0.0.1", {} /* dns_aliases */, addrlist);
DCHECK_EQ(OK, rv);
return OK;
}
ResolveKey key(hostname, address_family, host_resolver_flags);
if (rules_.count(key) == 0)
return ERR_NAME_NOT_RESOLVED;
*addrlist = rules_[key];
return OK;
}
CaptureList GetCaptureList() const {
CaptureList copy;
{
base::AutoLock lock(lock_);
copy = capture_list_;
}
return copy;
}
void ClearCaptureList() {
base::AutoLock lock(lock_);
capture_list_.clear();
}
bool HasBlockedRequests() const {
base::AutoLock lock(lock_);
return num_requests_waiting_ > num_slots_available_;
}
protected:
~MockHostResolverProc() override = default;
private:
mutable base::Lock lock_;
std::map<ResolveKey, AddressList> rules_;
CaptureList capture_list_;
unsigned num_requests_waiting_;
unsigned num_slots_available_;
base::ConditionVariable requests_waiting_;
base::ConditionVariable slots_available_;
DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc);
};
class ResolveHostResponseHelper {
public:
using Callback =
base::OnceCallback<void(CompletionOnceCallback completion_callback,
int error)>;
ResolveHostResponseHelper() = default;
explicit ResolveHostResponseHelper(
std::unique_ptr<HostResolverManager::CancellableResolveHostRequest>
request)
: request_(std::move(request)) {
top_level_result_error_ = request_->Start(base::BindOnce(
&ResolveHostResponseHelper::OnComplete, base::Unretained(this)));
}
ResolveHostResponseHelper(
std::unique_ptr<HostResolverManager::CancellableResolveHostRequest>
request,
Callback custom_callback)
: request_(std::move(request)) {
top_level_result_error_ = request_->Start(
base::BindOnce(std::move(custom_callback),
base::BindOnce(&ResolveHostResponseHelper::OnComplete,
base::Unretained(this))));
}
bool complete() const { return top_level_result_error_ != ERR_IO_PENDING; }
int top_level_result_error() {
WaitForCompletion();
return top_level_result_error_;
}
int result_error() {
WaitForCompletion();
return request_->GetResolveErrorInfo().error;
}
HostResolverManager::CancellableResolveHostRequest* request() {
return request_.get();
}
void CancelRequest() {
DCHECK(request_);
DCHECK(!complete());
request_ = nullptr;
}
void OnComplete(int error) {
DCHECK(!complete());
top_level_result_error_ = error;
run_loop_.Quit();
}
private:
void WaitForCompletion() {
DCHECK(request_);
if (complete()) {
return;
}
run_loop_.Run();
DCHECK(complete());
}
std::unique_ptr<HostResolverManager::CancellableResolveHostRequest> request_;
int top_level_result_error_ = ERR_IO_PENDING;
base::RunLoop run_loop_;
DISALLOW_COPY_AND_ASSIGN(ResolveHostResponseHelper);
};
// Using LookupAttemptHostResolverProc simulate very long lookups, and control
// which attempt resolves the host.
class LookupAttemptHostResolverProc : public HostResolverProc {
public:
LookupAttemptHostResolverProc(HostResolverProc* previous,
int attempt_number_to_resolve,
int total_attempts)
: HostResolverProc(previous),
attempt_number_to_resolve_(attempt_number_to_resolve),
current_attempt_number_(0),
total_attempts_(total_attempts),
total_attempts_resolved_(0),
resolved_attempt_number_(0),
num_attempts_waiting_(0),
all_done_(&lock_),
blocked_attempt_signal_(&lock_) {}
// Test harness will wait for all attempts to finish before checking the
// results.
void WaitForAllAttemptsToFinish() {
base::AutoLock auto_lock(lock_);
while (total_attempts_resolved_ != total_attempts_) {
all_done_.Wait();
}
}
void WaitForNAttemptsToBeBlocked(int n) {
base::AutoLock auto_lock(lock_);
while (num_attempts_waiting_ < n) {
blocked_attempt_signal_.Wait();
}
}
// All attempts will wait for an attempt to resolve the host.
void WaitForAnAttemptToComplete() {
{
base::AutoLock auto_lock(lock_);
base::ScopedAllowBaseSyncPrimitivesForTesting
scoped_allow_base_sync_primitives;
while (resolved_attempt_number_ == 0)
all_done_.Wait();
}
all_done_.Broadcast(); // Tell all waiting attempts to proceed.
}
// Returns the number of attempts that have finished the Resolve() method.
int GetTotalAttemptsResolved() {
base::AutoLock auto_lock(lock_);
return total_attempts_resolved_;
}
// Sets the resolved attempt number and unblocks waiting
// attempts.
void SetResolvedAttemptNumber(int n) {
base::AutoLock auto_lock(lock_);
EXPECT_EQ(0, resolved_attempt_number_);
resolved_attempt_number_ = n;
all_done_.Broadcast();
}
// HostResolverProc methods.
int Resolve(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) override {
bool wait_for_right_attempt_to_complete = true;
{
base::AutoLock auto_lock(lock_);
++current_attempt_number_;
++num_attempts_waiting_;
if (current_attempt_number_ == attempt_number_to_resolve_) {
resolved_attempt_number_ = current_attempt_number_;
wait_for_right_attempt_to_complete = false;
}
}
blocked_attempt_signal_.Broadcast();
if (wait_for_right_attempt_to_complete)
// Wait for the attempt_number_to_resolve_ attempt to resolve.
WaitForAnAttemptToComplete();
int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
addrlist, os_error);
{
base::AutoLock auto_lock(lock_);
++total_attempts_resolved_;
--num_attempts_waiting_;
}
all_done_.Broadcast(); // Tell all attempts to proceed.
// Since any negative number is considered a network error, with -1 having
// special meaning (ERR_IO_PENDING). We could return the attempt that has
// resolved the host as a negative number. For example, if attempt number 3
// resolves the host, then this method returns -4.
if (result == OK)
return -1 - resolved_attempt_number_;
else
return result;
}
protected:
~LookupAttemptHostResolverProc() override = default;
private:
int attempt_number_to_resolve_;
int current_attempt_number_; // Incremented whenever Resolve is called.
int total_attempts_;
int total_attempts_resolved_;
int resolved_attempt_number_;
int num_attempts_waiting_;
// All attempts wait for right attempt to be resolve.
base::Lock lock_;
base::ConditionVariable all_done_;
base::ConditionVariable blocked_attempt_signal_;
};
// TestHostResolverManager's sole purpose is to mock the IPv6 reachability test.
// By default, this pretends that IPv6 is globally reachable.
// This class is necessary so unit tests run the same on dual-stack machines as
// well as IPv4 only machines.
class TestHostResolverManager : public HostResolverManager {
public:
TestHostResolverManager(const HostResolver::ManagerOptions& options,
SystemDnsConfigChangeNotifier* notifier,
NetLog* net_log,
bool ipv6_reachable = true)
: HostResolverManager(options, notifier, net_log),
ipv6_reachable_(ipv6_reachable) {}
~TestHostResolverManager() override = default;
private:
const bool ipv6_reachable_;
bool IsGloballyReachable(const IPAddress& dest,
const NetLogWithSource& net_log) override {
return ipv6_reachable_;
}
};
bool HasAddress(const IPAddress& search_address, const AddressList& addresses) {
for (const auto& address : addresses) {
if (search_address == address.address())
return true;
}
return false;
}
void TestBothLoopbackIPs(const std::string& host) {
AddressList addresses;
EXPECT_TRUE(ResolveLocalHostname(host, &addresses));
EXPECT_EQ(2u, addresses.size());
EXPECT_TRUE(HasAddress(IPAddress::IPv4Localhost(), addresses));
EXPECT_TRUE(HasAddress(IPAddress::IPv6Localhost(), addresses));
}
} // namespace
class HostResolverManagerTest : public TestWithTaskEnvironment {
public:
static const int kDefaultPort = 80;
explicit HostResolverManagerTest(
base::test::TaskEnvironment::TimeSource time_source =
base::test::TaskEnvironment::TimeSource::SYSTEM_TIME)
: TestWithTaskEnvironment(time_source),
proc_(new MockHostResolverProc()) {}
void CreateResolver(bool check_ipv6_on_wifi = true) {
CreateResolverWithLimitsAndParams(kMaxJobs, DefaultParams(proc_.get()),
true /* ipv6_reachable */,
check_ipv6_on_wifi);
}
void DestroyResolver() {
if (!resolver_)
return;
resolver_->DeregisterResolveContext(resolve_context_.get());
resolver_ = nullptr;
}
// This HostResolverManager will only allow 1 outstanding resolve at a time
// and perform no retries.
void CreateSerialResolver(bool check_ipv6_on_wifi = true) {
ProcTaskParams params = DefaultParams(proc_.get());
params.max_retry_attempts = 0u;
CreateResolverWithLimitsAndParams(1u, params, true /* ipv6_reachable */,
check_ipv6_on_wifi);
}
protected:
// testing::Test implementation:
void SetUp() override {
request_context_ = std::make_unique<TestURLRequestContext>();
resolve_context_ = std::make_unique<ResolveContext>(
request_context_.get(), true /* enable_caching */);
CreateResolver();
}
void TearDown() override {
if (resolver_) {
EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
}
DestroyResolver();
EXPECT_FALSE(proc_->HasBlockedRequests());
}
void CreateResolverWithLimitsAndParams(size_t max_concurrent_resolves,
const ProcTaskParams& params,
bool ipv6_reachable,
bool check_ipv6_on_wifi) {
HostResolver::ManagerOptions options = DefaultOptions();
options.max_concurrent_resolves = max_concurrent_resolves;
options.check_ipv6_on_wifi = check_ipv6_on_wifi;
CreateResolverWithOptionsAndParams(std::move(options), params,
ipv6_reachable);
}
virtual HostResolver::ManagerOptions DefaultOptions() {
HostResolver::ManagerOptions options;
options.max_concurrent_resolves = kMaxJobs;
options.max_system_retry_attempts = kMaxRetryAttempts;
return options;
}
virtual void CreateResolverWithOptionsAndParams(
HostResolver::ManagerOptions options,
const ProcTaskParams& params,
bool ipv6_reachable) {
// Use HostResolverManagerDnsTest if enabling DNS client.
DCHECK(!options.insecure_dns_client_enabled);
DestroyResolver();
resolver_ = std::make_unique<TestHostResolverManager>(
options, nullptr /* notifier */, nullptr /* net_log */, ipv6_reachable);
resolver_->set_proc_params_for_test(params);
resolver_->RegisterResolveContext(resolve_context_.get());
}
// Friendship is not inherited, so use proxies to access those.
size_t num_running_dispatcher_jobs() const {
DCHECK(resolver_.get());
return resolver_->num_running_dispatcher_jobs_for_tests();
}
void set_allow_fallback_to_proctask(bool allow_fallback_to_proctask) {
DCHECK(resolver_.get());
resolver_->allow_fallback_to_proctask_ = allow_fallback_to_proctask;
}
static unsigned maximum_insecure_dns_task_failures() {
return DnsClient::kMaxInsecureFallbackFailures;
}
bool IsIPv6Reachable(const NetLogWithSource& net_log) {
return resolver_->IsIPv6Reachable(net_log);
}
void PopulateCache(const HostCache::Key& key, IPEndPoint endpoint) {
resolver_->CacheResult(resolve_context_->host_cache(), key,
HostCache::Entry(OK, AddressList(endpoint),
HostCache::Entry::SOURCE_UNKNOWN),
base::TimeDelta::FromSeconds(1));
}
const std::pair<const HostCache::Key, HostCache::Entry>* GetCacheHit(
const HostCache::Key& key) {
DCHECK(resolve_context_->host_cache());
return resolve_context_->host_cache()->LookupStale(
key, base::TimeTicks(), nullptr, false /* ignore_secure */);
}
void MakeCacheStale() {
DCHECK(resolve_context_->host_cache());
resolve_context_->host_cache()->Invalidate();
}
IPEndPoint CreateExpected(const std::string& ip_literal, uint16_t port) {
IPAddress ip;
bool result = ip.AssignFromIPLiteral(ip_literal);
DCHECK(result);
return IPEndPoint(ip, port);
}
scoped_refptr<MockHostResolverProc> proc_;
std::unique_ptr<HostResolverManager> resolver_;
std::unique_ptr<URLRequestContext> request_context_;
std::unique_ptr<ResolveContext> resolve_context_;
};
TEST_F(HostResolverManagerTest, AsynchronousLookup) {
proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_THAT(response.top_level_result_error(), IsOk());
EXPECT_THAT(response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("192.168.1.42", 80)));
EXPECT_FALSE(response.request()->GetStaleInfo());
EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
GetCacheHit(HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
0 /* host_resolver_flags */,
HostResolverSource::ANY,
NetworkIsolationKey()));
EXPECT_TRUE(cache_result);
}
TEST_F(HostResolverManagerTest, JobsClearedOnCompletion) {
proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
}
TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_MultipleRequests) {
proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response1(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
ResolveHostResponseHelper response2(resolver_->CreateRequest(
HostPortPair("just.testing", 85), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
EXPECT_THAT(response1.result_error(), IsOk());
EXPECT_THAT(response2.result_error(), IsOk());
EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
}
TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_Failure) {
proc_->AddRuleForAllFamilies(std::string(),
"0.0.0.1"); // Default to failures.
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
}
TEST_F(HostResolverManagerTest, JobsClearedOnCompletion_Abort) {
proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_EQ(1u, resolver_->num_jobs_for_testing());
NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
proc_->SignalMultiple(1u);
EXPECT_THAT(response.result_error(), IsError(ERR_NETWORK_CHANGED));
EXPECT_EQ(0u, resolver_->num_jobs_for_testing());
}
TEST_F(HostResolverManagerTest, DnsQueryType) {
proc_->AddRule("host", ADDRESS_FAMILY_IPV4, "192.168.1.20");
proc_->AddRule("host", ADDRESS_FAMILY_IPV6, "::5");
HostResolver::ResolveHostParameters parameters;
parameters.dns_query_type = DnsQueryType::A;
ResolveHostResponseHelper v4_response(resolver_->CreateRequest(
HostPortPair("host", 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
parameters.dns_query_type = DnsQueryType::AAAA;
ResolveHostResponseHelper v6_response(resolver_->CreateRequest(
HostPortPair("host", 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
proc_->SignalMultiple(2u);
EXPECT_THAT(v4_response.result_error(), IsOk());
EXPECT_THAT(v4_response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("192.168.1.20", 80)));
EXPECT_THAT(v6_response.result_error(), IsOk());
EXPECT_THAT(v6_response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("::5", 80)));
}
TEST_F(HostResolverManagerTest, DnsQueryWithoutAliases) {
proc_->AddRule("host", ADDRESS_FAMILY_IPV4, "192.168.1.20");
HostResolver::ResolveHostParameters parameters;
parameters.dns_query_type = DnsQueryType::A;
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("host", 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
proc_->SignalMultiple(1u);
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_THAT(response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("192.168.1.20", 80)));
EXPECT_FALSE(response.request()->GetDnsAliasResults());
}
TEST_F(HostResolverManagerTest, LocalhostIPV4IPV6Lookup) {
HostResolver::ResolveHostParameters parameters;
parameters.dns_query_type = DnsQueryType::A;
ResolveHostResponseHelper v4_v4_response(resolver_->CreateRequest(
HostPortPair("localhost", 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
EXPECT_THAT(v4_v4_response.result_error(), IsOk());
EXPECT_THAT(v4_v4_response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("127.0.0.1", 80)));
parameters.dns_query_type = DnsQueryType::AAAA;
ResolveHostResponseHelper v4_v6_response(resolver_->CreateRequest(
HostPortPair("localhost", 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
EXPECT_THAT(v4_v6_response.result_error(), IsOk());
EXPECT_THAT(v4_v6_response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("::1", 80)));
ResolveHostResponseHelper v4_unsp_response(resolver_->CreateRequest(
HostPortPair("localhost", 80), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(), resolve_context_->host_cache()));
EXPECT_THAT(v4_unsp_response.result_error(), IsOk());
EXPECT_THAT(
v4_unsp_response.request()->GetAddressResults().value().endpoints(),
testing::UnorderedElementsAre(CreateExpected("127.0.0.1", 80),
CreateExpected("::1", 80)));
}
TEST_F(HostResolverManagerTest, ResolveIPLiteralWithHostResolverSystemOnly) {
const char kIpLiteral[] = "178.78.32.1";
// Add a mapping to tell if the resolver proc was called (if it was called,
// then the result will be the remapped value. Otherwise it will be the IP
// literal).
proc_->AddRuleForAllFamilies(kIpLiteral, "183.45.32.1");
HostResolver::ResolveHostParameters parameters;
parameters.source = HostResolverSource::SYSTEM;
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair(kIpLiteral, 80), NetworkIsolationKey(), NetLogWithSource(),
parameters, resolve_context_.get(), resolve_context_->host_cache()));
// IP literal resolution is expected to take precedence over source, so the
// result is expected to be the input IP, not the result IP from the proc rule
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_THAT(response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected(kIpLiteral, 80)));
EXPECT_FALSE(response.request()->GetStaleInfo());
}
TEST_F(HostResolverManagerTest, EmptyListMeansNameNotResolved) {
proc_->AddRuleForAllFamilies("just.testing", "");
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_FALSE(response.request()->GetAddressResults());
EXPECT_FALSE(response.request()->GetStaleInfo());
EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
}
TEST_F(HostResolverManagerTest, FailedAsynchronousLookup) {
proc_->AddRuleForAllFamilies(std::string(),
"0.0.0.1"); // Default to failures.
proc_->SignalMultiple(1u);
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_THAT(response.top_level_result_error(),
IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_FALSE(response.request()->GetAddressResults());
EXPECT_FALSE(response.request()->GetStaleInfo());
EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
// Also test that the error is not cached.
const std::pair<const HostCache::Key, HostCache::Entry>* cache_result =
GetCacheHit(HostCache::Key("just.testing", DnsQueryType::UNSPECIFIED,
0 /* host_resolver_flags */,
HostResolverSource::ANY,
NetworkIsolationKey()));
EXPECT_FALSE(cache_result);
}
TEST_F(HostResolverManagerTest, AbortedAsynchronousLookup) {
ResolveHostResponseHelper response0(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
ASSERT_FALSE(response0.complete());
ASSERT_TRUE(proc_->WaitFor(1u));
// Resolver is destroyed while job is running on WorkerPool.
DestroyResolver();
proc_->SignalAll();
// To ensure there was no spurious callback, complete with a new resolver.
CreateResolver();
ResolveHostResponseHelper response1(resolver_->CreateRequest(
HostPortPair("just.testing", 80), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
proc_->SignalMultiple(2u);
EXPECT_THAT(response1.result_error(), IsOk());
// This request was canceled.
EXPECT_FALSE(response0.complete());
}
TEST_F(HostResolverManagerTest, NumericIPv4Address) {
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("127.1.2.3", 5555), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_THAT(response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("127.1.2.3", 5555)));
}
TEST_F(HostResolverManagerTest, NumericIPv6Address) {
// Resolve a plain IPv6 address. Don't worry about [brackets], because
// the caller should have removed them.
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair("2001:db8::1", 5555), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsOk());
EXPECT_THAT(response.request()->GetAddressResults().value().endpoints(),
testing::ElementsAre(CreateExpected("2001:db8::1", 5555)));
}
TEST_F(HostResolverManagerTest, EmptyHost) {
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair(std::string(), 5555), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_FALSE(response.request()->GetAddressResults());
}
TEST_F(HostResolverManagerTest, EmptyDotsHost) {
for (int i = 0; i < 16; ++i) {
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair(std::string(i, '.'), 5555), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_FALSE(response.request()->GetAddressResults());
}
}
TEST_F(HostResolverManagerTest, LongHost) {
ResolveHostResponseHelper response(resolver_->CreateRequest(
HostPortPair(std::string(4097, 'a'), 5555), NetworkIsolationKey(),
NetLogWithSource(), absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache()));
EXPECT_THAT(response.result_error(), IsError(ERR_NAME_NOT_RESOLVED));
EXPECT_FALSE(response.request()->GetAddressResults());
}
TEST_F(HostResolverManagerTest, DeDupeRequests) {
// Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
// blocked, these should all pile up until we signal it.
std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("a", 80), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("b", 80), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("b", 81), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("a", 82), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("b", 83), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
for (auto& response : responses) {
ASSERT_FALSE(response->complete());
}
proc_->SignalMultiple(2u); // One for "a", one for "b".
for (auto& response : responses) {
EXPECT_THAT(response->result_error(), IsOk());
}
}
TEST_F(HostResolverManagerTest, CancelMultipleRequests) {
std::vector<std::unique_ptr<ResolveHostResponseHelper>> responses;
responses.emplace_back(
std::make_unique<ResolveHostResponseHelper>(resolver_->CreateRequest(
HostPortPair("a", 80), NetworkIsolationKey(), NetLogWithSource(),
absl::nullopt, resolve_context_.get(),
resolve_context_->host_cache())));
responses.emplace_back(