1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 #include "mozilla/DataMutex.h"
10 #include "nsHostResolver.h"
11 #include "nsIObserver.h"
13 #include "nsWeakReference.h"
14 #include "TRRServiceBase.h"
15 #include "nsICaptivePortalService.h"
16 #include "nsTHashSet.h"
21 class nsINetworkLinkService
;
22 class nsIObserverService
;
27 class TRRServiceChild
;
28 class TRRServiceParent
;
30 class TRRService
: public TRRServiceBase
,
32 public nsSupportsWeakReference
,
34 public SingleWriterLockOwner
{
36 NS_DECL_ISUPPORTS_INHERITED
38 NS_DECL_NSIPROXYCONFIGCHANGEDCALLBACK
41 static TRRService
* Get();
43 bool OnWritingThread() const override
{ return NS_IsMainThread(); }
47 bool Enabled(nsIRequest::TRRMode aRequestMode
= nsIRequest::TRR_DEFAULT_MODE
);
48 bool IsConfirmed() { return mConfirmation
.State() == CONFIRM_OK
; }
49 uint32_t ConfirmationState() { return mConfirmation
.State(); }
51 void GetURI(nsACString
& result
) override
;
52 nsresult
GetCredentials(nsCString
& result
);
53 uint32_t GetRequestTimeout();
54 void RetryTRRConfirm();
56 LookupStatus
CompleteLookup(nsHostRecord
*, nsresult
, mozilla::net::AddrInfo
*,
57 bool pb
, const nsACString
& aOriginSuffix
,
58 TRRSkippedReason aReason
,
59 TRR
* aTrrRequest
) override
;
60 LookupStatus
CompleteLookupByType(nsHostRecord
*, nsresult
,
61 mozilla::net::TypeRecordResultType
&,
62 TRRSkippedReason
, uint32_t,
64 void AddToBlocklist(const nsACString
& host
, const nsACString
& originSuffix
,
65 bool privateBrowsing
, bool aParentsToo
);
66 bool IsTemporarilyBlocked(const nsACString
& aHost
,
67 const nsACString
& aOriginSuffix
,
68 bool aPrivateBrowsing
, bool aParentsToo
);
69 bool IsExcludedFromTRR(const nsACString
& aHost
);
71 bool MaybeBootstrap(const nsACString
& possible
, nsACString
& result
);
72 void RecordTRRStatus(TRR
* aTrrRequest
);
73 bool ParentalControlEnabled() const { return mParentalControlEnabled
; }
75 nsresult
DispatchTRRRequest(TRR
* aTrrRequest
);
76 already_AddRefed
<nsIThread
> TRRThread();
79 bool IsUsingAutoDetectedURL() { return mURISetByDetection
; }
81 void SetHeuristicDetectionResult(TRRSkippedReason aValue
) {
82 mHeuristicDetectionValue
= aValue
;
84 TRRSkippedReason
GetHeuristicDetectionResult() {
85 return mHeuristicDetectionValue
;
88 nsresult
LastConfirmationStatus() {
89 return mConfirmation
.LastConfirmationStatus();
91 TRRSkippedReason
LastConfirmationSkipReason() {
92 return mConfirmation
.LastConfirmationSkipReason();
95 // Returns a reference to a static string identifying the current DoH server
96 // If the DoH server is not one of the built-in ones it will return "(other)"
97 static const nsCString
& ProviderKey();
98 static void SetProviderDomain(const nsACString
& aTRRDomain
);
99 // Only called when TRR mode changed.
100 static void SetCurrentTRRMode(nsIDNSService::ResolverMode aMode
);
102 void InitTRRConnectionInfo() override
;
104 void DontUseTRRThread() { mDontUseTRRThread
= true; }
107 virtual ~TRRService();
109 friend class TRRServiceChild
;
110 friend class TRRServiceParent
;
111 static void AddObserver(nsIObserver
* aObserver
,
112 nsIObserverService
* aObserverService
= nullptr);
113 static bool CheckCaptivePortalIsPassed();
114 static bool GetParentalControlEnabledInternal();
115 static bool CheckPlatformDNSStatus(nsINetworkLinkService
* aLinkService
);
117 nsresult
ReadPrefs(const char* name
);
118 void GetPrefBranch(nsIPrefBranch
** result
);
119 friend class ::nsDNSService
;
120 void SetDetectedTrrURI(const nsACString
& aURI
);
122 bool IsDomainBlocked(const nsACString
& aHost
, const nsACString
& aOriginSuffix
,
123 bool aPrivateBrowsing
);
124 bool IsExcludedFromTRR_unlocked(const nsACString
& aHost
);
126 void RebuildSuffixList(nsTArray
<nsCString
>&& aSuffixList
);
128 nsresult
DispatchTRRRequestInternal(TRR
* aTrrRequest
, bool aWithLock
);
129 already_AddRefed
<nsIThread
> TRRThread_locked();
130 already_AddRefed
<nsIThread
> MainThreadOrTRRThread(bool aWithLock
= true);
132 // This method will process the URI and try to set mPrivateURI to that value.
133 // Will return true if performed the change (if the value was different)
134 // or false if mPrivateURI already had that value.
135 bool MaybeSetPrivateURI(const nsACString
& aURI
) override
;
136 void ClearEntireCache();
138 virtual void ReadEtcHostsFile() override
;
139 void AddEtcHosts(const nsTArray
<nsCString
>&);
141 bool mInitialized
{false};
142 MutexSingleWriter mLock
;
144 nsCString mPrivateCred
; // main thread only
145 nsCString mConfirmationNS
MOZ_GUARDED_BY(mLock
){"example.com"_ns
};
146 nsCString mBootstrapAddr
MOZ_GUARDED_BY(mLock
);
148 Atomic
<bool, Relaxed
> mCaptiveIsPassed
{
149 false}; // set when captive portal check is passed
150 Atomic
<bool, Relaxed
> mShutdown
{false};
151 Atomic
<bool, Relaxed
> mDontUseTRRThread
{false};
153 // TRR Blocklist storage
154 // mTRRBLStorage is only modified on the main thread, but we query whether it
155 // is initialized or not off the main thread as well. Therefore we need to
156 // lock while creating it and while accessing it off the main thread.
157 DataMutex
<nsTHashMap
<nsCStringHashKey
, int32_t>> mTRRBLStorage
{
158 "DataMutex::TRRBlocklist"};
160 // A set of domains that we should not use TRR for.
161 nsTHashSet
<nsCString
> mExcludedDomains
MOZ_GUARDED_BY(mLock
);
162 nsTHashSet
<nsCString
> mDNSSuffixDomains
MOZ_GUARDED_BY(mLock
);
163 nsTHashSet
<nsCString
> mEtcHostsDomains
MOZ_GUARDED_BY(mLock
);
165 // The result of the TRR heuristic detection
166 TRRSkippedReason mHeuristicDetectionValue
= nsITRRSkipReason::TRR_UNSET
;
168 enum class ConfirmationEvent
{
175 CaptivePortalConnectivity
,
181 // (FailedLookups/RetryTRR/URIChange/NetworkUp)
182 // +---------------------------+
184 // | (Init) | +------v---------+ +-+--+
185 // | | TRR turned on | | (ConfirmOK) | |
186 // | OFF +---------------> TRY-OK +---------------> OK |
187 // | | (PrefChange) | | | |
188 // +-----^-----+ +^-^----+--------+ +-^--+
189 // | (PrefChange/CP) | | | |
190 // TRR + +------------------+ | | |
191 // off | | +----+ |(ConfirmFail) |(ConfirmOK)
193 // +---------+-+ | | |
194 // | | (CPConn) | +-------v--------+ +-+---------+
195 // | ANY-STATE | (NetworkUp)| | | timer | |
196 // | | (URIChange)+-+ FAIL +---------------> TRY-FAIL |
197 // +-----+-----+ | | (Confirmation | |
198 // | +------^---------+ Retry) +------+----+
199 // | (PrefChange) | |
200 // | TRR_ONLY mode or +--------------------------------+
201 // | confirmationNS = skip (ConfirmFail)
208 enum ConfirmationState
{
210 CONFIRM_TRYING_OK
= 1,
213 CONFIRM_TRYING_FAILED
= 4,
214 CONFIRM_DISABLED
= 5,
217 class ConfirmationContext final
: public nsITimerCallback
, public nsINamed
{
218 NS_DECL_ISUPPORTS_INHERITED
219 NS_DECL_NSITIMERCALLBACK
223 static const size_t RESULTS_SIZE
= 32;
226 nsCOMPtr
<nsITimer
> mTimer
;
227 uint32_t mRetryInterval
= 125; // milliseconds until retry
228 // The number of TRR requests that failed in a row.
229 Atomic
<uint32_t, Relaxed
> mTRRFailures
{0};
231 // This buffer holds consecutive TRR failures reported by calling
232 // RecordTRRStatus(). It is only meant for reporting event telemetry.
233 char mFailureReasons
[RESULTS_SIZE
] = {0};
235 // The number of confirmation retries.
236 uint32_t mAttemptCount
= 0;
238 // The results of past confirmation attempts.
239 // This is circular buffer ending at mAttemptCount.
240 char mResults
[RESULTS_SIZE
] = {0};
242 // Time when first confirmation started. Needed so we can
243 // record the time from start to confirmed.
244 TimeStamp mFirstRequestTime
;
245 // The network ID at the start of the last confirmation attempt
246 nsCString mNetworkId
;
247 // Captive portal status at the time of recording.
248 int32_t mCaptivePortalStatus
= nsICaptivePortalService::UNKNOWN
;
250 // The reason the confirmation context changed.
251 nsCString mContextChangeReason
;
253 // What triggered the confirmation
256 // String representation of consecutive failed lookups that triggered
258 nsCString mFailedLookups
;
260 Atomic
<TRRSkippedReason
, Relaxed
> mLastConfirmationSkipReason
{
261 nsITRRSkipReason::TRR_UNSET
};
262 Atomic
<nsresult
, Relaxed
> mLastConfirmationStatus
{NS_OK
};
264 void SetState(enum ConfirmationState aNewState
);
267 // Called when a confirmation completes successfully or when the
268 // confirmation context changes.
269 void RecordEvent(const char* aReason
, const MutexSingleWriterAutoLock
&);
271 // Called when a confirmation request is completed. The status is recorded
273 void RequestCompleted(nsresult aLookupStatus
, nsresult aChannelStatus
);
275 enum ConfirmationState
State() { return mState
; }
277 void CompleteConfirmation(nsresult aStatus
, TRR
* aTrrRequest
);
279 void RecordTRRStatus(TRR
* aTrrRequest
);
281 // Returns true when handling the event caused a new confirmation task to be
283 bool HandleEvent(ConfirmationEvent aEvent
);
284 bool HandleEvent(ConfirmationEvent aEvent
,
285 const MutexSingleWriterAutoLock
&);
287 void SetCaptivePortalStatus(int32_t aStatus
) {
288 mCaptivePortalStatus
= aStatus
;
291 TRRSkippedReason
LastConfirmationSkipReason() {
292 return mLastConfirmationSkipReason
;
294 nsresult
LastConfirmationStatus() { return mLastConfirmationStatus
; }
296 uintptr_t TaskAddr() { return uintptr_t(mTask
.get()); }
299 // Since the ConfirmationContext is embedded in the TRRService object
300 // we can easily get a pointer to the TRRService. ConfirmationContext
301 // delegates AddRef/Release calls to the owning object since they are
302 // guaranteed to have the same lifetime.
303 TRRService
* OwningObject() {
304 return reinterpret_cast<TRRService
*>(
305 reinterpret_cast<uint8_t*>(this) -
306 offsetof(TRRService
, mConfirmation
) -
307 offsetof(ConfirmationWrapper
, mConfirmation
));
310 Atomic
<enum ConfirmationState
, Relaxed
> mState
{CONFIRM_OFF
};
312 // TRRService needs to be a friend class because it needs to access the
314 friend class TRRService
;
315 ~ConfirmationContext() = default;
318 // Because TRRService needs to be a friend class to ConfirmationContext that
319 // means it can access member variables. In order to properly separate logic
320 // and prevent direct access to its member variables we embed it in a wrapper
322 class ConfirmationWrapper
{
324 // Called when a confirmation completes successfully or when the
325 // confirmation context changes.
326 void RecordEvent(const char* aReason
,
327 const MutexSingleWriterAutoLock
& aLock
) {
328 mConfirmation
.RecordEvent(aReason
, aLock
);
331 // Called when a confirmation request is completed. The status is recorded
333 void RequestCompleted(nsresult aLookupStatus
, nsresult aChannelStatus
) {
334 mConfirmation
.RequestCompleted(aLookupStatus
, aChannelStatus
);
337 enum ConfirmationState
State() { return mConfirmation
.State(); }
339 void CompleteConfirmation(nsresult aStatus
, TRR
* aTrrRequest
) {
340 mConfirmation
.CompleteConfirmation(aStatus
, aTrrRequest
);
343 void RecordTRRStatus(TRR
* aTrrRequest
) {
344 mConfirmation
.RecordTRRStatus(aTrrRequest
);
347 bool HandleEvent(ConfirmationEvent aEvent
) {
348 return mConfirmation
.HandleEvent(aEvent
);
351 bool HandleEvent(ConfirmationEvent aEvent
,
352 const MutexSingleWriterAutoLock
& lock
) {
353 return mConfirmation
.HandleEvent(aEvent
, lock
);
356 void SetCaptivePortalStatus(int32_t aStatus
) {
357 mConfirmation
.SetCaptivePortalStatus(aStatus
);
360 TRRSkippedReason
LastConfirmationSkipReason() {
361 return mConfirmation
.LastConfirmationSkipReason();
363 nsresult
LastConfirmationStatus() {
364 return mConfirmation
.LastConfirmationStatus();
368 friend TRRService
* ConfirmationContext::OwningObject();
369 ConfirmationContext mConfirmation
;
372 ConfirmationWrapper mConfirmation
;
374 bool mParentalControlEnabled
{false};
375 // This is used to track whether a confirmation was triggered by a URI change,
376 // so we don't trigger another one just because other prefs have changed.
377 bool mConfirmationTriggered
{false};
378 nsCOMPtr
<nsINetworkLinkService
> mLinkService
;
382 } // namespace mozilla
384 #endif // TRRService_h_