forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsHostResolver.cpp
1986 lines (1685 loc) · 66.6 KB
/
nsHostResolver.cpp
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
/* vim:set ts=4 sw=2 sts=2 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsIThreadPool.h"
#if defined(HAVE_RES_NINIT)
# include <sys/types.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <arpa/nameser.h>
# include <resolv.h>
# define RES_RETRY_ON_FAILURE
#endif
#include <stdlib.h>
#include <ctime>
#include "nsHostResolver.h"
#include "nsError.h"
#include "nsISupports.h"
#include "nsISupportsUtils.h"
#include "nsIThreadManager.h"
#include "nsComponentManagerUtils.h"
#include "nsNetUtil.h"
#include "nsPrintfCString.h"
#include "nsXPCOMCIDInternal.h"
#include "prthread.h"
#include "prerror.h"
#include "prtime.h"
#include "mozilla/Logging.h"
#include "PLDHashTable.h"
#include "nsQueryObject.h"
#include "nsURLHelper.h"
#include "nsThreadUtils.h"
#include "nsThreadPool.h"
#include "GetAddrInfo.h"
#include "TRR.h"
#include "TRRQuery.h"
#include "TRRService.h"
#include "mozilla/Atomics.h"
#include "mozilla/glean/GleanMetrics.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Telemetry.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_network.h"
// Put DNSLogging.h at the end to avoid LOG being overwritten by other headers.
#include "DNSLogging.h"
#ifdef XP_WIN
# include "mozilla/WindowsVersion.h"
#endif // XP_WIN
#ifdef MOZ_WIDGET_ANDROID
# include "mozilla/jni/Utils.h"
#endif
#define IS_ADDR_TYPE(_type) ((_type) == nsIDNSService::RESOLVE_TYPE_DEFAULT)
#define IS_OTHER_TYPE(_type) ((_type) != nsIDNSService::RESOLVE_TYPE_DEFAULT)
using namespace mozilla;
using namespace mozilla::net;
// None of our implementations expose a TTL for negative responses, so we use a
// constant always.
static const unsigned int NEGATIVE_RECORD_LIFETIME = 60;
//----------------------------------------------------------------------------
// Use a persistent thread pool in order to avoid spinning up new threads all
// the time. In particular, thread creation results in a res_init() call from
// libc which is quite expensive.
//
// The pool dynamically grows between 0 and MaxResolverThreads() in size. New
// requests go first to an idle thread. If that cannot be found and there are
// fewer than MaxResolverThreads() currently in the pool a new thread is created
// for high priority requests. If the new request is at a lower priority a new
// thread will only be created if there are fewer than
// MaxResolverThreadsAnyPriority() currently outstanding. If a thread cannot be
// created or an idle thread located for the request it is queued.
//
// When the pool is greater than MaxResolverThreadsAnyPriority() in size a
// thread will be destroyed after ShortIdleTimeoutSeconds of idle time. Smaller
// pools use LongIdleTimeoutSeconds for a timeout period.
// for threads 1 -> MaxResolverThreadsAnyPriority()
#define LongIdleTimeoutSeconds 300
// for threads MaxResolverThreadsAnyPriority() + 1 -> MaxResolverThreads()
#define ShortIdleTimeoutSeconds 60
//----------------------------------------------------------------------------
namespace mozilla::net {
LazyLogModule gHostResolverLog("nsHostResolver");
} // namespace mozilla::net
//----------------------------------------------------------------------------
#if defined(RES_RETRY_ON_FAILURE)
// this class represents the resolver state for a given thread. if we
// encounter a lookup failure, then we can invoke the Reset method on an
// instance of this class to reset the resolver (in case /etc/resolv.conf
// for example changed). this is mainly an issue on GNU systems since glibc
// only reads in /etc/resolv.conf once per thread. it may be an issue on
// other systems as well.
class nsResState {
public:
nsResState()
// initialize mLastReset to the time when this object
// is created. this means that a reset will not occur
// if a thread is too young. the alternative would be
// to initialize this to the beginning of time, so that
// the first failure would cause a reset, but since the
// thread would have just started up, it likely would
// already have current /etc/resolv.conf info.
: mLastReset(PR_IntervalNow()) {}
bool Reset() {
// reset no more than once per second
if (PR_IntervalToSeconds(PR_IntervalNow() - mLastReset) < 1) {
return false;
}
mLastReset = PR_IntervalNow();
auto result = res_ninit(&_res);
LOG(("nsResState::Reset() > 'res_ninit' returned %d", result));
return (result == 0);
}
private:
PRIntervalTime mLastReset;
};
#endif // RES_RETRY_ON_FAILURE
class DnsThreadListener final : public nsIThreadPoolListener {
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSITHREADPOOLLISTENER
private:
virtual ~DnsThreadListener() = default;
};
NS_IMETHODIMP
DnsThreadListener::OnThreadCreated() { return NS_OK; }
NS_IMETHODIMP
DnsThreadListener::OnThreadShuttingDown() {
DNSThreadShutdown();
return NS_OK;
}
NS_IMPL_ISUPPORTS(DnsThreadListener, nsIThreadPoolListener)
//----------------------------------------------------------------------------
static const char kPrefGetTtl[] = "network.dns.get-ttl";
static const char kPrefNativeIsLocalhost[] = "network.dns.native-is-localhost";
static const char kPrefThreadIdleTime[] =
"network.dns.resolver-thread-extra-idle-time-seconds";
static bool sGetTtlEnabled = false;
mozilla::Atomic<bool, mozilla::Relaxed> gNativeIsLocalhost;
mozilla::Atomic<bool, mozilla::Relaxed> sNativeHTTPSSupported{false};
static void DnsPrefChanged(const char* aPref, void* aSelf) {
MOZ_ASSERT(NS_IsMainThread(),
"Should be getting pref changed notification on main thread!");
MOZ_ASSERT(aSelf);
if (!strcmp(aPref, kPrefGetTtl)) {
#ifdef DNSQUERY_AVAILABLE
sGetTtlEnabled = Preferences::GetBool(kPrefGetTtl);
#endif
} else if (!strcmp(aPref, kPrefNativeIsLocalhost)) {
gNativeIsLocalhost = Preferences::GetBool(kPrefNativeIsLocalhost);
}
}
NS_IMPL_ISUPPORTS0(nsHostResolver)
nsHostResolver::nsHostResolver(uint32_t maxCacheEntries,
uint32_t defaultCacheEntryLifetime,
uint32_t defaultGracePeriod)
: mMaxCacheEntries(maxCacheEntries),
mDefaultCacheLifetime(defaultCacheEntryLifetime),
mDefaultGracePeriod(defaultGracePeriod),
mIdleTaskCV(mLock, "nsHostResolver.mIdleTaskCV") {
mCreationTime = PR_Now();
mLongIdleTimeout = TimeDuration::FromSeconds(LongIdleTimeoutSeconds);
mShortIdleTimeout = TimeDuration::FromSeconds(ShortIdleTimeoutSeconds);
}
nsHostResolver::~nsHostResolver() = default;
nsresult nsHostResolver::Init() MOZ_NO_THREAD_SAFETY_ANALYSIS {
MOZ_ASSERT(NS_IsMainThread());
if (NS_FAILED(GetAddrInfoInit())) {
return NS_ERROR_FAILURE;
}
LOG(("nsHostResolver::Init this=%p", this));
mShutdown = false;
mNCS = NetworkConnectivityService::GetSingleton();
// The preferences probably haven't been loaded from the disk yet, so we
// need to register a callback that will set up the experiment once they
// are. We also need to explicitly set a value for the props otherwise the
// callback won't be called.
{
DebugOnly<nsresult> rv = Preferences::RegisterCallbackAndCall(
&DnsPrefChanged, kPrefGetTtl, this);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Could not register DNS TTL pref callback.");
rv = Preferences::RegisterCallbackAndCall(&DnsPrefChanged,
kPrefNativeIsLocalhost, this);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Could not register DNS pref callback.");
}
#if defined(HAVE_RES_NINIT)
// We want to make sure the system is using the correct resolver settings,
// so we force it to reload those settings whenever we startup a subsequent
// nsHostResolver instance. We assume that there is no reason to do this
// for the first nsHostResolver instance since that is usually created
// during application startup.
static int initCount = 0;
if (initCount++ > 0) {
auto result = res_ninit(&_res);
LOG(("nsHostResolver::Init > 'res_ninit' returned %d", result));
}
#endif
// We can configure the threadpool to keep threads alive for a while after
// the last ThreadFunc task has been executed.
int32_t poolTimeoutSecs = Preferences::GetInt(kPrefThreadIdleTime, 60);
uint32_t poolTimeoutMs;
if (poolTimeoutSecs < 0) {
// This means never shut down the idle threads
poolTimeoutMs = UINT32_MAX;
} else {
// We clamp down the idle time between 0 and one hour.
poolTimeoutMs =
mozilla::clamped<uint32_t>(poolTimeoutSecs * 1000, 0, 3600 * 1000);
}
#if defined(XP_WIN)
// For some reason, the DNSQuery_A API doesn't work on Windows 10.
// It returns a success code, but no records. We only allow
// native HTTPS records on Win 11 for now.
sNativeHTTPSSupported = StaticPrefs::network_dns_native_https_query_win10() ||
mozilla::IsWin11OrLater();
#elif defined(MOZ_WIDGET_ANDROID)
// android_res_nquery only got added in API level 29
sNativeHTTPSSupported = jni::GetAPIVersion() >= 29;
#elif defined(XP_LINUX) || defined(XP_MACOSX)
sNativeHTTPSSupported = true;
#endif
LOG(("Native HTTPS records supported=%d", bool(sNativeHTTPSSupported)));
nsCOMPtr<nsIThreadPool> threadPool = new nsThreadPool();
MOZ_ALWAYS_SUCCEEDS(threadPool->SetThreadLimit(MaxResolverThreads()));
MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadLimit(MaxResolverThreads()));
MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadTimeout(poolTimeoutMs));
MOZ_ALWAYS_SUCCEEDS(
threadPool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize));
MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("DNS Resolver"_ns));
nsCOMPtr<nsIThreadPoolListener> listener = new DnsThreadListener();
threadPool->SetListener(listener);
mResolverThreads = ToRefPtr(std::move(threadPool));
return NS_OK;
}
void nsHostResolver::ClearPendingQueue(
LinkedList<RefPtr<nsHostRecord>>& aPendingQ) {
// loop through pending queue, erroring out pending lookups.
if (!aPendingQ.isEmpty()) {
for (const RefPtr<nsHostRecord>& rec : aPendingQ) {
rec->Cancel();
if (rec->IsAddrRecord()) {
CompleteLookup(rec, NS_ERROR_ABORT, nullptr, rec->pb, rec->originSuffix,
rec->mTRRSkippedReason, nullptr);
} else {
mozilla::net::TypeRecordResultType empty(Nothing{});
CompleteLookupByType(rec, NS_ERROR_ABORT, empty, rec->mTRRSkippedReason,
0, rec->pb);
}
}
}
}
//
// FlushCache() is what we call when the network has changed. We must not
// trust names that were resolved before this change. They may resolve
// differently now.
//
// This function removes all existing resolved host entries from the hash.
// Names that are in the pending queues can be left there. Entries in the
// cache that have 'Resolve' set true but not 'OnQueue' are being resolved
// right now, so we need to mark them to get re-resolved on completion!
void nsHostResolver::FlushCache(bool aTrrToo) {
MutexAutoLock lock(mLock);
mQueue.FlushEvictionQ(mRecordDB, lock);
// Refresh the cache entries that are resolving RIGHT now, remove the rest.
for (auto iter = mRecordDB.Iter(); !iter.Done(); iter.Next()) {
nsHostRecord* record = iter.UserData();
// Try to remove the record, or mark it for refresh.
// By-type records are from TRR. We do not need to flush those entry
// when the network has change, because they are not local.
if (record->IsAddrRecord()) {
RefPtr<AddrHostRecord> addrRec = do_QueryObject(record);
MOZ_ASSERT(addrRec);
if (addrRec->RemoveOrRefresh(aTrrToo)) {
mQueue.MaybeRemoveFromQ(record, lock);
LOG(("Removing (%s) Addr record from mRecordDB", record->host.get()));
iter.Remove();
}
} else if (aTrrToo) {
// remove by type records
LOG(("Removing (%s) type record from mRecordDB", record->host.get()));
iter.Remove();
}
}
}
void nsHostResolver::Shutdown() {
LOG(("Shutting down host resolver.\n"));
{
DebugOnly<nsresult> rv =
Preferences::UnregisterCallback(&DnsPrefChanged, kPrefGetTtl, this);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Could not unregister DNS TTL pref callback.");
}
LinkedList<RefPtr<nsHostRecord>> pendingQHigh, pendingQMed, pendingQLow,
evictionQ;
{
MutexAutoLock lock(mLock);
mShutdown = true;
if (mNumIdleTasks) {
mIdleTaskCV.NotifyAll();
}
mQueue.ClearAll(
[&](nsHostRecord* aRec) {
mLock.AssertCurrentThreadOwns();
if (aRec->IsAddrRecord()) {
CompleteLookupLocked(aRec, NS_ERROR_ABORT, nullptr, aRec->pb,
aRec->originSuffix, aRec->mTRRSkippedReason,
nullptr, lock);
} else {
mozilla::net::TypeRecordResultType empty(Nothing{});
CompleteLookupByTypeLocked(aRec, NS_ERROR_ABORT, empty,
aRec->mTRRSkippedReason, 0, aRec->pb,
lock);
}
},
lock);
for (const auto& data : mRecordDB.Values()) {
data->Cancel();
}
// empty host database
mRecordDB.Clear();
mNCS = nullptr;
}
// Shutdown the resolver threads, but with a timeout of 2 seconds (prefable).
// If the timeout is exceeded, any stuck threads will be leaked.
mResolverThreads->ShutdownWithTimeout(
StaticPrefs::network_dns_resolver_shutdown_timeout_ms());
{
mozilla::DebugOnly<nsresult> rv = GetAddrInfoShutdown();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to shutdown GetAddrInfo");
}
}
nsresult nsHostResolver::GetHostRecord(
const nsACString& host, const nsACString& aTrrServer, uint16_t type,
nsIDNSService::DNSFlags flags, uint16_t af, bool pb,
const nsCString& originSuffix, nsHostRecord** result) {
MutexAutoLock lock(mLock);
nsHostKey key(host, aTrrServer, type, flags, af, pb, originSuffix);
RefPtr<nsHostRecord> rec =
mRecordDB.LookupOrInsertWith(key, [&] { return InitRecord(key); });
if (rec->IsAddrRecord()) {
RefPtr<AddrHostRecord> addrRec = do_QueryObject(rec);
if (addrRec->addr) {
return NS_ERROR_FAILURE;
}
}
if (rec->mResolving) {
return NS_ERROR_FAILURE;
}
*result = rec.forget().take();
return NS_OK;
}
nsHostRecord* nsHostResolver::InitRecord(const nsHostKey& key) {
if (IS_ADDR_TYPE(key.type)) {
return new AddrHostRecord(key);
}
return new TypeHostRecord(key);
}
already_AddRefed<nsHostRecord> nsHostResolver::InitLoopbackRecord(
const nsHostKey& key, nsresult* aRv) {
MOZ_ASSERT(aRv);
MOZ_ASSERT(IS_ADDR_TYPE(key.type));
*aRv = NS_ERROR_FAILURE;
RefPtr<nsHostRecord> rec = InitRecord(key);
nsTArray<NetAddr> addresses;
NetAddr addr;
if (key.af == PR_AF_INET || key.af == PR_AF_UNSPEC) {
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(addr.InitFromString("127.0.0.1"_ns)));
addresses.AppendElement(addr);
}
if (key.af == PR_AF_INET6 || key.af == PR_AF_UNSPEC) {
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(addr.InitFromString("::1"_ns)));
addresses.AppendElement(addr);
}
RefPtr<AddrInfo> ai =
new AddrInfo(rec->host, DNSResolverType::Native, 0, std::move(addresses));
RefPtr<AddrHostRecord> addrRec = do_QueryObject(rec);
MutexAutoLock lock(addrRec->addr_info_lock);
addrRec->addr_info = ai;
addrRec->SetExpiration(TimeStamp::NowLoRes(), mDefaultCacheLifetime,
mDefaultGracePeriod);
addrRec->negative = false;
*aRv = NS_OK;
return rec.forget();
}
static bool IsNativeHTTPSEnabled() {
if (!StaticPrefs::network_dns_native_https_query()) {
return false;
}
return sNativeHTTPSSupported;
}
nsresult nsHostResolver::ResolveHost(const nsACString& aHost,
const nsACString& aTrrServer,
int32_t aPort, uint16_t type,
const OriginAttributes& aOriginAttributes,
nsIDNSService::DNSFlags flags, uint16_t af,
nsResolveHostCallback* aCallback) {
nsAutoCString host(aHost);
NS_ENSURE_TRUE(!host.IsEmpty(), NS_ERROR_UNEXPECTED);
nsAutoCString originSuffix;
aOriginAttributes.CreateSuffix(originSuffix);
LOG(("Resolving host [%s]<%s>%s%s type %d. [this=%p]\n", host.get(),
originSuffix.get(), flags & RES_BYPASS_CACHE ? " - bypassing cache" : "",
flags & RES_REFRESH_CACHE ? " - refresh cache" : "", type, this));
// ensure that we are working with a valid hostname before proceeding. see
// bug 304904 for details.
if (!net_IsValidHostName(host)) {
return NS_ERROR_UNKNOWN_HOST;
}
// If TRR is disabled we can return immediately if the native API is disabled
if (!IsNativeHTTPSEnabled() && IS_OTHER_TYPE(type) &&
Mode() == nsIDNSService::MODE_TRROFF) {
return NS_ERROR_UNKNOWN_HOST;
}
// Used to try to parse to an IP address literal.
NetAddr tempAddr;
if (IS_OTHER_TYPE(type) && (NS_SUCCEEDED(tempAddr.InitFromString(host)))) {
// For by-type queries the host cannot be IP literal.
return NS_ERROR_UNKNOWN_HOST;
}
RefPtr<nsResolveHostCallback> callback(aCallback);
// if result is set inside the lock, then we need to issue the
// callback before returning.
RefPtr<nsHostRecord> result;
nsresult status = NS_OK, rv = NS_OK;
{
MutexAutoLock lock(mLock);
if (mShutdown) {
return NS_ERROR_NOT_INITIALIZED;
}
// check to see if there is already an entry for this |host|
// in the hash table. if so, then check to see if we can't
// just reuse the lookup result. otherwise, if there are
// any pending callbacks, then add to pending callbacks queue,
// and return. otherwise, add ourselves as first pending
// callback, and proceed to do the lookup.
Maybe<nsCString> originHost;
if (StaticPrefs::network_dns_port_prefixed_qname_https_rr() &&
type == nsIDNSService::RESOLVE_TYPE_HTTPSSVC && aPort != -1 &&
aPort != 443) {
originHost = Some(host);
host = nsPrintfCString("_%d._https.%s", aPort, host.get());
LOG((" Using port prefixed host name [%s]", host.get()));
}
bool excludedFromTRR = false;
if (TRRService::Get() && TRRService::Get()->IsExcludedFromTRR(host)) {
flags |= nsIDNSService::RESOLVE_DISABLE_TRR;
excludedFromTRR = true;
if (!aTrrServer.IsEmpty()) {
return NS_ERROR_UNKNOWN_HOST;
}
}
nsHostKey key(host, aTrrServer, type, flags, af,
(aOriginAttributes.mPrivateBrowsingId > 0), originSuffix);
// Check if we have a localhost domain, if so hardcode to loopback
if (IS_ADDR_TYPE(type) && IsLoopbackHostname(host)) {
nsresult rv;
RefPtr<nsHostRecord> result = InitLoopbackRecord(key, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
MOZ_ASSERT(result);
aCallback->OnResolveHostComplete(this, result, NS_OK);
return NS_OK;
}
RefPtr<nsHostRecord> rec =
mRecordDB.LookupOrInsertWith(key, [&] { return InitRecord(key); });
RefPtr<AddrHostRecord> addrRec = do_QueryObject(rec);
MOZ_ASSERT(rec, "Record should not be null");
MOZ_ASSERT((IS_ADDR_TYPE(type) && rec->IsAddrRecord() && addrRec) ||
(IS_OTHER_TYPE(type) && !rec->IsAddrRecord()));
if (IS_OTHER_TYPE(type) && originHost) {
RefPtr<TypeHostRecord> typeRec = do_QueryObject(rec);
typeRec->mOriginHost = std::move(originHost);
}
if (excludedFromTRR) {
rec->RecordReason(TRRSkippedReason::TRR_EXCLUDED);
}
if (!(flags & RES_BYPASS_CACHE) &&
rec->HasUsableResult(TimeStamp::NowLoRes(), flags)) {
result = FromCache(rec, host, type, status, lock);
} else if (addrRec && addrRec->addr) {
// if the host name is an IP address literal and has been
// parsed, go ahead and use it.
LOG((" Using cached address for IP Literal [%s].\n", host.get()));
result = FromCachedIPLiteral(rec);
} else if (addrRec && NS_SUCCEEDED(tempAddr.InitFromString(host))) {
// try parsing the host name as an IP address literal to short
// circuit full host resolution. (this is necessary on some
// platforms like Win9x. see bug 219376 for more details.)
LOG((" Host is IP Literal [%s].\n", host.get()));
result = FromIPLiteral(addrRec, tempAddr);
} else if (mQueue.PendingCount() >= MAX_NON_PRIORITY_REQUESTS &&
!IsHighPriority(flags) && !rec->mResolving) {
LOG(
(" Lookup queue full: dropping %s priority request for "
"host [%s].\n",
IsMediumPriority(flags) ? "medium" : "low", host.get()));
if (IS_ADDR_TYPE(type)) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_OVERFLOW);
}
// This is a lower priority request and we are swamped, so refuse it.
rv = NS_ERROR_DNS_LOOKUP_QUEUE_FULL;
// Check if the offline flag is set.
} else if (flags & RES_OFFLINE) {
LOG((" Offline request for host [%s]; ignoring.\n", host.get()));
rv = NS_ERROR_OFFLINE;
// We do not have a valid result till here.
// A/AAAA request can check for an alternative entry like AF_UNSPEC.
// Otherwise we need to start a new query.
} else if (!rec->mResolving) {
result =
FromUnspecEntry(rec, host, aTrrServer, originSuffix, type, flags, af,
aOriginAttributes.mPrivateBrowsingId > 0, status);
// If this is a by-type request or if no valid record was found
// in the cache or this is an AF_UNSPEC request, then start a
// new lookup.
if (!result) {
LOG((" No usable record in cache for host [%s] type %d.", host.get(),
type));
if (flags & RES_REFRESH_CACHE) {
rec->Invalidate();
}
// Add callback to the list of pending callbacks.
rec->mCallbacks.insertBack(callback);
rec->flags = flags;
rv = NameLookup(rec, lock);
if (IS_ADDR_TYPE(type)) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2,
METHOD_NETWORK_FIRST);
}
if (NS_FAILED(rv) && callback->isInList()) {
callback->remove();
} else {
LOG(
(" DNS lookup for host [%s] blocking "
"pending 'getaddrinfo' or trr query: "
"callback [%p]",
host.get(), callback.get()));
}
}
} else {
LOG(
(" Host [%s] is being resolved. Appending callback "
"[%p].",
host.get(), callback.get()));
rec->mCallbacks.insertBack(callback);
if (rec && rec->onQueue()) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2,
METHOD_NETWORK_SHARED);
// Consider the case where we are on a pending queue of
// lower priority than the request is being made at.
// In that case we should upgrade to the higher queue.
if (IsHighPriority(flags) && !IsHighPriority(rec->flags)) {
// Move from (low|med) to high.
mQueue.MoveToAnotherPendingQ(rec, flags, lock);
rec->flags = flags;
ConditionallyCreateThread(rec);
} else if (IsMediumPriority(flags) && IsLowPriority(rec->flags)) {
// Move from low to med.
mQueue.MoveToAnotherPendingQ(rec, flags, lock);
rec->flags = flags;
mIdleTaskCV.Notify();
}
}
}
if (result && callback->isInList()) {
callback->remove();
}
} // lock
if (result) {
callback->OnResolveHostComplete(this, result, status);
}
return rv;
}
already_AddRefed<nsHostRecord> nsHostResolver::FromCache(
nsHostRecord* aRec, const nsACString& aHost, uint16_t aType,
nsresult& aStatus, const MutexAutoLock& aLock) {
LOG((" Using cached record for host [%s].\n",
nsPromiseFlatCString(aHost).get()));
// put reference to host record on stack...
RefPtr<nsHostRecord> result = aRec;
if (IS_ADDR_TYPE(aType)) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_HIT);
}
// For entries that are in the grace period
// or all cached negative entries, use the cache but start a new
// lookup in the background
ConditionallyRefreshRecord(aRec, aHost, aLock);
if (aRec->negative) {
LOG((" Negative cache entry for host [%s].\n",
nsPromiseFlatCString(aHost).get()));
if (IS_ADDR_TYPE(aType)) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_NEGATIVE_HIT);
}
aStatus = NS_ERROR_UNKNOWN_HOST;
}
return result.forget();
}
already_AddRefed<nsHostRecord> nsHostResolver::FromCachedIPLiteral(
nsHostRecord* aRec) {
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_LITERAL);
RefPtr<nsHostRecord> result = aRec;
return result.forget();
}
already_AddRefed<nsHostRecord> nsHostResolver::FromIPLiteral(
AddrHostRecord* aAddrRec, const NetAddr& aAddr) {
// ok, just copy the result into the host record, and be
// done with it! ;-)
aAddrRec->addr = MakeUnique<NetAddr>(aAddr);
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_LITERAL);
// put reference to host record on stack...
RefPtr<nsHostRecord> result = aAddrRec;
return result.forget();
}
already_AddRefed<nsHostRecord> nsHostResolver::FromUnspecEntry(
nsHostRecord* aRec, const nsACString& aHost, const nsACString& aTrrServer,
const nsACString& aOriginSuffix, uint16_t aType,
nsIDNSService::DNSFlags aFlags, uint16_t af, bool aPb, nsresult& aStatus) {
RefPtr<nsHostRecord> result = nullptr;
// If this is an IPV4 or IPV6 specific request, check if there is
// an AF_UNSPEC entry we can use. Otherwise, hit the resolver...
RefPtr<AddrHostRecord> addrRec = do_QueryObject(aRec);
if (addrRec && !(aFlags & RES_BYPASS_CACHE) &&
((af == PR_AF_INET) || (af == PR_AF_INET6))) {
// Check for an AF_UNSPEC entry.
const nsHostKey unspecKey(aHost, aTrrServer,
nsIDNSService::RESOLVE_TYPE_DEFAULT, aFlags,
PR_AF_UNSPEC, aPb, aOriginSuffix);
RefPtr<nsHostRecord> unspecRec = mRecordDB.Get(unspecKey);
TimeStamp now = TimeStamp::NowLoRes();
if (unspecRec && unspecRec->HasUsableResult(now, aFlags)) {
MOZ_ASSERT(unspecRec->IsAddrRecord());
RefPtr<AddrHostRecord> addrUnspecRec = do_QueryObject(unspecRec);
MOZ_ASSERT(addrUnspecRec);
MOZ_ASSERT(addrUnspecRec->addr_info || addrUnspecRec->negative,
"Entry should be resolved or negative.");
LOG((" Trying AF_UNSPEC entry for host [%s] af: %s.\n",
PromiseFlatCString(aHost).get(),
(af == PR_AF_INET) ? "AF_INET" : "AF_INET6"));
// We need to lock in case any other thread is reading
// addr_info.
MutexAutoLock lock(addrRec->addr_info_lock);
addrRec->addr_info = nullptr;
addrRec->addr_info_gencnt++;
if (unspecRec->negative) {
aRec->negative = unspecRec->negative;
aRec->CopyExpirationTimesAndFlagsFrom(unspecRec);
} else if (addrUnspecRec->addr_info) {
MutexAutoLock lock(addrUnspecRec->addr_info_lock);
if (addrUnspecRec->addr_info) {
// Search for any valid address in the AF_UNSPEC entry
// in the cache (not blocklisted and from the right
// family).
nsTArray<NetAddr> addresses;
for (const auto& addr : addrUnspecRec->addr_info->Addresses()) {
if ((af == addr.inet.family) &&
!addrUnspecRec->Blocklisted(&addr)) {
addresses.AppendElement(addr);
}
}
if (!addresses.IsEmpty()) {
addrRec->addr_info = new AddrInfo(
addrUnspecRec->addr_info->Hostname(),
addrUnspecRec->addr_info->CanonicalHostname(),
addrUnspecRec->addr_info->ResolverType(),
addrUnspecRec->addr_info->TRRType(), std::move(addresses));
addrRec->addr_info_gencnt++;
aRec->CopyExpirationTimesAndFlagsFrom(unspecRec);
}
}
}
// Now check if we have a new record.
if (aRec->HasUsableResult(now, aFlags)) {
result = aRec;
if (aRec->negative) {
aStatus = NS_ERROR_UNKNOWN_HOST;
}
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2, METHOD_HIT);
ConditionallyRefreshRecord(aRec, aHost, lock);
} else if (af == PR_AF_INET6) {
// For AF_INET6, a new lookup means another AF_UNSPEC
// lookup. We have already iterated through the
// AF_UNSPEC addresses, so we mark this record as
// negative.
LOG(
(" No AF_INET6 in AF_UNSPEC entry: "
"host [%s] unknown host.",
nsPromiseFlatCString(aHost).get()));
result = aRec;
aRec->negative = true;
aStatus = NS_ERROR_UNKNOWN_HOST;
Telemetry::Accumulate(Telemetry::DNS_LOOKUP_METHOD2,
METHOD_NEGATIVE_HIT);
}
}
}
return result.forget();
}
void nsHostResolver::DetachCallback(
const nsACString& host, const nsACString& aTrrServer, uint16_t aType,
const OriginAttributes& aOriginAttributes, nsIDNSService::DNSFlags flags,
uint16_t af, nsResolveHostCallback* aCallback, nsresult status) {
RefPtr<nsHostRecord> rec;
RefPtr<nsResolveHostCallback> callback(aCallback);
{
MutexAutoLock lock(mLock);
nsAutoCString originSuffix;
aOriginAttributes.CreateSuffix(originSuffix);
nsHostKey key(host, aTrrServer, aType, flags, af,
(aOriginAttributes.mPrivateBrowsingId > 0), originSuffix);
RefPtr<nsHostRecord> entry = mRecordDB.Get(key);
if (entry) {
// walk list looking for |callback|... we cannot assume
// that it will be there!
for (nsResolveHostCallback* c : entry->mCallbacks) {
if (c == callback) {
rec = entry;
c->remove();
break;
}
}
}
}
// complete callback with the given status code; this would only be done if
// the record was in the process of being resolved.
if (rec) {
callback->OnResolveHostComplete(this, rec, status);
}
}
nsresult nsHostResolver::ConditionallyCreateThread(nsHostRecord* rec) {
if (mNumIdleTasks) {
// wake up idle tasks to process this lookup
mIdleTaskCV.Notify();
} else if ((mActiveTaskCount < MaxResolverThreadsAnyPriority()) ||
(IsHighPriority(rec->flags) &&
mActiveTaskCount < MaxResolverThreads())) {
nsCOMPtr<nsIRunnable> event = mozilla::NewRunnableMethod(
"nsHostResolver::ThreadFunc", this, &nsHostResolver::ThreadFunc);
mActiveTaskCount++;
nsresult rv =
mResolverThreads->Dispatch(event, nsIEventTarget::DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
mActiveTaskCount--;
}
} else {
LOG((" Unable to find a thread for looking up host [%s].\n",
rec->host.get()));
}
return NS_OK;
}
nsresult nsHostResolver::TrrLookup_unlocked(nsHostRecord* rec, TRR* pushedTRR) {
MutexAutoLock lock(mLock);
return TrrLookup(rec, lock, pushedTRR);
}
void nsHostResolver::MaybeRenewHostRecord(nsHostRecord* aRec) {
MutexAutoLock lock(mLock);
MaybeRenewHostRecordLocked(aRec, lock);
}
void nsHostResolver::MaybeRenewHostRecordLocked(nsHostRecord* aRec,
const MutexAutoLock& aLock) {
mQueue.MaybeRenewHostRecord(aRec, aLock);
}
bool nsHostResolver::TRRServiceEnabledForRecord(nsHostRecord* aRec) {
MOZ_ASSERT(aRec, "Record must not be empty");
MOZ_ASSERT(aRec->mEffectiveTRRMode != nsIRequest::TRR_DEFAULT_MODE,
"effective TRR mode must be computed before this call");
if (!TRRService::Get()) {
aRec->RecordReason(TRRSkippedReason::TRR_NO_GSERVICE);
return false;
}
// We always try custom resolvers.
if (!aRec->mTrrServer.IsEmpty()) {
return true;
}
nsIRequest::TRRMode reqMode = aRec->mEffectiveTRRMode;
if (TRRService::Get()->Enabled(reqMode)) {
return true;
}
if (NS_IsOffline()) {
// If we are in the NOT_CONFIRMED state _because_ we lack connectivity,
// then we should report that the browser is offline instead.
aRec->RecordReason(TRRSkippedReason::TRR_IS_OFFLINE);
return false;
}
auto hasConnectivity = [this]() -> bool {
mLock.AssertCurrentThreadOwns();
if (!mNCS) {
return true;
}
nsINetworkConnectivityService::ConnectivityState ipv4 = mNCS->GetIPv4();
nsINetworkConnectivityService::ConnectivityState ipv6 = mNCS->GetIPv6();
if (ipv4 == nsINetworkConnectivityService::OK ||
ipv6 == nsINetworkConnectivityService::OK) {
return true;
}
if (ipv4 == nsINetworkConnectivityService::UNKNOWN ||
ipv6 == nsINetworkConnectivityService::UNKNOWN) {
// One of the checks hasn't completed yet. Optimistically assume we'll
// have network connectivity.
return true;
}
return false;
};
if (!hasConnectivity()) {
aRec->RecordReason(TRRSkippedReason::TRR_NO_CONNECTIVITY);
return false;
}
bool isConfirmed = TRRService::Get()->IsConfirmed();
if (!isConfirmed) {
aRec->RecordReason(TRRSkippedReason::TRR_NOT_CONFIRMED);
}
return isConfirmed;
}
// returns error if no TRR resolve is issued
// it is impt this is not called while a native lookup is going on
nsresult nsHostResolver::TrrLookup(nsHostRecord* aRec,
const MutexAutoLock& aLock, TRR* pushedTRR) {
if (Mode() == nsIDNSService::MODE_TRROFF ||
StaticPrefs::network_dns_disabled()) {
return NS_ERROR_UNKNOWN_HOST;
}
LOG(("TrrLookup host:%s af:%" PRId16, aRec->host.get(), aRec->af));
RefPtr<nsHostRecord> rec(aRec);
mLock.AssertCurrentThreadOwns();
RefPtr<AddrHostRecord> addrRec;
RefPtr<TypeHostRecord> typeRec;
if (rec->IsAddrRecord()) {
addrRec = do_QueryObject(rec);
MOZ_ASSERT(addrRec);
} else {
typeRec = do_QueryObject(rec);
MOZ_ASSERT(typeRec);
}
MOZ_ASSERT(!rec->mResolving);
if (!TRRServiceEnabledForRecord(aRec)) {
return NS_ERROR_UNKNOWN_HOST;
}
MaybeRenewHostRecordLocked(rec, aLock);
RefPtr<TRRQuery> query = new TRRQuery(this, rec);
nsresult rv = query->DispatchLookup(pushedTRR);
if (NS_FAILED(rv)) {
rec->RecordReason(TRRSkippedReason::TRR_DID_NOT_MAKE_QUERY);
return rv;
}
{
auto lock = rec->mTRRQuery.Lock();
MOZ_ASSERT(!lock.ref(), "TRR already in progress");
lock.ref() = query;
}
rec->mResolving++;
rec->mTrrAttempts++;
rec->StoreNative(false);