Bug 1866777 - Disable test_race_cache_with_network.js on windows opt for frequent...
[gecko.git] / netwerk / dns / TRRService.h
blob3283a8ea06aabfc2c9830d43a00e76c3b3b3abbf
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/. */
6 #ifndef TRRService_h_
7 #define TRRService_h_
9 #include "mozilla/DataMutex.h"
10 #include "nsHostResolver.h"
11 #include "nsIObserver.h"
12 #include "nsITimer.h"
13 #include "nsWeakReference.h"
14 #include "TRRServiceBase.h"
15 #include "nsICaptivePortalService.h"
16 #include "nsTHashSet.h"
17 #include "TRR.h"
19 class nsDNSService;
20 class nsIPrefBranch;
21 class nsINetworkLinkService;
22 class nsIObserverService;
24 namespace mozilla {
25 namespace net {
27 class TRRServiceChild;
28 class TRRServiceParent;
30 class TRRService : public TRRServiceBase,
31 public nsIObserver,
32 public nsSupportsWeakReference,
33 public AHostResolver,
34 public SingleWriterLockOwner {
35 public:
36 NS_DECL_ISUPPORTS_INHERITED
37 NS_DECL_NSIOBSERVER
38 NS_DECL_NSIPROXYCONFIGCHANGEDCALLBACK
40 TRRService();
41 static TRRService* Get();
43 bool OnWritingThread() const override { return NS_IsMainThread(); }
45 nsresult Init();
46 nsresult Start();
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,
63 bool pb) override;
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();
77 bool IsOnTRRThread();
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; }
106 private:
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 {
169 Init,
170 PrefChange,
171 ConfirmationRetry,
172 FailedLookups,
173 RetryTRR,
174 URIChange,
175 CaptivePortalConnectivity,
176 NetworkUp,
177 ConfirmOK,
178 ConfirmFail,
181 // (FailedLookups/RetryTRR/URIChange/NetworkUp)
182 // +---------------------------+
183 // +-----------+ | |
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)
192 // (Pref)| | | | |
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)
202 // +-----v-----+
203 // | |
204 // | DISABLED |
205 // | |
206 // +-----------+
208 enum ConfirmationState {
209 CONFIRM_OFF = 0,
210 CONFIRM_TRYING_OK = 1,
211 CONFIRM_OK = 2,
212 CONFIRM_FAILED = 3,
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
220 NS_DECL_NSINAMED
222 private:
223 static const size_t RESULTS_SIZE = 32;
225 RefPtr<TRR> mTask;
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
254 nsCString mTrigger;
256 // String representation of consecutive failed lookups that triggered
257 // confirmation.
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);
266 public:
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
272 // in the results.
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
282 // dispatched.
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()); }
298 private:
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
313 // destructor.
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
321 // class.
322 class ConfirmationWrapper {
323 public:
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
332 // in the results.
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();
367 private:
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;
381 } // namespace net
382 } // namespace mozilla
384 #endif // TRRService_h_