1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=4 sw=2 sts=2 et cin: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 #include "nsCharSeparatedTokenizer.h"
10 #include "nsContentUtils.h"
11 #include "nsHttpHandler.h"
12 #include "nsHttpChannel.h"
13 #include "nsHostResolver.h"
14 #include "nsIHttpChannel.h"
15 #include "nsIHttpChannelInternal.h"
16 #include "nsIIOService.h"
17 #include "nsIInputStream.h"
18 #include "nsIObliviousHttp.h"
19 #include "nsISupports.h"
20 #include "nsISupportsUtils.h"
21 #include "nsITimedChannel.h"
22 #include "nsIUploadChannel2.h"
23 #include "nsIURIMutator.h"
24 #include "nsNetUtil.h"
25 #include "nsQueryObject.h"
26 #include "nsStringStream.h"
27 #include "nsThreadUtils.h"
28 #include "nsURLHelper.h"
29 #include "ObliviousHttpChannel.h"
31 #include "TRRService.h"
32 #include "TRRServiceChannel.h"
33 #include "TRRLoadInfo.h"
35 #include "mozilla/Base64.h"
36 #include "mozilla/DebugOnly.h"
37 #include "mozilla/Logging.h"
38 #include "mozilla/Preferences.h"
39 #include "mozilla/StaticPrefs_network.h"
40 #include "mozilla/Telemetry.h"
41 #include "mozilla/TimeStamp.h"
42 #include "mozilla/Tokenizer.h"
43 #include "mozilla/UniquePtr.h"
44 // Put DNSLogging.h at the end to avoid LOG being overwritten by other headers.
45 #include "DNSLogging.h"
50 NS_IMPL_ISUPPORTS(TRR
, nsIHttpPushListener
, nsIInterfaceRequestor
,
51 nsIStreamListener
, nsIRunnable
, nsITimerCallback
)
53 // when firing off a normal A or AAAA query
54 TRR::TRR(AHostResolver
* aResolver
, nsHostRecord
* aRec
, enum TrrType aType
)
55 : mozilla::Runnable("TRR"),
57 mHostResolver(aResolver
),
59 mOriginSuffix(aRec
->originSuffix
) {
62 MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess() || XRE_IsSocketProcess(),
63 "TRR must be in parent or socket process");
66 // when following CNAMEs
67 TRR::TRR(AHostResolver
* aResolver
, nsHostRecord
* aRec
, nsCString
& aHost
,
68 enum TrrType
& aType
, unsigned int aLoopCount
, bool aPB
)
69 : mozilla::Runnable("TRR"),
72 mHostResolver(aResolver
),
75 mCnameLoop(aLoopCount
),
76 mOriginSuffix(aRec
? aRec
->originSuffix
: ""_ns
) {
77 MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess() || XRE_IsSocketProcess(),
78 "TRR must be in parent or socket process");
82 TRR::TRR(AHostResolver
* aResolver
, bool aPB
)
83 : mozilla::Runnable("TRR"), mHostResolver(aResolver
), mPB(aPB
) {
84 MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess() || XRE_IsSocketProcess(),
85 "TRR must be in parent or socket process");
89 TRR::TRR(AHostResolver
* aResolver
, nsACString
& aHost
, enum TrrType aType
,
90 const nsACString
& aOriginSuffix
, bool aPB
, bool aUseFreshConnection
)
91 : mozilla::Runnable("TRR"),
94 mHostResolver(aResolver
),
97 mOriginSuffix(aOriginSuffix
),
98 mUseFreshConnection(aUseFreshConnection
) {
99 MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess() || XRE_IsSocketProcess(),
100 "TRR must be in parent or socket process");
103 void TRR::HandleTimeout() {
105 RecordReason(TRRSkippedReason::TRR_TIMEOUT
);
106 Cancel(NS_ERROR_NET_TIMEOUT_EXTERNAL
);
110 TRR::Notify(nsITimer
* aTimer
) {
111 if (aTimer
== mTimeout
) {
114 MOZ_CRASH("Unknown timer");
122 MOZ_ASSERT_IF(XRE_IsParentProcess() && TRRService::Get(),
123 NS_IsMainThread() || TRRService::Get()->IsOnTRRThread());
124 MOZ_ASSERT_IF(XRE_IsSocketProcess(), NS_IsMainThread());
126 if ((TRRService::Get() == nullptr) || NS_FAILED(SendHTTPRequest())) {
127 RecordReason(TRRSkippedReason::TRR_SEND_FAILED
);
128 FailData(NS_ERROR_FAILURE
);
129 // The dtor will now be run
134 DNSPacket
* TRR::GetOrCreateDNSPacket() {
136 mPacket
= MakeUnique
<DNSPacket
>();
139 return mPacket
.get();
142 nsresult
TRR::CreateQueryURI(nsIURI
** aOutURI
) {
144 nsCOMPtr
<nsIURI
> dnsURI
;
145 if (UseDefaultServer()) {
146 TRRService::Get()->GetURI(uri
);
148 uri
= mRec
->mTrrServer
;
151 nsresult rv
= NS_NewURI(getter_AddRefs(dnsURI
), uri
);
156 dnsURI
.forget(aOutURI
);
160 bool TRR::MaybeBlockRequest() {
161 if (((mType
== TRRTYPE_A
) || (mType
== TRRTYPE_AAAA
)) &&
162 mRec
->mEffectiveTRRMode
!= nsIRequest::TRR_ONLY_MODE
) {
163 // let NS resolves skip the blocklist check
164 // we also don't check the blocklist for TRR only requests
167 // If TRRService isn't enabled anymore for the req, don't do TRR.
168 if (!TRRService::Get()->Enabled(mRec
->mEffectiveTRRMode
)) {
169 RecordReason(TRRSkippedReason::TRR_MODE_NOT_ENABLED
);
173 if (!StaticPrefs::network_trr_strict_native_fallback() &&
174 UseDefaultServer() &&
175 TRRService::Get()->IsTemporarilyBlocked(mHost
, mOriginSuffix
, mPB
,
177 if (mType
== TRRTYPE_A
) {
178 // count only blocklist for A records to avoid double counts
179 Telemetry::Accumulate(Telemetry::DNS_TRR_BLACKLISTED3
,
180 TRRService::ProviderKey(), true);
183 RecordReason(TRRSkippedReason::TRR_HOST_BLOCKED_TEMPORARY
);
184 // not really an error but no TRR is issued
188 if (TRRService::Get()->IsExcludedFromTRR(mHost
)) {
189 RecordReason(TRRSkippedReason::TRR_EXCLUDED
);
193 if (UseDefaultServer() && (mType
== TRRTYPE_A
)) {
194 Telemetry::Accumulate(Telemetry::DNS_TRR_BLACKLISTED3
,
195 TRRService::ProviderKey(), false);
202 nsresult
TRR::SendHTTPRequest() {
203 // This is essentially the "run" method - created from nsHostResolver
205 return NS_ERROR_FAILURE
;
208 if ((mType
!= TRRTYPE_A
) && (mType
!= TRRTYPE_AAAA
) &&
209 (mType
!= TRRTYPE_NS
) && (mType
!= TRRTYPE_TXT
) &&
210 (mType
!= TRRTYPE_HTTPSSVC
)) {
211 // limit the calling interface because nsHostResolver has explicit slots for
213 return NS_ERROR_FAILURE
;
216 if (MaybeBlockRequest()) {
217 return NS_ERROR_UNKNOWN_HOST
;
220 LOG(("TRR::SendHTTPRequest resolve %s type %u\n", mHost
.get(), mType
));
223 bool disableECS
= StaticPrefs::network_trr_disable_ECS();
225 GetOrCreateDNSPacket()->EncodeRequest(body
, mHost
, mType
, disableECS
);
227 HandleEncodeError(rv
);
231 bool useGet
= StaticPrefs::network_trr_useGET();
232 nsCOMPtr
<nsIURI
> dnsURI
;
233 rv
= CreateQueryURI(getter_AddRefs(dnsURI
));
235 LOG(("TRR:SendHTTPRequest: NewURI failed!\n"));
240 /* For GET requests, the outgoing packet needs to be Base64url-encoded and
241 then appended to the end of the URI. */
242 nsAutoCString encoded
;
243 rv
= Base64URLEncode(body
.Length(),
244 reinterpret_cast<const unsigned char*>(body
.get()),
245 Base64URLEncodePaddingPolicy::Omit
, encoded
);
246 NS_ENSURE_SUCCESS(rv
, rv
);
249 rv
= dnsURI
->GetQuery(query
);
254 if (query
.IsEmpty()) {
255 query
.Assign("?dns="_ns
);
257 query
.Append("&dns="_ns
);
259 query
.Append(encoded
);
261 rv
= NS_MutateURI(dnsURI
).SetQuery(query
).Finalize(dnsURI
);
262 LOG(("TRR::SendHTTPRequest GET dns=%s\n", body
.get()));
265 nsCOMPtr
<nsIChannel
> channel
;
266 bool useOHTTP
= StaticPrefs::network_trr_use_ohttp();
268 nsCOMPtr
<nsIObliviousHttpService
> ohttpService(
269 do_GetService("@mozilla.org/network/oblivious-http-service;1"));
271 return NS_ERROR_FAILURE
;
273 nsCOMPtr
<nsIURI
> relayURI
;
274 nsTArray
<uint8_t> encodedConfig
;
275 rv
= ohttpService
->GetTRRSettings(getter_AddRefs(relayURI
), encodedConfig
);
280 return NS_ERROR_FAILURE
;
282 rv
= ohttpService
->NewChannel(relayURI
, dnsURI
, encodedConfig
,
283 getter_AddRefs(channel
));
285 rv
= DNSUtils::CreateChannelHelper(dnsURI
, getter_AddRefs(channel
));
287 if (NS_FAILED(rv
) || !channel
) {
288 LOG(("TRR:SendHTTPRequest: NewChannel failed!\n"));
292 auto loadFlags
= nsIRequest::LOAD_ANONYMOUS
| nsIRequest::INHIBIT_CACHING
|
293 nsIRequest::LOAD_BYPASS_CACHE
|
294 nsIChannel::LOAD_BYPASS_URL_CLASSIFIER
;
295 if (mUseFreshConnection
) {
296 // Causes TRRServiceChannel to tell the connection manager
297 // to clear out any connection with the current conn info.
298 loadFlags
|= nsIRequest::LOAD_FRESH_CONNECTION
;
300 channel
->SetLoadFlags(loadFlags
);
301 NS_ENSURE_SUCCESS(rv
, rv
);
303 rv
= channel
->SetNotificationCallbacks(this);
304 NS_ENSURE_SUCCESS(rv
, rv
);
306 nsCOMPtr
<nsIHttpChannel
> httpChannel
= do_QueryInterface(channel
);
308 return NS_ERROR_UNEXPECTED
;
311 // This connection should not use TRR
312 rv
= httpChannel
->SetTRRMode(nsIRequest::TRR_DISABLED_MODE
);
313 NS_ENSURE_SUCCESS(rv
, rv
);
315 nsCString
contentType(ContentType());
316 rv
= httpChannel
->SetRequestHeader("Accept"_ns
, contentType
, false);
317 NS_ENSURE_SUCCESS(rv
, rv
);
320 if (UseDefaultServer()) {
321 TRRService::Get()->GetCredentials(cred
);
323 if (!cred
.IsEmpty()) {
324 rv
= httpChannel
->SetRequestHeader("Authorization"_ns
, cred
, false);
325 NS_ENSURE_SUCCESS(rv
, rv
);
328 nsCOMPtr
<nsIHttpChannelInternal
> internalChannel
= do_QueryInterface(channel
);
329 if (!internalChannel
) {
330 return NS_ERROR_UNEXPECTED
;
333 // setting a small stream window means the h2 stack won't pipeline a window
334 // update with each HEADERS or reply to a DATA with a WINDOW UPDATE
335 rv
= internalChannel
->SetInitialRwin(127 * 1024);
336 NS_ENSURE_SUCCESS(rv
, rv
);
337 rv
= internalChannel
->SetIsTRRServiceChannel(true);
338 NS_ENSURE_SUCCESS(rv
, rv
);
340 if (UseDefaultServer() && StaticPrefs::network_trr_async_connInfo()) {
341 RefPtr
<nsHttpConnectionInfo
> trrConnInfo
=
342 TRRService::Get()->TRRConnectionInfo();
345 dnsURI
->GetHost(host
);
346 if (host
.Equals(trrConnInfo
->GetOrigin())) {
347 internalChannel
->SetConnectionInfo(trrConnInfo
);
348 LOG(("TRR::SendHTTPRequest use conn info:%s\n",
349 trrConnInfo
->HashKey().get()));
351 MOZ_DIAGNOSTIC_ASSERT(false);
354 TRRService::Get()->InitTRRConnectionInfo();
359 rv
= httpChannel
->SetRequestMethod("GET"_ns
);
360 NS_ENSURE_SUCCESS(rv
, rv
);
362 nsCOMPtr
<nsIUploadChannel2
> uploadChannel
= do_QueryInterface(httpChannel
);
363 if (!uploadChannel
) {
364 return NS_ERROR_UNEXPECTED
;
366 uint32_t streamLength
= body
.Length();
367 nsCOMPtr
<nsIInputStream
> uploadStream
;
369 NS_NewCStringInputStream(getter_AddRefs(uploadStream
), std::move(body
));
370 NS_ENSURE_SUCCESS(rv
, rv
);
372 rv
= uploadChannel
->ExplicitSetUploadStream(uploadStream
, contentType
,
373 streamLength
, "POST"_ns
, false);
374 NS_ENSURE_SUCCESS(rv
, rv
);
377 rv
= SetupTRRServiceChannelInternal(httpChannel
, useGet
, contentType
);
382 rv
= httpChannel
->AsyncOpen(this);
387 // If the asyncOpen succeeded we can say that we actually attempted to
388 // use the TRR connection.
389 RefPtr
<AddrHostRecord
> addrRec
= do_QueryObject(mRec
);
391 addrRec
->mResolverType
= ResolverType();
394 NS_NewTimerWithCallback(
395 getter_AddRefs(mTimeout
), this,
396 mTimeoutMs
? mTimeoutMs
: TRRService::Get()->GetRequestTimeout(),
397 nsITimer::TYPE_ONE_SHOT
);
404 nsresult
TRR::SetupTRRServiceChannelInternal(nsIHttpChannel
* aChannel
,
406 const nsACString
& aContentType
) {
407 nsCOMPtr
<nsIHttpChannel
> httpChannel
= aChannel
;
408 MOZ_ASSERT(httpChannel
);
413 httpChannel
->SetRequestHeader("Cache-Control"_ns
, "no-store"_ns
, false);
414 NS_ENSURE_SUCCESS(rv
, rv
);
417 // Sanitize the request by removing the Accept-Language header so we minimize
418 // the amount of fingerprintable information we send to the server.
419 if (!StaticPrefs::network_trr_send_accept_language_headers()) {
420 rv
= httpChannel
->SetRequestHeader("Accept-Language"_ns
, ""_ns
, false);
421 NS_ENSURE_SUCCESS(rv
, rv
);
424 // Sanitize the request by removing the User-Agent
425 if (!StaticPrefs::network_trr_send_user_agent_headers()) {
426 rv
= httpChannel
->SetRequestHeader("User-Agent"_ns
, ""_ns
, false);
427 NS_ENSURE_SUCCESS(rv
, rv
);
430 if (StaticPrefs::network_trr_send_empty_accept_encoding_headers()) {
431 rv
= httpChannel
->SetEmptyRequestHeader("Accept-Encoding"_ns
);
432 NS_ENSURE_SUCCESS(rv
, rv
);
435 // set the *default* response content type
436 if (NS_FAILED(httpChannel
->SetContentType(aContentType
))) {
437 LOG(("TRR::SetupTRRServiceChannelInternal: couldn't set content-type!\n"));
440 nsCOMPtr
<nsITimedChannel
> timedChan(do_QueryInterface(httpChannel
));
442 timedChan
->SetTimingEnabled(true);
449 TRR::GetInterface(const nsIID
& iid
, void** result
) {
450 if (!iid
.Equals(NS_GET_IID(nsIHttpPushListener
))) {
451 return NS_ERROR_NO_INTERFACE
;
454 nsCOMPtr
<nsIHttpPushListener
> copy(this);
455 *result
= copy
.forget().take();
459 nsresult
TRR::DohDecodeQuery(const nsCString
& query
, nsCString
& host
,
460 enum TrrType
& type
) {
461 FallibleTArray
<uint8_t> binary
;
462 bool found_dns
= false;
463 LOG(("TRR::DohDecodeQuery %s!\n", query
.get()));
465 // extract "dns=" from the query string
467 for (const nsACString
& token
:
468 nsCCharSeparatedTokenizer(query
, '&').ToRange()) {
469 nsDependentCSubstring dns
= Substring(token
, 0, 4);
470 nsAutoCString
check(dns
);
471 if (check
.Equals("dns=")) {
472 nsDependentCSubstring q
= Substring(token
, 4, -1);
479 LOG(("TRR::DohDecodeQuery no dns= in pushed URI query string\n"));
480 return NS_ERROR_ILLEGAL_VALUE
;
484 Base64URLDecode(data
, Base64URLDecodePaddingPolicy::Ignore
, binary
);
485 NS_ENSURE_SUCCESS(rv
, rv
);
486 uint32_t avail
= binary
.Length();
488 return NS_ERROR_FAILURE
;
490 // check the query bit and the opcode
491 if ((binary
[2] & 0xf8) != 0) {
492 return NS_ERROR_FAILURE
;
494 uint32_t qdcount
= (binary
[4] << 8) + binary
[5];
496 return NS_ERROR_FAILURE
;
503 if (avail
< (index
+ 1)) {
504 return NS_ERROR_UNEXPECTED
;
507 length
= binary
[index
];
512 if (avail
< (index
+ 1 + length
)) {
513 return NS_ERROR_UNEXPECTED
;
515 host
.Append((const char*)(&binary
[0]) + index
+ 1, length
);
517 index
+= 1 + length
; // skip length byte + label
520 LOG(("TRR::DohDecodeQuery host %s\n", host
.get()));
522 if (avail
< (index
+ 2)) {
523 return NS_ERROR_UNEXPECTED
;
526 i16
+= binary
[index
] << 8;
527 i16
+= binary
[index
+ 1];
528 type
= (enum TrrType
)i16
;
530 LOG(("TRR::DohDecodeQuery type %d\n", (int)type
));
535 nsresult
TRR::ReceivePush(nsIHttpChannel
* pushed
, nsHostRecord
* pushedRec
) {
536 if (!mHostResolver
) {
537 return NS_ERROR_UNEXPECTED
;
540 LOG(("TRR::ReceivePush: PUSH incoming!\n"));
542 nsCOMPtr
<nsIURI
> uri
;
543 pushed
->GetURI(getter_AddRefs(uri
));
546 uri
->GetQuery(query
);
549 if (NS_FAILED(DohDecodeQuery(query
, mHost
, mType
)) ||
550 HostIsIPLiteral(mHost
)) { // literal
551 LOG(("TRR::ReceivePush failed to decode %s\n", mHost
.get()));
552 return NS_ERROR_UNEXPECTED
;
555 if ((mType
!= TRRTYPE_A
) && (mType
!= TRRTYPE_AAAA
) &&
556 (mType
!= TRRTYPE_TXT
) && (mType
!= TRRTYPE_HTTPSSVC
)) {
557 LOG(("TRR::ReceivePush unknown type %d\n", mType
));
558 return NS_ERROR_UNEXPECTED
;
561 if (TRRService::Get()->IsExcludedFromTRR(mHost
)) {
562 return NS_ERROR_FAILURE
;
565 uint32_t type
= nsIDNSService::RESOLVE_TYPE_DEFAULT
;
566 if (mType
== TRRTYPE_TXT
) {
567 type
= nsIDNSService::RESOLVE_TYPE_TXT
;
568 } else if (mType
== TRRTYPE_HTTPSSVC
) {
569 type
= nsIDNSService::RESOLVE_TYPE_HTTPSSVC
;
572 RefPtr
<nsHostRecord
> hostRecord
;
574 rv
= mHostResolver
->GetHostRecord(
575 mHost
, ""_ns
, type
, pushedRec
->flags
, pushedRec
->af
, pushedRec
->pb
,
576 pushedRec
->originSuffix
, getter_AddRefs(hostRecord
));
581 // Since we don't ever call nsHostResolver::NameLookup for this record,
582 // we need to copy the trr mode from the previous record
583 if (hostRecord
->mEffectiveTRRMode
== nsIRequest::TRR_DEFAULT_MODE
) {
584 hostRecord
->mEffectiveTRRMode
=
585 static_cast<nsIRequest::TRRMode
>(pushedRec
->mEffectiveTRRMode
);
588 rv
= mHostResolver
->TrrLookup_unlocked(hostRecord
, this);
593 rv
= pushed
->AsyncOpen(this);
600 mRec
.swap(hostRecord
);
606 TRR::OnPush(nsIHttpChannel
* associated
, nsIHttpChannel
* pushed
) {
607 LOG(("TRR::OnPush entry\n"));
608 MOZ_ASSERT(associated
== mChannel
);
610 return NS_ERROR_FAILURE
;
612 if (!UseDefaultServer()) {
613 return NS_ERROR_FAILURE
;
616 RefPtr
<TRR
> trr
= new TRR(mHostResolver
, mPB
);
617 return trr
->ReceivePush(pushed
, mRec
);
621 TRR::OnStartRequest(nsIRequest
* aRequest
) {
622 LOG(("TRR::OnStartRequest %p %s %d\n", this, mHost
.get(), mType
));
624 nsresult status
= NS_OK
;
625 aRequest
->GetStatus(&status
);
627 if (NS_FAILED(status
)) {
628 if (NS_IsOffline()) {
629 RecordReason(TRRSkippedReason::TRR_IS_OFFLINE
);
633 case NS_ERROR_UNKNOWN_HOST
:
634 RecordReason(TRRSkippedReason::TRR_CHANNEL_DNS_FAIL
);
636 case NS_ERROR_OFFLINE
:
637 RecordReason(TRRSkippedReason::TRR_IS_OFFLINE
);
639 case NS_ERROR_NET_RESET
:
640 RecordReason(TRRSkippedReason::TRR_NET_RESET
);
642 case NS_ERROR_NET_TIMEOUT
:
643 case NS_ERROR_NET_TIMEOUT_EXTERNAL
:
644 RecordReason(TRRSkippedReason::TRR_NET_TIMEOUT
);
646 case NS_ERROR_PROXY_CONNECTION_REFUSED
:
647 RecordReason(TRRSkippedReason::TRR_NET_REFUSED
);
649 case NS_ERROR_NET_INTERRUPT
:
650 RecordReason(TRRSkippedReason::TRR_NET_INTERRUPT
);
652 case NS_ERROR_NET_INADEQUATE_SECURITY
:
653 RecordReason(TRRSkippedReason::TRR_NET_INADEQ_SEQURITY
);
656 RecordReason(TRRSkippedReason::TRR_UNKNOWN_CHANNEL_FAILURE
);
663 void TRR::SaveAdditionalRecords(
664 const nsClassHashtable
<nsCStringHashKey
, DOHresp
>& aRecords
) {
669 for (const auto& recordEntry
: aRecords
) {
670 if (recordEntry
.GetData() && recordEntry
.GetData()->mAddresses
.IsEmpty()) {
671 // no point in adding empty records.
674 RefPtr
<nsHostRecord
> hostRecord
;
675 rv
= mHostResolver
->GetHostRecord(
676 recordEntry
.GetKey(), EmptyCString(),
677 nsIDNSService::RESOLVE_TYPE_DEFAULT
, mRec
->flags
, AF_UNSPEC
, mRec
->pb
,
678 mRec
->originSuffix
, getter_AddRefs(hostRecord
));
680 LOG(("Failed to get host record for additional record %s",
681 nsCString(recordEntry
.GetKey()).get()));
685 new AddrInfo(recordEntry
.GetKey(), ResolverType(), TRRTYPE_A
,
686 std::move(recordEntry
.GetData()->mAddresses
),
687 recordEntry
.GetData()->mTtl
));
688 mHostResolver
->MaybeRenewHostRecord(hostRecord
);
690 // Since we're not actually calling NameLookup for this record, we need
691 // to set these fields to avoid assertions in CompleteLookup.
692 // This is quite hacky, and should be fixed.
694 hostRecord
->mResolving
++;
695 hostRecord
->mEffectiveTRRMode
=
696 static_cast<nsIRequest::TRRMode
>(mRec
->mEffectiveTRRMode
);
697 LOG(("Completing lookup for additional: %s",
698 nsCString(recordEntry
.GetKey()).get()));
699 (void)mHostResolver
->CompleteLookup(hostRecord
, NS_OK
, ai
, mPB
,
700 mOriginSuffix
, TRRSkippedReason::TRR_OK
,
705 void TRR::StoreIPHintAsDNSRecord(const struct SVCB
& aSVCBRecord
) {
706 LOG(("TRR::StoreIPHintAsDNSRecord [%p] [%s]", this,
707 aSVCBRecord
.mSvcDomainName
.get()));
708 CopyableTArray
<NetAddr
> addresses
;
709 aSVCBRecord
.GetIPHints(addresses
);
710 if (addresses
.IsEmpty()) {
714 RefPtr
<nsHostRecord
> hostRecord
;
715 nsresult rv
= mHostResolver
->GetHostRecord(
716 aSVCBRecord
.mSvcDomainName
, EmptyCString(),
717 nsIDNSService::RESOLVE_TYPE_DEFAULT
,
718 mRec
->flags
| nsIDNSService::RESOLVE_IP_HINT
, AF_UNSPEC
, mRec
->pb
,
719 mRec
->originSuffix
, getter_AddRefs(hostRecord
));
721 LOG(("Failed to get host record"));
725 mHostResolver
->MaybeRenewHostRecord(hostRecord
);
727 RefPtr
<AddrInfo
> ai(new AddrInfo(aSVCBRecord
.mSvcDomainName
, ResolverType(),
728 TRRTYPE_A
, std::move(addresses
), mTTL
));
730 // Since we're not actually calling NameLookup for this record, we need
731 // to set these fields to avoid assertions in CompleteLookup.
732 // This is quite hacky, and should be fixed.
733 hostRecord
->mResolving
++;
734 hostRecord
->mEffectiveTRRMode
=
735 static_cast<nsIRequest::TRRMode
>(mRec
->mEffectiveTRRMode
);
736 (void)mHostResolver
->CompleteLookup(hostRecord
, NS_OK
, ai
, mPB
, mOriginSuffix
,
737 TRRSkippedReason::TRR_OK
, this);
740 nsresult
TRR::ReturnData(nsIChannel
* aChannel
) {
741 if (mType
!= TRRTYPE_TXT
&& mType
!= TRRTYPE_HTTPSSVC
) {
742 // create and populate an AddrInfo instance to pass on
743 RefPtr
<AddrInfo
> ai(new AddrInfo(mHost
, ResolverType(), mType
,
744 nsTArray
<NetAddr
>(), mDNS
.mTtl
));
745 auto builder
= ai
->Build();
746 builder
.SetAddresses(std::move(mDNS
.mAddresses
));
747 builder
.SetCanonicalHostname(mCname
);
750 nsCOMPtr
<nsITimedChannel
> timedChan
= do_QueryInterface(aChannel
);
752 TimeStamp asyncOpen
, start
, end
;
753 if (NS_SUCCEEDED(timedChan
->GetAsyncOpen(&asyncOpen
)) &&
754 !asyncOpen
.IsNull()) {
755 builder
.SetTrrFetchDuration(
756 (TimeStamp::Now() - asyncOpen
).ToMilliseconds());
758 if (NS_SUCCEEDED(timedChan
->GetRequestStart(&start
)) &&
759 NS_SUCCEEDED(timedChan
->GetResponseEnd(&end
)) && !start
.IsNull() &&
761 builder
.SetTrrFetchDurationNetworkOnly((end
- start
).ToMilliseconds());
764 ai
= builder
.Finish();
766 if (!mHostResolver
) {
767 return NS_ERROR_FAILURE
;
769 (void)mHostResolver
->CompleteLookup(mRec
, NS_OK
, ai
, mPB
, mOriginSuffix
,
770 mTRRSkippedReason
, this);
771 mHostResolver
= nullptr;
774 (void)mHostResolver
->CompleteLookupByType(mRec
, NS_OK
, mResult
, mTTL
, mPB
);
779 nsresult
TRR::FailData(nsresult error
) {
780 if (!mHostResolver
) {
781 return NS_ERROR_FAILURE
;
784 // If we didn't record a reason until now, record a default one.
785 RecordReason(TRRSkippedReason::TRR_FAILED
);
787 if (mType
== TRRTYPE_TXT
|| mType
== TRRTYPE_HTTPSSVC
) {
788 TypeRecordResultType
empty(Nothing
{});
789 (void)mHostResolver
->CompleteLookupByType(mRec
, error
, empty
, 0, mPB
);
791 // create and populate an TRR AddrInfo instance to pass on to signal that
792 // this comes from TRR
793 nsTArray
<NetAddr
> noAddresses
;
794 RefPtr
<AddrInfo
> ai
=
795 new AddrInfo(mHost
, ResolverType(), mType
, std::move(noAddresses
));
797 (void)mHostResolver
->CompleteLookup(mRec
, error
, ai
, mPB
, mOriginSuffix
,
798 mTRRSkippedReason
, this);
801 mHostResolver
= nullptr;
806 void TRR::HandleDecodeError(nsresult aStatusCode
) {
807 auto rcode
= mPacket
->GetRCode();
808 if (rcode
.isOk() && rcode
.unwrap() != 0) {
809 if (rcode
.unwrap() == 0x03) {
810 RecordReason(TRRSkippedReason::TRR_NXDOMAIN
);
812 RecordReason(TRRSkippedReason::TRR_RCODE_FAIL
);
814 } else if (aStatusCode
== NS_ERROR_UNKNOWN_HOST
||
815 aStatusCode
== NS_ERROR_DEFINITIVE_UNKNOWN_HOST
) {
816 RecordReason(TRRSkippedReason::TRR_NO_ANSWERS
);
818 RecordReason(TRRSkippedReason::TRR_DECODE_FAILED
);
822 bool TRR::HasUsableResponse() {
823 if (mType
== TRRTYPE_A
|| mType
== TRRTYPE_AAAA
) {
824 return !mDNS
.mAddresses
.IsEmpty();
826 if (mType
== TRRTYPE_TXT
) {
827 return mResult
.is
<TypeRecordTxt
>();
829 if (mType
== TRRTYPE_HTTPSSVC
) {
830 return mResult
.is
<TypeRecordHTTPSSVC
>();
835 nsresult
TRR::FollowCname(nsIChannel
* aChannel
) {
838 while (NS_SUCCEEDED(rv
) && mDNS
.mAddresses
.IsEmpty() && !mCname
.IsEmpty() &&
841 LOG(("TRR::On200Response CNAME %s => %s (%u)\n", mHost
.get(), mCname
.get(),
846 LOG(("TRR: check for CNAME record for %s within previous response\n",
848 nsClassHashtable
<nsCStringHashKey
, DOHresp
> additionalRecords
;
849 rv
= GetOrCreateDNSPacket()->Decode(
850 cname
, mType
, mCname
, StaticPrefs::network_trr_allow_rfc1918(), mDNS
,
851 mResult
, additionalRecords
, mTTL
);
853 LOG(("TRR::FollowCname DohDecode %x\n", (int)rv
));
854 HandleDecodeError(rv
);
858 // restore mCname as DohDecode() change it
860 if (NS_SUCCEEDED(rv
) && HasUsableResponse()) {
861 ReturnData(aChannel
);
865 bool ra
= mPacket
&& mPacket
->RecursionAvailable().unwrapOr(false);
866 LOG(("ra = %d", ra
));
867 if (rv
== NS_ERROR_UNKNOWN_HOST
&& ra
) {
868 // If recursion is available, but no addresses have been returned,
869 // we can just return a failure here.
870 LOG(("TRR::FollowCname not sending another request as RA flag is set."));
871 FailData(NS_ERROR_UNKNOWN_HOST
);
876 LOG(("TRR::On200Response CNAME loop, eject!\n"));
877 return NS_ERROR_REDIRECT_LOOP
;
880 LOG(("TRR::On200Response CNAME %s => %s (%u)\n", mHost
.get(), mCname
.get(),
883 new TRR(mHostResolver
, mRec
, mCname
, mType
, mCnameLoop
, mPB
);
884 if (!TRRService::Get()) {
885 return NS_ERROR_FAILURE
;
887 return TRRService::Get()->DispatchTRRRequest(trr
);
890 nsresult
TRR::On200Response(nsIChannel
* aChannel
) {
891 // decode body and create an AddrInfo struct for the response
892 nsClassHashtable
<nsCStringHashKey
, DOHresp
> additionalRecords
;
893 RefPtr
<TypeHostRecord
> typeRec
= do_QueryObject(mRec
);
894 if (typeRec
&& typeRec
->mOriginHost
) {
895 GetOrCreateDNSPacket()->SetOriginHost(typeRec
->mOriginHost
);
897 nsresult rv
= GetOrCreateDNSPacket()->Decode(
898 mHost
, mType
, mCname
, StaticPrefs::network_trr_allow_rfc1918(), mDNS
,
899 mResult
, additionalRecords
, mTTL
);
901 LOG(("TRR::On200Response DohDecode %x\n", (int)rv
));
902 HandleDecodeError(rv
);
905 SaveAdditionalRecords(additionalRecords
);
907 if (mResult
.is
<TypeRecordHTTPSSVC
>()) {
908 auto& results
= mResult
.as
<TypeRecordHTTPSSVC
>();
909 for (const auto& rec
: results
) {
910 StoreIPHintAsDNSRecord(rec
);
914 if (!mDNS
.mAddresses
.IsEmpty() || mType
== TRRTYPE_TXT
|| mCname
.IsEmpty()) {
915 // pass back the response data
916 ReturnData(aChannel
);
920 LOG(("TRR::On200Response trying CNAME %s", mCname
.get()));
921 return FollowCname(aChannel
);
924 void TRR::RecordProcessingTime(nsIChannel
* aChannel
) {
925 // This method records the time it took from the last received byte of the
926 // DoH response until we've notified the consumer with a host record.
927 nsCOMPtr
<nsITimedChannel
> timedChan
= do_QueryInterface(aChannel
);
932 if (NS_FAILED(timedChan
->GetResponseEnd(&end
))) {
940 Telemetry::AccumulateTimeDelta(Telemetry::DNS_TRR_PROCESSING_TIME
, end
);
942 LOG(("Processing DoH response took %f ms",
943 (TimeStamp::Now() - end
).ToMilliseconds()));
946 void TRR::ReportStatus(nsresult aStatusCode
) {
947 // If the TRR was cancelled by nsHostResolver, then we don't need to report
948 // it as failed; otherwise it can cause the confirmation to fail.
949 if (UseDefaultServer() && aStatusCode
!= NS_ERROR_ABORT
) {
950 // Bad content is still considered "okay" if the HTTP response is okay
951 TRRService::Get()->RecordTRRStatus(this);
955 static void RecordHttpVersion(nsIHttpChannel
* aHttpChannel
) {
956 nsCOMPtr
<nsIHttpChannelInternal
> internalChannel
=
957 do_QueryInterface(aHttpChannel
);
958 if (!internalChannel
) {
959 LOG(("RecordHttpVersion: Failed to QI nsIHttpChannelInternal"));
963 uint32_t major
, minor
;
964 if (NS_FAILED(internalChannel
->GetResponseVersion(&major
, &minor
))) {
965 LOG(("RecordHttpVersion: Failed to get protocol version"));
969 auto label
= Telemetry::LABELS_DNS_TRR_HTTP_VERSION2::h_1
;
971 label
= Telemetry::LABELS_DNS_TRR_HTTP_VERSION2::h_2
;
972 } else if (major
== 3) {
973 label
= Telemetry::LABELS_DNS_TRR_HTTP_VERSION2::h_3
;
976 Telemetry::AccumulateCategoricalKeyed(TRRService::ProviderKey(), label
);
978 LOG(("RecordHttpVersion: Provider responded using HTTP version: %d", major
));
982 TRR::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatusCode
) {
983 // The dtor will be run after the function returns
984 LOG(("TRR:OnStopRequest %p %s %d failed=%d code=%X\n", this, mHost
.get(),
985 mType
, mFailed
, (unsigned int)aStatusCode
));
986 nsCOMPtr
<nsIChannel
> channel
;
987 channel
.swap(mChannel
);
989 mChannelStatus
= aStatusCode
;
992 // Cancel the timer since we don't need it anymore.
993 nsCOMPtr
<nsITimer
> timer
;
994 mTimeout
.swap(timer
);
1000 auto scopeExit
= MakeScopeExit([&] { ReportStatus(aStatusCode
); });
1002 nsresult rv
= NS_OK
;
1003 // if status was "fine", parse the response and pass on the answer
1004 if (!mFailed
&& NS_SUCCEEDED(aStatusCode
)) {
1005 nsCOMPtr
<nsIHttpChannel
> httpChannel
= do_QueryInterface(aRequest
);
1007 return NS_ERROR_UNEXPECTED
;
1009 nsAutoCString contentType
;
1010 httpChannel
->GetContentType(contentType
);
1011 if (contentType
.Length() &&
1012 !contentType
.LowerCaseEqualsASCII(ContentType())) {
1013 LOG(("TRR:OnStopRequest %p %s %d wrong content type %s\n", this,
1014 mHost
.get(), mType
, contentType
.get()));
1015 FailData(NS_ERROR_UNEXPECTED
);
1019 uint32_t httpStatus
;
1020 rv
= httpChannel
->GetResponseStatus(&httpStatus
);
1021 if (NS_SUCCEEDED(rv
) && httpStatus
== 200) {
1022 rv
= On200Response(channel
);
1023 if (NS_SUCCEEDED(rv
) && UseDefaultServer()) {
1024 RecordReason(TRRSkippedReason::TRR_OK
);
1025 RecordProcessingTime(channel
);
1026 RecordHttpVersion(httpChannel
);
1030 RecordReason(TRRSkippedReason::TRR_SERVER_RESPONSE_ERR
);
1031 LOG(("TRR:OnStopRequest:%d %p rv %x httpStatus %d\n", __LINE__
, this,
1032 (int)rv
, httpStatus
));
1036 LOG(("TRR:OnStopRequest %p status %x mFailed %d\n", this, (int)aStatusCode
,
1038 FailData(NS_SUCCEEDED(rv
) ? NS_ERROR_UNKNOWN_HOST
: rv
);
1043 TRR::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInputStream
,
1044 uint64_t aOffset
, const uint32_t aCount
) {
1045 LOG(("TRR:OnDataAvailable %p %s %d failed=%d aCount=%u\n", this, mHost
.get(),
1046 mType
, mFailed
, (unsigned int)aCount
));
1047 // receive DNS response into the local buffer
1049 return NS_ERROR_FAILURE
;
1052 nsresult rv
= GetOrCreateDNSPacket()->OnDataAvailable(aRequest
, aInputStream
,
1054 if (NS_FAILED(rv
)) {
1055 LOG(("TRR::OnDataAvailable:%d fail\n", __LINE__
));
1062 void TRR::Cancel(nsresult aStatus
) {
1063 bool isTRRServiceChannel
= false;
1064 nsCOMPtr
<nsIHttpChannelInternal
> httpChannelInternal(
1065 do_QueryInterface(mChannel
));
1066 if (httpChannelInternal
) {
1068 httpChannelInternal
->GetIsTRRServiceChannel(&isTRRServiceChannel
);
1069 if (NS_FAILED(rv
)) {
1070 isTRRServiceChannel
= false;
1073 // nsHttpChannel can be only canceled on the main thread.
1074 RefPtr
<nsHttpChannel
> httpChannel
= do_QueryObject(mChannel
);
1075 if (isTRRServiceChannel
&& !XRE_IsSocketProcess() && !httpChannel
) {
1076 if (TRRService::Get()) {
1077 nsCOMPtr
<nsIThread
> thread
= TRRService::Get()->TRRThread();
1078 if (thread
&& !thread
->IsOnCurrentThread()) {
1079 thread
->Dispatch(NS_NewRunnableFunction(
1081 [self
= RefPtr(this), aStatus
]() { self
->Cancel(aStatus
); }));
1086 if (!NS_IsMainThread()) {
1087 NS_DispatchToMainThread(NS_NewRunnableFunction(
1089 [self
= RefPtr(this), aStatus
]() { self
->Cancel(aStatus
); }));
1100 RecordReason(TRRSkippedReason::TRR_REQ_CANCELLED
);
1101 LOG(("TRR: %p canceling Channel %p %s %d status=%" PRIx32
"\n", this,
1102 mChannel
.get(), mHost
.get(), mType
, static_cast<uint32_t>(aStatus
)));
1103 mChannel
->Cancel(aStatus
);
1107 bool TRR::UseDefaultServer() { return !mRec
|| mRec
->mTrrServer
.IsEmpty(); }
1110 } // namespace mozilla