diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 01:14:29 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 01:14:29 +0000 |
commit | fbaf0bb26397aa498eb9156f06d5a6fe34dd7dd8 (patch) | |
tree | 4c1ccaf5486d4f2009f9a338a98a83e886e29c97 /netwerk | |
parent | Releasing progress-linux version 124.0.1-1~progress7.99u1. (diff) | |
download | firefox-fbaf0bb26397aa498eb9156f06d5a6fe34dd7dd8.tar.xz firefox-fbaf0bb26397aa498eb9156f06d5a6fe34dd7dd8.zip |
Merging upstream version 125.0.1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'netwerk')
375 files changed, 2961 insertions, 1826 deletions
diff --git a/netwerk/base/ContentRange.cpp b/netwerk/base/ContentRange.cpp new file mode 100644 index 0000000000..dfae132550 --- /dev/null +++ b/netwerk/base/ContentRange.cpp @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* 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 "ContentRange.h" +#include "nsContentUtils.h" + +mozilla::net::ContentRange::ContentRange(const nsACString& aRangeHeader, + uint64_t aSize) + : mStart(0), mEnd(0), mSize(0) { + auto parsed = nsContentUtils::ParseSingleRangeRequest(aRangeHeader, true); + // https://fetch.spec.whatwg.org/#ref-for-simple-range-header-value%E2%91%A1 + // If rangeValue is failure, then return a network error. + if (!parsed) { + return; + } + + // Sanity check: ParseSingleRangeRequest should handle these two cases. + // If rangeEndValue and rangeStartValue are null, then return failure. + MOZ_ASSERT(parsed->Start().isSome() || parsed->End().isSome()); + // If rangeStartValue and rangeEndValue are numbers, and rangeStartValue + // is greater than rangeEndValue, then return failure. + MOZ_ASSERT(parsed->Start().isNothing() || parsed->End().isNothing() || + *parsed->Start() <= *parsed->End()); + + // https://fetch.spec.whatwg.org/#ref-for-simple-range-header-value%E2%91%A1 + // If rangeStart is null: + if (parsed->Start().isNothing()) { + // Set rangeStart to fullLength − rangeEnd. + mStart = aSize - *parsed->End(); + + // Set rangeEnd to rangeStart + rangeEnd − 1. + mEnd = mStart + *parsed->End() - 1; + + // Otherwise: + } else { + // If rangeStart is greater than or equal to fullLength, then return a + // network error. + if (*parsed->Start() >= aSize) { + return; + } + mStart = *parsed->Start(); + + // If rangeEnd is null or rangeEnd is greater than or equal to fullLength, + // then set rangeEnd to fullLength − 1. + if (parsed->End().isNothing() || *parsed->End() >= aSize) { + mEnd = aSize - 1; + } else { + mEnd = *parsed->End(); + } + } + mSize = aSize; +} + +void mozilla::net::ContentRange::AsHeader(nsACString& aOutString) const { + aOutString.Assign("bytes "_ns); + aOutString.AppendInt(mStart); + aOutString.AppendLiteral("-"); + aOutString.AppendInt(mEnd); + aOutString.AppendLiteral("/"); + aOutString.AppendInt(mSize); +} diff --git a/netwerk/base/ContentRange.h b/netwerk/base/ContentRange.h new file mode 100644 index 0000000000..36b15214eb --- /dev/null +++ b/netwerk/base/ContentRange.h @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set et cin ts=4 sw=2 sts=2: */ +/* 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/. */ + +#ifndef ContentRange_h__ +#define ContentRange_h__ + +#include "mozilla/Maybe.h" +#include "nsString.h" +#include "nsISupportsImpl.h" + +// nsIBaseChannel subclasses may support range headers when accessed via +// Fetch or XMLHTTPRequest, even if they are not HTTP assets and so do not +// normally have access to headers (such as the blob URLs). The ContentRange +// class helps to encapsulate much of the common logic involved in parsing, +// storing, validating, and writing out Content-Range headers. + +namespace mozilla::net { + +class ContentRange { + private: + ~ContentRange() = default; + + uint64_t mStart{0}; + uint64_t mEnd{0}; + uint64_t mSize{0}; + + public: + uint64_t Start() const { return mStart; } + uint64_t End() const { return mEnd; } + uint64_t Size() const { return mSize; } + bool IsValid() const { return mStart < mSize; } + ContentRange(uint64_t aStart, uint64_t aEnd, uint64_t aSize) + : mStart(aStart), mEnd(aEnd), mSize(aSize) {} + ContentRange(const nsACString& aRangeHeader, uint64_t aSize); + void AsHeader(nsACString& aOutString) const; + + NS_INLINE_DECL_REFCOUNTING(ContentRange) +}; + +} // namespace mozilla::net + +#endif // ContentRange_h__ diff --git a/netwerk/base/NetUtil.sys.mjs b/netwerk/base/NetUtil.sys.mjs index 679c9979a7..c952fdeb33 100644 --- a/netwerk/base/NetUtil.sys.mjs +++ b/netwerk/base/NetUtil.sys.mjs @@ -66,7 +66,7 @@ export var NetUtil = { var observer; if (aCallback) { observer = { - onStartRequest(aRequest) {}, + onStartRequest() {}, onStopRequest(aRequest, aStatusCode) { aCallback(aStatusCode); }, @@ -118,7 +118,7 @@ export var NetUtil = { "@mozilla.org/network/simple-stream-listener;1" ].createInstance(Ci.nsISimpleStreamListener); listener.init(pipe.outputStream, { - onStartRequest(aRequest) {}, + onStartRequest() {}, onStopRequest(aRequest, aStatusCode) { pipe.outputStream.close(); aCallback(pipe.inputStream, aStatusCode, aRequest); diff --git a/netwerk/base/Predictor.cpp b/netwerk/base/Predictor.cpp index de19d0e06e..0c604d9d9a 100644 --- a/netwerk/base/Predictor.cpp +++ b/netwerk/base/Predictor.cpp @@ -487,7 +487,9 @@ Predictor::PredictNative(nsIURI* targetURI, nsIURI* sourceURI, PREDICTOR_LOG(("Predictor::Predict")); if (IsNeckoChild()) { - MOZ_DIAGNOSTIC_ASSERT(gNeckoChild); + if (!gNeckoChild) { + return NS_ERROR_FAILURE; + } PREDICTOR_LOG((" called on child process")); // If two different threads are predicting concurently, this will be @@ -1237,7 +1239,9 @@ Predictor::LearnNative(nsIURI* targetURI, nsIURI* sourceURI, PREDICTOR_LOG(("Predictor::Learn")); if (IsNeckoChild()) { - MOZ_DIAGNOSTIC_ASSERT(gNeckoChild); + if (!gNeckoChild) { + return NS_ERROR_FAILURE; + } PREDICTOR_LOG((" called on child process")); @@ -1715,7 +1719,9 @@ Predictor::Reset() { PREDICTOR_LOG(("Predictor::Reset")); if (IsNeckoChild()) { - MOZ_DIAGNOSTIC_ASSERT(gNeckoChild); + if (!gNeckoChild) { + return NS_ERROR_FAILURE; + } PREDICTOR_LOG((" forwarding to parent process")); gNeckoChild->SendPredReset(); diff --git a/netwerk/base/moz.build b/netwerk/base/moz.build index e069a5f296..adeac62cd8 100644 --- a/netwerk/base/moz.build +++ b/netwerk/base/moz.build @@ -18,6 +18,7 @@ XPIDL_SOURCES += [ "nsIAuthPromptCallback.idl", "nsIAuthPromptProvider.idl", "nsIBackgroundFileSaver.idl", + "nsIBaseChannel.idl", "nsIBufferedStreams.idl", "nsIByteRangeRequest.idl", "nsICacheInfoChannel.idl", @@ -157,6 +158,7 @@ EXPORTS.mozilla += [ EXPORTS.mozilla.net += [ "CacheInfoIPCTypes.h", "CaptivePortalService.h", + "ContentRange.h", "Dashboard.h", "DashboardTypes.h", "DefaultURI.h", @@ -178,6 +180,7 @@ UNIFIED_SOURCES += [ "ArrayBufferInputStream.cpp", "BackgroundFileSaver.cpp", "CaptivePortalService.cpp", + "ContentRange.cpp", "Dashboard.cpp", "DefaultURI.cpp", "EventTokenBucket.cpp", diff --git a/netwerk/base/nsBaseChannel.cpp b/netwerk/base/nsBaseChannel.cpp index df8aa23db4..2671b5886a 100644 --- a/netwerk/base/nsBaseChannel.cpp +++ b/netwerk/base/nsBaseChannel.cpp @@ -8,7 +8,6 @@ #include "nsContentUtils.h" #include "nsURLHelper.h" #include "nsNetCID.h" -#include "nsMimeTypes.h" #include "nsUnknownDecoder.h" #include "nsIScriptSecurityManager.h" #include "nsMimeTypes.h" @@ -302,6 +301,7 @@ NS_IMPL_RELEASE(nsBaseChannel) NS_INTERFACE_MAP_BEGIN(nsBaseChannel) NS_INTERFACE_MAP_ENTRY(nsIRequest) NS_INTERFACE_MAP_ENTRY(nsIChannel) + NS_INTERFACE_MAP_ENTRY(nsIBaseChannel) NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableRequest) NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor) NS_INTERFACE_MAP_ENTRY(nsITransportEventSink) @@ -967,58 +967,28 @@ void nsBaseChannel::SetupNeckoTarget() { mNeckoTarget = GetMainThreadSerialEventTarget(); } -nsBaseChannel::ContentRange::ContentRange(const nsACString& aRangeHeader, - uint64_t aSize) - : mStart(0), mEnd(0), mSize(0) { - auto parsed = nsContentUtils::ParseSingleRangeRequest(aRangeHeader, true); - // https://fetch.spec.whatwg.org/#ref-for-simple-range-header-value%E2%91%A1 - // If rangeValue is failure, then return a network error. - if (!parsed) { - return; +NS_IMETHODIMP nsBaseChannel::GetContentRange( + RefPtr<mozilla::net::ContentRange>* aRange) { + if (aRange) { + *aRange = mContentRange; } + return NS_OK; +} - // Sanity check: ParseSingleRangeRequest should handle these two cases. - // If rangeEndValue and rangeStartValue are null, then return failure. - MOZ_ASSERT(parsed->Start().isSome() || parsed->End().isSome()); - // If rangeStartValue and rangeEndValue are numbers, and rangeStartValue - // is greater than rangeEndValue, then return failure. - MOZ_ASSERT(parsed->Start().isNothing() || parsed->End().isNothing() || - *parsed->Start() <= *parsed->End()); - - // https://fetch.spec.whatwg.org/#ref-for-simple-range-header-value%E2%91%A1 - // If rangeStart is null: - if (parsed->Start().isNothing()) { - // Set rangeStart to fullLength − rangeEnd. - mStart = aSize - *parsed->End(); - - // Set rangeEnd to rangeStart + rangeEnd − 1. - mEnd = mStart + *parsed->End() - 1; - - // Otherwise: - } else { - // If rangeStart is greater than or equal to fullLength, then return a - // network error. - if (*parsed->Start() >= aSize) { - return; - } - mStart = *parsed->Start(); +NS_IMETHODIMP nsBaseChannel::SetContentRange( + RefPtr<mozilla::net::ContentRange> aRange) { + mContentRange = aRange; + return NS_OK; +} - // If rangeEnd is null or rangeEnd is greater than or equal to fullLength, - // then set rangeEnd to fullLength − 1. - if (parsed->End().isNothing() || *parsed->End() >= aSize) { - mEnd = aSize - 1; - } else { - mEnd = *parsed->End(); - } +NS_IMETHODIMP nsBaseChannel::GetFullMimeType(RefPtr<TMimeType<char>>* aOut) { + if (aOut) { + *aOut = mFullMimeType; } - mSize = aSize; + return NS_OK; } -void nsBaseChannel::ContentRange::AsHeader(nsACString& aOutString) const { - aOutString.Assign("bytes "_ns); - aOutString.AppendInt(mStart); - aOutString.AppendLiteral("-"); - aOutString.AppendInt(mEnd); - aOutString.AppendLiteral("/"); - aOutString.AppendInt(mSize); +NS_IMETHODIMP nsBaseChannel::SetFullMimeType(RefPtr<TMimeType<char>> aType) { + mFullMimeType = aType; + return NS_OK; } diff --git a/netwerk/base/nsBaseChannel.h b/netwerk/base/nsBaseChannel.h index 179a24bf45..c0db8e2500 100644 --- a/netwerk/base/nsBaseChannel.h +++ b/netwerk/base/nsBaseChannel.h @@ -6,13 +6,16 @@ #ifndef nsBaseChannel_h__ #define nsBaseChannel_h__ +#include "mozilla/dom/MimeType.h" #include "mozilla/Maybe.h" #include "mozilla/MozPromise.h" #include "mozilla/UniquePtr.h" +#include "mozilla/net/ContentRange.h" #include "mozilla/net/NeckoTargetHolder.h" #include "mozilla/net/PrivateBrowsingChannel.h" #include "nsHashPropertyBag.h" #include "nsIAsyncVerifyRedirectCallback.h" +#include "nsIBaseChannel.h" #include "nsIChannel.h" #include "nsIInterfaceRequestor.h" #include "nsILoadGroup.h" @@ -46,6 +49,7 @@ class nsICancelable; class nsBaseChannel : public nsHashPropertyBag, + public nsIBaseChannel, public nsIChannel, public nsIThreadRetargetableRequest, public nsIInterfaceRequestor, @@ -58,6 +62,7 @@ class nsBaseChannel NS_DECL_ISUPPORTS_INHERITED NS_DECL_NSIREQUEST NS_DECL_NSICHANNEL + NS_DECL_NSIBASECHANNEL NS_DECL_NSIINTERFACEREQUESTOR NS_DECL_NSITRANSPORTEVENTSINK NS_DECL_NSIASYNCVERIFYREDIRECTCALLBACK @@ -197,44 +202,6 @@ class nsBaseChannel return mPumpingData || mWaitingOnAsyncRedirect; } - // Blob requests may specify a range header. We must parse, validate, and - // store that info in a place where BlobURLInputStream::StoreBlobImplStream - // can access it. This class helps to encapsulate that logic. - class ContentRange { - private: - uint64_t mStart; - uint64_t mEnd; - uint64_t mSize; - - public: - uint64_t Start() const { return mStart; } - uint64_t End() const { return mEnd; } - uint64_t Size() const { return mSize; } - bool IsValid() const { return mStart < mSize; } - ContentRange() : mStart(0), mEnd(0), mSize(0) {} - ContentRange(uint64_t aStart, uint64_t aEnd, uint64_t aSize) - : mStart(aStart), mEnd(aEnd), mSize(aSize) {} - ContentRange(const nsACString& aRangeHeader, uint64_t aSize); - void AsHeader(nsACString& aOutString) const; - }; - - const mozilla::Maybe<ContentRange>& GetContentRange() const { - return mContentRange; - } - - void SetContentRange(uint64_t aStart, uint64_t aEnd, uint64_t aSize) { - mContentRange.emplace(ContentRange(aStart, aEnd, aSize)); - } - - bool SetContentRange(const nsACString& aRangeHeader, uint64_t aSize) { - auto range = ContentRange(aRangeHeader, aSize); - if (!range.IsValid()) { - return false; - } - mContentRange.emplace(range); - return true; - } - // Helper function for querying the channel's notification callbacks. template <class T> void GetCallback(nsCOMPtr<T>& result) { @@ -325,7 +292,8 @@ class nsBaseChannel bool mWaitingOnAsyncRedirect{false}; bool mOpenRedirectChannel{false}; uint32_t mRedirectFlags{0}; - mozilla::Maybe<ContentRange> mContentRange; + RefPtr<mozilla::net::ContentRange> mContentRange; + RefPtr<CMimeType> mFullMimeType; protected: nsCString mContentType; diff --git a/netwerk/base/nsIBaseChannel.idl b/netwerk/base/nsIBaseChannel.idl new file mode 100644 index 0000000000..5f2fe1517d --- /dev/null +++ b/netwerk/base/nsIBaseChannel.idl @@ -0,0 +1,63 @@ +/* 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 "nsISupports.idl" + +%{C++ +#include "mozilla/dom/MimeType.h" +#include "mozilla/net/ContentRange.h" +%} + +/** + * The nsIBaseChannel interface allows C++ code to query the interface + * of channels safely to gain access to content range functionality. + * This allows subclasses to optionally handle range-requests on their + * types using fetch/XMLHttpRequest even if they are not accessed via + * HTTP and therefore normally do not have support for headers. + */ + +native ContentRangeRef(RefPtr<mozilla::net::ContentRange>); +native MimeTypeRef(RefPtr<TMimeType<char>>); + +[uuid(036d5cd7-9a53-40e3-9c72-c2ffaa15aa2b)] +interface nsIBaseChannel : nsISupports { + + /** + * Used by fetch and XMLHttpRequest to get only the range specified in the + * Range request header (if given) for the response body (e.g, for blob URLs) + */ + attribute ContentRangeRef contentRange; + + /** + * Used by fetch and XMLHttpRequest to get the standards-compliant value they + * should set for the Content-Type header on response (if nullptr, they will + * use Firefox-specific values from nsIChannel::GetContentType and GetCharset). + */ + attribute MimeTypeRef fullMimeType; + +%{C++ + RefPtr<mozilla::net::ContentRange> ContentRange() { + RefPtr<mozilla::net::ContentRange> range; + mozilla::Unused << GetContentRange(&range); + return range; + } + + bool SetContentRangeFromHeader(const nsACString& aHeader, uint64_t aSize) { + RefPtr<mozilla::net::ContentRange> range = + new mozilla::net::ContentRange(aHeader, aSize); + if (!range->IsValid()) { + return false; + } + SetContentRange(range); + return true; + } + + RefPtr<CMimeType> FullMimeType() { + RefPtr<CMimeType> type; + mozilla::Unused << GetFullMimeType(&type); + return type; + } +%} + +}; diff --git a/netwerk/base/nsISecureBrowserUI.idl b/netwerk/base/nsISecureBrowserUI.idl index 3984310d93..6197a9adff 100644 --- a/netwerk/base/nsISecureBrowserUI.idl +++ b/netwerk/base/nsISecureBrowserUI.idl @@ -15,7 +15,3 @@ interface nsISecureBrowserUI : nsISupports readonly attribute bool isSecureContext; readonly attribute nsITransportSecurityInfo secInfo; }; - -%{C++ -#define NS_SECURE_BROWSER_UI_CONTRACTID "@mozilla.org/secure_browser_ui;1" -%} diff --git a/netwerk/base/nsISystemProxySettings.idl b/netwerk/base/nsISystemProxySettings.idl index 9cd561fb64..935da146af 100644 --- a/netwerk/base/nsISystemProxySettings.idl +++ b/netwerk/base/nsISystemProxySettings.idl @@ -39,4 +39,9 @@ interface nsISystemProxySettings : nsISupports in AUTF8String testScheme, in AUTF8String testHost, in int32_t testPort); + + /** + * Check if system settings are configured to use WPAD + */ + readonly attribute bool systemWPADSetting; }; diff --git a/netwerk/base/nsIURLParser.idl b/netwerk/base/nsIURLParser.idl index 3d6ac19b8c..209c04d888 100644 --- a/netwerk/base/nsIURLParser.idl +++ b/netwerk/base/nsIURLParser.idl @@ -90,9 +90,3 @@ interface nsIURLParser : nsISupports out unsigned long basenamePos, out long basenameLen, out unsigned long extensionPos, out long extensionLen); }; - -%{C++ -// url parser key for use with the category manager -// mapping from scheme to url parser. -#define NS_IURLPARSER_KEY "@mozilla.org/urlparser;1" -%} diff --git a/netwerk/base/nsLoadGroup.cpp b/netwerk/base/nsLoadGroup.cpp index 3e2445b6ae..0122e13ad2 100644 --- a/netwerk/base/nsLoadGroup.cpp +++ b/netwerk/base/nsLoadGroup.cpp @@ -1021,12 +1021,6 @@ void nsLoadGroup::TelemetryReportChannel(nsITimedChannel* aTimedChannel, if (httpChannel && NS_SUCCEEDED(httpChannel->GetHasHTTPSRR(&hasHTTPSRR)) && cacheReadStart.IsNull() && cacheReadEnd.IsNull() && !requestStart.IsNull()) { - nsCString key = (hasHTTPSRR) ? ((aDefaultRequest) ? "uses_https_rr_page"_ns - : "uses_https_rr_sub"_ns) - : ((aDefaultRequest) ? "no_https_rr_page"_ns - : "no_https_rr_sub"_ns); - Telemetry::AccumulateTimeDelta(Telemetry::HTTPS_RR_OPEN_TO_FIRST_SENT, key, - asyncOpen, requestStart); TimeDuration elapsed = requestStart - asyncOpen; if (hasHTTPSRR) { if (aDefaultRequest) { diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp index 4c03cf63c3..ac86d8fa32 100644 --- a/netwerk/base/nsNetUtil.cpp +++ b/netwerk/base/nsNetUtil.cpp @@ -96,7 +96,9 @@ #include "nsSocketTransportService2.h" #include "nsViewSourceHandler.h" #include "nsJARURI.h" -#include "nsIconURI.h" +#ifndef XP_IOS +# include "nsIconURI.h" +#endif #include "nsAboutProtocolHandler.h" #include "nsResProtocolHandler.h" #include "mozilla/net/ExtensionProtocolHandler.h" @@ -1951,11 +1953,13 @@ nsresult NS_NewURI(nsIURI** aURI, const nsACString& aSpec, .Finalize(aURI); } +#ifndef XP_IOS if (scheme.EqualsLiteral("moz-icon")) { return NS_MutateURI(new nsMozIconURI::Mutator()) .SetSpec(aSpec) .Finalize(aURI); } +#endif #ifdef MOZ_WIDGET_GTK if (scheme.EqualsLiteral("smb") || scheme.EqualsLiteral("sftp")) { diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 0cf66c8ee6..d4c6c4bd79 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -502,6 +502,13 @@ nsresult nsPACMan::PostQuery(PendingPACQuery* query) { return NS_OK; } +// check if proxy settings are configured for WPAD +bool IsProxyConfigValidForWPAD(int proxyConfigType, bool wpadSystemSettings) { + return proxyConfigType == nsIProtocolProxyService::PROXYCONFIG_WPAD || + (proxyConfigType == nsIProtocolProxyService::PROXYCONFIG_SYSTEM && + wpadSystemSettings); +} + nsresult nsPACMan::LoadPACFromURI(const nsACString& aSpec) { return LoadPACFromURI(aSpec, true); } @@ -541,7 +548,7 @@ nsresult nsPACMan::LoadPACFromURI(const nsACString& aSpec, if (NS_FAILED(rv)) { return rv; } - if (mProxyConfigType != nsIProtocolProxyService::PROXYCONFIG_WPAD) { + if (!IsProxyConfigValidForWPAD(mProxyConfigType, mAutoDetect)) { LOG( ("LoadPACFromURI - Aborting WPAD autodetection because the pref " "doesn't match anymore")); @@ -595,7 +602,7 @@ nsresult nsPACMan::GetPACFromDHCP(nsACString& aSpec) { nsresult nsPACMan::ConfigureWPAD(nsACString& aSpec) { MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); - if (mProxyConfigType != nsIProtocolProxyService::PROXYCONFIG_WPAD) { + if (!IsProxyConfigValidForWPAD(mProxyConfigType, mAutoDetect)) { LOG( ("ConfigureWPAD - Aborting WPAD autodetection because the pref " "doesn't match anymore")); diff --git a/netwerk/base/nsProtocolProxyService.cpp b/netwerk/base/nsProtocolProxyService.cpp index 9f721f94e8..7ccfc9363a 100644 --- a/netwerk/base/nsProtocolProxyService.cpp +++ b/netwerk/base/nsProtocolProxyService.cpp @@ -621,28 +621,29 @@ nsAsyncResolveRequest::AsyncApplyFilters::Cancel(nsresult reason) { return NS_OK; } -// Bug 1366133: make GetPACURI off-main-thread since it may hang on Windows -// platform -class AsyncGetPACURIRequest final : public nsIRunnable { +// Bug 1366133: make GetPACURI and GetSystemWPADSetting off-main-thread since it +// may hang on Windows platform +class AsyncGetPACURIRequestOrSystemWPADSetting final : public nsIRunnable { public: NS_DECL_THREADSAFE_ISUPPORTS using CallbackFunc = nsresult (nsProtocolProxyService::*)(bool, bool, nsresult, - const nsACString&); + const nsACString&, + bool); - AsyncGetPACURIRequest(nsProtocolProxyService* aService, - CallbackFunc aCallback, - nsISystemProxySettings* aSystemProxySettings, - bool aMainThreadOnly, bool aForceReload, - bool aResetPACThread) + AsyncGetPACURIRequestOrSystemWPADSetting( + nsProtocolProxyService* aService, CallbackFunc aCallback, + nsISystemProxySettings* aSystemProxySettings, bool aMainThreadOnly, + bool aForceReload, bool aResetPACThread, bool aSystemWPADAllowed) : mIsMainThreadOnly(aMainThreadOnly), mService(aService), mServiceHolder(do_QueryObject(aService)), mCallback(aCallback), mSystemProxySettings(aSystemProxySettings), mForceReload(aForceReload), - mResetPACThread(aResetPACThread) { + mResetPACThread(aResetPACThread), + mSystemWPADAllowed(aSystemWPADAllowed) { MOZ_ASSERT(NS_IsMainThread()); Unused << mIsMainThreadOnly; } @@ -650,21 +651,30 @@ class AsyncGetPACURIRequest final : public nsIRunnable { NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread() == mIsMainThreadOnly); + nsresult rv; nsCString pacUri; - nsresult rv = mSystemProxySettings->GetPACURI(pacUri); + bool systemWPADSetting = false; + if (mSystemWPADAllowed) { + mSystemProxySettings->GetSystemWPADSetting(&systemWPADSetting); + } + + rv = mSystemProxySettings->GetPACURI(pacUri); nsCOMPtr<nsIRunnable> event = - NewNonOwningCancelableRunnableMethod<bool, bool, nsresult, nsCString>( - "AsyncGetPACURIRequestCallback", mService, mCallback, mForceReload, - mResetPACThread, rv, pacUri); + NewNonOwningCancelableRunnableMethod<bool, bool, nsresult, nsCString, + bool>( + "AsyncGetPACURIRequestOrSystemWPADSettingCallback", mService, + mCallback, mForceReload, mResetPACThread, rv, pacUri, + systemWPADSetting); return NS_DispatchToMainThread(event); } private: - ~AsyncGetPACURIRequest() { - NS_ReleaseOnMainThread("AsyncGetPACURIRequest::mServiceHolder", - mServiceHolder.forget()); + ~AsyncGetPACURIRequestOrSystemWPADSetting() { + NS_ReleaseOnMainThread( + "AsyncGetPACURIRequestOrSystemWPADSetting::mServiceHolder", + mServiceHolder.forget()); } bool mIsMainThreadOnly; @@ -676,9 +686,10 @@ class AsyncGetPACURIRequest final : public nsIRunnable { bool mForceReload; bool mResetPACThread; + bool mSystemWPADAllowed; }; -NS_IMPL_ISUPPORTS(AsyncGetPACURIRequest, nsIRunnable) +NS_IMPL_ISUPPORTS(AsyncGetPACURIRequestOrSystemWPADSetting, nsIRunnable) //---------------------------------------------------------------------------- @@ -847,8 +858,8 @@ nsresult nsProtocolProxyService::ReloadNetworkPAC() { return NS_OK; } -nsresult nsProtocolProxyService::AsyncConfigureFromPAC(bool aForceReload, - bool aResetPACThread) { +nsresult nsProtocolProxyService::AsyncConfigureWPADOrFromPAC( + bool aForceReload, bool aResetPACThread, bool aSystemWPADAllowed) { MOZ_ASSERT(NS_IsMainThread()); bool mainThreadOnly; @@ -857,9 +868,10 @@ nsresult nsProtocolProxyService::AsyncConfigureFromPAC(bool aForceReload, return rv; } - nsCOMPtr<nsIRunnable> req = new AsyncGetPACURIRequest( - this, &nsProtocolProxyService::OnAsyncGetPACURI, mSystemProxySettings, - mainThreadOnly, aForceReload, aResetPACThread); + nsCOMPtr<nsIRunnable> req = new AsyncGetPACURIRequestOrSystemWPADSetting( + this, &nsProtocolProxyService::OnAsyncGetPACURIOrSystemWPADSetting, + mSystemProxySettings, mainThreadOnly, aForceReload, aResetPACThread, + aSystemWPADAllowed); if (mainThreadOnly) { return req->Run(); @@ -869,17 +881,24 @@ nsresult nsProtocolProxyService::AsyncConfigureFromPAC(bool aForceReload, nsIEventTarget::DISPATCH_NORMAL); } -nsresult nsProtocolProxyService::OnAsyncGetPACURI(bool aForceReload, - bool aResetPACThread, - nsresult aResult, - const nsACString& aUri) { +nsresult nsProtocolProxyService::OnAsyncGetPACURIOrSystemWPADSetting( + bool aForceReload, bool aResetPACThread, nsresult aResult, + const nsACString& aUri, bool aSystemWPADSetting) { MOZ_ASSERT(NS_IsMainThread()); if (aResetPACThread) { ResetPACThread(); } - if (NS_SUCCEEDED(aResult) && !aUri.IsEmpty()) { + if (aSystemWPADSetting) { + if (mSystemProxySettings || !mPACMan) { + mSystemProxySettings = nullptr; + ResetPACThread(); + } + + nsAutoCString tempString; + ConfigureFromPAC(EmptyCString(), false); + } else if (NS_SUCCEEDED(aResult) && !aUri.IsEmpty()) { ConfigureFromPAC(PromiseFlatCString(aUri), aForceReload); } @@ -960,7 +979,8 @@ void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch, auto invokeCallback = MakeScopeExit([&] { NotifyProxyConfigChangedInternal(); }); - if (!pref || !strcmp(pref, PROXY_PREF("type"))) { + if (!pref || !strcmp(pref, PROXY_PREF("type")) || + !strcmp(pref, PROXY_PREF("system_wpad"))) { int32_t type = -1; rv = prefBranch->GetIntPref(PROXY_PREF("type"), &type); if (NS_SUCCEEDED(rv)) { @@ -1076,9 +1096,12 @@ void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch, } else if (mProxyConfig == PROXYCONFIG_WPAD) { LOG(("Auto-detecting proxy - Reset Pac Thread")); ResetPACThread(); + } else if (mSystemProxySettings && mProxyConfig == PROXYCONFIG_SYSTEM && + StaticPrefs::network_proxy_system_wpad()) { + AsyncConfigureWPADOrFromPAC(false, false, true); } else if (mSystemProxySettings) { // Get System Proxy settings if available - AsyncConfigureFromPAC(false, false); + AsyncConfigureWPADOrFromPAC(false, false, false); } if (!tempString.IsEmpty() || mProxyConfig == PROXYCONFIG_WPAD) { ConfigureFromPAC(tempString, false); @@ -1478,7 +1501,8 @@ nsProtocolProxyService::ReloadPAC() { prefs->GetCharPref(PROXY_PREF("autoconfig_url"), pacSpec); } else if (type == PROXYCONFIG_SYSTEM) { if (mSystemProxySettings) { - AsyncConfigureFromPAC(true, true); + AsyncConfigureWPADOrFromPAC(true, true, + StaticPrefs::network_proxy_system_wpad()); } else { ResetPACThread(); } @@ -1555,7 +1579,8 @@ nsresult nsProtocolProxyService::AsyncResolveInternal( bool usePACThread; // adapt to realtime changes in the system proxy service - if (mProxyConfig == PROXYCONFIG_SYSTEM) { + if (mProxyConfig == PROXYCONFIG_SYSTEM && + !StaticPrefs::network_proxy_system_wpad()) { nsCOMPtr<nsISystemProxySettings> sp2 = do_GetService(NS_SYSTEMPROXYSETTINGS_CONTRACTID); if (sp2 != mSystemProxySettings) { @@ -2190,7 +2215,8 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, } // Proxy auto config magic... - if (mProxyConfig == PROXYCONFIG_PAC || mProxyConfig == PROXYCONFIG_WPAD) { + if (mProxyConfig == PROXYCONFIG_PAC || mProxyConfig == PROXYCONFIG_WPAD || + StaticPrefs::network_proxy_system_wpad()) { // Do not query PAC now. *usePACThread = true; return NS_OK; diff --git a/netwerk/base/nsProtocolProxyService.h b/netwerk/base/nsProtocolProxyService.h index 394450ca6e..2c102a808e 100644 --- a/netwerk/base/nsProtocolProxyService.h +++ b/netwerk/base/nsProtocolProxyService.h @@ -320,9 +320,13 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, nsresult ResetPACThread(); nsresult ReloadNetworkPAC(); - nsresult AsyncConfigureFromPAC(bool aForceReload, bool aResetPACThread); - nsresult OnAsyncGetPACURI(bool aForceReload, bool aResetPACThread, - nsresult aResult, const nsACString& aUri); + nsresult AsyncConfigureWPADOrFromPAC(bool aForceReload, bool aResetPACThread, + bool aSystemWPADAllowed); + nsresult OnAsyncGetPACURIOrSystemWPADSetting(bool aForceReload, + bool aResetPACThread, + nsresult aResult, + const nsACString& aUri, + bool aSystemWPADSetting); public: // The Sun Forte compiler and others implement older versions of the diff --git a/netwerk/base/nsStandardURL.cpp b/netwerk/base/nsStandardURL.cpp index de3578c439..d9b0c23ead 100644 --- a/netwerk/base/nsStandardURL.cpp +++ b/netwerk/base/nsStandardURL.cpp @@ -292,8 +292,8 @@ void nsStandardURL::SanityCheck() { (uint32_t)mExtension.mPos, (int32_t)mExtension.mLen, (uint32_t)mQuery.mPos, (int32_t)mQuery.mLen, (uint32_t)mRef.mPos, (int32_t)mRef.mLen); - CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::URLSegments, - msg); + CrashReporter::RecordAnnotationNSCString( + CrashReporter::Annotation::URLSegments, msg); MOZ_CRASH("nsStandardURL::SanityCheck failed"); } diff --git a/netwerk/base/nsTransportUtils.cpp b/netwerk/base/nsTransportUtils.cpp index df53ead198..242907da08 100644 --- a/netwerk/base/nsTransportUtils.cpp +++ b/netwerk/base/nsTransportUtils.cpp @@ -24,24 +24,21 @@ class nsTransportEventSinkProxy : public nsITransportEventSink { nsTransportEventSinkProxy(nsITransportEventSink* sink, nsIEventTarget* target) : mSink(sink), mTarget(target), - mLock("nsTransportEventSinkProxy.mLock"), - mLastEvent(nullptr) { - NS_ADDREF(mSink); - } + mLock("nsTransportEventSinkProxy.mLock") {} private: virtual ~nsTransportEventSinkProxy() { // our reference to mSink could be the last, so be sure to release // it on the target thread. otherwise, we could get into trouble. NS_ProxyRelease("nsTransportEventSinkProxy::mSink", mTarget, - dont_AddRef(mSink)); + mSink.forget()); } public: - nsITransportEventSink* mSink; + nsCOMPtr<nsITransportEventSink> mSink; nsCOMPtr<nsIEventTarget> mTarget; Mutex mLock MOZ_UNANNOTATED; - nsTransportStatusEvent* mLastEvent; + RefPtr<nsTransportStatusEvent> mLastEvent; }; class nsTransportStatusEvent : public Runnable { @@ -69,11 +66,14 @@ class nsTransportStatusEvent : public Runnable { // if not coalescing all, then last event may not equal self! { MutexAutoLock lock(mProxy->mLock); - if (mProxy->mLastEvent == this) mProxy->mLastEvent = nullptr; + if (mProxy->mLastEvent == this) { + mProxy->mLastEvent = nullptr; + } } mProxy->mSink->OnTransportStatus(mTransport, mStatus, mProgress, mProgressMax); + mProxy = nullptr; return NS_OK; } diff --git a/netwerk/base/nsURLHelper.cpp b/netwerk/base/nsURLHelper.cpp index 3850c6865a..ca82b0cd00 100644 --- a/netwerk/base/nsURLHelper.cpp +++ b/netwerk/base/nsURLHelper.cpp @@ -1236,8 +1236,8 @@ void URLParams::DecodeString(const nsACString& aInput, nsAString& aOutput) { /* static */ bool URLParams::ParseNextInternal(const char*& aStart, const char* const aEnd, - nsAString* aOutDecodedName, - nsAString* aOutDecodedValue) { + bool aShouldDecode, nsAString* aOutputName, + nsAString* aOutputValue) { nsDependentCSubstring string; const char* const iter = std::find(aStart, aEnd, '&'); @@ -1267,9 +1267,14 @@ bool URLParams::ParseNextInternal(const char*& aStart, const char* const aEnd, name.Rebind(string, 0); } - DecodeString(name, *aOutDecodedName); - DecodeString(value, *aOutDecodedValue); + if (aShouldDecode) { + DecodeString(name, *aOutputName); + DecodeString(value, *aOutputValue); + return true; + } + ConvertString(name, *aOutputName); + ConvertString(value, *aOutputValue); return true; } @@ -1278,7 +1283,7 @@ bool URLParams::Extract(const nsACString& aInput, const nsAString& aName, nsAString& aValue) { aValue.SetIsVoid(true); return !URLParams::Parse( - aInput, [&aName, &aValue](const nsAString& name, nsString&& value) { + aInput, true, [&aName, &aValue](const nsAString& name, nsString&& value) { if (aName == name) { aValue = std::move(value); return false; @@ -1291,7 +1296,7 @@ void URLParams::ParseInput(const nsACString& aInput) { // Remove all the existing data before parsing a new input. DeleteAll(); - URLParams::Parse(aInput, [this](nsString&& name, nsString&& value) { + URLParams::Parse(aInput, true, [this](nsString&& name, nsString&& value) { mParams.AppendElement(Param{std::move(name), std::move(value)}); return true; }); diff --git a/netwerk/base/nsURLHelper.h b/netwerk/base/nsURLHelper.h index f5ccc8bac6..36844e6e4b 100644 --- a/netwerk/base/nsURLHelper.h +++ b/netwerk/base/nsURLHelper.h @@ -257,19 +257,20 @@ class URLParams final { * true otherwise */ template <typename ParamHandler> - static bool Parse(const nsACString& aInput, ParamHandler aParamHandler) { + static bool Parse(const nsACString& aInput, bool aShouldDecode, + ParamHandler aParamHandler) { const char* start = aInput.BeginReading(); const char* const end = aInput.EndReading(); while (start != end) { - nsAutoString decodedName; - nsAutoString decodedValue; + nsAutoString name; + nsAutoString value; - if (!ParseNextInternal(start, end, &decodedName, &decodedValue)) { + if (!ParseNextInternal(start, end, aShouldDecode, &name, &value)) { continue; } - if (!aParamHandler(std::move(decodedName), std::move(decodedValue))) { + if (!aParamHandler(std::move(name), std::move(value))) { return false; } } @@ -357,8 +358,8 @@ class URLParams final { static void DecodeString(const nsACString& aInput, nsAString& aOutput); static void ConvertString(const nsACString& aInput, nsAString& aOutput); static bool ParseNextInternal(const char*& aStart, const char* aEnd, - nsAString* aOutDecodedName, - nsAString* aOutDecodedValue); + bool aShouldDecode, nsAString* aOutputName, + nsAString* aOutputValue); struct Param { nsString mKey; diff --git a/netwerk/cache2/CacheFileUtils.cpp b/netwerk/cache2/CacheFileUtils.cpp index 8d68cc82a0..fd1a8665e4 100644 --- a/netwerk/cache2/CacheFileUtils.cpp +++ b/netwerk/cache2/CacheFileUtils.cpp @@ -90,7 +90,6 @@ class KeyParser : protected Tokenizer { break; case 'b': // Leaving to be able to read and understand oldformatted entries - originAttribs.mInIsolatedMozBrowser = true; break; case 'a': isAnonymous = true; diff --git a/netwerk/cache2/CacheStorageService.cpp b/netwerk/cache2/CacheStorageService.cpp index ff5cc51d51..27c83cb699 100644 --- a/netwerk/cache2/CacheStorageService.cpp +++ b/netwerk/cache2/CacheStorageService.cpp @@ -883,13 +883,15 @@ nsresult CacheStorageService::ClearOriginInternal( NS_ERROR("aEntry->HashingKey() failed?"); return rv; } - + MOZ_ASSERT_IF(info->IsPrivate(), !entry->IsUsingDisk()); RemoveExactEntry(table, entryKey, entry, false /* don't overwrite */); } } } - rv = CacheFileIOManager::EvictByContext(info, false /* pinned */, aOrigin); + if (!info->IsPrivate()) { + rv = CacheFileIOManager::EvictByContext(info, false /* pinned */, aOrigin); + } NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -933,9 +935,13 @@ NS_IMETHODIMP CacheStorageService::PurgeFromMemoryRunnable::Run() { } if (mService) { - // TODO not all flags apply to both pools - mService->Pool(MemoryPool::EType::DISK).PurgeAll(mWhat); - mService->Pool(MemoryPool::EType::MEMORY).PurgeAll(mWhat); + // Note that we seem to come here only in the case of "memory-pressure" + // being notified (or in case of tests), so we start from purging in-memory + // entries first and ignore minprogress for disk entries. + // TODO not all flags apply to both pools. + mService->Pool(MemoryPool::EType::MEMORY) + .PurgeAll(mWhat, StaticPrefs::network_cache_purge_minprogress_memory()); + mService->Pool(MemoryPool::EType::DISK).PurgeAll(mWhat, 0); mService = nullptr; } @@ -1349,24 +1355,37 @@ void CacheStorageService::PurgeExpiredOrOverMemoryLimit() { mLastPurgeTime = now; - Pool(MemoryPool::EType::DISK).PurgeExpiredOrOverMemoryLimit(); + // We start purging memory entries first as we care more about RAM over + // disk space beeing freed in case we are interrupted. Pool(MemoryPool::EType::MEMORY).PurgeExpiredOrOverMemoryLimit(); + Pool(MemoryPool::EType::DISK).PurgeExpiredOrOverMemoryLimit(); } void CacheStorageService::MemoryPool::PurgeExpiredOrOverMemoryLimit() { TimeStamp start(TimeStamp::Now()); uint32_t const memoryLimit = Limit(); + size_t minprogress = + (mType == EType::DISK) + ? StaticPrefs::network_cache_purge_minprogress_disk() + : StaticPrefs::network_cache_purge_minprogress_memory(); // We always purge expired entries, even if under our limit. - size_t numExpired = PurgeExpired(); + size_t numExpired = PurgeExpired(minprogress); if (numExpired > 0) { LOG((" found and purged %zu expired entries", numExpired)); } + minprogress = (minprogress > numExpired) ? minprogress - numExpired : 0; // If we are still under pressure, purge LFU entries until we aren't. if (mMemorySize > memoryLimit) { - auto r = PurgeByFrecency(); + // Do not enter PurgeByFrecency if we reached the minimum and are asked to + // deliver entries. + if (minprogress == 0 && CacheIOThread::YieldAndRerun()) { + return; + } + + auto r = PurgeByFrecency(minprogress); if (MOZ_LIKELY(r.isOk())) { size_t numPurged = r.unwrap(); LOG(( @@ -1374,7 +1393,7 @@ void CacheStorageService::MemoryPool::PurgeExpiredOrOverMemoryLimit() { numPurged)); } else { // If we hit an error (OOM), do an emergency PurgeAll. - size_t numPurged = PurgeAll(CacheEntry::PURGE_WHOLE); + size_t numPurged = PurgeAll(CacheEntry::PURGE_WHOLE, minprogress); LOG( (" memory data consumption over the limit, emergency purged all %zu " "entries", @@ -1386,13 +1405,12 @@ void CacheStorageService::MemoryPool::PurgeExpiredOrOverMemoryLimit() { } // This function purges ALL expired entries. -size_t CacheStorageService::MemoryPool::PurgeExpired() { +size_t CacheStorageService::MemoryPool::PurgeExpired(size_t minprogress) { MOZ_ASSERT(IsOnManagementThread()); uint32_t now = NowInSeconds(); size_t numPurged = 0; - // Scan for items to purge. mManagedEntries is not sorted but comparing just // one integer should be faster than anything else, so go scan. RefPtr<CacheEntry> entry = mManagedEntries.getFirst(); @@ -1412,8 +1430,8 @@ size_t CacheStorageService::MemoryPool::PurgeExpired() { entry = std::move(nextEntry); // To have some progress even under load, we do the check only after - // purging at least one item if under pressure. - if ((numPurged > 0 || mMemorySize <= Limit()) && + // purging at least minprogress items if under pressure. + if ((numPurged >= minprogress || mMemorySize <= Limit()) && CacheIOThread::YieldAndRerun()) { break; } @@ -1422,7 +1440,8 @@ size_t CacheStorageService::MemoryPool::PurgeExpired() { return numPurged; } -Result<size_t, nsresult> CacheStorageService::MemoryPool::PurgeByFrecency() { +Result<size_t, nsresult> CacheStorageService::MemoryPool::PurgeByFrecency( + size_t minprogress) { MOZ_ASSERT(IsOnManagementThread()); // Pretend the limit is 10% lower so that we get rid of more entries at one @@ -1473,13 +1492,6 @@ Result<size_t, nsresult> CacheStorageService::MemoryPool::PurgeByFrecency() { size_t numPurged = 0; - // Given that sorting is expensive, let's ensure to interrupt only if we - // made at least some progress. We expect purging of memory entries to be - // less expensive than disk entries. - size_t minprogress = - (mType == EType::DISK) - ? StaticPrefs::network_cache_purgebyfrecency_minprogress_disk() - : StaticPrefs::network_cache_purgebyfrecency_minprogress_memory(); for (auto& checkPurge : mayPurgeSorted) { if (mMemorySize <= memoryLimit) { break; @@ -1504,7 +1516,8 @@ Result<size_t, nsresult> CacheStorageService::MemoryPool::PurgeByFrecency() { return numPurged; } -size_t CacheStorageService::MemoryPool::PurgeAll(uint32_t aWhat) { +size_t CacheStorageService::MemoryPool::PurgeAll(uint32_t aWhat, + size_t minprogress) { LOG(("CacheStorageService::MemoryPool::PurgeAll aWhat=%d", aWhat)); MOZ_ASSERT(IsOnManagementThread()); @@ -1512,7 +1525,7 @@ size_t CacheStorageService::MemoryPool::PurgeAll(uint32_t aWhat) { RefPtr<CacheEntry> entry = mManagedEntries.getFirst(); while (entry) { - if (numPurged > 0 && CacheIOThread::YieldAndRerun()) break; + if (numPurged >= minprogress && CacheIOThread::YieldAndRerun()) break; // Get the next entry before we may be removed from our list. RefPtr<CacheEntry> nextEntry = entry->getNext(); diff --git a/netwerk/cache2/CacheStorageService.h b/netwerk/cache2/CacheStorageService.h index 84b63438b0..0adc9f004d 100644 --- a/netwerk/cache2/CacheStorageService.h +++ b/netwerk/cache2/CacheStorageService.h @@ -349,9 +349,9 @@ class CacheStorageService final : public nsICacheStorageService, * Purges entries from memory based on the frecency ordered array. */ void PurgeExpiredOrOverMemoryLimit(); - size_t PurgeExpired(); - Result<size_t, nsresult> PurgeByFrecency(); - size_t PurgeAll(uint32_t aWhat); + size_t PurgeExpired(size_t minprogress); + Result<size_t, nsresult> PurgeByFrecency(size_t minprogress); + size_t PurgeAll(uint32_t aWhat, size_t minprogress); private: uint32_t Limit() const; diff --git a/netwerk/cookie/CookieCommons.cpp b/netwerk/cookie/CookieCommons.cpp index 3708f23daa..9b26fc4a6e 100644 --- a/netwerk/cookie/CookieCommons.cpp +++ b/netwerk/cookie/CookieCommons.cpp @@ -487,7 +487,8 @@ bool CookieCommons::ShouldIncludeCrossSiteCookieForDocument( aCookie->GetSameSite(&sameSiteAttr); if (aDocument->CookieJarSettings()->GetPartitionForeign() && - StaticPrefs::network_cookie_cookieBehavior_optInPartitioning()) { + StaticPrefs::network_cookie_cookieBehavior_optInPartitioning() && + !aCookie->IsPartitioned()) { return false; } diff --git a/netwerk/cookie/CookiePersistentStorage.cpp b/netwerk/cookie/CookiePersistentStorage.cpp index bb4e64f0f1..6358b39e3a 100644 --- a/netwerk/cookie/CookiePersistentStorage.cpp +++ b/netwerk/cookie/CookiePersistentStorage.cpp @@ -132,14 +132,7 @@ NS_IMETHODIMP ConvertAppIdToOriginAttrsSQLFunction::OnFunctionCall( mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) { nsresult rv; - int32_t inIsolatedMozBrowser; - - rv = aFunctionArguments->GetInt32(1, &inIsolatedMozBrowser); - NS_ENSURE_SUCCESS(rv, rv); - - // Create an originAttributes object by inIsolatedMozBrowser. - // Then create the originSuffix string from this object. - OriginAttributes attrs(inIsolatedMozBrowser != 0); + OriginAttributes attrs; nsAutoCString suffix; attrs.CreateSuffix(suffix); @@ -205,7 +198,7 @@ SetInBrowserFromOriginAttributesSQLFunction::OnFunctionCall( NS_ENSURE_TRUE(success, NS_ERROR_FAILURE); RefPtr<nsVariant> outVar(new nsVariant()); - rv = outVar->SetAsInt32(attrs.mInIsolatedMozBrowser); + rv = outVar->SetAsInt32(false); NS_ENSURE_SUCCESS(rv, rv); outVar.forget(aResult); diff --git a/netwerk/cookie/CookieService.cpp b/netwerk/cookie/CookieService.cpp index d306203c2f..0e90b8cbae 100644 --- a/netwerk/cookie/CookieService.cpp +++ b/netwerk/cookie/CookieService.cpp @@ -13,6 +13,7 @@ #include "mozilla/dom/Document.h" #include "mozilla/dom/nsMixedContentBlocker.h" #include "mozilla/dom/Promise.h" +#include "mozilla/glean/GleanMetrics.h" #include "mozilla/net/CookieJarSettings.h" #include "mozilla/net/CookiePersistentStorage.h" #include "mozilla/net/CookiePrivateStorage.h" @@ -372,44 +373,14 @@ CookieService::GetCookieStringFromDocument(Document* aDocument, return NS_OK; } - nsCOMPtr<nsIPrincipal> principal = aDocument->EffectiveCookiePrincipal(); + nsCOMPtr<nsIPrincipal> cookiePrincipal = + aDocument->EffectiveCookiePrincipal(); - if (!CookieCommons::IsSchemeSupported(principal)) { - return NS_OK; - } - - CookieStorage* storage = PickStorage(principal->OriginAttributesRef()); - - nsAutoCString baseDomain; - rv = CookieCommons::GetBaseDomain(principal, baseDomain); - if (NS_WARN_IF(NS_FAILED(rv))) { - return NS_OK; - } - - nsAutoCString hostFromURI; - rv = nsContentUtils::GetHostOrIPv6WithBrackets(principal, hostFromURI); - if (NS_WARN_IF(NS_FAILED(rv))) { - return NS_OK; - } - - nsAutoCString pathFromURI; - rv = principal->GetFilePath(pathFromURI); - if (NS_WARN_IF(NS_FAILED(rv))) { - return NS_OK; - } - - int64_t currentTimeInUsec = PR_Now(); - int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; - - const nsTArray<RefPtr<Cookie>>* cookies = - storage->GetCookiesFromHost(baseDomain, principal->OriginAttributesRef()); - if (!cookies) { - return NS_OK; - } - - // check if the nsIPrincipal is using an https secure protocol. - // if it isn't, then we can't send a secure cookie over the connection. - bool potentiallyTrustworthy = principal->GetIsOriginPotentiallyTrustworthy(); + // TODO (Bug 1874174): A document could access both unpartitioned and + // partitioned cookie jars. We will need to prepare partitioned and + // unpartitioned principals for access both cookie jars. + nsTArray<nsCOMPtr<nsIPrincipal>> principals; + principals.AppendElement(cookiePrincipal); bool thirdParty = true; nsPIDOMWindowInner* innerWindow = aDocument->GetInnerWindow(); @@ -424,47 +395,98 @@ CookieService::GetCookieStringFromDocument(Document* aDocument, } } - bool stale = false; nsTArray<Cookie*> cookieList; - // iterate the cookies! - for (Cookie* cookie : *cookies) { - // check the host, since the base domain lookup is conservative. - if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { - continue; + for (auto& principal : principals) { + if (!CookieCommons::IsSchemeSupported(principal)) { + return NS_OK; } - // if the cookie is httpOnly and it's not going directly to the HTTP - // connection, don't send it - if (cookie->IsHttpOnly()) { - continue; + CookieStorage* storage = PickStorage(principal->OriginAttributesRef()); + + nsAutoCString baseDomain; + rv = CookieCommons::GetBaseDomain(principal, baseDomain); + if (NS_WARN_IF(NS_FAILED(rv))) { + return NS_OK; } - if (thirdParty && !CookieCommons::ShouldIncludeCrossSiteCookieForDocument( - cookie, aDocument)) { - continue; + nsAutoCString hostFromURI; + rv = nsContentUtils::GetHostOrIPv6WithBrackets(principal, hostFromURI); + if (NS_WARN_IF(NS_FAILED(rv))) { + return NS_OK; } - // if the cookie is secure and the host scheme isn't, we can't send it - if (cookie->IsSecure() && !potentiallyTrustworthy) { - continue; + nsAutoCString pathFromURI; + rv = principal->GetFilePath(pathFromURI); + if (NS_WARN_IF(NS_FAILED(rv))) { + return NS_OK; } - // if the nsIURI path doesn't match the cookie path, don't send it back - if (!CookieCommons::PathMatches(cookie, pathFromURI)) { + int64_t currentTimeInUsec = PR_Now(); + int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; + + const nsTArray<RefPtr<Cookie>>* cookies = storage->GetCookiesFromHost( + baseDomain, principal->OriginAttributesRef()); + if (!cookies) { continue; } - // check if the cookie has expired - if (cookie->Expiry() <= currentTime) { + // check if the nsIPrincipal is using an https secure protocol. + // if it isn't, then we can't send a secure cookie over the connection. + bool potentiallyTrustworthy = + principal->GetIsOriginPotentiallyTrustworthy(); + + bool stale = false; + + // iterate the cookies! + for (Cookie* cookie : *cookies) { + // check the host, since the base domain lookup is conservative. + if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { + continue; + } + + // if the cookie is httpOnly and it's not going directly to the HTTP + // connection, don't send it + if (cookie->IsHttpOnly()) { + continue; + } + + if (thirdParty && !CookieCommons::ShouldIncludeCrossSiteCookieForDocument( + cookie, aDocument)) { + continue; + } + + // if the cookie is secure and the host scheme isn't, we can't send it + if (cookie->IsSecure() && !potentiallyTrustworthy) { + continue; + } + + // if the nsIURI path doesn't match the cookie path, don't send it back + if (!CookieCommons::PathMatches(cookie, pathFromURI)) { + continue; + } + + // check if the cookie has expired + if (cookie->Expiry() <= currentTime) { + continue; + } + + // all checks passed - add to list and check if lastAccessed stamp needs + // updating + cookieList.AppendElement(cookie); + if (cookie->IsStale()) { + stale = true; + } + } + + if (cookieList.IsEmpty()) { continue; } - // all checks passed - add to list and check if lastAccessed stamp needs - // updating - cookieList.AppendElement(cookie); - if (cookie->IsStale()) { - stale = true; + // update lastAccessed timestamps. we only do this if the timestamp is stale + // by a certain amount, to avoid thrashing the db during pageload. + if (stale) { + storage->StaleCookies(cookieList, currentTimeInUsec); } } @@ -472,12 +494,6 @@ CookieService::GetCookieStringFromDocument(Document* aDocument, return NS_OK; } - // update lastAccessed timestamps. we only do this if the timestamp is stale - // by a certain amount, to avoid thrashing the db during pageload. - if (stale) { - storage->StaleCookies(cookieList, currentTimeInUsec); - } - // return cookies in order of path length; longest to shortest. // this is required per RFC2109. if cookies match in length, // then sort by creation time (see bug 236772). @@ -512,6 +528,12 @@ CookieService::GetCookieStringFromHttp(nsIURI* aHostURI, nsIChannel* aChannel, bool isSameSiteForeign = CookieCommons::IsSameSiteForeign( aChannel, aHostURI, &hadCrossSiteRedirects); + // TODO (Bug 1874174): A channel could load both unpartitioned and partitioned + // cookie jars together. We will need to get cookies from both unpartitioned + // and partitioned cookie jars according to storage access. + nsTArray<OriginAttributes> originAttributesList; + originAttributesList.AppendElement(attrs); + AutoTArray<Cookie*, 8> foundCookieList; GetCookiesForURI( aHostURI, aChannel, result.contains(ThirdPartyAnalysis::IsForeign), @@ -519,7 +541,8 @@ CookieService::GetCookieStringFromHttp(nsIURI* aHostURI, nsIChannel* aChannel, result.contains(ThirdPartyAnalysis::IsThirdPartySocialTrackingResource), result.contains(ThirdPartyAnalysis::IsStorageAccessPermissionGranted), rejectedReason, isSafeTopLevelNav, isSameSiteForeign, - hadCrossSiteRedirects, true, false, attrs, foundCookieList); + hadCrossSiteRedirects, true, false, originAttributesList, + foundCookieList); ComposeCookieString(foundCookieList, aCookieString); @@ -936,7 +959,8 @@ void CookieService::GetCookiesForURI( bool aIsSafeTopLevelNav, bool aIsSameSiteForeign, bool aHadCrossSiteRedirects, bool aHttpBound, bool aAllowSecureCookiesToInsecureOrigin, - const OriginAttributes& aOriginAttrs, nsTArray<Cookie*>& aCookieList) { + const nsTArray<OriginAttributes>& aOriginAttrsList, + nsTArray<Cookie*>& aCookieList) { NS_ASSERTION(aHostURI, "null host!"); if (!CookieCommons::IsSchemeSupported(aHostURI)) { @@ -947,152 +971,165 @@ void CookieService::GetCookiesForURI( return; } - CookieStorage* storage = PickStorage(aOriginAttrs); - - // get the base domain, host, and path from the URI. - // e.g. for "www.bbc.co.uk", the base domain would be "bbc.co.uk". - // file:// URI's (i.e. with an empty host) are allowed, but any other - // scheme must have a non-empty host. A trailing dot in the host - // is acceptable. - bool requireHostMatch; - nsAutoCString baseDomain; - nsAutoCString hostFromURI; - nsAutoCString pathFromURI; - nsresult rv = CookieCommons::GetBaseDomain(mTLDService, aHostURI, baseDomain, - requireHostMatch); - if (NS_SUCCEEDED(rv)) { - rv = nsContentUtils::GetHostOrIPv6WithBrackets(aHostURI, hostFromURI); - } - if (NS_SUCCEEDED(rv)) { - rv = aHostURI->GetFilePath(pathFromURI); - } - if (NS_FAILED(rv)) { - COOKIE_LOGFAILURE(GET_COOKIE, aHostURI, VoidCString(), - "invalid host/path from URI"); - return; - } - nsCOMPtr<nsICookieJarSettings> cookieJarSettings = CookieCommons::GetCookieJarSettings(aChannel); - nsAutoCString normalizedHostFromURI(hostFromURI); - rv = NormalizeHost(normalizedHostFromURI); - NS_ENSURE_SUCCESS_VOID(rv); - - nsAutoCString baseDomainFromURI; - rv = CookieCommons::GetBaseDomainFromHost(mTLDService, normalizedHostFromURI, - baseDomainFromURI); - NS_ENSURE_SUCCESS_VOID(rv); - - // check default prefs - uint32_t rejectedReason = aRejectedReason; - uint32_t priorCookieCount = storage->CountCookiesFromHost( - baseDomainFromURI, aOriginAttrs.mPrivateBrowsingId); - nsCOMPtr<nsIConsoleReportCollector> crc = do_QueryInterface(aChannel); - CookieStatus cookieStatus = CheckPrefs( - crc, cookieJarSettings, aHostURI, aIsForeign, - aIsThirdPartyTrackingResource, aIsThirdPartySocialTrackingResource, - aStorageAccessPermissionGranted, VoidCString(), priorCookieCount, - aOriginAttrs, &rejectedReason); - - MOZ_ASSERT_IF(rejectedReason, cookieStatus == STATUS_REJECTED); - // for GetCookie(), we only fire acceptance/rejection notifications - // (but not if there was an error) - switch (cookieStatus) { - case STATUS_REJECTED: - // If we don't have any cookies from this host, fail silently. - if (priorCookieCount) { - CookieCommons::NotifyRejected(aHostURI, aChannel, rejectedReason, - OPERATION_READ); - } + for (const auto& attrs : aOriginAttrsList) { + CookieStorage* storage = PickStorage(attrs); + + // get the base domain, host, and path from the URI. + // e.g. for "www.bbc.co.uk", the base domain would be "bbc.co.uk". + // file:// URI's (i.e. with an empty host) are allowed, but any other + // scheme must have a non-empty host. A trailing dot in the host + // is acceptable. + bool requireHostMatch; + nsAutoCString baseDomain; + nsAutoCString hostFromURI; + nsAutoCString pathFromURI; + nsresult rv = CookieCommons::GetBaseDomain(mTLDService, aHostURI, + baseDomain, requireHostMatch); + if (NS_SUCCEEDED(rv)) { + rv = nsContentUtils::GetHostOrIPv6WithBrackets(aHostURI, hostFromURI); + } + if (NS_SUCCEEDED(rv)) { + rv = aHostURI->GetFilePath(pathFromURI); + } + if (NS_FAILED(rv)) { + COOKIE_LOGFAILURE(GET_COOKIE, aHostURI, VoidCString(), + "invalid host/path from URI"); return; - default: - break; - } - - // Note: The following permissions logic is mirrored in - // extensions::MatchPattern::MatchesCookie. - // If it changes, please update that function, or file a bug for someone - // else to do so. + } - // check if aHostURI is using an https secure protocol. - // if it isn't, then we can't send a secure cookie over the connection. - // if SchemeIs fails, assume an insecure connection, to be on the safe side - bool potentiallyTrustworthy = - nsMixedContentBlocker::IsPotentiallyTrustworthyOrigin(aHostURI); + nsAutoCString normalizedHostFromURI(hostFromURI); + rv = NormalizeHost(normalizedHostFromURI); + NS_ENSURE_SUCCESS_VOID(rv); + + nsAutoCString baseDomainFromURI; + rv = CookieCommons::GetBaseDomainFromHost( + mTLDService, normalizedHostFromURI, baseDomainFromURI); + NS_ENSURE_SUCCESS_VOID(rv); + + // check default prefs + uint32_t rejectedReason = aRejectedReason; + uint32_t priorCookieCount = storage->CountCookiesFromHost( + baseDomainFromURI, attrs.mPrivateBrowsingId); + + CookieStatus cookieStatus = CheckPrefs( + crc, cookieJarSettings, aHostURI, aIsForeign, + aIsThirdPartyTrackingResource, aIsThirdPartySocialTrackingResource, + aStorageAccessPermissionGranted, VoidCString(), priorCookieCount, attrs, + &rejectedReason); + + MOZ_ASSERT_IF(rejectedReason, cookieStatus == STATUS_REJECTED); + + // for GetCookie(), we only fire acceptance/rejection notifications + // (but not if there was an error) + switch (cookieStatus) { + case STATUS_REJECTED: + // If we don't have any cookies from this host, fail silently. + if (priorCookieCount) { + CookieCommons::NotifyRejected(aHostURI, aChannel, rejectedReason, + OPERATION_READ); + } + return; + default: + break; + } - int64_t currentTimeInUsec = PR_Now(); - int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; - bool stale = false; + // Note: The following permissions logic is mirrored in + // extensions::MatchPattern::MatchesCookie. + // If it changes, please update that function, or file a bug for someone + // else to do so. - const nsTArray<RefPtr<Cookie>>* cookies = - storage->GetCookiesFromHost(baseDomain, aOriginAttrs); - if (!cookies) { - return; - } + // check if aHostURI is using an https secure protocol. + // if it isn't, then we can't send a secure cookie over the connection. + // if SchemeIs fails, assume an insecure connection, to be on the safe side + bool potentiallyTrustworthy = + nsMixedContentBlocker::IsPotentiallyTrustworthyOrigin(aHostURI); - bool laxByDefault = - StaticPrefs::network_cookie_sameSite_laxByDefault() && - !nsContentUtils::IsURIInPrefList( - aHostURI, "network.cookie.sameSite.laxByDefault.disabledHosts"); + int64_t currentTimeInUsec = PR_Now(); + int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; + bool stale = false; - // iterate the cookies! - for (Cookie* cookie : *cookies) { - // check the host, since the base domain lookup is conservative. - if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { + const nsTArray<RefPtr<Cookie>>* cookies = + storage->GetCookiesFromHost(baseDomain, attrs); + if (!cookies) { continue; } - // if the cookie is secure and the host scheme isn't, we avoid sending - // cookie if possible. But for process synchronization purposes, we may want - // the content process to know about the cookie (without it's value). In - // which case we will wipe the value before sending - if (cookie->IsSecure() && !potentiallyTrustworthy && - !aAllowSecureCookiesToInsecureOrigin) { - continue; - } + bool laxByDefault = + StaticPrefs::network_cookie_sameSite_laxByDefault() && + !nsContentUtils::IsURIInPrefList( + aHostURI, "network.cookie.sameSite.laxByDefault.disabledHosts"); - // if the cookie is httpOnly and it's not going directly to the HTTP - // connection, don't send it - if (cookie->IsHttpOnly() && !aHttpBound) { - continue; - } + // iterate the cookies! + for (Cookie* cookie : *cookies) { + // check the host, since the base domain lookup is conservative. + if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { + continue; + } - // if the nsIURI path doesn't match the cookie path, don't send it back - if (!CookieCommons::PathMatches(cookie, pathFromURI)) { - continue; - } + // if the cookie is secure and the host scheme isn't, we avoid sending + // cookie if possible. But for process synchronization purposes, we may + // want the content process to know about the cookie (without it's value). + // In which case we will wipe the value before sending + if (cookie->IsSecure() && !potentiallyTrustworthy && + !aAllowSecureCookiesToInsecureOrigin) { + continue; + } - // check if the cookie has expired - if (cookie->Expiry() <= currentTime) { - continue; - } + // if the cookie is httpOnly and it's not going directly to the HTTP + // connection, don't send it + if (cookie->IsHttpOnly() && !aHttpBound) { + continue; + } - if (aHttpBound && aIsSameSiteForeign) { - bool blockCookie = !ProcessSameSiteCookieForForeignRequest( - aChannel, cookie, aIsSafeTopLevelNav, aHadCrossSiteRedirects, - laxByDefault); - - if (blockCookie) { - if (aHadCrossSiteRedirects) { - CookieLogging::LogMessageToConsole( - crc, aHostURI, nsIScriptError::warningFlag, - CONSOLE_REJECTION_CATEGORY, "CookieBlockedCrossSiteRedirect"_ns, - AutoTArray<nsString, 1>{ - NS_ConvertUTF8toUTF16(cookie->Name()), - }); - } + // if the nsIURI path doesn't match the cookie path, don't send it back + if (!CookieCommons::PathMatches(cookie, pathFromURI)) { continue; } + + // check if the cookie has expired + if (cookie->Expiry() <= currentTime) { + continue; + } + + if (aHttpBound && aIsSameSiteForeign) { + bool blockCookie = !ProcessSameSiteCookieForForeignRequest( + aChannel, cookie, aIsSafeTopLevelNav, aHadCrossSiteRedirects, + laxByDefault); + + if (blockCookie) { + if (aHadCrossSiteRedirects) { + CookieLogging::LogMessageToConsole( + crc, aHostURI, nsIScriptError::warningFlag, + CONSOLE_REJECTION_CATEGORY, "CookieBlockedCrossSiteRedirect"_ns, + AutoTArray<nsString, 1>{ + NS_ConvertUTF8toUTF16(cookie->Name()), + }); + } + continue; + } + } + + // all checks passed - add to list and check if lastAccessed stamp needs + // updating + aCookieList.AppendElement(cookie); + if (cookie->IsStale()) { + stale = true; + } } - // all checks passed - add to list and check if lastAccessed stamp needs - // updating - aCookieList.AppendElement(cookie); - if (cookie->IsStale()) { - stale = true; + if (aCookieList.IsEmpty()) { + continue; + } + + // update lastAccessed timestamps. we only do this if the timestamp is stale + // by a certain amount, to avoid thrashing the db during pageload. + if (stale) { + storage->StaleCookies(aCookieList, currentTimeInUsec); } } @@ -1104,12 +1141,6 @@ void CookieService::GetCookiesForURI( // some. NotifyAccepted(aChannel); - // update lastAccessed timestamps. we only do this if the timestamp is stale - // by a certain amount, to avoid thrashing the db during pageload. - if (stale) { - storage->StaleCookies(aCookieList, currentTimeInUsec); - } - // return cookies in order of path length; longest to shortest. // this is required per RFC2109. if cookies match in length, // then sort by creation time (see bug 236772). diff --git a/netwerk/cookie/CookieService.h b/netwerk/cookie/CookieService.h index 09eb4c1289..51344d6909 100644 --- a/netwerk/cookie/CookieService.h +++ b/netwerk/cookie/CookieService.h @@ -88,7 +88,7 @@ class CookieService final : public nsICookieService, bool aIsSameSiteForeign, bool aHadCrossSiteRedirects, bool aHttpBound, bool aAllowSecureCookiesToInsecureOrigin, - const OriginAttributes& aOriginAttrs, + const nsTArray<OriginAttributes>& aOriginAttrsList, nsTArray<Cookie*>& aCookieList); /** diff --git a/netwerk/cookie/CookieServiceChild.cpp b/netwerk/cookie/CookieServiceChild.cpp index a005b5dbe7..84f34a9a37 100644 --- a/netwerk/cookie/CookieServiceChild.cpp +++ b/netwerk/cookie/CookieServiceChild.cpp @@ -107,6 +107,12 @@ RefPtr<GenericPromise> CookieServiceChild::TrackCookieLoad( RefPtr<CookieServiceChild> self(this); + // TODO (Bug 1874174): A channel could access both unpartitioned and + // partitioned cookie jars. We will need to pass partitioned and unpartitioned + // originAttributes according the storage access. + nsTArray<OriginAttributes> attrsList; + attrsList.AppendElement(attrs); + return SendGetCookieList( uri, result.contains(ThirdPartyAnalysis::IsForeign), result.contains(ThirdPartyAnalysis::IsThirdPartyTrackingResource), @@ -115,14 +121,18 @@ RefPtr<GenericPromise> CookieServiceChild::TrackCookieLoad( result.contains( ThirdPartyAnalysis::IsStorageAccessPermissionGranted), rejectedReason, isSafeTopLevelNav, isSameSiteForeign, - hadCrossSiteRedirects, attrs) + hadCrossSiteRedirects, attrsList) ->Then( GetCurrentSerialEventTarget(), __func__, - [self, uri, attrs](const nsTArray<CookieStruct>& aCookiesList) { - for (uint32_t i = 0; i < aCookiesList.Length(); i++) { - RefPtr<Cookie> cookie = Cookie::Create(aCookiesList[i], attrs); - cookie->SetIsHttpOnly(false); - self->RecordDocumentCookie(cookie, attrs); + [self, uri](const nsTArray<CookieStructTable>& aCookiesListTable) { + for (auto& entry : aCookiesListTable) { + auto& cookies = entry.cookies(); + for (auto& cookieEntry : cookies) { + RefPtr<Cookie> cookie = + Cookie::Create(cookieEntry, entry.attrs()); + cookie->SetIsHttpOnly(false); + self->RecordDocumentCookie(cookie, entry.attrs()); + } } return GenericPromise::CreateAndResolve(true, __func__); }, @@ -215,11 +225,13 @@ IPCResult CookieServiceChild::RecvRemoveBatchDeletedCookies( } IPCResult CookieServiceChild::RecvTrackCookiesLoad( - nsTArray<CookieStruct>&& aCookiesList, const OriginAttributes& aAttrs) { - for (uint32_t i = 0; i < aCookiesList.Length(); i++) { - RefPtr<Cookie> cookie = Cookie::Create(aCookiesList[i], aAttrs); - cookie->SetIsHttpOnly(false); - RecordDocumentCookie(cookie, aAttrs); + nsTArray<CookieStructTable>&& aCookiesListTable) { + for (auto& entry : aCookiesListTable) { + for (auto& cookieEntry : entry.cookies()) { + RefPtr<Cookie> cookie = Cookie::Create(cookieEntry, entry.attrs()); + cookie->SetIsHttpOnly(false); + RecordDocumentCookie(cookie, entry.attrs()); + } } nsCOMPtr<nsIObserverService> obsService = services::GetObserverService(); @@ -313,34 +325,14 @@ CookieServiceChild::GetCookieStringFromDocument(dom::Document* aDocument, aCookieString.Truncate(); - nsCOMPtr<nsIPrincipal> principal = aDocument->EffectiveCookiePrincipal(); - - if (!CookieCommons::IsSchemeSupported(principal)) { - return NS_OK; - } - - nsAutoCString baseDomain; - nsresult rv = CookieCommons::GetBaseDomain(principal, baseDomain); - if (NS_WARN_IF(NS_FAILED(rv))) { - return NS_OK; - } - - CookieKey key(baseDomain, principal->OriginAttributesRef()); - CookiesList* cookiesList = nullptr; - mCookiesMap.Get(key, &cookiesList); - - if (!cookiesList) { - return NS_OK; - } + nsCOMPtr<nsIPrincipal> cookiePrincipal = + aDocument->EffectiveCookiePrincipal(); - nsAutoCString hostFromURI; - rv = nsContentUtils::GetHostOrIPv6WithBrackets(principal, hostFromURI); - if (NS_WARN_IF(NS_FAILED(rv))) { - return NS_OK; - } - - nsAutoCString pathFromURI; - principal->GetFilePath(pathFromURI); + // TODO (Bug 1874174): A document could access both unpartitioned and + // partitioned cookie jars. We will need to prepare partitioned and + // unpartitioned principals for access both cookie jars. + nsTArray<nsCOMPtr<nsIPrincipal>> principals; + principals.AppendElement(cookiePrincipal); bool thirdParty = true; nsPIDOMWindowInner* innerWindow = aDocument->GetInnerWindow(); @@ -355,54 +347,83 @@ CookieServiceChild::GetCookieStringFromDocument(dom::Document* aDocument, } } - bool isPotentiallyTrustworthy = - principal->GetIsOriginPotentiallyTrustworthy(); - int64_t currentTimeInUsec = PR_Now(); - int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; - - cookiesList->Sort(CompareCookiesForSending()); - for (uint32_t i = 0; i < cookiesList->Length(); i++) { - Cookie* cookie = cookiesList->ElementAt(i); - // check the host, since the base domain lookup is conservative. - if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { - continue; + for (auto& principal : principals) { + if (!CookieCommons::IsSchemeSupported(principal)) { + return NS_OK; } - // We don't show HttpOnly cookies in content processes. - if (cookie->IsHttpOnly()) { - continue; + nsAutoCString baseDomain; + nsresult rv = CookieCommons::GetBaseDomain(principal, baseDomain); + if (NS_WARN_IF(NS_FAILED(rv))) { + return NS_OK; } - if (thirdParty && !CookieCommons::ShouldIncludeCrossSiteCookieForDocument( - cookie, aDocument)) { - continue; - } + CookieKey key(baseDomain, principal->OriginAttributesRef()); + CookiesList* cookiesList = nullptr; + mCookiesMap.Get(key, &cookiesList); - // do not display the cookie if it is secure and the host scheme isn't - if (cookie->IsSecure() && !isPotentiallyTrustworthy) { + if (!cookiesList) { continue; } - // if the nsIURI path doesn't match the cookie path, don't send it back - if (!CookieCommons::PathMatches(cookie, pathFromURI)) { - continue; + nsAutoCString hostFromURI; + rv = nsContentUtils::GetHostOrIPv6WithBrackets(principal, hostFromURI); + if (NS_WARN_IF(NS_FAILED(rv))) { + return NS_OK; } - // check if the cookie has expired - if (cookie->Expiry() <= currentTime) { - continue; - } + nsAutoCString pathFromURI; + principal->GetFilePath(pathFromURI); - if (!cookie->Name().IsEmpty() || !cookie->Value().IsEmpty()) { - if (!aCookieString.IsEmpty()) { - aCookieString.AppendLiteral("; "); + bool isPotentiallyTrustworthy = + principal->GetIsOriginPotentiallyTrustworthy(); + int64_t currentTimeInUsec = PR_Now(); + int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC; + + cookiesList->Sort(CompareCookiesForSending()); + for (uint32_t i = 0; i < cookiesList->Length(); i++) { + Cookie* cookie = cookiesList->ElementAt(i); + // check the host, since the base domain lookup is conservative. + if (!CookieCommons::DomainMatches(cookie, hostFromURI)) { + continue; } - if (!cookie->Name().IsEmpty()) { - aCookieString.Append(cookie->Name().get()); - aCookieString.AppendLiteral("="); - aCookieString.Append(cookie->Value().get()); - } else { - aCookieString.Append(cookie->Value().get()); + + // We don't show HttpOnly cookies in content processes. + if (cookie->IsHttpOnly()) { + continue; + } + + if (thirdParty && !CookieCommons::ShouldIncludeCrossSiteCookieForDocument( + cookie, aDocument)) { + continue; + } + + // do not display the cookie if it is secure and the host scheme isn't + if (cookie->IsSecure() && !isPotentiallyTrustworthy) { + continue; + } + + // if the nsIURI path doesn't match the cookie path, don't send it back + if (!CookieCommons::PathMatches(cookie, pathFromURI)) { + continue; + } + + // check if the cookie has expired + if (cookie->Expiry() <= currentTime) { + continue; + } + + if (!cookie->Name().IsEmpty() || !cookie->Value().IsEmpty()) { + if (!aCookieString.IsEmpty()) { + aCookieString.AppendLiteral("; "); + } + if (!cookie->Name().IsEmpty()) { + aCookieString.Append(cookie->Name().get()); + aCookieString.AppendLiteral("="); + aCookieString.Append(cookie->Value().get()); + } else { + aCookieString.Append(cookie->Value().get()); + } } } } diff --git a/netwerk/cookie/CookieServiceChild.h b/netwerk/cookie/CookieServiceChild.h index b9caa2aaa7..562ee7f1ae 100644 --- a/netwerk/cookie/CookieServiceChild.h +++ b/netwerk/cookie/CookieServiceChild.h @@ -54,7 +54,7 @@ class CookieServiceChild final : public PCookieServiceChild, static bool RequireThirdPartyCheck(nsILoadInfo* aLoadInfo); mozilla::ipc::IPCResult RecvTrackCookiesLoad( - nsTArray<CookieStruct>&& aCookiesList, const OriginAttributes& aAttrs); + nsTArray<CookieStructTable>&& aCookiesListTable); mozilla::ipc::IPCResult RecvRemoveAll(); diff --git a/netwerk/cookie/CookieServiceParent.cpp b/netwerk/cookie/CookieServiceParent.cpp index c78a67513f..75c024cec6 100644 --- a/netwerk/cookie/CookieServiceParent.cpp +++ b/netwerk/cookie/CookieServiceParent.cpp @@ -5,6 +5,7 @@ #include "CookieCommons.h" #include "CookieLogging.h" +#include "CookieServiceParent.h" #include "mozilla/net/CookieService.h" #include "mozilla/net/CookieServiceParent.h" #include "mozilla/net/NeckoParent.h" @@ -124,6 +125,8 @@ void CookieServiceParent::TrackCookieLoad(nsIChannel* aChannel) { bool isSameSiteForeign = CookieCommons::IsSameSiteForeign(aChannel, uri, &hadCrossSiteRedirects); + // TODO (Bug 1874174): A channel could load both unpartitioned and partitioned + // cookie jars together. We will need to track both originAttributes for them. StoragePrincipalHelper::PrepareEffectiveStoragePrincipalOriginAttributes( aChannel, attrs); @@ -134,7 +137,12 @@ void CookieServiceParent::TrackCookieLoad(nsIChannel* aChannel) { ThirdPartyAnalysisResult result = thirdPartyUtil->AnalyzeChannel( aChannel, false, nullptr, nullptr, &rejectedReason); - UpdateCookieInContentList(uri, attrs); + nsTArray<OriginAttributes> originAttributesList; + originAttributesList.AppendElement(attrs); + + for (auto& originAttributes : originAttributesList) { + UpdateCookieInContentList(uri, originAttributes); + } // Send matching cookies to Child. nsTArray<Cookie*> foundCookieList; @@ -144,10 +152,11 @@ void CookieServiceParent::TrackCookieLoad(nsIChannel* aChannel) { result.contains(ThirdPartyAnalysis::IsThirdPartySocialTrackingResource), result.contains(ThirdPartyAnalysis::IsStorageAccessPermissionGranted), rejectedReason, isSafeTopLevelNav, isSameSiteForeign, - hadCrossSiteRedirects, false, true, attrs, foundCookieList); - nsTArray<CookieStruct> matchingCookiesList; - SerializeCookieList(foundCookieList, matchingCookiesList, uri); - Unused << SendTrackCookiesLoad(matchingCookiesList, attrs); + hadCrossSiteRedirects, false, true, originAttributesList, + foundCookieList); + nsTArray<CookieStructTable> matchingCookiesListTable; + SerializeCookieListTable(foundCookieList, matchingCookiesListTable, uri); + Unused << SendTrackCookiesLoad(matchingCookiesListTable); } // we append outgoing cookie info into a list here so the ContentParent can @@ -170,12 +179,22 @@ void CookieServiceParent::UpdateCookieInContentList( } // static -void CookieServiceParent::SerializeCookieList( +void CookieServiceParent::SerializeCookieListTable( const nsTArray<Cookie*>& aFoundCookieList, - nsTArray<CookieStruct>& aCookiesList, nsIURI* aHostURI) { - for (uint32_t i = 0; i < aFoundCookieList.Length(); i++) { - Cookie* cookie = aFoundCookieList.ElementAt(i); - CookieStruct* cookieStruct = aCookiesList.AppendElement(); + nsTArray<CookieStructTable>& aCookiesListTable, nsIURI* aHostURI) { + nsTHashMap<nsCStringHashKey, CookieStructTable*> cookieListTable; + + for (Cookie* cookie : aFoundCookieList) { + nsAutoCString attrsSuffix; + cookie->OriginAttributesRef().CreateSuffix(attrsSuffix); + CookieStructTable* table = + cookieListTable.LookupOrInsertWith(attrsSuffix, [&] { + CookieStructTable* newTable = aCookiesListTable.AppendElement(); + newTable->attrs() = cookie->OriginAttributesRef(); + return newTable; + }); + + CookieStruct* cookieStruct = table->cookies().AppendElement(); *cookieStruct = cookie->ToIPC(); // clear http-only cookie values @@ -200,7 +219,7 @@ IPCResult CookieServiceParent::RecvGetCookieList( const bool& aStorageAccessPermissionGranted, const uint32_t& aRejectedReason, const bool& aIsSafeTopLevelNav, const bool& aIsSameSiteForeign, const bool& aHadCrossSiteRedirects, - const OriginAttributes& aAttrs, GetCookieListResolver&& aResolve) { + nsTArray<OriginAttributes>&& aAttrsList, GetCookieListResolver&& aResolve) { // Send matching cookies to Child. if (!aHost) { return IPC_FAIL(this, "aHost must not be null"); @@ -208,7 +227,9 @@ IPCResult CookieServiceParent::RecvGetCookieList( // we append outgoing cookie info into a list here so the ContentParent can // filter cookies that do not need to go to certain ContentProcesses - UpdateCookieInContentList(aHost, aAttrs); + for (const auto& attrs : aAttrsList) { + UpdateCookieInContentList(aHost, attrs); + } nsTArray<Cookie*> foundCookieList; // Note: passing nullptr as aChannel to GetCookiesForURI() here is fine since @@ -218,12 +239,12 @@ IPCResult CookieServiceParent::RecvGetCookieList( aHost, nullptr, aIsForeign, aIsThirdPartyTrackingResource, aIsThirdPartySocialTrackingResource, aStorageAccessPermissionGranted, aRejectedReason, aIsSafeTopLevelNav, aIsSameSiteForeign, - aHadCrossSiteRedirects, false, true, aAttrs, foundCookieList); + aHadCrossSiteRedirects, false, true, aAttrsList, foundCookieList); - nsTArray<CookieStruct> matchingCookiesList; - SerializeCookieList(foundCookieList, matchingCookiesList, aHost); + nsTArray<CookieStructTable> matchingCookiesListTable; + SerializeCookieListTable(foundCookieList, matchingCookiesListTable, aHost); - aResolve(matchingCookiesList); + aResolve(matchingCookiesListTable); return IPC_OK(); } diff --git a/netwerk/cookie/CookieServiceParent.h b/netwerk/cookie/CookieServiceParent.h index 45b46883fb..9859879b05 100644 --- a/netwerk/cookie/CookieServiceParent.h +++ b/netwerk/cookie/CookieServiceParent.h @@ -70,11 +70,12 @@ class CookieServiceParent : public PCookieServiceParent { const bool& aStorageAccessPermissionGranted, const uint32_t& aRejectedReason, const bool& aIsSafeTopLevelNav, const bool& aIsSameSiteForeign, const bool& aHadCrossSiteRedirects, - const OriginAttributes& aAttrs, GetCookieListResolver&& aResolve); + nsTArray<OriginAttributes>&& aAttrsList, + GetCookieListResolver&& aResolve); - static void SerializeCookieList(const nsTArray<Cookie*>& aFoundCookieList, - nsTArray<CookieStruct>& aCookiesList, - nsIURI* aHostURI); + static void SerializeCookieListTable( + const nsTArray<Cookie*>& aFoundCookieList, + nsTArray<CookieStructTable>& aCookiesListTable, nsIURI* aHostURI); nsCOMPtr<nsIEffectiveTLDService> mTLDService; RefPtr<CookieService> mCookieService; diff --git a/netwerk/cookie/CookieStorage.cpp b/netwerk/cookie/CookieStorage.cpp index cc827a2372..fd0af6129b 100644 --- a/netwerk/cookie/CookieStorage.cpp +++ b/netwerk/cookie/CookieStorage.cpp @@ -7,6 +7,7 @@ #include "CookieCommons.h" #include "CookieLogging.h" #include "CookieNotification.h" +#include "mozilla/net/MozURL_ffi.h" #include "nsCOMPtr.h" #include "nsICookieNotification.h" #include "CookieStorage.h" @@ -334,14 +335,83 @@ void CookieStorage::RemoveCookiesWithOriginAttributes( } } +/* static */ bool CookieStorage::isIPv6BaseDomain( + const nsACString& aBaseDomain) { + return aBaseDomain.Contains(':'); +} + +/* static */ bool CookieStorage::SerializeIPv6BaseDomain( + nsACString& aBaseDomain) { + bool hasStartBracket = aBaseDomain.First() == '['; + bool hasEndBracket = aBaseDomain.Last() == ']'; + + // If only start or end bracket exists host is malformed. + if (hasStartBracket != hasEndBracket) { + return false; + } + + // If the base domain is not in URL format (e.g. [::1]) add brackets so we + // can use rusturl_parse_ipv6addr(). + if (!hasStartBracket) { + aBaseDomain.Insert('[', 0); + aBaseDomain.Append(']'); + } + + // Serialize base domain to "zero abbreviation" and lower-case hex + // representation. + nsAutoCString baseDomain; + nsresult rv = (nsresult)rusturl_parse_ipv6addr(&aBaseDomain, &baseDomain); + NS_ENSURE_SUCCESS(rv, false); + + // Strip brackets to match principal representation. + aBaseDomain = Substring(baseDomain, 1, baseDomain.Length() - 2); + + return true; +} + void CookieStorage::RemoveCookiesFromExactHost( const nsACString& aHost, const nsACString& aBaseDomain, const OriginAttributesPattern& aPattern) { + // Intermediate fix until Bug 1882259 is resolved. + // Bug 1860033 - Cookies do not serialize IPv6 host / base domain in contrast + // to principals. To allow deletion by principal serialize before comparison. + // We check the base domain since it is used as the CookieList key and equals + // the normalized (ASCII) host for IP addresses + // (it is equal to the CookieService::NormalizeHost() output). + nsAutoCString removeBaseDomain; + bool isIPv6 = isIPv6BaseDomain(aBaseDomain); + if (isIPv6) { + MOZ_ASSERT(!aBaseDomain.IsEmpty()); + // Copy base domain since argument is immutable. + removeBaseDomain = aBaseDomain; + if (NS_WARN_IF(!SerializeIPv6BaseDomain(removeBaseDomain))) { + // Return on malformed base domains. + return; + } + } + // Iterate the hash table of CookieEntry. for (auto iter = mHostTable.Iter(); !iter.Done(); iter.Next()) { CookieEntry* entry = iter.Get(); - if (!aBaseDomain.Equals(entry->mBaseDomain)) { + // IPv6 host / base domain cookies + if (isIPv6) { + // If we look for a IPv6 cookie skip non-IPv6 cookie entries. + if (!isIPv6BaseDomain(entry->mBaseDomain)) { + continue; + } + // Serialize IPv6 base domains before comparison. + // Copy base domain since argument is immutable. + nsAutoCString entryBaseDomain; + entryBaseDomain = entry->mBaseDomain; + if (NS_WARN_IF(!SerializeIPv6BaseDomain(entryBaseDomain))) { + continue; + } + if (!removeBaseDomain.Equals(entryBaseDomain)) { + continue; + } + // Non-IPv6 cookies + } else if (!aBaseDomain.Equals(entry->mBaseDomain)) { continue; } @@ -354,7 +424,9 @@ void CookieStorage::RemoveCookiesFromExactHost( CookieListIter iter(entry, i - 1); RefPtr<Cookie> cookie = iter.Cookie(); - if (!aHost.Equals(cookie->RawHost())) { + // For IP addresses (ASCII normalized) host == baseDomain, we checked + // equality already. + if (!isIPv6 && !aHost.Equals(cookie->RawHost())) { continue; } diff --git a/netwerk/cookie/CookieStorage.h b/netwerk/cookie/CookieStorage.h index 3836edbb9c..a85a16cd5e 100644 --- a/netwerk/cookie/CookieStorage.h +++ b/netwerk/cookie/CookieStorage.h @@ -200,6 +200,14 @@ class CookieStorage : public nsIObserver, public nsSupportsWeakReference { uint16_t aMaxNumberOfCookies, int64_t aCookiePurgeAge) = 0; + // This method returns true if aBaseDomain contains any colons since only + // IPv6 baseDomains may contain colons. + static bool isIPv6BaseDomain(const nsACString& aBaseDomain); + + // Serialize aBaseDomain e.g. apply "zero abbreveation" (::), use single + // zeros and remove brackets to match principal base domain representation. + static bool SerializeIPv6BaseDomain(nsACString& aBaseDomain); + virtual void CollectCookieJarSizeData() = 0; int64_t mCookieOldestTime{INT64_MAX}; diff --git a/netwerk/cookie/PCookieService.ipdl b/netwerk/cookie/PCookieService.ipdl index f8ec4c8d0f..053b8f35cc 100644 --- a/netwerk/cookie/PCookieService.ipdl +++ b/netwerk/cookie/PCookieService.ipdl @@ -47,14 +47,13 @@ parent: bool isSafeTopLevelNav, bool isSameSiteForeign, bool hadCrossSiteRedirects, - OriginAttributes attrs) - returns (CookieStruct[] cookies); + OriginAttributes[] attrsList) + returns (CookieStructTable[] cookies); async __delete__(); child: - async TrackCookiesLoad(CookieStruct[] cookiesList, - OriginAttributes attrs); + async TrackCookiesLoad(CookieStructTable[] cookiesListTable); async RemoveCookie(CookieStruct cookie, OriginAttributes attrs); diff --git a/netwerk/cookie/test/browser/browser_cookie_purge_sync.js b/netwerk/cookie/test/browser/browser_cookie_purge_sync.js index 186797d058..42614f0ca6 100644 --- a/netwerk/cookie/test/browser/browser_cookie_purge_sync.js +++ b/netwerk/cookie/test/browser/browser_cookie_purge_sync.js @@ -29,7 +29,7 @@ add_setup(async function () { function waitForNotificationPromise(notification, expected) { return new Promise(resolve => { - function observer(subject, topic, data) { + function observer() { is(content.document.cookie, expected); Services.obs.removeObserver(observer, notification); resolve(); @@ -70,7 +70,7 @@ add_task(async function test_purge_sync_batch_and_deleted() { () => content.document.cookie == "", "cookie did not expire in time", 200 - ).catch(msg => { + ).catch(() => { is(false, "Cookie did not expire in time"); }); }); diff --git a/netwerk/cookie/test/browser/browser_indexedDB.js b/netwerk/cookie/test/browser/browser_indexedDB.js index 7f417077eb..d5d47c1883 100644 --- a/netwerk/cookie/test/browser/browser_indexedDB.js +++ b/netwerk/cookie/test/browser/browser_indexedDB.js @@ -42,7 +42,7 @@ CookiePolicyHelper.runTest("IndexedDB in workers", { } }; - worker.onerror = function (e) { + worker.onerror = function () { reject(); }; }); @@ -76,7 +76,7 @@ CookiePolicyHelper.runTest("IndexedDB in workers", { } }; - worker.onerror = function (e) { + worker.onerror = function () { reject(); }; }); diff --git a/netwerk/cookie/test/unit/test_rawSameSite.js b/netwerk/cookie/test/unit/test_rawSameSite.js index dc739ef852..9a933ce5bf 100644 --- a/netwerk/cookie/test/unit/test_rawSameSite.js +++ b/netwerk/cookie/test/unit/test_rawSameSite.js @@ -88,7 +88,7 @@ add_task(async _ => { let test = tests[i]; let promise = new Promise(resolve => { - function observer(subject, topic, data) { + function observer() { Services.obs.removeObserver(observer, "cookie-saved-on-disk"); resolve(); } diff --git a/netwerk/dns/GetAddrInfo.cpp b/netwerk/dns/GetAddrInfo.cpp index 0dd1f0099a..352a01226e 100644 --- a/netwerk/dns/GetAddrInfo.cpp +++ b/netwerk/dns/GetAddrInfo.cpp @@ -579,6 +579,8 @@ nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags, return NS_ERROR_NOT_IMPLEMENTED; } +void DNSThreadShutdown() {} + #endif // MOZ_NO_HTTPS_IMPL } // namespace mozilla::net diff --git a/netwerk/dns/GetAddrInfo.h b/netwerk/dns/GetAddrInfo.h index e8dc095415..c8b4ebae69 100644 --- a/netwerk/dns/GetAddrInfo.h +++ b/netwerk/dns/GetAddrInfo.h @@ -67,6 +67,8 @@ nsresult GetAddrInfoInit(); */ nsresult GetAddrInfoShutdown(); +void DNSThreadShutdown(); + /** * Resolves a HTTPS record. Will check overrides before calling the * native OS implementation. diff --git a/netwerk/dns/PlatformDNSAndroid.cpp b/netwerk/dns/PlatformDNSAndroid.cpp index 78a944777f..171797b938 100644 --- a/netwerk/dns/PlatformDNSAndroid.cpp +++ b/netwerk/dns/PlatformDNSAndroid.cpp @@ -151,4 +151,6 @@ nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags, return NS_OK; } +void DNSThreadShutdown() {} + } // namespace mozilla::net diff --git a/netwerk/dns/PlatformDNSUnix.cpp b/netwerk/dns/PlatformDNSUnix.cpp index dedbe337df..c7f57fcdda 100644 --- a/netwerk/dns/PlatformDNSUnix.cpp +++ b/netwerk/dns/PlatformDNSUnix.cpp @@ -9,6 +9,7 @@ #include "nsIDNSService.h" #include "mozilla/Maybe.h" #include "mozilla/StaticPrefs_network.h" +#include "mozilla/ThreadLocal.h" #include <stdio.h> #include <stdlib.h> @@ -18,6 +19,10 @@ namespace mozilla::net { +#if defined(HAVE_RES_NINIT) +MOZ_THREAD_LOCAL(struct __res_state*) sThreadRes; +#endif + #define LOG(msg, ...) \ MOZ_LOG(gGetAddrInfoLog, LogLevel::Debug, ("[DNS]: " msg, ##__VA_ARGS__)) @@ -33,16 +38,28 @@ nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags, return NS_ERROR_UNKNOWN_HOST; } +#if defined(HAVE_RES_NINIT) + if (!sThreadRes.get()) { + UniquePtr<struct __res_state> resState(new struct __res_state); + memset(resState.get(), 0, sizeof(struct __res_state)); + if (int ret = res_ninit(resState.get())) { + LOG("res_ninit failed: %d", ret); + return NS_ERROR_UNKNOWN_HOST; + } + sThreadRes.set(resState.release()); + } +#endif + LOG("resolving %s\n", host.get()); // Perform the query rv = packet.FillBuffer( [&](unsigned char response[DNSPacket::MAX_SIZE]) -> int { int len = 0; -#if defined(XP_LINUX) - len = res_nquery(&_res, host.get(), ns_c_in, +#if defined(HAVE_RES_NINIT) + len = res_nquery(sThreadRes.get(), host.get(), ns_c_in, nsIDNSService::RESOLVE_TYPE_HTTPSSVC, response, DNSPacket::MAX_SIZE); -#elif defined(XP_MACOSX) +#else len = res_query(host.get(), ns_c_in, nsIDNSService::RESOLVE_TYPE_HTTPSSVC, response, DNSPacket::MAX_SIZE); @@ -60,4 +77,16 @@ nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags, return ParseHTTPSRecord(host, packet, aResult, aTTL); } +void DNSThreadShutdown() { +#if defined(HAVE_RES_NINIT) + auto* res = sThreadRes.get(); + if (!res) { + return; + } + + sThreadRes.set(nullptr); + res_nclose(res); +#endif +} + } // namespace mozilla::net diff --git a/netwerk/dns/PlatformDNSWin.cpp b/netwerk/dns/PlatformDNSWin.cpp index 8b5539d7de..42f1483ec3 100644 --- a/netwerk/dns/PlatformDNSWin.cpp +++ b/netwerk/dns/PlatformDNSWin.cpp @@ -137,4 +137,6 @@ nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags, return NS_OK; } +void DNSThreadShutdown() {} + } // namespace mozilla::net diff --git a/netwerk/dns/TRR.cpp b/netwerk/dns/TRR.cpp index aad65ab809..66bca3f423 100644 --- a/netwerk/dns/TRR.cpp +++ b/netwerk/dns/TRR.cpp @@ -616,6 +616,7 @@ TRR::OnPush(nsIHttpChannel* associated, nsIHttpChannel* pushed) { } RefPtr<TRR> trr = new TRR(mHostResolver, mPB); + trr->SetPurpose(mPurpose); return trr->ReceivePush(pushed, mRec); } @@ -901,6 +902,7 @@ nsresult TRR::FollowCname(nsIChannel* aChannel) { mCnameLoop)); RefPtr<TRR> trr = new TRR(mHostResolver, mRec, mCname, mType, mCnameLoop, mPB); + trr->SetPurpose(mPurpose); if (!TRRService::Get()) { return NS_ERROR_FAILURE; } diff --git a/netwerk/dns/effective_tld_names.dat b/netwerk/dns/effective_tld_names.dat index c2b813fa68..21df77442b 100644 --- a/netwerk/dns/effective_tld_names.dat +++ b/netwerk/dns/effective_tld_names.dat @@ -6710,7 +6710,7 @@ org.zw // newGTLDs -// List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2024-03-06T15:14:58Z +// List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2024-03-28T15:13:37Z // This list is auto-generated, don't edit it manually. // aaa : American Automobile Association, Inc. // https://www.iana.org/domains/root/db/aaa.html @@ -6988,10 +6988,6 @@ auto // https://www.iana.org/domains/root/db/autos.html autos -// avianca : Avianca Inc. -// https://www.iana.org/domains/root/db/avianca.html -avianca - // aws : AWS Registry LLC // https://www.iana.org/domains/root/db/aws.html aws @@ -13480,6 +13476,10 @@ whitesnow.jp zombie.jp heteml.net +// GoDaddy Registry : https://registry.godaddy +// Submitted by Rohan Durrant <tldns@registry.godaddy> +graphic.design + // GOV.UK Platform as a Service : https://www.cloud.service.gov.uk/ // Submitted by Tom Whitwell <gov-uk-paas-support@digital.cabinet-office.gov.uk> cloudapps.digital @@ -13737,7 +13737,7 @@ biz.at info.at // info.cx : http://info.cx -// Submitted by Jacob Slater <whois@igloo.to> +// Submitted by June Slater <whois@igloo.to> info.cx // Interlegis : http://www.interlegis.leg.br @@ -13786,6 +13786,10 @@ iopsys.se // Submitted by Matthew Hardeman <mhardeman@ipifony.com> ipifony.net +// ir.md : https://nic.ir.md +// Submitted by Ali Soizi <info@nic.ir.md> +ir.md + // IServ GmbH : https://iserv.de // Submitted by Mario Hoberg <info@iserv.de> iservschule.de @@ -14141,7 +14145,7 @@ co.pl // Managed by Corporate Domains // Microsoft Azure : https://home.azure *.azurecontainer.io -*.cloudapp.azure.com +cloudapp.azure.com azure-api.net azureedge.net azurefd.net @@ -14255,6 +14259,10 @@ nh-serv.co.uk // Submitted by Jeff Wheelhouse <support@nearlyfreespeech.net> nfshost.com +// NFT.Storage : https://nft.storage/ +// Submitted by Vasco Santos <vasco.santos@protocol.ai> or <support@nft.storage> +ipfs.nftstorage.link + // Noop : https://noop.app // Submitted by Nathaniel Schweinberg <noop@rearc.io> *.developer.app diff --git a/netwerk/dns/nsEffectiveTLDService.cpp b/netwerk/dns/nsEffectiveTLDService.cpp index fafbc296d5..fc9e8c0692 100644 --- a/netwerk/dns/nsEffectiveTLDService.cpp +++ b/netwerk/dns/nsEffectiveTLDService.cpp @@ -74,7 +74,7 @@ NS_IMETHODIMP nsEffectiveTLDService::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) { /** - * Signal sent from netwerk/dns/PublicSuffixList.jsm + * Signal sent from netwerk/dns/PublicSuffixList.sys.mjs * aSubject is the nsIFile object for dafsa.bin * aData is the absolute path to the dafsa.bin file (not used) */ diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index ccd6dca57b..ad28cbb284 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -3,6 +3,7 @@ * 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> @@ -137,6 +138,24 @@ class nsResState { #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"; @@ -252,6 +271,8 @@ nsresult nsHostResolver::Init() MOZ_NO_THREAD_SAFETY_ANALYSIS { 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; diff --git a/netwerk/dns/nsIDNService.cpp b/netwerk/dns/nsIDNService.cpp index 3db169d3af..6a87c8ee06 100644 --- a/netwerk/dns/nsIDNService.cpp +++ b/netwerk/dns/nsIDNService.cpp @@ -10,6 +10,8 @@ #include "nsReadableUtils.h" #include "nsCRT.h" #include "nsServiceManagerUtils.h" +#include "nsString.h" +#include "nsStringFwd.h" #include "nsUnicharUtils.h" #include "nsUnicodeProperties.h" #include "harfbuzz/hb.h" @@ -286,12 +288,35 @@ nsresult nsIDNService::ACEtoUTF8(const nsACString& input, nsACString& _retval, input.EndReading(end); _retval.Truncate(); + if (input.IsEmpty()) { + return NS_OK; + } + + nsAutoCString tld; + nsCString::const_iterator it = end, tldEnd = end; + --it; + if (it != start && *it == (char16_t)'.') { + // This is an FQDN (ends in .) + // Skip this dot to extract the TLD + tldEnd = it; + --it; + } + // Find last . and compute TLD + while (it != start) { + if (*it == (char16_t)'.') { + ++it; + tld.Assign(Substring(it, tldEnd)); + break; + } + --it; + } + // loop and decode nodes while (start != end) { len++; if (*start++ == '.') { nsDependentCSubstring origLabel(input, offset, len - 1); - if (NS_FAILED(decodeACE(origLabel, decodedBuf, flag))) { + if (NS_FAILED(decodeACE(origLabel, decodedBuf, flag, tld))) { // If decoding failed, use the original input sequence // for this label. _retval.Append(origLabel); @@ -307,7 +332,7 @@ nsresult nsIDNService::ACEtoUTF8(const nsACString& input, nsACString& _retval, // decode the last node if (len) { nsDependentCSubstring origLabel(input, offset, len); - if (NS_FAILED(decodeACE(origLabel, decodedBuf, flag))) { + if (NS_FAILED(decodeACE(origLabel, decodedBuf, flag, tld))) { _retval.Append(origLabel); } else { _retval.Append(decodedBuf); @@ -343,8 +368,7 @@ NS_IMETHODIMP nsIDNService::IsACE(const nsACString& input, bool* _retval) { return NS_OK; } -NS_IMETHODIMP nsIDNService::Normalize(const nsACString& input, - nsACString& output) { +nsresult nsIDNService::Normalize(const nsACString& input, nsACString& output) { // protect against bogus input NS_ENSURE_TRUE(IsUtf8(input), NS_ERROR_UNEXPECTED); @@ -562,7 +586,7 @@ nsresult nsIDNService::stringPrepAndACE(const nsAString& in, nsACString& out, return NS_OK; } - if (flag == eStringPrepForUI && NS_SUCCEEDED(rv) && isLabelSafe(in)) { + if (flag == eStringPrepForUI && NS_SUCCEEDED(rv) && isLabelSafe(in, u""_ns)) { CopyUTF16toUTF8(strPrep, out); return NS_OK; } @@ -598,7 +622,7 @@ void nsIDNService::normalizeFullStops(nsAString& s) { } nsresult nsIDNService::decodeACE(const nsACString& in, nsACString& out, - stringPrepFlag flag) { + stringPrepFlag flag, const nsACString& aTLD) { bool isAce; IsACE(in, &isAce); if (!isAce) { @@ -610,7 +634,9 @@ nsresult nsIDNService::decodeACE(const nsACString& in, nsACString& out, nsresult result = IDNA2008ToUnicode(in, utf16); NS_ENSURE_SUCCESS(result, result); - if (flag != eStringPrepForUI || isLabelSafe(utf16)) { + NS_ConvertUTF8toUTF16 tld(aTLD); + + if (flag != eStringPrepForUI || isLabelSafe(utf16, tld)) { CopyUTF16toUTF8(utf16, out); } else { out.Assign(in); @@ -652,17 +678,21 @@ enum ScriptCombo : int32_t { } // namespace mozilla::net -bool nsIDNService::isLabelSafe(const nsAString& label) { - AutoReadLock lock(mLock); +bool nsIDNService::isLabelSafe(const nsAString& label, const nsAString& tld) { + restrictionProfile profile{eASCIIOnlyProfile}; + { + AutoReadLock lock(mLock); - if (!isOnlySafeChars(PromiseFlatString(label), mIDNBlocklist)) { - return false; - } + if (!isOnlySafeChars(PromiseFlatString(label), mIDNBlocklist)) { + return false; + } - // We should never get here if the label is ASCII - NS_ASSERTION(!IsAscii(label), "ASCII label in IDN checking"); - if (mRestrictionProfile == eASCIIOnlyProfile) { - return false; + // We should never get here if the label is ASCII + NS_ASSERTION(!IsAscii(label), "ASCII label in IDN checking"); + if (mRestrictionProfile == eASCIIOnlyProfile) { + return false; + } + profile = mRestrictionProfile; } nsAString::const_iterator current, end; @@ -697,7 +727,7 @@ bool nsIDNService::isLabelSafe(const nsAString& label) { Script script = UnicodeProperties::GetScriptCode(ch); if (script != Script::COMMON && script != Script::INHERITED && script != lastScript) { - if (illegalScriptCombo(script, savedScript)) { + if (illegalScriptCombo(profile, script, savedScript)) { return false; } } @@ -708,11 +738,39 @@ bool nsIDNService::isLabelSafe(const nsAString& label) { return false; } + Script nextScript = Script::INVALID; + if (current != end) { + nextScript = UnicodeProperties::GetScriptCode(*current); + } + + if (ch == 0x30FB && + (lastScript == Script::LATIN || nextScript == Script::LATIN)) { + return false; + } + if (ch == 0x307 && (previousChar == 'i' || previousChar == 'j' || previousChar == 'l')) { return false; } + // U+00B7 is only allowed on Catalan domains between two l's. + if (ch == 0xB7 && (!tld.EqualsLiteral("cat") || previousChar != 'l' || + current == end || *current != 'l')) { + return false; + } + + // Disallow Icelandic confusables for domains outside Icelandic and Faroese + // ccTLD (.is, .fo) + if ((ch == 0xFE || ch == 0xF0) && !tld.EqualsLiteral("is") && + !tld.EqualsLiteral("fo")) { + return false; + } + + // Block single/double-quote-like characters. + if (ch == 0x2BB || ch == 0x2BC) { + return false; + } + // Check for mixed numbering systems auto genCat = GetGeneralCategory(ch); if (genCat == HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER) { @@ -834,7 +892,8 @@ static const ScriptCombo scriptComboTable[13][9] = { /* KORE */ {FAIL, FAIL, FAIL, KORE, KORE, FAIL, FAIL, KORE, FAIL}, /* HNLT */ {CHNA, FAIL, FAIL, KORE, HNLT, JPAN, JPAN, HNLT, FAIL}}; -bool nsIDNService::illegalScriptCombo(Script script, ScriptCombo& savedScript) { +bool nsIDNService::illegalScriptCombo(restrictionProfile profile, Script script, + ScriptCombo& savedScript) { if (savedScript == ScriptCombo::UNSET) { savedScript = findScriptIndex(script); return false; @@ -849,7 +908,6 @@ bool nsIDNService::illegalScriptCombo(Script script, ScriptCombo& savedScript) { * In the Moderately Restrictive profile Latin mixed with any other * single script is allowed. */ - return ((savedScript == OTHR && - mRestrictionProfile == eHighlyRestrictiveProfile) || + return ((savedScript == OTHR && profile == eHighlyRestrictiveProfile) || savedScript == FAIL); } diff --git a/netwerk/dns/nsIDNService.h b/netwerk/dns/nsIDNService.h index 1e90191326..6e5900e842 100644 --- a/netwerk/dns/nsIDNService.h +++ b/netwerk/dns/nsIDNService.h @@ -16,6 +16,7 @@ #include "mozilla/UniquePtr.h" #include "nsString.h" +#include "nsStringFwd.h" class nsIPrefBranch; @@ -83,8 +84,8 @@ class nsIDNService final : public nsIIDNService { * display, the output is the same as the input * @see isLabelSafe */ - nsresult decodeACE(const nsACString& in, nsACString& out, - stringPrepFlag flag); + nsresult decodeACE(const nsACString& in, nsACString& out, stringPrepFlag flag, + const nsACString& tld); /** * Convert complete domain names between UTF8 and ACE and vice versa @@ -98,6 +99,8 @@ class nsIDNService final : public nsIIDNService { nsresult ACEtoUTF8(const nsACString& input, nsACString& _retval, stringPrepFlag flag); + nsresult Normalize(const nsACString& input, nsACString& output); + void prefsChanged(const char* pref); static void PrefChanged(const char* aPref, void* aSelf) { @@ -132,7 +135,19 @@ class nsIDNService final : public nsIIDNService { * Both simplified-only and traditional-only Chinese characters * XXX this test was disabled by bug 857481 */ - bool isLabelSafe(const nsAString& label) MOZ_EXCLUDES(mLock); + bool isLabelSafe(const nsAString& label, const nsAString& tld) + MOZ_EXCLUDES(mLock); + + /** + * Restriction-level Detection profiles defined in UTR 39 + * http://www.unicode.org/reports/tr39/#Restriction_Level_Detection, + * and selected by the pref network.IDN.restriction_profile + */ + enum restrictionProfile { + eASCIIOnlyProfile, + eHighlyRestrictiveProfile, + eModeratelyRestrictiveProfile + }; /** * Determine whether a combination of scripts in a single label is @@ -148,9 +163,9 @@ class nsIDNService final : public nsIIDNService { * For the "Moderately restrictive" profile, Latin is also allowed * with other scripts except Cyrillic and Greek */ - bool illegalScriptCombo(mozilla::intl::Script script, - mozilla::net::ScriptCombo& savedScript) - MOZ_REQUIRES_SHARED(mLock); + bool illegalScriptCombo(restrictionProfile profile, + mozilla::intl::Script script, + mozilla::net::ScriptCombo& savedScript); /** * Convert a DNS label from ASCII to Unicode using IDNA2008 @@ -173,16 +188,6 @@ class nsIDNService final : public nsIIDNService { // guarded by mLock nsTArray<mozilla::net::BlocklistRange> mIDNBlocklist MOZ_GUARDED_BY(mLock); - /** - * Restriction-level Detection profiles defined in UTR 39 - * http://www.unicode.org/reports/tr39/#Restriction_Level_Detection, - * and selected by the pref network.IDN.restriction_profile - */ - enum restrictionProfile { - eASCIIOnlyProfile, - eHighlyRestrictiveProfile, - eModeratelyRestrictiveProfile - }; // guarded by mLock; restrictionProfile mRestrictionProfile MOZ_GUARDED_BY(mLock){ eASCIIOnlyProfile}; diff --git a/netwerk/dns/nsIIDNService.idl b/netwerk/dns/nsIIDNService.idl index 47ef561237..218e64a6e2 100644 --- a/netwerk/dns/nsIIDNService.idl +++ b/netwerk/dns/nsIIDNService.idl @@ -43,12 +43,6 @@ interface nsIIDNService : nsISupports boolean isACE(in ACString input); /** - * Performs the unicode normalization needed for hostnames in IDN, - * for callers that want early normalization. - */ - AUTF8String normalize(in AUTF8String input); - - /** * Normalizes and converts a host to UTF-8 if the host is in the IDN * whitelist, otherwise converts it to ACE. This is useful for display * purposes and to ensure an encoding consistent with nsIURI::GetHost(). diff --git a/netwerk/dns/tests/unit/test_PublicSuffixList.js b/netwerk/dns/tests/unit/test_PublicSuffixList.js index ad61abea8e..a0d837e465 100644 --- a/netwerk/dns/tests/unit/test_PublicSuffixList.js +++ b/netwerk/dns/tests/unit/test_PublicSuffixList.js @@ -71,7 +71,7 @@ const downloadToDiskBackup = CLIENT.attachments.downloadToDisk; // returns a fake fileURI and sends a signal with filePath and no nsifile function mockDownloadToDisk() { downloadToDiskCalled = false; - CLIENT.attachments.downloadToDisk = async rec => { + CLIENT.attachments.downloadToDisk = async () => { downloadToDiskCalled = true; return `file://${mockedFilePath}`; // Create a fake file URI }; diff --git a/netwerk/docs/captive_portals.md b/netwerk/docs/captive_portals.md index fecba8f913..6606088b54 100644 --- a/netwerk/docs/captive_portals.md +++ b/netwerk/docs/captive_portals.md @@ -26,7 +26,7 @@ The [CaptivePortalService](https://searchfox.org/mozilla-central/source/netwerk/ - A captive portal was detected, and internet connectivity is not currently available. - A [captive portal notification bar](https://searchfox.org/mozilla-central/source/browser/base/content/browser-captivePortal.js) might be displayed to the user. -The Captive portal service uses [CaptiveDetect.sys.mjs](https://searchfox.org/mozilla-central/source/toolkit/components/captivedetect/CaptiveDetect.jsm) to perform the checks, which in turn uses XMLHttpRequest. +The Captive portal service uses [CaptiveDetect.sys.mjs](https://searchfox.org/mozilla-central/source/toolkit/components/captivedetect/CaptiveDetect.sys.mjs) to perform the checks, which in turn uses XMLHttpRequest. This request needs to be exempted from HTTPS upgrades, DNS over HTTPS, and many new browser features in order to function as expected. ```{note} diff --git a/netwerk/docs/dns/dns-over-https-trr.md b/netwerk/docs/dns/dns-over-https-trr.md index cf025a1e60..7dfcff7dd7 100644 --- a/netwerk/docs/dns/dns-over-https-trr.md +++ b/netwerk/docs/dns/dns-over-https-trr.md @@ -142,7 +142,7 @@ Some domains will never be resolved via TRR. This includes: A small set of TRR providers are only available on certain networks. -Detection is performed in DoHHeuristics.jsm followed by a call to +Detection is performed in DoHHeuristics.sys.mjs followed by a call to _TRRService::SetDetectedURI_. This causes Firefox to use the network specific TRR provider until a network change occurs. diff --git a/netwerk/docs/url_parsers.md b/netwerk/docs/url_parsers.md index a0b978a2b1..9fa25db1d9 100644 --- a/netwerk/docs/url_parsers.md +++ b/netwerk/docs/url_parsers.md @@ -67,7 +67,7 @@ To change a URI the consumer must call `nsIURI.mutate()` which returns a `nsIMut - [nsStandardURL](https://searchfox.org/mozilla-central/source/netwerk/base/nsStandardURL.h) - [SubstitutingURL](https://searchfox.org/mozilla-central/source/netwerk/protocol/res/SubstitutingURL.h) - overrides nsStandardURL::GetFile to provide nsIFile resolution. - - This allows us to map URLs such as `resource://gre/actors/RemotePageChild.jsm` to the actual file on the disk. + - This allows us to map URLs such as `resource://gre/actors/RemotePageChild.sys.mjs` to the actual file on the disk. - [nsMozIconURI](https://searchfox.org/mozilla-central/source/image/decoders/icon/nsIconURI.h) - Used to represent icon URLs - [nsSimpleURI](https://searchfox.org/mozilla-central/source/netwerk/base/nsSimpleURI.h) diff --git a/netwerk/ipc/DocumentLoadListener.cpp b/netwerk/ipc/DocumentLoadListener.cpp index ca1f59e884..d849eab750 100644 --- a/netwerk/ipc/DocumentLoadListener.cpp +++ b/netwerk/ipc/DocumentLoadListener.cpp @@ -303,12 +303,12 @@ class ParentProcessDocumentOpenInfo final : public nsDocumentOpenInfo, nsresult rv = nsDocumentOpenInfo::OnStartRequest(request); - // If we didn't find a content handler, - // and we don't have a listener, then just forward to our - // default listener. This happens when the channel is in - // an error state, and we want to just forward that on to be - // handled in the content process. - if (NS_SUCCEEDED(rv) && !mUsedContentHandler && !m_targetStreamListener) { + // If we didn't find a content handler, and we don't have a listener, then + // just forward to our default listener. This happens when the channel is in + // an error state, and we want to just forward that on to be handled in the + // content process, or when DONT_RETARGET is set. + if ((NS_SUCCEEDED(rv) || rv == NS_ERROR_WONT_HANDLE_CONTENT) && + !mUsedContentHandler && !m_targetStreamListener) { m_targetStreamListener = mListener; return m_targetStreamListener->OnStartRequest(request); } @@ -340,6 +340,17 @@ class ParentProcessDocumentOpenInfo final : public nsDocumentOpenInfo, nsresult OnObjectStartRequest(nsIRequest* request) { LOG(("ParentProcessDocumentOpenInfo OnObjectStartRequest [this=%p]", this)); + + // If this load will be treated as a document load, run through + // nsDocumentOpenInfo for consistency with other document loads. + // + // If the dom.navigation.object_embed.allow_retargeting pref is enabled, + // this may lead to the resource being downloaded. + if (nsCOMPtr<nsIChannel> channel = do_QueryInterface(request); + channel && channel->IsDocument()) { + return OnDocumentStartRequest(request); + } + // Just redirect to the nsObjectLoadingContent in the content process. m_targetStreamListener = mListener; return m_targetStreamListener->OnStartRequest(request); @@ -815,11 +826,9 @@ auto DocumentLoadListener::Open(nsDocShellLoadState* aLoadState, } // Recalculate the openFlags, matching the logic in use in Content process. - // NOTE: The only case not handled here to mirror Content process is - // redirecting to re-use the channel. MOZ_ASSERT(!aLoadState->GetPendingRedirectedChannel()); - uint32_t openFlags = - nsDocShell::ComputeURILoaderFlags(loadingContext, aLoadState->LoadType()); + uint32_t openFlags = nsDocShell::ComputeURILoaderFlags( + loadingContext, aLoadState->LoadType(), mIsDocumentLoad); RefPtr<ParentProcessDocumentOpenInfo> openInfo = new ParentProcessDocumentOpenInfo(mParentChannelListener, openFlags, @@ -2377,8 +2386,8 @@ bool DocumentLoadListener::MaybeHandleLoadErrorWithURIFixup(nsresult aStatus) { // we can downgrade the scheme to HTTP again. bool isHTTPSFirstFixup = false; if (!newURI) { - newURI = nsHTTPSOnlyUtils::PotentiallyDowngradeHttpsFirstRequest(mChannel, - aStatus); + newURI = + nsHTTPSOnlyUtils::PotentiallyDowngradeHttpsFirstRequest(this, aStatus); isHTTPSFirstFixup = true; } diff --git a/netwerk/ipc/DocumentLoadListener.h b/netwerk/ipc/DocumentLoadListener.h index 98aacc98f8..a8e4ffa7ab 100644 --- a/netwerk/ipc/DocumentLoadListener.h +++ b/netwerk/ipc/DocumentLoadListener.h @@ -300,6 +300,7 @@ class DocumentLoadListener : public nsIInterfaceRequestor, uint32_t GetLoadType() const { return mLoadStateLoadType; } bool IsDownload() const { return mIsDownload; } bool IsLoadingJSURI() const { return mIsLoadingJSURI; } + nsDOMNavigationTiming* GetTiming() { return mTiming; } mozilla::dom::LoadingSessionHistoryInfo* GetLoadingSessionHistoryInfo() { return mLoadingSessionHistoryInfo.get(); diff --git a/netwerk/ipc/NeckoChannelParams.ipdlh b/netwerk/ipc/NeckoChannelParams.ipdlh index 44af8d4808..c2948c7766 100644 --- a/netwerk/ipc/NeckoChannelParams.ipdlh +++ b/netwerk/ipc/NeckoChannelParams.ipdlh @@ -420,6 +420,7 @@ struct HttpConnectionInfoCloneArgs nsCString topWindowOrigin; bool isHttp3; bool webTransport; + uint64_t webTransportId; bool hasIPHintAddress; nsCString echConfig; ProxyInfoCloneArgs[] proxyInfo; @@ -454,6 +455,12 @@ struct CookieStruct uint8_t schemeMap; }; +struct CookieStructTable +{ + OriginAttributes attrs; + CookieStruct[] cookies; +}; + struct DocumentCreationArgs { bool uriModified; bool isEmbeddingBlockedError; diff --git a/netwerk/ipc/NeckoMessageUtils.h b/netwerk/ipc/NeckoMessageUtils.h index a15398330e..a0729a94a0 100644 --- a/netwerk/ipc/NeckoMessageUtils.h +++ b/netwerk/ipc/NeckoMessageUtils.h @@ -10,15 +10,15 @@ #include "ipc/EnumSerializer.h" #include "ipc/IPCMessageUtils.h" +#include "ipc/IPCMessageUtilsSpecializations.h" +#include "mozilla/net/DNS.h" #include "nsExceptionHandler.h" +#include "nsIDNSService.h" #include "nsIHttpChannel.h" +#include "nsITRRSkipReason.h" #include "nsPrintfCString.h" #include "nsString.h" #include "prio.h" -#include "mozilla/net/DNS.h" -#include "ipc/IPCMessageUtilsSpecializations.h" -#include "nsITRRSkipReason.h" -#include "nsIDNSService.h" namespace IPC { @@ -92,9 +92,9 @@ struct ParamTraits<mozilla::net::NetAddr> { #endif } else { if (XRE_IsParentProcess()) { - nsPrintfCString msg("%d", aParam.raw.family); - CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::UnknownNetAddrSocketFamily, msg); + CrashReporter::RecordAnnotationU32( + CrashReporter::Annotation::UnknownNetAddrSocketFamily, + aParam.raw.family); } MOZ_CRASH("Unknown socket family"); diff --git a/netwerk/ipc/NeckoParent.cpp b/netwerk/ipc/NeckoParent.cpp index 102b46a378..727aea4660 100644 --- a/netwerk/ipc/NeckoParent.cpp +++ b/netwerk/ipc/NeckoParent.cpp @@ -123,7 +123,7 @@ const char* NeckoParent::GetValidatedOriginAttributes( if (!aSerialized.IsNotNull()) { // If serialized is null, we cannot validate anything. We have to assume // that this requests comes from a SystemPrincipal. - aAttrs = OriginAttributes(false); + aAttrs = OriginAttributes(); } else { aAttrs = aSerialized.mOriginAttributes; } diff --git a/netwerk/metrics.yaml b/netwerk/metrics.yaml index 35388c7a73..641c1500a6 100644 --- a/netwerk/metrics.yaml +++ b/netwerk/metrics.yaml @@ -500,6 +500,21 @@ networking: - rjesup@mozilla.com expires: 130 + http_content_cssloader_ondatafinished_to_onstop_delay: + type: timing_distribution + time_unit: millisecond + description: > + The time between processing OnDataFinished and processing OnStopRequest for CSSLoader in the content process + bugs: + - https://bugzilla.mozilla.org/show_bug.cgi?id=1883391 + data_reviews: + - https://bugzilla.mozilla.org/show_bug.cgi?id=1883391 + data_sensitivity: + - technical + notification_emails: + - necko@mozilla.com + expires: 130 + http_1_download_throughput: type: custom_distribution unit: mbps @@ -1012,6 +1027,37 @@ networking: - kershaw@mozilla.com expires: never + proxy_info_type: + type: labeled_counter + description: > + The proxies configurations created in the browser session (SOCKSv4, SOCKSv5, HTTP, HTTPS) + bugs: + - https://bugzilla.mozilla.org/show_bug.cgi?id=1879848 + data_reviews: + - https://bugzilla.mozilla.org/show_bug.cgi?id=1879848 + data_sensitivity: + - technical + notification_emails: + - necko@mozilla.com + - manuel@mozilla.com + expires: 129 + labels: + - http + - https + # SOCKS4 Proxy + - socks4 + # SOCKS4a Proxy. Proxy resolves URL hostname + - socks4a + # SOCKS5 Proxy + - socks5 + # SOCKS5 Proxy. Proxy resolves URL hostname + # Use convention from curl for socks5 proxies that resolve the hostname + # https://curl.se/libcurl/c/CURLOPT_PROXY.html + - socks5h + # No proxy + - direct + - unknown + transaction_wait_time: type: timing_distribution time_unit: millisecond diff --git a/netwerk/mime/nsIMIMEService.idl b/netwerk/mime/nsIMIMEService.idl index 89cda79ee5..717f595c50 100644 --- a/netwerk/mime/nsIMIMEService.idl +++ b/netwerk/mime/nsIMIMEService.idl @@ -10,16 +10,6 @@ interface nsIMIMEInfo; interface nsIURI; interface nsIChannel; -%{C++ -#define NS_MIMESERVICE_CID \ -{ /* 03af31da-3109-11d3-8cd0-0060b0fc14a3 */ \ - 0x03af31da, \ - 0x3109, \ - 0x11d3, \ - {0x8c, 0xd0, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \ -} -%} - /** * The MIME service is responsible for mapping file extensions to MIME-types * (see RFC 2045). It also provides access to nsIMIMEInfo interfaces and diff --git a/netwerk/protocol/about/nsIAboutModule.idl b/netwerk/protocol/about/nsIAboutModule.idl index 7750dd2d4b..f35d9366e9 100644 --- a/netwerk/protocol/about/nsIAboutModule.idl +++ b/netwerk/protocol/about/nsIAboutModule.idl @@ -108,6 +108,5 @@ interface nsIAboutModule : nsISupports #define NS_ABOUT_MODULE_CONTRACTID "@mozilla.org/network/protocol/about;1" #define NS_ABOUT_MODULE_CONTRACTID_PREFIX NS_ABOUT_MODULE_CONTRACTID "?what=" -#define NS_ABOUT_MODULE_CONTRACTID_LENGTH 49 // strlen(NS_ABOUT_MODULE_CONTRACTID_PREFIX) %} diff --git a/netwerk/protocol/data/nsDataChannel.cpp b/netwerk/protocol/data/nsDataChannel.cpp index 87b00adea3..df40971e1c 100644 --- a/netwerk/protocol/data/nsDataChannel.cpp +++ b/netwerk/protocol/data/nsDataChannel.cpp @@ -8,6 +8,7 @@ #include "nsDataChannel.h" #include "mozilla/Base64.h" +#include "mozilla/dom/MimeType.h" #include "nsDataHandler.h" #include "nsIInputStream.h" #include "nsEscape.h" @@ -59,9 +60,10 @@ nsresult nsDataChannel::OpenContentStream(bool async, nsIInputStream** result, nsCString contentType, contentCharset; nsDependentCSubstring dataRange; + RefPtr<CMimeType> fullMimeType; bool lBase64; rv = nsDataHandler::ParsePathWithoutRef(path, contentType, &contentCharset, - lBase64, &dataRange, &mMimeType); + lBase64, &dataRange, &fullMimeType); if (NS_FAILED(rv)) return rv; // This will avoid a copy if nothing needs to be unescaped. @@ -103,6 +105,7 @@ nsresult nsDataChannel::OpenContentStream(bool async, nsIInputStream** result, SetContentType(contentType); SetContentCharset(contentCharset); + SetFullMimeType(std::move(fullMimeType)); mContentLength = contentLen; // notify "data-channel-opened" observers diff --git a/netwerk/protocol/data/nsDataChannel.h b/netwerk/protocol/data/nsDataChannel.h index d7313d66a0..f7700ff2b4 100644 --- a/netwerk/protocol/data/nsDataChannel.h +++ b/netwerk/protocol/data/nsDataChannel.h @@ -16,14 +16,10 @@ class nsDataChannel : public nsBaseChannel { public: explicit nsDataChannel(nsIURI* uri) { SetURI(uri); } - const nsACString& MimeType() const { return mMimeType; } - protected: [[nodiscard]] virtual nsresult OpenContentStream( bool async, nsIInputStream** result, nsIChannel** channel) override; - nsCString mMimeType; - private: nsresult MaybeSendDataChannelOpenNotification(); }; diff --git a/netwerk/protocol/data/nsDataHandler.cpp b/netwerk/protocol/data/nsDataHandler.cpp index d3a5743097..adb86bf484 100644 --- a/netwerk/protocol/data/nsDataHandler.cpp +++ b/netwerk/protocol/data/nsDataHandler.cpp @@ -161,7 +161,7 @@ nsresult nsDataHandler::ParsePathWithoutRef(const nsACString& aPath, nsCString* aContentCharset, bool& aIsBase64, nsDependentCSubstring* aDataBuffer, - nsCString* aMimeType) { + RefPtr<CMimeType>* aMimeType) { static constexpr auto kCharset = "charset"_ns; // This implements https://fetch.spec.whatwg.org/#data-url-processor @@ -200,18 +200,18 @@ nsresult nsDataHandler::ParsePathWithoutRef(const nsACString& aPath, // This also checks for instances of ;base64 in the middle of the MimeType. // This is against the current spec, but we're doing it because we have // historically seen webcompat issues relying on this (see bug 781693). - if (mozilla::UniquePtr<CMimeType> parsed = CMimeType::Parse(mimeType)) { + if (RefPtr<CMimeType> parsed = CMimeType::Parse(mimeType)) { parsed->GetEssence(aContentType); if (aContentCharset) { parsed->GetParameterValue(kCharset, *aContentCharset); } - if (aMimeType) { - parsed->Serialize(*aMimeType); - } if (parsed->IsBase64() && !StaticPrefs::network_url_strict_data_url_base64_placement()) { aIsBase64 = true; } + if (aMimeType) { + *aMimeType = std::move(parsed); + } } else { // "If mimeTypeRecord is failure, then set mimeTypeRecord to // text/plain;charset=US-ASCII." @@ -220,7 +220,8 @@ nsresult nsDataHandler::ParsePathWithoutRef(const nsACString& aPath, aContentCharset->AssignLiteral("US-ASCII"); } if (aMimeType) { - aMimeType->AssignLiteral("text/plain;charset=US-ASCII"); + *aMimeType = new CMimeType("text"_ns, "plain"_ns); + (*aMimeType)->SetParameterValue("charset"_ns, "US-ASCII"_ns); } } diff --git a/netwerk/protocol/data/nsDataHandler.h b/netwerk/protocol/data/nsDataHandler.h index 4796f0f453..499e73b220 100644 --- a/netwerk/protocol/data/nsDataHandler.h +++ b/netwerk/protocol/data/nsDataHandler.h @@ -6,6 +6,7 @@ #ifndef nsDataHandler_h___ #define nsDataHandler_h___ +#include "mozilla/dom/MimeType.h" #include "nsIProtocolHandler.h" #include "nsWeakReference.h" @@ -50,7 +51,7 @@ class nsDataHandler : public nsIProtocolHandler, [[nodiscard]] static nsresult ParsePathWithoutRef( const nsACString& aPath, nsCString& aContentType, nsCString* aContentCharset, bool& aIsBase64, - nsDependentCSubstring* aDataBuffer, nsCString* aMimeType = nullptr); + nsDependentCSubstring* aDataBuffer, RefPtr<CMimeType>* = nullptr); }; #endif /* nsDataHandler_h___ */ diff --git a/netwerk/protocol/http/AlternateServices.cpp b/netwerk/protocol/http/AlternateServices.cpp index a386206b6d..e0571f02ce 100644 --- a/netwerk/protocol/http/AlternateServices.cpp +++ b/netwerk/protocol/http/AlternateServices.cpp @@ -7,6 +7,7 @@ #include "HttpLog.h" #include "AlternateServices.h" +#include <algorithm> #include "LoadInfo.h" #include "mozilla/Atomics.h" #include "mozilla/StaticPrefs_network.h" @@ -87,16 +88,15 @@ void AltSvcMapping::ProcessHeader( ParsedHeaderValueListList parsedAltSvc(buf); int32_t numEntriesInHeader = parsedAltSvc.mValues.Length(); - // Only use one http3 version. - bool http3Found = false; - + nsTArray<RefPtr<AltSvcMapping>> h3Mappings; + nsTArray<RefPtr<AltSvcMapping>> otherMappings; for (uint32_t index = 0; index < parsedAltSvc.mValues.Length(); ++index) { uint32_t maxage = 86400; // default nsAutoCString hostname; nsAutoCString npnToken; int32_t portno = originPort; bool clearEntry = false; - bool isHttp3 = false; + SupportedAlpnRank alpnRank = SupportedAlpnRank::NOT_SUPPORTED; for (uint32_t pairIndex = 0; pairIndex < parsedAltSvc.mValues[index].mValues.Length(); @@ -116,7 +116,7 @@ void AltSvcMapping::ProcessHeader( // h2=[hostname]:443 or h3-xx=[hostname]:port // XX is current version we support and it is define in nsHttp.h. - isHttp3 = gHttpHandler->IsHttp3VersionSupported(currentName); + alpnRank = IsAlpnSupported(currentName); npnToken = currentName; int32_t colonIndex = currentValue.FindChar(':'); @@ -153,12 +153,7 @@ void AltSvcMapping::ProcessHeader( // update nsCString length nsUnescape(npnToken.BeginWriting()); npnToken.SetLength(strlen(npnToken.BeginReading())); - - if (http3Found && isHttp3) { - LOG(("Alt Svc ignore multiple Http3 options (%s)", npnToken.get())); - continue; - } - + bool isHttp3 = net::IsHttp3(alpnRank); SpdyInformation* spdyInfo = gHttpHandler->SpdyInfo(); if (!(npnToken.Equals(spdyInfo->VersionString) && StaticPrefs::network_http_http2_enabled()) && @@ -169,16 +164,13 @@ void AltSvcMapping::ProcessHeader( continue; } - if (isHttp3) { - http3Found = true; - } - - RefPtr<AltSvcMapping> mapping = - new AltSvcMapping(gHttpHandler->AltServiceCache()->GetStoragePtr(), - gHttpHandler->AltServiceCache()->StorageEpoch(), - originScheme, originHost, originPort, username, - privateBrowsing, NowInSeconds() + maxage, hostname, - portno, npnToken, originAttributes, isHttp3); + LOG(("AltSvcMapping created npnToken=%s", npnToken.get())); + RefPtr<AltSvcMapping> mapping = new AltSvcMapping( + gHttpHandler->AltServiceCache()->GetStoragePtr(), + gHttpHandler->AltServiceCache()->StorageEpoch(), originScheme, + originHost, originPort, username, privateBrowsing, + NowInSeconds() + maxage, hostname, portno, npnToken, originAttributes, + isHttp3, alpnRank); if (mapping->TTL() <= 0) { LOG(("Alt Svc invalid map")); mapping = nullptr; @@ -186,15 +178,39 @@ void AltSvcMapping::ProcessHeader( // as that would have happened if we had accepted the parameters. gHttpHandler->AltServiceCache()->ClearHostMapping(originHost, originPort, originAttributes); - } else if (!aDontValidate) { - gHttpHandler->UpdateAltServiceMapping(mapping, proxyInfo, callbacks, caps, - originAttributes); + } else { + if (isHttp3) { + h3Mappings.AppendElement(std::move(mapping)); + } else { + otherMappings.AppendElement(std::move(mapping)); + } + } + } + + auto doUpdateAltSvcMapping = [&](AltSvcMapping* aMapping) { + if (!aDontValidate) { + gHttpHandler->UpdateAltServiceMapping(aMapping, proxyInfo, callbacks, + caps, originAttributes); } else { gHttpHandler->UpdateAltServiceMappingWithoutValidation( - mapping, proxyInfo, callbacks, caps, originAttributes); + aMapping, proxyInfo, callbacks, caps, originAttributes); } + }; + + if (!h3Mappings.IsEmpty()) { + // Select the HTTP/3 (h3) AltSvcMapping with the highest ALPN rank from + // h3Mappings. + RefPtr<AltSvcMapping> latestH3Mapping = *std::max_element( + h3Mappings.begin(), h3Mappings.end(), + [](const RefPtr<AltSvcMapping>& a, const RefPtr<AltSvcMapping>& b) { + return a->AlpnRank() < b->AlpnRank(); + }); + doUpdateAltSvcMapping(latestH3Mapping); } + std::for_each(otherMappings.begin(), otherMappings.end(), + doUpdateAltSvcMapping); + if (numEntriesInHeader) { // Ignore headers that were just "alt-svc: clear" Telemetry::Accumulate(Telemetry::HTTP_ALTSVC_ENTRIES_PER_HEADER, numEntriesInHeader); @@ -209,7 +225,7 @@ AltSvcMapping::AltSvcMapping(nsIDataStorage* storage, int32_t epoch, const nsACString& alternateHost, int32_t alternatePort, const nsACString& npnToken, const OriginAttributes& originAttributes, - bool aIsHttp3) + bool aIsHttp3, SupportedAlpnRank aRank) : mStorage(storage), mStorageEpoch(epoch), mAlternateHost(alternateHost), @@ -221,7 +237,8 @@ AltSvcMapping::AltSvcMapping(nsIDataStorage* storage, int32_t epoch, mExpiresAt(expiresAt), mNPNToken(npnToken), mOriginAttributes(originAttributes), - mIsHttp3(aIsHttp3) { + mIsHttp3(aIsHttp3), + mAlpnRank(aRank) { MOZ_ASSERT(NS_IsMainThread()); if (NS_FAILED(SchemeIsHTTPS(originScheme, mHttps))) { diff --git a/netwerk/protocol/http/AlternateServices.h b/netwerk/protocol/http/AlternateServices.h index 4de5a281c0..02b45f7bee 100644 --- a/netwerk/protocol/http/AlternateServices.h +++ b/netwerk/protocol/http/AlternateServices.h @@ -23,6 +23,7 @@ https://tools.ietf.org/html/draft-ietf-httpbis-alt-svc-06 #ifndef mozilla_net_AlternateServices_h #define mozilla_net_AlternateServices_h +#include "nsHttp.h" #include "nsRefPtrHashtable.h" #include "nsString.h" #include "nsIDataStorage.h" @@ -53,7 +54,8 @@ class AltSvcMapping { bool privateBrowsing, uint32_t expiresAt, const nsACString& alternateHost, int32_t alternatePort, const nsACString& npnToken, - const OriginAttributes& originAttributes, bool aIsHttp3); + const OriginAttributes& originAttributes, bool aIsHttp3, + SupportedAlpnRank aRank); public: AltSvcMapping(nsIDataStorage* storage, int32_t storageEpoch, @@ -103,6 +105,7 @@ class AltSvcMapping { bool IsHttp3() { return mIsHttp3; } const nsCString& NPNToken() const { return mNPNToken; } + SupportedAlpnRank AlpnRank() const { return mAlpnRank; } private: virtual ~AltSvcMapping() = default; @@ -138,6 +141,7 @@ class AltSvcMapping { bool mSyncOnlyOnSuccess{false}; bool mIsHttp3{false}; + SupportedAlpnRank mAlpnRank{SupportedAlpnRank::NOT_SUPPORTED}; }; class AltSvcOverride : public nsIInterfaceRequestor, diff --git a/netwerk/protocol/http/CacheControlParser.cpp b/netwerk/protocol/http/CacheControlParser.cpp index 79cdef5439..4166ab783d 100644 --- a/netwerk/protocol/http/CacheControlParser.cpp +++ b/netwerk/protocol/http/CacheControlParser.cpp @@ -69,6 +69,7 @@ void CacheControlParser::Directive() { bool CacheControlParser::SecondsValue(uint32_t* seconds, uint32_t defaultVal) { SkipWhites(); if (!CheckChar('=')) { + IgnoreDirective(); *seconds = defaultVal; return !!defaultVal; } @@ -76,7 +77,9 @@ bool CacheControlParser::SecondsValue(uint32_t* seconds, uint32_t defaultVal) { SkipWhites(); if (!ReadInteger(seconds)) { NS_WARNING("Unexpected value in Cache-control header value"); - return false; + IgnoreDirective(); + *seconds = defaultVal; + return !!defaultVal; } return true; diff --git a/netwerk/protocol/http/ConnectionEntry.cpp b/netwerk/protocol/http/ConnectionEntry.cpp index 473f0ab9fc..7b59011cd3 100644 --- a/netwerk/protocol/http/ConnectionEntry.cpp +++ b/netwerk/protocol/http/ConnectionEntry.cpp @@ -1098,5 +1098,16 @@ void ConnectionEntry::SetRetryDifferentIPFamilyForHttp3(uint16_t aIPFamily) { MOZ_DIAGNOSTIC_ASSERT(mPreferIPv4 ^ mPreferIPv6); } +void ConnectionEntry::SetServerCertHashes( + nsTArray<RefPtr<nsIWebTransportHash>>&& aHashes) { + mServerCertHashes = std::move(aHashes); +} + +const nsTArray<RefPtr<nsIWebTransportHash>>& +ConnectionEntry::GetServerCertHashes() { + MOZ_ASSERT(OnSocketThread(), "not on socket thread"); + return mServerCertHashes; +} + } // namespace net } // namespace mozilla diff --git a/netwerk/protocol/http/ConnectionEntry.h b/netwerk/protocol/http/ConnectionEntry.h index 811c5481de..8ccc126503 100644 --- a/netwerk/protocol/http/ConnectionEntry.h +++ b/netwerk/protocol/http/ConnectionEntry.h @@ -200,6 +200,10 @@ class ConnectionEntry { bool AllowToRetryDifferentIPFamilyForHttp3(nsresult aError); void SetRetryDifferentIPFamilyForHttp3(uint16_t aIPFamily); + void SetServerCertHashes(nsTArray<RefPtr<nsIWebTransportHash>>&& aHashes); + + const nsTArray<RefPtr<nsIWebTransportHash>>& GetServerCertHashes(); + private: void InsertIntoIdleConnections_internal(nsHttpConnection* conn); void RemoveFromIdleConnectionsIndex(size_t inx); @@ -219,6 +223,9 @@ class ConnectionEntry { nsTArray<RefPtr<DnsAndConnectSocket>> mDnsAndConnectSockets; // dns resolution and half open connections + // If serverCertificateHashes are used, these are stored here + nsTArray<RefPtr<nsIWebTransportHash>> mServerCertHashes; + PendingTransactionQueue mPendingQ; ~ConnectionEntry(); diff --git a/netwerk/protocol/http/Http2Session.cpp b/netwerk/protocol/http/Http2Session.cpp index e969d60c4d..d5793b2147 100644 --- a/netwerk/protocol/http/Http2Session.cpp +++ b/netwerk/protocol/http/Http2Session.cpp @@ -223,7 +223,7 @@ void Http2Session::ShutdownStream(Http2StreamBase* aStream, nsresult aReason) { CloseStream(aStream, NS_ERROR_NET_INADEQUATE_SECURITY); } else if (!mCleanShutdown && (mGoAwayReason != NO_HTTP_ERROR)) { CloseStream(aStream, NS_ERROR_NET_HTTP2_SENT_GOAWAY); - } else if (!mCleanShutdown && SecurityErrorThatMayNeedRestart(aReason)) { + } else if (!mCleanShutdown && PossibleZeroRTTRetryError(aReason)) { CloseStream(aStream, aReason); } else { CloseStream(aStream, NS_ERROR_ABORT); @@ -1419,6 +1419,13 @@ nsresult Http2Session::RecvHeaders(Http2Session* self) { return self->SessionError(PROTOCOL_ERROR); } + uint32_t frameSize = self->mInputFrameDataSize - paddingControlBytes - + priorityLen - paddingLength; + if (self->mAggregatedHeaderSize + frameSize > + StaticPrefs::network_http_max_response_header_size()) { + LOG(("Http2Session %p header exceeds the limit\n", self)); + return self->SessionError(PROTOCOL_ERROR); + } if (!self->mInputFrameDataStream) { // Cannot find stream. We can continue the session, but we need to // uncompress the header block to maintain the correct compression context @@ -1435,8 +1442,7 @@ nsresult Http2Session::RecvHeaders(Http2Session* self) { self->mDecompressBuffer.Append( &self->mInputFrameBuffer[kFrameHeaderBytes + paddingControlBytes + priorityLen], - self->mInputFrameDataSize - paddingControlBytes - priorityLen - - paddingLength); + frameSize); if (self->mInputFrameFlags & kFlag_END_HEADERS) { rv = self->UncompressAndDiscard(false); @@ -1466,21 +1472,16 @@ nsresult Http2Session::RecvHeaders(Http2Session* self) { self->mDecompressBuffer.Append( &self->mInputFrameBuffer[kFrameHeaderBytes + paddingControlBytes + priorityLen], - self->mInputFrameDataSize - paddingControlBytes - priorityLen - - paddingLength); + frameSize); self->mInputFrameDataStream->UpdateTransportReadEvents( self->mInputFrameDataSize); self->mLastDataReadEpoch = self->mLastReadEpoch; if (!isContinuation) { - self->mAggregatedHeaderSize = self->mInputFrameDataSize - - paddingControlBytes - priorityLen - - paddingLength; + self->mAggregatedHeaderSize = frameSize; } else { - self->mAggregatedHeaderSize += self->mInputFrameDataSize - - paddingControlBytes - priorityLen - - paddingLength; + self->mAggregatedHeaderSize += frameSize; } if (!endHeadersFlag) { // more are coming - don't process yet diff --git a/netwerk/protocol/http/Http3Session.cpp b/netwerk/protocol/http/Http3Session.cpp index 0369da94ac..80ee3267fa 100644 --- a/netwerk/protocol/http/Http3Session.cpp +++ b/netwerk/protocol/http/Http3Session.cpp @@ -29,6 +29,7 @@ #include "nsSocketTransportService2.h" #include "nsThreadUtils.h" #include "sslerr.h" +#include "WebTransportCertificateVerifier.h" namespace mozilla::net { @@ -153,7 +154,20 @@ nsresult Http3Session::Init(const nsHttpConnectionInfo* aConnInfo, SessionCacheInfo info; udpConn->ChangeConnectionState(ConnectionState::TLS_HANDSHAKING); - if (StaticPrefs::network_http_http3_enable_0rtt() && + auto hasServCertHashes = [&]() -> bool { + if (!mConnInfo->GetWebTransport()) { + return false; + } + const nsTArray<RefPtr<nsIWebTransportHash>>* servCertHashes = + gHttpHandler->ConnMgr()->GetServerCertHashes(mConnInfo); + return servCertHashes && !servCertHashes->IsEmpty(); + }; + + // In WebTransport, when servCertHashes is specified, it indicates that the + // connection to the WebTransport server should authenticate using the + // expected certificate hash. Therefore, 0RTT should be disabled in this + // context to ensure the certificate hash is checked. + if (StaticPrefs::network_http_http3_enable_0rtt() && !hasServCertHashes() && NS_SUCCEEDED(SSLTokensCache::Get(peerId, token, info))) { LOG(("Found a resumption token in the cache.")); mHttp3Connection->SetResumptionToken(token); @@ -1514,7 +1528,7 @@ nsresult Http3Session::SendData(nsIUDPSocket* socket) { while (CanSendData() && (stream = mReadyForWrite.PopFront())) { LOG(("Http3Session::SendData call ReadSegments from stream=%p [this=%p]", stream.get(), this)); - + stream->SetInTxQueue(false); rv = stream->ReadSegments(); // on stream error we return earlier to let the error be handled. @@ -1557,7 +1571,15 @@ nsresult Http3Session::SendData(nsIUDPSocket* socket) { void Http3Session::StreamReadyToWrite(Http3StreamBase* aStream) { MOZ_ASSERT(aStream); + // Http3Session::StreamReadyToWrite can be called multiple times when we get + // duplicate DataWrite events from neqo at the same time. In this case, we + // only want to insert the stream in `mReadyForWrite` once. + if (aStream->IsInTxQueue()) { + return; + } + mReadyForWrite.Push(aStream); + aStream->SetInTxQueue(true); if (CanSendData() && mConnection) { Unused << mConnection->ResumeSend(); } @@ -2119,6 +2141,32 @@ void Http3Session::CallCertVerification(Maybe<nsCString> aEchPublicName) { return; } + if (mConnInfo->GetWebTransport()) { + // if our connection is webtransport, we might do a verification + // based on serverCertificatedHashes + const nsTArray<RefPtr<nsIWebTransportHash>>* servCertHashes = + gHttpHandler->ConnMgr()->GetServerCertHashes(mConnInfo); + if (servCertHashes && !servCertHashes->IsEmpty() && + certInfo.certs.Length() >= 1) { + // ok, we verify based on serverCertificateHashes + mozilla::pkix::Result rv = AuthCertificateWithServerCertificateHashes( + certInfo.certs[0], *servCertHashes); + if (rv != mozilla::pkix::Result::Success) { + // ok we failed, report it back + LOG( + ("Http3Session::CallCertVerification [this=%p] " + "AuthCertificateWithServerCertificateHashes failed", + this)); + mHttp3Connection->PeerAuthenticated(SSL_ERROR_BAD_CERTIFICATE); + mError = psm::GetXPCOMFromNSSError(SSL_ERROR_BAD_CERTIFICATE); + return; + } + // ok, we succeded + Authenticated(0); + return; + } + } + Maybe<nsTArray<nsTArray<uint8_t>>> stapledOCSPResponse; if (certInfo.stapled_ocsp_responses_present) { stapledOCSPResponse.emplace(std::move(certInfo.stapled_ocsp_responses)); diff --git a/netwerk/protocol/http/Http3StreamBase.h b/netwerk/protocol/http/Http3StreamBase.h index 9ca85de98e..d658741384 100644 --- a/netwerk/protocol/http/Http3StreamBase.h +++ b/netwerk/protocol/http/Http3StreamBase.h @@ -52,6 +52,9 @@ class Http3StreamBase : public SupportsWeakPtr, public ARefBase { virtual bool RecvdReset() const { return mResetRecv; } virtual void SetRecvdReset() { mResetRecv = true; } + void SetInTxQueue(bool aValue) { mInTxQueue = aValue; } + bool IsInTxQueue() const { return mInTxQueue; } + protected: ~Http3StreamBase(); @@ -63,6 +66,7 @@ class Http3StreamBase : public SupportsWeakPtr, public ARefBase { bool mQueued{false}; bool mFin{false}; bool mResetRecv{false}; + bool mInTxQueue{false}; }; } // namespace mozilla::net diff --git a/netwerk/protocol/http/Http3WebTransportStream.cpp b/netwerk/protocol/http/Http3WebTransportStream.cpp index c76d8ef798..01a467030f 100644 --- a/netwerk/protocol/http/Http3WebTransportStream.cpp +++ b/netwerk/protocol/http/Http3WebTransportStream.cpp @@ -527,6 +527,10 @@ nsresult Http3WebTransportStream::WriteSegments() { if (rv == NS_BASE_STREAM_WOULD_BLOCK) { rv = NS_OK; } + if (rv == NS_BASE_STREAM_CLOSED) { + mReceiveStreamPipeOut->Close(); + rv = NS_OK; + } again = false; } else if (NS_FAILED(mSocketInCondition)) { if (mSocketInCondition != NS_BASE_STREAM_WOULD_BLOCK) { diff --git a/netwerk/protocol/http/HttpBaseChannel.cpp b/netwerk/protocol/http/HttpBaseChannel.cpp index 59242f6933..9008d758fc 100644 --- a/netwerk/protocol/http/HttpBaseChannel.cpp +++ b/netwerk/protocol/http/HttpBaseChannel.cpp @@ -3927,7 +3927,6 @@ HttpBaseChannel::GetRequestMode(RequestMode* aMode) { NS_IMETHODIMP HttpBaseChannel::SetRequestMode(RequestMode aMode) { - MOZ_ASSERT(aMode != RequestMode::EndGuard_); mRequestMode = aMode; return NS_OK; } @@ -4438,6 +4437,9 @@ void HttpBaseChannel::DoNotifyListener() { // as not-pending. StoreIsPending(false); + // notify "http-on-before-stop-request" observers + gHttpHandler->OnBeforeStopRequest(this); + if (mListener && !LoadOnStopRequestCalled()) { nsCOMPtr<nsIStreamListener> listener = mListener; StoreOnStopRequestCalled(true); @@ -4445,7 +4447,7 @@ void HttpBaseChannel::DoNotifyListener() { } StoreOnStopRequestCalled(true); - // notify "http-on-stop-connect" observers + // notify "http-on-stop-request" observers gHttpHandler->OnStopRequest(this); // This channel has finished its job, potentially release any tail-blocked diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp index 393d0aa37d..c7009f34d3 100644 --- a/netwerk/protocol/http/HttpChannelChild.cpp +++ b/netwerk/protocol/http/HttpChannelChild.cpp @@ -1160,25 +1160,45 @@ void HttpChannelChild::CollectOMTTelemetry() { key, static_cast<LABELS_HTTP_CHILD_OMT_STATS>(mOMTResult)); } +// We want to inspect all upgradable mixed content loads +// (i.e., loads point to HTTP from an HTTPS page), for +// resources that stem from audio, video and img elements. +// Of those, we want to measure which succceed and which fail. +// Some double negatives, but we check the following:exempt loads that +// 1) Request was upgraded as mixed passive content +// 2) Request _could_ have been upgraded as mixed passive content if the pref +// had been set and Request wasn't upgraded by any other means (URL isn't https) void HttpChannelChild::CollectMixedContentTelemetry() { MOZ_ASSERT(NS_IsMainThread()); - nsContentPolicyType internalLoadType; - mLoadInfo->GetInternalContentPolicyType(&internalLoadType); - bool statusIsSuccess = NS_SUCCEEDED(mStatus); + bool wasUpgraded = mLoadInfo->GetBrowserDidUpgradeInsecureRequests(); + if (!wasUpgraded) { + // If this wasn't upgraded, let's check if it _could_ have been upgraded as + // passive mixed content and that it wasn't upgraded with any other method + if (!mURI->SchemeIs("https") && + !mLoadInfo->GetBrowserWouldUpgradeInsecureRequests()) { + return; + } + } + + // UseCounters require a document. RefPtr<Document> doc; mLoadInfo->GetLoadingDocument(getter_AddRefs(doc)); if (!doc) { return; } - if (internalLoadType == nsIContentPolicy::TYPE_INTERNAL_IMAGE || - internalLoadType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD) { - if (mLoadInfo->GetBrowserUpgradeInsecureRequests()) { + + nsContentPolicyType internalLoadType; + mLoadInfo->GetInternalContentPolicyType(&internalLoadType); + bool statusIsSuccess = NS_SUCCEEDED(mStatus); + + if (internalLoadType == nsIContentPolicy::TYPE_INTERNAL_IMAGE) { + if (wasUpgraded) { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentUpgradedImageSuccess : eUseCounter_custom_MixedContentUpgradedImageFailure); - } else if (mLoadInfo->GetBrowserWouldUpgradeInsecureRequests()) { + } else { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentNotUpgradedImageSuccess @@ -1187,12 +1207,12 @@ void HttpChannelChild::CollectMixedContentTelemetry() { return; } if (internalLoadType == nsIContentPolicy::TYPE_INTERNAL_VIDEO) { - if (mLoadInfo->GetBrowserUpgradeInsecureRequests()) { + if (wasUpgraded) { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentUpgradedVideoSuccess : eUseCounter_custom_MixedContentUpgradedVideoFailure); - } else if (mLoadInfo->GetBrowserWouldUpgradeInsecureRequests()) { + } else { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentNotUpgradedVideoSuccess @@ -1201,12 +1221,12 @@ void HttpChannelChild::CollectMixedContentTelemetry() { return; } if (internalLoadType == nsIContentPolicy::TYPE_INTERNAL_AUDIO) { - if (mLoadInfo->GetBrowserUpgradeInsecureRequests()) { + if (wasUpgraded) { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentUpgradedAudioSuccess : eUseCounter_custom_MixedContentUpgradedAudioFailure); - } else if (mLoadInfo->GetBrowserWouldUpgradeInsecureRequests()) { + } else { doc->SetUseCounter( statusIsSuccess ? eUseCounter_custom_MixedContentNotUpgradedAudioSuccess @@ -1262,6 +1282,9 @@ void HttpChannelChild::DoOnStopRequest(nsIRequest* aRequest, MOZ_ASSERT(!LoadOnStopRequestCalled(), "We should not call OnStopRequest twice"); + // notify "http-on-before-stop-request" observers + gHttpHandler->OnBeforeStopRequest(this); + if (mListener) { nsCOMPtr<nsIStreamListener> listener(mListener); StoreOnStopRequestCalled(true); @@ -1280,7 +1303,7 @@ void HttpChannelChild::DoOnStopRequest(nsIRequest* aRequest, return; } - // notify "http-on-stop-connect" observers + // notify "http-on-stop-request" observers gHttpHandler->OnStopRequest(this); ReleaseListeners(); @@ -1471,6 +1494,9 @@ void HttpChannelChild::ContinueDoNotifyListener() { // as not-pending. StoreIsPending(false); + // notify "http-on-before-stop-request" observers + gHttpHandler->OnBeforeStopRequest(this); + if (mListener && !LoadOnStopRequestCalled()) { nsCOMPtr<nsIStreamListener> listener = mListener; StoreOnStopRequestCalled(true); @@ -3083,30 +3109,19 @@ HttpChannelChild::GetDeliveryTarget(nsISerialEventTarget** aEventTarget) { void HttpChannelChild::TrySendDeletingChannel() { AUTO_PROFILER_LABEL("HttpChannelChild::TrySendDeletingChannel", NETWORK); + MOZ_ASSERT(NS_IsMainThread()); + if (!mDeletingChannelSent.compareExchange(false, true)) { // SendDeletingChannel is already sent. return; } - if (NS_IsMainThread()) { - if (NS_WARN_IF(!CanSend())) { - // IPC actor is destroyed already, do not send more messages. - return; - } - - Unused << PHttpChannelChild::SendDeletingChannel(); + if (NS_WARN_IF(!CanSend())) { + // IPC actor is destroyed already, do not send more messages. return; } - nsCOMPtr<nsISerialEventTarget> neckoTarget = GetNeckoTarget(); - MOZ_ASSERT(neckoTarget); - - DebugOnly<nsresult> rv = neckoTarget->Dispatch( - NewNonOwningRunnableMethod( - "net::HttpChannelChild::TrySendDeletingChannel", this, - &HttpChannelChild::TrySendDeletingChannel), - NS_DISPATCH_NORMAL); - MOZ_ASSERT(NS_SUCCEEDED(rv)); + Unused << PHttpChannelChild::SendDeletingChannel(); } nsresult HttpChannelChild::AsyncCallImpl( diff --git a/netwerk/protocol/http/WebTransportCertificateVerifier.cpp b/netwerk/protocol/http/WebTransportCertificateVerifier.cpp new file mode 100644 index 0000000000..cc778640a1 --- /dev/null +++ b/netwerk/protocol/http/WebTransportCertificateVerifier.cpp @@ -0,0 +1,280 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* 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 "WebTransportCertificateVerifier.h" +#include "ScopedNSSTypes.h" +#include "nss/mozpkix/pkixutil.h" +#include "nss/mozpkix/pkixcheck.h" +#include "hasht.h" + +namespace mozilla::psm { + +class ServerCertHashesTrustDomain : public mozilla::pkix::TrustDomain { + public: + ServerCertHashesTrustDomain() = default; + + virtual mozilla::pkix::Result FindIssuer( + mozilla::pkix::Input encodedIssuerName, IssuerChecker& checker, + mozilla::pkix::Time time) override; + + virtual mozilla::pkix::Result GetCertTrust( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + const mozilla::pkix::CertPolicyId& policy, + mozilla::pkix::Input candidateCertDER, + /*out*/ mozilla::pkix::TrustLevel& trustLevel) override; + + virtual mozilla::pkix::Result CheckSignatureDigestAlgorithm( + mozilla::pkix::DigestAlgorithm digestAlg, + mozilla::pkix::EndEntityOrCA endEntityOrCA, + mozilla::pkix::Time notBefore) override; + + virtual mozilla::pkix::Result CheckRSAPublicKeyModulusSizeInBits( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + unsigned int modulusSizeInBits) override; + + virtual mozilla::pkix::Result VerifyRSAPKCS1SignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, + mozilla::pkix::Input subjectPublicKeyInfo) override; + + virtual mozilla::pkix::Result VerifyRSAPSSSignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, + mozilla::pkix::Input subjectPublicKeyInfo) override; + + virtual mozilla::pkix::Result CheckECDSACurveIsAcceptable( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + mozilla::pkix::NamedCurve curve) override; + + virtual mozilla::pkix::Result VerifyECDSASignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, + mozilla::pkix::Input subjectPublicKeyInfo) override; + + virtual mozilla::pkix::Result DigestBuf( + mozilla::pkix::Input item, mozilla::pkix::DigestAlgorithm digestAlg, + /*out*/ uint8_t* digestBuf, size_t digestBufLen) override; + + virtual mozilla::pkix::Result CheckValidityIsAcceptable( + mozilla::pkix::Time notBefore, mozilla::pkix::Time notAfter, + mozilla::pkix::EndEntityOrCA endEntityOrCA, + mozilla::pkix::KeyPurposeId keyPurpose) override; + + virtual mozilla::pkix::Result NetscapeStepUpMatchesServerAuth( + mozilla::pkix::Time notBefore, + /*out*/ bool& matches) override; + + virtual mozilla::pkix::Result CheckRevocation( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + const mozilla::pkix::CertID& certID, mozilla::pkix::Time time, + mozilla::pkix::Duration validityDuration, + /*optional*/ const mozilla::pkix::Input* stapledOCSPResponse, + /*optional*/ const mozilla::pkix::Input* aiaExtension, + /*optional*/ const mozilla::pkix::Input* sctExtension) override; + + virtual mozilla::pkix::Result IsChainValid( + const mozilla::pkix::DERArray& certChain, mozilla::pkix::Time time, + const mozilla::pkix::CertPolicyId& requiredPolicy) override; + + virtual void NoteAuxiliaryExtension( + mozilla::pkix::AuxiliaryExtension extension, + mozilla::pkix::Input extensionData) override; +}; + +mozilla::pkix::Result ServerCertHashesTrustDomain::FindIssuer( + mozilla::pkix::Input encodedIssuerName, IssuerChecker& checker, + mozilla::pkix::Time time) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::GetCertTrust( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + const mozilla::pkix::CertPolicyId& policy, + mozilla::pkix::Input candidateCertDER, + /*out*/ mozilla::pkix::TrustLevel& trustLevel) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result +ServerCertHashesTrustDomain::CheckSignatureDigestAlgorithm( + mozilla::pkix::DigestAlgorithm digestAlg, + mozilla::pkix::EndEntityOrCA endEntityOrCA, mozilla::pkix::Time notBefore) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result +ServerCertHashesTrustDomain::CheckRSAPublicKeyModulusSizeInBits( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + unsigned int modulusSizeInBits) { + return mozilla::pkix::Result:: + ERROR_UNSUPPORTED_KEYALG; // RSA is not supported for + // serverCertificateHashes, + // Chromium does only support it for an intermediate period due to spec + // change, we do not support it. +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::VerifyRSAPKCS1SignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, mozilla::pkix::Input subjectPublicKeyInfo) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::VerifyRSAPSSSignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, mozilla::pkix::Input subjectPublicKeyInfo) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::CheckECDSACurveIsAcceptable( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + mozilla::pkix::NamedCurve curve) { + return mozilla::pkix::Result::Success; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::VerifyECDSASignedData( + mozilla::pkix::Input data, mozilla::pkix::DigestAlgorithm digestAlgorithm, + mozilla::pkix::Input signature, mozilla::pkix::Input subjectPublicKeyInfo) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::DigestBuf( + mozilla::pkix::Input item, mozilla::pkix::DigestAlgorithm digestAlg, + /*out*/ uint8_t* digestBuf, size_t digestBufLen) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::CheckValidityIsAcceptable( + mozilla::pkix::Time notBefore, mozilla::pkix::Time notAfter, + mozilla::pkix::EndEntityOrCA endEntityOrCA, + mozilla::pkix::KeyPurposeId keyPurpose) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result +ServerCertHashesTrustDomain::NetscapeStepUpMatchesServerAuth( + mozilla::pkix::Time notBefore, + /*out*/ bool& matches) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::CheckRevocation( + mozilla::pkix::EndEntityOrCA endEntityOrCA, + const mozilla::pkix::CertID& certID, mozilla::pkix::Time time, + mozilla::pkix::Duration validityDuration, + /*optional*/ const mozilla::pkix::Input* stapledOCSPResponse, + /*optional*/ const mozilla::pkix::Input* aiaExtension, + /*optional*/ const mozilla::pkix::Input* sctExtension) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +mozilla::pkix::Result ServerCertHashesTrustDomain::IsChainValid( + const mozilla::pkix::DERArray& certChain, mozilla::pkix::Time time, + const mozilla::pkix::CertPolicyId& requiredPolicy) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); + + return mozilla::pkix::Result::FATAL_ERROR_LIBRARY_FAILURE; +} + +void ServerCertHashesTrustDomain::NoteAuxiliaryExtension( + mozilla::pkix::AuxiliaryExtension extension, + mozilla::pkix::Input extensionData) { + MOZ_ASSERT_UNREACHABLE("not expecting this to be called"); +} + +} // namespace mozilla::psm + +namespace mozilla::net { +// Does certificate verificate as required for serverCertificateHashes +// This function is currently only used for Quic, but may be used later also for +// http/2 +mozilla::pkix::Result AuthCertificateWithServerCertificateHashes( + nsTArray<uint8_t>& peerCert, + const nsTArray<RefPtr<nsIWebTransportHash>>& aServerCertHashes) { + using namespace mozilla::pkix; + Input certDER; + mozilla::pkix::Result rv = + certDER.Init(peerCert.Elements(), peerCert.Length()); + if (rv != Success) { + return rv; + } + BackCert cert(certDER, EndEntityOrCA::MustBeEndEntity, nullptr); + rv = cert.Init(); + if (rv != Success) { + return rv; + } + + Time notBefore(Time::uninitialized); + Time notAfter(Time::uninitialized); + rv = ParseValidity(cert.GetValidity(), ¬Before, ¬After); + if (rv != Success) { + return rv; + } + // now we check that validity is not greater than 14 days + Duration certDuration(notBefore, notAfter); + if (certDuration > Duration(60 * 60 * 24 * 14)) { + return mozilla::pkix::Result::ERROR_VALIDITY_TOO_LONG; + } + Time now = Now(); + // and if the certificate is actually valid? + rv = CheckValidity(now, notBefore, notAfter); + if (rv != Success) { + return rv; + } + + mozilla::psm::ServerCertHashesTrustDomain trustDomain; + rv = CheckSubjectPublicKeyInfo( + cert.GetSubjectPublicKeyInfo(), trustDomain, + EndEntityOrCA::MustBeEndEntity /* should be ignored*/); + if (rv != Success) { + return rv; + } + + // ok now the final check, calculate the hash and compare it: + // https://w3c.github.io/webtransport/#compute-a-certificate-hash + nsTArray<uint8_t> certHash; + if (NS_FAILED(Digest::DigestBuf(SEC_OID_SHA256, peerCert, certHash)) || + certHash.Length() != SHA256_LENGTH) { + return mozilla::pkix::Result::ERROR_INVALID_ALGORITHM; + } + + // https://w3c.github.io/webtransport/#verify-a-certificate-hash + for (const auto& hash : aServerCertHashes) { + nsCString algorithm; + if (NS_FAILED(hash->GetAlgorithm(algorithm)) || algorithm != "sha-256") { + continue; + } + + nsTArray<uint8_t> value; + if (NS_FAILED(hash->GetValue(value))) { + continue; + } + + if (certHash == value) { + return Success; + } + } + return mozilla::pkix::Result::ERROR_UNTRUSTED_CERT; +} +} // namespace mozilla::net diff --git a/netwerk/protocol/http/WebTransportCertificateVerifier.h b/netwerk/protocol/http/WebTransportCertificateVerifier.h new file mode 100644 index 0000000000..2045a95a89 --- /dev/null +++ b/netwerk/protocol/http/WebTransportCertificateVerifier.h @@ -0,0 +1,22 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* 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/. */ + +#ifndef mozilla_net_WebTransportCertificateVerifier_h +#define mozilla_net_WebTransportCertificateVerifier_h + +#include "nsTArray.h" +#include "nsIWebTransport.h" +#include "nss/mozpkix/pkixtypes.h" + +namespace mozilla::net { +// This is a special version for serverCertificateHashes introduced with +// WebTransport +mozilla::pkix::Result AuthCertificateWithServerCertificateHashes( + nsTArray<uint8_t>& peerCert, + const nsTArray<RefPtr<nsIWebTransportHash>>& aServerCertHashes); + +} // namespace mozilla::net + +#endif // mozilla_net_WebTransportCertificateVerifier_h diff --git a/netwerk/protocol/http/moz.build b/netwerk/protocol/http/moz.build index db6b2a1a68..b090a56d88 100644 --- a/netwerk/protocol/http/moz.build +++ b/netwerk/protocol/http/moz.build @@ -164,6 +164,7 @@ UNIFIED_SOURCES += [ "TlsHandshaker.cpp", "TLSTransportLayer.cpp", "TRRServiceChannel.cpp", + "WebTransportCertificateVerifier.cpp", ] if CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows": diff --git a/netwerk/protocol/http/nsHttp.cpp b/netwerk/protocol/http/nsHttp.cpp index 768ad91729..5425c3c7b9 100644 --- a/netwerk/protocol/http/nsHttp.cpp +++ b/netwerk/protocol/http/nsHttp.cpp @@ -1017,13 +1017,15 @@ SupportedAlpnRank IsAlpnSupported(const nsACString& aAlpn) { return SupportedAlpnRank::NOT_SUPPORTED; } -// On some security error when 0RTT is used we want to restart transactions -// without 0RTT. Some firewalls do not behave well with 0RTT and cause this -// errors. -bool SecurityErrorThatMayNeedRestart(nsresult aReason) { +// NSS Errors which *may* have been triggered by the use of 0-RTT in the +// presence of badly behaving middleboxes. We may re-attempt the connection +// without early data. +bool PossibleZeroRTTRetryError(nsresult aReason) { return (aReason == psm::GetXPCOMFromNSSError(SSL_ERROR_PROTOCOL_VERSION_ALERT)) || - (aReason == psm::GetXPCOMFromNSSError(SSL_ERROR_BAD_MAC_ALERT)); + (aReason == psm::GetXPCOMFromNSSError(SSL_ERROR_BAD_MAC_ALERT)) || + (aReason == + psm::GetXPCOMFromNSSError(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT)); } nsresult MakeOriginURL(const nsACString& origin, nsCOMPtr<nsIURI>& url) { diff --git a/netwerk/protocol/http/nsHttp.h b/netwerk/protocol/http/nsHttp.h index d0bd4cfe67..fc20351c9d 100644 --- a/netwerk/protocol/http/nsHttp.h +++ b/netwerk/protocol/http/nsHttp.h @@ -499,8 +499,6 @@ static inline bool AllowedErrorForHTTPSRRFallback(nsresult aError) { aError == NS_ERROR_UNKNOWN_HOST || aError == NS_ERROR_NET_TIMEOUT; } -bool SecurityErrorThatMayNeedRestart(nsresult aReason); - [[nodiscard]] nsresult MakeOriginURL(const nsACString& origin, nsCOMPtr<nsIURI>& url); @@ -521,6 +519,8 @@ uint64_t WebTransportErrorToHttp3Error(uint8_t aErrorCode); uint8_t Http3ErrorToWebTransportError(uint64_t aErrorCode); +bool PossibleZeroRTTRetryError(nsresult aReason); + } // namespace net } // namespace mozilla diff --git a/netwerk/protocol/http/nsHttpChannel.cpp b/netwerk/protocol/http/nsHttpChannel.cpp index b3806f761b..96e61e4fb8 100644 --- a/netwerk/protocol/http/nsHttpChannel.cpp +++ b/netwerk/protocol/http/nsHttpChannel.cpp @@ -9,11 +9,10 @@ #include <inttypes.h> -#include "DocumentChannelParent.h" #include "mozilla/ScopeExit.h" #include "mozilla/Sprintf.h" #include "mozilla/dom/nsCSPContext.h" -#include "mozilla/dom/nsCSPService.h" +#include "mozilla/glean/GleanMetrics.h" #include "mozilla/StoragePrincipalHelper.h" #include "nsContentSecurityUtils.h" @@ -29,7 +28,6 @@ #include "nsIEffectiveTLDService.h" #include "nsIHttpHeaderVisitor.h" #include "nsINetworkInterceptController.h" -#include "nsINSSErrorsService.h" #include "nsIStringBundle.h" #include "nsIStreamListenerTee.h" #include "nsISeekableStream.h" @@ -40,7 +38,6 @@ #include "nsMimeTypes.h" #include "nsNetCID.h" #include "nsNetUtil.h" -#include "nsIURL.h" #include "nsIStreamTransportService.h" #include "prnetdb.h" #include "nsEscape.h" @@ -63,11 +60,8 @@ #include "mozilla/BasePrincipal.h" #include "mozilla/DebugOnly.h" #include "mozilla/PerfStats.h" -#include "mozilla/Preferences.h" #include "mozilla/ProfilerLabels.h" #include "mozilla/Components.h" -#include "mozilla/StaticPrefs_browser.h" -#include "mozilla/StaticPrefs_fission.h" #include "mozilla/StaticPrefs_network.h" #include "mozilla/StaticPrefs_privacy.h" #include "mozilla/StaticPrefs_security.h" @@ -93,15 +87,12 @@ #include "nsIStreamConverterService.h" #include "nsISiteSecurityService.h" #include "nsString.h" -#include "CacheObserver.h" #include "mozilla/dom/PerformanceStorage.h" #include "mozilla/dom/ReferrerInfo.h" #include "mozilla/Telemetry.h" #include "AlternateServices.h" #include "NetworkMarker.h" #include "nsIHttpPushListener.h" -#include "nsIX509Cert.h" -#include "ScopedNSSTypes.h" #include "nsIDNSRecord.h" #include "mozilla/dom/Document.h" #include "nsICompressConvStats.h" @@ -116,14 +107,11 @@ #include "CacheStorageService.h" #include "HttpChannelParent.h" #include "HttpTransactionParent.h" -#include "ParentChannelListener.h" #include "ThirdPartyUtil.h" #include "InterceptedHttpChannel.h" #include "../../cache2/CacheFileUtils.h" -#include "nsIMultiplexInputStream.h" #include "nsINetworkLinkService.h" #include "mozilla/ContentBlockingAllowList.h" -#include "mozilla/dom/Promise.h" #include "mozilla/dom/ServiceWorkerUtils.h" #include "mozilla/dom/nsHTTPSOnlyStreamListener.h" #include "mozilla/dom/nsHTTPSOnlyUtils.h" @@ -134,7 +122,6 @@ #include "mozilla/net/UrlClassifierFeatureFactory.h" #include "HttpTrafficAnalyzer.h" #include "mozilla/net/SocketProcessParent.h" -#include "js/Conversions.h" #include "mozilla/dom/SecFetch.h" #include "mozilla/net/TRRService.h" #include "nsUnknownDecoder.h" @@ -560,7 +547,8 @@ nsresult nsHttpChannel::OnBeforeConnect() { } rv = sss->IsSecureURI(mURI, originAttributes, &isSecureURI); NS_ENSURE_SUCCESS(rv, rv); - // Save that on the loadInfo so it can later be consumed by SecurityInfo.jsm + // Save that on the loadInfo so it can later be consumed by + // SecurityInfo.sys.mjs mLoadInfo->SetHstsStatus(isSecureURI); RefPtr<mozilla::dom::BrowsingContext> bc; @@ -797,6 +785,19 @@ nsresult nsHttpChannel::ContinueOnBeforeConnect(bool aShouldUpgrade, mConnectionInfo->SetAnonymousAllowClientCert( (mLoadFlags & LOAD_ANONYMOUS_ALLOW_CLIENT_CERT) != 0); + if (mWebTransportSessionEventListener) { + nsTArray<RefPtr<nsIWebTransportHash>> aServerCertHashes; + nsresult rv; + nsCOMPtr<WebTransportConnectionSettings> wtconSettings = + do_QueryInterface(mWebTransportSessionEventListener, &rv); + NS_ENSURE_SUCCESS(rv, rv); + + wtconSettings->GetServerCertificateHashes(aServerCertHashes); + gHttpHandler->ConnMgr()->StoreServerCertHashes( + mConnectionInfo, gHttpHandler->IsHttp2Excluded(mConnectionInfo), + !Http3Allowed(), std::move(aServerCertHashes)); + } + // notify "http-on-before-connect" observers gHttpHandler->OnBeforeConnect(this); @@ -2277,8 +2278,10 @@ nsresult nsHttpChannel::ContinueProcessResponse1() { // Given a successful connection, process any STS or PKP data that's // relevant. - DebugOnly<nsresult> rv = ProcessSecurityHeaders(); - MOZ_ASSERT(NS_SUCCEEDED(rv), "ProcessSTSHeader failed, continuing load."); + nsresult rv = ProcessSecurityHeaders(); + if (NS_FAILED(rv)) { + NS_WARNING("ProcessSTSHeader failed, continuing load."); + } if ((httpStatus < 500) && (httpStatus != 421)) { ProcessAltService(); @@ -2400,7 +2403,6 @@ nsresult nsHttpChannel::ContinueProcessResponse3(nsresult rv) { rv = ProcessNormal(); } break; - case 300: case 301: case 302: case 307: @@ -6443,6 +6445,16 @@ nsresult nsHttpChannel::BeginConnect() { connInfo = new nsHttpConnectionInfo(host, port, "h3"_ns, mUsername, proxyInfo, originAttributes, isHttps, true, true); + bool dedicated = true; + nsresult rv; + nsCOMPtr<WebTransportConnectionSettings> wtconSettings = + do_QueryInterface(mWebTransportSessionEventListener, &rv); + NS_ENSURE_SUCCESS(rv, rv); + wtconSettings->GetDedicated(&dedicated); + if (dedicated) { + connInfo->SetWebTransportId( + gHttpHandler->ConnMgr()->GenerateNewWebTransportId()); + } } else { connInfo = new nsHttpConnectionInfo(host, port, ""_ns, mUsername, proxyInfo, originAttributes, isHttps); @@ -6954,7 +6966,54 @@ nsHttpChannel::OnProxyAvailable(nsICancelable* request, nsIChannel* channel, // request was canceled. We just failover to DIRECT when proxy resolution // fails (failure can mean that the PAC URL could not be loaded). - if (NS_SUCCEEDED(status)) mProxyInfo = pi; + if (NS_SUCCEEDED(status)) { + mProxyInfo = pi; + + if (mProxyInfo) { + nsAutoCStringN<8> type; + mProxyInfo->GetType(type); + uint32_t flags = 0; + mProxyInfo->GetFlags(&flags); + + if (type.EqualsLiteral("socks")) { + if (flags & nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST) { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eSocks5h) + .Add(1); + } else { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eSocks5) + .Add(1); + } + } else if (type.EqualsLiteral("socks4")) { + if (flags & nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST) { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eSocks4a) + .Add(1); + } else { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eSocks4) + .Add(1); + } + } else if (type.EqualsLiteral("http")) { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eHttp) + .Add(1); + } else if (type.EqualsLiteral("https")) { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eHttps) + .Add(1); + } else if (type.EqualsLiteral("direct")) { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eDirect) + .Add(1); + } else { + glean::networking::proxy_info_type + .EnumGet(glean::networking::ProxyInfoTypeLabel::eUnknown) + .Add(1); + } + } + } if (!gHttpHandler->Active()) { LOG( @@ -8203,6 +8262,10 @@ nsresult nsHttpChannel::ContinueOnStopRequest(nsresult aStatus, bool aIsFromNet, } mAuthRetryPending = false; } + + // notify "http-on-before-stop-request" observers + gHttpHandler->OnBeforeStopRequest(this); + if (mListener) { LOG(("nsHttpChannel %p calling OnStopRequest\n", this)); MOZ_ASSERT(LoadOnStartRequestCalled(), @@ -8219,7 +8282,7 @@ nsresult nsHttpChannel::ContinueOnStopRequest(nsresult aStatus, bool aIsFromNet, mRedirectChannel = nullptr; - // notify "http-on-stop-connect" observers + // notify "http-on-stop-request" observers gHttpHandler->OnStopRequest(this); RemoveAsNonTailRequest(); @@ -9342,8 +9405,8 @@ nsresult nsHttpChannel::OnPush(uint32_t aPushedStreamId, const nsACString& aUrl, // static bool nsHttpChannel::IsRedirectStatus(uint32_t status) { // 305 disabled as a security measure (see bug 187996). - return status == 300 || status == 301 || status == 302 || status == 303 || - status == 307 || status == 308; + return status == 301 || status == 302 || status == 303 || status == 307 || + status == 308; } void nsHttpChannel::SetCouldBeSynthesized() { diff --git a/netwerk/protocol/http/nsHttpConnection.cpp b/netwerk/protocol/http/nsHttpConnection.cpp index 023c06f3f3..cd41cd65bc 100644 --- a/netwerk/protocol/http/nsHttpConnection.cpp +++ b/netwerk/protocol/http/nsHttpConnection.cpp @@ -742,7 +742,7 @@ void nsHttpConnection::Close(nsresult reason, bool aIsShutdown) { gHttpHandler->ClearHostMapping(mConnInfo); } if (mTlsHandshaker->EarlyDataWasAvailable() && - SecurityErrorThatMayNeedRestart(reason)) { + PossibleZeroRTTRetryError(reason)) { gHttpHandler->Exclude0RttTcp(mConnInfo); } diff --git a/netwerk/protocol/http/nsHttpConnectionInfo.cpp b/netwerk/protocol/http/nsHttpConnectionInfo.cpp index e91128d85a..21c3e75b54 100644 --- a/netwerk/protocol/http/nsHttpConnectionInfo.cpp +++ b/netwerk/protocol/http/nsHttpConnectionInfo.cpp @@ -258,6 +258,12 @@ void nsHttpConnectionInfo::BuildHashKey() { } } + if (mWebTransportId) { + mHashKey.AppendLiteral("{wId"); + mHashKey.AppendInt(mWebTransportId, 16); + mHashKey.AppendLiteral("}"); + } + nsAutoCString originAttributes; mOriginAttributes.CreateSuffix(originAttributes); mHashKey.Append(originAttributes); @@ -326,6 +332,7 @@ already_AddRefed<nsHttpConnectionInfo> nsHttpConnectionInfo::Clone() const { clone->SetIPv6Disabled(GetIPv6Disabled()); clone->SetHasIPHintAddress(HasIPHintAddress()); clone->SetEchConfig(GetEchConfig()); + clone->SetWebTransportId(GetWebTransportId()); MOZ_ASSERT(clone->Equals(this)); return clone.forget(); @@ -418,6 +425,7 @@ void nsHttpConnectionInfo::SerializeHttpConnectionInfo( aArgs.hasIPHintAddress() = aInfo->HasIPHintAddress(); aArgs.echConfig() = aInfo->GetEchConfig(); aArgs.webTransport() = aInfo->GetWebTransport(); + aArgs.webTransportId() = aInfo->GetWebTransportId(); if (!aInfo->ProxyInfo()) { return; @@ -448,6 +456,8 @@ nsHttpConnectionInfo::DeserializeHttpConnectionInfoCloneArgs( aInfoArgs.routedHost(), aInfoArgs.routedPort(), aInfoArgs.isHttp3(), aInfoArgs.webTransport()); } + // Transfer Webtransport ids + cinfo->SetWebTransportId(aInfoArgs.webTransportId()); // Make sure the anonymous, insecure-scheme, and private flags are transferred cinfo->SetAnonymous(aInfoArgs.anonymous()); @@ -542,6 +552,13 @@ void nsHttpConnectionInfo::SetWebTransport(bool aWebTransport) { } } +void nsHttpConnectionInfo::SetWebTransportId(uint64_t id) { + if (mWebTransportId != id) { + mWebTransportId = id; + RebuildHashKey(); + } +} + void nsHttpConnectionInfo::SetTlsFlags(uint32_t aTlsFlags) { mTlsFlags = aTlsFlags; const uint32_t tlsFlagsLength = 8; diff --git a/netwerk/protocol/http/nsHttpConnectionInfo.h b/netwerk/protocol/http/nsHttpConnectionInfo.h index 892d795b10..3757b87be7 100644 --- a/netwerk/protocol/http/nsHttpConnectionInfo.h +++ b/netwerk/protocol/http/nsHttpConnectionInfo.h @@ -222,6 +222,9 @@ class nsHttpConnectionInfo final : public ARefBase { void SetWebTransport(bool aWebTransport); bool GetWebTransport() const { return mWebTransport; } + void SetWebTransportId(uint64_t id); + uint32_t GetWebTransportId() const { return mWebTransportId; }; + const nsCString& GetNPNToken() { return mNPNToken; } const nsCString& GetUsername() { return mUsername; } @@ -307,6 +310,9 @@ class nsHttpConnectionInfo final : public ARefBase { bool mHasIPHintAddress = false; nsCString mEchConfig; + uint64_t mWebTransportId = 0; // current dedicated Id only used for + // Webtransport, zero means not dedicated + // for RefPtr NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsHttpConnectionInfo, override) }; diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.cpp b/netwerk/protocol/http/nsHttpConnectionMgr.cpp index 2e937d0f2a..c7c385a42a 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp +++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp @@ -3821,6 +3821,62 @@ void nsHttpConnectionMgr::DecrementNumIdleConns() { ConditionallyStopPruneDeadConnectionsTimer(); } +// A structure used to marshall objects necessary for ServerCertificateHashaes +class nsStoreServerCertHashesData : public ARefBase { + public: + nsStoreServerCertHashesData( + nsHttpConnectionInfo* aConnInfo, bool aNoSpdy, bool aNoHttp3, + nsTArray<RefPtr<nsIWebTransportHash>>&& aServerCertHashes) + : mConnInfo(aConnInfo), + mNoSpdy(aNoSpdy), + mNoHttp3(aNoHttp3), + mServerCertHashes(std::move(aServerCertHashes)) {} + + NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsStoreServerCertHashesData, override) + + RefPtr<nsHttpConnectionInfo> mConnInfo; + bool mNoSpdy; + bool mNoHttp3; + nsTArray<RefPtr<nsIWebTransportHash>> mServerCertHashes; + + private: + virtual ~nsStoreServerCertHashesData() = default; +}; + +// The connection manager needs to know the hashes used for a WebTransport +// connection authenticated with serverCertHashes +nsresult nsHttpConnectionMgr::StoreServerCertHashes( + nsHttpConnectionInfo* aConnInfo, bool aNoSpdy, bool aNoHttp3, + nsTArray<RefPtr<nsIWebTransportHash>>&& aServerCertHashes) { + RefPtr<nsHttpConnectionInfo> ci = aConnInfo->Clone(); + RefPtr<nsStoreServerCertHashesData> data = new nsStoreServerCertHashesData( + ci, aNoSpdy, aNoHttp3, std::move(aServerCertHashes)); + return PostEvent(&nsHttpConnectionMgr::OnMsgStoreServerCertHashes, 0, data); +} + +void nsHttpConnectionMgr::OnMsgStoreServerCertHashes(int32_t, ARefBase* param) { + MOZ_ASSERT(OnSocketThread(), "not on socket thread"); + + nsStoreServerCertHashesData* data = + static_cast<nsStoreServerCertHashesData*>(param); + + bool isWildcard; + ConnectionEntry* connEnt = GetOrCreateConnectionEntry( + data->mConnInfo, true, data->mNoSpdy, data->mNoHttp3, &isWildcard); + MOZ_ASSERT(!isWildcard, "No webtransport with wildcard"); + connEnt->SetServerCertHashes(std::move(data->mServerCertHashes)); +} + +const nsTArray<RefPtr<nsIWebTransportHash>>* +nsHttpConnectionMgr::GetServerCertHashes(nsHttpConnectionInfo* aConnInfo) { + ConnectionEntry* connEnt = mCT.GetWeak(aConnInfo->HashKey()); + if (!connEnt) { + MOZ_ASSERT(0); + return nullptr; + } + return &connEnt->GetServerCertHashes(); +} + void nsHttpConnectionMgr::CheckTransInPendingQueue(nsHttpTransaction* aTrans) { #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED // We only do this check on socket thread. When this function is called on diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.h b/netwerk/protocol/http/nsHttpConnectionMgr.h index 2cf4ab7568..3be6b01689 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.h +++ b/netwerk/protocol/http/nsHttpConnectionMgr.h @@ -60,6 +60,12 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, [[nodiscard]] nsresult CancelTransactions(nsHttpConnectionInfo*, nsresult code); + // The connection manager needs to know the hashes used for a WebTransport + // connection authenticated with serverCertHashes + nsresult StoreServerCertHashes( + nsHttpConnectionInfo* aConnInfo, bool aNoSpdy, bool aNoHttp3, + nsTArray<RefPtr<nsIWebTransportHash>>&& aServerCertHashes); + //------------------------------------------------------------------------- // NOTE: functions below may be called only on the socket thread. //------------------------------------------------------------------------- @@ -143,6 +149,11 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, void NewIdleConnectionAdded(uint32_t timeToLive); void DecrementNumIdleConns(); + const nsTArray<RefPtr<nsIWebTransportHash>>* GetServerCertHashes( + nsHttpConnectionInfo* aConnInfo); + + uint64_t GenerateNewWebTransportId() { return mMaxWebTransportId++; } + private: virtual ~nsHttpConnectionMgr(); @@ -334,6 +345,7 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, void OnMsgPruneNoTraffic(int32_t, ARefBase*); void OnMsgUpdateCurrentBrowserId(int32_t, ARefBase*); void OnMsgClearConnectionHistory(int32_t, ARefBase*); + void OnMsgStoreServerCertHashes(int32_t, ARefBase*); // Total number of active connections in all of the ConnectionEntry objects // that are accessed from mCT connection table. @@ -462,6 +474,10 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, void NotifyConnectionOfBrowserIdChange(uint64_t previousId); void CheckTransInPendingQueue(nsHttpTransaction* aTrans); + + // Used for generating unique IDSs for dedicated connections, currently used + // by WebTransport + Atomic<uint64_t> mMaxWebTransportId{1}; }; } // namespace mozilla::net diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp index dcc5307984..4861b45466 100644 --- a/netwerk/protocol/http/nsHttpHandler.cpp +++ b/netwerk/protocol/http/nsHttpHandler.cpp @@ -1397,13 +1397,6 @@ void nsHttpHandler::PrefsChanged(const char* pref) { } } - if (PREF_CHANGED(HTTP_PREF("max_response_header_size"))) { - rv = Preferences::GetInt(HTTP_PREF("max_response_header_size"), &val); - if (NS_SUCCEEDED(rv)) { - mMaxHttpResponseHeaderSize = val; - } - } - if (PREF_CHANGED(HTTP_PREF("throttle.enable"))) { rv = Preferences::GetBool(HTTP_PREF("throttle.enable"), &mThrottleEnabled); if (NS_SUCCEEDED(rv) && mConnMgr) { diff --git a/netwerk/protocol/http/nsHttpHandler.h b/netwerk/protocol/http/nsHttpHandler.h index cf745347ee..2562d0c833 100644 --- a/netwerk/protocol/http/nsHttpHandler.h +++ b/netwerk/protocol/http/nsHttpHandler.h @@ -375,7 +375,12 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, NotifyObservers(chan, NS_DOCUMENT_ON_MODIFY_REQUEST_TOPIC); } - // Called by the channel before writing a request + // Called by the channel before calling onStopRequest + void OnBeforeStopRequest(nsIHttpChannel* chan) { + NotifyObservers(chan, NS_HTTP_ON_BEFORE_STOP_REQUEST_TOPIC); + } + + // Called by the channel after calling onStopRequest void OnStopRequest(nsIHttpChannel* chan) { NotifyObservers(chan, NS_HTTP_ON_STOP_REQUEST_TOPIC); } @@ -447,10 +452,6 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, return (uint16_t)mHttp3MaxBlockedStreams; } - uint32_t MaxHttpResponseHeaderSize() const { - return mMaxHttpResponseHeaderSize; - } - const nsCString& Http3QlogDir(); float FocusedWindowTransactionRatio() const { @@ -730,9 +731,6 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, nsCString mHttp3QlogDir; - // The max size (in bytes) for received Http response header. - uint32_t mMaxHttpResponseHeaderSize{393216}; - // The ratio for dispatching transactions from the focused window. float mFocusedWindowTransactionRatio{0.9f}; diff --git a/netwerk/protocol/http/nsHttpTransaction.cpp b/netwerk/protocol/http/nsHttpTransaction.cpp index 580ea35841..558de8e6ea 100644 --- a/netwerk/protocol/http/nsHttpTransaction.cpp +++ b/netwerk/protocol/http/nsHttpTransaction.cpp @@ -217,6 +217,13 @@ nsresult nsHttpTransaction::Init( LOG1(("nsHttpTransaction::Init [this=%p caps=%x]\n", this, caps)); + if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) { + LOG( + ("nsHttpTransaction aborting init because of app" + "shutdown")); + return NS_ERROR_ILLEGAL_DURING_SHUTDOWN; + } + MOZ_ASSERT(cinfo); MOZ_ASSERT(requestHead); MOZ_ASSERT(target); @@ -1334,7 +1341,7 @@ bool nsHttpTransaction::ShouldRestartOn0RttError(nsresult reason) { "mEarlyDataWasAvailable=%d error=%" PRIx32 "]\n", this, mEarlyDataWasAvailable, static_cast<uint32_t>(reason))); return StaticPrefs::network_http_early_data_disable_on_error() && - mEarlyDataWasAvailable && SecurityErrorThatMayNeedRestart(reason); + mEarlyDataWasAvailable && PossibleZeroRTTRetryError(reason); } static void MaybeRemoveSSLToken(nsITransportSecurityInfo* aSecurityInfo) { @@ -1501,7 +1508,7 @@ void nsHttpTransaction::Close(nsresult reason) { if (reason == psm::GetXPCOMFromNSSError(SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA) || - reason == psm::GetXPCOMFromNSSError(SSL_ERROR_PROTOCOL_VERSION_ALERT) || + PossibleZeroRTTRetryError(reason) || (!mReceivedData && ((mRequestHead && mRequestHead->IsSafeMethod()) || !reallySentData || connReused)) || shouldRestartTransactionForHTTPSRR) { @@ -1542,9 +1549,8 @@ void nsHttpTransaction::Close(nsresult reason) { } else if (reason == psm::GetXPCOMFromNSSError( SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA)) { SetRestartReason(TRANSACTION_RESTART_DOWNGRADE_WITH_EARLY_DATA); - } else if (reason == - psm::GetXPCOMFromNSSError(SSL_ERROR_PROTOCOL_VERSION_ALERT)) { - SetRestartReason(TRANSACTION_RESTART_PROTOCOL_VERSION_ALERT); + } else if (PossibleZeroRTTRetryError(reason)) { + SetRestartReason(TRANSACTION_RESTART_POSSIBLE_0RTT_ERROR); } // if restarting fails, then we must proceed to close the pipe, // which will notify the channel that the transaction failed. @@ -2520,7 +2526,7 @@ nsresult nsHttpTransaction::ProcessData(char* buf, uint32_t count, mCurrentHttpResponseHeaderSize += bytesConsumed; if (mCurrentHttpResponseHeaderSize > - gHttpHandler->MaxHttpResponseHeaderSize()) { + StaticPrefs::network_http_max_response_header_size()) { LOG(("nsHttpTransaction %p The response header exceeds the limit.\n", this)); return NS_ERROR_FILE_TOO_BIG; diff --git a/netwerk/protocol/http/nsHttpTransaction.h b/netwerk/protocol/http/nsHttpTransaction.h index 354fa2c4d2..5256de4cf2 100644 --- a/netwerk/protocol/http/nsHttpTransaction.h +++ b/netwerk/protocol/http/nsHttpTransaction.h @@ -299,6 +299,7 @@ class nsHttpTransaction final : public nsAHttpTransaction, TRANSACTION_RESTART_HTTP3_FAST_FALLBACK, TRANSACTION_RESTART_OTHERS, TRANSACTION_RESTART_PROTOCOL_VERSION_ALERT, + TRANSACTION_RESTART_POSSIBLE_0RTT_ERROR }; void SetRestartReason(TRANSACTION_RESTART_REASON aReason); diff --git a/netwerk/protocol/http/nsIHttpProtocolHandler.idl b/netwerk/protocol/http/nsIHttpProtocolHandler.idl index d6a6f8a0c1..03d1d6dfe5 100644 --- a/netwerk/protocol/http/nsIHttpProtocolHandler.idl +++ b/netwerk/protocol/http/nsIHttpProtocolHandler.idl @@ -206,6 +206,12 @@ interface nsIHttpProtocolHandler : nsIProxiedProtocolHandler #define NS_HTTP_ON_EXAMINE_CACHED_RESPONSE_TOPIC "http-on-examine-cached-response" /** + * This topic is notified for every http channel before calling + * OnStopRequest on its listener. + */ +#define NS_HTTP_ON_BEFORE_STOP_REQUEST_TOPIC "http-on-before-stop-request" + +/** * This topic is notified for every http channel right after it called * OnStopRequest on its listener, regardless whether it was finished * successfully, failed or has been canceled. diff --git a/netwerk/protocol/res/PageThumbProtocolHandler.cpp b/netwerk/protocol/res/PageThumbProtocolHandler.cpp index 5918b40fad..2d9777da7b 100644 --- a/netwerk/protocol/res/PageThumbProtocolHandler.cpp +++ b/netwerk/protocol/res/PageThumbProtocolHandler.cpp @@ -207,7 +207,7 @@ bool PageThumbProtocolHandler::ResolveSpecialCases(const nsACString& aHost, const nsACString& aPath, const nsACString& aPathname, nsACString& aResult) { - // This should match the scheme in PageThumbs.jsm. We will only resolve + // This should match the scheme in PageThumbs.sys.mjs. We will only resolve // URIs for thumbnails generated by PageThumbs here. if (!aHost.EqualsLiteral(PAGE_THUMB_HOST) && !aHost.EqualsLiteral(PLACES_PREVIEWS_HOST)) { diff --git a/netwerk/protocol/webtransport/WebTransportSessionProxy.cpp b/netwerk/protocol/webtransport/WebTransportSessionProxy.cpp index e650a74d5b..dd4ba7e7d0 100644 --- a/netwerk/protocol/webtransport/WebTransportSessionProxy.cpp +++ b/netwerk/protocol/webtransport/WebTransportSessionProxy.cpp @@ -27,7 +27,8 @@ namespace mozilla::net { LazyLogModule webTransportLog("nsWebTransport"); NS_IMPL_ISUPPORTS(WebTransportSessionProxy, WebTransportSessionEventListener, - nsIWebTransport, nsIRedirectResultListener, nsIStreamListener, + WebTransportConnectionSettings, nsIWebTransport, + nsIRedirectResultListener, nsIStreamListener, nsIChannelEventSink, nsIInterfaceRequestor); WebTransportSessionProxy::WebTransportSessionProxy() @@ -63,17 +64,17 @@ WebTransportSessionProxy::~WebTransportSessionProxy() { //----------------------------------------------------------------------------- nsresult WebTransportSessionProxy::AsyncConnect( - nsIURI* aURI, + nsIURI* aURI, bool aDedicated, const nsTArray<RefPtr<nsIWebTransportHash>>& aServerCertHashes, nsIPrincipal* aPrincipal, uint32_t aSecurityFlags, WebTransportSessionEventListener* aListener) { - return AsyncConnectWithClient(aURI, std::move(aServerCertHashes), aPrincipal, - aSecurityFlags, aListener, + return AsyncConnectWithClient(aURI, aDedicated, std::move(aServerCertHashes), + aPrincipal, aSecurityFlags, aListener, Maybe<dom::ClientInfo>()); } nsresult WebTransportSessionProxy::AsyncConnectWithClient( - nsIURI* aURI, + nsIURI* aURI, bool aDedicated, const nsTArray<RefPtr<nsIWebTransportHash>>& aServerCertHashes, nsIPrincipal* aPrincipal, uint32_t aSecurityFlags, WebTransportSessionEventListener* aListener, @@ -126,7 +127,10 @@ nsresult WebTransportSessionProxy::AsyncConnectWithClient( return NS_ERROR_ABORT; } + mDedicatedConnection = aDedicated; + if (!aServerCertHashes.IsEmpty()) { + mServerCertHashes.Clear(); mServerCertHashes.AppendElements(aServerCertHashes); } @@ -235,6 +239,18 @@ WebTransportSessionProxy::CloseSession(uint32_t status, return NS_OK; } +NS_IMETHODIMP WebTransportSessionProxy::GetDedicated(bool* dedicated) { + *dedicated = mDedicatedConnection; + return NS_OK; +} + +NS_IMETHODIMP WebTransportSessionProxy::GetServerCertificateHashes( + nsTArray<RefPtr<nsIWebTransportHash>>& aServerCertHashes) { + aServerCertHashes.Clear(); + aServerCertHashes.AppendElements(mServerCertHashes); + return NS_OK; +} + void WebTransportSessionProxy::CloseSessionInternalLocked() { MutexAutoLock lock(mMutex); CloseSessionInternal(); @@ -573,8 +589,7 @@ WebTransportSessionProxy::OnStartRequest(nsIRequest* aRequest) { nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel); if (!httpChannel || NS_FAILED(httpChannel->GetResponseStatus(&status)) || - !(status >= 200 && status < 300) || - !CheckServerCertificateIfNeeded()) { + !(status >= 200 && status < 300)) { listener = mListener; mListener = nullptr; mChannel = nullptr; @@ -990,57 +1005,6 @@ void WebTransportSessionProxy::CallOnSessionClosed() { } } -bool WebTransportSessionProxy::CheckServerCertificateIfNeeded() { - if (mServerCertHashes.IsEmpty()) { - return true; - } - - nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel); - MOZ_ASSERT(httpChannel, "Not a http channel ?"); - nsCOMPtr<nsITransportSecurityInfo> tsi; - httpChannel->GetSecurityInfo(getter_AddRefs(tsi)); - MOZ_ASSERT(tsi, - "We shouln't reach this code before setting the security info."); - nsCOMPtr<nsIX509Cert> cert; - nsresult rv = tsi->GetServerCert(getter_AddRefs(cert)); - if (!cert || NS_WARN_IF(NS_FAILED(rv))) return true; - nsTArray<uint8_t> certDER; - if (NS_FAILED(cert->GetRawDER(certDER))) { - return false; - } - // https://w3c.github.io/webtransport/#compute-a-certificate-hash - nsTArray<uint8_t> certHash; - if (NS_FAILED(Digest::DigestBuf(SEC_OID_SHA256, certDER.Elements(), - certDER.Length(), certHash)) || - certHash.Length() != SHA256_LENGTH) { - return false; - } - auto verifyCertDer = [&certHash](const auto& hash) { - return certHash.Length() == hash.Length() && - memcmp(certHash.Elements(), hash.Elements(), certHash.Length()) == 0; - }; - - // https://w3c.github.io/webtransport/#verify-a-certificate-hash - for (const auto& hash : mServerCertHashes) { - nsCString algorithm; - if (NS_FAILED(hash->GetAlgorithm(algorithm)) || algorithm != "sha-256") { - continue; - LOG(("Unexpected non-SHA-256 hash")); - } - - nsTArray<uint8_t> value; - if (NS_FAILED(hash->GetValue(value))) { - continue; - LOG(("Unexpected corrupted hash")); - } - - if (verifyCertDer(value)) { - return true; - } - } - return false; -} - void WebTransportSessionProxy::ChangeState( WebTransportSessionProxyState newState) { mMutex.AssertCurrentThreadOwns(); diff --git a/netwerk/protocol/webtransport/WebTransportSessionProxy.h b/netwerk/protocol/webtransport/WebTransportSessionProxy.h index aebb446e21..9e6f785d80 100644 --- a/netwerk/protocol/webtransport/WebTransportSessionProxy.h +++ b/netwerk/protocol/webtransport/WebTransportSessionProxy.h @@ -121,6 +121,7 @@ class WebTransportStreamCallbackWrapper; class WebTransportSessionProxy final : public nsIWebTransport, public WebTransportSessionEventListener, + public WebTransportConnectionSettings, public nsIStreamListener, public nsIChannelEventSink, public nsIRedirectResultListener, @@ -129,6 +130,7 @@ class WebTransportSessionProxy final : public nsIWebTransport, NS_DECL_THREADSAFE_ISUPPORTS NS_DECL_NSIWEBTRANSPORT NS_DECL_WEBTRANSPORTSESSIONEVENTLISTENER + NS_DECL_WEBTRANSPORTCONNECTIONSETTINGS NS_DECL_NSIREQUESTOBSERVER NS_DECL_NSISTREAMLISTENER NS_DECL_NSICHANNELEVENTSINK @@ -170,11 +172,9 @@ class WebTransportSessionProxy final : public nsIWebTransport, void OnMaxDatagramSizeInternal(uint64_t aSize); void OnOutgoingDatagramOutComeInternal( uint64_t aId, WebTransportSessionEventListener::DatagramOutcome aOutCome); - bool CheckServerCertificateIfNeeded(); nsCOMPtr<nsIChannel> mChannel; nsCOMPtr<nsIChannel> mRedirectChannel; - nsTArray<RefPtr<nsIWebTransportHash>> mServerCertHashes; nsCOMPtr<WebTransportSessionEventListener> mListener MOZ_GUARDED_BY(mMutex); RefPtr<Http3WebTransportSession> mWebTransportSession MOZ_GUARDED_BY(mMutex); uint64_t mSessionId MOZ_GUARDED_BY(mMutex) = UINT64_MAX; @@ -188,6 +188,8 @@ class WebTransportSessionProxy final : public nsIWebTransport, nsTArray<std::function<void(nsresult)>> mPendingCreateStreamEvents MOZ_GUARDED_BY(mMutex); nsCOMPtr<nsIEventTarget> mTarget MOZ_GUARDED_BY(mMutex); + nsTArray<RefPtr<nsIWebTransportHash>> mServerCertHashes; + bool mDedicatedConnection; // for WebTranport }; } // namespace mozilla::net diff --git a/netwerk/protocol/webtransport/nsIWebTransport.idl b/netwerk/protocol/webtransport/nsIWebTransport.idl index faf99e61b6..2283c42977 100644 --- a/netwerk/protocol/webtransport/nsIWebTransport.idl +++ b/netwerk/protocol/webtransport/nsIWebTransport.idl @@ -38,12 +38,14 @@ interface nsIWebTransport : nsISupports { // When called, perform steps in "Initialization WebTransport over HTTP". void asyncConnect(in nsIURI aURI, + in boolean aDedicated, in Array<nsIWebTransportHash> aServerCertHashes, in nsIPrincipal aLoadingPrincipal, in unsigned long aSecurityFlags, in WebTransportSessionEventListener aListener); void asyncConnectWithClient(in nsIURI aURI, + in boolean aDedicated, in Array<nsIWebTransportHash> aServerCertHashes, in nsIPrincipal aLoadingPrincipal, in unsigned long aSecurityFlags, @@ -116,6 +118,13 @@ interface WebTransportSessionEventListener : nsISupports { // void onStatsAvailable(in WebTransportStats aStats); }; +[uuid(faad75bd-83c6-420b-9fdb-a70bd70be449)] +interface WebTransportConnectionSettings : nsISupports { + // WebTransport specific connection information + readonly attribute bool dedicated; + void getServerCertificateHashes(out Array<nsIWebTransportHash> aServerCertHashes); +}; + // This interface is used as a callback when creating an outgoing // unidirectional or bidirectional stream. [scriptable, uuid(c6eeff1d-599b-40a8-9157-c7a40c3d51a2)] diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index 8af9a558b8..81f54e775d 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -268,7 +268,6 @@ class DataChannelRegistry { DeinitUsrSctp(); } -#ifdef SCTP_DTLS_SUPPORTED static int SctpDtlsOutput(void* addr, void* buffer, size_t length, uint8_t tos, uint8_t set_df) { uintptr_t id = reinterpret_cast<uintptr_t>(addr); @@ -278,7 +277,6 @@ class DataChannelRegistry { } return connection->SctpDtlsOutput(addr, buffer, length, tos, set_df); } -#endif void InitUsrSctp() { #ifndef MOZ_PEERCONNECTION @@ -1083,160 +1081,6 @@ int DataChannelConnection::SctpDtlsOutput(void* addr, void* buffer, } #endif -#ifdef ALLOW_DIRECT_SCTP_LISTEN_CONNECT -// listen for incoming associations -// Blocks! - Don't call this from main thread! - -bool DataChannelConnection::Listen(unsigned short port) { - struct sockaddr_in addr = {}; - socklen_t addr_len; - - NS_WARNING_ASSERTION(!NS_IsMainThread(), - "Blocks, do not call from main thread!!!"); - - /* Acting as the 'server' */ -# ifdef HAVE_SIN_LEN - addr.sin_len = sizeof(struct sockaddr_in); -# endif - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - DC_DEBUG(("Waiting for connections on port %u", ntohs(addr.sin_port))); - { - MutexAutoLock lock(mLock); - SetState(DataChannelConnectionState::Connecting); - } - if (usrsctp_bind(mMasterSocket, reinterpret_cast<struct sockaddr*>(&addr), - sizeof(struct sockaddr_in)) < 0) { - DC_ERROR(("***Failed userspace_bind")); - return false; - } - if (usrsctp_listen(mMasterSocket, 1) < 0) { - DC_ERROR(("***Failed userspace_listen")); - return false; - } - - DC_DEBUG(("Accepting connection")); - addr_len = 0; - if ((mSocket = usrsctp_accept(mMasterSocket, nullptr, &addr_len)) == - nullptr) { - DC_ERROR(("***Failed accept")); - return false; - } - - { - MutexAutoLock lock(mLock); - SetState(DataChannelConnectionState::Open); - } - - struct linger l; - l.l_onoff = 1; - l.l_linger = 0; - if (usrsctp_setsockopt(mSocket, SOL_SOCKET, SO_LINGER, (const void*)&l, - (socklen_t)sizeof(struct linger)) < 0) { - DC_WARN(("Couldn't set SO_LINGER on SCTP socket")); - } - - // Notify Connection open - // XXX We need to make sure connection sticks around until the message is - // delivered - DC_DEBUG(("%s: sending ON_CONNECTION for %p", __FUNCTION__, this)); - Dispatch(do_AddRef(new DataChannelOnMessageAvailable( - DataChannelOnMessageAvailable::EventType::OnConnection, this, - (DataChannel*)nullptr))); - return true; -} - -// Blocks! - Don't call this from main thread! -bool DataChannelConnection::Connect(const char* addr, unsigned short port) { - struct sockaddr_in addr4 = {}; - struct sockaddr_in6 addr6 = {}; - - NS_WARNING_ASSERTION(!NS_IsMainThread(), - "Blocks, do not call from main thread!!!"); - - /* Acting as the connector */ - DC_DEBUG(("Connecting to %s, port %u", addr, port)); -# ifdef HAVE_SIN_LEN - addr4.sin_len = sizeof(struct sockaddr_in); -# endif -# ifdef HAVE_SIN6_LEN - addr6.sin6_len = sizeof(struct sockaddr_in6); -# endif - addr4.sin_family = AF_INET; - addr6.sin6_family = AF_INET6; - addr4.sin_port = htons(port); - addr6.sin6_port = htons(port); - { - MutexAutoLock lock(mLock); - SetState(DataChannelConnectionState::Connecting); - } -# if !defined(__Userspace_os_Windows) - if (inet_pton(AF_INET6, addr, &addr6.sin6_addr) == 1) { - if (usrsctp_connect(mMasterSocket, - reinterpret_cast<struct sockaddr*>(&addr6), - sizeof(struct sockaddr_in6)) < 0) { - DC_ERROR(("*** Failed userspace_connect")); - return false; - } - } else if (inet_pton(AF_INET, addr, &addr4.sin_addr) == 1) { - if (usrsctp_connect(mMasterSocket, - reinterpret_cast<struct sockaddr*>(&addr4), - sizeof(struct sockaddr_in)) < 0) { - DC_ERROR(("*** Failed userspace_connect")); - return false; - } - } else { - DC_ERROR(("*** Illegal destination address.")); - } -# else - { - struct sockaddr_storage ss; - int sslen = sizeof(ss); - - if (!WSAStringToAddressA(const_cast<char*>(addr), AF_INET6, nullptr, - (struct sockaddr*)&ss, &sslen)) { - addr6.sin6_addr = - (reinterpret_cast<struct sockaddr_in6*>(&ss))->sin6_addr; - if (usrsctp_connect(mMasterSocket, - reinterpret_cast<struct sockaddr*>(&addr6), - sizeof(struct sockaddr_in6)) < 0) { - DC_ERROR(("*** Failed userspace_connect")); - return false; - } - } else if (!WSAStringToAddressA(const_cast<char*>(addr), AF_INET, nullptr, - (struct sockaddr*)&ss, &sslen)) { - addr4.sin_addr = (reinterpret_cast<struct sockaddr_in*>(&ss))->sin_addr; - if (usrsctp_connect(mMasterSocket, - reinterpret_cast<struct sockaddr*>(&addr4), - sizeof(struct sockaddr_in)) < 0) { - DC_ERROR(("*** Failed userspace_connect")); - return false; - } - } else { - DC_ERROR(("*** Illegal destination address.")); - } - } -# endif - - mSocket = mMasterSocket; - - DC_DEBUG(("connect() succeeded! Entering connected mode")); - { - MutexAutoLock lock(mLock); - SetState(DataChannelConnectionState::Open); - } - // Notify Connection open - // XXX We need to make sure connection sticks around until the message is - // delivered - DC_DEBUG(("%s: sending ON_CONNECTION for %p", __FUNCTION__, this)); - Dispatch(do_AddRef(new DataChannelOnMessageAvailable( - DataChannelOnMessageAvailable::EventType::OnConnection, this, - (DataChannel*)nullptr))); - return true; -} -#endif - DataChannel* DataChannelConnection::FindChannelByStream(uint16_t stream) { return mChannels.Get(stream).get(); } diff --git a/netwerk/sctp/datachannel/DataChannel.h b/netwerk/sctp/datachannel/DataChannel.h index 76fb6aeced..f3586f48a2 100644 --- a/netwerk/sctp/datachannel/DataChannel.h +++ b/netwerk/sctp/datachannel/DataChannel.h @@ -7,10 +7,6 @@ #ifndef NETWERK_SCTP_DATACHANNEL_DATACHANNEL_H_ #define NETWERK_SCTP_DATACHANNEL_DATACHANNEL_H_ -#ifdef MOZ_WEBRTC_SIGNALING -# define SCTP_DTLS_SUPPORTED 1 -#endif - #include <memory> #include <string> #include <vector> @@ -30,10 +26,8 @@ #include "mozilla/net/NeckoTargetHolder.h" #include "DataChannelLog.h" -#ifdef SCTP_DTLS_SUPPORTED -# include "transport/sigslot.h" -# include "transport/transportlayer.h" // For TransportLayer::State -#endif +#include "transport/sigslot.h" +#include "transport/transportlayer.h" // For TransportLayer::State #ifndef EALREADY # define EALREADY WSAEALREADY @@ -120,12 +114,8 @@ class QueuedDataMessage { }; // One per PeerConnection -class DataChannelConnection final : public net::NeckoTargetHolder -#ifdef SCTP_DTLS_SUPPORTED - , - public sigslot::has_slots<> -#endif -{ +class DataChannelConnection final : public net::NeckoTargetHolder, + public sigslot::has_slots<> { friend class DataChannel; friend class DataChannelOnMessageAvailable; friend class DataChannelConnectRunnable; @@ -182,15 +172,7 @@ class DataChannelConnection final : public net::NeckoTargetHolder void AppendStatsToReport(const UniquePtr<dom::RTCStatsCollection>& aReport, const DOMHighResTimeStamp aTimestamp) const; -#ifdef ALLOW_DIRECT_SCTP_LISTEN_CONNECT - // These block; they require something to decide on listener/connector - // (though you can do simultaneous Connect()). Do not call these from - // the main thread! - bool Listen(unsigned short port); - bool Connect(const char* addr, unsigned short port); -#endif -#ifdef SCTP_DTLS_SUPPORTED bool ConnectToTransport(const std::string& aTransportId, const bool aClient, const uint16_t aLocalPort, const uint16_t aRemotePort); @@ -198,7 +180,6 @@ class DataChannelConnection final : public net::NeckoTargetHolder TransportLayer::State aState); void CompleteConnect(); void SetSignals(const std::string& aTransportId); -#endif [[nodiscard]] already_AddRefed<DataChannel> Open( const nsACString& label, const nsACString& protocol, @@ -235,10 +216,8 @@ class DataChannelConnection final : public net::NeckoTargetHolder bool SendDeferredMessages() MOZ_REQUIRES(mLock); -#ifdef SCTP_DTLS_SUPPORTED int SctpDtlsOutput(void* addr, void* buffer, size_t length, uint8_t tos, uint8_t set_df); -#endif bool InShutdown() const { #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED @@ -296,12 +275,10 @@ class DataChannelConnection final : public net::NeckoTargetHolder static int OnThresholdEvent(struct socket* sock, uint32_t sb_free, void* ulp_info); -#ifdef SCTP_DTLS_SUPPORTED static void DTLSConnectThread(void* data); void SendPacket(std::unique_ptr<MediaPacket>&& packet); void SctpDtlsInput(const std::string& aTransportId, const MediaPacket& packet); -#endif DataChannel* FindChannelByStream(uint16_t stream) MOZ_REQUIRES(mLock); uint16_t FindFreeStream() const MOZ_REQUIRES(mLock); bool RequestMoreStreams(int32_t aNeeded = 16) MOZ_REQUIRES(mLock); @@ -373,7 +350,6 @@ class DataChannelConnection final : public net::NeckoTargetHolder void HandleNotification(const union sctp_notification* notif, size_t n) MOZ_REQUIRES(mLock); -#ifdef SCTP_DTLS_SUPPORTED bool IsSTSThread() const { bool on = false; if (mSTS) { @@ -381,7 +357,6 @@ class DataChannelConnection final : public net::NeckoTargetHolder } return on; } -#endif mutable Mutex mLock; // Avoid cycles with PeerConnectionImpl @@ -420,12 +395,10 @@ class DataChannelConnection final : public net::NeckoTargetHolder DataChannelConnectionState mState MOZ_GUARDED_BY(mLock) = DataChannelConnectionState::Closed; -#ifdef SCTP_DTLS_SUPPORTED std::string mTransportId; bool mConnectedToTransportHandler = false; RefPtr<MediaTransportHandler> mTransportHandler; nsCOMPtr<nsIEventTarget> mSTS; -#endif uint16_t mLocalPort = 0; // Accessed from connect thread uint16_t mRemotePort = 0; diff --git a/netwerk/socket/neqo_glue/Cargo.toml b/netwerk/socket/neqo_glue/Cargo.toml index 0e506c8c2d..2d7f0d9a5f 100644 --- a/netwerk/socket/neqo_glue/Cargo.toml +++ b/netwerk/socket/neqo_glue/Cargo.toml @@ -9,16 +9,16 @@ license = "MPL-2.0" name = "neqo_glue" [dependencies] -neqo-http3 = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-transport = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-common = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-qpack = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } +neqo-http3 = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-transport = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-common = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-qpack = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } nserror = { path = "../../../xpcom/rust/nserror" } nsstring = { path = "../../../xpcom/rust/nsstring" } xpcom = { path = "../../../xpcom/rust/xpcom" } thin-vec = { version = "0.2.1", features = ["gecko-ffi"] } log = "0.4.0" -qlog = { git = "https://github.com/cloudflare/quiche", rev = "09ea4b244096a013071cfe2175bbf2945fb7f8d1" } +qlog = "0.12" libc = "0.2.0" static_prefs = { path = "../../../modules/libpref/init/static_prefs"} uuid = { version = "1.0", features = ["v4"] } @@ -27,7 +27,7 @@ uuid = { version = "1.0", features = ["v4"] } winapi = {version = "0.3", features = ["ws2def"] } [dependencies.neqo-crypto] -tag = "v0.7.0" +tag = "v0.7.2" git = "https://github.com/mozilla/neqo" default-features = false features = ["gecko"] diff --git a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp index da430a0611..e06c72222b 100644 --- a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp +++ b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp @@ -264,6 +264,7 @@ nsresult nsHTTPCompressConv::BrotliHandler(nsIInputStream* stream, reinterpret_cast<const char*>(outBuffer.get()), outSize))) { return self->mBrotli->mStatus; } + self->mBrotli->mSourceOffset += outSize; } // See bug 1759745. If the decoder has more output data, take it. @@ -276,6 +277,7 @@ nsresult nsHTTPCompressConv::BrotliHandler(nsIInputStream* stream, outSize))) { return self->mBrotli->mStatus; } + self->mBrotli->mSourceOffset += outSize; } if (res == BROTLI_DECODER_RESULT_SUCCESS || @@ -295,7 +297,9 @@ nsHTTPCompressConv::OnDataAvailable(nsIRequest* request, nsIInputStream* iStr, uint64_t aSourceOffset, uint32_t aCount) { nsresult rv = NS_ERROR_INVALID_CONTENT_ENCODING; uint32_t streamLen = aCount; - LOG(("nsHttpCompressConv %p OnDataAvailable %d", this, aCount)); + LOG(("nsHttpCompressConv %p OnDataAvailable aSourceOffset:%" PRIu64 + " count:%u", + this, aSourceOffset, aCount)); if (streamLen == 0) { NS_ERROR("count of zero passed to OnDataAvailable"); @@ -561,6 +565,9 @@ nsresult nsHTTPCompressConv::do_OnDataAvailable(nsIRequest* request, MutexAutoLock lock(mMutex); listener = mListener; } + LOG(("nsHTTPCompressConv::do_OnDataAvailable req:%p offset: offset:%" PRIu64 + "count:%u", + request, offset, count)); nsresult rv = listener->OnDataAvailable(request, mStream, offset, count); // Make sure the stream no longer references |buffer| in case our listener diff --git a/netwerk/streamconv/mozITXTToHTMLConv.idl b/netwerk/streamconv/mozITXTToHTMLConv.idl index 5a2a1510c9..53686802fe 100644 --- a/netwerk/streamconv/mozITXTToHTMLConv.idl +++ b/netwerk/streamconv/mozITXTToHTMLConv.idl @@ -14,10 +14,6 @@ #include "nsIStreamConverter.idl" %{C++ -// {77c0e42a-1dd2-11b2-8ebf-edc6606f2f4b} -#define MOZITXTTOHTMLCONV_CID \ - { 0x77c0e42a, 0x1dd2, 0x11b2, \ - { 0x8e, 0xbf, 0xed, 0xc6, 0x60, 0x6f, 0x2f, 0x4b } } #define MOZ_TXTTOHTMLCONV_CONTRACTID \ "@mozilla.org/txttohtmlconv;1" diff --git a/netwerk/test/browser/browser_103_assets.js b/netwerk/test/browser/browser_103_assets.js index 4e32c8bf7c..0d2ad354f2 100644 --- a/netwerk/test/browser/browser_103_assets.js +++ b/netwerk/test/browser/browser_103_assets.js @@ -41,7 +41,7 @@ async function test_hint_asset(testName, asset, variant) { let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == "earlyhints-connectback") { numConnectBackRemaining -= 1; } diff --git a/netwerk/test/browser/browser_103_cleanup.js b/netwerk/test/browser/browser_103_cleanup.js index c823f5f01a..9609312e02 100644 --- a/netwerk/test/browser/browser_103_cleanup.js +++ b/netwerk/test/browser/browser_103_cleanup.js @@ -16,7 +16,7 @@ add_task(async function test_103_cancel_parent_connect() { let observed_cancel_reason = ""; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { aSubject = aSubject.QueryInterface(Ci.nsIRequest); if ( aTopic == "http-on-stop-request" && diff --git a/netwerk/test/browser/browser_103_private_window.js b/netwerk/test/browser/browser_103_private_window.js index 7d23ea4b28..909bec0143 100644 --- a/netwerk/test/browser/browser_103_private_window.js +++ b/netwerk/test/browser/browser_103_private_window.js @@ -35,7 +35,7 @@ async function test_early_hints_load_url(usePrivateWin) { let observed = {}; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == "http-on-opening-request") { let channel = aSubject.QueryInterface(Ci.nsIHttpChannel); if (channel.URI.spec === expectedUrl) { diff --git a/netwerk/test/browser/browser_103_redirect_from_server.js b/netwerk/test/browser/browser_103_redirect_from_server.js index 0357d11516..2edf15ba97 100644 --- a/netwerk/test/browser/browser_103_redirect_from_server.js +++ b/netwerk/test/browser/browser_103_redirect_from_server.js @@ -111,7 +111,7 @@ async function test_hint_redirect( if (numRequestRemaining > 0) { let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { aSubject.QueryInterface(Ci.nsIIdentChannel); let id = aSubject.channelId; if (observedChannelIds.includes(id)) { diff --git a/netwerk/test/browser/browser_NetUtil.js b/netwerk/test/browser/browser_NetUtil.js index 09875a5280..791498f031 100644 --- a/netwerk/test/browser/browser_NetUtil.js +++ b/netwerk/test/browser/browser_NetUtil.js @@ -107,5 +107,5 @@ WindowListener.prototype = { { once: true } ); }, - onCloseWindow(aXULWindow) {}, + onCloseWindow() {}, }; diff --git a/netwerk/test/browser/browser_cookie_filtering_basic.js b/netwerk/test/browser/browser_cookie_filtering_basic.js index e51bed5bc5..c5dfb622ab 100644 --- a/netwerk/test/browser/browser_cookie_filtering_basic.js +++ b/netwerk/test/browser/browser_cookie_filtering_basic.js @@ -104,15 +104,17 @@ async function test_basic_suite_org_duplicate() { let parentpid = Services.appinfo.processID; let pid1 = testStruct1.browser.frameLoader.remoteTab.osPid; let pid3 = testStruct3.browser.frameLoader.remoteTab.osPid; - ok( - parentpid != pid1, + Assert.notEqual( + parentpid, + pid1, "Parent pid should differ from content process for 1st example.org" ); - ok( - parentpid != pid3, + Assert.notEqual( + parentpid, + pid3, "Parent pid should differ from content process for 2nd example.org" ); - ok(pid1 != pid3, "Content pids should differ from each other"); + Assert.notEqual(pid1, pid3, "Content pids should differ from each other"); await SpecialPowers.spawn( testStruct1.browser, diff --git a/netwerk/test/browser/browser_cookie_filtering_oa.js b/netwerk/test/browser/browser_cookie_filtering_oa.js index f69ad09e81..13102a1954 100644 --- a/netwerk/test/browser/browser_cookie_filtering_oa.js +++ b/netwerk/test/browser/browser_cookie_filtering_oa.js @@ -119,9 +119,21 @@ async function test_private() { let parentpid = Services.appinfo.processID; let privatePid = testStruct5.browser.frameLoader.remoteTab.osPid; let pid = testStruct2.browser.frameLoader.remoteTab.osPid; - ok(parentpid != privatePid, "Parent and private processes are unique"); - ok(parentpid != pid, "Parent and non-private processes are unique"); - ok(privatePid != pid, "Private and non-private processes are unique"); + Assert.notEqual( + parentpid, + privatePid, + "Parent and private processes are unique" + ); + Assert.notEqual( + parentpid, + pid, + "Parent and non-private processes are unique" + ); + Assert.notEqual( + privatePid, + pid, + "Private and non-private processes are unique" + ); // example.com await SpecialPowers.spawn( diff --git a/netwerk/test/browser/browser_cookie_sync_across_tabs.js b/netwerk/test/browser/browser_cookie_sync_across_tabs.js index 127bb2555b..483169ed44 100644 --- a/netwerk/test/browser/browser_cookie_sync_across_tabs.js +++ b/netwerk/test/browser/browser_cookie_sync_across_tabs.js @@ -34,7 +34,7 @@ add_task(async function () { let pid2 = browser2.frameLoader.remoteTab.osPid; // Note, this might not be true once fission is implemented (Bug 1451850) - ok(pid1 != pid2, "We should have different processes here."); + Assert.notEqual(pid1, pid2, "We should have different processes here."); await SpecialPowers.spawn(browser1, [], async function () { is(content.document.cookie, "", "Expecting no cookies"); diff --git a/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js b/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js index e791794579..20ef3840f3 100644 --- a/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js +++ b/netwerk/test/browser/browser_nsIFormPOSTActionChannel.js @@ -26,7 +26,7 @@ CustomProtocolHandler.prototype = { newChannel(aURI, aLoadInfo) { return new CustomChannel(aURI, aLoadInfo); }, - allowPort(port, scheme) { + allowPort(port) { return port != -1; }, @@ -56,7 +56,7 @@ CustomChannel.prototype = { set uploadStream(val) { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, - setUploadStream(aStream, aContentType, aContentLength) { + setUploadStream(aStream) { this._uploadStream = aStream; }, @@ -172,7 +172,7 @@ document.getElementById('form').submit(); get status() { return Cr.NS_OK; }, - cancel(status) {}, + cancel() {}, loadGroup: null, loadFlags: Ci.nsIRequest.LOAD_NORMAL | diff --git a/netwerk/test/browser/browser_test_io_activity.js b/netwerk/test/browser/browser_test_io_activity.js index 1e9cb29b6d..b6f498ed5f 100644 --- a/netwerk/test/browser/browser_test_io_activity.js +++ b/netwerk/test/browser/browser_test_io_activity.js @@ -35,8 +35,8 @@ add_task(async function testRequestIOActivity() { waitForExplicitFinish(); Services.obs.notifyObservers(null, "profile-initial-state"); - await BrowserTestUtils.withNewTab(TEST_URL, async function (browser) { - await BrowserTestUtils.withNewTab(TEST_URL2, async function (browser) { + await BrowserTestUtils.withNewTab(TEST_URL, async function () { + await BrowserTestUtils.withNewTab(TEST_URL2, async function () { let results = await ChromeUtils.requestIOActivity(); processResults(results); diff --git a/netwerk/test/gtest/TestCacheControlParser.cpp b/netwerk/test/gtest/TestCacheControlParser.cpp new file mode 100644 index 0000000000..df1cd9ec73 --- /dev/null +++ b/netwerk/test/gtest/TestCacheControlParser.cpp @@ -0,0 +1,64 @@ +#include "gtest/gtest.h" + +#include "CacheControlParser.h" + +using namespace mozilla; +using namespace mozilla::net; + +TEST(TestCacheControlParser, NegativeMaxAge) +{ + CacheControlParser cc( + "no-store,no-cache,max-age=-3600,max-stale=7,private"_ns); + ASSERT_TRUE(cc.NoStore()); + ASSERT_TRUE(cc.NoCache()); + uint32_t max_age{2}; + ASSERT_FALSE(cc.MaxAge(&max_age)); + ASSERT_EQ(max_age, 0U); + uint32_t max_stale; + ASSERT_TRUE(cc.MaxStale(&max_stale)); + ASSERT_EQ(max_stale, 7U); + ASSERT_TRUE(cc.Private()); +} + +TEST(TestCacheControlParser, EmptyMaxAge) +{ + CacheControlParser cc("no-store,no-cache,max-age,max-stale=77,private"_ns); + ASSERT_TRUE(cc.NoStore()); + ASSERT_TRUE(cc.NoCache()); + uint32_t max_age{5}; + ASSERT_FALSE(cc.MaxAge(&max_age)); + ASSERT_EQ(max_age, 0U); + uint32_t max_stale; + ASSERT_TRUE(cc.MaxStale(&max_stale)); + ASSERT_EQ(max_stale, 77U); + ASSERT_TRUE(cc.Private()); +} + +TEST(TestCacheControlParser, NegaTiveMaxStale) +{ + CacheControlParser cc( + "no-store,no-cache,max-age=3600,max-stale=-222,private"_ns); + ASSERT_TRUE(cc.NoStore()); + ASSERT_TRUE(cc.NoCache()); + uint32_t max_age; + ASSERT_TRUE(cc.MaxAge(&max_age)); + ASSERT_EQ(max_age, 3600U); + uint32_t max_stale; + ASSERT_TRUE(cc.MaxStale(&max_stale)); + ASSERT_EQ(max_stale, PR_UINT32_MAX); + ASSERT_TRUE(cc.Private()); +} + +TEST(TestCacheControlParser, EmptyMaxStale) +{ + CacheControlParser cc("no-store,no-cache,max-age=3600,max-stale,private"_ns); + ASSERT_TRUE(cc.NoStore()); + ASSERT_TRUE(cc.NoCache()); + uint32_t max_age; + ASSERT_TRUE(cc.MaxAge(&max_age)); + ASSERT_EQ(max_age, 3600U); + uint32_t max_stale; + ASSERT_TRUE(cc.MaxStale(&max_stale)); + ASSERT_EQ(max_stale, PR_UINT32_MAX); + ASSERT_TRUE(cc.Private()); +} diff --git a/netwerk/test/gtest/moz.build b/netwerk/test/gtest/moz.build index b6d82b41db..571c908707 100644 --- a/netwerk/test/gtest/moz.build +++ b/netwerk/test/gtest/moz.build @@ -8,6 +8,7 @@ UNIFIED_SOURCES += [ "TestBase64Stream.cpp", "TestBind.cpp", "TestBufferedInputStream.cpp", + "TestCacheControlParser.cpp", "TestCommon.cpp", "TestCookie.cpp", "TestDNSPacket.cpp", @@ -47,7 +48,7 @@ if CONFIG["OS_TARGET"] == "WINNT": UNIFIED_SOURCES += ["TestNetworkLinkIdHashingWindows.cpp"] # run the test on mac only -if CONFIG["OS_TARGET"] == "Darwin": +if CONFIG["TARGET_OS"] == "OSX": UNIFIED_SOURCES += ["TestNetworkLinkIdHashingDarwin.cpp"] TEST_HARNESS_FILES.gtest += [ @@ -61,6 +62,7 @@ USE_LIBS += [ LOCAL_INCLUDES += [ "/netwerk/base", "/netwerk/cookie", + "/netwerk/protocol/http", "/toolkit/components/jsoncpp/include", "/xpcom/tests/gtest", ] @@ -70,7 +72,7 @@ if CONFIG["OS_TARGET"] == "WINNT": LOCAL_INCLUDES += ["/netwerk/system/win32"] # mac includes only -if CONFIG["OS_TARGET"] == "Darwin": +if CONFIG["TARGET_OS"] == "OSX": LOCAL_INCLUDES += ["/netwerk/system/mac"] include("/ipc/chromium/chromium-config.mozbuild") diff --git a/netwerk/test/http3server/Cargo.toml b/netwerk/test/http3server/Cargo.toml index 24fdd28137..60ff22c530 100644 --- a/netwerk/test/http3server/Cargo.toml +++ b/netwerk/test/http3server/Cargo.toml @@ -6,10 +6,10 @@ edition = "2018" license = "MPL-2.0" [dependencies] -neqo-transport = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-common = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-http3 = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } -neqo-qpack = { tag = "v0.7.0", git = "https://github.com/mozilla/neqo" } +neqo-transport = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-common = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-http3 = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } +neqo-qpack = { tag = "v0.7.2", git = "https://github.com/mozilla/neqo" } mio = "0.6.17" mio-extras = "2.0.5" log = "0.4.0" @@ -21,7 +21,7 @@ tokio = { version = "1", features = ["rt-multi-thread"] } mozilla-central-workspace-hack = { version = "0.1", features = ["http3server"], optional = true } [dependencies.neqo-crypto] -tag = "v0.7.0" +tag = "v0.7.2" git = "https://github.com/mozilla/neqo" default-features = false features = ["gecko"] diff --git a/netwerk/test/httpserver/httpd.sys.mjs b/netwerk/test/httpserver/httpd.sys.mjs index 569e4d1489..b9d728d631 100644 --- a/netwerk/test/httpserver/httpd.sys.mjs +++ b/netwerk/test/httpserver/httpd.sys.mjs @@ -450,7 +450,7 @@ nsHttpServer.prototype = { * was stopped using nsIHttpServer.stop) * @see nsIServerSocketListener.onStopListening */ - onStopListening(socket, status) { + onStopListening(socket) { dumpn(">>> shutting down server on port " + socket.port); for (var n in this._connections) { if (!this._connections[n]._requestStarted) { @@ -4430,7 +4430,7 @@ Response.prototype = { var response = this; var copyObserver = { - onStartRequest(request) { + onStartRequest() { dumpn("*** preamble copying started"); }, @@ -4488,7 +4488,7 @@ Response.prototype = { var response = this; var copyObserver = { - onStartRequest(request) { + onStartRequest() { dumpn("*** onStartRequest"); }, diff --git a/netwerk/test/httpserver/test/data/sjs/range-checker.sjs b/netwerk/test/httpserver/test/data/sjs/range-checker.sjs index 4bc447f739..b73064a568 100644 --- a/netwerk/test/httpserver/test/data/sjs/range-checker.sjs +++ b/netwerk/test/httpserver/test/data/sjs/range-checker.sjs @@ -1 +1 @@ -function handleRequest(request, response) {} +function handleRequest() {} diff --git a/netwerk/test/httpserver/test/test_body_length.js b/netwerk/test/httpserver/test/test_body_length.js index 85f35d7441..80c548274f 100644 --- a/netwerk/test/httpserver/test/test_body_length.js +++ b/netwerk/test/httpserver/test/test_body_length.js @@ -22,7 +22,7 @@ function run_test() { const REQUEST_DATA = "12345678901234567"; -function contentLength(request, response) { +function contentLength(request) { Assert.equal(request.method, "POST"); Assert.equal(request.getHeader("Content-Length"), "017"); diff --git a/netwerk/test/httpserver/test/test_errorhandler_exception.js b/netwerk/test/httpserver/test/test_errorhandler_exception.js index e9cdb0bf4f..5167ed23a8 100644 --- a/netwerk/test/httpserver/test/test_errorhandler_exception.js +++ b/netwerk/test/httpserver/test/test_errorhandler_exception.js @@ -78,18 +78,18 @@ function start_multiple_exceptions_500(ch) { checkStatusLine(ch, 1, 1, 500, "Internal Server Error"); } -function succeeded(ch, status, data) { +function succeeded(ch, status) { Assert.ok(Components.isSuccessCode(status)); } -function register400Handler(ch) { +function register400Handler() { srv.registerErrorHandler(400, throwsException); } // PATH HANDLERS // /throws/exception (and also a 404 and 400 error handler) -function throwsException(metadata, response) { +function throwsException() { throw new Error("this shouldn't cause an exit..."); do_throw("Not reached!"); // eslint-disable-line no-unreachable } diff --git a/netwerk/test/httpserver/test/test_processasync.js b/netwerk/test/httpserver/test/test_processasync.js index 321c9b086f..d652860a25 100644 --- a/netwerk/test/httpserver/test/test_processasync.js +++ b/netwerk/test/httpserver/test/test_processasync.js @@ -181,7 +181,7 @@ handlers["/handleAsync2"] = handleAsync2; var startTime_handleAsync2; -function init_handleAsync2(ch) { +function init_handleAsync2() { var now = (startTime_handleAsync2 = Date.now()); dumpn("*** init_HandleAsync2: start time " + now); } diff --git a/netwerk/test/httpserver/test/test_setindexhandler.js b/netwerk/test/httpserver/test/test_setindexhandler.js index e65f565673..644edd404b 100644 --- a/netwerk/test/httpserver/test/test_setindexhandler.js +++ b/netwerk/test/httpserver/test/test_setindexhandler.js @@ -44,7 +44,7 @@ function stopCustomIndexHandler(ch, status, data) { function startDefaultIndexHandler(ch) { Assert.equal(ch.responseStatus, 200); } -function stopDefaultIndexHandler(ch, status, data) { +function stopDefaultIndexHandler(ch, status) { Assert.ok(Components.isSuccessCode(status)); } diff --git a/netwerk/test/httpserver/test/test_setstatusline.js b/netwerk/test/httpserver/test/test_setstatusline.js index f9cc189a68..b4749fd8e5 100644 --- a/netwerk/test/httpserver/test/test_setstatusline.js +++ b/netwerk/test/httpserver/test/test_setstatusline.js @@ -69,11 +69,11 @@ ChromeUtils.defineLazyGetter(this, "tests", function () { }); // /no/setstatusline -function noSetstatusline(metadata, response) {} +function noSetstatusline() {} function startNoSetStatusLine(ch) { checkStatusLine(ch, 1, 1, 200, "OK"); } -function stop(ch, status, data) { +function stop(ch, status) { Assert.ok(Components.isSuccessCode(status)); } diff --git a/netwerk/test/httpserver/test/test_sjs.js b/netwerk/test/httpserver/test/test_sjs.js index 51d92ec4e0..71d04f8727 100644 --- a/netwerk/test/httpserver/test/test_sjs.js +++ b/netwerk/test/httpserver/test/test_sjs.js @@ -210,7 +210,7 @@ tests.push(test); // extension of the file on the server, not by the extension of the requested // path. -function setupFileMapping(ch) { +function setupFileMapping() { srv.registerFile("/script.html", sjs); } diff --git a/netwerk/test/httpserver/test/test_sjs_object_state.js b/netwerk/test/httpserver/test/test_sjs_object_state.js index 30c1e5c064..42402a8716 100644 --- a/netwerk/test/httpserver/test/test_sjs_object_state.js +++ b/netwerk/test/httpserver/test/test_sjs_object_state.js @@ -56,7 +56,7 @@ function run_test() { */ var initialStarted = false; -function initialStart(ch) { +function initialStart() { dumpn("*** initialStart"); if (initialStarted) { @@ -106,7 +106,7 @@ function initialStop(ch, status, data) { } var intermediateStarted = false; -function intermediateStart(ch) { +function intermediateStart() { dumpn("*** intermediateStart"); Assert.notEqual(srv.getObjectState("object-state-test"), null); @@ -152,7 +152,7 @@ function intermediateStop(ch, status, data) { } var triggerStarted = false; -function triggerStart(ch) { +function triggerStart() { dumpn("*** triggerStart"); if (!initialStarted) { diff --git a/netwerk/test/mochitests/file_1331680.js b/netwerk/test/mochitests/file_1331680.js index 868d6991ae..c99e1d399d 100644 --- a/netwerk/test/mochitests/file_1331680.js +++ b/netwerk/test/mochitests/file_1331680.js @@ -13,12 +13,12 @@ var observer = { }, }; -addMessageListener("createObserver", function (e) { +addMessageListener("createObserver", function () { Services.obs.addObserver(observer, "cookie-changed"); sendAsyncMessage("createObserver:return"); }); -addMessageListener("removeObserver", function (e) { +addMessageListener("removeObserver", function () { Services.obs.removeObserver(observer, "cookie-changed"); sendAsyncMessage("removeObserver:return"); }); diff --git a/netwerk/test/mochitests/test_1396395.html b/netwerk/test/mochitests/test_1396395.html index dcfb952b3a..ecbd01da16 100644 --- a/netwerk/test/mochitests/test_1396395.html +++ b/netwerk/test/mochitests/test_1396395.html @@ -13,7 +13,7 @@ SimpleTest.waitForExplicitFinish(); var script = SpecialPowers.loadChromeScript(() => { /* eslint-env mozilla/chrome-script */ - Services.obs.addObserver(function onExamResp(subject, topic, data) { + Services.obs.addObserver(function onExamResp(subject) { let channel = subject.QueryInterface(Ci.nsIHttpChannel); if (!channel.URI.spec.startsWith("http://example.org")) { return; diff --git a/netwerk/test/mochitests/test_idn_redirect.html b/netwerk/test/mochitests/test_idn_redirect.html index cc920665b3..8445f440e8 100644 --- a/netwerk/test/mochitests/test_idn_redirect.html +++ b/netwerk/test/mochitests/test_idn_redirect.html @@ -24,7 +24,7 @@ iframe.addEventListener("load", finishTest); document.body.appendChild(iframe); iframe.src = "http://mochi.test:8888/tests/netwerk/test/mochitests/redirect_idn.html"; -function finishTest(e) { +function finishTest() { ok(true); SimpleTest.finish(); } diff --git a/netwerk/test/mochitests/test_origin_header.html b/netwerk/test/mochitests/test_origin_header.html index f90887ddf0..4d096e75c6 100644 --- a/netwerk/test/mochitests/test_origin_header.html +++ b/netwerk/test/mochitests/test_origin_header.html @@ -193,7 +193,7 @@ function frameLoaded(test, check) function submitForm(test, check) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { document.getElementById(check.frameID).onload = () => { frameLoaded(test, check); resolve(); @@ -204,7 +204,7 @@ function submitForm(test, check) function loadIframe(test, check) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { let frame = SpecialPowers.wrap(window.document.getElementById(check.frameID)); frame.onload = function () { // Ignore the first load and wait for the submitted form instead. @@ -220,7 +220,7 @@ function loadIframe(test, check) function loadSrcDocFrame(test, check) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { let frame = SpecialPowers.wrap(window.document.getElementById(check.frameID)); frame.onload = function () { // Ignore the first load and wait for the submitted form instead. @@ -240,7 +240,7 @@ function loadSrcDocFrame(test, check) function loadDataURIFrame(test, check) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { let frame = SpecialPowers.wrap(window.document.getElementById(check.frameID)); frame.onload = function () { // Ignore the first load and wait for the submitted form instead. @@ -262,7 +262,7 @@ async function resetFrames() { let checkPromises = []; for (let check of checksToRun) { - checkPromises.push(new Promise((resolve, reject) => { + checkPromises.push(new Promise((resolve) => { let frame = document.getElementById(check.frameID); frame.onload = () => resolve(); if (check.srcdoc) { diff --git a/netwerk/test/mochitests/test_partially_cached_content.html b/netwerk/test/mochitests/test_partially_cached_content.html index 8b6df555f8..8dc93e2c81 100644 --- a/netwerk/test/mochitests/test_partially_cached_content.html +++ b/netwerk/test/mochitests/test_partially_cached_content.html @@ -26,7 +26,7 @@ /* Check that the iframe has initial content only after the first load. */ -function expectInitialContent(e) { +function expectInitialContent() { info("expectInitialContent", "First response received: should have partial content"); var frameElement = document.getElementById('contentFrame'); @@ -57,7 +57,7 @@ function expectInitialContent(e) { /* Check that the iframe has all the content after the second load. */ -function expectFullContent(e) +function expectFullContent() { info("expectFullContent", "Second response received: should complete content from first load"); diff --git a/netwerk/test/mochitests/test_redirect_ref.html b/netwerk/test/mochitests/test_redirect_ref.html index 0b234695d4..33f4031d28 100644 --- a/netwerk/test/mochitests/test_redirect_ref.html +++ b/netwerk/test/mochitests/test_redirect_ref.html @@ -18,7 +18,7 @@ iframe.addEventListener("load", finishTest); document.body.appendChild(iframe); iframe.src = "redirect.sjs#start"; -function finishTest(e) { +function finishTest() { is(iframe.contentWindow.location.href, "http://mochi.test:8888/tests/netwerk/test/mochitests/empty.html#"); SimpleTest.finish(); } diff --git a/netwerk/test/mochitests/test_rel_preconnect.html b/netwerk/test/mochitests/test_rel_preconnect.html index c7e0bada07..a0c3309954 100644 --- a/netwerk/test/mochitests/test_rel_preconnect.html +++ b/netwerk/test/mochitests/test_rel_preconnect.html @@ -19,7 +19,7 @@ async function doTest() { await SpecialPowers.setBoolPref("network.http.debug-observations", true); - observer = SpecialPowers.wrapCallback(function(subject, topic, data) { + observer = SpecialPowers.wrapCallback(function() { remainder--; ok(true, "observed remainder = " + remainder); if (!remainder) { diff --git a/netwerk/test/unit/head_cache.js b/netwerk/test/unit/head_cache.js index 7ec0e11f97..bf86e5d186 100644 --- a/netwerk/test/unit/head_cache.js +++ b/netwerk/test/unit/head_cache.js @@ -84,7 +84,7 @@ function syncWithCacheIOThread(callback, force) { "disk", Ci.nsICacheStorage.OPEN_READONLY, null, - function (status, entry) { + function (status) { Assert.equal(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); callback(); } diff --git a/netwerk/test/unit/head_cache2.js b/netwerk/test/unit/head_cache2.js index f7c865872a..3c5871ccbb 100644 --- a/netwerk/test/unit/head_cache2.js +++ b/netwerk/test/unit/head_cache2.js @@ -71,8 +71,8 @@ function pumpReadStream(inputStream, goon) { pump.init(inputStream, 0, 0, true); let data = ""; pump.asyncRead({ - onStartRequest(aRequest) {}, - onDataAvailable(aRequest, aInputStream, aOffset, aCount) { + onStartRequest() {}, + onDataAvailable(aRequest, aInputStream) { var wrapper = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( Ci.nsIScriptableInputStream ); @@ -422,7 +422,7 @@ function wait_for_cache_index(continue_func) { } function finish_cache2_test() { - callbacks.forEach(function (callback, index) { + callbacks.forEach(function (callback) { callback.selfCheck(); }); do_test_finished(); diff --git a/netwerk/test/unit/head_channels.js b/netwerk/test/unit/head_channels.js index 140135339a..ca16bd2835 100644 --- a/netwerk/test/unit/head_channels.js +++ b/netwerk/test/unit/head_channels.js @@ -274,12 +274,10 @@ ChannelEventSink.prototype = { /** * A helper class to construct origin attributes. */ -function OriginAttributes(inIsolatedMozBrowser, privateId) { - this.inIsolatedMozBrowser = inIsolatedMozBrowser; +function OriginAttributes(privateId) { this.privateBrowsingId = privateId; } OriginAttributes.prototype = { - inIsolatedMozBrowser: false, privateBrowsingId: 0, }; @@ -525,3 +523,27 @@ function makeHTTPChannel(url, with_proxy) { loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); } + +// Like ChannelListener but does not throw an exception if something +// goes wrong. Callback is supposed to do all the work. +class SimpleChannelListener { + constructor(callback) { + this._onStopCallback = callback; + this._buffer = ""; + } + get QueryInterface() { + return ChromeUtils.generateQI(["nsIStreamListener", "nsIRequestObserver"]); + } + + onStartRequest() {} + + onDataAvailable(request, stream, offset, count) { + this._buffer = this._buffer.concat(read_stream(stream, count)); + } + + onStopRequest(request) { + if (this._onStopCallback) { + this._onStopCallback(request, this._buffer); + } + } +} diff --git a/netwerk/test/unit/head_cookies.js b/netwerk/test/unit/head_cookies.js index 037068689f..9c7885fb66 100644 --- a/netwerk/test/unit/head_cookies.js +++ b/netwerk/test/unit/head_cookies.js @@ -59,7 +59,7 @@ function _observer(generator, topic) { } _observer.prototype = { - observe(subject, topic, data) { + observe(subject, topic) { Assert.equal(this.topic, topic); Services.obs.removeObserver(this, this.topic); @@ -93,7 +93,7 @@ function _promise_observer(topic) { } _promise_observer.prototype = { - observe(subject, topic, data) { + observe(subject, topic) { Assert.equal(this.topic, topic); Services.obs.removeObserver(this, this.topic); diff --git a/netwerk/test/unit/head_http3.js b/netwerk/test/unit/head_http3.js index 56bc04db14..fe1e908e01 100644 --- a/netwerk/test/unit/head_http3.js +++ b/netwerk/test/unit/head_http3.js @@ -44,13 +44,13 @@ CheckHttp3Listener.prototype = { expectedRoute: "", http3version: "", - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let routed = "NA"; try { routed = request.getRequestHeader("Alt-Used"); diff --git a/netwerk/test/unit/head_servers.js b/netwerk/test/unit/head_servers.js index d2d449b482..b8087e496f 100644 --- a/netwerk/test/unit/head_servers.js +++ b/netwerk/test/unit/head_servers.js @@ -327,21 +327,31 @@ class BaseProxyCode { // Connect to an origin server const { port, hostname } = new URL(`https://${req.url}`); const serverSocket = net - .connect(port || 443, hostname, () => { - clientSocket.write( - "HTTP/1.1 200 Connection Established\r\n" + - "Proxy-agent: Node.js-Proxy\r\n" + - "\r\n" - ); - serverSocket.write(head); - serverSocket.pipe(clientSocket); - clientSocket.pipe(serverSocket); - }) + .connect( + { + port: port || 443, + host: hostname, + family: 4, // Specifies to use IPv4 + }, + () => { + clientSocket.write( + "HTTP/1.1 200 Connection Established\r\n" + + "Proxy-agent: Node.js-Proxy\r\n" + + "\r\n" + ); + serverSocket.write(head); + serverSocket.pipe(clientSocket); + clientSocket.pipe(serverSocket); + } + ) .on("error", e => { + console.log("error" + e); // The socket will error out when we kill the connection // just ignore it. }); + clientSocket.on("error", e => { + console.log("client error" + e); // Sometimes we got ECONNRESET error on windows platform. // Ignore it for now. }); @@ -848,22 +858,22 @@ class WebSocketConnection { ]); } - onAcknowledge(aContext, aSize) {} + onAcknowledge() {} onBinaryMessageAvailable(aContext, aMsg) { this._messages.push(aMsg); this._msgCallback(); } - onMessageAvailable(aContext, aMsg) {} - onServerClose(aContext, aCode, aReason) {} - onWebSocketListenerStart(aContext) {} - onStart(aContext) { + onMessageAvailable() {} + onServerClose() {} + onWebSocketListenerStart() {} + onStart() { this._openCallback(); } onStop(aContext, aStatusCode) { this._stopCallback({ status: aStatusCode }); this._ws = null; } - onProxyAvailable(req, chan, proxyInfo, status) { + onProxyAvailable(req, chan, proxyInfo) { if (proxyInfo) { this._proxyAvailCallback({ type: proxyInfo.type }); } else { diff --git a/netwerk/test/unit/head_trr.js b/netwerk/test/unit/head_trr.js index 8262c735de..00624e2c96 100644 --- a/netwerk/test/unit/head_trr.js +++ b/netwerk/test/unit/head_trr.js @@ -263,7 +263,7 @@ function answerHandler(req, resp) { answers: response.answers || [], additionals: response.additionals || [], }); - let writeResponse = (resp2, buf2, context) => { + let writeResponse = (resp2, buf2) => { try { let data = buf2.toString("hex"); resp2.setHeader("Content-Length", data.length); diff --git a/netwerk/test/unit/head_websocket.js b/netwerk/test/unit/head_websocket.js index 84c5987f38..1ac2e09ae5 100644 --- a/netwerk/test/unit/head_websocket.js +++ b/netwerk/test/unit/head_websocket.js @@ -17,16 +17,16 @@ WebSocketListener.prototype = { _received: null, QueryInterface: ChromeUtils.generateQI(["nsIWebSocketListener"]), - onAcknowledge(aContext, aSize) {}, + onAcknowledge() {}, onBinaryMessageAvailable(aContext, aMsg) { info("WsListener::onBinaryMessageAvailable"); this._received = aMsg; this._ws.close(0, null); }, - onMessageAvailable(aContext, aMsg) {}, - onServerClose(aContext, aCode, aReason) {}, - onWebSocketListenerStart(aContext) {}, - onStart(aContext) { + onMessageAvailable() {}, + onServerClose() {}, + onWebSocketListenerStart() {}, + onStart() { this._ws.sendMsg(this._sentMsg); }, onStop(aContext, aStatusCode) { diff --git a/netwerk/test/unit/http2_test_common.js b/netwerk/test/unit/http2_test_common.js index 341aa191da..1fa1df8ad2 100644 --- a/netwerk/test/unit/http2_test_common.js +++ b/netwerk/test/unit/http2_test_common.js @@ -123,7 +123,7 @@ Http2MultiplexListener.prototype.onDataAvailable = function ( this.buffer = this.buffer.concat(data); }; -Http2MultiplexListener.prototype.onStopRequest = function (request, status) { +Http2MultiplexListener.prototype.onStopRequest = function (request) { Assert.ok(this.onStartRequestFired); Assert.ok(this.onDataAvailableFired); Assert.ok(this.isHttp2Connection); @@ -290,7 +290,7 @@ Http2BigListener.prototype.onDataAvailable = function ( Assert.equal(bigListenerMD5, request.getResponseHeader("X-Expected-MD5")); }; -Http2BigListener.prototype.onStopRequest = function (request, status) { +Http2BigListener.prototype.onStopRequest = function (request) { Assert.ok(this.onStartRequestFired); Assert.ok(this.onDataAvailableFired); Assert.ok(this.isHttp2Connection); @@ -320,10 +320,7 @@ Http2HugeSuspendedListener.prototype.onDataAvailable = function ( read_stream(stream, cnt); }; -Http2HugeSuspendedListener.prototype.onStopRequest = function ( - request, - status -) { +Http2HugeSuspendedListener.prototype.onStopRequest = function (request) { Assert.ok(this.onStartRequestFired); Assert.ok(this.onDataAvailableFired); Assert.ok(this.isHttp2Connection); @@ -470,7 +467,7 @@ async function test_http2_xhr(serverPort) { return new Promise(resolve => { var req = new XMLHttpRequest(); req.open("GET", `https://localhost:${serverPort}/`, true); - req.addEventListener("readystatechange", function (evt) { + req.addEventListener("readystatechange", function () { checkXhr(req, resolve); }); req.send(null); @@ -485,7 +482,7 @@ Http2ConcurrentListener.prototype.target = 0; Http2ConcurrentListener.prototype.reset = 0; Http2ConcurrentListener.prototype.recvdHdr = 0; -Http2ConcurrentListener.prototype.onStopRequest = function (request, status) { +Http2ConcurrentListener.prototype.onStopRequest = function (request) { this.count++; Assert.ok(this.isHttp2Connection); if (this.recvdHdr > 0) { @@ -814,7 +811,7 @@ altsvcClientListener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { var isHttp2Connection = checkIsHttp2( request.QueryInterface(Ci.nsIHttpChannel) ); @@ -875,7 +872,7 @@ altsvcClientListener2.prototype = { read_stream(stream, cnt); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { var isHttp2Connection = checkIsHttp2( request.QueryInterface(Ci.nsIHttpChannel) ); @@ -959,7 +956,7 @@ Http2PushApiListener.prototype = { }, // normal Channel listeners - onStartRequest: function pushAPIOnStart(request) {}, + onStartRequest: function pushAPIOnStart() {}, onDataAvailable: function pushAPIOnDataAvailable( request, @@ -997,7 +994,7 @@ Http2PushApiListener.prototype = { } }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { if ( request.originalURI.spec == `https://localhost:${this.serverPort}/pushapi1/2` @@ -1100,10 +1097,7 @@ function H11RequiredSessionListener() {} H11RequiredSessionListener.prototype = new Http2CheckListener(); -H11RequiredSessionListener.prototype.onStopRequest = function ( - request, - status -) { +H11RequiredSessionListener.prototype.onStopRequest = function (request) { var streamReused = request.getResponseHeader("X-H11Required-Stream-Ok"); Assert.equal(streamReused, "yes"); @@ -1151,14 +1145,29 @@ async function test_http2_continuations(loadGroup, serverPort) { }); } +async function test_http2_continuations_over_max_response_limit( + loadGroup, + serverPort +) { + var chan = makeHTTPChannel( + `https://localhost:${serverPort}/hugecontinuedheaders?size=385` + ); + chan.loadGroup = loadGroup; + return new Promise(resolve => { + var listener = new Http2CheckListener(); + listener.finish = resolve; + listener.shouldSucceed = false; + chan.asyncOpen(listener); + }); +} + function Http2IllegalHpackValidationListener() {} Http2IllegalHpackValidationListener.prototype = new Http2CheckListener(); Http2IllegalHpackValidationListener.prototype.shouldGoAway = false; Http2IllegalHpackValidationListener.prototype.onStopRequest = function ( - request, - status + request ) { var wentAway = request.getResponseHeader("X-Did-Goaway") === "yes"; Assert.equal(wentAway, this.shouldGoAway); @@ -1176,7 +1185,7 @@ function Http2IllegalHpackListener() {} Http2IllegalHpackListener.prototype = new Http2CheckListener(); Http2IllegalHpackListener.prototype.shouldGoAway = false; -Http2IllegalHpackListener.prototype.onStopRequest = function (request, status) { +Http2IllegalHpackListener.prototype.onStopRequest = function () { var chan = makeHTTPChannel( `https://localhost:${this.serverPort}/illegalhpack_validate` ); diff --git a/netwerk/test/unit/node_execute/test_node_execute_loop.js b/netwerk/test/unit/node_execute/test_node_execute_loop.js index 10400b8b54..44871c65c2 100644 --- a/netwerk/test/unit/node_execute/test_node_execute_loop.js +++ b/netwerk/test/unit/node_execute/test_node_execute_loop.js @@ -16,7 +16,7 @@ add_task(async function killOnEnd() { await NodeServer.execute(id, `console.log("hello");`); await NodeServer.execute(id, `console.error("hello");`); // Make the forked subprocess hang forever. - NodeServer.execute(id, "while (true) {}").catch(e => {}); + NodeServer.execute(id, "while (true) {}").catch(() => {}); await new Promise(resolve => do_timeout(10, resolve)); // Should get killed at the end of the test by the harness. }); diff --git a/netwerk/test/unit/test_304_headers.js b/netwerk/test/unit/test_304_headers.js index b3583663bf..edf0e4f38c 100644 --- a/netwerk/test/unit/test_304_headers.js +++ b/netwerk/test/unit/test_304_headers.js @@ -66,7 +66,7 @@ add_task(async function test() { ); resolve(); }, - onStartRequest(req) {}, + onStartRequest() {}, onDataAvailable() {}, }); }); @@ -84,7 +84,7 @@ add_task(async function test() { ); resolve(); }, - onStartRequest(req) {}, + onStartRequest() {}, onDataAvailable() {}, }); }); diff --git a/netwerk/test/unit/test_304_responses.js b/netwerk/test/unit/test_304_responses.js index a468eec191..c67e1d72ee 100644 --- a/netwerk/test/unit/test_304_responses.js +++ b/netwerk/test/unit/test_304_responses.js @@ -48,7 +48,7 @@ function run_test() { run_next_test(); } -function consume304(request, buffer) { +function consume304(request) { request.QueryInterface(Ci.nsIHttpChannel); Assert.equal(request.responseStatus, 304); Assert.equal(request.getResponseHeader("Returned-From-Handler"), "1"); diff --git a/netwerk/test/unit/test_421.js b/netwerk/test/unit/test_421.js index 680973384e..5125895d38 100644 --- a/netwerk/test/unit/test_421.js +++ b/netwerk/test/unit/test_421.js @@ -52,7 +52,7 @@ function serverHandler(metadata, response) { response.bodyOutputStream.write(httpbody, httpbody.length); } -function checkRequestResponse(request, data, context) { +function checkRequestResponse(request, data) { Assert.equal(channel.responseStatus, 200); Assert.equal(channel.responseStatusText, "OK"); Assert.ok(channel.requestSucceeded); diff --git a/netwerk/test/unit/test_SuperfluousAuth.js b/netwerk/test/unit/test_SuperfluousAuth.js index 2766b00c4c..f5a710e0d8 100644 --- a/netwerk/test/unit/test_SuperfluousAuth.js +++ b/netwerk/test/unit/test_SuperfluousAuth.js @@ -95,7 +95,7 @@ function firstTimeThrough(request, buffer) { Assert.ok(gMockPromptService.firstTimeCalled, "Prompt service invoked"); } -function secondTimeThrough(request, buffer) { +function secondTimeThrough(request) { Assert.equal(request.status, Cr.NS_ERROR_SUPERFLUOS_AUTH); httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_URIs.js b/netwerk/test/unit/test_URIs.js index 548ecd5535..ae778ca6ef 100644 --- a/netwerk/test/unit/test_URIs.js +++ b/netwerk/test/unit/test_URIs.js @@ -618,7 +618,7 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { do_check_property(aTest, testURI, "pathQueryRef", function (aStr) { return aStr + aSuffix; }); - do_check_property(aTest, testURI, "ref", function (aStr) { + do_check_property(aTest, testURI, "ref", function () { return aSuffix.substr(1); }); } diff --git a/netwerk/test/unit/test_URIs2.js b/netwerk/test/unit/test_URIs2.js index 3ca9706543..8101f95e8b 100644 --- a/netwerk/test/unit/test_URIs2.js +++ b/netwerk/test/unit/test_URIs2.js @@ -736,7 +736,7 @@ function do_test_uri_with_hash_suffix(aTest, aSuffix) { do_check_property(aTest, testURI, "pathQueryRef", function (aStr) { return aStr + aSuffix; }); - do_check_property(aTest, testURI, "ref", function (aStr) { + do_check_property(aTest, testURI, "ref", function () { return aSuffix.substr(1); }); } diff --git a/netwerk/test/unit/test_about_networking.js b/netwerk/test/unit/test_about_networking.js index 2cbae65058..b8b864c5a0 100644 --- a/netwerk/test/unit/test_about_networking.js +++ b/netwerk/test/unit/test_about_networking.js @@ -72,7 +72,7 @@ add_test(function test_sockets() { null ); let listener = { - onTransportStatus(aTransport, aStatus, aProgress, aProgressMax) { + onTransportStatus(aTransport, aStatus) { if (aStatus == Ci.nsISocketTransport.STATUS_CONNECTED_TO) { gDashboard.requestSockets(function (data) { gServerSocket.close(); diff --git a/netwerk/test/unit/test_about_protocol.js b/netwerk/test/unit/test_about_protocol.js index 7fc6d63c1e..972b1e3a43 100644 --- a/netwerk/test/unit/test_about_protocol.js +++ b/netwerk/test/unit/test_about_protocol.js @@ -12,7 +12,7 @@ var unsafeAboutModule = { chan.owner = Services.scriptSecurityManager.getSystemPrincipal(); return chan; }, - getURIFlags(aURI) { + getURIFlags() { return Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT; }, }; diff --git a/netwerk/test/unit/test_alt-data_closeWithStatus.js b/netwerk/test/unit/test_alt-data_closeWithStatus.js index df81419cc2..b0427f2e9a 100644 --- a/netwerk/test/unit/test_alt-data_closeWithStatus.js +++ b/netwerk/test/unit/test_alt-data_closeWithStatus.js @@ -32,7 +32,7 @@ var cacheFlushObserver = (cacheFlushObserver = { var currentThread = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_alt-data_cross_process.js b/netwerk/test/unit/test_alt-data_cross_process.js index e46120f312..e3d825c7f1 100644 --- a/netwerk/test/unit/test_alt-data_cross_process.js +++ b/netwerk/test/unit/test_alt-data_cross_process.js @@ -21,7 +21,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_alt-data_simple.js b/netwerk/test/unit/test_alt-data_simple.js index d648884e7a..7fa175db28 100644 --- a/netwerk/test/unit/test_alt-data_simple.js +++ b/netwerk/test/unit/test_alt-data_simple.js @@ -21,7 +21,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_alt-data_stream.js b/netwerk/test/unit/test_alt-data_stream.js index 9b6bfd050a..02fe8803b1 100644 --- a/netwerk/test/unit/test_alt-data_stream.js +++ b/netwerk/test/unit/test_alt-data_stream.js @@ -103,7 +103,7 @@ function openAltChannel() { var altDataListener = { buffer: "", - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { let string = NetUtil.readInputStreamToString(stream, count); this.buffer += string; @@ -120,7 +120,7 @@ var altDataListener = { os.close(); } }, - onStopRequest(request, status) { + onStopRequest(request) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(cc.alternativeDataType, altContentType); Assert.equal(this.buffer.length, altContent.length); @@ -143,12 +143,12 @@ function openAltChannelWithOriginalContent() { var originalListener = { buffer: "", - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { let string = NetUtil.readInputStreamToString(stream, count); this.buffer += string; }, - onStopRequest(request, status) { + onStopRequest(request) { var cc = request.QueryInterface(Ci.nsICacheInfoChannel); Assert.equal(cc.alternativeDataType, altContentType); Assert.equal(this.buffer.length, responseContent.length); diff --git a/netwerk/test/unit/test_auth_dialog_permission.js b/netwerk/test/unit/test_auth_dialog_permission.js index a45b651588..76e92e72f5 100644 --- a/netwerk/test/unit/test_auth_dialog_permission.js +++ b/netwerk/test/unit/test_auth_dialog_permission.js @@ -63,7 +63,7 @@ AuthPrompt.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt(title, text, realm, save, defaultText, result) { + prompt() { do_throw("unexpected prompt call"); }, @@ -75,7 +75,7 @@ AuthPrompt.prototype = { return true; }, - promptPassword(title, text, realm, save, pwd) { + promptPassword() { do_throw("unexpected promptPassword call"); }, }; @@ -159,7 +159,7 @@ Test.prototype = { throw Components.Exception("", Cr.NS_ERROR_ABORT); }, - onDataAvailable(request, stream, offset, count) { + onDataAvailable() { do_throw("Should not get any data!"); }, diff --git a/netwerk/test/unit/test_auth_jar.js b/netwerk/test/unit/test_auth_jar.js deleted file mode 100644 index a6f1ea257c..0000000000 --- a/netwerk/test/unit/test_auth_jar.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; - -function createURI(s) { - return Services.io.newURI(s); -} - -function run_test() { - // Set up a profile. - do_get_profile(); - - var secMan = Services.scriptSecurityManager; - const kURI1 = "http://example.com"; - var app = secMan.createContentPrincipal(createURI(kURI1), {}); - var appbrowser = secMan.createContentPrincipal(createURI(kURI1), { - inIsolatedMozBrowser: true, - }); - - var am = Cc["@mozilla.org/network/http-auth-manager;1"].getService( - Ci.nsIHttpAuthManager - ); - am.setAuthIdentity( - "http", - "a.example.com", - -1, - "basic", - "realm", - "", - "example.com", - "user", - "pass", - false, - app - ); - am.setAuthIdentity( - "http", - "a.example.com", - -1, - "basic", - "realm", - "", - "example.com", - "user3", - "pass3", - false, - appbrowser - ); - - Services.clearData.deleteDataFromOriginAttributesPattern({ - inIsolatedMozBrowser: true, - }); - - var domain = { value: "" }, - user = { value: "" }, - pass = { value: "" }; - try { - am.getAuthIdentity( - "http", - "a.example.com", - -1, - "basic", - "realm", - "", - domain, - user, - pass, - false, - appbrowser - ); - Assert.equal(false, true); // no identity should be present - } catch (x) { - Assert.equal(domain.value, ""); - Assert.equal(user.value, ""); - Assert.equal(pass.value, ""); - } - - am.getAuthIdentity( - "http", - "a.example.com", - -1, - "basic", - "realm", - "", - domain, - user, - pass, - false, - app - ); - Assert.equal(domain.value, "example.com"); - Assert.equal(user.value, "user"); - Assert.equal(pass.value, "pass"); -} diff --git a/netwerk/test/unit/test_auth_multiple.js b/netwerk/test/unit/test_auth_multiple.js index 3cf039ea7d..9574c39b9b 100644 --- a/netwerk/test/unit/test_auth_multiple.js +++ b/netwerk/test/unit/test_auth_multiple.js @@ -42,7 +42,7 @@ AuthPrompt1.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt: function ap1_prompt(title, text, realm, save, defaultText, result) { + prompt: function ap1_prompt() { do_throw("unexpected prompt call"); }, @@ -94,7 +94,7 @@ AuthPrompt1.prototype = { return true; }, - promptPassword: function ap1_promptPW(title, text, realm, save, pwd) { + promptPassword: function ap1_promptPW() { do_throw("unexpected promptPassword call"); }, }; @@ -117,7 +117,7 @@ AuthPrompt2.prototype = { return true; }, - asyncPromptAuth: function ap2_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap2_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -175,7 +175,7 @@ RealmTestRequestor.prototype = { return false; }, - asyncPromptAuth: function realmtest_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function realmtest_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; diff --git a/netwerk/test/unit/test_authentication.js b/netwerk/test/unit/test_authentication.js index 823e2cb36b..f21e0fd4ff 100644 --- a/netwerk/test/unit/test_authentication.js +++ b/netwerk/test/unit/test_authentication.js @@ -43,7 +43,7 @@ AuthPrompt1.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt: function ap1_prompt(title, text, realm, save, defaultText, result) { + prompt: function ap1_prompt() { do_throw("unexpected prompt call"); }, @@ -99,7 +99,7 @@ AuthPrompt1.prototype = { return true; }, - promptPassword: function ap1_promptPW(title, text, realm, save, pwd) { + promptPassword: function ap1_promptPW() { do_throw("unexpected promptPassword call"); }, }; @@ -252,7 +252,7 @@ RealmTestRequestor.prototype = { return false; }, - asyncPromptAuth: function realmtest_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function realmtest_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -377,7 +377,7 @@ function makeChan( var ChannelCreationObserver = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == "http-on-opening-request") { initialChannelId = aSubject.QueryInterface(Ci.nsIIdentChannel).channelId; } @@ -666,7 +666,7 @@ async function test_nonascii_xhr() { await new Promise(resolve => { let xhr = new XMLHttpRequest(); xhr.open("GET", URL + "/auth/non_ascii", true, "é", "é"); - xhr.onreadystatechange = function (event) { + xhr.onreadystatechange = function () { if (xhr.readyState == 4) { Assert.equal(xhr.status, 200); resolve(); diff --git a/netwerk/test/unit/test_authpromptwrapper.js b/netwerk/test/unit/test_authpromptwrapper.js index 69680354ab..85bf690bca 100644 --- a/netwerk/test/unit/test_authpromptwrapper.js +++ b/netwerk/test/unit/test_authpromptwrapper.js @@ -51,7 +51,7 @@ function run_test() { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt: function ap1_prompt(title, text, realm, save, defaultText, result) { + prompt: function ap1_prompt(title, text, realm) { this.called |= CALLED_PROMPT; this.doChecks(text, realm); return this.rv; diff --git a/netwerk/test/unit/test_backgroundfilesaver.js b/netwerk/test/unit/test_backgroundfilesaver.js index eeceab9bf8..58382fa98b 100644 --- a/netwerk/test/unit/test_backgroundfilesaver.js +++ b/netwerk/test/unit/test_backgroundfilesaver.js @@ -213,11 +213,7 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { * @resolves When the operation completes with a success code. * @rejects With an exception, if the operation fails. */ -function promisePumpToSaver( - aSourceString, - aSaverStreamListener, - aCloseWhenDone -) { +function promisePumpToSaver(aSourceString, aSaverStreamListener) { return new Promise((resolve, reject) => { aSaverStreamListener.QueryInterface(Ci.nsIStreamListener); let inputStream = new StringInputStream( @@ -603,7 +599,7 @@ add_task(async function test_enableAppend_hash() { add_task(async function test_finish_only() { // This test checks creating the object and doing nothing. let saver = new BackgroundFileSaverOutputStream(); - function onTargetChange(aTarget) { + function onTargetChange() { do_throw("Should not receive the onTargetChange notification."); } let completionPromise = promiseSaverComplete(saver, onTargetChange); diff --git a/netwerk/test/unit/test_be_conservative.js b/netwerk/test/unit/test_be_conservative.js index af8cf23976..8998420c9e 100644 --- a/netwerk/test/unit/test_be_conservative.js +++ b/netwerk/test/unit/test_be_conservative.js @@ -169,7 +169,7 @@ function startClient(port, beConservative, expectSuccess) { req.open("GET", `https://${hostname}:${port}`); let internalChannel = req.channel.QueryInterface(Ci.nsIHttpChannelInternal); internalChannel.beConservative = beConservative; - return new Promise((resolve, reject) => { + return new Promise(resolve => { req.onload = () => { ok( expectSuccess, diff --git a/netwerk/test/unit/test_be_conservative_error_handling.js b/netwerk/test/unit/test_be_conservative_error_handling.js index eae3042592..b1d1e58e10 100644 --- a/netwerk/test/unit/test_be_conservative_error_handling.js +++ b/netwerk/test/unit/test_be_conservative_error_handling.js @@ -151,7 +151,7 @@ function startClient(port, beConservative, expectSuccess) { req.open("GET", `https://${hostname}:${port}`); let internalChannel = req.channel.QueryInterface(Ci.nsIHttpChannelInternal); internalChannel.beConservative = beConservative; - return new Promise((resolve, reject) => { + return new Promise(resolve => { req.onload = () => { ok( expectSuccess, diff --git a/netwerk/test/unit/test_brotli_decoding.js b/netwerk/test/unit/test_brotli_decoding.js index 55e2869401..bb5229cf73 100644 --- a/netwerk/test/unit/test_brotli_decoding.js +++ b/netwerk/test/unit/test_brotli_decoding.js @@ -26,7 +26,7 @@ let channelListener = function (closure) { }; channelListener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { let data = read_stream(stream, cnt); @@ -39,7 +39,7 @@ channelListener.prototype = { } }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest() { this._closure(); }, }; diff --git a/netwerk/test/unit/test_bug1064258.js b/netwerk/test/unit/test_bug1064258.js index 9be44254b5..9cf59287be 100644 --- a/netwerk/test/unit/test_bug1064258.js +++ b/netwerk/test/unit/test_bug1064258.js @@ -22,7 +22,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_bug1177909.js b/netwerk/test/unit/test_bug1177909.js index 0fc94f8a2c..5b4e23fd0a 100644 --- a/netwerk/test/unit/test_bug1177909.js +++ b/netwerk/test/unit/test_bug1177909.js @@ -55,9 +55,9 @@ async function TestProxyType(chan, flags) { Ci.nsIProtocolProxyService.PROXYCONFIG_SYSTEM ); - return new Promise((resolve, reject) => { + return new Promise(resolve => { gProxyService.asyncResolve(chan, flags, { - onProxyAvailable(req, uri, pi, status) { + onProxyAvailable(req, uri, pi) { resolve(pi); }, }); diff --git a/netwerk/test/unit/test_bug1218029.js b/netwerk/test/unit/test_bug1218029.js index 48165807bf..c3eaa201a4 100644 --- a/netwerk/test/unit/test_bug1218029.js +++ b/netwerk/test/unit/test_bug1218029.js @@ -84,7 +84,7 @@ function execute_test(test) { equal(status, test.status); }, onIncrementalData(loader, context, length, data, consumed) { - ok(chunkIndex < test.dataChunks.length - 1); + Assert.less(chunkIndex, test.dataChunks.length - 1); var expectedChunk = test.dataChunks[chunkIndex]; equal(length, expectedChunk.length); equal(String.fromCharCode.apply(null, data), expectedChunk); diff --git a/netwerk/test/unit/test_bug1279246.js b/netwerk/test/unit/test_bug1279246.js index be73dbee14..8f904eb7eb 100644 --- a/netwerk/test/unit/test_bug1279246.js +++ b/netwerk/test/unit/test_bug1279246.js @@ -45,7 +45,7 @@ Listener.prototype = { } }, - onStopRequest(request, status) { + onStopRequest() { if (pass == 0) { Assert.equal(this._buffer.length, responseLen); pass++; diff --git a/netwerk/test/unit/test_bug1312774_http1.js b/netwerk/test/unit/test_bug1312774_http1.js index 6f100295ae..9232e0042b 100644 --- a/netwerk/test/unit/test_bug1312774_http1.js +++ b/netwerk/test/unit/test_bug1312774_http1.js @@ -90,11 +90,11 @@ function HttpResponseListener(id) { } HttpResponseListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, off, cnt) {}, + onDataAvailable() {}, - onStopRequest(request, status) { + onStopRequest() { log("STOP id=" + this.id); do_test_finished(); }, diff --git a/netwerk/test/unit/test_bug1312782_http1.js b/netwerk/test/unit/test_bug1312782_http1.js index cf820a4f56..15af4da76e 100644 --- a/netwerk/test/unit/test_bug1312782_http1.js +++ b/netwerk/test/unit/test_bug1312782_http1.js @@ -99,11 +99,11 @@ function HttpResponseListener(id) { } HttpResponseListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, off, cnt) {}, + onDataAvailable() {}, - onStopRequest(request, status) { + onStopRequest() { log("STOP id=" + this.id); do_test_finished(); }, diff --git a/netwerk/test/unit/test_bug1355539_http1.js b/netwerk/test/unit/test_bug1355539_http1.js index 17b2930388..50c1114fd5 100644 --- a/netwerk/test/unit/test_bug1355539_http1.js +++ b/netwerk/test/unit/test_bug1355539_http1.js @@ -134,11 +134,11 @@ function HttpResponseListener(id, onStopCallback) { } HttpResponseListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, off, cnt) {}, + onDataAvailable() {}, - onStopRequest(request, status) { + onStopRequest() { log("STOP id=" + this.id); do_test_finished(); if (this.stopCallback) { diff --git a/netwerk/test/unit/test_bug1378385_http1.js b/netwerk/test/unit/test_bug1378385_http1.js index 0e21db3478..3ca4432cdf 100644 --- a/netwerk/test/unit/test_bug1378385_http1.js +++ b/netwerk/test/unit/test_bug1378385_http1.js @@ -113,11 +113,11 @@ function HttpResponseListener(id) { } HttpResponseListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, off, cnt) {}, + onDataAvailable() {}, - onStopRequest(request, status) { + onStopRequest() { log("STOP id=" + this.id); do_test_finished(); }, diff --git a/netwerk/test/unit/test_bug1411316_http1.js b/netwerk/test/unit/test_bug1411316_http1.js index d1df42afdc..529fbead9a 100644 --- a/netwerk/test/unit/test_bug1411316_http1.js +++ b/netwerk/test/unit/test_bug1411316_http1.js @@ -72,9 +72,9 @@ function HttpResponseListener(id, onStopRequestStatus) { } HttpResponseListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, off, cnt) {}, + onDataAvailable() {}, onStopRequest(request, status) { log("STOP id=" + this.id + " status=" + status); diff --git a/netwerk/test/unit/test_bug1527293.js b/netwerk/test/unit/test_bug1527293.js index bed2bddec6..5a86243495 100644 --- a/netwerk/test/unit/test_bug1527293.js +++ b/netwerk/test/unit/test_bug1527293.js @@ -25,7 +25,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_bug1683176.js b/netwerk/test/unit/test_bug1683176.js index 9b0fddf7bd..f7b30e80f1 100644 --- a/netwerk/test/unit/test_bug1683176.js +++ b/netwerk/test/unit/test_bug1683176.js @@ -66,7 +66,7 @@ function channelOpenPromise(chan) { let topic = "http-on-transaction-suspended-authentication"; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == topic) { Services.obs.removeObserver(observer, topic); let channel = aSubject.QueryInterface(Ci.nsIChannel); diff --git a/netwerk/test/unit/test_bug282432.js b/netwerk/test/unit/test_bug282432.js index 5e6e7a19b6..1dc8d890fa 100644 --- a/netwerk/test/unit/test_bug282432.js +++ b/netwerk/test/unit/test_bug282432.js @@ -11,7 +11,7 @@ function run_test() { "nsIRequestObserver", ]), - onStartRequest(aRequest) {}, + onStartRequest() {}, onStopRequest(aRequest, aStatusCode) { // Make sure we can catch the error NS_ERROR_FILE_NOT_FOUND here. @@ -19,7 +19,7 @@ function run_test() { do_test_finished(); }, - onDataAvailable(aRequest, aStream, aOffset, aCount) { + onDataAvailable() { do_throw("The channel must not call onDataAvailable()."); }, }; diff --git a/netwerk/test/unit/test_bug331825.js b/netwerk/test/unit/test_bug331825.js index 5a389c74a4..15a5d36053 100644 --- a/netwerk/test/unit/test_bug331825.js +++ b/netwerk/test/unit/test_bug331825.js @@ -8,8 +8,8 @@ var server; const BUGID = "331825"; function TestListener() {} -TestListener.prototype.onStartRequest = function (request) {}; -TestListener.prototype.onStopRequest = function (request, status) { +TestListener.prototype.onStartRequest = function () {}; +TestListener.prototype.onStopRequest = function (request) { var channel = request.QueryInterface(Ci.nsIHttpChannel); Assert.equal(channel.responseStatus, 304); diff --git a/netwerk/test/unit/test_bug369787.js b/netwerk/test/unit/test_bug369787.js index 36cf2472e1..3254bdf568 100644 --- a/netwerk/test/unit/test_bug369787.js +++ b/netwerk/test/unit/test_bug369787.js @@ -29,7 +29,7 @@ TestListener.prototype.onStartRequest = function (request) { throw ex; } }; -TestListener.prototype.onStopRequest = function (request, status) { +TestListener.prototype.onStopRequest = function () { try { change_content_type(); } catch (ex) { @@ -68,6 +68,6 @@ function run_test() { } // PATH HANDLER FOR /bug369787 -function bug369787(metadata, response) { +function bug369787() { /* do nothing */ } diff --git a/netwerk/test/unit/test_bug401564.js b/netwerk/test/unit/test_bug401564.js index 7cc52f3965..9b92272410 100644 --- a/netwerk/test/unit/test_bug401564.js +++ b/netwerk/test/unit/test_bug401564.js @@ -14,12 +14,12 @@ function redirectHandler(metadata, response) { response.setHeader("Location", noRedirectURI, false); } -function contentHandler(metadata, response) { +function contentHandler(metadata) { Assert.equal(metadata.getHeader("Accept"), acceptType); httpserver.stop(do_test_finished); } -function dummyHandler(request, buffer) {} +function dummyHandler() {} function run_test() { httpserver = new HttpServer(); diff --git a/netwerk/test/unit/test_bug412945.js b/netwerk/test/unit/test_bug412945.js index 78c48bbf22..c44aa48795 100644 --- a/netwerk/test/unit/test_bug412945.js +++ b/netwerk/test/unit/test_bug412945.js @@ -8,9 +8,9 @@ var httpserv; function TestListener() {} -TestListener.prototype.onStartRequest = function (request) {}; +TestListener.prototype.onStartRequest = function () {}; -TestListener.prototype.onStopRequest = function (request, status) { +TestListener.prototype.onStopRequest = function () { httpserv.stop(do_test_finished); }; @@ -34,7 +34,7 @@ function run_test() { do_test_pending(); } -function bug412945(metadata, response) { +function bug412945(metadata) { if ( !metadata.hasHeader("Content-Length") || metadata.getHeader("Content-Length") != "0" diff --git a/netwerk/test/unit/test_bug455311.js b/netwerk/test/unit/test_bug455311.js index 36e000a174..284fcf0ac7 100644 --- a/netwerk/test/unit/test_bug455311.js +++ b/netwerk/test/unit/test_bug455311.js @@ -25,7 +25,7 @@ NotificationCallbacks.prototype = { getInterface(iid) { return this.QueryInterface(iid); }, - asyncOnChannelRedirect(oldChan, newChan, flags, callback) { + asyncOnChannelRedirect(oldChan, newChan) { Assert.equal(oldChan.URI.spec, this._origURI.spec); Assert.equal(oldChan.URI, this._origURI); Assert.equal(oldChan.originalURI.spec, this._origURI.spec); @@ -54,7 +54,7 @@ RequestObserver.prototype = { Assert.equal(chan.originalURI.spec, this._origURI.spec); Assert.equal(chan.originalURI, this._origURI); }, - onDataAvailable(req, stream, offset, count) { + onDataAvailable() { do_throw("Unexpected call to onDataAvailable"); }, onStopRequest(req, status) { diff --git a/netwerk/test/unit/test_bug468426.js b/netwerk/test/unit/test_bug468426.js index def7041ad8..e2598721d3 100644 --- a/netwerk/test/unit/test_bug468426.js +++ b/netwerk/test/unit/test_bug468426.js @@ -58,7 +58,7 @@ function triggerNextTest() { channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { Assert.equal(tests[index].expected, data); if (index < tests.length - 1) { diff --git a/netwerk/test/unit/test_bug468594.js b/netwerk/test/unit/test_bug468594.js index abab980f48..de7ed84f6f 100644 --- a/netwerk/test/unit/test_bug468594.js +++ b/netwerk/test/unit/test_bug468594.js @@ -101,7 +101,7 @@ function triggerNextTest() { channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { logit(index, data); Assert.equal(tests[index].expected, data); diff --git a/netwerk/test/unit/test_bug470716.js b/netwerk/test/unit/test_bug470716.js index 009e7eee11..f359aa9c1e 100644 --- a/netwerk/test/unit/test_bug470716.js +++ b/netwerk/test/unit/test_bug470716.js @@ -26,7 +26,7 @@ var test_sink_closed; var test_nr; var copyObserver = { - onStartRequest(request) {}, + onStartRequest() {}, onStopRequest(request, statusCode) { // check status code diff --git a/netwerk/test/unit/test_bug482601.js b/netwerk/test/unit/test_bug482601.js index ae4e848dbf..04ee143cdb 100644 --- a/netwerk/test/unit/test_bug482601.js +++ b/netwerk/test/unit/test_bug482601.js @@ -13,7 +13,7 @@ var buffer = ""; var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject, topic) { if (observers_called.length) { observers_called += ","; } @@ -23,7 +23,7 @@ var observer = { }; var listener = { - onStartRequest(request) { + onStartRequest() { buffer = ""; }, @@ -259,6 +259,6 @@ function bug482601_cached(metadata, response) { } // /bug482601/only_from_cache -function bug482601_only_from_cache(metadata, response) { +function bug482601_only_from_cache() { do_throw("This should not be reached"); } diff --git a/netwerk/test/unit/test_bug482934.js b/netwerk/test/unit/test_bug482934.js index ee2579b1bb..8388c35d2b 100644 --- a/netwerk/test/unit/test_bug482934.js +++ b/netwerk/test/unit/test_bug482934.js @@ -91,7 +91,7 @@ add_test(() => { var ch = make_channel(resource_url); ch.asyncOpen( - new ChannelListener(function (aRequest, aData) { + new ChannelListener(function (aRequest) { syncWithCacheIOThread(() => { Assert.ok(hit_server); Assert.equal( @@ -117,7 +117,7 @@ add_test(() => { var ch = make_channel(resource_url); ch.asyncOpen( - new ChannelListener(function (aRequest, aData) { + new ChannelListener(function (aRequest) { syncWithCacheIOThread(() => { Assert.ok(hit_server); Assert.equal( @@ -170,7 +170,7 @@ add_test(() => { response_time = "Sat, 3 Jan 2009 00:00:00 GMT"; var ch = make_channel(resource_url); ch.asyncOpen( - new ChannelListener(function (aRequest, aData) { + new ChannelListener(function (aRequest) { syncWithCacheIOThread(() => { Assert.ok(hit_server); Assert.equal( diff --git a/netwerk/test/unit/test_bug490095.js b/netwerk/test/unit/test_bug490095.js index 4e0a37e450..261632b4c7 100644 --- a/netwerk/test/unit/test_bug490095.js +++ b/netwerk/test/unit/test_bug490095.js @@ -79,7 +79,7 @@ function triggerNextTest() { channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { logit(index, data); Assert.equal(tests[index].expected, data); diff --git a/netwerk/test/unit/test_bug510359.js b/netwerk/test/unit/test_bug510359.js index a273cc4710..2262e0a2e6 100644 --- a/netwerk/test/unit/test_bug510359.js +++ b/netwerk/test/unit/test_bug510359.js @@ -28,7 +28,7 @@ function triggerNextTest() { channel.asyncOpen(new ChannelListener(checkValueAndTrigger, null)); } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { Assert.equal(tests[index].expected, data); if (index < tests.length - 1) { diff --git a/netwerk/test/unit/test_bug536324_64bit_content_length.js b/netwerk/test/unit/test_bug536324_64bit_content_length.js index 7ed8ceca6f..c81c619f31 100644 --- a/netwerk/test/unit/test_bug536324_64bit_content_length.js +++ b/netwerk/test/unit/test_bug536324_64bit_content_length.js @@ -14,16 +14,16 @@ const CONTENT_LENGTH = "1152921504606846975"; var httpServer = null; var listener = { - onStartRequest(req) {}, + onStartRequest() {}, - onDataAvailable(req, stream, off, count) { + onDataAvailable(req) { Assert.equal(req.getResponseHeader("Content-Length"), CONTENT_LENGTH); // We're done here, cancel the channel req.cancel(Cr.NS_BINDING_ABORTED); }, - onStopRequest(req, stat) { + onStopRequest() { httpServer.stop(do_test_finished); }, }; diff --git a/netwerk/test/unit/test_bug540566.js b/netwerk/test/unit/test_bug540566.js index 24260421ad..354b5c509f 100644 --- a/netwerk/test/unit/test_bug540566.js +++ b/netwerk/test/unit/test_bug540566.js @@ -4,7 +4,7 @@ "use strict"; -function continue_test(status, entry) { +function continue_test(status) { Assert.equal(status, Cr.NS_OK); // TODO - mayhemer: remove this tests completely // entry.deviceID; diff --git a/netwerk/test/unit/test_bug561042.js b/netwerk/test/unit/test_bug561042.js index 6bdf4d59a6..63696f2ae7 100644 --- a/netwerk/test/unit/test_bug561042.js +++ b/netwerk/test/unit/test_bug561042.js @@ -17,9 +17,9 @@ for (let i = 0; i < 10000; i++) { } var listener = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream) {}, + onDataAvailable() {}, onStopRequest(request, status) { Assert.equal(status, Cr.NS_OK); diff --git a/netwerk/test/unit/test_bug561276.js b/netwerk/test/unit/test_bug561276.js index 9176b7c702..532ef056e6 100644 --- a/netwerk/test/unit/test_bug561276.js +++ b/netwerk/test/unit/test_bug561276.js @@ -22,7 +22,7 @@ function setupChannel(suffix) { return httpChan; } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { Assert.equal("Ok", data); httpserver.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_bug586908.js b/netwerk/test/unit/test_bug586908.js index 1d3ab20347..1491729f19 100644 --- a/netwerk/test/unit/test_bug586908.js +++ b/netwerk/test/unit/test_bug586908.js @@ -15,13 +15,13 @@ ChromeUtils.defineLazyGetter(this, "systemSettings", function () { mainThreadOnly: true, PACURI: "http://localhost:" + httpserv.identity.primaryPort + "/redirect", - getProxyForURI(aURI) { + getProxyForURI() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; }); -function checkValue(request, data, ctx) { +function checkValue(request, data) { Assert.ok(called); Assert.equal("ok", data); httpserv.stop(do_test_finished); diff --git a/netwerk/test/unit/test_bug596443.js b/netwerk/test/unit/test_bug596443.js index 55f9922e07..156bf33d29 100644 --- a/netwerk/test/unit/test_bug596443.js +++ b/netwerk/test/unit/test_bug596443.js @@ -39,13 +39,13 @@ Listener.prototype = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, onDataAvailable(request, stream, offset, count) { this._buffer = this._buffer.concat(read_stream(stream, count)); }, - onStopRequest(request, status) { + onStopRequest() { Assert.equal(this._buffer, this._response); if (--expectedOnStopRequests == 0) { do_timeout(10, function () { diff --git a/netwerk/test/unit/test_bug618835.js b/netwerk/test/unit/test_bug618835.js index 4f4ea8b776..61946209e5 100644 --- a/netwerk/test/unit/test_bug618835.js +++ b/netwerk/test/unit/test_bug618835.js @@ -29,8 +29,8 @@ function setupChannel(path) { // Verify that Content-Location-URI has been loaded once, load post_target function InitialListener() {} InitialListener.prototype = { - onStartRequest(request) {}, - onStopRequest(request, status) { + onStartRequest() {}, + onStopRequest() { Assert.equal(1, numberOfCLHandlerCalls); executeSoon(function () { var channel = setupChannel( @@ -45,8 +45,8 @@ InitialListener.prototype = { // Verify that Location-URI has been loaded once, reload post_target function RedirectingListener() {} RedirectingListener.prototype = { - onStartRequest(request) {}, - onStopRequest(request, status) { + onStartRequest() {}, + onStopRequest() { Assert.equal(1, numberOfHandlerCalls); executeSoon(function () { var channel = setupChannel( @@ -62,8 +62,8 @@ RedirectingListener.prototype = { // reload Content-Location-URI function VerifyingListener() {} VerifyingListener.prototype = { - onStartRequest(request) {}, - onStopRequest(request, status) { + onStartRequest() {}, + onStopRequest() { Assert.equal(2, numberOfHandlerCalls); var channel = setupChannel( "http://localhost:" + httpserv.identity.primaryPort + "/cl" @@ -76,8 +76,8 @@ VerifyingListener.prototype = { // stop test function FinalListener() {} FinalListener.prototype = { - onStartRequest(request) {}, - onStopRequest(request, status) { + onStartRequest() {}, + onStopRequest() { Assert.equal(2, numberOfCLHandlerCalls); httpserv.stop(do_test_finished); }, diff --git a/netwerk/test/unit/test_bug633743.js b/netwerk/test/unit/test_bug633743.js index 6e49751c78..d6be50b7c2 100644 --- a/netwerk/test/unit/test_bug633743.js +++ b/netwerk/test/unit/test_bug633743.js @@ -10,7 +10,7 @@ const CACHECTRL_HDR_NAME = "X-CACHE-CONTROL-HEADER"; var httpserver = null; -function make_channel(flags, vary, value) { +function make_channel() { var chan = NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/bug633743", loadUsingSystemPrincipal: true, @@ -39,13 +39,13 @@ Test.prototype = { "nsIRequestObserver", ]), - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { this._buffer = this._buffer.concat(read_stream(stream, count)); }, - onStopRequest(request, status) { + onStopRequest() { Assert.equal(this._buffer, this._expectVal); do_timeout(0, run_next_test); }, diff --git a/netwerk/test/unit/test_bug650995.js b/netwerk/test/unit/test_bug650995.js index d9ccab6540..e7032b09e2 100644 --- a/netwerk/test/unit/test_bug650995.js +++ b/netwerk/test/unit/test_bug650995.js @@ -158,7 +158,7 @@ function TestCacheEntrySize( channel.asyncOpen(new ChannelListener(ctx.testAndTriggerNext, ctx)); }); }; - this.testAndTriggerNext = function (request, data, ctx) { + this.testAndTriggerNext = function (request, data) { Assert.equal(secondExpectedReply, data); executeSoon(nextTest); }; diff --git a/netwerk/test/unit/test_bug659569.js b/netwerk/test/unit/test_bug659569.js index 1bdc61b618..4235c742e0 100644 --- a/netwerk/test/unit/test_bug659569.js +++ b/netwerk/test/unit/test_bug659569.js @@ -13,7 +13,7 @@ function setupChannel(suffix) { }); } -function checkValueAndTrigger(request, data, ctx) { +function checkValueAndTrigger(request, data) { Assert.equal("Ok", data); httpserver.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_bug667907.js b/netwerk/test/unit/test_bug667907.js index 5c6b13d538..b407a4777b 100644 --- a/netwerk/test/unit/test_bug667907.js +++ b/netwerk/test/unit/test_bug667907.js @@ -35,7 +35,7 @@ var listener_proto = { request.cancel(Cr.NS_BINDING_ABORTED); }, - onDataAvailable(request, stream, offset, count) { + onDataAvailable() { do_throw("Unexpected onDataAvailable"); }, diff --git a/netwerk/test/unit/test_bug669001.js b/netwerk/test/unit/test_bug669001.js index ebd5998cf1..c402a6e975 100644 --- a/netwerk/test/unit/test_bug669001.js +++ b/netwerk/test/unit/test_bug669001.js @@ -28,13 +28,13 @@ var fetched; var tests = [ { prepare() {}, - test(response) { + test() { Assert.ok(fetched); }, }, { prepare() {}, - test(response) { + test() { Assert.ok(!fetched); }, }, @@ -42,13 +42,13 @@ var tests = [ prepare() { setUA("A different User Agent"); }, - test(response) { + test() { Assert.ok(fetched); }, }, { prepare() {}, - test(response) { + test() { Assert.ok(!fetched); }, }, @@ -56,13 +56,13 @@ var tests = [ prepare() { setUA("And another User Agent"); }, - test(response) { + test() { Assert.ok(fetched); }, }, { prepare() {}, - test(response) { + test() { Assert.ok(!fetched); }, }, diff --git a/netwerk/test/unit/test_bug812167.js b/netwerk/test/unit/test_bug812167.js index 8f4d1310a0..1773a733c2 100644 --- a/netwerk/test/unit/test_bug812167.js +++ b/netwerk/test/unit/test_bug812167.js @@ -25,7 +25,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI2", function () { return "http://localhost:" + httpserver.identity.primaryPort + randomPath2; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_bug856978.js b/netwerk/test/unit/test_bug856978.js index 607b392473..5152abb764 100644 --- a/netwerk/test/unit/test_bug856978.js +++ b/netwerk/test/unit/test_bug856978.js @@ -55,7 +55,7 @@ RequestObserver.prototype = { "nsISupportsWeakReference", ]), - observe(subject, topic, data) { + observe(subject, topic) { if (topic == notification) { if (!(subject instanceof Ci.nsIHttpChannel)) { do_throw(notification + " observed a non-HTTP channel."); @@ -76,13 +76,13 @@ RequestObserver.prototype = { }; var listener = { - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA() { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { if (current_test < tests.length - 1) { current_test++; tests[current_test](); diff --git a/netwerk/test/unit/test_bug894586.js b/netwerk/test/unit/test_bug894586.js index bc25731d36..ecce039790 100644 --- a/netwerk/test/unit/test_bug894586.js +++ b/netwerk/test/unit/test_bug894586.js @@ -25,7 +25,7 @@ ProtocolHandler.prototype = { this.loadInfo = aLoadInfo; return this; }, - allowPort(port, scheme) { + allowPort(port) { return port != -1; }, @@ -67,7 +67,7 @@ ProtocolHandler.prototype = { loadUsingSystemPrincipal: true, }).open(); }, - asyncOpen(aListener, aContext) { + asyncOpen() { throw Components.Exception("Not implemented", Cr.NS_ERROR_NOT_IMPLEMENTED); }, contentDisposition: Ci.nsIChannel.DISPOSITION_INLINE, @@ -86,7 +86,7 @@ ProtocolHandler.prototype = { get status() { return Cr.NS_OK; }, - cancel(status) {}, + cancel() {}, loadGroup: null, loadFlags: Ci.nsIRequest.LOAD_NORMAL | diff --git a/netwerk/test/unit/test_cache-control_request.js b/netwerk/test/unit/test_cache-control_request.js index f0873cba24..25ca26f40b 100644 --- a/netwerk/test/unit/test_cache-control_request.js +++ b/netwerk/test/unit/test_cache-control_request.js @@ -106,7 +106,7 @@ add_test(() => { // Must not create a cache entry var ch = make_channel(resource_age_100_url, "no-store"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(!cache.exists(make_uri(resource_age_100_url), "")); @@ -119,7 +119,7 @@ add_test(() => { // Prepare state only, cache the entry var ch = make_channel(resource_age_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -132,7 +132,7 @@ add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -146,7 +146,7 @@ add_test(() => { // the channel must not use it, entry should stay in the cache var ch = make_channel(resource_age_100_url, "no-store"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -162,7 +162,7 @@ add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -175,7 +175,7 @@ add_test(() => { // The existing entry should be revalidated (we expect a server hit) var ch = make_channel(resource_age_100_url, "no-cache"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -191,7 +191,7 @@ add_test(() => { // Check the prepared cache entry is used when no special directives are added var ch = make_channel(resource_age_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -205,7 +205,7 @@ add_test(() => { // should hit server var ch = make_channel(resource_age_100_url, "max-age=10"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -219,7 +219,7 @@ add_test(() => { // but the max-stale directive says to use it when it's fresh enough var ch = make_channel(resource_age_100_url, "max-age=10, max-stale=99999"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -233,7 +233,7 @@ add_test(() => { // should go from cache var ch = make_channel(resource_age_100_url, "max-age=1000"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_age_100_url), "")); @@ -249,7 +249,7 @@ add_test(() => { // Preprate the entry first var ch = make_channel(resource_stale_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); @@ -264,7 +264,7 @@ add_test(() => { // are provided var ch = make_channel(resource_stale_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); @@ -277,7 +277,7 @@ add_test(() => { // Accept cached responses of any stale time var ch = make_channel(resource_stale_100_url, "max-stale"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); @@ -290,7 +290,7 @@ add_test(() => { // The entry is stale only by 100 seconds, accept it var ch = make_channel(resource_stale_100_url, "max-stale=1000"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); @@ -304,7 +304,7 @@ add_test(() => { // entry, go from server var ch = make_channel(resource_stale_100_url, "max-stale=10"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_stale_100_url), "")); @@ -320,7 +320,7 @@ add_test(() => { // Preprate the entry first var ch = make_channel(resource_fresh_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); @@ -333,7 +333,7 @@ add_test(() => { // Check it's reused when no special directives are provided var ch = make_channel(resource_fresh_100_url); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); @@ -346,7 +346,7 @@ add_test(() => { // Entry fresh enough to be served from the cache var ch = make_channel(resource_fresh_100_url, "min-fresh=10"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(!hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); @@ -359,7 +359,7 @@ add_test(() => { // The entry is not fresh enough var ch = make_channel(resource_fresh_100_url, "min-fresh=1000"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); @@ -378,7 +378,7 @@ add_test(() => { 'unknown1,unknown2 = "a,b", min-fresh = 1000 ' ); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); @@ -390,7 +390,7 @@ add_test(() => { add_test(() => { var ch = make_channel(resource_fresh_100_url, "no-cache = , min-fresh = 10"); ch.asyncOpen( - new ChannelListener(function (request, data) { + new ChannelListener(function () { Assert.ok(hit_server); Assert.ok(cache.exists(make_uri(resource_fresh_100_url), "")); diff --git a/netwerk/test/unit/test_cache2-02b-open-non-existing-and-doom.js b/netwerk/test/unit/test_cache2-02b-open-non-existing-and-doom.js index d54aeeb9eb..67c5d14c54 100644 --- a/netwerk/test/unit/test_cache2-02b-open-non-existing-and-doom.js +++ b/netwerk/test/unit/test_cache2-02b-open-non-existing-and-doom.js @@ -126,7 +126,7 @@ add_task(async function test() { onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, status) { + onCacheEntryAvailable() { info("opened"); r2(); }, @@ -154,17 +154,7 @@ add_task(async function test() { let entryCount = 0; let visitor = { onCacheStorageInfo() {}, - async onCacheEntryInfo( - aURI, - aIdEnhance, - aDataSize, - aAltDataSize, - aFetchCount, - aLastModifiedTime, - aExpirationTime, - aPinned, - aInfo - ) { + async onCacheEntryInfo() { entryCount++; }, onCacheEntryVisitCompleted() { diff --git a/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js b/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js index 395c41dd7c..a0602d80e6 100644 --- a/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js +++ b/netwerk/test/unit/test_cache2-08-evict-disk-by-memory-storage.js @@ -8,7 +8,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW, "a1m", "a1d", function (entry) { + new OpenCallback(NEW, "a1m", "a1d", function () { var storage = getCacheStorage("memory"); // Have to fail storage.asyncDoomURI( diff --git a/netwerk/test/unit/test_cache2-14-concurent-readers.js b/netwerk/test/unit/test_cache2-14-concurent-readers.js index d2e80582dc..2696790f1b 100644 --- a/netwerk/test/unit/test_cache2-14-concurent-readers.js +++ b/netwerk/test/unit/test_cache2-14-concurent-readers.js @@ -8,7 +8,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW, "x1m", "x1d", function (entry) { + new OpenCallback(NEW, "x1m", "x1d", function () { // nothing to do here, we expect concurent callbacks to get // all notified, then the test finishes }) @@ -21,7 +21,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "x1m", "x1d", function (entry) { + new OpenCallback(NORMAL, "x1m", "x1d", function () { mc.fired(); }) ); @@ -30,7 +30,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "x1m", "x1d", function (entry) { + new OpenCallback(NORMAL, "x1m", "x1d", function () { mc.fired(); }) ); @@ -39,7 +39,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "x1m", "x1d", function (entry) { + new OpenCallback(NORMAL, "x1m", "x1d", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js b/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js index 244dca9a3b..5da0937836 100644 --- a/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js +++ b/netwerk/test/unit/test_cache2-14b-concurent-readers-complete.js @@ -8,7 +8,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NEW, "x1m", "x1d", function (entry) { + new OpenCallback(NEW, "x1m", "x1d", function () { // nothing to do here, we expect concurent callbacks to get // all notified, then the test finishes }) diff --git a/netwerk/test/unit/test_cache2-15-conditional-304.js b/netwerk/test/unit/test_cache2-15-conditional-304.js index 7b672e69a2..5133b4cd96 100644 --- a/netwerk/test/unit/test_cache2-15-conditional-304.js +++ b/netwerk/test/unit/test_cache2-15-conditional-304.js @@ -31,7 +31,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "31m", "31d", function (entry) { + new OpenCallback(NORMAL, "31m", "31d", function () { mc.fired(); }) ); @@ -40,7 +40,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "31m", "31d", function (entry) { + new OpenCallback(NORMAL, "31m", "31d", function () { mc.fired(); }) ); @@ -49,7 +49,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "31m", "31d", function (entry) { + new OpenCallback(NORMAL, "31m", "31d", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-16-conditional-200.js b/netwerk/test/unit/test_cache2-16-conditional-200.js index beaa3f0dae..6c8b3f0728 100644 --- a/netwerk/test/unit/test_cache2-16-conditional-200.js +++ b/netwerk/test/unit/test_cache2-16-conditional-200.js @@ -45,7 +45,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "22m", "22d", function (entry) { + new OpenCallback(NORMAL, "22m", "22d", function () { mc.fired(); }) ); @@ -54,7 +54,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "22m", "22d", function (entry) { + new OpenCallback(NORMAL, "22m", "22d", function () { mc.fired(); }) ); @@ -63,7 +63,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "22m", "22d", function (entry) { + new OpenCallback(NORMAL, "22m", "22d", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-19-range-206.js b/netwerk/test/unit/test_cache2-19-range-206.js index f3f9491932..b29b4b27f0 100644 --- a/netwerk/test/unit/test_cache2-19-range-206.js +++ b/netwerk/test/unit/test_cache2-19-range-206.js @@ -36,7 +36,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "206m", "206part1--part2", function (entry) { + new OpenCallback(NORMAL, "206m", "206part1--part2", function () { mc.fired(); }) ); @@ -45,7 +45,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "206m", "206part1--part2", function (entry) { + new OpenCallback(NORMAL, "206m", "206part1--part2", function () { mc.fired(); }) ); @@ -54,7 +54,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "206m", "206part1--part2", function (entry) { + new OpenCallback(NORMAL, "206m", "206part1--part2", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-20-range-200.js b/netwerk/test/unit/test_cache2-20-range-200.js index 31b8223c35..a3f2dc379e 100644 --- a/netwerk/test/unit/test_cache2-20-range-200.js +++ b/netwerk/test/unit/test_cache2-20-range-200.js @@ -37,9 +37,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function ( - entry - ) { + new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function () { mc.fired(); }) ); @@ -48,9 +46,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function ( - entry - ) { + new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function () { mc.fired(); }) ); @@ -59,9 +55,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null, - new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function ( - entry - ) { + new OpenCallback(NORMAL, "200m2", "200part1b--part2b", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-22-anon-visit.js b/netwerk/test/unit/test_cache2-22-anon-visit.js index 1768f142bd..6ceaa26c9f 100644 --- a/netwerk/test/unit/test_cache2-22-anon-visit.js +++ b/netwerk/test/unit/test_cache2-22-anon-visit.js @@ -24,7 +24,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, - new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function () { mc.fired(); }) ); @@ -34,7 +34,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.anonymous, - new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "an2", "an2", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-24-exists.js b/netwerk/test/unit/test_cache2-24-exists.js index 7f7c50e9f0..662a9b5139 100644 --- a/netwerk/test/unit/test_cache2-24-exists.js +++ b/netwerk/test/unit/test_cache2-24-exists.js @@ -24,7 +24,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, - new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function () { mc.fired(); }) ); @@ -34,7 +34,7 @@ function run_test() { "memory", Ci.nsICacheStorage.OPEN_NORMALLY, Services.loadContextInfo.default, - new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "meta", "data", function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js b/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js index b97c4b113c..da95e63754 100644 --- a/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js +++ b/netwerk/test/unit/test_cache2-29a-concurrent_read_resumable_entry_size_zero.js @@ -27,7 +27,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js b/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js index e221be7661..fb7111659c 100644 --- a/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js +++ b/netwerk/test/unit/test_cache2-29b-concurrent_read_non-resumable_entry_size_zero.js @@ -29,7 +29,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js b/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js index 706ad894ca..3a5b22eea8 100644 --- a/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js +++ b/netwerk/test/unit/test_cache2-29c-concurrent_read_half-interrupted.js @@ -29,7 +29,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js b/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js index d9886a6fbf..e59286ee33 100644 --- a/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js +++ b/netwerk/test/unit/test_cache2-29d-concurrent_read_half-corrupted-206.js @@ -29,7 +29,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -90,6 +90,6 @@ function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) { +function secondTimeThrough() { httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js b/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js index 7d517d518d..a491c9925e 100644 --- a/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js +++ b/netwerk/test/unit/test_cache2-29e-concurrent_read_half-non-206-response.js @@ -29,7 +29,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -85,6 +85,6 @@ function firstTimeThrough(request, buffer) { Assert.equal(buffer, responseBody); } -function secondTimeThrough(request, buffer) { +function secondTimeThrough() { httpServer.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js b/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js index 73dfee0f6b..f70926ebd0 100644 --- a/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js +++ b/netwerk/test/unit/test_cache2-30c-pinning-deferred-doom.js @@ -74,7 +74,7 @@ function run_test() { "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function () { mc.fired(); }) ); @@ -85,7 +85,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function () { mc.fired(); }) ); @@ -95,7 +95,7 @@ function run_test() { Services.obs.addObserver( { - observe(subject, topic, data) { + observe() { // (3) log_("after purge, second set of opens"); @@ -112,7 +112,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function (entry) { + new OpenCallback(NORMAL, "m" + i, "p" + i, function () { mc.fired(); }) ); @@ -131,9 +131,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(MAYBE_NEW | DOOMED, "m" + i, "d" + i, function ( - entry - ) { + new OpenCallback(MAYBE_NEW | DOOMED, "m" + i, "d" + i, function () { mc.fired(); }) ); @@ -158,7 +156,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function (entry) { + new OpenCallback(NORMAL, "m" + i, "p" + i, function () { mc.fired(); }) ); @@ -169,7 +167,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NEW, "m2" + i, "d2" + i, function (entry) { + new OpenCallback(NEW, "m2" + i, "d2" + i, function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js b/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js index fd4622f3f4..aafe911235 100644 --- a/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js +++ b/netwerk/test/unit/test_cache2-30d-pinning-WasEvicted-API.js @@ -69,7 +69,7 @@ function run_test() { "pin", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "p" + i, function () { mc.fired(); }) ); @@ -80,7 +80,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_TRUNCATE, lci, - new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function (entry) { + new OpenCallback(NEW | WAITFORWRITE, "m" + i, "d" + i, function () { mc.fired(); }) ); @@ -90,7 +90,7 @@ function run_test() { Services.obs.addObserver( { - observe(subject, topic, data) { + observe() { // (3) log_("after purge"); @@ -113,7 +113,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NORMAL, "m" + i, "p" + i, function (entry) { + new OpenCallback(NORMAL, "m" + i, "p" + i, function () { mc.fired(); }) ); @@ -124,7 +124,7 @@ function run_test() { "disk", Ci.nsICacheStorage.OPEN_NORMALLY, lci, - new OpenCallback(NEW, "m2" + i, "d2" + i, function (entry) { + new OpenCallback(NEW, "m2" + i, "d2" + i, function () { mc.fired(); }) ); diff --git a/netwerk/test/unit/test_cache_204_response.js b/netwerk/test/unit/test_cache_204_response.js index 3038b7ed71..4c02e1c60d 100644 --- a/netwerk/test/unit/test_cache_204_response.js +++ b/netwerk/test/unit/test_cache_204_response.js @@ -35,7 +35,11 @@ async function get_response(channel, fromCache) { return new Promise(resolve => { channel.asyncOpen( new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + Assert.equal( + fromCache, + isFromCache, + `got response from cache = ${fromCache}` + ); resolve(); }) ); diff --git a/netwerk/test/unit/test_cache_jar.js b/netwerk/test/unit/test_cache_jar.js index bedde668b4..1ab93980a6 100644 --- a/netwerk/test/unit/test_cache_jar.js +++ b/netwerk/test/unit/test_cache_jar.js @@ -20,27 +20,24 @@ function cached_handler(metadata, response) { handlers_called++; } -function makeChan(url, inIsolatedMozBrowser, userContextId) { +function makeChan(url, userContextId) { var chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true, }).QueryInterface(Ci.nsIHttpChannel); - chan.loadInfo.originAttributes = { inIsolatedMozBrowser, userContextId }; + chan.loadInfo.originAttributes = { userContextId }; return chan; } -// [inIsolatedMozBrowser, userContextId, expected_handlers_called] +// [userContextId, expected_handlers_called] var firstTests = [ - [false, 0, 1], - [true, 0, 1], - [false, 1, 1], - [true, 1, 1], + [0, 1], + [1, 1], ]; var secondTests = [ - [false, 0, 0], - [true, 0, 0], - [false, 1, 1], - [true, 1, 0], + [0, 0], + [1, 1], + [1, 0], ]; async function run_all_tests() { @@ -81,9 +78,9 @@ function run_test() { }); } -function test_channel(inIsolatedMozBrowser, userContextId, expected) { +function test_channel(userContextId, expected) { return new Promise(resolve => { - var chan = makeChan(URL, inIsolatedMozBrowser, userContextId); + var chan = makeChan(URL, userContextId); chan.asyncOpen( new ChannelListener(doneFirstLoad.bind(null, resolve), expected) ); @@ -93,7 +90,7 @@ function test_channel(inIsolatedMozBrowser, userContextId, expected) { function doneFirstLoad(resolve, req, buffer, expected) { // Load it again, make sure it hits the cache var oa = req.loadInfo.originAttributes; - var chan = makeChan(URL, oa.isInIsolatedMozBrowserElement, oa.userContextId); + var chan = makeChan(URL, oa.userContextId); chan.asyncOpen( new ChannelListener(doneSecondLoad.bind(null, resolve), expected) ); diff --git a/netwerk/test/unit/test_captive_portal_service.js b/netwerk/test/unit/test_captive_portal_service.js index d5c951d16c..86e0db3b83 100644 --- a/netwerk/test/unit/test_captive_portal_service.js +++ b/netwerk/test/unit/test_captive_portal_service.js @@ -274,7 +274,7 @@ add_task(async function test_changed_notification() { let changedNotificationCount = 0; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe() { changedNotificationCount += 1; }, }; diff --git a/netwerk/test/unit/test_channel_close.js b/netwerk/test/unit/test_channel_close.js index f8f78fd211..a143f4c495 100644 --- a/netwerk/test/unit/test_channel_close.js +++ b/netwerk/test/unit/test_channel_close.js @@ -18,32 +18,41 @@ var httpbody = "0123456789"; var live_channels = []; -function run_test() { +add_task(async function test() { httpserver.registerPathHandler(testpath, serverHandler); httpserver.start(-1); + registerCleanupFunction(async () => { + if (httpserver) { + await httpserver.stop(); + } + }); - httpProtocolHandler.EnsureHSTSDataReady().then(function () { - var local_channel; + await httpProtocolHandler.EnsureHSTSDataReady(); - // Opened channel that has no remaining references on shutdown - local_channel = setupChannel(testpath); - local_channel.asyncOpen(new ChannelListener(checkRequest, local_channel)); + // Opened channel that has no remaining references on shutdown + let local_channel = setupChannel(testpath); + local_channel.asyncOpen(new SimpleChannelListener()); - // Opened channel that has no remaining references after being opened - setupChannel(testpath).asyncOpen(new ChannelListener(function () {}, null)); + // Opened channel that has no remaining references after being opened + setupChannel(testpath).asyncOpen(new SimpleChannelListener()); - // Unopened channel that has remaining references on shutdown - live_channels.push(setupChannel(testpath)); + // Unopened channel that has remaining references on shutdown + live_channels.push(setupChannel(testpath)); - // Opened channel that has remaining references on shutdown - live_channels.push(setupChannel(testpath)); + // Opened channel that has remaining references on shutdown + live_channels.push(setupChannel(testpath)); + await new Promise(resolve => { live_channels[1].asyncOpen( - new ChannelListener(checkRequestFinish, live_channels[1]) + new SimpleChannelListener((req, data) => { + Assert.equal(data, httpbody); + resolve(); + }) ); }); - do_test_pending(); -} + await httpserver.stop(); + httpserver = null; +}); function setupChannel(path) { var chan = NetUtil.newChannel({ @@ -59,12 +68,3 @@ function serverHandler(metadata, response) { response.setHeader("Content-Type", "text/plain", false); response.bodyOutputStream.write(httpbody, httpbody.length); } - -function checkRequest(request, data, context) { - Assert.equal(data, httpbody); -} - -function checkRequestFinish(request, data, context) { - checkRequest(request, data, context); - httpserver.stop(do_test_finished); -} diff --git a/netwerk/test/unit/test_chunked_responses.js b/netwerk/test/unit/test_chunked_responses.js index c8dee14efe..3a2f11a802 100644 --- a/netwerk/test/unit/test_chunked_responses.js +++ b/netwerk/test/unit/test_chunked_responses.js @@ -75,7 +75,7 @@ function handler1(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest1(request, data, ctx) { +function completeTest1(request) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); run_test_number(2); @@ -100,7 +100,7 @@ function handler2(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest2(request, data, ctx) { +function completeTest2(request) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); run_test_number(3); } @@ -124,7 +124,7 @@ function handler3(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest3(request, data, ctx) { +function completeTest3(request) { Assert.equal(request.status, 0); run_test_number(4); } @@ -148,7 +148,7 @@ function handler4(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest4(request, data, ctx) { +function completeTest4(request) { Assert.equal(request.status, 0); run_test_number(5); } @@ -173,7 +173,7 @@ function handler5(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest5(request, data, ctx) { +function completeTest5(request) { Assert.equal(request.status, Cr.NS_ERROR_UNEXPECTED); endTests(); // run_test_number(6); diff --git a/netwerk/test/unit/test_client_auth_with_proxy.js b/netwerk/test/unit/test_client_auth_with_proxy.js index 5a205f4db1..11f0ebdafe 100644 --- a/netwerk/test/unit/test_client_auth_with_proxy.js +++ b/netwerk/test/unit/test_client_auth_with_proxy.js @@ -41,7 +41,7 @@ class SecurityObserver { this.output = output; } - onHandshakeDone(socket, status) { + onHandshakeDone() { info("TLS handshake done"); let output = this.output; diff --git a/netwerk/test/unit/test_connection_based_auth.js b/netwerk/test/unit/test_connection_based_auth.js index 3a21ffcb77..049478aeba 100644 --- a/netwerk/test/unit/test_connection_based_auth.js +++ b/netwerk/test/unit/test_connection_based_auth.js @@ -37,7 +37,7 @@ add_task(async function test_connection_based_auth() { let proxy = new NodeHTTPSProxyServer(); await proxy.start(); - await proxy.registerConnectHandler((req, clientSocket, head) => { + await proxy.registerConnectHandler((req, clientSocket) => { if (!req.headers["proxy-authorization"]) { clientSocket.write( "HTTP/1.1 407 Unauthorized\r\n" + diff --git a/netwerk/test/unit/test_content_encoding_gzip.js b/netwerk/test/unit/test_content_encoding_gzip.js index 48479034b8..1137a306e5 100644 --- a/netwerk/test/unit/test_content_encoding_gzip.js +++ b/netwerk/test/unit/test_content_encoding_gzip.js @@ -113,7 +113,7 @@ function startIter() { ); } -function completeIter(request, data, ctx) { +function completeIter(request, data) { if (!(tests[index].flags & CL_EXPECT_FAILURE)) { Assert.equal(data.length, tests[index].datalen, "test " + index); } diff --git a/netwerk/test/unit/test_content_length_underrun.js b/netwerk/test/unit/test_content_length_underrun.js index f5f8e40a8a..2a01b98110 100644 --- a/netwerk/test/unit/test_content_length_underrun.js +++ b/netwerk/test/unit/test_content_length_underrun.js @@ -73,7 +73,7 @@ function run_gzip_test(num) { "nsIRequestObserver", ]), - onStartRequest(aRequest) {}, + onStartRequest() {}, onStopRequest(aRequest, aStatusCode) { // Make sure we catch the error NS_ERROR_NET_PARTIAL_TRANSFER here. @@ -82,7 +82,7 @@ function run_gzip_test(num) { endTests(); }, - onDataAvailable(request, stream, offset, count) {}, + onDataAvailable() {}, }; let listener = new StreamListener(); @@ -128,7 +128,7 @@ function handler1(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest1(request, data, ctx) { +function completeTest1(request) { Assert.equal(request.status, Cr.NS_ERROR_NET_PARTIAL_TRANSFER); run_test_number(11); @@ -152,7 +152,7 @@ function handler11(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest11(request, data, ctx) { +function completeTest11(request) { Assert.equal(request.status, Cr.NS_OK); run_test_number(2); } @@ -176,7 +176,7 @@ function handler2(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest2(request, data, ctx) { +function completeTest2(request) { Assert.equal(request.status, Cr.NS_OK); // test 3 requires the enforce-framing prefs to be false @@ -207,7 +207,7 @@ function handler3(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest3(request, data, ctx) { +function completeTest3(request) { Assert.equal(request.status, Cr.NS_OK); prefs.setBoolPref("network.http.enforce-framing.soft", true); run_test_number(4); @@ -249,7 +249,7 @@ function handler4(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest4(request, data, ctx) { +function completeTest4(request) { Assert.equal(request.status, Cr.NS_OK); prefs.setBoolPref("network.http.enforce-framing.http1", true); diff --git a/netwerk/test/unit/test_content_sniffer.js b/netwerk/test/unit/test_content_sniffer.js index 26fb55cece..7b109019cd 100644 --- a/netwerk/test/unit/test_content_sniffer.js +++ b/netwerk/test/unit/test_content_sniffer.js @@ -27,7 +27,7 @@ var sniffer = { return this.QueryInterface(iid); }, - getMIMETypeFromContent(request, data, length) { + getMIMETypeFromContent() { return sniffedType; }, }; @@ -72,7 +72,7 @@ var listener = { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { run_test_iteration(this._iteration); do_test_finished(); }, diff --git a/netwerk/test/unit/test_cookie_header.js b/netwerk/test/unit/test_cookie_header.js index a5326ef25c..15f384c5cf 100644 --- a/netwerk/test/unit/test_cookie_header.js +++ b/netwerk/test/unit/test_cookie_header.js @@ -48,7 +48,7 @@ var listener = { throw Components.Exception("", Cr.NS_ERROR_UNEXPECTED); }, - onStopRequest: async function test_onStopR(request, status) { + onStopRequest: async function test_onStopR() { if (this._iteration == 1) { await run_test_continued(); } else { diff --git a/netwerk/test/unit/test_cookiejars.js b/netwerk/test/unit/test_cookiejars.js index 1d78893f8c..aaf8832f62 100644 --- a/netwerk/test/unit/test_cookiejars.js +++ b/netwerk/test/unit/test_cookiejars.js @@ -36,19 +36,11 @@ function inChildProcess() { var tests = [ { cookieName: "LCC_App0_BrowF_PrivF", - originAttributes: new OriginAttributes(0, false, 0), - }, - { - cookieName: "LCC_App0_BrowT_PrivF", - originAttributes: new OriginAttributes(0, true, 0), + originAttributes: new OriginAttributes(0), }, { cookieName: "LCC_App1_BrowF_PrivF", - originAttributes: new OriginAttributes(1, false, 0), - }, - { - cookieName: "LCC_App1_BrowT_PrivF", - originAttributes: new OriginAttributes(1, true, 0), + originAttributes: new OriginAttributes(1), }, ]; @@ -88,7 +80,7 @@ function setCookie() { channel.asyncOpen(new ChannelListener(setNextCookie, null)); } -function setNextCookie(request, data, context) { +function setNextCookie() { if (++i == tests.length) { // all cookies set: switch to checking them i = 0; @@ -106,7 +98,7 @@ function checkCookie() { channel.asyncOpen(new ChannelListener(completeCheckCookie, null)); } -function completeCheckCookie(request, data, context) { +function completeCheckCookie(request) { // Look for all cookies in what the server saw: fail if we see any besides the // one expected cookie for each namespace; var expectedCookie = tests[i].cookieName; diff --git a/netwerk/test/unit/test_cookiejars_safebrowsing.js b/netwerk/test/unit/test_cookiejars_safebrowsing.js index 855bacef42..8cb9d03c37 100644 --- a/netwerk/test/unit/test_cookiejars_safebrowsing.js +++ b/netwerk/test/unit/test_cookiejars_safebrowsing.js @@ -154,7 +154,7 @@ add_test(function test_safebrowsing_gethash() { URL + safebrowsingGethashPath, "test-phish-simple", { - completionV2(hash, table, chunkId) {}, + completionV2() {}, completionFinished(status) { Assert.equal(status, Cr.NS_OK); @@ -181,7 +181,7 @@ add_test(function test_non_safebrowsing_cookie() { ); } - function completeCheckNonSafeBrowsingCookie(request, data, context) { + function completeCheckNonSafeBrowsingCookie(request) { // Confirm that only the >> ONE << cookie is sent over the channel. var expectedCookie = cookieName + "=1"; request.QueryInterface(Ci.nsIHttpChannel); @@ -212,7 +212,7 @@ add_test(function test_safebrowsing_cookie() { ); } - function completeCheckSafeBrowsingCookie(request, data, context) { + function completeCheckSafeBrowsingCookie(request) { // Confirm that all >> THREE << cookies are sent back over the channel: // a) the safebrowsing cookie set when updating // b) the safebrowsing cookie set when sending gethash diff --git a/netwerk/test/unit/test_cookies_async_failure.js b/netwerk/test/unit/test_cookies_async_failure.js index c61da23f99..9aaad03982 100644 --- a/netwerk/test/unit/test_cookies_async_failure.js +++ b/netwerk/test/unit/test_cookies_async_failure.js @@ -158,7 +158,7 @@ async function run_test_1() { Assert.equal(Services.cookies.countCookiesFromHost(cookie.host), 1); let isRebuildingDone = false; - let rebuildingObserve = function (subject, topic, data) { + let rebuildingObserve = function () { isRebuildingDone = true; Services.obs.removeObserver(rebuildingObserve, "cookie-db-rebuilding"); }; diff --git a/netwerk/test/unit/test_dns_localredirect.js b/netwerk/test/unit/test_dns_localredirect.js index 3ca432f477..5907f15b06 100644 --- a/netwerk/test/unit/test_dns_localredirect.js +++ b/netwerk/test/unit/test_dns_localredirect.js @@ -5,7 +5,7 @@ var prefs = Services.prefs; var nextTest; var listener = { - onLookupComplete(inRequest, inRecord, inStatus) { + onLookupComplete(inRequest, inRecord) { inRecord.QueryInterface(Ci.nsIDNSAddrRecord); var answer = inRecord.getNextAddrAsString(); Assert.ok(answer == "127.0.0.1" || answer == "::1"); diff --git a/netwerk/test/unit/test_dns_onion.js b/netwerk/test/unit/test_dns_onion.js index 928753f71f..e13974a39e 100644 --- a/netwerk/test/unit/test_dns_onion.js +++ b/netwerk/test/unit/test_dns_onion.js @@ -17,7 +17,7 @@ var listenerBlock = { // check that we do lookup .onion (via pref) var listenerDontBlock = { - onLookupComplete(inRequest, inRecord, inStatus) { + onLookupComplete(inRequest, inRecord) { inRecord.QueryInterface(Ci.nsIDNSAddrRecord); var answer = inRecord.getNextAddrAsString(); Assert.ok(answer == "127.0.0.1" || answer == "::1"); diff --git a/netwerk/test/unit/test_dns_proxy_bypass.js b/netwerk/test/unit/test_dns_proxy_bypass.js index d53efc3dd3..6951b5cd1f 100644 --- a/netwerk/test/unit/test_dns_proxy_bypass.js +++ b/netwerk/test/unit/test_dns_proxy_bypass.js @@ -48,12 +48,12 @@ function WSListener(closure) { this._closure = closure; } WSListener.prototype = { - onAcknowledge(aContext, aSize) {}, - onBinaryMessageAvailable(aContext, aMsg) {}, - onMessageAvailable(aContext, aMsg) {}, - onServerClose(aContext, aCode, aReason) {}, - onStart(aContext) {}, - onStop(aContext, aStatusCode) { + onAcknowledge() {}, + onBinaryMessageAvailable() {}, + onMessageAvailable() {}, + onServerClose() {}, + onStart() {}, + onStop() { dnsRequestObserver.unregister(); this._closure(); }, diff --git a/netwerk/test/unit/test_dns_retry.js b/netwerk/test/unit/test_dns_retry.js index 24688417fa..477586126e 100644 --- a/netwerk/test/unit/test_dns_retry.js +++ b/netwerk/test/unit/test_dns_retry.js @@ -142,8 +142,8 @@ StatusCounter.prototype = { return this.QueryInterface(iid); }, - onProgress(request, progress, progressMax) {}, - onStatus(request, status, statusArg) { + onProgress() {}, + onStatus(request, status) { this._statusCount[status] = 1 + (this._statusCount[status] || 0); }, }; @@ -154,7 +154,7 @@ let HttpListener = function (finish, succeeded) { }; HttpListener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); @@ -167,7 +167,7 @@ HttpListener.prototype = { }; function promiseObserverNotification(aTopic, matchFunc) { - return new Promise((resolve, reject) => { + return new Promise(resolve => { Services.obs.addObserver(function observe(subject, topic, data) { let matches = typeof matchFunc != "function" || matchFunc(subject, data); if (!matches) { diff --git a/netwerk/test/unit/test_dooh.js b/netwerk/test/unit/test_dooh.js index cab4b3bb02..d422bac5e9 100644 --- a/netwerk/test/unit/test_dooh.js +++ b/netwerk/test/unit/test_dooh.js @@ -127,7 +127,7 @@ add_setup(async function setup() { Services.prefs.clearUserPref("network.trr.ohttp.relay_uri"); Services.prefs.clearUserPref("network.trr.ohttp.uri"); Services.prefs.clearUserPref("network.dns.get-ttl"); - await new Promise((resolve, reject) => { + await new Promise(resolve => { httpServer.stop(resolve); }); }); diff --git a/netwerk/test/unit/test_duplicate_headers.js b/netwerk/test/unit/test_duplicate_headers.js index 78d2355d1e..12e8e8d0d3 100644 --- a/netwerk/test/unit/test_duplicate_headers.js +++ b/netwerk/test/unit/test_duplicate_headers.js @@ -73,7 +73,7 @@ function handler1(metadata, response) { response.finish(); } -function completeTest1(request, data, ctx) { +function completeTest1(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(2); @@ -94,7 +94,7 @@ function handler2(metadata, response) { response.finish(); } -function completeTest2(request, data, ctx) { +function completeTest2(request) { Assert.equal(request.status, 0); run_test_number(3); } @@ -115,7 +115,7 @@ function handler3(metadata, response) { response.finish(); } -function completeTest3(request, data, ctx) { +function completeTest3(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(4); @@ -143,7 +143,7 @@ function handler4(metadata, response) { response.finish(); } -function completeTest4(request, data, ctx) { +function completeTest4(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(5); @@ -166,7 +166,7 @@ function handler5(metadata, response) { response.finish(); } -function completeTest5(request, data, ctx) { +function completeTest5(request) { try { let referer = request.getResponseHeader("Referer"); Assert.equal(referer, "naive.org"); @@ -196,7 +196,7 @@ function handler6(metadata, response) { response.finish(); } -function completeTest6(request, data, ctx) { +function completeTest6(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); // run_test_number(7); // Test 7 leaking under e10s: unrelated bug? @@ -221,7 +221,7 @@ function handler7(metadata, response) { response.finish(); } -function completeTest7(request, data, ctx) { +function completeTest7(request) { // for some reason need this here request.QueryInterface(Ci.nsIHttpChannel); @@ -254,7 +254,7 @@ function handler8(metadata, response) { response.finish(); } -function completeTest8(request, data, ctx) { +function completeTest8(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(9); @@ -282,7 +282,7 @@ function handler9(metadata, response) { response.finish(); } -function completeTest9(request, data, ctx) { +function completeTest9(request) { // All redirection should fail: Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); @@ -307,7 +307,7 @@ function handler10(metadata, response) { response.finish(); } -function completeTest10(request, data, ctx) { +function completeTest10(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(11); @@ -329,7 +329,7 @@ function handler11(metadata, response) { response.finish(); } -function completeTest11(request, data, ctx) { +function completeTest11(request) { Assert.equal(request.status, 0); try { @@ -360,7 +360,7 @@ function handler12(metadata, response) { response.finish(); } -function completeTest12(request, data, ctx) { +function completeTest12(request, data) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -383,7 +383,7 @@ function handler13(metadata, response) { response.finish(); } -function completeTest13(request, data, ctx) { +function completeTest13(request, data) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -408,7 +408,7 @@ function handler14(metadata, response) { response.finish(); } -function completeTest14(request, data, ctx) { +function completeTest14(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(15); @@ -432,7 +432,7 @@ function handler15(metadata, response) { response.finish(); } -function completeTest15(request, data, ctx) { +function completeTest15(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(16); @@ -456,7 +456,7 @@ function handler16(metadata, response) { response.finish(); } -function completeTest16(request, data, ctx) { +function completeTest16(request, data) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -485,7 +485,7 @@ function handler17(metadata, response) { response.finish(); } -function completeTest17(request, data, ctx) { +function completeTest17(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); run_test_number(18); @@ -507,7 +507,7 @@ function handler18(metadata, response) { response.finish(); } -function completeTest18(request, data, ctx) { +function completeTest18(request, data) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -530,7 +530,7 @@ function handler19(metadata, response) { response.finish(); } -function completeTest19(request, data, ctx) { +function completeTest19(request, data) { Assert.equal(request.status, Cr.NS_OK); Assert.equal(30, data.length); @@ -556,7 +556,7 @@ function handler20(metadata, response) { response.finish(); } -function completeTest20(request, data, ctx) { +function completeTest20(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); endTests(); diff --git a/netwerk/test/unit/test_ech_grease.js b/netwerk/test/unit/test_ech_grease.js index bbe9c027b5..7505985ef8 100644 --- a/netwerk/test/unit/test_ech_grease.js +++ b/netwerk/test/unit/test_ech_grease.js @@ -182,7 +182,7 @@ function startClient(port, useGREASE, beConservative) { nonflavors.push("_ECH_GREASE"); } - return new Promise((resolve, reject) => { + return new Promise(resolve => { req.onload = () => { equal(req.responseText, "OK", "response text should be 'OK'"); diff --git a/netwerk/test/unit/test_event_sink.js b/netwerk/test/unit/test_event_sink.js index e49080c88c..d89c905cd2 100644 --- a/netwerk/test/unit/test_event_sink.js +++ b/netwerk/test/unit/test_event_sink.js @@ -26,12 +26,7 @@ var eventsink = { return this.QueryInterface(iid); }, - asyncOnChannelRedirect: function eventsink_onredir( - oldChan, - newChan, - flags, - callback - ) { + asyncOnChannelRedirect: function eventsink_onredir() { // veto this.called = true; throw Components.Exception("", Cr.NS_BINDING_ABORTED); @@ -89,7 +84,7 @@ var listener = { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { if (this._iteration <= 2) { run_test_continued(); } else { diff --git a/netwerk/test/unit/test_file_protocol.js b/netwerk/test/unit/test_file_protocol.js index 707bddef24..4cb6b32b9e 100644 --- a/netwerk/test/unit/test_file_protocol.js +++ b/netwerk/test/unit/test_file_protocol.js @@ -163,7 +163,7 @@ function do_test_read_dir(set_type, expected_type) { var file = do_get_tempdir(); var chan = new_file_channel(file); - function on_read_complete(data) { + function on_read_complete() { dump( "*** test_read_dir.on_read_complete(" + set_type + diff --git a/netwerk/test/unit/test_freshconnection.js b/netwerk/test/unit/test_freshconnection.js index 5d0f5bc5b7..796111e87b 100644 --- a/netwerk/test/unit/test_freshconnection.js +++ b/netwerk/test/unit/test_freshconnection.js @@ -5,13 +5,13 @@ "use strict"; var listener = { - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA() { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { do_test_finished(); }, }; diff --git a/netwerk/test/unit/test_getHost.js b/netwerk/test/unit/test_getHost.js index c27fc0c028..98bbab9dfc 100644 --- a/netwerk/test/unit/test_getHost.js +++ b/netwerk/test/unit/test_getHost.js @@ -32,7 +32,7 @@ CheckGetHostListener.prototype = { } }, - onStopRequest(request, statusCode) { + onStopRequest() { dump("*** listener onStopRequest\n"); Assert.equal(gotOnStartRequest, true); diff --git a/netwerk/test/unit/test_gio_protocol.js b/netwerk/test/unit/test_gio_protocol.js index 37ce37abab..2d3250c203 100644 --- a/netwerk/test/unit/test_gio_protocol.js +++ b/netwerk/test/unit/test_gio_protocol.js @@ -82,7 +82,7 @@ FileStreamListener.prototype = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { if (this._got_onstartrequest) { do_throw("Got second onStartRequest event!"); } diff --git a/netwerk/test/unit/test_head.js b/netwerk/test/unit/test_head.js index 8a6b2a5cd7..fba5e95736 100644 --- a/netwerk/test/unit/test_head.js +++ b/netwerk/test/unit/test_head.js @@ -141,7 +141,7 @@ function serverHandler(metadata, response) { } } -function checkRequestResponse(request, data, context) { +function checkRequestResponse(request, data) { if (dbg) { print("============== checkRequestResponse: in"); } diff --git a/netwerk/test/unit/test_head_request_no_response_body.js b/netwerk/test/unit/test_head_request_no_response_body.js index 852a03040f..7f33850217 100644 --- a/netwerk/test/unit/test_head_request_no_response_body.js +++ b/netwerk/test/unit/test_head_request_no_response_body.js @@ -43,7 +43,11 @@ async function get_response(channel, fromCache) { return new Promise(resolve => { channel.asyncOpen( new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + Assert.equal( + fromCache, + isFromCache, + `got response from cache = ${fromCache}` + ); resolve(buffer); }) ); @@ -66,13 +70,13 @@ add_task(async function () { let response; response = await get_response(make_channel(URI, "GET"), false); - ok(response === responseContent, "got response body"); + Assert.strictEqual(response, responseContent, "got response body"); response = await get_response(make_channel(URI, "GET"), true); - ok(response === responseContent, "got response body from cache"); + Assert.strictEqual(response, responseContent, "got response body from cache"); response = await get_response(make_channel(URI, "HEAD"), false); - ok(response === "", "should have empty body"); + Assert.strictEqual(response, "", "should have empty body"); await stop_server(httpserver); }); diff --git a/netwerk/test/unit/test_header_Server_Timing.js b/netwerk/test/unit/test_header_Server_Timing.js index 0e65cf3ccf..dbf05177e2 100644 --- a/netwerk/test/unit/test_header_Server_Timing.js +++ b/netwerk/test/unit/test_header_Server_Timing.js @@ -56,7 +56,7 @@ function checkServerTimingContent(headers) { } } -function readServerContent(request, buffer) { +function readServerContent(request) { let channel = request.QueryInterface(Ci.nsITimedChannel); let headers = channel.serverTiming.QueryInterface(Ci.nsIArray); checkServerTimingContent(headers); diff --git a/netwerk/test/unit/test_headers.js b/netwerk/test/unit/test_headers.js index e1439c6c43..352ea6b3aa 100644 --- a/netwerk/test/unit/test_headers.js +++ b/netwerk/test/unit/test_headers.js @@ -94,7 +94,7 @@ function handler1(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest1(request, data, ctx) { +function completeTest1(request) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); @@ -118,7 +118,7 @@ function handler2(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest2(request, data, ctx) { +function completeTest2(request) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); @@ -143,7 +143,7 @@ function handler3(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest3(request, data, ctx) { +function completeTest3(request) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_ATTACHMENT); @@ -169,7 +169,7 @@ function handler4(metadata, response) { } // eslint-disable-next-line no-unused-vars -function completeTest4(request, data, ctx) { +function completeTest4(request) { try { var chan = request.QueryInterface(Ci.nsIChannel); Assert.equal(chan.contentDisposition, chan.DISPOSITION_INLINE); diff --git a/netwerk/test/unit/test_http2.js b/netwerk/test/unit/test_http2.js index 0b80e99dcc..3fef56a14c 100644 --- a/netwerk/test/unit/test_http2.js +++ b/netwerk/test/unit/test_http2.js @@ -479,3 +479,12 @@ add_task(async function do_test_http2_push_userContext3() { ); Assert.equal(httpProxyConnectResponseCode, -1); }); + +add_task(async function do_test_http2_continuations_over_max_response_limit() { + const { httpProxyConnectResponseCode } = + await test_http2_continuations_over_max_response_limit( + loadGroup, + serverPort + ); + Assert.equal(httpProxyConnectResponseCode, -1); +}); diff --git a/netwerk/test/unit/test_http2_with_proxy.js b/netwerk/test/unit/test_http2_with_proxy.js index 858a0da570..dcc913f039 100644 --- a/netwerk/test/unit/test_http2_with_proxy.js +++ b/netwerk/test/unit/test_http2_with_proxy.js @@ -423,3 +423,12 @@ add_task(async function do_test_http2_push_userContext3() { ); Assert.equal(httpProxyConnectResponseCode, 200); }); + +add_task(async function do_test_http2_continuations_over_max_response_limit() { + const { httpProxyConnectResponseCode } = + await test_http2_continuations_over_max_response_limit( + loadGroup, + serverPort + ); + Assert.equal(httpProxyConnectResponseCode, 200); +}); diff --git a/netwerk/test/unit/test_http3.js b/netwerk/test/unit/test_http3.js index 7f3f5b118d..4f202e7fe4 100644 --- a/netwerk/test/unit/test_http3.js +++ b/netwerk/test/unit/test_http3.js @@ -283,7 +283,7 @@ MultipleListener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let routed = ""; try { routed = request.getRequestHeader("Alt-Used"); diff --git a/netwerk/test/unit/test_http3_0rtt.js b/netwerk/test/unit/test_http3_0rtt.js index 1002263ed5..efb6e3539f 100644 --- a/netwerk/test/unit/test_http3_0rtt.js +++ b/netwerk/test/unit/test_http3_0rtt.js @@ -32,7 +32,7 @@ Http3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_http3_alt_svc.js b/netwerk/test/unit/test_http3_alt_svc.js index 201101eb19..46488525ae 100644 --- a/netwerk/test/unit/test_http3_alt_svc.js +++ b/netwerk/test/unit/test_http3_alt_svc.js @@ -5,7 +5,7 @@ let h3AltSvc; let h3Route; let prefs; -let tests = [test_https_alt_svc, testsDone]; +let tests = [test_https_alt_svc, test_https_alt_svc_1, testsDone]; let current_test = 0; @@ -68,7 +68,9 @@ function makeChan(uri) { return chan; } -let WaitForHttp3Listener = function () {}; +let WaitForHttp3Listener = function (expectedH3Version) { + this._expectedH3Version = expectedH3Version; +}; WaitForHttp3Listener.prototype = { onDataAvailableFired: false, @@ -84,7 +86,7 @@ WaitForHttp3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let routed = "NA"; try { routed = request.getRequestHeader("Alt-Used"); @@ -96,13 +98,18 @@ WaitForHttp3Listener.prototype = { try { httpVersion = request.protocolVersion; } catch (e) {} - Assert.equal(httpVersion, "h3-29"); + Assert.equal(httpVersion, this._expectedH3Version); run_next_test(); } else { dump("poll later for alt svc mapping\n"); do_test_pending(); do_timeout(500, () => { - doTest(this.uri, this.expectedRoute, this.h3AltSvc); + doTest( + this.uri, + this.expectedRoute, + this.h3AltSvc, + this._expectedH3Version + ); }); } @@ -110,9 +117,9 @@ WaitForHttp3Listener.prototype = { }, }; -function doTest(uri, expectedRoute, altSvc) { +function doTest(uri, expectedRoute, altSvc, expectedH3Version) { let chan = makeChan(uri); - let listener = new WaitForHttp3Listener(); + let listener = new WaitForHttp3Listener(expectedH3Version); listener.uri = uri; listener.expectedRoute = expectedRoute; listener.h3AltSvc = altSvc; @@ -121,11 +128,23 @@ function doTest(uri, expectedRoute, altSvc) { } // Test Alt-Svc for http3. -// H2 server returns alt-svc=h2=foo2.example.com:8000,h3-29=:h3port,h3-30=foo2.example.com:8443 +// H2 server returns alt-svc=h2=foo2.example.com:8000,h3-29=:h3port function test_https_alt_svc() { dump("test_https_alt_svc()\n"); do_test_pending(); - doTest(httpsOrigin + "http3-test2", h3Route, h3AltSvc); + doTest(httpsOrigin + "http3-test2", h3Route, h3AltSvc, "h3-29"); +} + +// Test if we use the latest version of HTTP/3. +// H2 server returns alt-svc=h3-29=:h3port,h3=:h3port +function test_https_alt_svc_1() { + // Close the previous connection and clear alt-svc mappings. + Services.obs.notifyObservers(null, "last-pb-context-exited"); + Services.obs.notifyObservers(null, "net:cancel-all-connections"); + do_test_pending(); + do_timeout(1000, () => { + doTest(httpsOrigin + "http3-test3", h3Route, h3AltSvc, "h3"); + }); } function testsDone() { diff --git a/netwerk/test/unit/test_http3_error_before_connect.js b/netwerk/test/unit/test_http3_error_before_connect.js index 72f8d61182..6cfab99d7e 100644 --- a/netwerk/test/unit/test_http3_error_before_connect.js +++ b/netwerk/test/unit/test_http3_error_before_connect.js @@ -70,7 +70,7 @@ add_task(async function test_fatal_stream_error() { let CheckOnlyHttp2Listener = function () {}; CheckOnlyHttp2Listener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); diff --git a/netwerk/test/unit/test_http3_fast_fallback.js b/netwerk/test/unit/test_http3_fast_fallback.js index ab2b6b7044..94a3268702 100644 --- a/netwerk/test/unit/test_http3_fast_fallback.js +++ b/netwerk/test/unit/test_http3_fast_fallback.js @@ -102,7 +102,7 @@ function channelOpenPromise(chan, flags, delay) { let CheckOnlyHttp2Listener = function () {}; CheckOnlyHttp2Listener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); diff --git a/netwerk/test/unit/test_http3_fatal_stream_error.js b/netwerk/test/unit/test_http3_fatal_stream_error.js index 4c0b41089a..13b2411df0 100644 --- a/netwerk/test/unit/test_http3_fatal_stream_error.js +++ b/netwerk/test/unit/test_http3_fatal_stream_error.js @@ -19,7 +19,7 @@ registerCleanupFunction(async () => { let Http3FailedListener = function () {}; Http3FailedListener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { this.amount += cnt; @@ -103,7 +103,7 @@ add_task(async function test_fatal_stream_error() { let CheckOnlyHttp2Listener = function () {}; CheckOnlyHttp2Listener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); diff --git a/netwerk/test/unit/test_http3_large_post.js b/netwerk/test/unit/test_http3_large_post.js index 2ed8e51bb4..50ad3ef37a 100644 --- a/netwerk/test/unit/test_http3_large_post.js +++ b/netwerk/test/unit/test_http3_large_post.js @@ -38,7 +38,7 @@ Http3Listener.prototype = { this.onProgressNotificationCount += 1; }, - onStatus(request, status, statusArg) {}, + onStatus() {}, onStartRequest: function testOnStartRequest(request) { Assert.equal(request.status, this.expectedStatus); @@ -55,7 +55,7 @@ Http3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_http3_large_post_telemetry.js b/netwerk/test/unit/test_http3_large_post_telemetry.js index 33ad4b7d21..a473dd5442 100644 --- a/netwerk/test/unit/test_http3_large_post_telemetry.js +++ b/netwerk/test/unit/test_http3_large_post_telemetry.js @@ -59,7 +59,7 @@ Http3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_http3_prio_helpers.js b/netwerk/test/unit/test_http3_prio_helpers.js index c1f6d06bcb..416a968746 100644 --- a/netwerk/test/unit/test_http3_prio_helpers.js +++ b/netwerk/test/unit/test_http3_prio_helpers.js @@ -64,7 +64,7 @@ Http3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_http3_server_not_existing.js b/netwerk/test/unit/test_http3_server_not_existing.js index b2b5518974..cdaebc1412 100644 --- a/netwerk/test/unit/test_http3_server_not_existing.js +++ b/netwerk/test/unit/test_http3_server_not_existing.js @@ -77,7 +77,7 @@ add_task(async function test_fatal_stream_error() { let CheckOnlyHttp2Listener = function () {}; CheckOnlyHttp2Listener.prototype = { - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); diff --git a/netwerk/test/unit/test_http3_trans_close.js b/netwerk/test/unit/test_http3_trans_close.js index 0bbb183aab..7fc57873cf 100644 --- a/netwerk/test/unit/test_http3_trans_close.js +++ b/netwerk/test/unit/test_http3_trans_close.js @@ -29,7 +29,7 @@ Http3Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_http3_version1.js b/netwerk/test/unit/test_http3_version1.js index 65f4eef906..6c41a29ed7 100644 --- a/netwerk/test/unit/test_http3_version1.js +++ b/netwerk/test/unit/test_http3_version1.js @@ -45,13 +45,13 @@ let Http3Listener = function () {}; Http3Listener.prototype = { version1enabled: "", - onStartRequest: function testOnStartRequest(request) {}, + onStartRequest: function testOnStartRequest() {}, onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_httpResponseTimeout.js b/netwerk/test/unit/test_httpResponseTimeout.js index c689abc2b5..267b3aa5f4 100644 --- a/netwerk/test/unit/test_httpResponseTimeout.js +++ b/netwerk/test/unit/test_httpResponseTimeout.js @@ -27,9 +27,9 @@ function TimeoutListener(expectResponse) { } TimeoutListener.prototype = { - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream) {}, + onDataAvailable() {}, onStopRequest(request, status) { if (this.expectResponse) { diff --git a/netwerk/test/unit/test_http_server_timing.js b/netwerk/test/unit/test_http_server_timing.js index c9d46797f3..7ade62edef 100644 --- a/netwerk/test/unit/test_http_server_timing.js +++ b/netwerk/test/unit/test_http_server_timing.js @@ -53,7 +53,7 @@ add_task(async function test_localhost_origin() { }); await new Promise(resolve => { chan.asyncOpen( - new ChannelListener((request, buffer) => { + new ChannelListener(request => { let channel = request.QueryInterface(Ci.nsITimedChannel); let headers = channel.serverTiming.QueryInterface(Ci.nsIArray); ok(headers.length); @@ -86,7 +86,7 @@ add_task(async function test_http_non_localhost() { }); await new Promise(resolve => { chan.asyncOpen( - new ChannelListener((request, buffer) => { + new ChannelListener(request => { let channel = request.QueryInterface(Ci.nsITimedChannel); let headers = channel.serverTiming.QueryInterface(Ci.nsIArray); Assert.equal(headers.length, 0); diff --git a/netwerk/test/unit/test_httpcancel.js b/netwerk/test/unit/test_httpcancel.js index 04958ffd2b..9ed17235cd 100644 --- a/netwerk/test/unit/test_httpcancel.js +++ b/netwerk/test/unit/test_httpcancel.js @@ -27,7 +27,7 @@ var ReferrerInfo = Components.Constructor( var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject) { subject = subject.QueryInterface(Ci.nsIRequest); subject.cancelWithReason(Cr.NS_BINDING_ABORTED, reason); @@ -83,7 +83,7 @@ let cancelDuringOnStartListener = { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { this.resolved(); }, }; @@ -92,7 +92,7 @@ var cancelDuringOnDataListener = { data: "", channel: null, receivedSomeData: null, - onStartRequest: function test_onStartR(request, ctx) { + onStartRequest: function test_onStartR(request) { Assert.equal(request.status, Cr.NS_OK); }, @@ -106,7 +106,7 @@ var cancelDuringOnDataListener = { } }, - onStopRequest: function test_onStopR(request, ctx, status) { + onStopRequest: function test_onStopR(request) { Assert.ok(this.data.includes("a"), `data: ${this.data}`); Assert.equal(request.status, Cr.NS_BINDING_ABORTED); this.resolved(); @@ -195,7 +195,7 @@ add_task(async function test_cancel_during_onData() { var cancelAfterOnStopListener = { data: "", channel: null, - onStartRequest: function test_onStartR(request, ctx) { + onStartRequest: function test_onStartR(request) { Assert.equal(request.status, Cr.NS_OK); }, @@ -204,7 +204,7 @@ var cancelAfterOnStopListener = { this.data += string; }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { info("onStopRequest"); Assert.equal(request.status, Cr.NS_OK); this.resolved(); @@ -233,7 +233,7 @@ add_task(async function test_cancel_after_onStop() { // PATHS // /failtest -function failtest(metadata, response) { +function failtest() { do_throw("This should not be reached"); } diff --git a/netwerk/test/unit/test_httpssvc_https_upgrade.js b/netwerk/test/unit/test_httpssvc_https_upgrade.js index 837006767c..08f95d987c 100644 --- a/netwerk/test/unit/test_httpssvc_https_upgrade.js +++ b/netwerk/test/unit/test_httpssvc_https_upgrade.js @@ -192,7 +192,7 @@ add_task(async function testInvalidDNSResult1() { let topic = "http-on-modify-request"; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == topic) { Services.obs.removeObserver(observer, topic); let channel = aSubject.QueryInterface(Ci.nsIChannel); @@ -266,7 +266,7 @@ add_task(async function testHttpRequestBlocked() { this.obs.removeObserver(this, "dns-resolution-request"); } }, - observe(subject, topic, data) { + observe(subject, topic) { if (topic == "dns-resolution-request") { Assert.ok(false, "unreachable"); } @@ -278,7 +278,7 @@ add_task(async function testHttpRequestBlocked() { Services.prefs.setBoolPref("network.dns.disablePrefetch", true); let httpserv = new HttpServer(); - httpserv.registerPathHandler("/", function handler(metadata, response) { + httpserv.registerPathHandler("/", function handler() { Assert.ok(false, "unreachable"); }); httpserv.start(-1); @@ -295,7 +295,7 @@ add_task(async function testHttpRequestBlocked() { let topic = "http-on-modify-request"; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == topic) { Services.obs.removeObserver(observer, topic); let channel = aSubject.QueryInterface(Ci.nsIChannel); diff --git a/netwerk/test/unit/test_httpsuspend.js b/netwerk/test/unit/test_httpsuspend.js index 581caf906e..ecbb648f4e 100644 --- a/netwerk/test/unit/test_httpsuspend.js +++ b/netwerk/test/unit/test_httpsuspend.js @@ -52,7 +52,7 @@ var listener = { this._gotData = true; }, - onStopRequest(request, status) { + onStopRequest() { Assert.ok(this._gotData); httpserv.stop(do_test_finished); }, diff --git a/netwerk/test/unit/test_idn_spoof.js b/netwerk/test/unit/test_idn_spoof.js index 8512d3272e..5710b3b778 100644 --- a/netwerk/test/unit/test_idn_spoof.js +++ b/netwerk/test/unit/test_idn_spoof.js @@ -243,9 +243,9 @@ let testCases = [ // Han + U+30FB + Han ["xn--vek160nb2ay85atj0b.jp", "\u65e5\u672c\u30fb\u91ce\u7403.jp", kSafe], // Latin + U+30FB + Latin - ["xn--abcdef-k64e.jp", "abc\u30fbdef.jp", kUnsafe, "DISABLED"], + ["xn--abcdef-k64e.jp", "abc\u30fbdef.jp", kUnsafe], // U+30FB + Latin - ["xn--abc-os4b.jp", "\u30fbabc.jp", kUnsafe, "DISABLED"], + ["xn--abc-os4b.jp", "\u30fbabc.jp", kUnsafe], // U+30FD (ヽ) is allowed only after Katakana. // Katakana + U+30FD @@ -416,7 +416,7 @@ let testCases = [ // þħĸŧƅ.com ["xn--vda6f3b2kpf.com", "\u00fe\u0127\u0138\u0167\u0185.com", kUnsafe], // þhktb.com - ["xn--hktb-9ra.com", "\u00fehktb.com", kUnsafe, "DISABLED"], + ["xn--hktb-9ra.com", "\u00fehktb.com", kUnsafe], // pħktb.com ["xn--pktb-5xa.com", "p\u0127ktb.com", kUnsafe, "DISABLED"], // phĸtb.com @@ -708,9 +708,9 @@ let testCases = [ // Block single/double-quote-like characters. // U+02BB (Ê») - ["xn--ab-8nb.com", "a\u02bbb.com", kUnsafe, "DISABLED"], + ["xn--ab-8nb.com", "a\u02bbb.com", kUnsafe], // U+02BC (ʼ) - ["xn--ab-cob.com", "a\u02bcb.com", kUnsafe, "DISABLED"], + ["xn--ab-cob.com", "a\u02bcb.com", kUnsafe], // U+144A: Not allowed to mix with scripts other than Canadian Syllabics. ["xn--ab-jom.com", "a\u144ab.com", kUnsafe], ["xn--xcec9s.com", "\u1401\u144a\u1402.com", kUnsafe], @@ -876,8 +876,8 @@ let testCases = [ ["xn--ceba.com", "\u05d7\u05d7.com", kUnsafe, "DISABLED"], // U+00FE (þ) and U+00F0 (ð) are only allowed under the .is TLD. - ["xn--acdef-wva.com", "a\u00fecdef.com", kUnsafe, "DISABLED"], - ["xn--mnpqr-jta.com", "mn\u00f0pqr.com", kUnsafe, "DISABLED"], + ["xn--acdef-wva.com", "a\u00fecdef.com", kUnsafe], + ["xn--mnpqr-jta.com", "mn\u00f0pqr.com", kUnsafe], ["xn--acdef-wva.is", "a\u00fecdef.is", kSafe], ["xn--mnpqr-jta.is", "mn\u00f0pqr.is", kSafe], @@ -886,13 +886,13 @@ let testCases = [ ["xn--xample-vyc.az", "\u0259xample.az", kSafe], // U+00B7 is only allowed on Catalan domains between two l's. - ["xn--googlecom-5pa.com", "google\u00b7com.com", kUnsafe, "DISABLED"], - ["xn--ll-0ea.com", "l\u00b7l.com", kUnsafe, "DISABLED"], + ["xn--googlecom-5pa.com", "google\u00b7com.com", kUnsafe], + ["xn--ll-0ea.com", "l\u00b7l.com", kUnsafe], ["xn--ll-0ea.cat", "l\u00b7l.cat", kSafe], - ["xn--al-0ea.cat", "a\u00b7l.cat", kUnsafe, "DISABLED"], - ["xn--la-0ea.cat", "l\u00b7a.cat", kUnsafe, "DISABLED"], - ["xn--l-fda.cat", "\u00b7l.cat", kUnsafe, "DISABLED"], - ["xn--l-gda.cat", "l\u00b7.cat", kUnsafe, "DISABLED"], + ["xn--al-0ea.cat", "a\u00b7l.cat", kUnsafe], + ["xn--la-0ea.cat", "l\u00b7a.cat", kUnsafe], + ["xn--l-fda.cat", "\u00b7l.cat", kUnsafe], + ["xn--l-gda.cat", "l\u00b7.cat", kUnsafe], ["xn--googlecom-gk6n.com", "google\u4e28com.com", kUnsafe, "DISABLED"], ["xn--googlecom-0y6n.com", "google\u4e5bcom.com", kUnsafe, "DISABLED"], @@ -1050,3 +1050,9 @@ add_task(async function test_chrome_spoofs() { } } }); + +add_task(async function test_interpuncts_fqdn() { + let isAscii = {}; + let result = idnService.convertToDisplayIDN("xn--ll-0ea.cat.", isAscii); + Assert.equal(result, "l\u00b7l.cat."); +}); diff --git a/netwerk/test/unit/test_immutable.js b/netwerk/test/unit/test_immutable.js index f2b07c7114..2cd8d8a721 100644 --- a/netwerk/test/unit/test_immutable.js +++ b/netwerk/test/unit/test_immutable.js @@ -75,7 +75,7 @@ Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { if (expectConditional) { Assert.equal(request.getResponseHeader("x-conditional"), "true"); } else { diff --git a/netwerk/test/unit/test_loadgroup_cancel.js b/netwerk/test/unit/test_loadgroup_cancel.js index 9d5779437f..d63fb4a841 100644 --- a/netwerk/test/unit/test_loadgroup_cancel.js +++ b/netwerk/test/unit/test_loadgroup_cancel.js @@ -43,7 +43,7 @@ add_task(async function test_cancelledInOnStop() { ); let loadListener = { - onStartRequest: aRequest => { + onStartRequest: () => { info("onStartRequest"); }, onStopRequest: (aRequest, aStatusCode) => { diff --git a/netwerk/test/unit/test_mismatch_last-modified.js b/netwerk/test/unit/test_mismatch_last-modified.js index 010d5d1178..1f96c5170a 100644 --- a/netwerk/test/unit/test_mismatch_last-modified.js +++ b/netwerk/test/unit/test_mismatch_last-modified.js @@ -32,7 +32,7 @@ var listener_3 = { "nsIRequestObserver", ]), - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA(request, inputStream, offset, count) { var data = new BinaryInputStream(inputStream).readByteArray(count); @@ -40,7 +40,7 @@ var listener_3 = { Assert.equal(data[0], "B".charCodeAt(0)); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { httpserver.stop(do_test_finished); }, }; @@ -55,7 +55,7 @@ ChromeUtils.defineLazyGetter(this, "listener_2", function () { "nsIRequestObserver", ]), - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA(request, inputStream, offset, count) { var data = new BinaryInputStream(inputStream).readByteArray(count); @@ -66,7 +66,7 @@ ChromeUtils.defineLazyGetter(this, "listener_2", function () { Assert.equal(data[0], "A".charCodeAt(0)); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { request.QueryInterface(Ci.nsIHttpChannel); var chan = NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", @@ -87,14 +87,14 @@ ChromeUtils.defineLazyGetter(this, "listener_1", function () { "nsIRequestObserver", ]), - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA(request, inputStream, offset, count) { var data = new BinaryInputStream(inputStream).readByteArray(count); Assert.equal(data[0], "A".charCodeAt(0)); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { request.QueryInterface(Ci.nsIHttpChannel); var chan = NetUtil.newChannel({ uri: "http://localhost:" + httpserver.identity.primaryPort + "/test1", diff --git a/netwerk/test/unit/test_multipart_byteranges.js b/netwerk/test/unit/test_multipart_byteranges.js index 475aced456..014e040395 100644 --- a/netwerk/test/unit/test_multipart_byteranges.js +++ b/netwerk/test/unit/test_multipart_byteranges.js @@ -100,7 +100,7 @@ var multipartListener = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, @@ -113,7 +113,7 @@ var multipartListener = { } }, - onStopRequest(request, status) { + onStopRequest(request) { try { responseHandler(request, this._buffer); } catch (ex) { diff --git a/netwerk/test/unit/test_multipart_set_cookie.js b/netwerk/test/unit/test_multipart_set_cookie.js new file mode 100644 index 0000000000..c8943cf3cc --- /dev/null +++ b/netwerk/test/unit/test_multipart_set_cookie.js @@ -0,0 +1,116 @@ +"use strict"; + +const { HttpServer } = ChromeUtils.importESModule( + "resource://testing-common/httpd.sys.mjs" +); + +var httpserver = null; + +ChromeUtils.defineLazyGetter(this, "uri", function () { + return "http://localhost:" + httpserver.identity.primaryPort + "/multipart"; +}); + +function make_channel(url) { + return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); +} + +var multipartBody = + "--boundary\r\nSet-Cookie: foo=bar\r\n\r\nSome text\r\n--boundary--"; + +function contentHandler(metadata, response) { + response.setHeader( + "Content-Type", + 'multipart/x-mixed-replace; boundary="boundary"' + ); + response.bodyOutputStream.write(multipartBody, multipartBody.length); +} + +let first = true; + +function responseHandler(request, buffer) { + let channel = request.QueryInterface(Ci.nsIChannel); + Assert.equal(buffer, "Some text"); + Assert.equal(channel.contentType, "text/plain"); + + // two runs: pref on and off + if (first) { + // foo=bar should not be visible here + Assert.equal( + Services.cookies.getCookieStringFromHttp(channel.URI, channel), + "" + ); + first = false; + Services.prefs.setBoolPref( + "network.cookie.prevent_set_cookie_from_multipart", + false + ); + createConverterAndRequest(); + } else { + // validate that the pref is working + Assert.equal( + Services.cookies.getCookieStringFromHttp(channel.URI, channel), + "foo=bar" + ); + httpserver.stop(do_test_finished); + } +} + +var multipartListener = { + _buffer: "", + + QueryInterface: ChromeUtils.generateQI([ + "nsIStreamListener", + "nsIRequestObserver", + ]), + + onStartRequest(request) { + this._buffer = ""; + }, + + onDataAvailable(request, stream, offset, count) { + try { + this._buffer = this._buffer.concat(read_stream(stream, count)); + dump("BUFFEEE: " + this._buffer + "\n\n"); + } catch (ex) { + do_throw("Error in onDataAvailable: " + ex); + } + }, + + onStopRequest(request, status) { + try { + responseHandler(request, this._buffer); + } catch (ex) { + do_throw("Error in closure function: " + ex); + } + }, +}; + +function createConverterAndRequest() { + var streamConv = Cc["@mozilla.org/streamConverters;1"].getService( + Ci.nsIStreamConverterService + ); + var conv = streamConv.asyncConvertData( + "multipart/x-mixed-replace", + "*/*", + multipartListener, + null + ); + + var chan = make_channel(uri); + chan.asyncOpen(conv); +} + +function run_test() { + Services.prefs.setBoolPref( + "network.cookieJarSettings.unblocked_for_testing", + true + ); + + httpserver = new HttpServer(); + httpserver.registerPathHandler("/multipart", contentHandler); + httpserver.start(-1); + + createConverterAndRequest(); + + do_test_pending(); +} diff --git a/netwerk/test/unit/test_multipart_streamconv-byte-by-byte.js b/netwerk/test/unit/test_multipart_streamconv-byte-by-byte.js index c1865f5668..c4e0db0ff5 100644 --- a/netwerk/test/unit/test_multipart_streamconv-byte-by-byte.js +++ b/netwerk/test/unit/test_multipart_streamconv-byte-by-byte.js @@ -66,7 +66,7 @@ var multipartListener = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, @@ -79,7 +79,7 @@ var multipartListener = { } }, - onStopRequest(request, status) { + onStopRequest(request) { this._index++; // Second part should be last part Assert.equal( diff --git a/netwerk/test/unit/test_multipart_streamconv.js b/netwerk/test/unit/test_multipart_streamconv.js index c1503e4d8c..159b11f802 100644 --- a/netwerk/test/unit/test_multipart_streamconv.js +++ b/netwerk/test/unit/test_multipart_streamconv.js @@ -51,7 +51,7 @@ var multipartListener = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, @@ -64,7 +64,7 @@ var multipartListener = { } }, - onStopRequest(request, status) { + onStopRequest(request) { this._index++; // Second part should be last part Assert.equal( diff --git a/netwerk/test/unit/test_multipart_streamconv_empty.js b/netwerk/test/unit/test_multipart_streamconv_empty.js index 3d3f9dc859..82b7f7000c 100644 --- a/netwerk/test/unit/test_multipart_streamconv_empty.js +++ b/netwerk/test/unit/test_multipart_streamconv_empty.js @@ -34,7 +34,7 @@ add_task(async function test_empty() { "nsIRequestObserver", ]), - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { try { this._buffer = this._buffer.concat(read_stream(stream, count)); diff --git a/netwerk/test/unit/test_multipart_streamconv_missing_boundary_lead_dashes.js b/netwerk/test/unit/test_multipart_streamconv_missing_boundary_lead_dashes.js index 3ed2bd39c6..6829c14158 100644 --- a/netwerk/test/unit/test_multipart_streamconv_missing_boundary_lead_dashes.js +++ b/netwerk/test/unit/test_multipart_streamconv_missing_boundary_lead_dashes.js @@ -49,7 +49,7 @@ var multipartListener = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, @@ -62,7 +62,7 @@ var multipartListener = { } }, - onStopRequest(request, status) { + onStopRequest(request) { try { responseHandler(request, this._buffer); } catch (ex) { diff --git a/netwerk/test/unit/test_multipart_streamconv_missing_lead_boundary.js b/netwerk/test/unit/test_multipart_streamconv_missing_lead_boundary.js index 1df4311b90..c57223a1b0 100644 --- a/netwerk/test/unit/test_multipart_streamconv_missing_lead_boundary.js +++ b/netwerk/test/unit/test_multipart_streamconv_missing_lead_boundary.js @@ -49,7 +49,7 @@ var multipartListener = { "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, @@ -62,7 +62,7 @@ var multipartListener = { } }, - onStopRequest(request, status) { + onStopRequest(request) { try { responseHandler(request, this._buffer); } catch (ex) { diff --git a/netwerk/test/unit/test_net_addr.js b/netwerk/test/unit/test_net_addr.js index 331fa9bc74..49f00ce639 100644 --- a/netwerk/test/unit/test_net_addr.js +++ b/netwerk/test/unit/test_net_addr.js @@ -62,7 +62,7 @@ TestServer.prototype = { this.reset(); }, - onStopListening(socket) {}, + onStopListening() {}, /** * Called to close a connection and clean up properties. diff --git a/netwerk/test/unit/test_network_connectivity_service.js b/netwerk/test/unit/test_network_connectivity_service.js index 6774e79e34..7604c263c6 100644 --- a/netwerk/test/unit/test_network_connectivity_service.js +++ b/netwerk/test/unit/test_network_connectivity_service.js @@ -15,7 +15,7 @@ const { HttpServer } = ChromeUtils.importESModule( * @returns {Promise} A promise that fulfills when the notification is fired. */ function promiseObserverNotification(topicName, matchFunc) { - return new Promise((resolve, reject) => { + return new Promise(resolve => { Services.obs.addObserver(function observe(subject, topic, data) { let matches = typeof matchFunc != "function" || matchFunc(subject, data); if (!matches) { diff --git a/netwerk/test/unit/test_networking_over_socket_process.js b/netwerk/test/unit/test_networking_over_socket_process.js index 79e17140e1..7d879b20c5 100644 --- a/netwerk/test/unit/test_networking_over_socket_process.js +++ b/netwerk/test/unit/test_networking_over_socket_process.js @@ -157,7 +157,7 @@ add_task(async function testTooManyCrashes() { Assert.ok(socketProcessId != 0); let socketProcessCrashed = false; - Services.obs.addObserver(function observe(subject, topic, data) { + Services.obs.addObserver(function observe(subject, topic) { Services.obs.removeObserver(observe, topic); socketProcessCrashed = true; }, "network:socket-process-crashed"); diff --git a/netwerk/test/unit/test_nojsredir.js b/netwerk/test/unit/test_nojsredir.js index 6b6831a222..227cb04608 100644 --- a/netwerk/test/unit/test_nojsredir.js +++ b/netwerk/test/unit/test_nojsredir.js @@ -33,7 +33,7 @@ function startIter() { ); } -function completeIter(request, data, ctx) { +function completeIter(request, data) { Assert.ok(data.length == tests[index].datalen); if (++index < tests.length) { startIter(); diff --git a/netwerk/test/unit/test_ntlm_authentication.js b/netwerk/test/unit/test_ntlm_authentication.js index f17f7ebf7d..1517a65df6 100644 --- a/netwerk/test/unit/test_ntlm_authentication.js +++ b/netwerk/test/unit/test_ntlm_authentication.js @@ -39,7 +39,7 @@ AuthPrompt1.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt: function ap1_prompt(title, text, realm, save, defaultText, result) { + prompt: function ap1_prompt() { do_throw("unexpected prompt call"); }, @@ -95,7 +95,7 @@ AuthPrompt1.prototype = { return true; }, - promptPassword: function ap1_promptPW(title, text, realm, save, pwd) { + promptPassword: function ap1_promptPW() { do_throw("unexpected promptPassword call"); }, }; @@ -118,7 +118,7 @@ AuthPrompt2.prototype = { return true; }, - asyncPromptAuth: function ap2_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap2_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -176,7 +176,7 @@ RealmTestRequestor.prototype = { return false; }, - asyncPromptAuth: function realmtest_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function realmtest_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; diff --git a/netwerk/test/unit/test_ntlm_proxy_and_web_auth.js b/netwerk/test/unit/test_ntlm_proxy_and_web_auth.js index 3435839275..eb3396770e 100644 --- a/netwerk/test/unit/test_ntlm_proxy_and_web_auth.js +++ b/netwerk/test/unit/test_ntlm_proxy_and_web_auth.js @@ -30,7 +30,7 @@ AuthPrompt.prototype = { return true; }, - asyncPromptAuth: function ap_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -71,7 +71,7 @@ function makeChan(url, loadingUrl) { function TestListener(resolve) { this.resolve = resolve; } -TestListener.prototype.onStartRequest = function (request, context) { +TestListener.prototype.onStartRequest = function (request) { // Need to do the instanceof to allow request.responseStatus // to be read. if (!(request instanceof Ci.nsIHttpChannel)) { @@ -80,7 +80,7 @@ TestListener.prototype.onStartRequest = function (request, context) { Assert.equal(expectedResponse, request.responseStatus, "HTTP Status code"); }; -TestListener.prototype.onStopRequest = function (request, context, status) { +TestListener.prototype.onStopRequest = function () { Assert.equal(expectedRequests, requestsMade, "Number of requests made "); this.resolve(); diff --git a/netwerk/test/unit/test_ntlm_proxy_auth.js b/netwerk/test/unit/test_ntlm_proxy_auth.js index b6cb27890b..194050c027 100644 --- a/netwerk/test/unit/test_ntlm_proxy_auth.js +++ b/netwerk/test/unit/test_ntlm_proxy_auth.js @@ -29,7 +29,7 @@ AuthPrompt.prototype = { return true; }, - asyncPromptAuth: function ap_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -70,7 +70,7 @@ function makeChan(url, loadingUrl) { function TestListener(resolve) { this.resolve = resolve; } -TestListener.prototype.onStartRequest = function (request, context) { +TestListener.prototype.onStartRequest = function (request) { // Need to do the instanceof to allow request.responseStatus // to be read. if (!(request instanceof Ci.nsIHttpChannel)) { @@ -79,7 +79,7 @@ TestListener.prototype.onStartRequest = function (request, context) { Assert.equal(expectedResponse, request.responseStatus, "HTTP Status code"); }; -TestListener.prototype.onStopRequest = function (request, context, status) { +TestListener.prototype.onStopRequest = function () { Assert.equal(expectedRequests, requestsMade, "Number of requests made "); Assert.equal( exptTypeOneCount, diff --git a/netwerk/test/unit/test_ntlm_web_auth.js b/netwerk/test/unit/test_ntlm_web_auth.js index 1325477bc6..9a61e91445 100644 --- a/netwerk/test/unit/test_ntlm_web_auth.js +++ b/netwerk/test/unit/test_ntlm_web_auth.js @@ -29,7 +29,7 @@ AuthPrompt.prototype = { return true; }, - asyncPromptAuth: function ap_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -68,7 +68,7 @@ function makeChan(url, loadingUrl) { } function TestListener() {} -TestListener.prototype.onStartRequest = function (request, context) { +TestListener.prototype.onStartRequest = function (request) { // Need to do the instanceof to allow request.responseStatus // to be read. if (!(request instanceof Ci.nsIHttpChannel)) { @@ -77,7 +77,7 @@ TestListener.prototype.onStartRequest = function (request, context) { Assert.equal(expectedResponse, request.responseStatus, "HTTP Status code"); }; -TestListener.prototype.onStopRequest = function (request, context, status) { +TestListener.prototype.onStopRequest = function () { Assert.equal(expectedRequests, requestsMade, "Number of requests made "); if (current_test < tests.length - 1) { diff --git a/netwerk/test/unit/test_oblivious_http.js b/netwerk/test/unit/test_oblivious_http.js index 027426038d..14b3dc7f81 100644 --- a/netwerk/test/unit/test_oblivious_http.js +++ b/netwerk/test/unit/test_oblivious_http.js @@ -167,8 +167,8 @@ async function run_one_testcase(testcase) { false ); } - let response = await new Promise((resolve, reject) => { - NetUtil.asyncFetch(obliviousHttpChannel, function (inputStream, result) { + let response = await new Promise(resolve => { + NetUtil.asyncFetch(obliviousHttpChannel, function (inputStream) { let scriptableInputStream = Cc[ "@mozilla.org/scriptableinputstream;1" ].createInstance(Ci.nsIScriptableInputStream); @@ -200,7 +200,7 @@ async function run_one_testcase(testcase) { ).relayChannel; equal(relayChannel.responseStatus, 404); } - await new Promise((resolve, reject) => { + await new Promise(resolve => { httpServer.stop(resolve); }); } diff --git a/netwerk/test/unit/test_origin.js b/netwerk/test/unit/test_origin.js index 9ef86e8885..d97a6cc0ef 100644 --- a/netwerk/test/unit/test_origin.js +++ b/netwerk/test/unit/test_origin.js @@ -94,7 +94,7 @@ FailListener.prototype = { onDataAvailable: function testOnDataAvailable(request, stream, off, cnt) { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { Assert.ok(!Components.isSuccessCode(request.status)); nextTest(); do_test_finished(); @@ -293,7 +293,7 @@ Http2PushApiListener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR(request) { dump("push api onstop " + request.originalURI.spec + "\n"); Assert.ok(this.fooOK); Assert.ok(this.alt1OK); diff --git a/netwerk/test/unit/test_original_sent_received_head.js b/netwerk/test/unit/test_original_sent_received_head.js index 744528b832..fa06234386 100644 --- a/netwerk/test/unit/test_original_sent_received_head.js +++ b/netwerk/test/unit/test_original_sent_received_head.js @@ -122,7 +122,7 @@ function serverHandler(metadata, response) { } } -function checkResponse(request, data, context) { +function checkResponse(request) { if (dbg) { print("============== checkResponse: in"); } @@ -184,7 +184,7 @@ function checkResponse(request, data, context) { var linkHeaderFound2 = false; var locationHeaderFound2 = 0; request.visitResponseHeaders({ - visitHeader: function visit(aName, aValue) { + visitHeader: function visit(aName) { if (aName == "Link") { linkHeaderFound2 = true; } diff --git a/netwerk/test/unit/test_pac_reload_after_network_change.js b/netwerk/test/unit/test_pac_reload_after_network_change.js index 1b236473ab..dcd082d373 100644 --- a/netwerk/test/unit/test_pac_reload_after_network_change.js +++ b/netwerk/test/unit/test_pac_reload_after_network_change.js @@ -36,7 +36,7 @@ registerCleanupFunction(async () => { }); async function getProxyInfo() { - return new Promise((resolve, reject) => { + return new Promise(resolve => { let uri = Services.io.newURI("http://www.mozilla.org/"); gProxyService.asyncResolve(uri, 0, { onProxyAvailable(_req, _uri, pi, _status) { diff --git a/netwerk/test/unit/test_partial_response_entry_size_smart_shrink.js b/netwerk/test/unit/test_partial_response_entry_size_smart_shrink.js index 0dd5482708..c2a16cc8eb 100644 --- a/netwerk/test/unit/test_partial_response_entry_size_smart_shrink.js +++ b/netwerk/test/unit/test_partial_response_entry_size_smart_shrink.js @@ -19,7 +19,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -84,7 +84,7 @@ function run_test() { do_test_pending(); } -function firstTimeThrough(request, buffer) { +function firstTimeThrough() { // Change single cache entry limit to 1 kb. This emulates smart size change. Services.prefs.setIntPref("browser.cache.disk.max_entry_size", 1); diff --git a/netwerk/test/unit/test_plaintext_sniff.js b/netwerk/test/unit/test_plaintext_sniff.js index 896e458165..5983e4599a 100644 --- a/netwerk/test/unit/test_plaintext_sniff.js +++ b/netwerk/test/unit/test_plaintext_sniff.js @@ -137,7 +137,7 @@ function makeListener(headerIdx, bodyIdx) { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { // Advance to next test ++headerIdx; if (headerIdx == contentTypeHeaderList.length) { diff --git a/netwerk/test/unit/test_port_remapping.js b/netwerk/test/unit/test_port_remapping.js index 274a1117ec..7a333a7af7 100644 --- a/netwerk/test/unit/test_port_remapping.js +++ b/netwerk/test/unit/test_port_remapping.js @@ -7,7 +7,7 @@ const { HttpServer } = ChromeUtils.importESModule( "resource://testing-common/httpd.sys.mjs" ); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_post.js b/netwerk/test/unit/test_post.js index f57a149920..dbbe96825f 100644 --- a/netwerk/test/unit/test_post.js +++ b/netwerk/test/unit/test_post.js @@ -56,7 +56,7 @@ var listenerCallback = { } }, - onStatus(request, status, statusArg) {}, + onStatus() {}, }; function run_test() { @@ -114,7 +114,7 @@ function setupChannel(path) { }).QueryInterface(Ci.nsIHttpChannel); } -function serverHandler(metadata, response) { +function serverHandler(metadata) { Assert.equal(metadata.method, "POST"); var data = read_stream( @@ -135,7 +135,7 @@ function serverHandler(metadata, response) { ); } -function checkRequest(request, data, context) { +function checkRequest() { Assert.ok(correctOnProgress); httpserver.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_predictor.js b/netwerk/test/unit/test_predictor.js index dce86ce5e0..021a0a6cac 100644 --- a/netwerk/test/unit/test_predictor.js +++ b/netwerk/test/unit/test_predictor.js @@ -38,11 +38,11 @@ ValidityChecker.prototype = { QueryInterface: ChromeUtils.generateQI(["nsICacheEntryOpenCallback"]), - onCacheEntryCheck(entry) { + onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, status) { + onCacheEntryAvailable(entry) { // Check if forced valid Assert.equal(entry.isForcedValid, this.httpStatus === 200); this.verifier.maybe_run_next_test(); @@ -155,7 +155,7 @@ var prepListener = { this.continueCallback = cb; }, - onCacheEntryCheck(entry) { + onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, @@ -555,7 +555,7 @@ var prefetchListener = { read_stream(stream, cnt); }, - onStopRequest(request, status) { + onStopRequest() { run_next_test(); }, }; @@ -736,17 +736,7 @@ function test_visitor_doom() { let entryCount = 0; let visitor = { onCacheStorageInfo() {}, - async onCacheEntryInfo( - aURI, - aIdEnhance, - aDataSize, - aAltDataSize, - aFetchCount, - aLastModifiedTime, - aExpirationTime, - aPinned, - aInfo - ) { + async onCacheEntryInfo() { entryCount++; }, onCacheEntryVisitCompleted() { @@ -797,7 +787,7 @@ var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject, topic) { if (topic != "predictor-reset-complete") { return; } diff --git a/netwerk/test/unit/test_private_necko_channel.js b/netwerk/test/unit/test_private_necko_channel.js index dc6a73e145..90f4e72629 100644 --- a/netwerk/test/unit/test_private_necko_channel.js +++ b/netwerk/test/unit/test_private_necko_channel.js @@ -45,7 +45,7 @@ function serverHandler(metadata, response) { response.bodyOutputStream.write(httpbody, httpbody.length); } -function checkRequest(request, data, context) { +function checkRequest() { get_device_entry_count("disk", null, function (count) { Assert.equal(count, 0); get_device_entry_count( diff --git a/netwerk/test/unit/test_progress.js b/netwerk/test/unit/test_progress.js index 8363f0e337..552e2549f7 100644 --- a/netwerk/test/unit/test_progress.js +++ b/netwerk/test/unit/test_progress.js @@ -139,7 +139,7 @@ function serverHandler(metadata, response) { } } -function checkRequest(request, data, context) { +function checkRequest() { Assert.equal(last, httpbody.length * LOOPS); Assert.equal(max, httpbody.length * LOOPS); } diff --git a/netwerk/test/unit/test_progress_no_proxy_and_proxy.js b/netwerk/test/unit/test_progress_no_proxy_and_proxy.js index cb132360c8..edaf9b389d 100644 --- a/netwerk/test/unit/test_progress_no_proxy_and_proxy.js +++ b/netwerk/test/unit/test_progress_no_proxy_and_proxy.js @@ -117,7 +117,7 @@ function chanPromise(uri, statusArg, version) { }); } -function checkRequest(request, data, context) { +function checkRequest() { Assert.equal(last, RESPONSE_LENGTH); Assert.equal(max, RESPONSE_LENGTH); } diff --git a/netwerk/test/unit/test_protocolproxyservice-async-filters.js b/netwerk/test/unit/test_protocolproxyservice-async-filters.js index fcf43d63ef..e7898dbb59 100644 --- a/netwerk/test/unit/test_protocolproxyservice-async-filters.js +++ b/netwerk/test/unit/test_protocolproxyservice-async-filters.js @@ -25,10 +25,10 @@ TestProtocolHandler.prototype = { Ci.nsIProtocolHandler.URI_NORELATIVE | Ci.nsIProtocolHandler.ALLOWS_PROXY | Ci.nsIProtocolHandler.URI_DANGEROUS_TO_LOAD, - newChannel(uri, aLoadInfo) { + newChannel() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, - allowPort(port, scheme) { + allowPort() { return true; }, }; @@ -128,7 +128,7 @@ resolveCallback.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIProtocolProxyCallback"]), - onProxyAvailable(req, channel, pi, status) { + onProxyAvailable(req, channel, pi) { this.nextFunction(pi); }, }; diff --git a/netwerk/test/unit/test_protocolproxyservice.js b/netwerk/test/unit/test_protocolproxyservice.js index 64472651f6..74493db08c 100644 --- a/netwerk/test/unit/test_protocolproxyservice.js +++ b/netwerk/test/unit/test_protocolproxyservice.js @@ -39,10 +39,10 @@ TestProtocolHandler.prototype = { Ci.nsIProtocolHandler.URI_NORELATIVE | Ci.nsIProtocolHandler.ALLOWS_PROXY | Ci.nsIProtocolHandler.URI_DANGEROUS_TO_LOAD, - newChannel(uri, aLoadInfo) { + newChannel() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, - allowPort(port, scheme) { + allowPort() { return true; }, }; @@ -160,7 +160,7 @@ resolveCallback.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIProtocolProxyCallback"]), - onProxyAvailable(req, channel, pi, status) { + onProxyAvailable(req, channel, pi) { this.nextFunction(pi); }, }; @@ -943,10 +943,10 @@ function failed_script_callback(pi) { var directFilterListener = { onModifyRequestCalled: false, - onStartRequest: function test_onStart(request) {}, + onStartRequest: function test_onStart() {}, onDataAvailable: function test_OnData() {}, - onStopRequest: function test_onStop(request, status) { + onStopRequest: function test_onStop(request) { // check on the PI from the channel itself request.QueryInterface(Ci.nsIProxiedChannel); check_proxy(request.proxyInfo, "http", "127.0.0.1", 7246, 0, 0, false); @@ -961,7 +961,7 @@ var directFilterListener = { run_isresolvable_test(); }, - observe(subject, topic, data) { + observe(subject, topic) { if ( topic === "http-on-modify-request" && subject instanceof Ci.nsIHttpChannel && diff --git a/netwerk/test/unit/test_proxy-failover_canceled.js b/netwerk/test/unit/test_proxy-failover_canceled.js index e594c497cc..a40a0c3316 100644 --- a/netwerk/test/unit/test_proxy-failover_canceled.js +++ b/netwerk/test/unit/test_proxy-failover_canceled.js @@ -6,7 +6,7 @@ const { HttpServer } = ChromeUtils.importESModule( var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true, diff --git a/netwerk/test/unit/test_proxy-failover_passing.js b/netwerk/test/unit/test_proxy-failover_passing.js index a6fab56690..dc0cba58b1 100644 --- a/netwerk/test/unit/test_proxy-failover_passing.js +++ b/netwerk/test/unit/test_proxy-failover_passing.js @@ -6,7 +6,7 @@ const { HttpServer } = ChromeUtils.importESModule( var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_proxy-replace_canceled.js b/netwerk/test/unit/test_proxy-replace_canceled.js index b39d5e97f6..c2efa50c5b 100644 --- a/netwerk/test/unit/test_proxy-replace_canceled.js +++ b/netwerk/test/unit/test_proxy-replace_canceled.js @@ -6,7 +6,7 @@ const { HttpServer } = ChromeUtils.importESModule( var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true, diff --git a/netwerk/test/unit/test_proxy-replace_passing.js b/netwerk/test/unit/test_proxy-replace_passing.js index 9c843c001e..b04a52c51d 100644 --- a/netwerk/test/unit/test_proxy-replace_passing.js +++ b/netwerk/test/unit/test_proxy-replace_passing.js @@ -6,7 +6,7 @@ const { HttpServer } = ChromeUtils.importESModule( var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_proxy-slow-upload.js b/netwerk/test/unit/test_proxy-slow-upload.js index 1a406890e1..bef006e1e0 100644 --- a/netwerk/test/unit/test_proxy-slow-upload.js +++ b/netwerk/test/unit/test_proxy-slow-upload.js @@ -91,7 +91,7 @@ add_task(async function test_slow_upload() { }); equal(req.status, Cr.NS_OK); equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200); - ok(buff == CONTENT, "Content must match"); + Assert.equal(buff, CONTENT, "Content must match"); ok(!!req.QueryInterface(Ci.nsIProxiedChannel).proxyInfo); greater( await server.execute(`global.data_count`), diff --git a/netwerk/test/unit/test_proxy_cancel.js b/netwerk/test/unit/test_proxy_cancel.js index d891f3147c..6374a162c9 100644 --- a/netwerk/test/unit/test_proxy_cancel.js +++ b/netwerk/test/unit/test_proxy_cancel.js @@ -19,6 +19,14 @@ function makeChan(uri) { return chan; } +add_setup(async function setup() { + // See Bug 1878505 + Services.prefs.setIntPref("network.http.speculative-parallel-limit", 0); + registerCleanupFunction(async () => { + Services.prefs.clearUserPref("network.http.speculative-parallel-limit"); + }); +}); + add_task(async function test_cancel_after_asyncOpen() { let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( Ci.nsIX509CertDB @@ -123,8 +131,8 @@ add_task(async function test_cancel_after_connect_http2proxy() { return this.QueryInterface(iid); }, - onProgress(request, progress, progressMax) {}, - onStatus(request, status, statusArg) { + onProgress() {}, + onStatus(request, status) { info(`status = ${status}`); // XXX(valentin): Is this the best status to be cancelling? if (status == NS_NET_STATUS_WAITING_FOR) { @@ -347,7 +355,7 @@ add_task(async function test_cancel_during_response() { // Check that we never get more than 1000 bytes. Assert.equal(progress, 1000); }, - onStatus(request, status, statusArg) { + onStatus(request, status) { if (status == NS_NET_STATUS_RECEIVING_FROM) { info("cancelling when receiving request"); chan.cancel(Cr.NS_ERROR_ABORT); diff --git a/netwerk/test/unit/test_proxyconnect.js b/netwerk/test/unit/test_proxyconnect.js index 7015b3bffb..7de1fb39d4 100644 --- a/netwerk/test/unit/test_proxyconnect.js +++ b/netwerk/test/unit/test_proxyconnect.js @@ -72,7 +72,7 @@ var proxiedChannel; var listener = { expectedCode: -1, // uninitialized - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA() { do_throw("Should not get any data!"); diff --git a/netwerk/test/unit/test_range_requests.js b/netwerk/test/unit/test_range_requests.js index cb7a1e7a72..dd2483407c 100644 --- a/netwerk/test/unit/test_range_requests.js +++ b/netwerk/test/unit/test_range_requests.js @@ -38,7 +38,7 @@ const encodedBody = [ const partial_data_length = 4; var port = null; // set in run_test -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true, @@ -54,7 +54,7 @@ Canceler.prototype = { "nsIStreamListener", "nsIRequestObserver", ]), - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { // Read stream so we don't assert for not reading from the stream @@ -78,14 +78,14 @@ MyListener.prototype = { "nsIStreamListener", "nsIRequestObserver", ]), - onStartRequest(request) { + onStartRequest() { this._buffer = ""; }, onDataAvailable(request, stream, offset, count) { this._buffer = this._buffer.concat(read_stream(stream, count)); }, - onStopRequest(request, status) { + onStopRequest(request) { this.continueFn(request, this._buffer); }, }; @@ -99,7 +99,7 @@ FailedChannelListener.prototype = { "nsIStreamListener", "nsIRequestObserver", ]), - onStartRequest(request) {}, + onStartRequest() {}, onDataAvailable(request, stream, offset, count) { read_stream(stream, count); @@ -192,7 +192,7 @@ function handler_4(metadata, response) { } case_4_request_no++; } -function received_partial_4(request, data) { +function received_partial_4() { // checking length does not work with encoded data // do_check_eq(partial_data_length, data.length); var chan = make_channel("http://localhost:" + port + "/test_4"); diff --git a/netwerk/test/unit/test_rcwn_interrupted.js b/netwerk/test/unit/test_rcwn_interrupted.js index 5f3d059999..3c640df5f7 100644 --- a/netwerk/test/unit/test_rcwn_interrupted.js +++ b/netwerk/test/unit/test_rcwn_interrupted.js @@ -29,7 +29,7 @@ ChromeUtils.defineLazyGetter(this, "URL", function () { var httpServer = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect-caching_canceled.js b/netwerk/test/unit/test_redirect-caching_canceled.js index 0ecf2f74b7..847e054d07 100644 --- a/netwerk/test/unit/test_redirect-caching_canceled.js +++ b/netwerk/test/unit/test_redirect-caching_canceled.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect-caching_failure.js b/netwerk/test/unit/test_redirect-caching_failure.js index 2f8105dd94..343d3bfe13 100644 --- a/netwerk/test/unit/test_redirect-caching_failure.js +++ b/netwerk/test/unit/test_redirect-caching_failure.js @@ -28,7 +28,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect-caching_passing.js b/netwerk/test/unit/test_redirect-caching_passing.js index 0e6616f493..17fbb62744 100644 --- a/netwerk/test/unit/test_redirect-caching_passing.js +++ b/netwerk/test/unit/test_redirect-caching_passing.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_baduri.js b/netwerk/test/unit/test_redirect_baduri.js index f83c9a264f..3806d02e9a 100644 --- a/netwerk/test/unit/test_redirect_baduri.js +++ b/netwerk/test/unit/test_redirect_baduri.js @@ -17,7 +17,7 @@ ChromeUtils.defineLazyGetter(this, "BadRedirectURI", function () { ); }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -27,7 +27,7 @@ function BadRedirectHandler(metadata, response) { response.setHeader("Location", "http://localhost:4444>BadRedirect", false); } -function checkFailed(request, buffer) { +function checkFailed(request) { Assert.equal(request.status, Cr.NS_ERROR_CORRUPTED_CONTENT); httpServer.stop(do_test_finished); diff --git a/netwerk/test/unit/test_redirect_canceled.js b/netwerk/test/unit/test_redirect_canceled.js index 9eb9d8b33a..8ada84efe4 100644 --- a/netwerk/test/unit/test_redirect_canceled.js +++ b/netwerk/test/unit/test_redirect_canceled.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_different-protocol.js b/netwerk/test/unit/test_redirect_different-protocol.js index 78b305c84e..16c89eede7 100644 --- a/netwerk/test/unit/test_redirect_different-protocol.js +++ b/netwerk/test/unit/test_redirect_different-protocol.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_failure.js b/netwerk/test/unit/test_redirect_failure.js index 28b4668580..b361c66d00 100644 --- a/netwerk/test/unit/test_redirect_failure.js +++ b/netwerk/test/unit/test_redirect_failure.js @@ -27,7 +27,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_from_script.js b/netwerk/test/unit/test_redirect_from_script.js index 0c42d66b64..6ca2e4ff65 100644 --- a/netwerk/test/unit/test_redirect_from_script.js +++ b/netwerk/test/unit/test_redirect_from_script.js @@ -86,7 +86,7 @@ var testHeaderName = "X-Redirected-By-Script"; var testHeaderVal = "Success"; var testHeaderVal2 = "Success on server 2"; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -130,7 +130,7 @@ Redirector.prototype = { "nsISupportsWeakReference", ]), - observe(subject, topic, data) { + observe(subject, topic) { if (topic == redirectHook) { if (!(subject instanceof Ci.nsIHttpChannel)) { do_throw(redirectHook + " observed a non-HTTP channel"); diff --git a/netwerk/test/unit/test_redirect_from_script_after-open_passing.js b/netwerk/test/unit/test_redirect_from_script_after-open_passing.js index 315f888f64..49fe4e9ec7 100644 --- a/netwerk/test/unit/test_redirect_from_script_after-open_passing.js +++ b/netwerk/test/unit/test_redirect_from_script_after-open_passing.js @@ -86,7 +86,7 @@ var testHeaderName = "X-Redirected-By-Script"; var testHeaderVal = "Success"; var testHeaderVal2 = "Success on server 2"; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -130,7 +130,7 @@ Redirector.prototype = { "nsISupportsWeakReference", ]), - observe(subject, topic, data) { + observe(subject, topic) { if (topic == redirectHook) { if (!(subject instanceof Ci.nsIHttpChannel)) { do_throw(redirectHook + " observed a non-HTTP channel"); diff --git a/netwerk/test/unit/test_redirect_history.js b/netwerk/test/unit/test_redirect_history.js index 124f976881..bb1a00260f 100644 --- a/netwerk/test/unit/test_redirect_history.js +++ b/netwerk/test/unit/test_redirect_history.js @@ -17,7 +17,7 @@ var httpServer = null; var redirects = []; const numRedirects = 10; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_loop.js b/netwerk/test/unit/test_redirect_loop.js index f25bee18c5..f599f2014e 100644 --- a/netwerk/test/unit/test_redirect_loop.js +++ b/netwerk/test/unit/test_redirect_loop.js @@ -25,7 +25,7 @@ var relativeLoopURI = "http://localhost:" + PORT + relativeLoopPath; var emptyLoopPath = "/empty/"; var emptyLoopURI = "http://localhost:" + PORT + emptyLoopPath; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -55,7 +55,7 @@ function emptyLoopHandler(metadata, response) { response.finish(); } -function testFullLoop(request, buffer) { +function testFullLoop(request) { Assert.equal(request.status, Cr.NS_ERROR_REDIRECT_LOOP); var chan = make_channel(relativeLoopURI); @@ -64,14 +64,14 @@ function testFullLoop(request, buffer) { ); } -function testRelativeLoop(request, buffer) { +function testRelativeLoop(request) { Assert.equal(request.status, Cr.NS_ERROR_REDIRECT_LOOP); var chan = make_channel(emptyLoopURI); chan.asyncOpen(new ChannelListener(testEmptyLoop, null, CL_EXPECT_FAILURE)); } -function testEmptyLoop(request, buffer) { +function testEmptyLoop(request) { Assert.equal(request.status, Cr.NS_ERROR_REDIRECT_LOOP); httpServer.stop(do_test_finished); diff --git a/netwerk/test/unit/test_redirect_passing.js b/netwerk/test/unit/test_redirect_passing.js index b712e4d819..bbd3aa54e7 100644 --- a/netwerk/test/unit/test_redirect_passing.js +++ b/netwerk/test/unit/test_redirect_passing.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_redirect_protocol_telemetry.js b/netwerk/test/unit/test_redirect_protocol_telemetry.js index 526ba440ec..022e166fc1 100644 --- a/netwerk/test/unit/test_redirect_protocol_telemetry.js +++ b/netwerk/test/unit/test_redirect_protocol_telemetry.js @@ -4,7 +4,7 @@ const { HttpServer } = ChromeUtils.importESModule( "resource://testing-common/httpd.sys.mjs" ); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -51,7 +51,7 @@ add_task(async function check_protocols() { let p = new Promise(resolve1 => channel.asyncOpen(new ChannelListener(resolve1)) ); - p.then((request, buffer) => { + p.then(() => { TelemetryTestUtils.assertKeyedHistogramSum(redirect_hist, protocol, 1); resolve(); }); diff --git a/netwerk/test/unit/test_redirect_veto.js b/netwerk/test/unit/test_redirect_veto.js index bcc9ddb625..d73635ca90 100644 --- a/netwerk/test/unit/test_redirect_veto.js +++ b/netwerk/test/unit/test_redirect_veto.js @@ -16,7 +16,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit/test_reentrancy.js b/netwerk/test/unit/test_reentrancy.js index 3bd7f54f79..0259ced338 100644 --- a/netwerk/test/unit/test_reentrancy.js +++ b/netwerk/test/unit/test_reentrancy.js @@ -64,7 +64,7 @@ var listener = { this._done_onData = true; }, - onStopRequest(request, status) { + onStopRequest() { Assert.ok(this._done_onData); this._reset(); if (this._test <= MAX_TESTS) { diff --git a/netwerk/test/unit/test_reopen.js b/netwerk/test/unit/test_reopen.js index 6bae0e71cf..271a7f3e9a 100644 --- a/netwerk/test/unit/test_reopen.js +++ b/netwerk/test/unit/test_reopen.js @@ -67,7 +67,7 @@ function check_async_open_throws(error) { } var listener = { - onStartRequest: function test_onStartR(request) { + onStartRequest: function test_onStartR() { check_async_open_throws(NS_ERROR_IN_PROGRESS); }, @@ -76,7 +76,7 @@ var listener = { check_async_open_throws(NS_ERROR_IN_PROGRESS); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { // Once onStopRequest is reached, the channel is marked as having been // opened check_async_open_throws(NS_ERROR_ALREADY_OPENED); diff --git a/netwerk/test/unit/test_reply_without_content_type.js b/netwerk/test/unit/test_reply_without_content_type.js index f32ad81d84..439ffb64ac 100644 --- a/netwerk/test/unit/test_reply_without_content_type.js +++ b/netwerk/test/unit/test_reply_without_content_type.js @@ -137,7 +137,7 @@ function serverHandler_GZip(metadata, response) { } } -function checkRequest(request, data, context) { +function checkRequest(request, data) { if (dbg) { print("============== checkRequest: in"); } diff --git a/netwerk/test/unit/test_resumable_channel.js b/netwerk/test/unit/test_resumable_channel.js index 0407aa4983..8c7aca9e0a 100644 --- a/netwerk/test/unit/test_resumable_channel.js +++ b/netwerk/test/unit/test_resumable_channel.js @@ -16,7 +16,7 @@ const NS_ERROR_NOT_RESUMABLE = 0x804b0019; const rangeBody = "Body of the range request handler.\r\n"; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -34,7 +34,7 @@ AuthPrompt2.prototype = { return true; }, - asyncPromptAuth: function ap2_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap2_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -69,7 +69,7 @@ function run_test() { var entityID; - function get_entity_id(request, data, ctx) { + function get_entity_id(request) { dump("*** get_entity_id()\n"); Assert.ok( request instanceof Ci.nsIResumableChannel, @@ -84,7 +84,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_resume, null, CL_EXPECT_FAILURE)); } - function try_resume(request, data, ctx) { + function try_resume(request) { dump("*** try_resume()\n"); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); @@ -94,7 +94,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_resume_zero, null)); } - function try_resume_zero(request, data, ctx) { + function try_resume_zero(request, data) { dump("*** try_resume_zero()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody.substring(1)); @@ -106,7 +106,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_no_range, null, CL_EXPECT_FAILURE)); } - function try_no_range(request, data, ctx) { + function try_no_range(request) { dump("*** try_no_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); @@ -118,7 +118,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_bytes_range, null)); } - function try_bytes_range(request, data, ctx) { + function try_bytes_range(request, data) { dump("*** try_bytes_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody); @@ -132,7 +132,7 @@ function run_test() { ); } - function try_foo_bar_range(request, data, ctx) { + function try_foo_bar_range(request) { dump("*** try_foo_bar_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); @@ -146,7 +146,7 @@ function run_test() { ); } - function try_foobar_range(request, data, ctx) { + function try_foobar_range(request) { dump("*** try_foobar_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); @@ -162,7 +162,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_bytes_foobar_range, null)); } - function try_bytes_foobar_range(request, data, ctx) { + function try_bytes_foobar_range(request, data) { dump("*** try_bytes_foobar_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody); @@ -180,7 +180,7 @@ function run_test() { ); } - function try_bytesfoo_bar_range(request, data, ctx) { + function try_bytesfoo_bar_range(request) { dump("*** try_bytesfoo_bar_range()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); @@ -191,7 +191,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(try_no_accept_ranges, null)); } - function try_no_accept_ranges(request, data, ctx) { + function try_no_accept_ranges(request, data) { dump("*** try_no_accept_ranges()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody); @@ -208,7 +208,7 @@ function run_test() { ); } - function try_suspend_resume(request, data, ctx) { + function try_suspend_resume(request, data) { dump("*** try_suspend_resume()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody); @@ -219,7 +219,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(success, null)); } - function success(request, data, ctx) { + function success(request, data) { dump("*** success()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody); @@ -234,7 +234,7 @@ function run_test() { ); } - function test_auth_nopw(request, data, ctx) { + function test_auth_nopw(request) { dump("*** test_auth_nopw()\n"); Assert.ok(!request.nsIHttpChannel.requestSucceeded); Assert.equal(request.status, NS_ERROR_ENTITY_CHANGED); @@ -249,7 +249,7 @@ function run_test() { chan.notificationCallbacks = new Requestor(); chan.asyncOpen(new ChannelListener(test_auth, null, CL_EXPECT_FAILURE)); } - function test_auth(request, data, ctx) { + function test_auth(request) { dump("*** test_auth()\n"); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); Assert.ok(request.nsIHttpChannel.responseStatus < 300); @@ -266,7 +266,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(test_auth_resume, null)); } - function test_auth_resume(request, data, ctx) { + function test_auth_resume(request, data) { dump("*** test_auth_resume()\n"); Assert.equal(data, rangeBody.substring(1)); Assert.ok(request.nsIHttpChannel.requestSucceeded); @@ -278,7 +278,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(test_404, null, CL_EXPECT_FAILURE)); } - function test_404(request, data, ctx) { + function test_404(request) { dump("*** test_404()\n"); Assert.equal(request.status, NS_ERROR_ENTITY_CHANGED); Assert.equal(request.nsIHttpChannel.responseStatus, 404); @@ -289,7 +289,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(test_416, null, CL_EXPECT_FAILURE)); } - function test_416(request, data, ctx) { + function test_416(request) { dump("*** test_416()\n"); Assert.equal(request.status, NS_ERROR_ENTITY_CHANGED); Assert.equal(request.nsIHttpChannel.responseStatus, 416); @@ -301,7 +301,7 @@ function run_test() { chan.asyncOpen(new ChannelListener(test_redir_resume, null)); } - function test_redir_resume(request, data, ctx) { + function test_redir_resume(request, data) { dump("*** test_redir_resume()\n"); Assert.ok(request.nsIHttpChannel.requestSucceeded); Assert.equal(data, rangeBody.substring(1)); @@ -316,7 +316,7 @@ function run_test() { ); } - function test_redir_noresume(request, data, ctx) { + function test_redir_noresume(request) { dump("*** test_redir_noresume()\n"); Assert.equal(request.status, NS_ERROR_NOT_RESUMABLE); diff --git a/netwerk/test/unit/test_resumable_truncate.js b/netwerk/test/unit/test_resumable_truncate.js index cdcab591c2..c0da631e08 100644 --- a/netwerk/test/unit/test_resumable_truncate.js +++ b/netwerk/test/unit/test_resumable_truncate.js @@ -6,7 +6,7 @@ const { HttpServer } = ChromeUtils.importESModule( var httpserver = null; -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } @@ -52,9 +52,9 @@ Canceler.prototype = { "nsIRequestObserver", ]), - onStartRequest(request) {}, + onStartRequest() {}, - onDataAvailable(request, stream, offset, count) { + onDataAvailable(request) { request.QueryInterface(Ci.nsIChannel).cancel(Cr.NS_BINDING_ABORTED); }, diff --git a/netwerk/test/unit/test_retry_0rtt.js b/netwerk/test/unit/test_retry_0rtt.js index e1770ab8a1..661d7d2ab4 100644 --- a/netwerk/test/unit/test_retry_0rtt.js +++ b/netwerk/test/unit/test_retry_0rtt.js @@ -11,7 +11,7 @@ var httpServer = null; let handlerCallbacks = {}; -function listenHandler(metadata, response) { +function listenHandler(metadata) { info(metadata.path); handlerCallbacks[metadata.path] = (handlerCallbacks[metadata.path] || 0) + 1; } @@ -48,6 +48,12 @@ add_setup( ); let nssComponent = Cc["@mozilla.org/psm;1"].getService(Ci.nsINSSComponent); await nssComponent.asyncClearSSLExternalAndInternalSessionCache(); + + // See Bug 1878505 + Services.prefs.setIntPref("network.http.speculative-parallel-limit", 0); + registerCleanupFunction(async () => { + Services.prefs.clearUserPref("network.http.speculative-parallel-limit"); + }); } ); @@ -83,7 +89,7 @@ add_task( var retryDomains = [ "0rtt-alert-bad-mac.example.com", "0rtt-alert-protocol-version.example.com", - //"0rtt-alert-unexpected.example.com", // TODO(bug 1753204): uncomment this + "0rtt-alert-unexpected.example.com", ]; Services.prefs.setCharPref("network.dns.localDomains", retryDomains); diff --git a/netwerk/test/unit/test_simple.js b/netwerk/test/unit/test_simple.js index 52c068f517..98f1d3ee3e 100644 --- a/netwerk/test/unit/test_simple.js +++ b/netwerk/test/unit/test_simple.js @@ -58,7 +58,7 @@ function serverHandler(metadata, response) { } } -function checkRequest(request, data, context) { +function checkRequest(request, data) { if (dbg) { print("============== checkRequest: in"); } diff --git a/netwerk/test/unit/test_socks.js b/netwerk/test/unit/test_socks.js index 6ce9f4895e..7588857f78 100644 --- a/netwerk/test/unit/test_socks.js +++ b/netwerk/test/unit/test_socks.js @@ -461,7 +461,7 @@ SocksTestServer.prototype = { this.client_connections.push(client); }, - onStopListening(socket) {}, + onStopListening() {}, close() { if (this.client_subprocess) { diff --git a/netwerk/test/unit/test_speculative_connect.js b/netwerk/test/unit/test_speculative_connect.js index f99ace0d71..776273b8f2 100644 --- a/netwerk/test/unit/test_speculative_connect.js +++ b/netwerk/test/unit/test_speculative_connect.js @@ -81,7 +81,7 @@ function TestServer() { TestServer.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIServerSocket"]), - onSocketAccepted(socket, trans) { + onSocketAccepted() { try { this.listener.close(); } catch (e) {} @@ -89,7 +89,7 @@ TestServer.prototype = { next_test(); }, - onStopListening(socket) {}, + onStopListening() {}, }; /** TestFailedStreamCallback diff --git a/netwerk/test/unit/test_stale-while-revalidate_loop.js b/netwerk/test/unit/test_stale-while-revalidate_loop.js index dc28815119..5b6d47fd5b 100644 --- a/netwerk/test/unit/test_stale-while-revalidate_loop.js +++ b/netwerk/test/unit/test_stale-while-revalidate_loop.js @@ -16,10 +16,10 @@ function make_channel(url) { }).QueryInterface(Ci.nsIHttpChannel); } -async function get_response(channel, fromCache) { +async function get_response(channel) { return new Promise(resolve => { channel.asyncOpen( - new ChannelListener((request, buffer, ctx, isFromCache) => { + new ChannelListener((request, buffer) => { resolve(buffer); }) ); @@ -37,7 +37,7 @@ add_task(async function () { addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); let response = await get_response(make_channel(URI), false); - ok(response == "1", "got response ver 1"); + Assert.equal(response, "1", "got response ver 1"); response = await get_response(make_channel(URI), false); - ok(response == "1", "got response ver 1"); + Assert.equal(response, "1", "got response ver 1"); }); diff --git a/netwerk/test/unit/test_stale-while-revalidate_max-age-0.js b/netwerk/test/unit/test_stale-while-revalidate_max-age-0.js index 01bb6639bc..c2b7809f07 100644 --- a/netwerk/test/unit/test_stale-while-revalidate_max-age-0.js +++ b/netwerk/test/unit/test_stale-while-revalidate_max-age-0.js @@ -54,7 +54,11 @@ async function get_response(channel, fromCache) { return new Promise(resolve => { channel.asyncOpen( new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + Assert.equal( + fromCache, + isFromCache, + `got response from cache = ${fromCache}` + ); resolve(buffer); }) ); @@ -91,7 +95,7 @@ add_task(async function () { version = 1; max_age = 0; response = await get_response(make_channel(URI), false); - ok(response == generate_response(1), "got response ver 1"); + Assert.equal(response, generate_response(1), "got response ver 1"); await sleep(2); @@ -102,12 +106,12 @@ add_task(async function () { version = 2; max_age = 100; response = await get_response(make_channel(URI), true); - ok(response == generate_response(1), "got response ver 1"); + Assert.equal(response, generate_response(1), "got response ver 1"); await reval_done; response = await get_response(make_channel(URI), true); - ok(response == generate_response(2), "got response ver 2"); + Assert.equal(response, generate_response(2), "got response ver 2"); await stop_server(httpserver); }); diff --git a/netwerk/test/unit/test_stale-while-revalidate_negative.js b/netwerk/test/unit/test_stale-while-revalidate_negative.js index c9ef87e2dd..1715cdbc1a 100644 --- a/netwerk/test/unit/test_stale-while-revalidate_negative.js +++ b/netwerk/test/unit/test_stale-while-revalidate_negative.js @@ -49,7 +49,11 @@ async function get_response(channel, fromCache) { return new Promise(resolve => { channel.asyncOpen( new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + Assert.equal( + fromCache, + isFromCache, + `got response from cache = ${fromCache}` + ); resolve(buffer); }) ); @@ -80,13 +84,13 @@ add_task(async function () { version = 1; max_age = 1; response = await get_response(make_channel(URI), false); - ok(response == generate_response(1), "got response ver 1"); + Assert.equal(response, generate_response(1), "got response ver 1"); await sleep(max_age + 1 /* stale window */ + 1 /* to expire the window */); version = 2; response = await get_response(make_channel(URI), false); - ok(response == generate_response(2), "got response ver 2"); + Assert.equal(response, generate_response(2), "got response ver 2"); await stop_server(httpserver); }); diff --git a/netwerk/test/unit/test_stale-while-revalidate_positive.js b/netwerk/test/unit/test_stale-while-revalidate_positive.js index 51ce6bdd83..45dc0d305a 100644 --- a/netwerk/test/unit/test_stale-while-revalidate_positive.js +++ b/netwerk/test/unit/test_stale-while-revalidate_positive.js @@ -54,7 +54,11 @@ async function get_response(channel, fromCache) { return new Promise(resolve => { channel.asyncOpen( new ChannelListener((request, buffer, ctx, isFromCache) => { - ok(fromCache == isFromCache, `got response from cache = ${fromCache}`); + Assert.equal( + fromCache, + isFromCache, + `got response from cache = ${fromCache}` + ); resolve(buffer); }) ); @@ -91,7 +95,7 @@ add_task(async function () { version = 1; max_age = 1; response = await get_response(make_channel(URI), false); - ok(response == generate_response(1), "got response ver 1"); + Assert.equal(response, generate_response(1), "got response ver 1"); await sleep(max_age + 1); @@ -102,12 +106,12 @@ add_task(async function () { version = 2; max_age = 100; response = await get_response(make_channel(URI), true); - ok(response == generate_response(1), "got response ver 1"); + Assert.equal(response, generate_response(1), "got response ver 1"); await reval_done; response = await get_response(make_channel(URI), true); - ok(response == generate_response(2), "got response ver 2"); + Assert.equal(response, generate_response(2), "got response ver 2"); await stop_server(httpserver); }); diff --git a/netwerk/test/unit/test_streamcopier.js b/netwerk/test/unit/test_streamcopier.js index f550923546..536a9d5689 100644 --- a/netwerk/test/unit/test_streamcopier.js +++ b/netwerk/test/unit/test_streamcopier.js @@ -36,7 +36,7 @@ function run_test() { ctx.wrappedJSObject = ctx; var observer = { - onStartRequest(aRequest) {}, + onStartRequest() {}, onStopRequest(aRequest, aStatusCode) { Assert.equal(aStatusCode, 0); var sis = Cc["@mozilla.org/scriptableinputstream;1"].createInstance( diff --git a/netwerk/test/unit/test_suspend_channel_before_connect.js b/netwerk/test/unit/test_suspend_channel_before_connect.js index 79a0c43236..2b0da8ac88 100644 --- a/netwerk/test/unit/test_suspend_channel_before_connect.js +++ b/netwerk/test/unit/test_suspend_channel_before_connect.js @@ -20,11 +20,11 @@ function TestServer() { } TestServer.prototype = { - onSocketAccepted(socket, trans) { + onSocketAccepted() { Assert.ok(false, "Socket should not have tried to connect!"); }, - onStopListening(socket) {}, + onStopListening() {}, stop() { try { @@ -36,7 +36,7 @@ TestServer.prototype = { var requestListenerObserver = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject, topic) { if ( topic === "http-on-modify-request" && subject instanceof Ci.nsIHttpChannel @@ -62,13 +62,13 @@ var requestListenerObserver = { }; var listener = { - onStartRequest: function test_onStartR(request) {}, + onStartRequest: function test_onStartR() {}, onDataAvailable: function test_ODA() { do_throw("Should not get any data!"); }, - onStopRequest: function test_onStopR(request, status) { + onStopRequest: function test_onStopR() { executeSoon(run_next_test); }, }; diff --git a/netwerk/test/unit/test_suspend_channel_on_authRetry.js b/netwerk/test/unit/test_suspend_channel_on_authRetry.js index ad0b728b68..ef242b65e5 100644 --- a/netwerk/test/unit/test_suspend_channel_on_authRetry.js +++ b/netwerk/test/unit/test_suspend_channel_on_authRetry.js @@ -22,7 +22,7 @@ AuthPrompt.prototype = { QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]), - prompt: function ap1_prompt(title, text, realm, save, defaultText, result) { + prompt: function ap1_prompt() { do_throw("unexpected prompt call"); }, @@ -42,7 +42,7 @@ AuthPrompt.prototype = { return true; }, - promptPassword: function promptPW(title, text, realm, save, pwd) { + promptPassword: function promptPW() { do_throw("unexpected promptPassword call"); }, }; @@ -64,7 +64,7 @@ requestListenerObserver.prototype = { resumeOnModifyRequest: false, QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject, topic) { if ( topic === "http-on-before-connect" && subject instanceof Ci.nsIHttpChannel diff --git a/netwerk/test/unit/test_suspend_channel_on_examine.js b/netwerk/test/unit/test_suspend_channel_on_examine.js index 7667026a56..0dd36be28f 100644 --- a/netwerk/test/unit/test_suspend_channel_on_examine.js +++ b/netwerk/test/unit/test_suspend_channel_on_examine.js @@ -19,7 +19,7 @@ function responseHandler(metadata, response) { function onExamineListener(callback) { obs.addObserver( { - observe(subject, topic, data) { + observe(subject) { obs.removeObserver(this, "http-on-examine-response"); callback(subject.QueryInterface(Ci.nsIHttpChannel)); }, @@ -48,7 +48,7 @@ add_test(function testAsyncCancel() { chan.resume(); }); }); - startChannelRequest(baseUrl, CL_EXPECT_FAILURE, (request, data, context) => { + startChannelRequest(baseUrl, CL_EXPECT_FAILURE, (request, data) => { Assert.ok(!data, "no response"); Assert.equal( diff --git a/netwerk/test/unit/test_suspend_channel_on_examine_merged_response.js b/netwerk/test/unit/test_suspend_channel_on_examine_merged_response.js index 7496796500..eb26f9d9db 100644 --- a/netwerk/test/unit/test_suspend_channel_on_examine_merged_response.js +++ b/netwerk/test/unit/test_suspend_channel_on_examine_merged_response.js @@ -20,7 +20,7 @@ var channelResumed = false; var observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject, topic) { if ( topic === "http-on-examine-merged-response" && subject instanceof Ci.nsIHttpChannel @@ -39,7 +39,7 @@ var observer = { }; var listener = { - onStartRequest(request) { + onStartRequest() { buffer = ""; }, diff --git a/netwerk/test/unit/test_suspend_channel_on_modified.js b/netwerk/test/unit/test_suspend_channel_on_modified.js index 397ffae881..20b52ba817 100644 --- a/netwerk/test/unit/test_suspend_channel_on_modified.js +++ b/netwerk/test/unit/test_suspend_channel_on_modified.js @@ -31,7 +31,7 @@ function successResponseHandler(metadata, response) { function onModifyListener(callback) { obs.addObserver( { - observe(subject, topic, data) { + observe(subject) { obs.removeObserver(this, "http-on-modify-request"); callback(subject.QueryInterface(Ci.nsIHttpChannel)); }, @@ -47,7 +47,7 @@ function startChannelRequest(uri, flags, expectedResponse = null) { }); chan.asyncOpen( new ChannelListener( - (request, data, context) => { + (request, data) => { if (expectedResponse) { Assert.equal(data, expectedResponse); } else { diff --git a/netwerk/test/unit/test_synthesized_response.js b/netwerk/test/unit/test_synthesized_response.js index a598e649c4..e5a82405f2 100644 --- a/netwerk/test/unit/test_synthesized_response.js +++ b/netwerk/test/unit/test_synthesized_response.js @@ -45,10 +45,10 @@ function make_channel(url, body, cb) { getInterface(iid) { return this.QueryInterface(iid); }, - onProgress(request, progress, progressMax) { + onProgress() { gotOnProgress = true; }, - onStatus(request, status, statusArg) { + onStatus() { gotOnStatus = true; }, shouldPrepareForIntercept() { @@ -277,7 +277,7 @@ add_test(function () { // In this case we should automatically ResetInterception() and complete the // network request. add_test(function () { - var chan = make_channel(URL + "/body", null, function (channel) { + var chan = make_channel(URL + "/body", null, function () { throw new Error("boom"); }); chan.asyncOpen(new ChannelListener(handle_remote_response, null)); diff --git a/netwerk/test/unit/test_throttlechannel.js b/netwerk/test/unit/test_throttlechannel.js index 5a0cfd1151..af5604ff36 100644 --- a/netwerk/test/unit/test_throttlechannel.js +++ b/netwerk/test/unit/test_throttlechannel.js @@ -38,7 +38,11 @@ function run_test() { channel.asyncOpen( new ChannelListener(() => { - ok(tq.bytesProcessed() > 0, "throttled queue processed some bytes"); + Assert.greater( + tq.bytesProcessed(), + 0, + "throttled queue processed some bytes" + ); httpserver.stop(do_test_finished); }) diff --git a/netwerk/test/unit/test_throttling.js b/netwerk/test/unit/test_throttling.js index 7627684dce..c51bc62e95 100644 --- a/netwerk/test/unit/test_throttling.js +++ b/netwerk/test/unit/test_throttling.js @@ -56,7 +56,11 @@ function run_test() { let startTime = Date.now(); channel.asyncOpen( new ChannelListener(() => { - ok(Date.now() - startTime > 1000, "request took more than one second"); + Assert.greater( + Date.now() - startTime, + 1000, + "request took more than one second" + ); httpserver.stop(do_test_finished); }) diff --git a/netwerk/test/unit/test_tls13_disabled.js b/netwerk/test/unit/test_tls13_disabled.js index 3bcb6333aa..4a86cf452c 100644 --- a/netwerk/test/unit/test_tls13_disabled.js +++ b/netwerk/test/unit/test_tls13_disabled.js @@ -32,7 +32,7 @@ Listener.prototype = { read_stream(stream, cnt); }, - onStopRequest: function testOnStopRequest(request, status) { + onStopRequest: function testOnStopRequest(request) { let httpVersion = ""; try { httpVersion = request.protocolVersion; diff --git a/netwerk/test/unit/test_tls_flags.js b/netwerk/test/unit/test_tls_flags.js index 876cd0ccea..5d803c48a2 100644 --- a/netwerk/test/unit/test_tls_flags.js +++ b/netwerk/test/unit/test_tls_flags.js @@ -166,7 +166,7 @@ function startClient(port, tlsFlags, expectSuccess) { req.open("GET", `https://${hostname}:${port}`); let internalChannel = req.channel.QueryInterface(Ci.nsIHttpChannelInternal); internalChannel.tlsFlags = tlsFlags; - return new Promise((resolve, reject) => { + return new Promise(resolve => { req.onload = () => { ok( expectSuccess, diff --git a/netwerk/test/unit/test_tls_server_multiple_clients.js b/netwerk/test/unit/test_tls_server_multiple_clients.js index fdafd9744d..8054d7746c 100644 --- a/netwerk/test/unit/test_tls_server_multiple_clients.js +++ b/netwerk/test/unit/test_tls_server_multiple_clients.js @@ -34,7 +34,7 @@ function startServer(cert) { input = transport.openInputStream(0, 0, 0); output = transport.openOutputStream(0, 0, 0); }, - onHandshakeDone(socket, status) { + onHandshakeDone() { info("TLS handshake done"); input.asyncWait( diff --git a/netwerk/test/unit/test_traceable_channel.js b/netwerk/test/unit/test_traceable_channel.js index 3390682bcf..d4086763cd 100644 --- a/netwerk/test/unit/test_traceable_channel.js +++ b/netwerk/test/unit/test_traceable_channel.js @@ -48,7 +48,7 @@ TracingListener.prototype = { do_throw("replaced channel's listener during onStartRequest."); }, - onStopRequest(request, statusCode) { + onStopRequest() { dump("*** tracing listener onStopRequest\n"); Assert.equal(gotOnStartRequest, true); @@ -88,7 +88,7 @@ HttpResponseExaminer.prototype = { }, // Replace channel's listener. - observe(subject, topic, data) { + observe(subject) { dump("In HttpResponseExaminer.observe\n"); try { subject.QueryInterface(Ci.nsITraceableChannel); @@ -129,7 +129,7 @@ function make_channel(url) { } // Check if received body is correctly modified. -function channel_finished(request, input, ctx) { +function channel_finished() { httpserver.stop(do_test_finished); } diff --git a/netwerk/test/unit/test_trackingProtection_annotateChannels.js b/netwerk/test/unit/test_trackingProtection_annotateChannels.js index a54005b8e2..2fb086bc1f 100644 --- a/netwerk/test/unit/test_trackingProtection_annotateChannels.js +++ b/netwerk/test/unit/test_trackingProtection_annotateChannels.js @@ -63,8 +63,8 @@ listener.prototype = { request.cancel(Cr.NS_ERROR_ABORT); this._nextTest(); }, - onDataAvailable: (request, stream, offset, count) => {}, - onStopRequest: (request, status) => {}, + onDataAvailable: () => {}, + onStopRequest: () => {}, }; var httpServer; diff --git a/netwerk/test/unit/test_trr.js b/netwerk/test/unit/test_trr.js index 52b36620b1..1d5d9cd971 100644 --- a/netwerk/test/unit/test_trr.js +++ b/netwerk/test/unit/test_trr.js @@ -57,7 +57,7 @@ function setModeAndURI(mode, path) { ); } -function makeChan(url, mode, bypassCache) { +function makeChan(url, mode) { let chan = NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true, diff --git a/netwerk/test/unit/test_trr_blocklist.js b/netwerk/test/unit/test_trr_blocklist.js index 8f9d3ffbc5..3c72e4e0a7 100644 --- a/netwerk/test/unit/test_trr_blocklist.js +++ b/netwerk/test/unit/test_trr_blocklist.js @@ -14,6 +14,21 @@ function setup() { } setup(); +// Waits until a predicate returns true or re-tries the predicate calls +// |retry| times, we wait for 100ms between each calls. +async function waitUntil(predicate, retry = 20) { + let count = 0; + while (count++ < retry) { + if (await predicate()) { + return true; + } + // Wait for 100 milliseconds. + await new Promise(resolve => do_timeout(100, resolve)); + } + // Timed out after trying too many times. + return false; +} + add_task(async function checkBlocklisting() { let trrServer = new TRRServer(); registerCleanupFunction(async () => { @@ -76,3 +91,52 @@ add_task(async function checkBlocklisting() { "We should do another TRR request because the bloclist expired" ); }); + +add_task(async function test_blocklist_cname() { + let trrServer = new TRRServer(); + registerCleanupFunction(async () => { + await trrServer.stop(); + }); + await trrServer.start(); + info(`port = ${trrServer.port()}\n`); + + Services.dns.clearCache(true); + Services.prefs.setCharPref( + "network.trr.uri", + `https://foo.example.com:${trrServer.port()}/dns-query` + ); + Services.prefs.setIntPref("network.trr.mode", Ci.nsIDNSService.MODE_TRRFIRST); + + await trrServer.registerDoHAnswers(`top.test.com`, "NS", { + answers: [ + { + name: "top.test.com", + ttl: 55, + type: "CNAME", + flush: false, + data: "other.foo", + }, + ], + }); + + await trrServer.registerDoHAnswers(`other.foo`, "NS", { + answers: [ + { + name: "other.foo", + ttl: 55, + type: "NS", + flush: false, + data: "ns.other.foo", + }, + ], + }); + + override.addIPOverride("sub.top.test.com", "2.2.2.2"); + await new TRRDNSListener("sub.top.test.com", { + expectedAnswer: "2.2.2.2", + }); + + await waitUntil(async () => { + return (await trrServer.requestCount("top.test.com", "NS")) == 1; + }); +}); diff --git a/netwerk/test/unit/test_trr_confirmation.js b/netwerk/test/unit/test_trr_confirmation.js index 6635f71377..354e50eb35 100644 --- a/netwerk/test/unit/test_trr_confirmation.js +++ b/netwerk/test/unit/test_trr_confirmation.js @@ -246,7 +246,7 @@ add_task(async function multiple_failures() { CONFIRM_TRYING_OK, "Should be CONFIRM_TRYING_OK" ); - await waitForConfirmationState(CONFIRM_OK, 4500); + await waitForConfirmationState(CONFIRM_OK, 6000); }); add_task(async function test_connectivity_change() { diff --git a/netwerk/test/unit/test_trr_https_fallback.js b/netwerk/test/unit/test_trr_https_fallback.js index 23c5adedaa..dde8e16086 100644 --- a/netwerk/test/unit/test_trr_https_fallback.js +++ b/netwerk/test/unit/test_trr_https_fallback.js @@ -963,14 +963,14 @@ add_task(async function testAllRecordsInHttp3ExcludedList() { }); WebSocketListener.prototype = { - onAcknowledge(aContext, aSize) {}, - onBinaryMessageAvailable(aContext, aMsg) {}, - onMessageAvailable(aContext, aMsg) {}, - onServerClose(aContext, aCode, aReason) {}, - onStart(aContext) { + onAcknowledge() {}, + onBinaryMessageAvailable() {}, + onMessageAvailable() {}, + onServerClose() {}, + onStart() { this.finish(); }, - onStop(aContext, aStatusCode) {}, + onStop() {}, }; add_task(async function testUpgradeNotUsingHTTPSRR() { diff --git a/netwerk/test/unit/test_trr_nat64.js b/netwerk/test/unit/test_trr_nat64.js index aa41f2a611..296035884b 100644 --- a/netwerk/test/unit/test_trr_nat64.js +++ b/netwerk/test/unit/test_trr_nat64.js @@ -22,7 +22,7 @@ registerCleanupFunction(async () => { * @returns {Promise} A promise that fulfills when the notification is fired. */ function promiseObserverNotification(topic, matchFunc) { - return new Promise((resolve, reject) => { + return new Promise(resolve => { Services.obs.addObserver(function observe(subject, topic1, data) { let matches = typeof matchFunc != "function" || matchFunc(subject, data); if (!matches) { diff --git a/netwerk/test/unit/test_trr_proxy.js b/netwerk/test/unit/test_trr_proxy.js index 962971d103..9c1154d7a7 100644 --- a/netwerk/test/unit/test_trr_proxy.js +++ b/netwerk/test/unit/test_trr_proxy.js @@ -38,7 +38,7 @@ ChromeUtils.defineLazyGetter(this, "systemSettings", function () { PACURI: `data:application/x-ns-proxy-autoconfig;charset=utf-8,${encodeURIComponent( FindProxyForURL.toString() )}`, - getProxyForURI(aURI) { + getProxyForURI() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; diff --git a/netwerk/test/unit/test_trr_proxy_auth.js b/netwerk/test/unit/test_trr_proxy_auth.js index f339d82dea..afd2043d32 100644 --- a/netwerk/test/unit/test_trr_proxy_auth.js +++ b/netwerk/test/unit/test_trr_proxy_auth.js @@ -34,7 +34,7 @@ AuthPrompt.prototype = { return true; }, - asyncPromptAuth: function ap_async(chan, cb, ctx, lvl, info) { + asyncPromptAuth: function ap_async() { throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED); }, }; @@ -99,7 +99,7 @@ add_task(async function test_trr_proxy_auth() { let authTriggered = false; let observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(aSubject, aTopic, aData) { + observe(aSubject, aTopic) { if (aTopic == "http-on-examine-response") { Services.obs.removeObserver(observer, "http-on-examine-response"); let channel = aSubject.QueryInterface(Ci.nsIChannel); diff --git a/netwerk/test/unit/test_trr_with_proxy.js b/netwerk/test/unit/test_trr_with_proxy.js index 7d238adb98..d7f520595c 100644 --- a/netwerk/test/unit/test_trr_with_proxy.js +++ b/netwerk/test/unit/test_trr_with_proxy.js @@ -156,7 +156,7 @@ add_task(async function test_trr_proxy() { QueryInterface: ChromeUtils.generateQI(["nsISystemProxySettings"]), mainThreadOnly: true, PACURI: null, - getProxyForURI: (aSpec, aScheme, aHost, aPort) => { + getProxyForURI: () => { return `HTTPS foo.example.com:${proxyPort}`; }, }; diff --git a/netwerk/test/unit/test_udp_multicast.js b/netwerk/test/unit/test_udp_multicast.js index 202a4a1d99..a2022f5bf1 100644 --- a/netwerk/test/unit/test_udp_multicast.js +++ b/netwerk/test/unit/test_udp_multicast.js @@ -37,7 +37,7 @@ function sendPing(socket, addr) { socket.close(); resolve(message.data); }, - onStopListening(sock, status) {}, + onStopListening() {}, }); info("Multicast send to port " + socket.port); diff --git a/netwerk/test/unit/test_udpsocket.js b/netwerk/test/unit/test_udpsocket.js index 340fe6aa13..54170489e3 100644 --- a/netwerk/test/unit/test_udpsocket.js +++ b/netwerk/test/unit/test_udpsocket.js @@ -25,7 +25,7 @@ add_test(function test_udp_message_raw_data() { socket.close(); run_next_test(); }, - onStopListening(aSocket, aStatus) {}, + onStopListening() {}, }); let rawData = new Uint8Array(HELLO_WORLD.length); @@ -52,7 +52,7 @@ add_test(function test_udp_send_stream() { socket.close(); run_next_test(); }, - onStopListening(aSocket, aStatus) {}, + onStopListening() {}, }); let stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( @@ -80,7 +80,7 @@ add_test(function test_udp_message_zero_length() { socket.close(); run_next_test(); }, - onStopListening(aSocket, aStatus) {}, + onStopListening() {}, }); let rawData = new Uint8Array(EMPTY_MESSAGE.length); diff --git a/netwerk/test/unit/test_unix_domain.js b/netwerk/test/unit/test_unix_domain.js index 221721dc38..25a98b9aae 100644 --- a/netwerk/test/unit/test_unix_domain.js +++ b/netwerk/test/unit/test_unix_domain.js @@ -131,7 +131,7 @@ function test_echo() { ); }, - onStopListening(aServ, aStatus) { + onStopListening(aServ) { info("called test_echo's onStopListening"); log += "s"; @@ -456,7 +456,7 @@ function test_connect_permission() { let serverOutput = aTransport.openOutputStream(0, 0, 0); serverInput.asyncWait( - function (aStream) { + function () { info( "called test_connect_permission's socketAccepted's onInputStreamReady" ); @@ -485,7 +485,7 @@ function test_connect_permission() { server.close(); } - function stopListening(aServ, aStatus) { + function stopListening() { info("called test_connect_permission's server's stopListening"); log += "s"; @@ -650,7 +650,7 @@ function test_abstract_address_socket() { let serverOutput = aTransport.openOutputStream(0, 0, 0); serverInput.asyncWait( - aStream => { + () => { info( "called test_abstract_address_socket's onSocketAccepted's onInputStreamReady" ); @@ -665,7 +665,7 @@ function test_abstract_address_socket() { threadManager.currentThread ); }, - onStopListening: (aServ, aTransport) => {}, + onStopListening: () => {}, }); let client = @@ -680,7 +680,7 @@ function test_abstract_address_socket() { clientOutput.write("ping ping", 9); clientInput.asyncWait( - aStream => { + () => { let clientScriptInput = new ScriptableInputStream(clientInput); let available = clientScriptInput.available(); if (available) { diff --git a/netwerk/test/unit/test_websocket_offline.js b/netwerk/test/unit/test_websocket_offline.js index 1f13879dbc..ef8fe0e8dc 100644 --- a/netwerk/test/unit/test_websocket_offline.js +++ b/netwerk/test/unit/test_websocket_offline.js @@ -10,11 +10,11 @@ var chan; var offlineStatus; var listener = { - onAcknowledge(aContext, aSize) {}, - onBinaryMessageAvailable(aContext, aMsg) {}, - onMessageAvailable(aContext, aMsg) {}, - onServerClose(aContext, aCode, aReason) {}, - onStart(aContext) { + onAcknowledge() {}, + onBinaryMessageAvailable() {}, + onMessageAvailable() {}, + onServerClose() {}, + onStart() { // onStart is not called when a connection fails Assert.ok(false); }, diff --git a/netwerk/test/unit/test_websocket_with_h3_active.js b/netwerk/test/unit/test_websocket_with_h3_active.js index f9ed2b08a0..7aa7ffc6da 100644 --- a/netwerk/test/unit/test_websocket_with_h3_active.js +++ b/netwerk/test/unit/test_websocket_with_h3_active.js @@ -25,14 +25,14 @@ add_task(async function setup() { }); WebSocketListener.prototype = { - onAcknowledge(aContext, aSize) {}, - onBinaryMessageAvailable(aContext, aMsg) {}, - onMessageAvailable(aContext, aMsg) {}, - onServerClose(aContext, aCode, aReason) {}, - onStart(aContext) { + onAcknowledge() {}, + onBinaryMessageAvailable() {}, + onMessageAvailable() {}, + onServerClose() {}, + onStart() { this.finish(); }, - onStop(aContext, aStatusCode) {}, + onStop() {}, }; function makeH2Chan() { diff --git a/netwerk/test/unit/test_webtransport_simple.js b/netwerk/test/unit/test_webtransport_simple.js index bd99654bc3..4b64ef840e 100644 --- a/netwerk/test/unit/test_webtransport_simple.js +++ b/netwerk/test/unit/test_webtransport_simple.js @@ -77,6 +77,7 @@ add_task(async function test_wt_datagram() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -134,6 +135,7 @@ add_task(async function test_connect_wt() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -156,6 +158,7 @@ add_task(async function test_redirect_wt() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/redirect`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -175,6 +178,7 @@ add_task(async function test_reject() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/reject`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -198,6 +202,7 @@ async function test_closed(path) { }); webTransport.asyncConnect( NetUtil.newURI(`https://${host}${path}`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -229,6 +234,7 @@ add_task(async function test_wt_stream_create() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -255,6 +261,7 @@ add_task(async function test_wt_stream_send_and_stats() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -295,6 +302,7 @@ add_task(async function test_wt_receive_stream_and_stats() { }); webTransport.asyncConnect( NetUtil.newURI(`https://${host}/create_unidi_stream_and_hello`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -337,6 +345,7 @@ add_task(async function test_wt_outgoing_bidi_stream() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -388,6 +397,7 @@ add_task(async function test_wt_incoming_bidi_stream() { }); webTransport.asyncConnect( NetUtil.newURI(`https://${host}/create_bidi_stream`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, @@ -434,6 +444,7 @@ async function createWebTransportAndConnect() { webTransport.asyncConnect( NetUtil.newURI(`https://${host}/success`), + true, [], Services.scriptSecurityManager.getSystemPrincipal(), Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, diff --git a/netwerk/test/unit/test_xmlhttprequest.js b/netwerk/test/unit/test_xmlhttprequest.js index 7363a54cfd..457e24d80c 100644 --- a/netwerk/test/unit/test_xmlhttprequest.js +++ b/netwerk/test/unit/test_xmlhttprequest.js @@ -42,7 +42,7 @@ function run_test() { // Test async XHR sending let async = createXHR(true); - async.addEventListener("readystatechange", function (event) { + async.addEventListener("readystatechange", function () { if (checkResults(async)) { httpserver.stop(do_test_finished); } diff --git a/netwerk/test/unit/trr_common.js b/netwerk/test/unit/trr_common.js index 2ddd556983..d65157edee 100644 --- a/netwerk/test/unit/trr_common.js +++ b/netwerk/test/unit/trr_common.js @@ -1043,8 +1043,8 @@ async function test_no_retry_without_doh() { getInterface(iid) { return this.QueryInterface(iid); }, - onProgress(request, progress, progressMax) {}, - onStatus(request, status, statusArg) { + onProgress() {}, + onStatus(request, status) { this.statusCount[status] = 1 + (this.statusCount[status] || 0); }, }; diff --git a/netwerk/test/unit/xpcshell.toml b/netwerk/test/unit/xpcshell.toml index dd5957abdb..fb3791963d 100644 --- a/netwerk/test/unit/xpcshell.toml +++ b/netwerk/test/unit/xpcshell.toml @@ -35,9 +35,11 @@ support-files = [ # https://bugzilla.mozilla.org/show_bug.cgi?id=1816325 # Several tests rely on redirecting to data: URIs, which was allowed for a long # time but now forbidden. So we enable it just for these tests. +# Native HTTPS query changes timings for some tests. Disable it for now. prefs = [ "dom.serviceWorkers.enabled=true", - "network.allow_redirect_to_data=true", + "network.allow_redirect_to_data=true", + "network.dns.native_https_query=false", ] ["test_1073747.js"] @@ -106,8 +108,6 @@ skip-if = [ ["test_auth_dialog_permission.js"] -["test_auth_jar.js"] - ["test_auth_multiple.js"] ["test_auth_proxy.js"] @@ -434,7 +434,6 @@ run-sequentially = "node server exceptions dont replay well" run-sequentially = "node server exceptions dont replay well" ["test_channel_close.js"] -skip-if = ["os == 'win' && socketprocess_networking && !debug"] ["test_channel_long_domain.js"] @@ -444,7 +443,9 @@ skip-if = ["os == 'win' && socketprocess_networking && !debug"] prefs = ["security.allow_eval_with_system_principal=true"] ["test_client_auth_with_proxy.js"] -skip-if = ["os == 'android'"] +skip-if = [ + "os == 'android'", +] ["test_coaleasing_h2_and_h3_connection.js"] skip-if = [ @@ -606,6 +607,9 @@ skip-if = ["!nightly_build"] # OHTTP Config manager not currently shipped to rel ["test_http2-proxy-failing.js"] run-sequentially = "node server exceptions dont replay well" +skip-if = [ + "os == 'win'" # https://bugzilla.mozilla.org/show_bug.cgi?id=1881334 +] ["test_http2-proxy.js"] run-sequentially = "one http2 node proxy is used for all tests, this test is using global session counter" @@ -731,6 +735,7 @@ run-sequentially = "http3server" skip-if = [ "os == 'android'", "os == 'win' && msix", # https://bugzilla.mozilla.org/show_bug.cgi?id=1807931 + "true", # Will be reenabled in bug 1865394 ] run-sequentially = "http3server" @@ -856,6 +861,8 @@ run-sequentially = "node server exceptions dont replay well" ["test_multipart_streamconv_missing_lead_boundary.js"] +["test_multipart_set_cookie.js"] + ["test_nestedabout_serialize.js"] ["test_net_addr.js"] diff --git a/netwerk/test/unit_ipc/child_veto_in_parent.js b/netwerk/test/unit_ipc/child_veto_in_parent.js index 8f922a254e..f1bc0a4f50 100644 --- a/netwerk/test/unit_ipc/child_veto_in_parent.js +++ b/netwerk/test/unit_ipc/child_veto_in_parent.js @@ -18,7 +18,7 @@ ChromeUtils.defineLazyGetter(this, "randomURI", function () { return URL + randomPath; }); -function make_channel(url, callback, ctx) { +function make_channel(url) { return NetUtil.newChannel({ uri: url, loadUsingSystemPrincipal: true }); } diff --git a/netwerk/test/unit_ipc/test_alt-data_cross_process_wrap.js b/netwerk/test/unit_ipc/test_alt-data_cross_process_wrap.js index 336b9e3129..07c3e8398a 100644 --- a/netwerk/test/unit_ipc/test_alt-data_cross_process_wrap.js +++ b/netwerk/test/unit_ipc/test_alt-data_cross_process_wrap.js @@ -41,7 +41,7 @@ function load_channel(channelUrl) { chan.asyncOpen(new ChannelListener(readTextData, null)); } -function make_channel(channelUrl, callback, ctx) { +function make_channel(channelUrl) { return NetUtil.newChannel({ uri: channelUrl, loadUsingSystemPrincipal: true, diff --git a/netwerk/test/unit_ipc/test_channel_id.js b/netwerk/test/unit_ipc/test_channel_id.js index fc37651249..1031dba4e2 100644 --- a/netwerk/test/unit_ipc/test_channel_id.js +++ b/netwerk/test/unit_ipc/test_channel_id.js @@ -47,7 +47,7 @@ let parentChannelsDone = new Promise(resolve => { }; }); -function observer(subject, topic, data) { +function observer(subject) { let channel = subject.QueryInterface(Ci.nsIHttpChannel); let uri = channel.URI.spec; diff --git a/netwerk/test/unit_ipc/test_gio_protocol_wrap.js b/netwerk/test/unit_ipc/test_gio_protocol_wrap.js index f6aa6b83e8..e6e2c42bc2 100644 --- a/netwerk/test/unit_ipc/test_gio_protocol_wrap.js +++ b/netwerk/test/unit_ipc/test_gio_protocol_wrap.js @@ -9,7 +9,7 @@ function run_test() { "localtest:,recent:" ); - do_await_remote_message("gio-allow-test-protocols").then(port => { + do_await_remote_message("gio-allow-test-protocols").then(() => { do_send_remote_message("gio-allow-test-protocols-done"); }); diff --git a/netwerk/test/unit_ipc/test_httpcancel_wrap.js b/netwerk/test/unit_ipc/test_httpcancel_wrap.js index f56d0e198b..3e54171ede 100644 --- a/netwerk/test/unit_ipc/test_httpcancel_wrap.js +++ b/netwerk/test/unit_ipc/test_httpcancel_wrap.js @@ -13,7 +13,7 @@ function run_test() { observer = { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]), - observe(subject, topic, data) { + observe(subject) { subject = subject.QueryInterface(Ci.nsIRequest); subject.cancel(Cr.NS_BINDING_ABORTED); diff --git a/netwerk/test/unit_ipc/xpcshell.toml b/netwerk/test/unit_ipc/xpcshell.toml index 569bcda751..24c84d745d 100644 --- a/netwerk/test/unit_ipc/xpcshell.toml +++ b/netwerk/test/unit_ipc/xpcshell.toml @@ -153,6 +153,7 @@ run-sequentially = "http3server" skip-if = [ "os == 'android'", "os == 'win' && msix", + "true", # Will be reenabled in bug 1865394 ] # https://bugzilla.mozilla.org/show_bug.cgi?id=1807925 run-sequentially = "http3server" diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 5a7be15d16..f437dec4bd 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -364,13 +364,13 @@ nsresult nsWifiMonitor::DoScan() { } return NS_DispatchToMainThread( - NewRunnableMethod<const nsTArray<RefPtr<nsIWifiAccessPoint>>&&, bool>( + NewRunnableMethod<nsTArray<RefPtr<nsIWifiAccessPoint>>, bool>( "CallWifiListeners", this, &nsWifiMonitor::CallWifiListeners, mLastAccessPoints.Clone(), accessPointsChanged)); } nsresult nsWifiMonitor::CallWifiListeners( - nsTArray<RefPtr<nsIWifiAccessPoint>>&& aAccessPoints, + const nsTArray<RefPtr<nsIWifiAccessPoint>>& aAccessPoints, bool aAccessPointsChanged) { MOZ_ASSERT(NS_IsMainThread()); LOG(("Sending wifi access points to the listeners")); diff --git a/netwerk/wifi/nsWifiMonitor.h b/netwerk/wifi/nsWifiMonitor.h index 5a37cc75be..55a3feedea 100644 --- a/netwerk/wifi/nsWifiMonitor.h +++ b/netwerk/wifi/nsWifiMonitor.h @@ -69,7 +69,7 @@ class nsWifiMonitor final : public nsIWifiMonitor, public nsIObserver { nsresult DoScan(); nsresult CallWifiListeners( - nsTArray<RefPtr<nsIWifiAccessPoint>>&& aAccessPoints, + const nsTArray<RefPtr<nsIWifiAccessPoint>>& aAccessPoints, bool aAccessPointsChanged); nsresult PassErrorToWifiListeners(nsresult rv); |