From 98146ae90bebe760a43e5404ca559a38533cea45 Mon Sep 17 00:00:00 2001 From: Valentin Gosu Date: Fri, 4 Jun 2021 10:00:55 +0000 Subject: [PATCH] Bug 1714307 - Autofix static-analysis warnings in netwerk/ r=necko-reviewers,kershaw Differential Revision: https://phabricator.services.mozilla.com/D116701 --- netwerk/base/Dashboard.cpp | 4 +- netwerk/base/EventTokenBucket.cpp | 11 +- netwerk/base/EventTokenBucket.h | 2 +- netwerk/base/IOActivityMonitor.h | 2 +- netwerk/base/LoadContextInfo.h | 3 +- netwerk/base/LoadInfo.cpp | 2 +- netwerk/base/LoadInfo.h | 4 +- netwerk/base/MemoryDownloader.h | 2 +- netwerk/base/NetworkConnectivityService.cpp | 10 +- netwerk/base/NetworkDataCountLayer.cpp | 2 +- netwerk/base/NetworkInfoServiceImpl.h | 2 +- netwerk/base/NetworkInfoServiceLinux.cpp | 6 +- netwerk/base/Predictor.cpp | 6 +- netwerk/base/Predictor.h | 2 +- netwerk/base/ProxyAutoConfig.cpp | 15 +- netwerk/base/RequestContextService.cpp | 2 +- netwerk/base/SSLTokensCache.h | 2 +- netwerk/base/SimpleBuffer.h | 4 +- netwerk/base/SimpleChannel.h | 5 +- netwerk/base/ThrottleQueue.cpp | 6 +- netwerk/base/ThrottleQueue.h | 2 +- netwerk/base/nsBaseChannel.cpp | 12 +- netwerk/base/nsBaseChannel.h | 2 +- netwerk/base/nsDirectoryIndexStream.h | 2 +- netwerk/base/nsFileStreams.cpp | 13 +- netwerk/base/nsFileStreams.h | 12 +- netwerk/base/nsIOService.cpp | 39 ++-- netwerk/base/nsIOService.h | 5 +- netwerk/base/nsIncrementalDownload.cpp | 21 ++- netwerk/base/nsInputStreamPump.cpp | 19 +- netwerk/base/nsInputStreamPump.h | 7 +- netwerk/base/nsLoadGroup.cpp | 15 +- netwerk/base/nsMIMEInputStream.cpp | 4 +- netwerk/base/nsMediaFragmentURIParser.cpp | 3 +- netwerk/base/nsNetUtil.cpp | 52 ++--- netwerk/base/nsNetUtil.h | 2 +- netwerk/base/nsPACMan.cpp | 18 +- netwerk/base/nsPACMan.h | 2 +- netwerk/base/nsPreloadedStream.cpp | 3 +- netwerk/base/nsProtocolProxyService.cpp | 134 ++++++++----- netwerk/base/nsProtocolProxyService.h | 24 +-- netwerk/base/nsServerSocket.cpp | 17 +- netwerk/base/nsServerSocket.h | 2 +- netwerk/base/nsSimpleURI.h | 17 +- netwerk/base/nsSocketTransport2.cpp | 139 ++++++++------ netwerk/base/nsSocketTransport2.h | 30 +-- netwerk/base/nsSocketTransportService2.cpp | 55 +++--- netwerk/base/nsSocketTransportService2.h | 4 +- netwerk/base/nsStandardURL.h | 47 +++-- netwerk/base/nsStreamListenerTee.cpp | 5 +- netwerk/base/nsStreamTransportService.cpp | 6 +- netwerk/base/nsUDPSocket.cpp | 7 +- netwerk/base/nsURLHelper.cpp | 52 ++--- netwerk/base/nsURLHelper.h | 9 +- netwerk/base/nsURLHelperUnix.cpp | 18 +- netwerk/base/nsURLParsers.cpp | 55 +++--- netwerk/build/nsNetModule.cpp | 4 +- netwerk/cache/nsDeleteDir.cpp | 6 +- netwerk/cache/nsDeleteDir.h | 2 +- netwerk/cache2/CacheEntry.cpp | 24 +-- netwerk/cache2/CacheEntry.h | 16 +- netwerk/cache2/CacheFile.cpp | 27 ++- netwerk/cache2/CacheFileChunk.cpp | 6 +- netwerk/cache2/CacheFileChunk.h | 2 +- netwerk/cache2/CacheFileContextEvictor.cpp | 9 +- netwerk/cache2/CacheFileContextEvictor.h | 6 +- netwerk/cache2/CacheFileIOManager.cpp | 44 ++--- netwerk/cache2/CacheFileIOManager.h | 12 +- netwerk/cache2/CacheFileInputStream.cpp | 6 +- netwerk/cache2/CacheFileMetadata.cpp | 15 +- netwerk/cache2/CacheFileMetadata.h | 2 +- netwerk/cache2/CacheFileOutputStream.cpp | 6 +- netwerk/cache2/CacheFileUtils.cpp | 8 +- netwerk/cache2/CacheFileUtils.h | 4 +- netwerk/cache2/CacheHashUtils.cpp | 6 +- netwerk/cache2/CacheHashUtils.h | 6 +- netwerk/cache2/CacheIOThread.cpp | 14 +- netwerk/cache2/CacheIOThread.h | 2 +- netwerk/cache2/CacheIndex.cpp | 17 +- netwerk/cache2/CacheIndex.h | 26 ++- netwerk/cache2/CacheIndexContextIterator.cpp | 6 +- netwerk/cache2/CacheIndexIterator.cpp | 6 +- netwerk/cache2/CacheLog.cpp | 6 +- netwerk/cache2/CacheObserver.cpp | 13 +- netwerk/cache2/CacheStorage.h | 2 +- netwerk/cache2/CacheStorageService.cpp | 22 ++- netwerk/cache2/CacheStorageService.h | 4 +- netwerk/cookie/CookieCommons.cpp | 6 +- netwerk/cookie/CookiePersistentStorage.cpp | 4 +- netwerk/cookie/CookieService.cpp | 35 ++-- netwerk/cookie/CookieServiceParent.cpp | 6 +- netwerk/cookie/CookieStorage.cpp | 7 +- netwerk/cookie/CookieStorage.h | 4 +- netwerk/ipc/DocumentLoadListener.h | 29 ++- .../ipc/InputChannelThrottleQueueParent.cpp | 4 +- netwerk/ipc/SocketProcessBridgeChild.h | 4 +- netwerk/ipc/SocketProcessChild.cpp | 6 +- netwerk/ipc/SocketProcessImpl.h | 2 +- netwerk/ipc/SocketProcessParent.h | 2 +- netwerk/mime/nsMIMEHeaderParamImpl.cpp | 43 +++-- netwerk/protocol/about/nsAboutCache.h | 84 +++++---- netwerk/protocol/about/nsAboutCacheEntry.cpp | 6 +- .../protocol/about/nsAboutProtocolHandler.cpp | 12 +- .../protocol/about/nsAboutProtocolHandler.h | 7 - netwerk/protocol/file/nsFileChannel.cpp | 6 +- .../protocol/file/nsFileProtocolHandler.cpp | 3 +- netwerk/protocol/http/ASpdySession.h | 6 +- netwerk/protocol/http/AlternateServices.h | 16 +- .../http/BackgroundChannelRegistrar.h | 8 +- .../protocol/http/ConnectionDiagnostics.cpp | 11 +- netwerk/protocol/http/ConnectionEntry.cpp | 7 +- .../protocol/http/DelayHttpChannelQueue.cpp | 6 +- netwerk/protocol/http/DnsAndConnectSocket.cpp | 17 +- netwerk/protocol/http/Http2Compression.cpp | 9 +- netwerk/protocol/http/Http2Compression.h | 6 +- netwerk/protocol/http/Http2Push.cpp | 3 +- netwerk/protocol/http/Http2Push.h | 6 +- netwerk/protocol/http/Http2Session.cpp | 75 +++++--- netwerk/protocol/http/Http2Session.h | 5 +- netwerk/protocol/http/Http2Stream.cpp | 18 +- netwerk/protocol/http/Http2Stream.h | 8 +- netwerk/protocol/http/Http3Session.cpp | 7 +- netwerk/protocol/http/Http3Session.h | 6 +- .../http/HttpBackgroundChannelChild.h | 2 +- netwerk/protocol/http/HttpBaseChannel.h | 7 +- netwerk/protocol/http/HttpChannelChild.cpp | 6 +- netwerk/protocol/http/HttpChannelChild.h | 5 +- netwerk/protocol/http/HttpChannelParent.cpp | 11 +- netwerk/protocol/http/HttpChannelParent.h | 11 +- .../protocol/http/HttpConnectionMgrChild.cpp | 2 +- .../protocol/http/HttpConnectionMgrChild.h | 2 +- netwerk/protocol/http/HttpConnectionUDP.cpp | 15 +- netwerk/protocol/http/HttpConnectionUDP.h | 14 +- netwerk/protocol/http/HttpLog.h | 2 +- netwerk/protocol/http/HttpTransactionChild.h | 8 +- .../protocol/http/HttpTransactionParent.cpp | 2 +- netwerk/protocol/http/HttpTransactionParent.h | 2 +- .../protocol/http/SpeculativeTransaction.cpp | 2 - .../protocol/http/SpeculativeTransaction.h | 2 +- netwerk/protocol/http/TRRServiceChannel.cpp | 59 +++--- netwerk/protocol/http/TunnelUtils.cpp | 2 +- netwerk/protocol/http/TunnelUtils.h | 4 +- netwerk/protocol/http/nsAHttpConnection.h | 178 +++++++++--------- netwerk/protocol/http/nsCORSListenerProxy.cpp | 4 +- netwerk/protocol/http/nsCORSListenerProxy.h | 2 +- netwerk/protocol/http/nsHttp.h | 2 +- .../http/nsHttpActivityDistributor.cpp | 4 +- .../protocol/http/nsHttpActivityDistributor.h | 4 +- netwerk/protocol/http/nsHttpChannel.h | 2 +- .../protocol/http/nsHttpChunkedDecoder.cpp | 4 +- netwerk/protocol/http/nsHttpChunkedDecoder.h | 2 +- netwerk/protocol/http/nsHttpConnection.cpp | 36 ++-- netwerk/protocol/http/nsHttpConnection.h | 4 +- netwerk/protocol/http/nsHttpConnectionInfo.h | 19 +- netwerk/protocol/http/nsHttpConnectionMgr.cpp | 20 +- netwerk/protocol/http/nsHttpConnectionMgr.h | 10 +- netwerk/protocol/http/nsHttpHandler.cpp | 79 +++++--- netwerk/protocol/http/nsHttpHandler.h | 7 +- netwerk/protocol/http/nsHttpTransaction.h | 5 +- netwerk/protocol/http/nsServerTiming.h | 2 +- .../res/SubstitutingProtocolHandler.h | 2 +- .../viewsource/nsViewSourceChannel.cpp | 8 +- .../websocket/BaseWebSocketChannel.cpp | 10 +- .../protocol/websocket/WebSocketChannel.cpp | 48 +++-- netwerk/protocol/websocket/WebSocketChannel.h | 2 +- .../websocket/WebSocketChannelChild.h | 6 +- .../websocket/WebSocketEventService.cpp | 2 +- .../websocket/WebSocketEventService.h | 2 +- netwerk/protocol/websocket/WebSocketFrame.cpp | 2 +- netwerk/protocol/websocket/WebSocketFrame.h | 4 +- netwerk/socket/nsSOCKSIOLayer.cpp | 12 +- netwerk/socket/nsSOCKSSocketProvider.cpp | 10 +- .../converters/mozTXTToHTMLConv.cpp | 107 ++++++----- .../streamconv/converters/mozTXTToHTMLConv.h | 4 +- .../converters/nsDirIndexParser.cpp | 16 +- .../streamconv/converters/nsDirIndexParser.h | 4 +- .../converters/nsHTTPCompressConv.cpp | 6 +- .../converters/nsHTTPCompressConv.h | 10 +- .../streamconv/converters/nsIndexedToHTML.cpp | 3 +- .../converters/nsMultiMixedConv.cpp | 6 +- .../streamconv/converters/nsMultiMixedConv.h | 4 +- .../converters/nsUnknownDecoder.cpp | 3 +- .../streamconv/converters/nsUnknownDecoder.h | 2 +- .../streamconv/nsStreamConverterService.cpp | 8 +- netwerk/system/linux/nsNetworkLinkService.cpp | 3 +- netwerk/test/gtest/TestCookie.cpp | 7 +- netwerk/test/gtest/TestMozURL.cpp | 4 +- netwerk/test/gtest/TestPACMan.cpp | 6 +- netwerk/test/gtest/TestServerTimingHeader.cpp | 53 +++--- .../test/gtest/TestSocketTransportService.cpp | 2 +- netwerk/test/gtest/TestStandardURL.cpp | 12 +- netwerk/test/gtest/TestUDPSocket.cpp | 7 +- .../AsyncUrlChannelClassifier.cpp | 2 +- .../url-classifier/UrlClassifierCommon.cpp | 8 +- .../UrlClassifierFeatureBase.cpp | 2 +- .../UrlClassifierFeatureFactory.h | 2 +- .../UrlClassifierFeatureFlash.h | 2 +- .../UrlClassifierFeaturePhishingProtection.h | 2 +- .../url-classifier/nsChannelClassifier.cpp | 2 +- netwerk/wifi/nsWifiAccessPoint.h | 4 +- netwerk/wifi/nsWifiMonitor.cpp | 7 +- 201 files changed, 1458 insertions(+), 1249 deletions(-) diff --git a/netwerk/base/Dashboard.cpp b/netwerk/base/Dashboard.cpp index c5c5eb601090..eae01b4a8a2a 100644 --- a/netwerk/base/Dashboard.cpp +++ b/netwerk/base/Dashboard.cpp @@ -1148,10 +1148,10 @@ nsresult Dashboard::TestNewConnection(ConnectionData* aConnectionData) { return rv; } -typedef struct { +using ErrorEntry = struct { nsresult key; const char* error; -} ErrorEntry; +}; #undef ERROR #define ERROR(key, val) \ diff --git a/netwerk/base/EventTokenBucket.cpp b/netwerk/base/EventTokenBucket.cpp index af902801c3f2..3fcd550476a5 100644 --- a/netwerk/base/EventTokenBucket.cpp +++ b/netwerk/base/EventTokenBucket.cpp @@ -90,8 +90,9 @@ EventTokenBucket::EventTokenBucket(uint32_t eventsPerSecond, uint32_t burstSize) nsresult rv; nsCOMPtr sts; nsCOMPtr ioService = do_GetIOService(&rv); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv); + } if (NS_SUCCEEDED(rv)) mTimer = NS_NewTimer(sts); SetRate(eventsPerSecond, burstSize); } @@ -261,8 +262,9 @@ void EventTokenBucket::DispatchEvents() { void EventTokenBucket::UpdateTimer() { MOZ_ASSERT(OnSocketThread(), "not on socket thread"); - if (mTimerArmed || mPaused || mStopped || !mEvents.GetSize() || !mTimer) + if (mTimerArmed || mPaused || mStopped || !mEvents.GetSize() || !mTimer) { return; + } if (mCredit >= mUnitCost) return; @@ -273,10 +275,11 @@ void EventTokenBucket::UpdateTimer() { uint64_t deficit = mUnitCost - mCredit; uint64_t msecWait = (deficit + (kUsecPerMsec - 1)) / kUsecPerMsec; - if (msecWait < 4) // minimum wait + if (msecWait < 4) { // minimum wait msecWait = 4; - else if (msecWait > 60000) // maximum wait + } else if (msecWait > 60000) { // maximum wait msecWait = 60000; + } #ifdef XP_WIN FineGrainTimers(); diff --git a/netwerk/base/EventTokenBucket.h b/netwerk/base/EventTokenBucket.h index cab8937400f8..4206a622f59b 100644 --- a/netwerk/base/EventTokenBucket.h +++ b/netwerk/base/EventTokenBucket.h @@ -103,7 +103,7 @@ class EventTokenBucket : public nsITimerCallback, friend class RunNotifyEvent; friend class SetTimerEvent; - bool TryImmediateDispatch(TokenBucketCancelable* event); + bool TryImmediateDispatch(TokenBucketCancelable* cancelable); void SetRate(uint32_t eventsPerSecond, uint32_t burstSize); void DispatchEvents(); diff --git a/netwerk/base/IOActivityMonitor.h b/netwerk/base/IOActivityMonitor.h index cb2c4ad3798b..998049a9dbc2 100644 --- a/netwerk/base/IOActivityMonitor.h +++ b/netwerk/base/IOActivityMonitor.h @@ -29,7 +29,7 @@ namespace net { #define IO_ACTIVITY_ENABLED_PREF "io.activity.enabled" -typedef nsTHashMap Activities; +using Activities = nsTHashMap; // IOActivityMonitor has several roles: // - maintains an IOActivity per resource and updates it diff --git a/netwerk/base/LoadContextInfo.h b/netwerk/base/LoadContextInfo.h index bf6c4ca0edec..efaf912db45f 100644 --- a/netwerk/base/LoadContextInfo.h +++ b/netwerk/base/LoadContextInfo.h @@ -41,8 +41,7 @@ LoadContextInfo* GetLoadContextInfo(nsIChannel* aChannel); LoadContextInfo* GetLoadContextInfo(nsILoadContext* aLoadContext, bool aIsAnonymous); -LoadContextInfo* GetLoadContextInfo(nsIDOMWindow* aLoadContext, - bool aIsAnonymous); +LoadContextInfo* GetLoadContextInfo(nsIDOMWindow* aWindow, bool aIsAnonymous); LoadContextInfo* GetLoadContextInfo(nsILoadContextInfo* aInfo); diff --git a/netwerk/base/LoadInfo.cpp b/netwerk/base/LoadInfo.cpp index cbe5be65c47f..aef56488327c 100644 --- a/netwerk/base/LoadInfo.cpp +++ b/netwerk/base/LoadInfo.cpp @@ -832,7 +832,7 @@ nsIPrincipal* LoadInfo::FindPrincipalToInherit(nsIChannel* aChannel) { Unused << aChannel->GetOriginalURI(getter_AddRefs(uri)); } - auto prin = BasePrincipal::Cast(mTriggeringPrincipal); + auto* prin = BasePrincipal::Cast(mTriggeringPrincipal); return prin->PrincipalToInherit(uri); } diff --git a/netwerk/base/LoadInfo.h b/netwerk/base/LoadInfo.h index 84ee548be2da..73ad986ccace 100644 --- a/netwerk/base/LoadInfo.h +++ b/netwerk/base/LoadInfo.h @@ -48,7 +48,7 @@ nsresult LoadInfoArgsToLoadInfo( namespace net { -typedef nsTArray> RedirectHistoryArray; +using RedirectHistoryArray = nsTArray>; /** * Class that provides an nsILoadInfo implementation. @@ -280,7 +280,7 @@ class LoadInfo final : public nsILoadInfo { nsWeakPtr mContextForTopLevelLoad; nsSecurityFlags mSecurityFlags; uint32_t mSandboxFlags; - uint32_t mTriggeringSandboxFlags; + uint32_t mTriggeringSandboxFlags = 0; nsContentPolicyType mInternalContentPolicyType; LoadTainting mTainting = LoadTainting::Basic; bool mBlockAllMixedContent = false; diff --git a/netwerk/base/MemoryDownloader.h b/netwerk/base/MemoryDownloader.h index 6337d439ea66..842fb5057073 100644 --- a/netwerk/base/MemoryDownloader.h +++ b/netwerk/base/MemoryDownloader.h @@ -29,7 +29,7 @@ class MemoryDownloader final : public nsIStreamListener { NS_DECL_NSIREQUESTOBSERVER NS_DECL_NSISTREAMLISTENER - typedef mozilla::UniquePtr> Data; + using Data = mozilla::UniquePtr>; class IObserver : public nsISupports { public: diff --git a/netwerk/base/NetworkConnectivityService.cpp b/netwerk/base/NetworkConnectivityService.cpp index fa7b6e495880..af5aa7c53504 100644 --- a/netwerk/base/NetworkConnectivityService.cpp +++ b/netwerk/base/NetworkConnectivityService.cpp @@ -136,13 +136,9 @@ static inline bool NAT64PrefixFromPref(NetAddr* prefix) { nsresult rv = Preferences::GetCString( "network.connectivity-service.nat64-prefix", nat64PrefixPref); - if (NS_FAILED(rv) || nat64PrefixPref.IsEmpty() || - NS_FAILED(prefix->InitFromString(nat64PrefixPref)) || - prefix->raw.family != PR_AF_INET6) { - return false; - } - - return true; + return !(NS_FAILED(rv) || nat64PrefixPref.IsEmpty() || + NS_FAILED(prefix->InitFromString(nat64PrefixPref)) || + prefix->raw.family != PR_AF_INET6); } static inline bool NAT64PrefixCompare(const NetAddr& prefix1, diff --git a/netwerk/base/NetworkDataCountLayer.cpp b/netwerk/base/NetworkDataCountLayer.cpp index 7b6461b5f8dd..bee8bd1ee554 100644 --- a/netwerk/base/NetworkDataCountLayer.cpp +++ b/netwerk/base/NetworkDataCountLayer.cpp @@ -18,7 +18,7 @@ static PRIOMethods* sNetworkDataCountLayerMethodsPtr = nullptr; class NetworkDataCountSecret { public: - NetworkDataCountSecret() {} + NetworkDataCountSecret() = default; uint64_t mSentBytes = 0; uint64_t mReceivedBytes = 0; diff --git a/netwerk/base/NetworkInfoServiceImpl.h b/netwerk/base/NetworkInfoServiceImpl.h index a723b92bae8a..218f31cb0c6c 100644 --- a/netwerk/base/NetworkInfoServiceImpl.h +++ b/netwerk/base/NetworkInfoServiceImpl.h @@ -10,7 +10,7 @@ namespace mozilla { namespace net { -typedef nsTHashMap AddrMapType; +using AddrMapType = nsTHashMap; nsresult DoListAddresses(AddrMapType& aAddrMap); diff --git a/netwerk/base/NetworkInfoServiceLinux.cpp b/netwerk/base/NetworkInfoServiceLinux.cpp index c9488bc6884e..c8a7b024908d 100644 --- a/netwerk/base/NetworkInfoServiceLinux.cpp +++ b/netwerk/base/NetworkInfoServiceLinux.cpp @@ -19,7 +19,7 @@ namespace mozilla::net { -static nsresult ListInterfaceAddresses(int aFd, const char* aIface, +static nsresult ListInterfaceAddresses(int aFd, const char* aInterface, AddrMapType& aAddrMap); nsresult DoListAddresses(AddrMapType& aAddrMap) { @@ -30,7 +30,7 @@ nsresult DoListAddresses(AddrMapType& aAddrMap) { auto autoCloseSocket = MakeScopeExit([&] { close(fd); }); - struct ifconf ifconf; + struct ifconf ifconf {}; /* 16k of space should be enough to list all interfaces. Worst case, if it's * not then we will error out and fail to list addresses. This should only * happen on pathological machines with way too many interfaces. @@ -61,7 +61,7 @@ nsresult DoListAddresses(AddrMapType& aAddrMap) { static nsresult ListInterfaceAddresses(int aFd, const char* aInterface, AddrMapType& aAddrMap) { - struct ifreq ifreq; + struct ifreq ifreq {}; memset(&ifreq, 0, sizeof(struct ifreq)); strncpy(ifreq.ifr_name, aInterface, IFNAMSIZ - 1); if (ioctl(aFd, SIOCGIFADDR, &ifreq) != 0) { diff --git a/netwerk/base/Predictor.cpp b/netwerk/base/Predictor.cpp index 5a787fbbe304..77f45c715ccf 100644 --- a/netwerk/base/Predictor.cpp +++ b/netwerk/base/Predictor.cpp @@ -571,7 +571,7 @@ Predictor::PredictNative(nsIURI* targetURI, nsIURI* sourceURI, return NS_ERROR_INVALID_ARG; } - Predictor::Reason argReason; + Predictor::Reason argReason{}; argReason.mPredict = reason; // First we open the regular cache entry, to ensure we don't gum up the works @@ -727,7 +727,7 @@ bool Predictor::PredictForPageload(nsICacheEntry* entry, nsIURI* targetURI, if (WouldRedirect(entry, loadCount, lastLoad, globalDegradation, getter_AddRefs(redirectURI))) { mPreconnects.AppendElement(redirectURI); - Predictor::Reason reason; + Predictor::Reason reason{}; reason.mPredict = nsINetworkPredictor::PREDICT_LOAD; RefPtr redirectAction = new Predictor::Action( Predictor::Action::IS_FULL_URI, Predictor::Action::DO_PREDICT, reason, @@ -1328,7 +1328,7 @@ Predictor::LearnNative(nsIURI* targetURI, nsIURI* sourceURI, Telemetry::AutoCounter learnAttempts; ++learnAttempts; - Predictor::Reason argReason; + Predictor::Reason argReason{}; argReason.mLearn = reason; // We always open the full uri (general cache) entry first, so we don't gum up diff --git a/netwerk/base/Predictor.h b/netwerk/base/Predictor.h index 5cdbba92945c..78a3008a7fdb 100644 --- a/netwerk/base/Predictor.h +++ b/netwerk/base/Predictor.h @@ -64,7 +64,7 @@ class Predictor final : public nsINetworkPredictor, static void UpdateCacheability(nsIURI* sourceURI, nsIURI* targetURI, uint32_t httpStatus, nsHttpRequestHead& requestHead, - nsHttpResponseHead* reqponseHead, + nsHttpResponseHead* responseHead, nsILoadContextInfo* lci, bool isTracking); private: diff --git a/netwerk/base/ProxyAutoConfig.cpp b/netwerk/base/ProxyAutoConfig.cpp index 8c79b188a99f..10135ee7cae2 100644 --- a/netwerk/base/ProxyAutoConfig.cpp +++ b/netwerk/base/ProxyAutoConfig.cpp @@ -377,8 +377,9 @@ static void PACLogErrorOrWarning(const nsAString& aKind, nsString formattedMessage(u"PAC Execution "_ns); formattedMessage += aKind; formattedMessage += u": "_ns; - if (aReport->message()) + if (aReport->message()) { formattedMessage.Append(NS_ConvertUTF8toUTF16(aReport->message().c_str())); + } formattedMessage += u" ["_ns; formattedMessage.Append(aReport->linebuf(), aReport->linebufLength()); formattedMessage += u"]"_ns; @@ -488,11 +489,7 @@ bool ProxyAutoConfig::ResolveAddress(const nsCString& aHostName, } nsCOMPtr rec = do_QueryInterface(helper->mResponse); - if (!rec || NS_FAILED(rec->GetNextAddr(0, aNetAddr))) { - return false; - } - - return true; + return !(!rec || NS_FAILED(rec->GetNextAddr(0, aNetAddr))); } static bool PACResolveToString(const nsCString& aHostName, @@ -502,8 +499,9 @@ static bool PACResolveToString(const nsCString& aHostName, if (!PACResolve(aHostName, &netAddr, aTimeout)) return false; char dottedDecimal[128]; - if (!netAddr.ToStringBuffer(dottedDecimal, sizeof(dottedDecimal))) + if (!netAddr.ToStringBuffer(dottedDecimal, sizeof(dottedDecimal))) { return false; + } aDottedDecimal.Assign(dottedDecimal); return true; @@ -932,8 +930,9 @@ bool ProxyAutoConfig::SrcAddress(const NetAddr* remoteAddress, char dottedDecimal[128]; if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) != - PR_SUCCESS) + PR_SUCCESS) { return false; + } localAddress.Assign(dottedDecimal); diff --git a/netwerk/base/RequestContextService.cpp b/netwerk/base/RequestContextService.cpp index 2b34831b2e0c..e6ee3281d9de 100644 --- a/netwerk/base/RequestContextService.cpp +++ b/netwerk/base/RequestContextService.cpp @@ -61,7 +61,7 @@ class RequestContext final : public nsIRequestContext, public nsITimerCallback { Atomic mBlockingTransactionCount; UniquePtr mSpdyCache; - typedef nsCOMPtr PendingTailRequest; + using PendingTailRequest = nsCOMPtr; // Number of known opened non-tailed requets uint32_t mNonTailRequests; // Queue of requests that have been tailed, when conditions are met diff --git a/netwerk/base/SSLTokensCache.h b/netwerk/base/SSLTokensCache.h index 77d715c8dd6e..47e662c19fc8 100644 --- a/netwerk/base/SSLTokensCache.h +++ b/netwerk/base/SSLTokensCache.h @@ -73,7 +73,7 @@ class SSLTokensCache : public nsIMemoryReporter { void Reset(); nsCString mKey; - PRUint32 mExpirationTime; + PRUint32 mExpirationTime = 0; nsTArray mToken; SessionCacheInfo mSessionCacheInfo; }; diff --git a/netwerk/base/SimpleBuffer.h b/netwerk/base/SimpleBuffer.h index c518d1b3418f..6b142988b98c 100644 --- a/netwerk/base/SimpleBuffer.h +++ b/netwerk/base/SimpleBuffer.h @@ -26,7 +26,7 @@ class SimpleBufferPage : public LinkedListElement { private: friend class SimpleBuffer; - char mBuffer[kSimpleBufferPageSize]; + char mBuffer[kSimpleBufferPageSize]{}; size_t mReadOffset; size_t mWriteOffset; }; @@ -36,7 +36,7 @@ class SimpleBuffer { SimpleBuffer(); ~SimpleBuffer() = default; - nsresult Write(char* stc, size_t len); // return OK or OUT_OF_MEMORY + nsresult Write(char* src, size_t len); // return OK or OUT_OF_MEMORY size_t Read(char* dest, size_t maxLen); // return bytes read size_t Available(); void Clear(); diff --git a/netwerk/base/SimpleChannel.h b/netwerk/base/SimpleChannel.h index 6e45c5bdb40c..891ed56dc043 100644 --- a/netwerk/base/SimpleChannel.h +++ b/netwerk/base/SimpleChannel.h @@ -122,7 +122,8 @@ inline already_AddRefed NS_NewSimpleChannel( using namespace mozilla; auto callbacks = MakeUnique>( - std::move(aStartAsyncRead), std::move(aOpenContentStream), context); + std::forward(aStartAsyncRead), std::forward(aOpenContentStream), + context); return net::NS_NewSimpleChannelInternal(aURI, aLoadInfo, std::move(callbacks)); @@ -140,7 +141,7 @@ inline already_AddRefed NS_NewSimpleChannel(nsIURI* aURI, }; return NS_NewSimpleChannel(aURI, aLoadInfo, context, - std::move(aStartAsyncRead), + std::forward(aStartAsyncRead), std::move(openContentStream)); } diff --git a/netwerk/base/ThrottleQueue.cpp b/netwerk/base/ThrottleQueue.cpp index 535ed8d16942..0015a88f77e9 100644 --- a/netwerk/base/ThrottleQueue.cpp +++ b/netwerk/base/ThrottleQueue.cpp @@ -241,8 +241,9 @@ ThrottleQueue::ThrottleQueue() nsresult rv; nsCOMPtr sts; nsCOMPtr ioService = do_GetIOService(&rv); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv); + } if (NS_SUCCEEDED(rv)) mTimer = NS_NewTimer(sts); } @@ -350,7 +351,8 @@ ThrottleQueue::GetName(nsACString& aName) { void ThrottleQueue::QueueStream(ThrottleInputStream* aStream) { MOZ_ASSERT(OnSocketThread(), "not on socket thread"); - if (mAsyncEvents.IndexOf(aStream) == mAsyncEvents.NoIndex) { + if (mAsyncEvents.IndexOf(aStream) == + nsTArray>::NoIndex) { mAsyncEvents.AppendElement(aStream); if (!mTimerArmed) { diff --git a/netwerk/base/ThrottleQueue.h b/netwerk/base/ThrottleQueue.h index 49885e888739..8dcf638a77f7 100644 --- a/netwerk/base/ThrottleQueue.h +++ b/netwerk/base/ThrottleQueue.h @@ -46,7 +46,7 @@ class ThrottleQueue : public nsIInputChannelThrottleQueue, struct ThrottleEntry { TimeStamp mTime; - uint32_t mBytesRead; + uint32_t mBytesRead = 0; }; nsTArray mReadEvents; diff --git a/netwerk/base/nsBaseChannel.cpp b/netwerk/base/nsBaseChannel.cpp index 43dac0a7c23a..1f2b9ee5ab21 100644 --- a/netwerk/base/nsBaseChannel.cpp +++ b/netwerk/base/nsBaseChannel.cpp @@ -646,8 +646,9 @@ nsBaseChannel::Open(nsIInputStream** aStream) { rv = Redirect(chan, nsIChannelEventSink::REDIRECT_INTERNAL, false); if (NS_FAILED(rv)) return rv; rv = chan->Open(aStream); - } else if (rv == NS_ERROR_NOT_IMPLEMENTED) + } else if (rv == NS_ERROR_NOT_IMPLEMENTED) { return NS_ImplementChannelOpen(this, aStream); + } if (NS_SUCCEEDED(rv)) { mWasOpened = true; @@ -823,14 +824,16 @@ nsBaseChannel::OnStartRequest(nsIRequest* request) { } // Now, the general type sniffers. Skip this if we have none. - if (mLoadFlags & LOAD_CALL_CONTENT_SNIFFERS) + if (mLoadFlags & LOAD_CALL_CONTENT_SNIFFERS) { mPump->PeekStream(CallTypeSniffers, static_cast(this)); + } } SUSPEND_PUMP_FOR_SCOPE(); - if (mListener) // null in case of redirect + if (mListener) { // null in case of redirect return mListener->OnStartRequest(this); + } return NS_OK; } @@ -845,8 +848,9 @@ nsBaseChannel::OnStopRequest(nsIRequest* request, nsresult status) { mRequest = nullptr; mPumpingData = false; - if (mListener) // null in case of redirect + if (mListener) { // null in case of redirect mListener->OnStopRequest(this, mStatus); + } ChannelDone(); // No need to suspend pump in this scope since we will not be receiving diff --git a/netwerk/base/nsBaseChannel.h b/netwerk/base/nsBaseChannel.h index c6e12d9b33a8..2c868917e2a0 100644 --- a/netwerk/base/nsBaseChannel.h +++ b/netwerk/base/nsBaseChannel.h @@ -212,7 +212,7 @@ class nsBaseChannel // This function optionally returns a reference to the new converter. nsresult PushStreamConverter(const char* fromType, const char* toType, bool invalidatesContentLength = true, - nsIStreamListener** converter = nullptr); + nsIStreamListener** result = nullptr); protected: void DisallowThreadRetargeting() { mAllowThreadRetargeting = false; } diff --git a/netwerk/base/nsDirectoryIndexStream.h b/netwerk/base/nsDirectoryIndexStream.h index 8e4721300c90..e0ed2a8deaf1 100644 --- a/netwerk/base/nsDirectoryIndexStream.h +++ b/netwerk/base/nsDirectoryIndexStream.h @@ -34,7 +34,7 @@ class nsDirectoryIndexStream final : public nsIInputStream { /** * aDir will only be used on the calling thread. */ - static nsresult Create(nsIFile* aDir, nsIInputStream** aStreamResult); + static nsresult Create(nsIFile* aDir, nsIInputStream** aResult); // nsISupportsInterface NS_DECL_THREADSAFE_ISUPPORTS diff --git a/netwerk/base/nsFileStreams.cpp b/netwerk/base/nsFileStreams.cpp index 41526c76423a..9940857c744e 100644 --- a/netwerk/base/nsFileStreams.cpp +++ b/netwerk/base/nsFileStreams.cpp @@ -30,7 +30,7 @@ #include "nsNetCID.h" #include "nsXULAppAPI.h" -typedef mozilla::ipc::FileDescriptor::PlatformHandleType FileHandleType; +using FileHandleType = mozilla::ipc::FileDescriptor::PlatformHandleType; using namespace mozilla::ipc; using namespace mozilla::net; @@ -854,8 +854,9 @@ nsAtomicFileOutputStream::Finish() { // in writing to the target file), there is nothing more to do. #ifdef DEBUG bool equal; - if (NS_FAILED(mTargetFile->Equals(mTempFile, &equal)) || !equal) + if (NS_FAILED(mTargetFile->Equals(mTempFile, &equal)) || !equal) { NS_WARNING("mTempFile not equal to mTargetFile"); + } #endif } else { nsAutoString targetFilename; @@ -881,13 +882,15 @@ nsAtomicFileOutputStream::Write(const char* buf, uint32_t count, uint32_t* result) { nsresult rv = nsFileOutputStream::Write(buf, count, result); if (NS_SUCCEEDED(mWriteResult)) { - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { mWriteResult = rv; - else if (count != *result) + } else if (count != *result) { mWriteResult = NS_ERROR_LOSS_OF_SIGNIFICANT_DATA; + } - if (NS_FAILED(mWriteResult) && count > 0) + if (NS_FAILED(mWriteResult) && count > 0) { NS_WARNING("writing to output stream failed! data may be lost"); + } } return rv; } diff --git a/netwerk/base/nsFileStreams.h b/netwerk/base/nsFileStreams.h index c694d1b366c0..d546e66d5ae1 100644 --- a/netwerk/base/nsFileStreams.h +++ b/netwerk/base/nsFileStreams.h @@ -41,13 +41,13 @@ class nsFileStreamBase : public nsISeekableStream, public nsIFileMetadata { virtual ~nsFileStreamBase(); nsresult Close(); - nsresult Available(uint64_t* _retval); - nsresult Read(char* aBuf, uint32_t aCount, uint32_t* _retval); + nsresult Available(uint64_t* aResult); + nsresult Read(char* aBuf, uint32_t aCount, uint32_t* aResult); nsresult ReadSegments(nsWriteSegmentFun aWriter, void* aClosure, uint32_t aCount, uint32_t* _retval); - nsresult IsNonBlocking(bool* _retval); + nsresult IsNonBlocking(bool* aNonBlocking); nsresult Flush(); - nsresult Write(const char* aBuf, uint32_t aCount, uint32_t* _retval); + nsresult Write(const char* aBuf, uint32_t aCount, uint32_t* result); nsresult WriteFrom(nsIInputStream* aFromStream, uint32_t aCount, uint32_t* _retval); nsresult WriteSegments(nsReadSegmentFun aReader, void* aClosure, @@ -76,8 +76,8 @@ class nsFileStreamBase : public nsISeekableStream, public nsIFileMetadata { struct OpenParams { nsCOMPtr localFile; - int32_t ioFlags; - int32_t perm; + int32_t ioFlags = 0; + int32_t perm = 0; }; /** diff --git a/netwerk/base/nsIOService.cpp b/netwerk/base/nsIOService.cpp index fc85a1c887f7..c437717aabad 100644 --- a/netwerk/base/nsIOService.cpp +++ b/netwerk/base/nsIOService.cpp @@ -275,8 +275,9 @@ nsresult nsIOService::Init() { InitializeCaptivePortalService(); // setup our bad port list stuff - for (int i = 0; gBadPortList[i]; i++) + for (int i = 0; gBadPortList[i]; i++) { mRestrictedPortList.AppendElement(gBadPortList[i]); + } // Further modifications to the port list come from prefs Preferences::RegisterPrefixCallbacks(nsIOService::PrefsChanged, @@ -1230,8 +1231,9 @@ nsIOService::SetOffline(bool offline) { LOG(("nsIOService::SetOffline offline=%d\n", offline)); // When someone wants to go online (!offline) after we got XPCOM shutdown // throw ERROR_NOT_AVAILABLE to prevent return to online state. - if ((mShutdown || mOfflineForProfileChange) && !offline) + if ((mShutdown || mOfflineForProfileChange) && !offline) { return NS_ERROR_NOT_AVAILABLE; + } // SetOffline() may re-enter while it's shutting down services. // If that happens, save the most recent value and it will be @@ -1267,18 +1269,20 @@ nsIOService::SetOffline(bool offline) { mOffline = true; // indicate we're trying to shutdown // don't care if notifications fail - if (observerService) + if (observerService) { observerService->NotifyObservers(subject, NS_IOSERVICE_GOING_OFFLINE_TOPIC, u"" NS_IOSERVICE_OFFLINE); + } if (mSocketTransportService) mSocketTransportService->SetOffline(true); mLastOfflineStateChange = PR_IntervalNow(); - if (observerService) + if (observerService) { observerService->NotifyObservers(subject, NS_IOSERVICE_OFFLINE_STATUS_TOPIC, u"" NS_IOSERVICE_OFFLINE); + } } else if (!offline && mOffline) { // go online InitializeSocketTransportService(); @@ -1440,12 +1444,14 @@ void nsIOService::PrefsChanged(const char* pref, void* self) { void nsIOService::PrefsChanged(const char* pref) { // Look for extra ports to block - if (!pref || strcmp(pref, PORT_PREF("banned")) == 0) + if (!pref || strcmp(pref, PORT_PREF("banned")) == 0) { ParsePortList(PORT_PREF("banned"), false); + } // ...as well as previous blocks to remove. - if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0) + if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0) { ParsePortList(PORT_PREF("banned.override"), true); + } if (!pref || strcmp(pref, MANAGE_OFFLINE_STATUS_PREF) == 0) { bool manage; @@ -1461,20 +1467,23 @@ void nsIOService::PrefsChanged(const char* pref) { if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_COUNT_PREF) == 0) { int32_t count; if (NS_SUCCEEDED( - Preferences::GetInt(NECKO_BUFFER_CACHE_COUNT_PREF, &count))) + Preferences::GetInt(NECKO_BUFFER_CACHE_COUNT_PREF, &count))) { /* check for bogus values and default if we find such a value */ if (count > 0) gDefaultSegmentCount = count; + } } if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_SIZE_PREF) == 0) { int32_t size; - if (NS_SUCCEEDED(Preferences::GetInt(NECKO_BUFFER_CACHE_SIZE_PREF, &size))) + if (NS_SUCCEEDED( + Preferences::GetInt(NECKO_BUFFER_CACHE_SIZE_PREF, &size))) { /* check for bogus values and default if we find such a value * the upper limit here is arbitrary. having a 1mb segment size * is pretty crazy. if you remove this, consider adding some * integer rollover test. */ if (size > 0 && size < 1024 * 1024) gDefaultSegmentSize = size; + } NS_WARNING_ASSERTION(!(size & (size - 1)), "network segment size is not a power of 2!"); } @@ -1515,21 +1524,24 @@ void nsIOService::ParsePortList(const char* pref, bool remove) { if ((portBegin < 65536) && (portEnd < 65536)) { int32_t curPort; if (remove) { - for (curPort = portBegin; curPort <= portEnd; curPort++) + for (curPort = portBegin; curPort <= portEnd; curPort++) { restrictedPortList.RemoveElement(curPort); + } } else { - for (curPort = portBegin; curPort <= portEnd; curPort++) + for (curPort = portBegin; curPort <= portEnd; curPort++) { restrictedPortList.AppendElement(curPort); + } } } } else { nsresult aErrorCode; int32_t port = portListArray[index].ToInteger(&aErrorCode); if (NS_SUCCEEDED(aErrorCode) && port < 65536) { - if (remove) + if (remove) { restrictedPortList.RemoveElement(port); - else + } else { restrictedPortList.AppendElement(port); + } } } } @@ -1819,8 +1831,9 @@ nsIOService::EscapeString(const nsACString& aString, uint32_t aEscapeType, nsAutoCString stringCopy(aString); nsCString result; - if (!NS_Escape(stringCopy, result, (nsEscapeMask)aEscapeType)) + if (!NS_Escape(stringCopy, result, (nsEscapeMask)aEscapeType)) { return NS_ERROR_OUT_OF_MEMORY; + } aResult.Assign(result); diff --git a/netwerk/base/nsIOService.h b/netwerk/base/nsIOService.h index f6182a30a985..ab79dea027c3 100644 --- a/netwerk/base/nsIOService.h +++ b/netwerk/base/nsIOService.h @@ -26,7 +26,7 @@ #include "nsTHashSet.h" #include "nsWeakReference.h" -#define NS_N(x) (sizeof(x) / sizeof(*x)) +#define NS_N(x) (sizeof(x) / sizeof(*(x))) // We don't want to expose this observer topic. // Intended internal use only for remoting offline/inline events. @@ -158,7 +158,8 @@ class nsIOService final : public nsIIOService, nsresult GetCachedProtocolHandler(const char* scheme, nsIProtocolHandler** hdlrResult, uint32_t start = 0, uint32_t end = 0); - nsresult CacheProtocolHandler(const char* scheme, nsIProtocolHandler* hdlr); + nsresult CacheProtocolHandler(const char* scheme, + nsIProtocolHandler* handler); nsresult InitializeCaptivePortalService(); nsresult RecheckCaptivePortalIfLocalRedirect(nsIChannel* newChan); diff --git a/netwerk/base/nsIncrementalDownload.cpp b/netwerk/base/nsIncrementalDownload.cpp index c9fb767f943f..68c1d472dfe2 100644 --- a/netwerk/base/nsIncrementalDownload.cpp +++ b/netwerk/base/nsIncrementalDownload.cpp @@ -53,8 +53,9 @@ static nsresult WriteToFile(nsIFile* lf, const char* data, uint32_t len, rv = lf->OpenNSPRFileDesc(flags, mode, &fd); if (NS_FAILED(rv)) return rv; - if (len) + if (len) { rv = PR_Write(fd, data, len) == int32_t(len) ? NS_OK : NS_ERROR_FAILURE; + } PR_Close(fd); return rv; @@ -173,8 +174,9 @@ nsresult nsIncrementalDownload::FlushChunk() { void nsIncrementalDownload::UpdateProgress() { mLastProgressUpdate = PR_Now(); - if (mProgressSink) + if (mProgressSink) { mProgressSink->OnProgress(this, mCurrentSize + mChunkLen, mTotalSize); + } } nsresult nsIncrementalDownload::CallOnStartRequest() { @@ -527,9 +529,10 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { bool confirmedOK = false; rv = http->GetResponseHeader("Content-Range"_ns, buf); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return rv; // it isn't a useful 206 without a CONTENT-RANGE of some - // sort + } + // sort // Content-Range: bytes 0-299999/25604694 int32_t p = buf.Find("bytes "); @@ -583,8 +586,9 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { rv = http->GetURI(getter_AddRefs(mFinalURI)); if (NS_FAILED(rv)) return rv; Unused << http->GetResponseHeader("Etag"_ns, mPartialValidator); - if (StringBeginsWith(mPartialValidator, "W/"_ns)) + if (StringBeginsWith(mPartialValidator, "W/"_ns)) { mPartialValidator.Truncate(); // don't use weak validators + } if (mPartialValidator.IsEmpty()) { rv = http->GetResponseHeader("Last-Modified"_ns, mPartialValidator); if (NS_FAILED(rv)) { @@ -605,8 +609,10 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { NS_WARNING("server returned invalid Content-Range header!"); return NS_ERROR_UNEXPECTED; } - if (PR_sscanf(buf.get() + slash + 1, "%lld", (int64_t*)&mTotalSize) != 1) + if (PR_sscanf(buf.get() + slash + 1, "%lld", (int64_t*)&mTotalSize) != + 1) { return NS_ERROR_UNEXPECTED; + } } else { rv = http->GetContentLength(&mTotalSize); if (NS_FAILED(rv)) return rv; @@ -694,8 +700,9 @@ nsIncrementalDownload::OnDataAvailable(nsIRequest* request, } } - if (PR_Now() > mLastProgressUpdate + UPDATE_PROGRESS_INTERVAL) + if (PR_Now() > mLastProgressUpdate + UPDATE_PROGRESS_INTERVAL) { UpdateProgress(); + } return NS_OK; } diff --git a/netwerk/base/nsInputStreamPump.cpp b/netwerk/base/nsInputStreamPump.cpp index 3165cf07fa28..a662300eb319 100644 --- a/netwerk/base/nsInputStreamPump.cpp +++ b/netwerk/base/nsInputStreamPump.cpp @@ -556,11 +556,12 @@ uint32_t nsInputStreamPump::OnStateTransfer() { // NOTE: if Tell fails, which can happen if the stream is // now closed, then we assume that everything was read. int64_t offsetAfter; - if (NS_FAILED(tellable->Tell(&offsetAfter))) + if (NS_FAILED(tellable->Tell(&offsetAfter))) { offsetAfter = offsetBefore + odaAvail; - if (offsetAfter > offsetBefore) + } + if (offsetAfter > offsetBefore) { mStreamOffset += (offsetAfter - offsetBefore); - else if (mSuspendCount == 0) { + } else if (mSuspendCount == 0) { // // possible infinite loop if we continue pumping data! // @@ -571,8 +572,9 @@ uint32_t nsInputStreamPump::OnStateTransfer() { NS_ERROR("OnDataAvailable implementation consumed no data"); mStatus = NS_ERROR_UNEXPECTED; } - } else + } else { mStreamOffset += odaAvail; // assume ODA behaved well + } } } @@ -580,9 +582,9 @@ uint32_t nsInputStreamPump::OnStateTransfer() { // abort; however, we must not stop on mStatus if already canceled. if (NS_SUCCEEDED(mStatus)) { - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { mStatus = rv; - else if (avail) { + } else if (avail) { // if stream is now closed, advance to STATE_STOP right away. // Available may return 0 bytes available at the moment; that // would not mean that we are done. @@ -633,10 +635,11 @@ uint32_t nsInputStreamPump::OnStateStop() { return STATE_IDLE; } - if (NS_FAILED(mStatus)) + if (NS_FAILED(mStatus)) { mAsyncStream->CloseWithStatus(mStatus); - else if (mCloseWhenDone) + } else if (mCloseWhenDone) { mAsyncStream->Close(); + } mAsyncStream = nullptr; mTargetThread = nullptr; diff --git a/netwerk/base/nsInputStreamPump.h b/netwerk/base/nsInputStreamPump.h index a9f852508875..4dcbdcba37a8 100644 --- a/netwerk/base/nsInputStreamPump.h +++ b/netwerk/base/nsInputStreamPump.h @@ -30,8 +30,8 @@ class nsInputStreamPump final : public nsIInputStreamPump, ~nsInputStreamPump() = default; public: - typedef mozilla::RecursiveMutexAutoLock RecursiveMutexAutoLock; - typedef mozilla::RecursiveMutexAutoUnlock RecursiveMutexAutoUnlock; + using RecursiveMutexAutoLock = mozilla::RecursiveMutexAutoLock; + using RecursiveMutexAutoUnlock = mozilla::RecursiveMutexAutoUnlock; NS_DECL_THREADSAFE_ISUPPORTS NS_DECL_NSIREQUEST NS_DECL_NSIINPUTSTREAMPUMP @@ -46,8 +46,7 @@ class nsInputStreamPump final : public nsIInputStreamPump, bool closeWhenDone = false, nsIEventTarget* mainThreadTarget = nullptr); - typedef void (*PeekSegmentFun)(void* closure, const uint8_t* buf, - uint32_t bufLen); + using PeekSegmentFun = void (*)(void*, const uint8_t*, uint32_t); /** * Peek into the first chunk of data that's in the stream. Note that this * method will not call the callback when there is no data in the stream. diff --git a/netwerk/base/nsLoadGroup.cpp b/netwerk/base/nsLoadGroup.cpp index ae678fe081ef..a51de7095f1b 100644 --- a/netwerk/base/nsLoadGroup.cpp +++ b/netwerk/base/nsLoadGroup.cpp @@ -146,14 +146,15 @@ nsLoadGroup::GetName(nsACString& result) { NS_IMETHODIMP nsLoadGroup::IsPending(bool* aResult) { - *aResult = (mForegroundCount > 0) ? true : false; + *aResult = mForegroundCount > 0; return NS_OK; } NS_IMETHODIMP nsLoadGroup::GetStatus(nsresult* status) { - if (NS_SUCCEEDED(mStatus) && mDefaultLoadRequest) + if (NS_SUCCEEDED(mStatus) && mDefaultLoadRequest) { return mDefaultLoadRequest->GetStatus(status); + } *status = mStatus; return NS_OK; @@ -162,7 +163,7 @@ nsLoadGroup::GetStatus(nsresult* status) { static bool AppendRequestsToArray(PLDHashTable* aTable, nsTArray* aArray) { for (auto iter = aTable->Iter(); !iter.Done(); iter.Next()) { - auto e = static_cast(iter.Get()); + auto* e = static_cast(iter.Get()); nsIRequest* request = e->mKey; NS_ASSERTION(request, "What? Null key in PLDHashTable entry?"); @@ -456,7 +457,7 @@ nsLoadGroup::AddRequest(nsIRequest* request, nsISupports* ctxt) { // Add the request to the list of active requests... // - auto entry = static_cast(mRequests.Add(request, fallible)); + auto* entry = static_cast(mRequests.Add(request, fallible)); if (!entry) { return NS_ERROR_OUT_OF_MEMORY; } @@ -548,7 +549,7 @@ nsresult nsLoadGroup::RemoveRequestFromHashtable(nsIRequest* request, // the request was *not* in the group so do not update the foreground // count or it will get messed up... // - auto entry = static_cast(mRequests.Search(request)); + auto* entry = static_cast(mRequests.Search(request)); if (!entry) { LOG(("LOADGROUP [%p]: Unable to remove request %p. Not in group!\n", this, @@ -645,7 +646,7 @@ nsLoadGroup::GetRequests(nsISimpleEnumerator** aRequests) { requests.SetCapacity(mRequests.EntryCount()); for (auto iter = mRequests.Iter(); !iter.Done(); iter.Next()) { - auto e = static_cast(iter.Get()); + auto* e = static_cast(iter.Get()); requests.AppendObject(e->mKey); } @@ -759,7 +760,7 @@ nsLoadGroup::AdjustPriority(int32_t aDelta) { if (aDelta != 0) { mPriority += aDelta; for (auto iter = mRequests.Iter(); !iter.Done(); iter.Next()) { - auto e = static_cast(iter.Get()); + auto* e = static_cast(iter.Get()); RescheduleRequest(e->mKey, aDelta); } } diff --git a/netwerk/base/nsMIMEInputStream.cpp b/netwerk/base/nsMIMEInputStream.cpp index d5f02e2759bb..7405d0943ca4 100644 --- a/netwerk/base/nsMIMEInputStream.cpp +++ b/netwerk/base/nsMIMEInputStream.cpp @@ -68,8 +68,8 @@ class nsMIMEInputStream : public nsIMIMEInputStream, struct MOZ_STACK_CLASS ReadSegmentsState { nsCOMPtr mThisStream; - nsWriteSegmentFun mWriter; - void* mClosure; + nsWriteSegmentFun mWriter{nullptr}; + void* mClosure{nullptr}; }; static nsresult ReadSegCb(nsIInputStream* aIn, void* aClosure, const char* aFromRawSegment, uint32_t aToOffset, diff --git a/netwerk/base/nsMediaFragmentURIParser.cpp b/netwerk/base/nsMediaFragmentURIParser.cpp index 9252c2426345..bfa82530c62b 100644 --- a/netwerk/base/nsMediaFragmentURIParser.cpp +++ b/netwerk/base/nsMediaFragmentURIParser.cpp @@ -339,7 +339,8 @@ void nsMediaFragmentURIParser::Parse(nsACString& aRef) { if (gotTemporal && gotSpatial) { // We've got one of each possible type. No need to look at the rest. break; - } else if (!gotTemporal && fragments[i].first.EqualsLiteral("t")) { + } + if (!gotTemporal && fragments[i].first.EqualsLiteral("t")) { nsAutoString value = NS_ConvertUTF8toUTF16(fragments[i].second); gotTemporal = ParseNPT(nsDependentSubstring(value, 0)); } else if (!gotSpatial && fragments[i].first.EqualsLiteral("xywh")) { diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp index 42a5f6cf4743..2b20d4a1583b 100644 --- a/netwerk/base/nsNetUtil.cpp +++ b/netwerk/base/nsNetUtil.cpp @@ -602,10 +602,11 @@ nsresult NS_MakeAbsoluteURI(nsACString& result, const nsACString& spec, NS_WARNING("It doesn't make sense to not supply a base URI"); result = spec; rv = NS_OK; - } else if (spec.IsEmpty()) + } else if (spec.IsEmpty()) { rv = baseURI->GetSpec(result); - else + } else { rv = baseURI->Resolve(spec, result); + } return rv; } @@ -629,10 +630,11 @@ nsresult NS_MakeAbsoluteURI(nsAString& result, const nsAString& spec, rv = NS_OK; } else { nsAutoCString resultBuf; - if (spec.IsEmpty()) + if (spec.IsEmpty()) { rv = baseURI->GetSpec(resultBuf); - else + } else { rv = baseURI->Resolve(NS_ConvertUTF16toUTF8(spec), resultBuf); + } if (NS_SUCCEEDED(rv)) CopyUTF8toUTF16(resultBuf, result); } return rv; @@ -674,9 +676,7 @@ bool NS_StringToACE(const nsACString& idn, nsACString& result) { nsCOMPtr idnSrv = do_GetService(NS_IDNSERVICE_CONTRACTID); if (!idnSrv) return false; nsresult rv = idnSrv->ConvertUTF8toACE(idn, result); - if (NS_FAILED(rv)) return false; - - return true; + return NS_SUCCEEDED(rv); } int32_t NS_GetRealPort(nsIURI* aURI) { @@ -1096,8 +1096,9 @@ nsresult NS_CheckPortSafety(int32_t port, const char* scheme, nsresult NS_CheckPortSafety(nsIURI* uri) { int32_t port; nsresult rv = uri->GetPort(&port); - if (NS_FAILED(rv) || port == -1) // port undefined or default-valued + if (NS_FAILED(rv) || port == -1) { // port undefined or default-valued return NS_OK; + } nsAutoCString scheme; uri->GetScheme(scheme); return NS_CheckPortSafety(port, scheme.get()); @@ -1108,9 +1109,10 @@ nsresult NS_NewProxyInfo(const nsACString& type, const nsACString& host, nsresult rv; nsCOMPtr pps = do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID, &rv); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { rv = pps->NewProxyInfo(type, host, port, ""_ns, ""_ns, flags, UINT32_MAX, nullptr, result); + } return rv; } @@ -2261,8 +2263,9 @@ uint32_t NS_SecurityHashURI(nsIURI* aURI) { nsAutoCString scheme; uint32_t schemeHash = 0; - if (NS_SUCCEEDED(baseURI->GetScheme(scheme))) + if (NS_SUCCEEDED(baseURI->GetScheme(scheme))) { schemeHash = mozilla::HashString(scheme); + } // TODO figure out how to hash file:// URIs if (scheme.EqualsLiteral("file")) return schemeHash; // sad face @@ -2285,8 +2288,9 @@ uint32_t NS_SecurityHashURI(nsIURI* aURI) { nsAutoCString host; uint32_t hostHash = 0; - if (NS_SUCCEEDED(baseURI->GetAsciiHost(host))) + if (NS_SUCCEEDED(baseURI->GetAsciiHost(host))) { hostHash = mozilla::HashString(host); + } return mozilla::AddToHash(schemeHash, hostHash, NS_GetRealPort(baseURI)); } @@ -2628,8 +2632,9 @@ uint32_t NS_GetContentDispositionFromToken(const nsAString& aDispToken) { // Broken sites just send // Content-Disposition: filename="file" // without a disposition token... screen those out. - StringHead(aDispToken, 8).LowerCaseEqualsLiteral("filename")) + StringHead(aDispToken, 8).LowerCaseEqualsLiteral("filename")) { return nsIChannel::DISPOSITION_INLINE; + } return nsIChannel::DISPOSITION_ATTACHMENT; } @@ -2647,8 +2652,9 @@ uint32_t NS_GetContentDispositionFromHeader(const nsACString& aHeader, if (NS_FAILED(rv)) { // special case (see bug 272541): empty disposition type handled as "inline" - if (rv == NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY) + if (rv == NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY) { return nsIChannel::DISPOSITION_INLINE; + } return nsIChannel::DISPOSITION_ATTACHMENT; } @@ -2719,15 +2725,17 @@ nsresult NS_GenerateHostPort(const nsCString& host, int32_t port, hostLine.Assign('['); // scope id is not needed for Host header. int scopeIdPos = host.FindChar('%'); - if (scopeIdPos == -1) + if (scopeIdPos == -1) { hostLine.Append(host); - else if (scopeIdPos > 0) + } else if (scopeIdPos > 0) { hostLine.Append(Substring(host, 0, scopeIdPos)); - else + } else { return NS_ERROR_MALFORMED_URI; + } hostLine.Append(']'); - } else + } else { hostLine.Assign(host); + } if (port != -1) { hostLine.Append(':'); hostLine.AppendInt(port); @@ -2738,7 +2746,7 @@ nsresult NS_GenerateHostPort(const nsCString& host, int32_t port, void NS_SniffContent(const char* aSnifferType, nsIRequest* aRequest, const uint8_t* aData, uint32_t aLength, nsACString& aSniffedType) { - typedef nsCategoryCache ContentSnifferCache; + using ContentSnifferCache = nsCategoryCache; extern ContentSnifferCache* gNetSniffers; extern ContentSnifferCache* gDataSniffers; extern ContentSnifferCache* gORBSniffers; @@ -3180,12 +3188,8 @@ bool NS_ShouldClassifyChannel(nsIChannel* aChannel) { ExtContentPolicyType type = loadInfo->GetExternalContentPolicyType(); // Skip classifying channel triggered by system unless it is a top-level // load. - if (loadInfo->TriggeringPrincipal()->IsSystemPrincipal() && - ExtContentPolicy::TYPE_DOCUMENT != type) { - return false; - } - - return true; + return !(loadInfo->TriggeringPrincipal()->IsSystemPrincipal() && + ExtContentPolicy::TYPE_DOCUMENT != type); } namespace mozilla { diff --git a/netwerk/base/nsNetUtil.h b/netwerk/base/nsNetUtil.h index 4f996e0a25af..9a3081749060 100644 --- a/netwerk/base/nsNetUtil.h +++ b/netwerk/base/nsNetUtil.h @@ -81,7 +81,7 @@ already_AddRefed do_GetNetUtil(nsresult* error = nullptr); // private little helper function... don't call this directly! nsresult net_EnsureIOService(nsIIOService** ios, nsCOMPtr& grip); -nsresult NS_NewURI(nsIURI** result, const nsACString& spec, +nsresult NS_NewURI(nsIURI** aURI, const nsACString& spec, const char* charset = nullptr, nsIURI* baseURI = nullptr); nsresult NS_NewURI(nsIURI** result, const nsACString& spec, diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 509c9a3508ed..b2a9ab5aef3e 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -327,10 +327,11 @@ void PendingPACQuery::Complete(nsresult status, const nsACString& pacString) { if (!mCallback) return; RefPtr runnable = new ExecuteCallback(mCallback, status); runnable->SetPACString(pacString); - if (mOnMainThreadOnly) + if (mOnMainThreadOnly) { mPACMan->Dispatch(runnable.forget()); - else + } else { runnable->Run(); + } } void PendingPACQuery::UseAlternatePACFile(const nsACString& pacURL) { @@ -338,10 +339,11 @@ void PendingPACQuery::UseAlternatePACFile(const nsACString& pacURL) { RefPtr runnable = new ExecuteCallback(mCallback, NS_OK); runnable->SetPACURL(pacURL); - if (mOnMainThreadOnly) + if (mOnMainThreadOnly) { mPACMan->Dispatch(runnable.forget()); - else + } else { runnable->Run(); + } } NS_IMETHODIMP @@ -762,8 +764,9 @@ void nsPACMan::CancelPendingQ(nsresult status, bool aShutdown) { void nsPACMan::ProcessPendingQ() { MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); - while (ProcessPending()) + while (ProcessPending()) { ; + } if (mShutdown) { mPAC.Shutdown(); @@ -895,10 +898,11 @@ nsPACMan::OnStreamComplete(nsIStreamLoader* loader, nsISupports* context, OnLoadFailure(); } - if (NS_SUCCEEDED(status)) + if (NS_SUCCEEDED(status)) { PostProcessPendingQ(); - else + } else { PostCancelPendingQ(status); + } return NS_OK; } diff --git a/netwerk/base/nsPACMan.h b/netwerk/base/nsPACMan.h index 373220ab30bb..d1e5861f2d64 100644 --- a/netwerk/base/nsPACMan.h +++ b/netwerk/base/nsPACMan.h @@ -119,7 +119,7 @@ class nsPACMan final : public nsIStreamLoaderObserver, * If set to false the callback can be made from the PAC thread */ nsresult AsyncGetProxyForURI(nsIURI* uri, nsPACManCallback* callback, - uint32_t flags, bool mustCallbackOnMainThread); + uint32_t flags, bool mainThreadResponse); /** * This method may be called to reload the PAC file. While we are loading diff --git a/netwerk/base/nsPreloadedStream.cpp b/netwerk/base/nsPreloadedStream.cpp index 4effa08066ad..fd515c49c872 100644 --- a/netwerk/base/nsPreloadedStream.cpp +++ b/netwerk/base/nsPreloadedStream.cpp @@ -107,8 +107,9 @@ NS_IMETHODIMP nsPreloadedStream::AsyncWait(nsIInputStreamCallback* aCallback, uint32_t aFlags, uint32_t aRequestedCount, nsIEventTarget* aEventTarget) { - if (!mLen) + if (!mLen) { return mStream->AsyncWait(aCallback, aFlags, aRequestedCount, aEventTarget); + } if (!aCallback) return NS_OK; diff --git a/netwerk/base/nsProtocolProxyService.cpp b/netwerk/base/nsProtocolProxyService.cpp index 8365e733eddb..0a0a72e96630 100644 --- a/netwerk/base/nsProtocolProxyService.cpp +++ b/netwerk/base/nsProtocolProxyService.cpp @@ -70,8 +70,8 @@ extern const char kProxyType_DIRECT[]; // This structure is intended to be allocated on the stack struct nsProtocolInfo { nsAutoCString scheme; - uint32_t flags; - int32_t defaultPort; + uint32_t flags = 0; + int32_t defaultPort = 0; }; //---------------------------------------------------------------------------- @@ -181,8 +181,8 @@ class nsAsyncResolveRequest final : public nsIRunnable, NS_DECL_NSIRUNNABLE NS_DECL_NSICANCELABLE - typedef std::function - Callback; + using Callback = + std::function; explicit AsyncApplyFilters(nsProtocolInfo& aInfo, Callback const& aCallback); @@ -197,7 +197,7 @@ class nsAsyncResolveRequest final : public nsIRunnable, nsresult AsyncProcess(nsAsyncResolveRequest* aRequest); private: - typedef nsProtocolProxyService::FilterLink FilterLink; + using FilterLink = nsProtocolProxyService::FilterLink; virtual ~AsyncApplyFilters(); // Processes the next filter and loops until a filter is successfully @@ -288,13 +288,14 @@ class nsAsyncResolveRequest final : public nsIRunnable, } nsresult DispatchCallback() { - if (mDispatched) // Only need to dispatch once + if (mDispatched) { // Only need to dispatch once return NS_OK; + } nsresult rv = NS_DispatchToCurrentThread(this); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { NS_WARNING("unable to dispatch callback event"); - else { + } else { mDispatched = true; return NS_OK; } @@ -396,8 +397,9 @@ class nsAsyncResolveRequest final : public nsIRunnable, mResolveFlags, true); } - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { mCallback->OnProxyAvailable(this, mChannel, nullptr, rv); + } // do not call onproxyavailable() in SUCCESS case - the newRequest will // take care of that @@ -712,9 +714,9 @@ static void proxy_GetStringPref(nsIPrefBranch* aPrefBranch, const char* aPref, nsCString& aResult) { nsAutoCString temp; nsresult rv = aPrefBranch->GetCharPref(aPref, temp); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { aResult.Truncate(); - else { + } else { aResult.Assign(temp); // all of our string prefs are hostnames, so we should remove any // whitespace characters that the user might have unknowingly entered. @@ -726,20 +728,22 @@ static void proxy_GetIntPref(nsIPrefBranch* aPrefBranch, const char* aPref, int32_t& aResult) { int32_t temp; nsresult rv = aPrefBranch->GetIntPref(aPref, &temp); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { aResult = -1; - else + } else { aResult = temp; + } } static void proxy_GetBoolPref(nsIPrefBranch* aPrefBranch, const char* aPref, bool& aResult) { bool temp; nsresult rv = aPrefBranch->GetBoolPref(aPref, &temp); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { aResult = false; - else + } else { aResult = temp; + } } //---------------------------------------------------------------------------- @@ -992,37 +996,45 @@ void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch, } } - if (!pref || !strcmp(pref, PROXY_PREF("http"))) + if (!pref || !strcmp(pref, PROXY_PREF("http"))) { proxy_GetStringPref(prefBranch, PROXY_PREF("http"), mHTTPProxyHost); + } - if (!pref || !strcmp(pref, PROXY_PREF("http_port"))) + if (!pref || !strcmp(pref, PROXY_PREF("http_port"))) { proxy_GetIntPref(prefBranch, PROXY_PREF("http_port"), mHTTPProxyPort); + } - if (!pref || !strcmp(pref, PROXY_PREF("ssl"))) + if (!pref || !strcmp(pref, PROXY_PREF("ssl"))) { proxy_GetStringPref(prefBranch, PROXY_PREF("ssl"), mHTTPSProxyHost); + } - if (!pref || !strcmp(pref, PROXY_PREF("ssl_port"))) + if (!pref || !strcmp(pref, PROXY_PREF("ssl_port"))) { proxy_GetIntPref(prefBranch, PROXY_PREF("ssl_port"), mHTTPSProxyPort); + } - if (!pref || !strcmp(pref, PROXY_PREF("socks"))) + if (!pref || !strcmp(pref, PROXY_PREF("socks"))) { proxy_GetStringPref(prefBranch, PROXY_PREF("socks"), mSOCKSProxyTarget); + } - if (!pref || !strcmp(pref, PROXY_PREF("socks_port"))) + if (!pref || !strcmp(pref, PROXY_PREF("socks_port"))) { proxy_GetIntPref(prefBranch, PROXY_PREF("socks_port"), mSOCKSProxyPort); + } if (!pref || !strcmp(pref, PROXY_PREF("socks_version"))) { int32_t version; proxy_GetIntPref(prefBranch, PROXY_PREF("socks_version"), version); // make sure this preference value remains sane - if (version == 5) + if (version == 5) { mSOCKSProxyVersion = 5; - else + } else { mSOCKSProxyVersion = 4; + } } - if (!pref || !strcmp(pref, PROXY_PREF("socks_remote_dns"))) + if (!pref || !strcmp(pref, PROXY_PREF("socks_remote_dns"))) { proxy_GetBoolPref(prefBranch, PROXY_PREF("socks_remote_dns"), mSOCKSProxyRemoteDNS); + } if (!pref || !strcmp(pref, PROXY_PREF("proxy_over_tls"))) { proxy_GetBoolPref(prefBranch, PROXY_PREF("proxy_over_tls"), mProxyOverTLS); @@ -1034,9 +1046,10 @@ void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch, reloadPAC = reloadPAC || mProxyConfig == PROXYCONFIG_WPAD; } - if (!pref || !strcmp(pref, PROXY_PREF("failover_timeout"))) + if (!pref || !strcmp(pref, PROXY_PREF("failover_timeout"))) { proxy_GetIntPref(prefBranch, PROXY_PREF("failover_timeout"), mFailedProxyTimeout); + } if (!pref || !strcmp(pref, PROXY_PREF("no_proxies_on"))) { rv = prefBranch->GetCharPref(PROXY_PREF("no_proxies_on"), tempString); @@ -1046,8 +1059,9 @@ void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch, // We're done if not using something that could give us a PAC URL // (PAC, WPAD or System) if (mProxyConfig != PROXYCONFIG_PAC && mProxyConfig != PROXYCONFIG_WPAD && - mProxyConfig != PROXYCONFIG_SYSTEM) + mProxyConfig != PROXYCONFIG_SYSTEM) { return; + } // OK, we need to reload the PAC file if: // 1) network.proxy.type changed, or @@ -1131,8 +1145,9 @@ bool nsProtocolProxyService::CanUseProxy(nsIURI* aURI, int32_t defaultPort) { proxy_MaskIPv6Addr(masked, hinfo->ip.mask_len); // check for a match - if (memcmp(&masked, &hinfo->ip.addr, sizeof(PRIPv6Addr)) == 0) + if (memcmp(&masked, &hinfo->ip.addr, sizeof(PRIPv6Addr)) == 0) { return false; // proxy disallowed + } } else { uint32_t host_len = host.Length(); uint32_t filter_host_len = hinfo->name.host_len; @@ -1225,14 +1240,15 @@ const char* nsProtocolProxyService::ExtractProxyInfo(const char* start, } break; case 6: - if (nsCRT::strncasecmp(start, kProxyType_DIRECT, 6) == 0) + if (nsCRT::strncasecmp(start, kProxyType_DIRECT, 6) == 0) { type = kProxyType_DIRECT; - else if (nsCRT::strncasecmp(start, kProxyType_SOCKS4, 6) == 0) + } else if (nsCRT::strncasecmp(start, kProxyType_SOCKS4, 6) == 0) { type = kProxyType_SOCKS4; - else if (nsCRT::strncasecmp(start, kProxyType_SOCKS5, 6) == 0) + } else if (nsCRT::strncasecmp(start, kProxyType_SOCKS5, 6) == 0) { // map "SOCKS5" to "socks" to match contract-id of registered // SOCKS-v5 socket provider. type = kProxyType_SOCKS; + } break; } if (type) { @@ -1241,8 +1257,9 @@ const char* nsProtocolProxyService::ExtractProxyInfo(const char* start, // If it's a SOCKS5 proxy, do name resolution on the server side. // We could use this with SOCKS4a servers too, but they might not // support it. - if (type == kProxyType_SOCKS || mSOCKSProxyRemoteDNS) + if (type == kProxyType_SOCKS || mSOCKSProxyRemoteDNS) { flags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST; + } // extract host:port start = sp; @@ -1441,8 +1458,9 @@ void nsProtocolProxyService::ProcessPACString(const nsCString& pacString, if (last) { NS_ASSERTION(last->mNext == nullptr, "leaking nsProxyInfo"); last->mNext = pi; - } else + } else { first = pi; + } last = pi; } } @@ -1460,9 +1478,9 @@ nsProtocolProxyService::ReloadPAC() { if (NS_FAILED(rv)) return NS_OK; nsAutoCString pacSpec; - if (type == PROXYCONFIG_PAC) + if (type == PROXYCONFIG_PAC) { prefs->GetCharPref(PROXY_PREF("autoconfig_url"), pacSpec); - else if (type == PROXYCONFIG_SYSTEM) { + } else if (type == PROXYCONFIG_SYSTEM) { if (mSystemProxySettings) { AsyncConfigureFromPAC(true, true); } else { @@ -1470,8 +1488,9 @@ nsProtocolProxyService::ReloadPAC() { } } - if (!pacSpec.IsEmpty() || type == PROXYCONFIG_WPAD) + if (!pacSpec.IsEmpty() || type == PROXYCONFIG_WPAD) { ConfigureFromPAC(pacSpec, true); + } return NS_OK; } @@ -1672,8 +1691,9 @@ nsProtocolProxyService::GetFailoverForProxy(nsIProxyInfo* aProxy, nsIURI* aURI, // We only support failover when a PAC file is configured, either // directly or via system settings if (mProxyConfig != PROXYCONFIG_PAC && mProxyConfig != PROXYCONFIG_WPAD && - mProxyConfig != PROXYCONFIG_SYSTEM) + mProxyConfig != PROXYCONFIG_SYSTEM) { return NS_ERROR_NOT_AVAILABLE; + } // Verify that |aProxy| is one of our nsProxyInfo objects. nsCOMPtr pi = do_QueryInterface(aProxy); @@ -1699,7 +1719,7 @@ nsProtocolProxyService::GetFailoverForProxy(nsIProxyInfo* aProxy, nsIURI* aURI, namespace { // anon class ProxyFilterPositionComparator { - typedef RefPtr FilterLinkRef; + using FilterLinkRef = RefPtr; public: bool Equals(const FilterLinkRef& a, const FilterLinkRef& b) const { @@ -1711,7 +1731,7 @@ class ProxyFilterPositionComparator { }; class ProxyFilterObjectComparator { - typedef RefPtr FilterLinkRef; + using FilterLinkRef = RefPtr; public: bool Equals(const FilterLinkRef& link, const nsISupports* obj) const { @@ -2054,8 +2074,9 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, *usePACThread = false; *result = nullptr; - if (!(info.flags & nsIProtocolHandler::ALLOWS_PROXY)) + if (!(info.flags & nsIProtocolHandler::ALLOWS_PROXY)) { return NS_OK; // Can't proxy this (filters may not override) + } nsCOMPtr uri; nsresult rv = GetProxyURI(channel, getter_AddRefs(uri)); @@ -2069,8 +2090,9 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, // if proxies are enabled and this host:port combo is supposed to use a // proxy, check for a proxy. if ((mProxyConfig == PROXYCONFIG_DIRECT) || - !CanUseProxy(uri, info.defaultPort)) + !CanUseProxy(uri, info.defaultPort)) { return NS_OK; + } bool mainThreadOnly; if (mSystemProxySettings && mProxyConfig == PROXYCONFIG_SYSTEM && @@ -2156,8 +2178,9 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, // proxy, check for a proxy. if (mProxyConfig == PROXYCONFIG_DIRECT || (mProxyConfig == PROXYCONFIG_MANUAL && - !CanUseProxy(uri, info.defaultPort))) + !CanUseProxy(uri, info.defaultPort))) { return NS_OK; + } // Proxy auto config magic... if (mProxyConfig == PROXYCONFIG_PAC || mProxyConfig == PROXYCONFIG_WPAD) { @@ -2180,13 +2203,15 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, if ((flags & RESOLVE_PREFER_SOCKS_PROXY) && !mSOCKSProxyTarget.IsEmpty() && (IsHostLocalTarget(mSOCKSProxyTarget) || mSOCKSProxyPort > 0)) { host = &mSOCKSProxyTarget; - if (mSOCKSProxyVersion == 4) + if (mSOCKSProxyVersion == 4) { type = kProxyType_SOCKS4; - else + } else { type = kProxyType_SOCKS; + } port = mSOCKSProxyPort; - if (mSOCKSProxyRemoteDNS) + if (mSOCKSProxyRemoteDNS) { proxyFlags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST; + } } else if ((flags & RESOLVE_PREFER_HTTPS_PROXY) && !mHTTPSProxyHost.IsEmpty() && mHTTPSProxyPort > 0) { host = &mHTTPSProxyHost; @@ -2207,13 +2232,15 @@ nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel, } else if (!mSOCKSProxyTarget.IsEmpty() && (IsHostLocalTarget(mSOCKSProxyTarget) || mSOCKSProxyPort > 0)) { host = &mSOCKSProxyTarget; - if (mSOCKSProxyVersion == 4) + if (mSOCKSProxyVersion == 4) { type = kProxyType_SOCKS4; - else + } else { type = kProxyType_SOCKS; + } port = mSOCKSProxyPort; - if (mSOCKSProxyRemoteDNS) + if (mSOCKSProxyRemoteDNS) { proxyFlags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST; + } } if (type) { @@ -2304,10 +2331,11 @@ void nsProtocolProxyService::PruneProxyInfo(const nsProtocolInfo& info, if ((iter->Type() == kProxyType_HTTP) || (iter->Type() == kProxyType_HTTPS)) { // reject! - if (last) + if (last) { last->mNext = iter->mNext; - else + } else { head = iter->mNext; + } nsProxyInfo* next = iter->mNext; iter->mNext = nullptr; iter->Release(); @@ -2347,10 +2375,11 @@ void nsProtocolProxyService::PruneProxyInfo(const nsProtocolInfo& info, nsProxyInfo* reject = iter; iter = iter->mNext; - if (last) + if (last) { last->mNext = iter; - else + } else { head = iter; + } reject->mNext = nullptr; NS_RELEASE(reject); @@ -2371,8 +2400,9 @@ void nsProtocolProxyService::PruneProxyInfo(const nsProtocolInfo& info, } // if only DIRECT was specified then return no proxy info, and we're done. - if (head && !head->mNext && head->mType == kProxyType_DIRECT) + if (head && !head->mNext && head->mType == kProxyType_DIRECT) { NS_RELEASE(head); + } *list = head; // Transfer ownership diff --git a/netwerk/base/nsProtocolProxyService.h b/netwerk/base/nsProtocolProxyService.h index 26b19a1a09cc..351b0c7280f6 100644 --- a/netwerk/base/nsProtocolProxyService.h +++ b/netwerk/base/nsProtocolProxyService.h @@ -25,7 +25,7 @@ class nsISystemProxySettings; namespace mozilla { namespace net { -typedef nsTHashMap nsFailedProxyTable; +using nsFailedProxyTable = nsTHashMap; class nsPACMan; class nsProxyInfo; @@ -90,7 +90,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * This can be the name of a fully-qualified preference, or it can * be null, in which case all preferences will be initialized. */ - void PrefsChanged(nsIPrefBranch* prefs, const char* name); + void PrefsChanged(nsIPrefBranch* prefBranch, const char* pref); /** * This method is called to create a nsProxyInfo instance from the given @@ -108,7 +108,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * * @return A pointer beyond the parsed proxy string (never null). */ - const char* ExtractProxyInfo(const char* proxy, uint32_t aResolveFlags, + const char* ExtractProxyInfo(const char* start, uint32_t aResolveFlags, nsProxyInfo** result); /** @@ -117,7 +117,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * @param pacURI * The URI spec of the PAC file to load. */ - nsresult ConfigureFromPAC(const nsCString& pacURI, bool forceReload); + nsresult ConfigureFromPAC(const nsCString& spec, bool forceReload); /** * This method builds a list of nsProxyInfo objects from the given PAC- @@ -143,7 +143,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * @param result * Upon return, this parameter holds the generated key. */ - void GetProxyKey(nsProxyInfo* pi, nsCString& result); + void GetProxyKey(nsProxyInfo* pi, nsCString& key); /** * @return Seconds since start of session. @@ -187,7 +187,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * of structure when you call this method. This parameter must not * be null. */ - nsresult GetProtocolInfo(nsIURI* uri, nsProtocolInfo* result); + nsresult GetProtocolInfo(nsIURI* uri, nsProtocolInfo* info); /** * This method is an internal version nsIProtocolProxyService::newProxyInfo @@ -220,8 +220,8 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, const nsACString& aProxyAuthorizationHeader, const nsACString& aConnectionIsolationKey, uint32_t flags, uint32_t timeout, - nsIProxyInfo* next, uint32_t aResolveFlags, - nsIProxyInfo** result); + nsIProxyInfo* aFailoverProxy, + uint32_t aResolveFlags, nsIProxyInfo** result); /** * This method is an internal version of Resolve that does not query PAC. @@ -258,7 +258,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * asynchronously) to provide the updated proxyinfo list. */ bool ApplyFilter(FilterLink const* filterLink, nsIChannel* channel, - const nsProtocolInfo& info, nsCOMPtr proxyInfo, + const nsProtocolInfo& info, nsCOMPtr list, nsIProxyProtocolFilterResult* callback); /** @@ -270,7 +270,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * @param proxyInfo * The proxy info list to be modified. This is an inout param. */ - void PruneProxyInfo(const nsProtocolInfo& info, nsIProxyInfo** proxyInfo); + void PruneProxyInfo(const nsProtocolInfo& info, nsIProxyInfo** list); /** * This method is a simple wrapper around PruneProxyInfo that takes the @@ -290,7 +290,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, * @param hostFilters * A "no-proxy-for" exclusion list. */ - void LoadHostFilters(const nsACString& hostFilters); + void LoadHostFilters(const nsACString& aFilters); /** * This method checks the given URI against mHostFiltersArray. @@ -344,7 +344,7 @@ class nsProtocolProxyService final : public nsIProtocolProxyService2, bool is_ipaddr; int32_t port; union { - HostInfoIP ip; + HostInfoIP ip{}; HostInfoName name; }; diff --git a/netwerk/base/nsServerSocket.cpp b/netwerk/base/nsServerSocket.cpp index e0ac43ebd96d..8c5bc817b6f3 100644 --- a/netwerk/base/nsServerSocket.cpp +++ b/netwerk/base/nsServerSocket.cpp @@ -22,7 +22,7 @@ namespace net { //----------------------------------------------------------------------------- -typedef void (nsServerSocket::*nsServerSocketFunc)(void); +using nsServerSocketFunc = void (nsServerSocket::*)(); static nsresult PostEvent(nsServerSocket* s, nsServerSocketFunc func) { nsCOMPtr ev = NewRunnableMethod("net::PostEvent", s, func); @@ -284,8 +284,9 @@ nsServerSocket::InitWithFilename(nsIFile* aPath, uint32_t aPermissions, // Create a Unix domain PRNetAddr referring to the given path. PRNetAddr addr; - if (path.Length() > sizeof(addr.local.path) - 1) + if (path.Length() > sizeof(addr.local.path) - 1) { return NS_ERROR_FILE_NAME_TOO_LONG; + } addr.local.family = PR_AF_LOCAL; memcpy(addr.local.path, path.get(), path.Length()); addr.local.path[path.Length()] = '\0'; @@ -328,10 +329,11 @@ nsServerSocket::InitSpecialConnection(int32_t aPort, nsServerSocketFlag aFlags, PRNetAddr addr; if (aPort < 0) aPort = 0; - if (aFlags & nsIServerSocket::LoopbackOnly) + if (aFlags & nsIServerSocket::LoopbackOnly) { val = PR_IpAddrLoopback; - else + } else { val = PR_IpAddrAny; + } PR_SetNetAddr(val, PR_AF_INET, aPort, &addr); mKeepWhenOffline = ((aFlags & nsIServerSocket::KeepWhenOffline) != 0); @@ -528,12 +530,13 @@ NS_IMETHODIMP nsServerSocket::GetPort(int32_t* aResult) { // no need to enter the lock here uint16_t port; - if (mAddr.raw.family == PR_AF_INET) + if (mAddr.raw.family == PR_AF_INET) { port = mAddr.inet.port; - else if (mAddr.raw.family == PR_AF_INET6) + } else if (mAddr.raw.family == PR_AF_INET6) { port = mAddr.ipv6.port; - else + } else { return NS_ERROR_FAILURE; + } *aResult = static_cast(NetworkEndian::readUint16(&port)); return NS_OK; diff --git a/netwerk/base/nsServerSocket.h b/netwerk/base/nsServerSocket.h index 3690a99a9dc1..40bba17884d1 100644 --- a/netwerk/base/nsServerSocket.h +++ b/netwerk/base/nsServerSocket.h @@ -52,7 +52,7 @@ class nsServerSocket : public nsASocketHandler, public nsIServerSocket { // lock protects access to mListener; so it is not cleared while being used. mozilla::Mutex mLock; - PRNetAddr mAddr; + PRNetAddr mAddr = {.raw = {0, {0}}}; nsCOMPtr mListenerTarget; bool mAttached; bool mKeepWhenOffline; diff --git a/netwerk/base/nsSimpleURI.h b/netwerk/base/nsSimpleURI.h index 0154cd6ff662..9d995c66faf9 100644 --- a/netwerk/base/nsSimpleURI.h +++ b/netwerk/base/nsSimpleURI.h @@ -55,21 +55,21 @@ class nsSimpleURI : public nsIURI, public nsISerializable, public nsISizeOf { // enum used in a few places to specify how .ref attribute should be handled enum RefHandlingEnum { eIgnoreRef, eHonorRef, eReplaceRef }; - virtual nsresult Clone(nsIURI** aURI); + virtual nsresult Clone(nsIURI** result); virtual nsresult SetSpecInternal(const nsACString& aSpec, bool aStripWhitespace = false); - virtual nsresult SetScheme(const nsACString& input); + virtual nsresult SetScheme(const nsACString& scheme); virtual nsresult SetUserPass(const nsACString& input); nsresult SetUsername(const nsACString& input); virtual nsresult SetPassword(const nsACString& input); virtual nsresult SetHostPort(const nsACString& aValue); virtual nsresult SetHost(const nsACString& input); virtual nsresult SetPort(int32_t port); - virtual nsresult SetPathQueryRef(const nsACString& input); - virtual nsresult SetRef(const nsACString& input); - virtual nsresult SetFilePath(const nsACString& input); - virtual nsresult SetQuery(const nsACString& input); - virtual nsresult SetQueryWithEncoding(const nsACString& input, + virtual nsresult SetPathQueryRef(const nsACString& aPath); + virtual nsresult SetRef(const nsACString& aRef); + virtual nsresult SetFilePath(const nsACString& aFilePath); + virtual nsresult SetQuery(const nsACString& aQuery); + virtual nsresult SetQueryWithEncoding(const nsACString& aQuery, const Encoding* encoding); nsresult ReadPrivate(nsIObjectInputStream* stream); @@ -96,7 +96,7 @@ class nsSimpleURI : public nsIURI, public nsISerializable, public nsISizeOf { // Helper to share code between Clone methods. virtual nsresult CloneInternal(RefHandlingEnum refHandlingMode, - const nsACString& newRef, nsIURI** clone); + const nsACString& newRef, nsIURI** result); nsresult EscapeAndSetPathQueryRef(const nsACString& aPath); nsresult SetPathQueryRefInternal(const nsACString& aPath); @@ -108,7 +108,6 @@ class nsSimpleURI : public nsIURI, public nsISerializable, public nsISizeOf { nsCString mRef; // so that URIs with different refs can share string data. nsCString mQuery; // so that URLs with different querys can share string data. - bool mMutable; bool mIsRefValid; // To distinguish between empty-ref and no-ref. bool mIsQueryValid; // To distinguish between empty-query and no-query. diff --git a/netwerk/base/nsSocketTransport2.cpp b/netwerk/base/nsSocketTransport2.cpp index 551fa4d50997..3ff75a498745 100644 --- a/netwerk/base/nsSocketTransport2.cpp +++ b/netwerk/base/nsSocketTransport2.cpp @@ -344,9 +344,9 @@ nsSocketInputStream::Available(uint64_t* avail) { mTransport->ReleaseFD_Locked(fd); - if (n >= 0) + if (n >= 0) { *avail = n; - else { + } else { PRErrorCode code = PR_GetError(); if (code == PR_WOULD_BLOCK_ERROR) return NS_OK; mCondition = ErrorAccordingToNSPR(code); @@ -367,8 +367,9 @@ nsSocketInputStream::Read(char* buf, uint32_t count, uint32_t* countRead) { { MutexAutoLock lock(mTransport->mLock); - if (NS_FAILED(mCondition)) + if (NS_FAILED(mCondition)) { return (mCondition == NS_BASE_STREAM_CLOSED) ? NS_OK : mCondition; + } fd = mTransport->GetFD_Locked(); if (!fd) return NS_BASE_STREAM_WOULD_BLOCK; @@ -393,9 +394,9 @@ nsSocketInputStream::Read(char* buf, uint32_t count, uint32_t* countRead) { mTransport->ReleaseFD_Locked(fd); - if (n > 0) + if (n > 0) { mByteCount += (*countRead = n); - else if (n < 0) { + } else if (n < 0) { PRErrorCode code = PR_GetError(); if (code == PR_WOULD_BLOCK_ERROR) return NS_BASE_STREAM_WOULD_BLOCK; mCondition = ErrorAccordingToNSPR(code); @@ -435,10 +436,11 @@ nsSocketInputStream::CloseWithStatus(nsresult reason) { { MutexAutoLock lock(mTransport->mLock); - if (NS_SUCCEEDED(mCondition)) + if (NS_SUCCEEDED(mCondition)) { rv = mCondition = reason; - else + } else { rv = NS_OK; + } } if (NS_FAILED(rv)) mTransport->OnInputClosed(rv); return NS_OK; @@ -459,8 +461,9 @@ nsSocketInputStream::AsyncWait(nsIInputStreamCallback* callback, uint32_t flags, // mCallback = NS_NewInputStreamReadyEvent("nsSocketInputStream::AsyncWait", callback, target); - } else + } else { mCallback = callback; + } mCallbackFlags = flags; hasError = NS_FAILED(mCondition); @@ -579,9 +582,9 @@ nsSocketOutputStream::Write(const char* buf, uint32_t count, mTransport->ReleaseFD_Locked(fd); - if (n > 0) + if (n > 0) { mByteCount += (*countWritten = n); - else if (n < 0) { + } else if (n < 0) { PRErrorCode code = PR_GetError(); if (code == PR_WOULD_BLOCK_ERROR) return NS_BASE_STREAM_WOULD_BLOCK; mCondition = ErrorAccordingToNSPR(code); @@ -637,10 +640,11 @@ nsSocketOutputStream::CloseWithStatus(nsresult reason) { { MutexAutoLock lock(mTransport->mLock); - if (NS_SUCCEEDED(mCondition)) + if (NS_SUCCEEDED(mCondition)) { rv = mCondition = reason; - else + } else { rv = NS_OK; + } } if (NS_FAILED(rv)) mTransport->OnOutputClosed(rv); return NS_OK; @@ -660,8 +664,9 @@ nsSocketOutputStream::AsyncWait(nsIOutputStreamCallback* callback, // build event proxy // mCallback = NS_NewOutputStreamReadyEvent(callback, target); - } else + } else { mCallback = callback; + } mCallbackFlags = flags; } @@ -798,10 +803,11 @@ nsresult nsSocketTransport::Init(const nsTArray& types, // now verify that each socket type has a registered socket provider. for (uint32_t i = 0, type = 0; i < typeCount; ++i) { // store socket types - if (i == 0 && proxyType) + if (i == 0 && proxyType) { mTypes.AppendElement(proxyType); - else + } else { mTypes.AppendElement(types[type++]); + } nsCOMPtr provider; rv = spserv->GetSocketProvider(mTypes[i].get(), getter_AddRefs(provider)); @@ -869,12 +875,13 @@ nsresult nsSocketTransport::InitWithConnectedSocket(PRFileDesc* fd, mHost.Assign(buf); uint16_t port; - if (addr->raw.family == AF_INET) + if (addr->raw.family == AF_INET) { port = addr->inet.port; - else if (addr->raw.family == AF_INET6) + } else if (addr->raw.family == AF_INET6) { port = addr->inet6.port; - else + } else { port = 0; + } mPort = ntohs(port); memcpy(&mNetAddr, addr, sizeof(NetAddr)); @@ -1021,16 +1028,21 @@ nsresult nsSocketTransport::ResolveHost() { mResolving = true; uint32_t dnsFlags = 0; - if (mConnectionFlags & nsSocketTransport::BYPASS_CACHE) + if (mConnectionFlags & nsSocketTransport::BYPASS_CACHE) { dnsFlags = nsIDNSService::RESOLVE_BYPASS_CACHE; - if (mConnectionFlags & nsSocketTransport::REFRESH_CACHE) + } + if (mConnectionFlags & nsSocketTransport::REFRESH_CACHE) { dnsFlags = nsIDNSService::RESOLVE_REFRESH_CACHE; - if (mConnectionFlags & nsSocketTransport::DISABLE_IPV6) + } + if (mConnectionFlags & nsSocketTransport::DISABLE_IPV6) { dnsFlags |= nsIDNSService::RESOLVE_DISABLE_IPV6; - if (mConnectionFlags & nsSocketTransport::DISABLE_IPV4) + } + if (mConnectionFlags & nsSocketTransport::DISABLE_IPV4) { dnsFlags |= nsIDNSService::RESOLVE_DISABLE_IPV4; - if (mConnectionFlags & nsSocketTransport::DISABLE_TRR) + } + if (mConnectionFlags & nsSocketTransport::DISABLE_TRR) { dnsFlags |= nsIDNSService::RESOLVE_DISABLE_TRR; + } if (mConnectionFlags & nsSocketTransport::USE_IP_HINT_ADDRESS) { dnsFlags |= nsIDNSService::RESOLVE_IP_HINT; @@ -1094,17 +1106,21 @@ nsresult nsSocketTransport::BuildSocket(PRFileDesc*& fd, bool& proxyTransparent, fd = nullptr; uint32_t controlFlags = 0; - if (mProxyTransparentResolvesHost) + if (mProxyTransparentResolvesHost) { controlFlags |= nsISocketProvider::PROXY_RESOLVES_HOST; + } - if (mConnectionFlags & nsISocketTransport::ANONYMOUS_CONNECT) + if (mConnectionFlags & nsISocketTransport::ANONYMOUS_CONNECT) { controlFlags |= nsISocketProvider::ANONYMOUS_CONNECT; + } - if (mConnectionFlags & nsISocketTransport::NO_PERMANENT_STORAGE) + if (mConnectionFlags & nsISocketTransport::NO_PERMANENT_STORAGE) { controlFlags |= nsISocketProvider::NO_PERMANENT_STORAGE; + } - if (mConnectionFlags & nsISocketTransport::BE_CONSERVATIVE) + if (mConnectionFlags & nsISocketTransport::BE_CONSERVATIVE) { controlFlags |= nsISocketProvider::BE_CONSERVATIVE; + } if (mConnectionFlags & nsISocketTransport::ANONYMOUS_CONNECT_ALLOW_CLIENT_CERT) { @@ -1269,8 +1285,9 @@ nsresult nsSocketTransport::InitiateSocket() { nsAutoCString netAddrCString; netAddrCString.SetLength(kIPv6CStrBufSize); if (!mNetAddr.ToStringBuffer(netAddrCString.BeginWriting(), - kIPv6CStrBufSize)) + kIPv6CStrBufSize)) { netAddrCString = ""_ns; + } SOCKET_LOG( ("nsSocketTransport::InitiateSocket skipping " "speculative connection for host [%s:%d] proxy " @@ -1538,12 +1555,12 @@ nsresult nsSocketTransport::InitiateSocket() { // // If the PR_Connect(...) would block, then poll for a connection. // - if ((PR_WOULD_BLOCK_ERROR == code) || (PR_IN_PROGRESS_ERROR == code)) + if ((PR_WOULD_BLOCK_ERROR == code) || (PR_IN_PROGRESS_ERROR == code)) { mPollFlags = (PR_POLL_EXCEPT | PR_POLL_WRITE); - // - // If the socket is already connected, then return success... - // - else if (PR_IS_CONNECTED_ERROR == code) { + // + // If the socket is already connected, then return success... + // + } else if (PR_IS_CONNECTED_ERROR == code) { // // we are connected! // @@ -1591,8 +1608,9 @@ nsresult nsSocketTransport::InitiateSocket() { } rv = ErrorAccordingToNSPR(code); - if ((rv == NS_ERROR_CONNECTION_REFUSED) && !mProxyHost.IsEmpty()) + if ((rv == NS_ERROR_CONNECTION_REFUSED) && !mProxyHost.IsEmpty()) { rv = NS_ERROR_PROXY_CONNECTION_REFUSED; + } } } return rv; @@ -1772,12 +1790,12 @@ void nsSocketTransport::OnMsgInputClosed(nsresult reason) { mInputClosed = true; // check if event should affect entire transport - if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED)) + if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED)) { mCondition = reason; // XXX except if NS_FAILED(mCondition), right?? - else if (mOutputClosed) + } else if (mOutputClosed) { mCondition = NS_BASE_STREAM_CLOSED; // XXX except if NS_FAILED(mCondition), right?? - else { + } else { if (mState == STATE_TRANSFERRING) mPollFlags &= ~PR_POLL_READ; mInput.OnSocketReady(reason); } @@ -1793,12 +1811,12 @@ void nsSocketTransport::OnMsgOutputClosed(nsresult reason) { mOutputClosed = true; // check if event should affect entire transport - if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED)) + if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED)) { mCondition = reason; // XXX except if NS_FAILED(mCondition), right?? - else if (mInputClosed) + } else if (mInputClosed) { mCondition = NS_BASE_STREAM_CLOSED; // XXX except if NS_FAILED(mCondition), right?? - else { + } else { if (mState == STATE_TRANSFERRING) mPollFlags &= ~PR_POLL_WRITE; mOutput.OnSocketReady(reason); } @@ -1966,9 +1984,9 @@ void nsSocketTransport::OnSocketEvent(uint32_t type, nsresult status, // need. Internet address families require a DNS lookup (or possibly // several) before we can connect. #if defined(XP_UNIX) - if (mNetAddrIsSet && mNetAddr.raw.family == AF_LOCAL) + if (mNetAddrIsSet && mNetAddr.raw.family == AF_LOCAL) { mCondition = InitiateSocket(); - else + } else #endif mCondition = ResolveHost(); @@ -1997,10 +2015,11 @@ void nsSocketTransport::OnSocketEvent(uint32_t type, nsresult status, // transport resolves the real host here, so there's no fixup // (see bug 226943). if ((status == NS_ERROR_UNKNOWN_HOST) && !mProxyTransparent && - !mProxyHost.IsEmpty()) + !mProxyHost.IsEmpty()) { mCondition = NS_ERROR_UNKNOWN_PROXY_HOST; - else + } else { mCondition = status; + } } else if (mState == STATE_RESOLVING) { mCondition = InitiateSocket(); } @@ -2045,10 +2064,12 @@ void nsSocketTransport::OnSocketEvent(uint32_t type, nsresult status, if (NS_FAILED(mCondition)) { SOCKET_LOG((" after event [this=%p cond=%" PRIx32 "]\n", this, static_cast(mCondition))); - if (!mAttached) // need to process this error ourselves... + if (!mAttached) { // need to process this error ourselves... OnSocketDetached(nullptr); - } else if (mPollFlags == PR_POLL_EXCEPT) + } + } else if (mPollFlags == PR_POLL_EXCEPT) { mPollFlags = 0; // make idle + } } //----------------------------------------------------------------------------- @@ -2155,8 +2176,9 @@ void nsSocketTransport::OnSocketReady(PRFileDesc* fd, int16_t outFlags) { // mCondition = ErrorAccordingToNSPR(code); if ((mCondition == NS_ERROR_CONNECTION_REFUSED) && - !mProxyHost.IsEmpty()) + !mProxyHost.IsEmpty()) { mCondition = NS_ERROR_PROXY_CONNECTION_REFUSED; + } SOCKET_LOG((" connection failed! [reason=%" PRIx32 "]\n", static_cast(mCondition))); } @@ -2197,9 +2219,9 @@ void nsSocketTransport::OnSocketDetached(PRFileDesc* fd) { } // If we are not shutting down try again. - if (!gIOService->IsNetTearingDown() && RecoverFromError()) + if (!gIOService->IsNetTearingDown() && RecoverFromError()) { mCondition = NS_OK; - else { + } else { mState = STATE_CLOSED; // make sure there isn't any pending DNS request @@ -2306,8 +2328,9 @@ nsSocketTransport::OpenInputStream(uint32_t flags, uint32_t segsize, if (NS_FAILED(rv)) return rv; *result = pipeIn; - } else + } else { *result = &mInput; + } // flag input stream as open mInputClosed = false; @@ -2349,8 +2372,9 @@ nsSocketTransport::OpenOutputStream(uint32_t flags, uint32_t segsize, if (NS_FAILED(rv)) return rv; *result = pipeOut; - } else + } else { *result = &mOutput; + } // flag output stream as open mOutputClosed = false; @@ -2445,8 +2469,9 @@ nsSocketTransport::IsAlive(bool* result) { char c; int32_t rval = PR_Recv(fd, &c, 1, PR_MSG_PEEK, 0); - if ((rval > 0) || (rval < 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR)) + if ((rval > 0) || (rval < 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR)) { *result = true; + } return NS_OK; } @@ -2649,10 +2674,11 @@ nsSocketTransport::GetRecvBufferSize(uint32_t* aSize) { nsresult rv = NS_OK; PRSocketOptionData opt; opt.option = PR_SockOpt_RecvBufferSize; - if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS) + if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS) { *aSize = opt.value.recv_buffer_size; - else + } else { rv = NS_ERROR_FAILURE; + } return rv; } @@ -2665,10 +2691,11 @@ nsSocketTransport::GetSendBufferSize(uint32_t* aSize) { nsresult rv = NS_OK; PRSocketOptionData opt; opt.option = PR_SockOpt_SendBufferSize; - if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS) + if (PR_GetSocketOption(fd, &opt) == PR_SUCCESS) { *aSize = opt.value.send_buffer_size; - else + } else { rv = NS_ERROR_FAILURE; + } return rv; } diff --git a/netwerk/base/nsSocketTransport2.h b/netwerk/base/nsSocketTransport2.h index 5bb946aad51d..c18f86ed66f6 100644 --- a/netwerk/base/nsSocketTransport2.h +++ b/netwerk/base/nsSocketTransport2.h @@ -135,7 +135,7 @@ class nsSocketTransport final : public nsASocketHandler, // this method instructs the socket transport to use an already connected // socket with the given address, and additionally supplies security info. - nsresult InitWithConnectedSocket(PRFileDesc* aSocketFD, const NetAddr* aAddr, + nsresult InitWithConnectedSocket(PRFileDesc* aFD, const NetAddr* aAddr, nsISupports* aSecInfo); #ifdef XP_UNIX @@ -344,12 +344,14 @@ class nsSocketTransport final : public nsASocketHandler, bool RecoverFromError(); void OnMsgInputPending() { - if (mState == STATE_TRANSFERRING) + if (mState == STATE_TRANSFERRING) { mPollFlags |= (PR_POLL_READ | PR_POLL_EXCEPT); + } } void OnMsgOutputPending() { - if (mState == STATE_TRANSFERRING) + if (mState == STATE_TRANSFERRING) { mPollFlags |= (PR_POLL_WRITE | PR_POLL_EXCEPT); + } } void OnMsgInputClosed(nsresult reason); void OnMsgOutputClosed(nsresult reason); @@ -382,7 +384,7 @@ class nsSocketTransport final : public nsASocketHandler, friend class nsSocketOutputStream; // socket timeouts are protected by mLock. - uint16_t mTimeouts[2]; + uint16_t mTimeouts[2]{}; // linger options to use when closing bool mLingerPolarity; @@ -402,31 +404,35 @@ class nsSocketTransport final : public nsASocketHandler, // void OnInputClosed(nsresult reason) { // no need to post an event if called on the socket thread - if (OnSocketThread()) + if (OnSocketThread()) { OnMsgInputClosed(reason); - else + } else { PostEvent(MSG_INPUT_CLOSED, reason); + } } void OnInputPending() { // no need to post an event if called on the socket thread - if (OnSocketThread()) + if (OnSocketThread()) { OnMsgInputPending(); - else + } else { PostEvent(MSG_INPUT_PENDING); + } } void OnOutputClosed(nsresult reason) { // no need to post an event if called on the socket thread - if (OnSocketThread()) + if (OnSocketThread()) { OnMsgOutputClosed(reason); // XXX need to not be inside lock! - else + } else { PostEvent(MSG_OUTPUT_CLOSED, reason); + } } void OnOutputPending() { // no need to post an event if called on the socket thread - if (OnSocketThread()) + if (OnSocketThread()) { OnMsgOutputPending(); - else + } else { PostEvent(MSG_OUTPUT_PENDING); + } } #ifdef ENABLE_SOCKET_TRACING diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index d93e302e5c93..6471b6e02600 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -410,7 +410,7 @@ nsSocketTransportService::AttachSocket(PRFileDesc* fd, return NS_ERROR_NOT_AVAILABLE; } - SocketContext sock; + SocketContext sock{}; sock.mFD = fd; sock.mHandler = handler; sock.mPollStartEpoch = 0; @@ -463,10 +463,11 @@ nsresult nsSocketTransportService::DetachSocket(SocketContext* listHead, sock->mFD = nullptr; NS_RELEASE(sock->mHandler); - if (listHead == mActiveList) + if (listHead == mActiveList) { RemoveFromPollList(sock); - else + } else { RemoveFromIdleList(sock); + } // NOTE: sock is now an invalid pointer @@ -576,18 +577,20 @@ void nsSocketTransportService::RemoveFromIdleList(SocketContext* sock) { void nsSocketTransportService::MoveToIdleList(SocketContext* sock) { nsresult rv = AddToIdleList(sock); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { DetachSocket(mActiveList, sock); - else + } else { RemoveFromPollList(sock); + } } void nsSocketTransportService::MoveToPollList(SocketContext* sock) { nsresult rv = AddToPollList(sock); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { DetachSocket(mIdleList, sock); - else + } else { RemoveFromIdleList(sock); + } } bool nsSocketTransportService::GrowActiveList() { @@ -675,10 +678,11 @@ int32_t nsSocketTransportService::Poll(TimeDuration* pollDuration, } else { // no pollable event, so busy wait... pollCount = mActiveCount; - if (pollCount) + if (pollCount) { pollList = &mPollList[1]; - else + } else { pollList = nullptr; + } pollTimeout = pendingEvents ? PR_INTERVAL_NO_WAIT : PR_MillisecondsToInterval(25); } @@ -1323,10 +1327,11 @@ nsresult nsSocketTransportService::DoPollIteration(TimeDuration* pollDuration) { static_cast(mIdleList[i].mHandler->mCondition), mIdleList[i].mHandler->mPollFlags)); //--- - if (NS_FAILED(mIdleList[i].mHandler->mCondition)) + if (NS_FAILED(mIdleList[i].mHandler->mCondition)) { DetachSocket(mIdleList, &mIdleList[i]); - else if (mIdleList[i].mHandler->mPollFlags != 0) + } else if (mIdleList[i].mHandler->mPollFlags != 0) { MoveToPollList(&mIdleList[i]); + } } { @@ -1404,8 +1409,9 @@ nsresult nsSocketTransportService::DoPollIteration(TimeDuration* pollDuration) { // reverse order obviously). // for (i = mActiveCount - 1; i >= 0; --i) { - if (NS_FAILED(mActiveList[i].mHandler->mCondition)) + if (NS_FAILED(mActiveList[i].mHandler->mCondition)) { DetachSocket(mActiveList, &mActiveList[i]); + } } { @@ -1460,20 +1466,23 @@ nsresult nsSocketTransportService::UpdatePrefs() { int32_t keepaliveIdleTimeS; nsresult rv = Preferences::GetInt(KEEPALIVE_IDLE_TIME_PREF, &keepaliveIdleTimeS); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mKeepaliveIdleTimeS = clamped(keepaliveIdleTimeS, 1, kMaxTCPKeepIdle); + } int32_t keepaliveRetryIntervalS; rv = Preferences::GetInt(KEEPALIVE_RETRY_INTERVAL_PREF, &keepaliveRetryIntervalS); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mKeepaliveRetryIntervalS = clamped(keepaliveRetryIntervalS, 1, kMaxTCPKeepIntvl); + } int32_t keepaliveProbeCount; rv = Preferences::GetInt(KEEPALIVE_PROBE_COUNT_PREF, &keepaliveProbeCount); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mKeepaliveProbeCount = clamped(keepaliveProbeCount, 1, kMaxTCPKeepCount); + } bool keepaliveEnabled = false; rv = Preferences::GetBool(KEEPALIVE_ENABLED_PREF, &keepaliveEnabled); if (NS_SUCCEEDED(rv) && keepaliveEnabled != mKeepaliveEnabledPref) { @@ -1724,9 +1733,10 @@ PRStatus nsSocketTransportService::DiscoverMaxCount() { // most linux at 1000. We can reliably use [sg]rlimit to // query that and raise it if needed. - struct rlimit rlimitData; - if (getrlimit(RLIMIT_NOFILE, &rlimitData) == -1) // rlimit broken - use min + struct rlimit rlimitData {}; + if (getrlimit(RLIMIT_NOFILE, &rlimitData) == -1) { // rlimit broken - use min return PR_SUCCESS; + } if (rlimitData.rlim_cur >= SOCKET_LIMIT_TARGET) { // larger than target! gMaxCount = SOCKET_LIMIT_TARGET; @@ -1791,10 +1801,11 @@ void nsSocketTransportService::AnalyzeConnection(nsTArray* data, } uint16_t port; - if (peer_addr.raw.family == PR_AF_INET) + if (peer_addr.raw.family == PR_AF_INET) { port = peer_addr.inet.port; - else + } else { port = peer_addr.ipv6.port; + } port = PR_ntohs(port); uint64_t sent = context->mHandler->ByteCountSent(); uint64_t received = context->mHandler->ByteCountReceived(); @@ -1806,10 +1817,12 @@ void nsSocketTransportService::AnalyzeConnection(nsTArray* data, void nsSocketTransportService::GetSocketConnections( nsTArray* data) { MOZ_ASSERT(OnSocketThread(), "not on socket thread"); - for (uint32_t i = 0; i < mActiveCount; i++) + for (uint32_t i = 0; i < mActiveCount; i++) { AnalyzeConnection(data, &mActiveList[i], true); - for (uint32_t i = 0; i < mIdleCount; i++) + } + for (uint32_t i = 0; i < mIdleCount; i++) { AnalyzeConnection(data, &mIdleList[i], false); + } } bool nsSocketTransportService::IsTelemetryEnabledAndNotSleepPhase() { diff --git a/netwerk/base/nsSocketTransportService2.h b/netwerk/base/nsSocketTransportService2.h index 875028c0d6f9..4abde5fd3f5e 100644 --- a/netwerk/base/nsSocketTransportService2.h +++ b/netwerk/base/nsSocketTransportService2.h @@ -251,7 +251,7 @@ class nsSocketTransportService final : public nsPISocketTransportService, PRIntervalTime now); // computes ideal poll timeout nsresult DoPollIteration(TimeDuration* pollDuration); // perfoms a single poll iteration - int32_t Poll(TimeDuration* pollDuration, PRIntervalTime now); + int32_t Poll(TimeDuration* pollDuration, PRIntervalTime ts); // calls PR_Poll. the out param // interval indicates the poll // duration in seconds. @@ -303,7 +303,7 @@ class nsSocketTransportService final : public nsPISocketTransportService, // <1> the less-or-equal port number of the range to remap // <2> the port number to remap to, when the given port number falls to the // range - typedef CopyableTArray> TPortRemapping; + using TPortRemapping = CopyableTArray>; Maybe mPortRemapping; // Called on the socket thread to apply the mapping build on the main thread diff --git a/netwerk/base/nsStandardURL.h b/netwerk/base/nsStandardURL.h index 054144399c39..fa69918021d9 100644 --- a/netwerk/base/nsStandardURL.h +++ b/netwerk/base/nsStandardURL.h @@ -215,27 +215,27 @@ class nsStandardURL : public nsIFileURL, char* AppendToSubstring(uint32_t pos, int32_t len, const char* tail); // dependent substring helpers - const nsDependentCSubstring Segment(uint32_t pos, int32_t len); // see below - const nsDependentCSubstring Segment(const URLSegment& s) { + nsDependentCSubstring Segment(uint32_t pos, int32_t len); // see below + nsDependentCSubstring Segment(const URLSegment& s) { return Segment(s.mPos, s.mLen); } // dependent substring getters - const nsDependentCSubstring Prepath(); // see below - const nsDependentCSubstring Scheme() { return Segment(mScheme); } - const nsDependentCSubstring Userpass(bool includeDelim = false); // see below - const nsDependentCSubstring Username() { return Segment(mUsername); } - const nsDependentCSubstring Password() { return Segment(mPassword); } - const nsDependentCSubstring Hostport(); // see below - const nsDependentCSubstring Host(); // see below - const nsDependentCSubstring Path() { return Segment(mPath); } - const nsDependentCSubstring Filepath() { return Segment(mFilepath); } - const nsDependentCSubstring Directory() { return Segment(mDirectory); } - const nsDependentCSubstring Filename(); // see below - const nsDependentCSubstring Basename() { return Segment(mBasename); } - const nsDependentCSubstring Extension() { return Segment(mExtension); } - const nsDependentCSubstring Query() { return Segment(mQuery); } - const nsDependentCSubstring Ref() { return Segment(mRef); } + nsDependentCSubstring Prepath(); // see below + nsDependentCSubstring Scheme() { return Segment(mScheme); } + nsDependentCSubstring Userpass(bool includeDelim = false); // see below + nsDependentCSubstring Username() { return Segment(mUsername); } + nsDependentCSubstring Password() { return Segment(mPassword); } + nsDependentCSubstring Hostport(); // see below + nsDependentCSubstring Host(); // see below + nsDependentCSubstring Path() { return Segment(mPath); } + nsDependentCSubstring Filepath() { return Segment(mFilepath); } + nsDependentCSubstring Directory() { return Segment(mDirectory); } + nsDependentCSubstring Filename(); // see below + nsDependentCSubstring Basename() { return Segment(mBasename); } + nsDependentCSubstring Extension() { return Segment(mExtension); } + nsDependentCSubstring Query() { return Segment(mQuery); } + nsDependentCSubstring Ref() { return Segment(mRef); } // shift the URLSegments to the right by diff void ShiftFromAuthority(int32_t diff); @@ -476,8 +476,7 @@ class nsStandardURL : public nsIFileURL, // Dependent substring getters //----------------------------------------------------------------------------- -inline const nsDependentCSubstring nsStandardURL::Segment(uint32_t pos, - int32_t len) { +inline nsDependentCSubstring nsStandardURL::Segment(uint32_t pos, int32_t len) { if (len < 0) { pos = 0; len = 0; @@ -485,13 +484,13 @@ inline const nsDependentCSubstring nsStandardURL::Segment(uint32_t pos, return Substring(mSpec, pos, uint32_t(len)); } -inline const nsDependentCSubstring nsStandardURL::Prepath() { +inline nsDependentCSubstring nsStandardURL::Prepath() { uint32_t len = 0; if (mAuthority.mLen >= 0) len = mAuthority.mPos + mAuthority.mLen; return Substring(mSpec, 0, len); } -inline const nsDependentCSubstring nsStandardURL::Userpass(bool includeDelim) { +inline nsDependentCSubstring nsStandardURL::Userpass(bool includeDelim) { uint32_t pos = 0, len = 0; if (mUsername.mLen > 0 || mPassword.mLen > 0) { if (mUsername.mLen > 0) { @@ -510,7 +509,7 @@ inline const nsDependentCSubstring nsStandardURL::Userpass(bool includeDelim) { return Substring(mSpec, pos, len); } -inline const nsDependentCSubstring nsStandardURL::Hostport() { +inline nsDependentCSubstring nsStandardURL::Hostport() { uint32_t pos = 0, len = 0; if (mAuthority.mLen > 0) { pos = mHost.mPos; @@ -519,7 +518,7 @@ inline const nsDependentCSubstring nsStandardURL::Hostport() { return Substring(mSpec, pos, len); } -inline const nsDependentCSubstring nsStandardURL::Host() { +inline nsDependentCSubstring nsStandardURL::Host() { uint32_t pos = 0, len = 0; if (mHost.mLen > 0) { pos = mHost.mPos; @@ -532,7 +531,7 @@ inline const nsDependentCSubstring nsStandardURL::Host() { return Substring(mSpec, pos, len); } -inline const nsDependentCSubstring nsStandardURL::Filename() { +inline nsDependentCSubstring nsStandardURL::Filename() { uint32_t pos = 0, len = 0; // if there is no basename, then there can be no extension if (mBasename.mLen > 0) { diff --git a/netwerk/base/nsStreamListenerTee.cpp b/netwerk/base/nsStreamListenerTee.cpp index 308b21e84121..0a6a78068f63 100644 --- a/netwerk/base/nsStreamListenerTee.cpp +++ b/netwerk/base/nsStreamListenerTee.cpp @@ -66,11 +66,12 @@ nsStreamListenerTee::OnDataAvailable(nsIRequest* request, nsIInputStream* input, nsresult rv; if (!mInputTee) { - if (mEventTarget) + if (mEventTarget) { rv = NS_NewInputStreamTeeAsync(getter_AddRefs(tee), input, mSink, mEventTarget); - else + } else { rv = NS_NewInputStreamTee(getter_AddRefs(tee), input, mSink); + } if (NS_FAILED(rv)) return rv; mInputTee = do_QueryInterface(tee, &rv); diff --git a/netwerk/base/nsStreamTransportService.cpp b/netwerk/base/nsStreamTransportService.cpp index 35c11f2a2244..d1e88eb253b3 100644 --- a/netwerk/base/nsStreamTransportService.cpp +++ b/netwerk/base/nsStreamTransportService.cpp @@ -145,9 +145,10 @@ nsInputStreamTransport::SetEventSink(nsITransportEventSink* sink, nsIEventTarget* target) { NS_ENSURE_TRUE(!mInProgress, NS_ERROR_IN_PROGRESS); - if (target) + if (target) { return net_NewTransportEventSinkProxy(getter_AddRefs(mEventSink), sink, target); + } mEventSink = sink; return NS_OK; @@ -175,8 +176,9 @@ nsInputStreamTransport::Read(char* buf, uint32_t count, uint32_t* result) { if (NS_SUCCEEDED(rv)) { mOffset += *result; - if (mEventSink) + if (mEventSink) { mEventSink->OnTransportStatus(this, NS_NET_STATUS_READING, mOffset, -1); + } } return rv; } diff --git a/netwerk/base/nsUDPSocket.cpp b/netwerk/base/nsUDPSocket.cpp index de279a7c4078..5497e9aeaa6a 100644 --- a/netwerk/base/nsUDPSocket.cpp +++ b/netwerk/base/nsUDPSocket.cpp @@ -37,7 +37,7 @@ static const uint32_t UDP_PACKET_CHUNK_SIZE = 1400; //----------------------------------------------------------------------------- -typedef void (nsUDPSocket::*nsUDPSocketFunc)(void); +using nsUDPSocketFunc = void (nsUDPSocket::*)(); static nsresult PostEvent(nsUDPSocket* s, nsUDPSocketFunc func) { if (!gSocketTransportService) return NS_ERROR_FAILURE; @@ -503,10 +503,11 @@ nsUDPSocket::Init(int32_t aPort, bool aLoopbackOnly, nsIPrincipal* aPrincipal, addr.raw.family = AF_INET; addr.inet.port = htons(aPort); - if (aLoopbackOnly) + if (aLoopbackOnly) { addr.inet.ip = htonl(INADDR_LOOPBACK); - else + } else { addr.inet.ip = htonl(INADDR_ANY); + } return InitWithAddress(&addr, aPrincipal, aAddressReuse, aOptionalArgc); } diff --git a/netwerk/base/nsURLHelper.cpp b/netwerk/base/nsURLHelper.cpp index 0c8f703328b4..3092f264a83c 100644 --- a/netwerk/base/nsURLHelper.cpp +++ b/netwerk/base/nsURLHelper.cpp @@ -187,13 +187,16 @@ nsresult net_ParseFileURL(const nsACString& inURL, nsACString& outDirectory, &extensionPos, &extensionLen); if (NS_FAILED(rv)) return rv; - if (directoryLen > 0) + if (directoryLen > 0) { outDirectory = Substring(inURL, filepathPos + directoryPos, directoryLen); - if (basenameLen > 0) + } + if (basenameLen > 0) { outFileBaseName = Substring(inURL, filepathPos + basenamePos, basenameLen); - if (extensionLen > 0) + } + if (extensionLen > 0) { outFileExtension = Substring(inURL, filepathPos + extensionPos, extensionLen); + } // since we are using a no-auth url parser, there will never be a host // XXX not strictly true... file://localhost/foo/bar.html is a valid URL @@ -225,10 +228,11 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path) { the path can begin // or /%2F to mark the root of the servers filesystem, a simple / only marks the root relative to the user loging in. We remember the length of the marker */ - if (nsCRT::strncasecmp(path, "/%2F", 4) == 0) + if (nsCRT::strncasecmp(path, "/%2F", 4) == 0) { special_ftp_len = 4; - else if (strncmp(path, "//", 2) == 0) + } else if (strncmp(path, "//", 2) == 0) { special_ftp_len = 2; + } } /* find the last slash before # or ? */ @@ -286,8 +290,9 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path) { // otherwise retain them in the path if (traversal > 0 || !(flags & NET_COALESCE_ALLOW_RELATIVE_ROOT)) { if (urlPtr != path) urlPtr--; // we must be going back at least by one - for (; *urlPtr != '/' && urlPtr != path; urlPtr--) - ; // null body + for (; *urlPtr != '/' && urlPtr != path; urlPtr--) { + ; // null body + } --traversal; // count back // forward the fwdPtr past the ../ fwdPtr += 2; @@ -312,10 +317,11 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path) { // /%2F and urlPtr just points at the "F" of "/%2F" then do // not overwrite it with the /, just copy .. and move forward // urlPtr. - if (special_ftp_len > 3 && urlPtr == path + special_ftp_len - 1) + if (special_ftp_len > 3 && urlPtr == path + special_ftp_len - 1) { ++urlPtr; - else + } else { *urlPtr++ = *fwdPtr; + } ++fwdPtr; *urlPtr++ = *fwdPtr; ++fwdPtr; @@ -325,8 +331,9 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path) { // count the hierachie, but only if we do not have reached // the root of some special urls with a special root marker if (*fwdPtr == '/' && *(fwdPtr + 1) != '.' && - (special_ftp_len != 2 || *(fwdPtr + 1) != '/')) + (special_ftp_len != 2 || *(fwdPtr + 1) != '/')) { traversal++; + } // copy the url incrementaly *urlPtr++ = *fwdPtr; } @@ -337,8 +344,10 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path) { * /foo/foo1/. -> /foo/foo1/ */ - if ((urlPtr > (path + 1)) && (*(urlPtr - 1) == '.') && (*(urlPtr - 2) == '/')) + if ((urlPtr > (path + 1)) && (*(urlPtr - 1) == '.') && + (*(urlPtr - 2) == '/')) { urlPtr--; + } // Copy remaining stuff past the #?; for (; *fwdPtr != '\0'; ++fwdPtr) { @@ -437,13 +446,13 @@ bool net_IsAbsoluteURL(const nsACString& uri) { void net_FilterURIString(const nsACString& input, nsACString& result) { result.Truncate(); - auto start = input.BeginReading(); - auto end = input.EndReading(); + const auto* start = input.BeginReading(); + const auto* end = input.EndReading(); // Trim off leading and trailing invalid chars. auto charFilter = [](char c) { return static_cast(c) > 0x20; }; - auto newStart = std::find_if(start, end, charFilter); - auto newEnd = + const auto* newStart = std::find_if(start, end, charFilter); + const auto* newEnd = std::find_if(std::reverse_iterator(end), std::reverse_iterator(newStart), charFilter) @@ -452,7 +461,7 @@ void net_FilterURIString(const nsACString& input, nsACString& result) { // Check if chars need to be stripped. bool needsStrip = false; const ASCIIMaskArray& mask = ASCIIMask::MaskCRLFTab(); - for (auto itr = start; itr != end; ++itr) { + for (const auto* itr = start; itr != end; ++itr) { if (ASCIIMask::IsMasked(mask, *itr)) { needsStrip = true; break; @@ -477,13 +486,13 @@ nsresult net_FilterAndEscapeURI(const nsACString& aInput, uint32_t aFlags, nsACString& aResult) { aResult.Truncate(); - auto start = aInput.BeginReading(); - auto end = aInput.EndReading(); + const auto* start = aInput.BeginReading(); + const auto* end = aInput.EndReading(); // Trim off leading and trailing invalid chars. auto charFilter = [](char c) { return static_cast(c) > 0x20; }; - auto newStart = std::find_if(start, end, charFilter); - auto newEnd = + const auto* newStart = std::find_if(start, end, charFilter); + const auto* newEnd = std::find_if(std::reverse_iterator(end), std::reverse_iterator(newStart), charFilter) @@ -886,8 +895,9 @@ bool net_IsValidHostName(const nsACString& host) { if (net_FindCharNotInSet(host.BeginReading(), end, "abcdefghijklmnopqrstuvwxyz" ".-0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ$+_") == end) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ$+_") == end) { return true; + } // Might be a valid IPv6 link-local address containing a percent sign return mozilla::net::HostIsIPLiteral(host); diff --git a/netwerk/base/nsURLHelper.h b/netwerk/base/nsURLHelper.h index af37936e1b72..effe323ea1d9 100644 --- a/netwerk/base/nsURLHelper.h +++ b/netwerk/base/nsURLHelper.h @@ -68,7 +68,7 @@ void net_CoalesceDirs(netCoalesceFlags flags, char* path); * @param inURL URL spec * @return true if the given spec represents an absolute URL */ -bool net_IsAbsoluteURL(const nsACString& inURL); +bool net_IsAbsoluteURL(const nsACString& uri); /** * Extract URI-Scheme if possible @@ -137,7 +137,7 @@ void net_ToLowerCase(char* str); * then |end| is returned. stops prematurely if a null byte is encountered, * and returns the address of the null byte. */ -char* net_FindCharInSet(const char* str, const char* end, const char* set); +char* net_FindCharInSet(const char* iter, const char* stop, const char* set); /** * returns pointer to first character of |str| NOT in the given set. if all @@ -145,13 +145,14 @@ char* net_FindCharInSet(const char* str, const char* end, const char* set); * included in |set|, then stops prematurely if a null byte is encountered, * and returns the address of the null byte. */ -char* net_FindCharNotInSet(const char* str, const char* end, const char* set); +char* net_FindCharNotInSet(const char* iter, const char* stop, const char* set); /** * returns pointer to last character of |str| NOT in the given set. if all * characters are in the given set, then |str - 1| is returned. */ -char* net_RFindCharNotInSet(const char* str, const char* end, const char* set); +char* net_RFindCharNotInSet(const char* stop, const char* iter, + const char* set); /** * Parses a content-type header and returns the content type and diff --git a/netwerk/base/nsURLHelperUnix.cpp b/netwerk/base/nsURLHelperUnix.cpp index c1eeb36e0b3f..abb8b0cfeb54 100644 --- a/netwerk/base/nsURLHelperUnix.cpp +++ b/netwerk/base/nsURLHelperUnix.cpp @@ -26,19 +26,21 @@ nsresult net_GetURLSpecFromActualFile(nsIFile* aFile, nsACString& result) { NS_CopyUnicodeToNative(path, ePath); // Use UTF8 version if conversion was successful - if (nativePath == ePath) + if (nativePath == ePath) { CopyUTF16toUTF8(path, ePath); - else + } else { ePath = nativePath; + } nsAutoCString escPath; constexpr auto prefix = "file://"_ns; // Escape the path with the directory mask - if (NS_EscapeURL(ePath.get(), -1, esc_Directory + esc_Forced, escPath)) + if (NS_EscapeURL(ePath.get(), -1, esc_Directory + esc_Forced, escPath)) { escPath.Insert(prefix, 0); - else + } else { escPath.Assign(prefix + ePath); + } // esc_Directory does not escape the semicolons, so if a filename // contains semicolons we need to manually escape them. @@ -86,17 +88,19 @@ nsresult net_GetFileFromURLSpec(const nsACString& aURL, nsIFile** result) { if (IsUtf8(path)) { // speed up the start-up where UTF-8 is the native charset // (e.g. on recent Linux distributions) - if (NS_IsNativeUTF8()) + if (NS_IsNativeUTF8()) { rv = localFile->InitWithNativePath(path); - else + } else { rv = localFile->InitWithPath(NS_ConvertUTF8toUTF16(path)); + } // XXX In rare cases, a valid UTF-8 string can be valid as a native // encoding (e.g. 0xC5 0x83 is valid both as UTF-8 and Windows-125x). // However, the chance is very low that a meaningful word in a legacy // encoding is valid as UTF-8. - } else + } else { // if path is not in UTF-8, assume it is encoded in the native charset rv = localFile->InitWithNativePath(path); + } if (NS_FAILED(rv)) return rv; diff --git a/netwerk/base/nsURLParsers.cpp b/netwerk/base/nsURLParsers.cpp index 2ed642230d8d..618222de421b 100644 --- a/netwerk/base/nsURLParsers.cpp +++ b/netwerk/base/nsURLParsers.cpp @@ -37,9 +37,9 @@ NS_IMPL_ISUPPORTS(nsNoAuthURLParser, nsIURLParser) if (component##Len) *component##Len = int32_t(len); \ PR_END_MACRO -#define OFFSET_RESULT(component, offset) \ - PR_BEGIN_MACRO \ - if (component##Pos) *component##Pos += offset; \ +#define OFFSET_RESULT(component, offset) \ + PR_BEGIN_MACRO \ + if (component##Pos) *component##Pos += (offset); \ PR_END_MACRO NS_IMETHODIMP @@ -98,8 +98,9 @@ nsBaseURLParser::ParseURL(const char* spec, int32_t specLen, } // ignore trailing whitespace and control characters - for (p = spec + specLen - 1; ((unsigned char)*p <= ' ') && (p != spec); --p) + for (p = spec + specLen - 1; ((unsigned char)*p <= ' ') && (p != spec); --p) { ; + } specLen = p - spec + 1; @@ -209,9 +210,9 @@ nsBaseURLParser::ParsePath(const char* path, int32_t pathLen, const char* p = nullptr; for (p = path; p < path + pathLen; ++p) { // only match the query string if it precedes the reference fragment - if (!ref_beg && !query_beg && *p == '?') + if (!ref_beg && !query_beg && *p == '?') { query_beg = p + 1; - else if (*p == '#') { + } else if (*p == '#') { ref_beg = p + 1; if (query_beg) query_end = p; break; @@ -219,31 +220,36 @@ nsBaseURLParser::ParsePath(const char* path, int32_t pathLen, } if (query_beg) { - if (query_end) + if (query_end) { SET_RESULT(query, query_beg - path, query_end - query_beg); - else + } else { SET_RESULT(query, query_beg - path, pathLen - (query_beg - path)); - } else + } + } else { SET_RESULT(query, 0, -1); + } - if (ref_beg) + if (ref_beg) { SET_RESULT(ref, ref_beg - path, pathLen - (ref_beg - path)); - else + } else { SET_RESULT(ref, 0, -1); + } const char* end; - if (query_beg) + if (query_beg) { end = query_beg - 1; - else if (ref_beg) + } else if (ref_beg) { end = ref_beg - 1; - else + } else { end = path + pathLen; + } // an empty file path is no file path - if (end != path) + if (end != path) { SET_RESULT(filepath, 0, end - path); - else + } else { SET_RESULT(filepath, 0, -1); + } return NS_OK; } @@ -269,13 +275,15 @@ nsBaseURLParser::ParseFilePath(const char* filepath, int32_t filepathLen, const char* end = filepath + filepathLen; // search backwards for filename - for (p = end - 1; *p != '/' && p > filepath; --p) + for (p = end - 1; *p != '/' && p > filepath; --p) { ; + } if (*p == '/') { // catch /.. and /. if ((p + 1 < end && *(p + 1) == '.') && - (p + 2 == end || (*(p + 2) == '.' && p + 3 == end))) + (p + 2 == end || (*(p + 2) == '.' && p + 3 == end))) { p = end - 1; + } // filepath = . SET_RESULT(directory, 0, p - filepath + 1); ParseFileName(p + 1, end - (p + 1), basenamePos, basenameLen, extensionPos, @@ -365,10 +373,11 @@ void nsNoAuthURLParser::ParseAfterScheme(const char* spec, int32_t specLen, } } SET_RESULT(auth, 0, -1); - if (p && p != spec + specLen) + if (p && p != spec + specLen) { SET_RESULT(path, p - spec, specLen - (p - spec)); - else + } else { SET_RESULT(path, 0, -1); + } return; } default: @@ -547,8 +556,9 @@ nsAuthURLParser::ParseServerInfo(const char* serverinfo, int32_t serverinfoLen, nsresult err; *port = buf.ToInteger(&err); if (NS_FAILED(err) || *port < 0 || - *port > std::numeric_limits::max()) + *port > std::numeric_limits::max()) { return NS_ERROR_MALFORMED_URI; + } } } } else { @@ -561,8 +571,9 @@ nsAuthURLParser::ParseServerInfo(const char* serverinfo, int32_t serverinfoLen, if (*hostnameLen > 1 && *(serverinfo + *hostnamePos) == '[' && *(serverinfo + *hostnamePos + *hostnameLen - 1) == ']' && !net_IsValidIPv6Addr( - Substring(serverinfo + *hostnamePos + 1, *hostnameLen - 2))) + Substring(serverinfo + *hostnamePos + 1, *hostnameLen - 2))) { return NS_ERROR_MALFORMED_URI; + } return NS_OK; } diff --git a/netwerk/build/nsNetModule.cpp b/netwerk/build/nsNetModule.cpp index 347e2a18a3fd..f10645becf7d 100644 --- a/netwerk/build/nsNetModule.cpp +++ b/netwerk/build/nsNetModule.cpp @@ -33,14 +33,14 @@ using namespace mozilla; -typedef nsCategoryCache ContentSnifferCache; +using ContentSnifferCache = nsCategoryCache; ContentSnifferCache* gNetSniffers = nullptr; ContentSnifferCache* gDataSniffers = nullptr; ContentSnifferCache* gORBSniffers = nullptr; ContentSnifferCache* gNetAndORBSniffers = nullptr; #define static -typedef mozilla::net::nsLoadGroup nsLoadGroup; +using nsLoadGroup = mozilla::net::nsLoadGroup; NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsLoadGroup, Init) #undef static diff --git a/netwerk/cache/nsDeleteDir.cpp b/netwerk/cache/nsDeleteDir.cpp index f99896b721e5..8b306335bb3c 100644 --- a/netwerk/cache/nsDeleteDir.cpp +++ b/netwerk/cache/nsDeleteDir.cpp @@ -97,8 +97,9 @@ nsresult nsDeleteDir::Shutdown(bool finishDeleting) { delete gInstance; - for (int32_t i = 0; i < dirsToRemove.Count(); i++) + for (int32_t i = 0; i < dirsToRemove.Count(); i++) { dirsToRemove[i]->Remove(true); + } return NS_OK; } @@ -119,9 +120,10 @@ nsresult nsDeleteDir::InitThread() { void nsDeleteDir::DestroyThread() { if (!mBackgroundET) return; - if (mTimers.Count()) + if (mTimers.Count()) { // more work to do, so don't delete thread. return; + } mBackgroundET = nullptr; } diff --git a/netwerk/cache/nsDeleteDir.h b/netwerk/cache/nsDeleteDir.h index cf6de26ddee5..7487d1ba8dad 100644 --- a/netwerk/cache/nsDeleteDir.h +++ b/netwerk/cache/nsDeleteDir.h @@ -47,7 +47,7 @@ class nsDeleteDir { /** * Returns the trash directory corresponding to the given directory. */ - static nsresult GetTrashDir(nsIFile* dir, nsCOMPtr* result); + static nsresult GetTrashDir(nsIFile* target, nsCOMPtr* result); /** * Remove all trashes left from previous run. This function does nothing when diff --git a/netwerk/cache2/CacheEntry.cpp b/netwerk/cache2/CacheEntry.cpp index b63b6e5e0965..ce502c51e07f 100644 --- a/netwerk/cache2/CacheEntry.cpp +++ b/netwerk/cache2/CacheEntry.cpp @@ -30,8 +30,7 @@ #include #include -namespace mozilla { -namespace net { +namespace mozilla::net { static uint32_t const ENTRY_WANTED = nsICacheEntryOpenCallback::ENTRY_WANTED; static uint32_t const RECHECK_AFTER_WRITE_FINISHED = @@ -114,8 +113,8 @@ CacheEntry::Callback::Callback(CacheEntry* aEntry, mRecheckAfterWrite(false), mNotWanted(false), mSecret(false), - mDoomWhenFoundPinned(aDoomWhenFoundInPinStatus == true), - mDoomWhenFoundNonPinned(aDoomWhenFoundInPinStatus == false) { + mDoomWhenFoundPinned(aDoomWhenFoundInPinStatus), + mDoomWhenFoundNonPinned(!aDoomWhenFoundInPinStatus) { MOZ_COUNT_CTOR(CacheEntry::Callback); MOZ_ASSERT(mEntry->HandlesCount()); mEntry->AddHandleRef(); @@ -572,16 +571,18 @@ void CacheEntry::TransferCallbacks(CacheEntry& aFromEntry) { LOG(("CacheEntry::TransferCallbacks [entry=%p, from=%p]", this, &aFromEntry)); - if (!mCallbacks.Length()) + if (!mCallbacks.Length()) { mCallbacks.SwapElements(aFromEntry.mCallbacks); - else + } else { mCallbacks.AppendElements(aFromEntry.mCallbacks); + } uint32_t callbacksLength = mCallbacks.Length(); if (callbacksLength) { // Carry the entry reference (unfortunately, needs to be done manually...) - for (uint32_t i = 0; i < callbacksLength; ++i) + for (uint32_t i = 0; i < callbacksLength; ++i) { mCallbacks[i].ExchangeEntry(this); + } BackgroundOp(Ops::CALLBACKS, true); } @@ -1396,8 +1397,9 @@ nsresult CacheEntry::AsyncDoom(nsICacheEntryDoomCallback* aCallback) { { mozilla::MutexAutoLock lock(mLock); - if (mIsDoomed || mDoomCallback) + if (mIsDoomed || mDoomCallback) { return NS_ERROR_IN_PROGRESS; // to aggregate have DOOMING state + } RemoveForcedValidity(); @@ -1790,8 +1792,9 @@ void CacheEntry::BackgroundOp(uint32_t aOperations, bool aForceAsync) { mLock.AssertCurrentThreadOwns(); if (!CacheStorageService::IsOnManagementThread() || aForceAsync) { - if (mBackgroundOperations.Set(aOperations)) + if (mBackgroundOperations.Set(aOperations)) { CacheStorageService::Self()->Dispatch(this); + } LOG(("CacheEntry::BackgroundOp this=%p dipatch of %x", this, aOperations)); return; @@ -1910,5 +1913,4 @@ size_t CacheEntry::SizeOfIncludingThis( return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheEntry.h b/netwerk/cache2/CacheEntry.h index 52212faae24e..08129c1c723b 100644 --- a/netwerk/cache2/CacheEntry.h +++ b/netwerk/cache2/CacheEntry.h @@ -62,14 +62,14 @@ class CacheEntry final : public nsIRunnable, public CacheFileListener { // Forwarded to from CacheEntryHandle : nsICacheEntry nsresult GetKey(nsACString& aKey); nsresult GetCacheEntryId(uint64_t* aCacheEntryId); - nsresult GetPersistent(bool* aPersistent); + nsresult GetPersistent(bool* aPersistToDisk); nsresult GetFetchCount(int32_t* aFetchCount); nsresult GetLastFetched(uint32_t* aLastFetched); nsresult GetLastModified(uint32_t* aLastModified); nsresult GetExpirationTime(uint32_t* aExpirationTime); nsresult SetExpirationTime(uint32_t expirationTime); - nsresult GetOnStartTime(uint64_t* aOnStartTime); - nsresult GetOnStopTime(uint64_t* aOnStopTime); + nsresult GetOnStartTime(uint64_t* aTime); + nsresult GetOnStopTime(uint64_t* aTime); nsresult SetNetworkTimes(uint64_t onStartTime, uint64_t onStopTime); nsresult SetContentType(uint8_t aContentType); nsresult ForceValidFor(uint32_t aSecondsToTheFuture); @@ -80,8 +80,8 @@ class CacheEntry final : public nsIRunnable, public CacheFileListener { nsresult GetSecurityInfo(nsISupports** aSecurityInfo); nsresult SetSecurityInfo(nsISupports* aSecurityInfo); nsresult GetStorageDataSize(uint32_t* aStorageDataSize); - nsresult AsyncDoom(nsICacheEntryDoomCallback* listener); - nsresult GetMetaDataElement(const char* key, char** _retval); + nsresult AsyncDoom(nsICacheEntryDoomCallback* aCallback); + nsresult GetMetaDataElement(const char* key, char** aRetval); nsresult SetMetaDataElement(const char* key, const char* value); nsresult VisitMetaData(nsICacheEntryMetaDataVisitor* visitor); nsresult MetaDataReady(void); @@ -89,18 +89,18 @@ class CacheEntry final : public nsIRunnable, public CacheFileListener { nsresult GetDiskStorageSizeInKB(uint32_t* aDiskStorageSizeInKB); nsresult Recreate(bool aMemoryOnly, nsICacheEntry** _retval); nsresult GetDataSize(int64_t* aDataSize); - nsresult GetAltDataSize(int64_t* aAltDataSize); + nsresult GetAltDataSize(int64_t* aDataSize); nsresult GetAltDataType(nsACString& aAltDataType); nsresult OpenAlternativeOutputStream(const nsACString& type, int64_t predictedSize, nsIAsyncOutputStream** _retval); nsresult OpenAlternativeInputStream(const nsACString& type, nsIInputStream** _retval); - nsresult GetLoadContextInfo(nsILoadContextInfo** aLoadContextInfo); + nsresult GetLoadContextInfo(nsILoadContextInfo** aInfo); nsresult Close(void); nsresult MarkValid(void); nsresult MaybeMarkValid(void); - nsresult HasWriteAccess(bool aWriteAllowed, bool* _retval); + nsresult HasWriteAccess(bool aWriteAllowed, bool* aWriteAccess); public: uint32_t GetMetadataMemoryConsumption(); diff --git a/netwerk/cache2/CacheFile.cpp b/netwerk/cache2/CacheFile.cpp index 2c0db9693c80..a6a8667a994f 100644 --- a/netwerk/cache2/CacheFile.cpp +++ b/netwerk/cache2/CacheFile.cpp @@ -30,8 +30,7 @@ //#define CACHE_CHUNKS -namespace mozilla { -namespace net { +namespace mozilla::net { class NotifyCacheFileListenerEvent : public Runnable { public: @@ -1171,9 +1170,10 @@ nsresult CacheFile::SetFrecency(uint32_t aFrecency) { PostWriteTimer(); - if (mHandle && !mHandle->IsDoomed()) + if (mHandle && !mHandle->IsDoomed()) { CacheFileIOManager::UpdateIndexEntry(mHandle, &aFrecency, nullptr, nullptr, nullptr, nullptr); + } mMetadata->SetFrecency(aFrecency); return NS_OK; @@ -1504,7 +1504,8 @@ nsresult CacheFile::GetChunkLocked(uint32_t aIndex, ECallerType aCaller, } return NS_OK; - } else if (off == mDataSize) { + } + if (off == mDataSize) { if (aCaller == WRITER) { // this listener is going to write to the chunk chunk = new CacheFileChunk(this, aIndex, true); @@ -2074,7 +2075,7 @@ void CacheFile::RemoveInput(CacheFileInputStream* aInput, nsresult aStatus) { LOG(("CacheFile::RemoveInput() [this=%p, input=%p, status=0x%08" PRIx32 "]", this, aInput, static_cast(aStatus))); - DebugOnly found; + DebugOnly found{}; found = mInputs.RemoveElement(aInput); MOZ_ASSERT(found); @@ -2241,7 +2242,7 @@ void CacheFile::NotifyListenersAboutOutputRemoval() { // First fail all chunk listeners that wait for non-existent chunk for (auto iter = mChunkListeners.Iter(); !iter.Done(); iter.Next()) { uint32_t idx = iter.Key(); - auto listeners = iter.UserData(); + auto* listeners = iter.UserData(); LOG( ("CacheFile::NotifyListenersAboutOutputRemoval() - fail " @@ -2360,11 +2361,7 @@ bool CacheFile::EntryWouldExceedLimit(int64_t aOffset, int64_t aSize, totalSize += (mAltDataOffset == -1) ? mDataSize : mAltDataOffset; } - if (CacheObserver::EntryIsTooBig(totalSize, !mMemoryOnly)) { - return true; - } - - return false; + return CacheObserver::EntryIsTooBig(totalSize, !mMemoryOnly); } bool CacheFile::IsDirty() { return mDataIsDirty || mMetadata->IsDirty(); } @@ -2396,8 +2393,9 @@ void CacheFile::WriteMetadataIfNeededLocked(bool aFireAndForget) { if (NS_FAILED(mStatus)) return; if (!IsDirty() || mOutput || mInputs.Length() || mChunks.Count() || - mWritingMetadata || mOpeningFile || mKill) + mWritingMetadata || mOpeningFile || mKill) { return; + } if (!aFireAndForget) { // if aFireAndForget is set, we are called from dtor. Write @@ -2507,7 +2505,7 @@ nsresult CacheFile::InitIndexEntry() { uint32_t frecency = mMetadata->GetFrecency(); bool hasAltData = - mMetadata->GetElement(CacheFileUtils::kAltDataKey) ? true : false; + mMetadata->GetElement(CacheFileUtils::kAltDataKey) != nullptr; static auto toUint16 = [](const char* s) -> uint16_t { if (s) { @@ -2590,5 +2588,4 @@ size_t CacheFile::SizeOfIncludingThis( return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileChunk.cpp b/netwerk/cache2/CacheFileChunk.cpp index faf8b9c78c80..ca952a0058a6 100644 --- a/netwerk/cache2/CacheFileChunk.cpp +++ b/netwerk/cache2/CacheFileChunk.cpp @@ -10,8 +10,7 @@ #include "mozilla/IntegerPrintfMacros.h" -namespace mozilla { -namespace net { +namespace mozilla::net { #define kMinBufSize 512 @@ -836,5 +835,4 @@ mozilla::Atomic& CacheFileChunk::ChunksMemoryUsage() return mIsPriority ? prioChunksMemoryUsage : chunksMemoryUsage; } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileChunk.h b/netwerk/cache2/CacheFileChunk.h index ea82fb377318..4d20bf19eb27 100644 --- a/netwerk/cache2/CacheFileChunk.h +++ b/netwerk/cache2/CacheFileChunk.h @@ -27,7 +27,7 @@ class CacheFileChunkBuffer { explicit CacheFileChunkBuffer(CacheFileChunk* aChunk); - nsresult EnsureBufSize(uint32_t aSize); + nsresult EnsureBufSize(uint32_t aBufSize); void CopyFrom(CacheFileChunkBuffer* aOther); nsresult FillInvalidRanges(CacheFileChunkBuffer* aOther, CacheFileUtils::ValidityMap* aMap); diff --git a/netwerk/cache2/CacheFileContextEvictor.cpp b/netwerk/cache2/CacheFileContextEvictor.cpp index 852db6103cec..c8be80ba9db8 100644 --- a/netwerk/cache2/CacheFileContextEvictor.cpp +++ b/netwerk/cache2/CacheFileContextEvictor.cpp @@ -20,8 +20,7 @@ #include "nsContentUtils.h" #include "nsNetUtil.h" -namespace mozilla { -namespace net { +namespace mozilla::net { #define CONTEXT_EVICTION_PREFIX "ce_" const uint32_t kContextEvictionPrefixLength = @@ -609,7 +608,8 @@ void CacheFileContextEvictor::EvictEntries() { mEntries[0]->mOrigin); mEntries.RemoveElementAt(0); continue; - } else if (NS_FAILED(rv)) { + } + if (NS_FAILED(rv)) { LOG( ("CacheFileContextEvictor::EvictEntries() - Iterator failed to " "provide next hash (shutdown?), keeping eviction info on disk." @@ -739,5 +739,4 @@ void CacheFileContextEvictor::EvictEntries() { MOZ_ASSERT_UNREACHABLE("We should never get here"); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileContextEvictor.h b/netwerk/cache2/CacheFileContextEvictor.h index 387f9ea6e4de..28300a562755 100644 --- a/netwerk/cache2/CacheFileContextEvictor.h +++ b/netwerk/cache2/CacheFileContextEvictor.h @@ -20,9 +20,9 @@ class CacheIndexIterator; struct CacheFileContextEvictorEntry { nsCOMPtr mInfo; - bool mPinned; - nsString mOrigin; // it can be empty - PRTime mTimeStamp; // in milliseconds + bool mPinned = false; + nsString mOrigin; // it can be empty + PRTime mTimeStamp = 0; // in milliseconds RefPtr mIterator; }; diff --git a/netwerk/cache2/CacheFileIOManager.cpp b/netwerk/cache2/CacheFileIOManager.cpp index 949581cf26db..b3482fbdcd2b 100644 --- a/netwerk/cache2/CacheFileIOManager.cpp +++ b/netwerk/cache2/CacheFileIOManager.cpp @@ -41,8 +41,7 @@ // XXX add necessary include file for ftruncate (or equivalent) #endif -namespace mozilla { -namespace net { +namespace mozilla::net { #define kOpenHandlesLimit 128 #define kMetadataWriteDelay 5000 @@ -70,11 +69,7 @@ bool CacheFileHandle::DispatchRelease() { NewNonOwningRunnableMethod("net::CacheFileHandle::Release", this, &CacheFileHandle::Release), nsIEventTarget::DISPATCH_NORMAL); - if (NS_FAILED(rv)) { - return false; - } - - return true; + return NS_SUCCEEDED(rv); } NS_IMPL_ADDREF(CacheFileHandle) @@ -269,7 +264,7 @@ void CacheFileHandles::HandleHashKey::AddHandle(CacheFileHandle* aHandle) { void CacheFileHandles::HandleHashKey::RemoveHandle(CacheFileHandle* aHandle) { MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); - DebugOnly found; + DebugOnly found{}; found = mHandles.RemoveElement(aHandle); MOZ_ASSERT(found); } @@ -287,7 +282,7 @@ CacheFileHandles::HandleHashKey::GetNewestHandle() { } void CacheFileHandles::HandleHashKey::GetHandles( - nsTArray >& aResult) { + nsTArray>& aResult) { MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); for (uint32_t i = 0; i < mHandles.Length(); ++i) { @@ -465,7 +460,7 @@ void CacheFileHandles::RemoveHandle(CacheFileHandle* aHandle) { } void CacheFileHandles::GetAllHandles( - nsTArray >* _retval) { + nsTArray>* _retval) { MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) { iter.Get()->GetHandles(*_retval); @@ -473,7 +468,7 @@ void CacheFileHandles::GetAllHandles( } void CacheFileHandles::GetActiveHandles( - nsTArray >* _retval) { + nsTArray>* _retval) { MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) { RefPtr handle = iter.Get()->GetNewestHandle(); @@ -496,7 +491,7 @@ uint32_t CacheFileHandles::HandleCount() { return mTable.Count(); } void CacheFileHandles::Log(CacheFileHandlesEntry* entry) { LOG(("CacheFileHandles::Log() BEGIN [entry=%p]", entry)); - nsTArray > array; + nsTArray> array; aEntry->GetHandles(array); for (uint32_t i = 0; i < array.Length(); ++i) { @@ -597,7 +592,7 @@ class IOPerfReportEvent { // average value. Do not add the value to the filtered stats when the event // had to wait in a long queue. uint32_t eventCounter = aIOThread->EventCounter(); - bool shortOnly = eventCounter - mEventCounter < 5 ? false : true; + bool shortOnly = eventCounter - mEventCounter >= 5; CacheFileUtils::CachePerfStats::AddValue(mType, duration, shortOnly); } @@ -662,7 +657,7 @@ class OpenFileEvent : public Runnable, public IOPerfReportEvent { } protected: - SHA1Sum::Hash mHash; + SHA1Sum::Hash mHash{}; uint32_t mFlags; nsCOMPtr mCallback; RefPtr mIOMan; @@ -850,7 +845,7 @@ class DoomFileByKeyEvent : public Runnable { } protected: - SHA1Sum::Hash mHash; + SHA1Sum::Hash mHash{}; nsCOMPtr mCallback; RefPtr mIOMan; }; @@ -1209,7 +1204,7 @@ void CacheFileIOManager::ShutdownInternal() { } // close all handles and delete all associated files - nsTArray > handles; + nsTArray> handles; mHandles.GetAllHandles(&handles); handles.AppendElements(mSpecialHandles); @@ -1422,7 +1417,7 @@ nsresult CacheFileIOManager::ScheduleMetadataWriteInternal(CacheFile* aFile) { } if (mScheduledMetadataWrites.IndexOf(aFile) != - mScheduledMetadataWrites.NoIndex) { + nsTArray>::NoIndex) { return NS_OK; } @@ -1471,7 +1466,7 @@ nsresult CacheFileIOManager::ShutdownMetadataWriteScheduling() { void CacheFileIOManager::ShutdownMetadataWriteSchedulingInternal() { MOZ_ASSERT(IsOnIOThreadOrCeased()); - nsTArray > files = std::move(mScheduledMetadataWrites); + nsTArray> files = std::move(mScheduledMetadataWrites); for (uint32_t i = 0; i < files.Length(); ++i) { CacheFile* file = files[i]; file->WriteMetadataIfNeeded(); @@ -1490,7 +1485,7 @@ CacheFileIOManager::Notify(nsITimer* aTimer) { mMetadataWritesTimer = nullptr; - nsTArray > files = std::move(mScheduledMetadataWrites); + nsTArray> files = std::move(mScheduledMetadataWrites); for (uint32_t i = 0; i < files.Length(); ++i) { CacheFile* file = files[i]; file->WriteMetadataIfNeeded(); @@ -2295,7 +2290,7 @@ nsresult CacheFileIOManager::MaybeReleaseNSPRHandleInternal( MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); if (aHandle->mFD) { - DebugOnly found; + DebugOnly found{}; found = mHandlesByLastUsed.RemoveElement(aHandle); MOZ_ASSERT(found); } @@ -2965,7 +2960,7 @@ nsresult CacheFileIOManager::EvictAllInternal() { } // Doom all active handles - nsTArray > handles; + nsTArray> handles; mHandles.GetActiveHandles(&handles); for (uint32_t i = 0; i < handles.Length(); ++i) { @@ -3087,7 +3082,7 @@ nsresult CacheFileIOManager::EvictByContextInternal( NS_ConvertUTF16toUTF8 origin(aOrigin); // Doom all active handles that matches the load context - nsTArray > handles; + nsTArray> handles; mHandles.GetActiveHandles(&handles); for (uint32_t i = 0; i < handles.Length(); ++i) { @@ -3928,7 +3923,7 @@ void CacheFileIOManager::NSPRHandleUsed(CacheFileHandle* aHandle) { MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased()); MOZ_ASSERT(aHandle->mFD); - DebugOnly found; + DebugOnly found{}; found = mHandlesByLastUsed.RemoveElement(aHandle); MOZ_ASSERT(found); @@ -4221,5 +4216,4 @@ size_t CacheFileIOManager::SizeOfIncludingThis( return mallocSizeOf(gInstance) + SizeOfExcludingThis(mallocSizeOf); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileIOManager.h b/netwerk/cache2/CacheFileIOManager.h index 579e58e3284d..cc19b74e64a9 100644 --- a/netwerk/cache2/CacheFileIOManager.h +++ b/netwerk/cache2/CacheFileIOManager.h @@ -139,7 +139,7 @@ class CacheFileHandles { already_AddRefed NewHandle(const SHA1Sum::Hash*, bool aPriority, CacheFileHandle::PinningStatus); - void RemoveHandle(CacheFileHandle* aHandlle); + void RemoveHandle(CacheFileHandle* aHandle); void GetAllHandles(nsTArray >* _retval); void GetActiveHandles(nsTArray >* _retval); void ClearAll(); @@ -155,8 +155,8 @@ class CacheFileHandles { class HandleHashKey : public PLDHashEntryHdr { public: - typedef const SHA1Sum::Hash& KeyType; - typedef const SHA1Sum::Hash* KeyTypePointer; + using KeyType = const SHA1Sum::Hash&; + using KeyTypePointer = const SHA1Sum::Hash*; explicit HandleHashKey(KeyTypePointer aKey) { MOZ_COUNT_CTOR(HandleHashKey); @@ -316,7 +316,7 @@ class CacheFileIOManager final : public nsITimerCallback, public nsINamed { static nsresult EvictIfOverLimit(); static nsresult EvictAll(); static nsresult EvictByContext(nsILoadContextInfo* aLoadContextInfo, - bool aPinning, const nsAString& aOrigin); + bool aPinned, const nsAString& aOrigin); static nsresult InitIndexEntry(CacheFileHandle* aHandle, OriginAttrsHash aOriginAttrsHash, @@ -384,7 +384,7 @@ class CacheFileIOManager final : public nsITimerCallback, public nsINamed { bool aTruncate); nsresult DoomFileInternal( CacheFileHandle* aHandle, - PinningDoomRestriction aPinningStatusRestriction = NO_RESTRICTION); + PinningDoomRestriction aPinningDoomRestriction = NO_RESTRICTION); nsresult DoomFileByKeyInternal(const SHA1Sum::Hash* aHash); nsresult MaybeReleaseNSPRHandleInternal(CacheFileHandle* aHandle, bool aIgnoreShutdownLag = false); @@ -396,7 +396,7 @@ class CacheFileIOManager final : public nsITimerCallback, public nsINamed { nsresult OverLimitEvictionInternal(); nsresult EvictAllInternal(); nsresult EvictByContextInternal(nsILoadContextInfo* aLoadContextInfo, - bool aPinning, const nsAString& aOrigin); + bool aPinned, const nsAString& aOrigin); nsresult TrashDirectory(nsIFile* aFile); static void OnTrashTimer(nsITimer* aTimer, void* aClosure); diff --git a/netwerk/cache2/CacheFileInputStream.cpp b/netwerk/cache2/CacheFileInputStream.cpp index dc6d0208e63d..c034cb27ed75 100644 --- a/netwerk/cache2/CacheFileInputStream.cpp +++ b/netwerk/cache2/CacheFileInputStream.cpp @@ -10,8 +10,7 @@ #include "nsThreadUtils.h" #include -namespace mozilla { -namespace net { +namespace mozilla::net { NS_IMPL_ADDREF(CacheFileInputStream) NS_IMETHODIMP_(MozExternalRefCountType) @@ -715,5 +714,4 @@ size_t CacheFileInputStream::SizeOfIncludingThis( return mallocSizeOf(this); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileMetadata.cpp b/netwerk/cache2/CacheFileMetadata.cpp index 738a1e9f49e6..1629f305e821 100644 --- a/netwerk/cache2/CacheFileMetadata.cpp +++ b/netwerk/cache2/CacheFileMetadata.cpp @@ -19,8 +19,7 @@ #include "mozilla/IntegerPrintfMacros.h" #include "prnetdb.h" -namespace mozilla { -namespace net { +namespace mozilla::net { #define kMinMetadataRead 1024 // TODO find optimal value from telemetry #define kAlignSize 4096 @@ -33,7 +32,7 @@ namespace net { #define kInitialBufSize 64 // Max size of elements in bytes. -#define kMaxElementsSize 64 * 1024 +#define kMaxElementsSize (64 * 1024) #define NOW_SECONDS() (uint32_t(PR_Now() / PR_USEC_PER_SEC)) @@ -63,7 +62,7 @@ CacheFileMetadata::CacheFileMetadata(CacheFileHandle* aHandle, mMetaHdr.mExpirationTime = nsICacheEntry::NO_EXPIRATION_TIME; mKey = aKey; - DebugOnly rv; + DebugOnly rv{}; rv = ParseKey(aKey); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -96,7 +95,7 @@ CacheFileMetadata::CacheFileMetadata(bool aMemoryOnly, bool aPinned, mKey = aKey; mMetaHdr.mKeySize = mKey.Length(); - DebugOnly rv; + DebugOnly rv{}; rv = ParseKey(aKey); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -504,7 +503,8 @@ nsresult CacheFileMetadata::SetHash(uint32_t aIndex, if (aIndex > mHashCount) { return NS_ERROR_INVALID_ARG; - } else if (aIndex == mHashCount) { + } + if (aIndex == mHashCount) { if ((aIndex + 1) * sizeof(CacheHash::Hash16_t) > mHashArraySize) { // reallocate hash array buffer if (mHashArraySize == 0) { @@ -1045,5 +1045,4 @@ size_t CacheFileMetadata::SizeOfIncludingThis( return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileMetadata.h b/netwerk/cache2/CacheFileMetadata.h index 32ac9ef0f905..f3b992f46055 100644 --- a/netwerk/cache2/CacheFileMetadata.h +++ b/netwerk/cache2/CacheFileMetadata.h @@ -220,7 +220,7 @@ class CacheFileMetadata final : public CacheFileIOListener, // to elements uint32_t mBufSize; char* mWriteBuf; - CacheFileMetadataHeader mMetaHdr; + CacheFileMetadataHeader mMetaHdr{0}; uint32_t mElementsSize; bool mIsDirty : 1; bool mAnonymous : 1; diff --git a/netwerk/cache2/CacheFileOutputStream.cpp b/netwerk/cache2/CacheFileOutputStream.cpp index 93517650385b..507898f6c4a9 100644 --- a/netwerk/cache2/CacheFileOutputStream.cpp +++ b/netwerk/cache2/CacheFileOutputStream.cpp @@ -12,8 +12,7 @@ #include "mozilla/DebugOnly.h" #include -namespace mozilla { -namespace net { +namespace mozilla::net { NS_IMPL_ADDREF(CacheFileOutputStream) NS_IMETHODIMP_(MozExternalRefCountType) @@ -462,5 +461,4 @@ size_t CacheFileOutputStream::SizeOfIncludingThis( return mallocSizeOf(this); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheFileUtils.cpp b/netwerk/cache2/CacheFileUtils.cpp index 2ae4fe1ecb78..4234b21cb425 100644 --- a/netwerk/cache2/CacheFileUtils.cpp +++ b/netwerk/cache2/CacheFileUtils.cpp @@ -14,9 +14,7 @@ #include #include "mozilla/Unused.h" -namespace mozilla { -namespace net { -namespace CacheFileUtils { +namespace mozilla::net::CacheFileUtils { // This designates the format for the "alt-data" metadata. // When the format changes we need to update the version. @@ -665,6 +663,4 @@ void BuildAlternativeDataInfo(const char* aInfo, int64_t aOffset, _retval.Append(aInfo); } -} // namespace CacheFileUtils -} // namespace net -} // namespace mozilla +} // namespace mozilla::net::CacheFileUtils diff --git a/netwerk/cache2/CacheFileUtils.h b/netwerk/cache2/CacheFileUtils.h index 57e251cf14b6..90ede6ad18dd 100644 --- a/netwerk/cache2/CacheFileUtils.h +++ b/netwerk/cache2/CacheFileUtils.h @@ -104,8 +104,8 @@ class DetailedCacheHitTelemetry { void Reset(); private: - uint32_t mHitCnt; - uint32_t mMissCnt; + uint32_t mHitCnt = 0; + uint32_t mMissCnt = 0; }; // Group the hits and misses statistics by cache files count ranges (0-5000, diff --git a/netwerk/cache2/CacheHashUtils.cpp b/netwerk/cache2/CacheHashUtils.cpp index c47f87ba34f6..a62d353133d9 100644 --- a/netwerk/cache2/CacheHashUtils.cpp +++ b/netwerk/cache2/CacheHashUtils.cpp @@ -9,8 +9,7 @@ #include "mozilla/SHA1.h" #include "plstr.h" -namespace mozilla { -namespace net { +namespace mozilla::net { /** * CacheHash::Hash(const char * key, uint32_t initval) @@ -233,5 +232,4 @@ OriginAttrsHash GetOriginAttrsHash(const mozilla::OriginAttributes& aOA) { return BigEndian::readUint64(&hash); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheHashUtils.h b/netwerk/cache2/CacheHashUtils.h index 574e0aff0afd..adf21093c41a 100644 --- a/netwerk/cache2/CacheHashUtils.h +++ b/netwerk/cache2/CacheHashUtils.h @@ -30,8 +30,8 @@ class CacheHash : public nsISupports { public: NS_DECL_THREADSAFE_ISUPPORTS - typedef uint16_t Hash16_t; - typedef uint32_t Hash32_t; + using Hash16_t = uint16_t; + using Hash32_t = uint32_t; static Hash32_t Hash(const char* aData, uint32_t aSize, uint32_t aInitval = 0); @@ -57,7 +57,7 @@ class CacheHash : public nsISupports { bool mFinalized; }; -typedef uint64_t OriginAttrsHash; +using OriginAttrsHash = uint64_t; OriginAttrsHash GetOriginAttrsHash(const mozilla::OriginAttributes& aOA); diff --git a/netwerk/cache2/CacheIOThread.cpp b/netwerk/cache2/CacheIOThread.cpp index caeab955c18f..80170b2f9204 100644 --- a/netwerk/cache2/CacheIOThread.cpp +++ b/netwerk/cache2/CacheIOThread.cpp @@ -29,14 +29,13 @@ # include "TracedTaskCommon.h" #endif -namespace mozilla { -namespace net { +namespace mozilla::net { namespace { // anon class CacheIOTelemetry { public: - typedef CacheIOThread::EventQueue::size_type size_type; + using size_type = CacheIOThread::EventQueue::size_type; static size_type mMinLengthToReport[CacheIOThread::LAST_LEVEL]; static void Report(uint32_t aLevel, size_type aLength); }; @@ -277,8 +276,9 @@ nsresult CacheIOThread::Dispatch(already_AddRefed aRunnable, MonitorAutoLock lock(mMonitor); - if (mShutdown && (PR_GetCurrentThread() != mThread)) + if (mShutdown && (PR_GetCurrentThread() != mThread)) { return NS_ERROR_UNEXPECTED; + } return DispatchInternal(runnable.forget(), aLevel); } @@ -289,8 +289,9 @@ nsresult CacheIOThread::DispatchAfterPendingOpens(nsIRunnable* aRunnable) { MonitorAutoLock lock(mMonitor); - if (mShutdown && (PR_GetCurrentThread() != mThread)) + if (mShutdown && (PR_GetCurrentThread() != mThread)) { return NS_ERROR_UNEXPECTED; + } // Move everything from later executed OPEN level to the OPEN_PRIORITY level // where we post the (eviction) runnable. @@ -641,5 +642,4 @@ CacheIOThread::Cancelable::~Cancelable() { } } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheIOThread.h b/netwerk/cache2/CacheIOThread.h index 3c7b11cbf83f..bbb12faea788 100644 --- a/netwerk/cache2/CacheIOThread.h +++ b/netwerk/cache2/CacheIOThread.h @@ -36,7 +36,7 @@ class CacheIOThread final : public nsIThreadObserver { CacheIOThread(); - typedef nsTArray> EventQueue; + using EventQueue = nsTArray>; enum ELevel : uint32_t { OPEN_PRIORITY, diff --git a/netwerk/cache2/CacheIndex.cpp b/netwerk/cache2/CacheIndex.cpp index a9a4ae2acfd3..7d2adde990b6 100644 --- a/netwerk/cache2/CacheIndex.cpp +++ b/netwerk/cache2/CacheIndex.cpp @@ -34,8 +34,7 @@ #define TEMP_INDEX_NAME "index.tmp" #define JOURNAL_NAME "index.log" -namespace mozilla { -namespace net { +namespace mozilla::net { namespace { @@ -1396,8 +1395,9 @@ nsresult CacheIndex::GetCacheStats(nsILoadContextInfo* aInfo, uint32_t* aSize, for (auto iter = index->mFrecencyArray.Iter(); !iter.Done(); iter.Next()) { if (aInfo && - !CacheIndexEntry::RecordMatchesLoadContextInfo(iter.Get(), aInfo)) + !CacheIndexEntry::RecordMatchesLoadContextInfo(iter.Get(), aInfo)) { continue; + } *aSize += CacheIndexEntry::GetFileSize(*(iter.Get()->Get())); ++*aCount; @@ -2663,7 +2663,7 @@ nsresult CacheIndex::InitEntryFromDiskData(CacheIndexEntry* aEntry, aEntry->SetFrecency(aMetaData->GetFrecency()); const char* altData = aMetaData->GetElement(CacheFileUtils::kAltDataKey); - bool hasAltData = altData ? true : false; + bool hasAltData = altData != nullptr; if (hasAltData && NS_FAILED(CacheFileUtils::ParseAlternativeDataInfo( altData, nullptr, nullptr))) { return NS_ERROR_FAILURE; @@ -2705,11 +2705,7 @@ nsresult CacheIndex::InitEntryFromDiskData(CacheIndexEntry* aEntry, bool CacheIndex::IsUpdatePending() { sLock.AssertCurrentThreadOwns(); - if (mUpdateTimer || mUpdateEventPending) { - return true; - } - - return false; + return mUpdateTimer || mUpdateEventPending; } void CacheIndex::BuildIndex() { @@ -3874,5 +3870,4 @@ void CacheIndex::OnAsyncEviction(bool aEvicting) { } } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheIndex.h b/netwerk/cache2/CacheIndex.h index 5982dcad9f93..43044f46f510 100644 --- a/netwerk/cache2/CacheIndex.h +++ b/netwerk/cache2/CacheIndex.h @@ -41,7 +41,7 @@ class CacheIndexIterator; const uint16_t kIndexTimeNotAvailable = 0xFFFFU; const uint16_t kIndexTimeOutOfBound = 0xFFFEU; -typedef struct { +using CacheIndexHeader = struct { // Version of the index. The index must be ignored and deleted when the file // on disk was written with a newer version. uint32_t mVersion; @@ -63,7 +63,7 @@ typedef struct { // kTelemetryReportBytesLimit a telemetry report is sent and the counter is // reset. uint32_t mKBWritten; -} CacheIndexHeader; +}; static_assert(sizeof(CacheIndexHeader::mVersion) + sizeof(CacheIndexHeader::mTimeStamp) + @@ -74,7 +74,7 @@ static_assert(sizeof(CacheIndexHeader::mVersion) + #pragma pack(push, 1) struct CacheIndexRecord { - SHA1Sum::Hash mHash; + SHA1Sum::Hash mHash{}; uint32_t mFrecency; OriginAttrsHash mOriginAttrsHash; uint16_t mOnStartTime; @@ -128,8 +128,8 @@ class CacheIndexRecordWrapper final { class CacheIndexEntry : public PLDHashEntryHdr { public: - typedef const SHA1Sum::Hash& KeyType; - typedef const SHA1Sum::Hash* KeyTypePointer; + using KeyType = const SHA1Sum::Hash&; + using KeyTypePointer = const SHA1Sum::Hash*; explicit CacheIndexEntry(KeyTypePointer aKey) { MOZ_COUNT_CTOR(CacheIndexEntry); @@ -338,14 +338,10 @@ class CacheIndexEntry : public PLDHashEntryHdr { nsILoadContextInfo* aInfo) { MOZ_ASSERT(aInfo); - if (!aInfo->IsPrivate() && - GetOriginAttrsHash(*aInfo->OriginAttributesPtr()) == - aRec->Get()->mOriginAttrsHash && - aInfo->IsAnonymous() == !!(aRec->Get()->mFlags & kAnonymousMask)) { - return true; - } - - return false; + return !aInfo->IsPrivate() && + GetOriginAttrsHash(*aInfo->OriginAttributesPtr()) == + aRec->Get()->mOriginAttrsHash && + aInfo->IsAnonymous() == !!(aRec->Get()->mFlags & kAnonymousMask); } // Memory reporting @@ -694,14 +690,14 @@ class CacheIndexStats { private: uint32_t mCount; - uint32_t mCountByType[nsICacheEntry::CONTENT_TYPE_LAST]; + uint32_t mCountByType[nsICacheEntry::CONTENT_TYPE_LAST]{}; uint32_t mNotInitialized; uint32_t mRemoved; uint32_t mDirty; uint32_t mFresh; uint32_t mEmpty; uint32_t mSize; - uint32_t mSizeByType[nsICacheEntry::CONTENT_TYPE_LAST]; + uint32_t mSizeByType[nsICacheEntry::CONTENT_TYPE_LAST]{}; #ifdef DEBUG // We completely remove the data about an entry from the stats in // BeforeChange() and set this flag to true. The entry is then modified, diff --git a/netwerk/cache2/CacheIndexContextIterator.cpp b/netwerk/cache2/CacheIndexContextIterator.cpp index 7eb968a3b623..4a0ccbb88d56 100644 --- a/netwerk/cache2/CacheIndexContextIterator.cpp +++ b/netwerk/cache2/CacheIndexContextIterator.cpp @@ -7,8 +7,7 @@ #include "CacheIndex.h" #include "nsString.h" -namespace mozilla { -namespace net { +namespace mozilla::net { CacheIndexContextIterator::CacheIndexContextIterator(CacheIndex* aIndex, bool aAddNew, @@ -29,5 +28,4 @@ void CacheIndexContextIterator::AddRecords( } } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheIndexIterator.cpp b/netwerk/cache2/CacheIndexIterator.cpp index ff009962239b..b7e498790e8d 100644 --- a/netwerk/cache2/CacheIndexIterator.cpp +++ b/netwerk/cache2/CacheIndexIterator.cpp @@ -8,8 +8,7 @@ #include "nsString.h" #include "mozilla/DebugOnly.h" -namespace mozilla { -namespace net { +namespace mozilla::net { CacheIndexIterator::CacheIndexIterator(CacheIndex* aIndex, bool aAddNew) : mStatus(NS_OK), mIndex(aIndex), mAddNew(aAddNew) { @@ -98,5 +97,4 @@ bool CacheIndexIterator::ReplaceRecord(CacheIndexRecordWrapper* aOldRecord, return false; } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheLog.cpp b/netwerk/cache2/CacheLog.cpp index 67d879a6c496..ea81ff2a198d 100644 --- a/netwerk/cache2/CacheLog.cpp +++ b/netwerk/cache2/CacheLog.cpp @@ -4,8 +4,7 @@ #include "CacheLog.h" -namespace mozilla { -namespace net { +namespace mozilla::net { // Log module for cache2 (2013) cache implementation logging... // @@ -18,5 +17,4 @@ namespace net { // the file network.log. LazyLogModule gCache2Log("cache2"); -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheObserver.cpp b/netwerk/cache2/CacheObserver.cpp index 3cbf4c45040f..c553e1fc6b1e 100644 --- a/netwerk/cache2/CacheObserver.cpp +++ b/netwerk/cache2/CacheObserver.cpp @@ -18,8 +18,7 @@ #include #include -namespace mozilla { -namespace net { +namespace mozilla::net { StaticRefPtr CacheObserver::sSelf; @@ -170,9 +169,7 @@ bool CacheObserver::EntryIsTooBig(int64_t aSize, bool aUsingDisk) { aUsingDisk ? DiskCacheCapacity() : MemoryCacheCapacity(); derivedLimit <<= (10 - 3); - if (aSize > derivedLimit) return true; - - return false; + return aSize > derivedLimit; } // static @@ -243,8 +240,9 @@ CacheObserver::Observe(nsISupports* aSubject, const char* aTopic, if (!strcmp(aTopic, "memory-pressure")) { RefPtr service = CacheStorageService::Self(); - if (service) + if (service) { service->PurgeFromMemory(nsICacheStorageService::PURGE_EVERYTHING); + } return NS_OK; } @@ -253,5 +251,4 @@ CacheObserver::Observe(nsISupports* aSubject, const char* aTopic, return NS_OK; } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheStorage.h b/netwerk/cache2/CacheStorage.h index 80f7568d0d45..b50e616693a2 100644 --- a/netwerk/cache2/CacheStorage.h +++ b/netwerk/cache2/CacheStorage.h @@ -21,7 +21,7 @@ namespace net { // This dance is needed to make CacheEntryTable declarable-only in headers // w/o exporting CacheEntry.h file to make nsNetModule.cpp compilable. -typedef nsRefPtrHashtable TCacheEntryTable; +using TCacheEntryTable = nsRefPtrHashtable; class CacheEntryTable : public TCacheEntryTable { public: enum EType { MEMORY_ONLY, ALL_ENTRIES }; diff --git a/netwerk/cache2/CacheStorageService.cpp b/netwerk/cache2/CacheStorageService.cpp index 7847c8bb2ebc..4a9ca7f08b9a 100644 --- a/netwerk/cache2/CacheStorageService.cpp +++ b/netwerk/cache2/CacheStorageService.cpp @@ -33,8 +33,7 @@ #include "mozilla/IntegerPrintfMacros.h" #include "mozilla/Telemetry.h" -namespace mozilla { -namespace net { +namespace mozilla::net { namespace { @@ -50,7 +49,7 @@ void AppendMemoryStorageTag(nsAutoCString& key) { // Not defining as static or class member of CacheStorageService since // it would otherwise need to include CacheEntry.h and that then would // need to be exported to make nsNetModule.cpp compilable. -typedef nsClassHashtable GlobalEntryTables; +using GlobalEntryTables = nsClassHashtable; /** * Keeps tables of entries. There is one entries table for each distinct load @@ -316,8 +315,9 @@ class WalkMemoryCacheRunnable : public WalkCacheRunnable { } virtual ~WalkMemoryCacheRunnable() { - if (mCallback) + if (mCallback) { ProxyReleaseMainThread("WalkMemoryCacheRunnable::mCallback", mCallback); + } } virtual void OnEntryInfo(const nsACString& aURISpec, @@ -1097,14 +1097,16 @@ bool CacheStorageService::RemoveEntry(CacheEntry* aEntry, } CacheEntryTable* entries; - if (sGlobalEntryTables->Get(aEntry->GetStorageID(), &entries)) + if (sGlobalEntryTables->Get(aEntry->GetStorageID(), &entries)) { RemoveExactEntry(entries, entryKey, aEntry, false /* don't overwrite */); + } nsAutoCString memoryStorageID(aEntry->GetStorageID()); AppendMemoryStorageTag(memoryStorageID); - if (sGlobalEntryTables->Get(memoryStorageID, &entries)) + if (sGlobalEntryTables->Get(memoryStorageID, &entries)) { RemoveExactEntry(entries, entryKey, aEntry, false /* don't overwrite */); + } return true; } @@ -1719,8 +1721,9 @@ class CacheEntryDoomByKeyCallback : public CacheFileIOListener, }; CacheEntryDoomByKeyCallback::~CacheEntryDoomByKeyCallback() { - if (mCallback) + if (mCallback) { ProxyReleaseMainThread("CacheEntryDoomByKeyCallback::mCallback", mCallback); + } } NS_IMETHODIMP CacheEntryDoomByKeyCallback::OnFileDoomed( @@ -1908,7 +1911,7 @@ nsresult CacheStorageService::DoomStorageEntries( CacheEntryTable* diskEntries; if (memoryEntries && sGlobalEntryTables->Get(aContextKey, &diskEntries)) { for (const auto& memoryEntry : *memoryEntries) { - auto entry = memoryEntry.GetData(); + const auto& entry = memoryEntry.GetData(); RemoveExactEntry(diskEntries, memoryEntry.GetKey(), entry, false); } } @@ -2335,5 +2338,4 @@ CacheStorageService::Flush(nsIObserver* aObserver) { return thread->Dispatch(r, CacheIOThread::WRITE); } -} // namespace net -} // namespace mozilla +} // namespace mozilla::net diff --git a/netwerk/cache2/CacheStorageService.h b/netwerk/cache2/CacheStorageService.h index b72faa392bda..6e93ca950445 100644 --- a/netwerk/cache2/CacheStorageService.h +++ b/netwerk/cache2/CacheStorageService.h @@ -122,7 +122,7 @@ class CacheStorageService final : public nsICacheStorageService, // Invokes OnEntryInfo for the given aEntry, synchronously. static void GetCacheEntryInfo(CacheEntry* aEntry, - EntryInfoCallback* aVisitor); + EntryInfoCallback* aCallback); nsresult GetCacheIndexEntryAttrs(CacheStorage const* aStorage, const nsACString& aURI, @@ -202,7 +202,7 @@ class CacheStorageService final : public nsICacheStorageService, * thrown away when forced valid * See nsICacheEntry.idl for more details */ - bool IsForcedValidEntry(nsACString const& aEntryKeyWithContext); + bool IsForcedValidEntry(nsACString const& aContextEntryKey); private: // These are helpers for telemetry monitoring of the memory pools. diff --git a/netwerk/cookie/CookieCommons.cpp b/netwerk/cookie/CookieCommons.cpp index 1aef96a0680c..2137877725bd 100644 --- a/netwerk/cookie/CookieCommons.cpp +++ b/netwerk/cookie/CookieCommons.cpp @@ -68,11 +68,7 @@ bool CookieCommons::PathMatches(Cookie* aCookie, const nsACString& aPath) { // of the request path that is not included in the cookie path is a %x2F ("/") // character, they match. uint32_t cookiePathLen = cookiePath.Length(); - if (isPrefix && aPath[cookiePathLen] == '/') { - return true; - } - - return false; + return isPrefix && aPath[cookiePathLen] == '/'; } // Get the base domain for aHostURI; e.g. for "www.bbc.co.uk", this would be diff --git a/netwerk/cookie/CookiePersistentStorage.cpp b/netwerk/cookie/CookiePersistentStorage.cpp index 28ab3868d137..e80097b50bbf 100644 --- a/netwerk/cookie/CookiePersistentStorage.cpp +++ b/netwerk/cookie/CookiePersistentStorage.cpp @@ -131,7 +131,7 @@ ConvertAppIdToOriginAttrsSQLFunction::OnFunctionCall( // Create an originAttributes object by inIsolatedMozBrowser. // Then create the originSuffix string from this object. - OriginAttributes attrs(inIsolatedMozBrowser ? true : false); + OriginAttributes attrs(inIsolatedMozBrowser != 0); nsAutoCString suffix; attrs.CreateSuffix(suffix); @@ -382,7 +382,7 @@ void CookiePersistentStorage::NotifyChangedInternal(nsISupports* aSubject, u"added"_ns.Equals(aData)) { nsCOMPtr xpcCookie = do_QueryInterface(aSubject); MOZ_ASSERT(xpcCookie); - auto cookie = static_cast(xpcCookie.get()); + auto* cookie = static_cast(xpcCookie.get()); if (!cookie->IsSession() && !aOldCookieIsSession) { return; } diff --git a/netwerk/cookie/CookieService.cpp b/netwerk/cookie/CookieService.cpp index ef55f378d3e8..956090aabca6 100644 --- a/netwerk/cookie/CookieService.cpp +++ b/netwerk/cookie/CookieService.cpp @@ -1321,7 +1321,6 @@ bool CookieService::GetTokenValue(nsACString::const_char_iterator& aIter, lastSpace = aIter; if (lastSpace != start) { while (--lastSpace != start && iswhitespace(*lastSpace)) { - continue; } ++lastSpace; } @@ -1331,7 +1330,6 @@ bool CookieService::GetTokenValue(nsACString::const_char_iterator& aIter, if (aEqualsFound) { // find while (++aIter != aEndIter && iswhitespace(*aIter)) { - continue; } start = aIter; @@ -1346,7 +1344,6 @@ bool CookieService::GetTokenValue(nsACString::const_char_iterator& aIter, if (aIter != start) { lastSpace = aIter; while (--lastSpace != start && iswhitespace(*lastSpace)) { - continue; } aTokenValue.Rebind(start, ++lastSpace); @@ -1586,8 +1583,7 @@ CookieStatus CookieService::CheckPrefs( // don't let unsupported scheme sites get/set cookies (could be a security // issue) if (!CookieCommons::IsSchemeSupported(aHostURI)) { - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, "non http/https sites cannot read cookies"); return STATUS_REJECTED_WITH_ERROR; } @@ -1596,8 +1592,7 @@ CookieStatus CookieService::CheckPrefs( BasePrincipal::CreateContentPrincipal(aHostURI, aOriginAttrs); if (!principal) { - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, "non-content principals cannot get/set cookies"); return STATUS_REJECTED_WITH_ERROR; } @@ -1609,8 +1604,7 @@ CookieStatus CookieService::CheckPrefs( if (NS_SUCCEEDED(rv)) { switch (cookiePermission) { case nsICookiePermission::ACCESS_DENY: - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, "cookies are blocked for this site"); CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, @@ -1650,8 +1644,7 @@ CookieStatus CookieService::CheckPrefs( return STATUS_ACCEPTED; } - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, "cookies are disabled in trackers"); if (aIsThirdPartySocialTrackingResource) { *aRejectedReason = @@ -1671,8 +1664,8 @@ CookieStatus CookieService::CheckPrefs( if (aCookieJarSettings->GetCookieBehavior() == nsICookieService::BEHAVIOR_REJECT && !aStorageAccessPermissionGranted) { - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, "cookies are disabled"); + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, + "cookies are disabled"); *aRejectedReason = nsIWebProgressListener::STATE_COOKIES_BLOCKED_ALL; return STATUS_REJECTED; } @@ -1682,8 +1675,8 @@ CookieStatus CookieService::CheckPrefs( if (aCookieJarSettings->GetCookieBehavior() == nsICookieService::BEHAVIOR_REJECT_FOREIGN && !aStorageAccessPermissionGranted) { - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, "context is third party"); + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, + "context is third party"); CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_REJECTION_CATEGORY, "CookieRejectedThirdParty"_ns, @@ -1696,8 +1689,8 @@ CookieStatus CookieService::CheckPrefs( if (aCookieJarSettings->GetLimitForeignContexts() && !aStorageAccessPermissionGranted && aNumOfCookies == 0) { - COOKIE_LOGFAILURE(aCookieHeader.IsVoid() ? GET_COOKIE : SET_COOKIE, - aHostURI, aCookieHeader, "context is third party"); + COOKIE_LOGFAILURE(!aCookieHeader.IsVoid(), aHostURI, aCookieHeader, + "context is third party"); CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_REJECTION_CATEGORY, "CookieRejectedThirdParty"_ns, @@ -1850,11 +1843,7 @@ bool CookieService::CheckPath(CookieStruct& aCookieData, return false; } - if (aCookieData.path().Contains('\t')) { - return false; - } - - return true; + return !aCookieData.path().Contains('\t'); } // CheckPrefixes @@ -2010,7 +1999,7 @@ CookieService::CookieExistsNative(const nsACString& aHost, CookieCommons::GetBaseDomainFromHost(mTLDService, aHost, baseDomain); NS_ENSURE_SUCCESS(rv, rv); - CookieListIter iter; + CookieListIter iter{}; CookieStorage* storage = PickStorage(*aOriginAttributes); *aFoundCookie = storage->FindCookie(baseDomain, *aOriginAttributes, aHost, aName, aPath, iter); diff --git a/netwerk/cookie/CookieServiceParent.cpp b/netwerk/cookie/CookieServiceParent.cpp index d87c1c551e8a..71411c574fc7 100644 --- a/netwerk/cookie/CookieServiceParent.cpp +++ b/netwerk/cookie/CookieServiceParent.cpp @@ -40,7 +40,7 @@ void CookieServiceParent::RemoveBatchDeletedCookies(nsIArray* aCookieList) { nsTArray attrsList; for (uint32_t i = 0; i < len; i++) { nsCOMPtr xpcCookie = do_QueryElementAt(aCookieList, i); - auto cookie = static_cast(xpcCookie.get()); + auto* cookie = static_cast(xpcCookie.get()); attrs = cookie->OriginAttributesRef(); cookieStruct = cookie->ToIPC(); if (cookie->IsHttpOnly()) { @@ -56,7 +56,7 @@ void CookieServiceParent::RemoveBatchDeletedCookies(nsIArray* aCookieList) { void CookieServiceParent::RemoveAll() { Unused << SendRemoveAll(); } void CookieServiceParent::RemoveCookie(nsICookie* aCookie) { - auto cookie = static_cast(aCookie); + auto* cookie = static_cast(aCookie); const OriginAttributes& attrs = cookie->OriginAttributesRef(); CookieStruct cookieStruct = cookie->ToIPC(); if (cookie->IsHttpOnly()) { @@ -66,7 +66,7 @@ void CookieServiceParent::RemoveCookie(nsICookie* aCookie) { } void CookieServiceParent::AddCookie(nsICookie* aCookie) { - auto cookie = static_cast(aCookie); + auto* cookie = static_cast(aCookie); const OriginAttributes& attrs = cookie->OriginAttributesRef(); CookieStruct cookieStruct = cookie->ToIPC(); if (cookie->IsHttpOnly()) { diff --git a/netwerk/cookie/CookieStorage.cpp b/netwerk/cookie/CookieStorage.cpp index baeae6de3d03..204d8b6e5265 100644 --- a/netwerk/cookie/CookieStorage.cpp +++ b/netwerk/cookie/CookieStorage.cpp @@ -48,7 +48,6 @@ class CompareCookiesByAge { // Other non-expired cookies are sorted by their age. class CookieIterComparator { private: - CompareCookiesByAge mAgeComparator; int64_t mCurrentTime; public: @@ -65,7 +64,7 @@ class CookieIterComparator { return false; } - return mAgeComparator.LessThan(lhs, rhs); + return mozilla::net::CompareCookiesByAge::LessThan(lhs, rhs); } }; @@ -278,7 +277,7 @@ void CookieStorage::RemoveCookie(const nsACString& aBaseDomain, const nsACString& aHost, const nsACString& aName, const nsACString& aPath) { - CookieListIter matchIter; + CookieListIter matchIter{}; RefPtr cookie; if (FindCookie(aBaseDomain, aOriginAttributes, aHost, aName, aPath, matchIter)) { @@ -403,7 +402,7 @@ void CookieStorage::AddCookie(nsIConsoleReportCollector* aCRC, bool aFromHttp) { int64_t currentTime = aCurrentTimeInUsec / PR_USEC_PER_SEC; - CookieListIter exactIter; + CookieListIter exactIter{}; bool foundCookie = false; foundCookie = FindCookie(aBaseDomain, aOriginAttributes, aCookie->Host(), aCookie->Name(), aCookie->Path(), exactIter); diff --git a/netwerk/cookie/CookieStorage.h b/netwerk/cookie/CookieStorage.h index 407195a46f8b..36df7c765c35 100644 --- a/netwerk/cookie/CookieStorage.h +++ b/netwerk/cookie/CookieStorage.h @@ -27,8 +27,8 @@ class Cookie; class CookieEntry : public CookieKey { public: // Hash methods - typedef nsTArray> ArrayType; - typedef ArrayType::index_type IndexType; + using ArrayType = nsTArray>; + using IndexType = ArrayType::index_type; explicit CookieEntry(KeyTypePointer aKey) : CookieKey(aKey) {} diff --git a/netwerk/ipc/DocumentLoadListener.h b/netwerk/ipc/DocumentLoadListener.h index 10c7130517ae..fb9500e78f74 100644 --- a/netwerk/ipc/DocumentLoadListener.h +++ b/netwerk/ipc/DocumentLoadListener.h @@ -59,7 +59,7 @@ struct StreamFilterRequest { } } RefPtr mPromise; - base::ProcessId mChildProcessId; + base::ProcessId mChildProcessId = 0; mozilla::ipc::Endpoint mChildEndpoint; }; } // namespace net @@ -119,9 +119,8 @@ class DocumentLoadListener : public nsIInterfaceRequestor, bool mSwitchedProcess = false; }; - typedef MozPromise - OpenPromise; + using OpenPromise = + MozPromise; // Interface which may be provided when performing an or load // with `DocumentLoadListener`, to allow upgrading the Object load to a proper @@ -169,7 +168,7 @@ class DocumentLoadListener : public nsIInterfaceRequestor, nsDOMNavigationTiming* aTiming, Maybe&& aInfo, uint64_t aInnerWindowId, nsLoadFlags aLoadFlags, nsContentPolicyType aContentPolicyType, bool aUrgentStart, - base::ProcessId aPid, ObjectUpgradeHandler* aUpgradeHandler, + base::ProcessId aPid, ObjectUpgradeHandler* aObjectUpgradeHandler, nsresult* aRv); // Creates a DocumentLoadListener entirely in the parent process and opens it, @@ -401,10 +400,9 @@ class DocumentLoadListener : public nsIInterfaceRequestor, bool mIsThirdParty; }; - typedef mozilla::Variant< + using IParentChannelFunction = mozilla::Variant< nsIHttpChannel::FlashPluginState, ClassifierMatchedInfoParams, - ClassifierMatchedTrackingInfoParams, ClassificationFlagsParams> - IParentChannelFunction; + ClassifierMatchedTrackingInfoParams, ClassificationFlagsParams>; // Store a list of all the attribute setters that have been called on this // channel, so that we can repeat them on the real channel that we redirect @@ -427,15 +425,14 @@ class DocumentLoadListener : public nsIInterfaceRequestor, struct LogMimeTypeMismatchParams { nsCString mMessageName; - bool mWarning; + bool mWarning = false; nsString mURL; nsString mContentType; }; - typedef mozilla::Variant - SecurityWarningFunction; + using SecurityWarningFunction = + mozilla::Variant; nsTArray mSecurityWarningFunctions; struct OnStartRequestParams { @@ -454,9 +451,9 @@ class DocumentLoadListener : public nsIInterfaceRequestor, struct OnAfterLastPartParams { nsresult status; }; - typedef mozilla::Variant - StreamListenerFunction; + using StreamListenerFunction = + mozilla::Variant; // TODO Backtrack this. // The set of nsIStreamListener functions that got called on this // listener, so that we can replay them onto the replacement channel's diff --git a/netwerk/ipc/InputChannelThrottleQueueParent.cpp b/netwerk/ipc/InputChannelThrottleQueueParent.cpp index 30a406facb18..e68ff1417ac0 100644 --- a/netwerk/ipc/InputChannelThrottleQueueParent.cpp +++ b/netwerk/ipc/InputChannelThrottleQueueParent.cpp @@ -23,7 +23,7 @@ InputChannelThrottleQueueParent::Release(void) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(int32_t(mRefCnt) > 0, "dup release"); - if (!mRefCnt.isThreadSafe) { + if (!nsAutoRefCnt::isThreadSafe) { NS_ASSERT_OWNINGTHREAD(InputChannelThrottleQueueParent); } @@ -31,7 +31,7 @@ InputChannelThrottleQueueParent::Release(void) { NS_LOG_RELEASE(this, count, "InputChannelThrottleQueueParent"); if (count == 0) { - if (!mRefCnt.isThreadSafe) { + if (!nsAutoRefCnt::isThreadSafe) { NS_ASSERT_OWNINGTHREAD(InputChannelThrottleQueueParent); } diff --git a/netwerk/ipc/SocketProcessBridgeChild.h b/netwerk/ipc/SocketProcessBridgeChild.h index 385d8e8ac6ef..71cae2d3f66e 100644 --- a/netwerk/ipc/SocketProcessBridgeChild.h +++ b/netwerk/ipc/SocketProcessBridgeChild.h @@ -23,8 +23,8 @@ class SocketProcessBridgeChild final : public PSocketProcessBridgeChild, NS_DECL_NSIOBSERVER static already_AddRefed GetSingleton(); - typedef MozPromise, nsCString, false> - GetPromise; + using GetPromise = + MozPromise, nsCString, false>; static RefPtr GetSocketProcessBridge(); mozilla::ipc::IPCResult RecvTest(); diff --git a/netwerk/ipc/SocketProcessChild.cpp b/netwerk/ipc/SocketProcessChild.cpp index eb6485591dc4..14dee5de750d 100644 --- a/netwerk/ipc/SocketProcessChild.cpp +++ b/netwerk/ipc/SocketProcessChild.cpp @@ -148,11 +148,7 @@ bool SocketProcessChild::Init(base::ProcessId aParentPid, // Initialize DNS Service here, since it needs to be done in main thread. nsCOMPtr dns = do_GetService("@mozilla.org/network/dns-service;1", &rv); - if (NS_FAILED(rv)) { - return false; - } - - return true; + return NS_SUCCEEDED(rv); } void SocketProcessChild::ActorDestroy(ActorDestroyReason aWhy) { diff --git a/netwerk/ipc/SocketProcessImpl.h b/netwerk/ipc/SocketProcessImpl.h index 51d609b4a9e9..7fbc34a0749f 100644 --- a/netwerk/ipc/SocketProcessImpl.h +++ b/netwerk/ipc/SocketProcessImpl.h @@ -16,7 +16,7 @@ namespace net { // It is instantiated as a singleton in XRE_InitChildProcess. class SocketProcessImpl final : public mozilla::ipc::ProcessChild { protected: - typedef mozilla::ipc::ProcessChild ProcessChild; + using ProcessChild = mozilla::ipc::ProcessChild; public: explicit SocketProcessImpl(ProcessId aParentPid); diff --git a/netwerk/ipc/SocketProcessParent.h b/netwerk/ipc/SocketProcessParent.h index f7f24567b86f..1fa152c09df0 100644 --- a/netwerk/ipc/SocketProcessParent.h +++ b/netwerk/ipc/SocketProcessParent.h @@ -59,7 +59,7 @@ class SocketProcessParent final const uint16_t& aType, const OriginAttributes& aOriginAttributes, const uint32_t& aFlags); virtual mozilla::ipc::IPCResult RecvPDNSRequestConstructor( - PDNSRequestParent* actor, const nsCString& hostName, + PDNSRequestParent* actor, const nsCString& aHost, const nsCString& trrServer, const uint16_t& type, const OriginAttributes& aOriginAttributes, const uint32_t& flags) override; diff --git a/netwerk/mime/nsMIMEHeaderParamImpl.cpp b/netwerk/mime/nsMIMEHeaderParamImpl.cpp index fb4f45aac08e..d3cf803b3dfd 100644 --- a/netwerk/mime/nsMIMEHeaderParamImpl.cpp +++ b/netwerk/mime/nsMIMEHeaderParamImpl.cpp @@ -44,7 +44,7 @@ static nsresult ToUTF8(const nsACString& aString, const nsACString& aCharset, return NS_ERROR_INVALID_ARG; } - auto encoding = Encoding::ForLabelNoReplacement(aCharset); + const auto* encoding = Encoding::ForLabelNoReplacement(aCharset); if (!encoding) { return NS_ERROR_UCONV_NOCONV; } @@ -168,8 +168,9 @@ nsresult nsMIMEHeaderParamImpl::DoGetParameter( return NS_OK; } - if (aTryLocaleCharset && !NS_IsNativeUTF8()) + if (aTryLocaleCharset && !NS_IsNativeUTF8()) { return NS_CopyNativeToUnicode(str1, aResult); + } CopyASCIItoUTF16(str1, aResult); return NS_OK; @@ -402,16 +403,18 @@ nsresult nsMIMEHeaderParamImpl::DoParameterInternal( const char* str = aHeaderValue; // skip leading white space. - for (; *str && nsCRT::IsAsciiSpace(*str); ++str) + for (; *str && nsCRT::IsAsciiSpace(*str); ++str) { ; + } const char* start = str; // aParamName is empty. return the first (possibly) _unnamed_ 'parameter' // For instance, return 'inline' in the following case: // Content-Disposition: inline; filename=..... if (!aParamName || !*aParamName) { - for (; *str && *str != ';' && !nsCRT::IsAsciiSpace(*str); ++str) + for (; *str && *str != ';' && !nsCRT::IsAsciiSpace(*str); ++str) { ; + } if (str == start) return NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY; *aResult = (char*)moz_xmemdup(start, (str - start) + 1); @@ -420,12 +423,14 @@ nsresult nsMIMEHeaderParamImpl::DoParameterInternal( } /* Skip forward to first ';' */ - for (; *str && *str != ';' && *str != ','; ++str) + for (; *str && *str != ';' && *str != ','; ++str) { ; + } if (*str) str++; /* Skip over following whitespace */ - for (; *str && nsCRT::IsAsciiSpace(*str); ++str) + for (; *str && nsCRT::IsAsciiSpace(*str); ++str) { ; + } // Some broken http servers just specify parameters // like 'filename' without specifying disposition @@ -475,8 +480,9 @@ nsresult nsMIMEHeaderParamImpl::DoParameterInternal( // Skip forward to the end of this token. for (; *str && !nsCRT::IsAsciiSpace(*str) && *str != '=' && *str != ';'; - str++) + str++) { ; + } nameEnd = str; int32_t nameLen = nameEnd - nameStart; @@ -511,10 +517,11 @@ nsresult nsMIMEHeaderParamImpl::DoParameterInternal( ++str; valueStart = str; for (valueEnd = str; *valueEnd; ++valueEnd) { - if (*valueEnd == '\\' && *(valueEnd + 1)) + if (*valueEnd == '\\' && *(valueEnd + 1)) { ++valueEnd; - else if (*valueEnd == '"') + } else if (*valueEnd == '"') { break; + } } str = valueEnd; // *valueEnd != null means that *valueEnd is quote character. @@ -684,15 +691,17 @@ nsresult nsMIMEHeaderParamImpl::DoParameterInternal( if (caseBResult && !charsetB.IsEmpty()) { // check that the 2231/5987 result decodes properly given the // specified character set - if (!IsValidOctetSequenceForCharset(charsetB, caseBResult)) + if (!IsValidOctetSequenceForCharset(charsetB, caseBResult)) { caseBResult = nullptr; + } } if (caseCDResult && !charsetCD.IsEmpty()) { // check that the 2231/5987 result decodes properly given the // specified character set - if (!IsValidOctetSequenceForCharset(charsetCD, caseCDResult)) + if (!IsValidOctetSequenceForCharset(charsetCD, caseCDResult)) { caseCDResult = nullptr; + } } if (caseBResult) { @@ -963,8 +972,9 @@ char* DecodeQ(const char* in, uint32_t length) { switch (*in) { case '=': // check if |in| in the form of '=hh' where h is [0-9a-fA-F]. - if (length < 3 || !ISHEXCHAR(in[1]) || !ISHEXCHAR(in[2])) + if (length < 3 || !ISHEXCHAR(in[1]) || !ISHEXCHAR(in[2])) { goto badsyntax; + } PR_sscanf(in + 1, "%2X", &c); *out++ = (char)c; in += 3; @@ -1088,10 +1098,11 @@ void CopyRawHeader(const char* aInput, uint32_t aLen, } else { // replace each octet with Unicode replacement char in UTF-8. for (uint32_t i = 0; i < aLen; i++) { c = uint8_t(*aInput++); - if (c & 0x80) + if (c & 0x80) { aOutput.Append(REPLACEMENT_CHAR); - else + } else { aOutput.Append(char(c)); + } } } } @@ -1101,9 +1112,9 @@ nsresult DecodeQOrBase64Str(const char* aEncoded, size_t aLen, char aQOrBase64, char* decodedText; bool b64alloc = false; NS_ASSERTION(aQOrBase64 == 'Q' || aQOrBase64 == 'B', "Should be 'Q' or 'B'"); - if (aQOrBase64 == 'Q') + if (aQOrBase64 == 'Q') { decodedText = DecodeQ(aEncoded, aLen); - else if (aQOrBase64 == 'B') { + } else if (aQOrBase64 == 'B') { decodedText = PL_Base64Decode(aEncoded, aLen, nullptr); b64alloc = true; } else { diff --git a/netwerk/protocol/about/nsAboutCache.h b/netwerk/protocol/about/nsAboutCache.h index 2c7064d89ea4..984d799f4356 100644 --- a/netwerk/protocol/about/nsAboutCache.h +++ b/netwerk/protocol/about/nsAboutCache.h @@ -20,91 +20,97 @@ #define NS_FORWARD_SAFE_NSICHANNEL_SUBSET(_to) \ NS_IMETHOD GetOriginalURI(nsIURI** aOriginalURI) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetOriginalURI(aOriginalURI); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetOriginalURI(aOriginalURI); \ } \ NS_IMETHOD SetOriginalURI(nsIURI* aOriginalURI) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->SetOriginalURI(aOriginalURI); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetOriginalURI(aOriginalURI); \ } \ NS_IMETHOD GetURI(nsIURI** aURI) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetURI(aURI); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->GetURI(aURI); \ } \ NS_IMETHOD GetOwner(nsISupports** aOwner) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetOwner(aOwner); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->GetOwner(aOwner); \ } \ NS_IMETHOD SetOwner(nsISupports* aOwner) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->SetOwner(aOwner); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->SetOwner(aOwner); \ } \ NS_IMETHOD GetNotificationCallbacks( \ nsIInterfaceRequestor** aNotificationCallbacks) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetNotificationCallbacks(aNotificationCallbacks); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetNotificationCallbacks(aNotificationCallbacks); \ } \ NS_IMETHOD SetNotificationCallbacks( \ nsIInterfaceRequestor* aNotificationCallbacks) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->SetNotificationCallbacks(aNotificationCallbacks); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetNotificationCallbacks(aNotificationCallbacks); \ } \ NS_IMETHOD GetSecurityInfo(nsISupports** aSecurityInfo) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetSecurityInfo(aSecurityInfo); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetSecurityInfo(aSecurityInfo); \ } \ NS_IMETHOD GetContentType(nsACString& aContentType) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetContentType(aContentType); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentType(aContentType); \ } \ NS_IMETHOD SetContentType(const nsACString& aContentType) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->SetContentType(aContentType); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetContentType(aContentType); \ } \ NS_IMETHOD GetContentCharset(nsACString& aContentCharset) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetContentCharset(aContentCharset); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentCharset(aContentCharset); \ } \ NS_IMETHOD SetContentCharset(const nsACString& aContentCharset) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->SetContentCharset(aContentCharset); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetContentCharset(aContentCharset); \ } \ NS_IMETHOD GetContentLength(int64_t* aContentLength) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetContentLength(aContentLength); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentLength(aContentLength); \ } \ NS_IMETHOD SetContentLength(int64_t aContentLength) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->SetContentLength(aContentLength); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetContentLength(aContentLength); \ } \ NS_IMETHOD GetContentDisposition(uint32_t* aContentDisposition) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetContentDisposition(aContentDisposition); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentDisposition(aContentDisposition); \ } \ NS_IMETHOD SetContentDisposition(uint32_t aContentDisposition) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->SetContentDisposition(aContentDisposition); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetContentDisposition(aContentDisposition); \ } \ NS_IMETHOD GetContentDispositionFilename( \ nsAString& aContentDispositionFilename) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetContentDispositionFilename( \ - aContentDispositionFilename); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentDispositionFilename( \ + aContentDispositionFilename); \ } \ NS_IMETHOD SetContentDispositionFilename( \ const nsAString& aContentDispositionFilename) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->SetContentDispositionFilename( \ - aContentDispositionFilename); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->SetContentDispositionFilename( \ + aContentDispositionFilename); \ } \ NS_IMETHOD GetContentDispositionHeader( \ nsACString& aContentDispositionHeader) override { \ - return !_to ? NS_ERROR_NULL_POINTER \ - : _to->GetContentDispositionHeader(aContentDispositionHeader); \ + return !(_to) ? NS_ERROR_NULL_POINTER \ + : (_to)->GetContentDispositionHeader( \ + aContentDispositionHeader); \ } \ NS_IMETHOD GetLoadInfo(nsILoadInfo** aLoadInfo) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetLoadInfo(aLoadInfo); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->GetLoadInfo(aLoadInfo); \ } \ NS_IMETHOD SetLoadInfo(nsILoadInfo* aLoadInfo) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->SetLoadInfo(aLoadInfo); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->SetLoadInfo(aLoadInfo); \ } \ NS_IMETHOD GetIsDocument(bool* aIsDocument) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetIsDocument(aIsDocument); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->GetIsDocument(aIsDocument); \ } \ NS_IMETHOD GetCanceled(bool* aCanceled) override { \ - return !_to ? NS_ERROR_NULL_POINTER : _to->GetCanceled(aCanceled); \ + return !(_to) ? NS_ERROR_NULL_POINTER : (_to)->GetCanceled(aCanceled); \ }; class nsAboutCache final : public nsIAboutModule { @@ -160,14 +166,14 @@ class nsAboutCache final : public nsIAboutModule { // Whether we are showing overview status of all available // storages. - bool mOverview; + bool mOverview = false; // Flag initially false, that indicates the entries header has // been added to the output HTML. - bool mEntriesHeaderAdded; + bool mEntriesHeaderAdded = false; // Cancelation flag - bool mCancel; + bool mCancel = false; // The list of all storage names we want to visit nsTArray mStorageList; diff --git a/netwerk/protocol/about/nsAboutCacheEntry.cpp b/netwerk/protocol/about/nsAboutCacheEntry.cpp index 822ae47b22ec..1de10b3ae75f 100644 --- a/netwerk/protocol/about/nsAboutCacheEntry.cpp +++ b/netwerk/protocol/about/nsAboutCacheEntry.cpp @@ -215,15 +215,17 @@ nsresult nsAboutCacheEntry::Channel::ParseURI(nsIURI* uri, keyBegin = begin; keyEnd = end; - if (!FindInReadable("?storage="_ns, keyBegin, keyEnd)) + if (!FindInReadable("?storage="_ns, keyBegin, keyEnd)) { return NS_ERROR_FAILURE; + } valBegin = keyEnd; // the value of the storage key starts after the key keyBegin = keyEnd; keyEnd = end; - if (!FindInReadable("&context="_ns, keyBegin, keyEnd)) + if (!FindInReadable("&context="_ns, keyBegin, keyEnd)) { return NS_ERROR_FAILURE; + } storageName.Assign(Substring(valBegin, keyBegin)); valBegin = keyEnd; // the value of the context key starts after the key diff --git a/netwerk/protocol/about/nsAboutProtocolHandler.cpp b/netwerk/protocol/about/nsAboutProtocolHandler.cpp index de8a83a5dfa6..76127599eb8a 100644 --- a/netwerk/protocol/about/nsAboutProtocolHandler.cpp +++ b/netwerk/protocol/about/nsAboutProtocolHandler.cpp @@ -55,12 +55,8 @@ static bool IsSafeToLinkForUntrustedContent(nsIURI* aURI) { // The about modules for these URL types have the // URI_SAFE_FOR_UNTRUSTED_CONTENT and MAKE_LINKABLE flags set. - if (path.EqualsLiteral("blank") || path.EqualsLiteral("logo") || - path.EqualsLiteral("srcdoc")) { - return true; - } - - return false; + return path.EqualsLiteral("blank") || path.EqualsLiteral("logo") || + path.EqualsLiteral("srcdoc"); } //////////////////////////////////////////////////////////////////////////////// @@ -302,9 +298,9 @@ NS_IMPL_CLASSINFO(nsNestedAboutURI, nullptr, nsIClassInfo::THREADSAFE, NS_IMPL_CI_INTERFACE_GETTER0(nsNestedAboutURI) NS_INTERFACE_MAP_BEGIN(nsNestedAboutURI) - if (aIID.Equals(kNestedAboutURICID)) + if (aIID.Equals(kNestedAboutURICID)) { foundInterface = static_cast(this); - else + } else NS_IMPL_QUERY_CLASSINFO(nsNestedAboutURI) NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI) diff --git a/netwerk/protocol/about/nsAboutProtocolHandler.h b/netwerk/protocol/about/nsAboutProtocolHandler.h index 173742e45883..1a15400361be 100644 --- a/netwerk/protocol/about/nsAboutProtocolHandler.h +++ b/netwerk/protocol/about/nsAboutProtocolHandler.h @@ -109,7 +109,6 @@ class nsNestedAboutURI final : public nsSimpleNestedURI { } [[nodiscard]] NS_IMETHOD Finalize(nsIURI** aURI) override { - mURI->mMutable = false; mURI.forget(aURI); return NS_OK; } @@ -128,12 +127,6 @@ class nsNestedAboutURI final : public nsSimpleNestedURI { return NS_OK; } - void ResetMutable() { - if (mURI) { - mURI->mMutable = true; - } - } - friend class nsNestedAboutURI; }; diff --git a/netwerk/protocol/file/nsFileChannel.cpp b/netwerk/protocol/file/nsFileChannel.cpp index 357324420b83..ffb5f2aab388 100644 --- a/netwerk/protocol/file/nsFileChannel.cpp +++ b/netwerk/protocol/file/nsFileChannel.cpp @@ -306,8 +306,9 @@ nsresult nsFileChannel::MakeFileInputStream(nsIFile* file, if (isDir) { rv = nsDirectoryIndexStream::Create(file, getter_AddRefs(stream)); - if (NS_SUCCEEDED(rv) && !HasContentTypeHint()) + if (NS_SUCCEEDED(rv) && !HasContentTypeHint()) { contentType.AssignLiteral(APPLICATION_HTTP_INDEX_FORMAT); + } } else { rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file, -1, -1, async ? nsIFileInputStream::DEFER_OPEN : 0); @@ -377,8 +378,9 @@ nsresult nsFileChannel::OpenContentStream(bool async, nsIInputStream** result, // to something other than "unknown" to avoid triggering the content-type // sniffer code in nsBaseChannel. // However, don't override explicitly set types. - if (!HasContentTypeHint()) + if (!HasContentTypeHint()) { SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM)); + } } else { nsAutoCString contentType; rv = MakeFileInputStream(file, stream, contentType, async); diff --git a/netwerk/protocol/file/nsFileProtocolHandler.cpp b/netwerk/protocol/file/nsFileProtocolHandler.cpp index d1ab886a0ff2..4a76d353c1fd 100644 --- a/netwerk/protocol/file/nsFileProtocolHandler.cpp +++ b/netwerk/protocol/file/nsFileProtocolHandler.cpp @@ -94,8 +94,9 @@ nsFileProtocolHandler::ReadURLFile(nsIFile* aFile, nsIURI** aURI) { // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s02.html nsAutoCString leafName; nsresult rv = aFile->GetNativeLeafName(leafName); - if (NS_FAILED(rv) || !StringEndsWith(leafName, ".desktop"_ns)) + if (NS_FAILED(rv) || !StringEndsWith(leafName, ".desktop"_ns)) { return NS_ERROR_NOT_AVAILABLE; + } bool isFile = false; rv = aFile->IsFile(&isFile); diff --git a/netwerk/protocol/http/ASpdySession.h b/netwerk/protocol/http/ASpdySession.h index 1a7e4c749653..3009b93d33a4 100644 --- a/netwerk/protocol/http/ASpdySession.h +++ b/netwerk/protocol/http/ASpdySession.h @@ -91,7 +91,7 @@ class ASpdySession : public nsAHttpTransaction { virtual bool CanAcceptWebsocket() = 0; }; -typedef bool (*ALPNCallback)(nsISupports*); // nsISSLSocketControl is typical +using ALPNCallback = bool (*)(nsISupports*); // nsISSLSocketControl is typical // this is essentially a single instantiation as a member of nsHttpHandler. // It could be all static except using static ctors of XPCOM objects is a @@ -111,14 +111,14 @@ class SpdyInformation { // determine if a version of the protocol is enabled for index < kCount bool ProtocolEnabled(uint32_t index) const; - SpdyVersion Version[kCount]; // telemetry enum e.g. SPDY_VERSION_31 + SpdyVersion Version[kCount]{}; // telemetry enum e.g. SPDY_VERSION_31 nsCString VersionString[kCount]; // npn string e.g. "spdy/3.1" // the ALPNCallback function allows the protocol stack to decide whether or // not to offer a particular protocol based on the known TLS information // that we will offer in the client hello (such as version). There has // not been a Server Hello received yet, so not much else can be considered. - ALPNCallback ALPNCallbacks[kCount]; + ALPNCallback ALPNCallbacks[kCount]{}; }; } // namespace net diff --git a/netwerk/protocol/http/AlternateServices.h b/netwerk/protocol/http/AlternateServices.h index 5ecb63ae2b34..e6579ede4e92 100644 --- a/netwerk/protocol/http/AlternateServices.h +++ b/netwerk/protocol/http/AlternateServices.h @@ -57,7 +57,7 @@ class AltSvcMapping { public: AltSvcMapping(DataStorage* storage, int32_t storageEpoch, - const nsCString& serialized); + const nsCString& str); static void ProcessHeader( const nsCString& buf, const nsCString& originScheme, @@ -69,7 +69,7 @@ class AltSvcMapping { // AcceptableProxy() decides whether a particular proxy configuration (pi) is // suitable for use with Alt-Svc. No proxy (including a null pi) is suitable. - static bool AcceptableProxy(nsProxyInfo* pi); + static bool AcceptableProxy(nsProxyInfo* proxyInfo); const nsCString& AlternateHost() const { return mAlternateHost; } const nsCString& OriginHost() const { return mOriginHost; } @@ -99,14 +99,14 @@ class AltSvcMapping { const nsACString& originHost, int32_t originPort, bool privateBrowsing, const OriginAttributes& originAttributes, - bool aIsHttp3); + bool aHttp3); bool IsHttp3() { return mIsHttp3; } const nsCString& NPNToken() const { return mNPNToken; } private: virtual ~AltSvcMapping() = default; - void SyncString(const nsCString& val); + void SyncString(const nsCString& str); RefPtr mStorage; int32_t mStorageEpoch; void Serialize(nsCString& out); @@ -126,7 +126,7 @@ class AltSvcMapping { MOZ_INIT_OUTSIDE_CTOR uint32_t mExpiresAt; // alt-svc mappping MOZ_INIT_OUTSIDE_CTOR bool mValidated; - MOZ_INIT_OUTSIDE_CTOR bool mHttps; // origin is https:// + MOZ_INIT_OUTSIDE_CTOR bool mHttps{}; // origin is https:// MOZ_INIT_OUTSIDE_CTOR bool mMixedScheme; // .wk allows http and https on same con @@ -191,9 +191,9 @@ class AltSvcCache { uint32_t caps, const OriginAttributes& originAttributes); // main thread already_AddRefed GetAltServiceMapping( - const nsACString& scheme, const nsACString& host, int32_t port, bool pb, - const OriginAttributes& originAttributes, bool aHttp2Allowed, - bool aHttp3Allowed); + const nsACString& scheme, const nsACString& host, int32_t port, + bool privateBrowsing, const OriginAttributes& originAttributes, + bool aHttp2Allowed, bool aHttp3Allowed); void ClearAltServiceMappings(); void ClearHostMapping(const nsACString& host, int32_t port, const OriginAttributes& originAttributes); diff --git a/netwerk/protocol/http/BackgroundChannelRegistrar.h b/netwerk/protocol/http/BackgroundChannelRegistrar.h index fe6ba88ac41f..b6d9380ddd38 100644 --- a/netwerk/protocol/http/BackgroundChannelRegistrar.h +++ b/netwerk/protocol/http/BackgroundChannelRegistrar.h @@ -18,10 +18,10 @@ class HttpBackgroundChannelParent; class HttpChannelParent; class BackgroundChannelRegistrar final : public nsIBackgroundChannelRegistrar { - typedef nsRefPtrHashtable - ChannelHashtable; - typedef nsRefPtrHashtable - BackgroundChannelHashtable; + using ChannelHashtable = + nsRefPtrHashtable; + using BackgroundChannelHashtable = + nsRefPtrHashtable; public: NS_DECL_ISUPPORTS diff --git a/netwerk/protocol/http/ConnectionDiagnostics.cpp b/netwerk/protocol/http/ConnectionDiagnostics.cpp index bc424e003329..ad170b418c61 100644 --- a/netwerk/protocol/http/ConnectionDiagnostics.cpp +++ b/netwerk/protocol/http/ConnectionDiagnostics.cpp @@ -47,7 +47,7 @@ void nsHttpConnectionMgr::OnMsgPrintDiagnostics(int32_t, ARefBase*) { mLogData.AppendPrintf("mNumActiveConns = %d\n", mNumActiveConns); mLogData.AppendPrintf("mNumIdleConns = %d\n", mNumIdleConns); - for (RefPtr ent : mCT.Values()) { + for (const RefPtr& ent : mCT.Values()) { mLogData.AppendPrintf( " AtActiveConnectionLimit = %d\n", AtActiveConnectionLimit(ent, NS_HTTP_ALLOW_KEEPALIVE)); @@ -148,8 +148,8 @@ void nsHttpConnection::PrintDiagnostics(nsCString& log) { log.AppendPrintf(" iskeepalive = %d dontReuse = %d isReused = %d\n", IsKeepAlive(), mDontReuse, mIsReused); - log.AppendPrintf(" mTransaction = %d mSpdySession = %d\n", - !!mTransaction.get(), !!mSpdySession.get()); + log.AppendPrintf(" mTransaction = %d mSpdySession = %d\n", !!mTransaction, + !!mSpdySession); PRIntervalTime now = PR_IntervalNow(); log.AppendPrintf(" time since last read = %ums\n", @@ -205,12 +205,13 @@ void Http2Session::PrintDiagnostics(nsCString& log) { PR_IntervalToMilliseconds(now - mLastReadEpoch)); log.AppendPrintf(" Idle for Data Activity = %ums\n", PR_IntervalToMilliseconds(now - mLastDataReadEpoch)); - if (mPingSentEpoch) + if (mPingSentEpoch) { log.AppendPrintf(" Ping Outstanding (ping) = %ums, expired = %d\n", PR_IntervalToMilliseconds(now - mPingSentEpoch), now - mPingSentEpoch >= gHttpHandler->SpdyPingTimeout()); - else + } else { log.AppendPrintf(" No Ping Outstanding\n"); + } } void nsHttpTransaction::PrintDiagnostics(nsCString& log) { diff --git a/netwerk/protocol/http/ConnectionEntry.cpp b/netwerk/protocol/http/ConnectionEntry.cpp index b9044b56916b..6365c1f85801 100644 --- a/netwerk/protocol/http/ConnectionEntry.cpp +++ b/netwerk/protocol/http/ConnectionEntry.cpp @@ -48,9 +48,8 @@ bool ConnectionEntry::AvailableForDispatchNow() { return true; } - return gHttpHandler->ConnMgr()->GetH2orH3ActiveConn(this, false, false) - ? true - : false; + return gHttpHandler->ConnMgr()->GetH2orH3ActiveConn(this, false, false) != + nullptr; } uint32_t ConnectionEntry::UnconnectedDnsAndConnectSockets() const { @@ -810,7 +809,7 @@ HttpRetParams ConnectionEntry::GetConnectionData() { data.idle.AppendElement(info); } for (uint32_t i = 0; i < mDnsAndConnectSockets.Length(); i++) { - DnsAndConnectSockets dnsAndSock; + DnsAndConnectSockets dnsAndSock{}; dnsAndSock.speculative = mDnsAndConnectSockets[i]->IsSpeculative(); data.dnsAndSocks.AppendElement(dnsAndSock); } diff --git a/netwerk/protocol/http/DelayHttpChannelQueue.cpp b/netwerk/protocol/http/DelayHttpChannelQueue.cpp index 03500ef94377..4ada97a248e0 100644 --- a/netwerk/protocol/http/DelayHttpChannelQueue.cpp +++ b/netwerk/protocol/http/DelayHttpChannelQueue.cpp @@ -66,11 +66,7 @@ bool DelayHttpChannelQueue::Initialize() { } rv = obs->AddObserver(this, "xpcom-shutdown", false); - if (NS_WARN_IF(NS_FAILED(rv))) { - return false; - } - - return true; + return !NS_WARN_IF(NS_FAILED(rv)); } NS_IMETHODIMP diff --git a/netwerk/protocol/http/DnsAndConnectSocket.cpp b/netwerk/protocol/http/DnsAndConnectSocket.cpp index 4a0242c72900..51a91cc5bff0 100644 --- a/netwerk/protocol/http/DnsAndConnectSocket.cpp +++ b/netwerk/protocol/http/DnsAndConnectSocket.cpp @@ -1292,16 +1292,15 @@ nsresult DnsAndConnectSocket::TransportSetup::OnLookupComplete( if (dnsAndSock->mEnt->mConnInfo->IsHttp3()) { mState = TransportSetup::TransportSetupState::RESOLVED; return status; - } else { - nsresult rv = SetupStreams(dnsAndSock); - if (NS_SUCCEEDED(rv)) { - mState = TransportSetup::TransportSetupState::CONNECTING; - } else { - CloseAll(); - mState = TransportSetup::TransportSetupState::DONE; - } - return rv; } + nsresult rv = SetupStreams(dnsAndSock); + if (NS_SUCCEEDED(rv)) { + mState = TransportSetup::TransportSetupState::CONNECTING; + } else { + CloseAll(); + mState = TransportSetup::TransportSetupState::DONE; + } + return rv; } // DNS lookup status failed diff --git a/netwerk/protocol/http/Http2Compression.cpp b/netwerk/protocol/http/Http2Compression.cpp index 8dba00768804..16de42b73c1b 100644 --- a/netwerk/protocol/http/Http2Compression.cpp +++ b/netwerk/protocol/http/Http2Compression.cpp @@ -562,7 +562,8 @@ nsresult Http2Decompressor::OutputHeader(const nsACString& name, if (*cPtr == ':') { isColonHeader = true; break; - } else if (*cPtr != ' ' && *cPtr != '\t') { + } + if (*cPtr != ' ' && *cPtr != '\t') { isColonHeader = false; break; } @@ -1115,7 +1116,8 @@ nsresult Http2Compressor::EncodeHeaderBlock( if (*cPtr == ':') { isColonHeader = true; break; - } else if (*cPtr != ' ' && *cPtr != '\t') { + } + if (*cPtr != ' ' && *cPtr != '\t') { isColonHeader = false; break; } @@ -1126,8 +1128,9 @@ nsresult Http2Compressor::EncodeHeaderBlock( int32_t valueIndex = colonIndex + 1; - while (valueIndex < crlfIndex && beginBuffer[valueIndex] == ' ') + while (valueIndex < crlfIndex && beginBuffer[valueIndex] == ' ') { ++valueIndex; + } nsDependentCSubstring value = Substring(beginBuffer + valueIndex, beginBuffer + crlfIndex); diff --git a/netwerk/protocol/http/Http2Compression.h b/netwerk/protocol/http/Http2Compression.h index 1ab6661449b4..e10ce9e7ea6c 100644 --- a/netwerk/protocol/http/Http2Compression.h +++ b/netwerk/protocol/http/Http2Compression.h @@ -125,15 +125,15 @@ class Http2Decompressor final : public Http2BaseCompressor { [[nodiscard]] nsresult DoLiteralNeverIndexed(); [[nodiscard]] nsresult DoContextUpdate(); - [[nodiscard]] nsresult DecodeInteger(uint32_t prefixLen, uint32_t& result); + [[nodiscard]] nsresult DecodeInteger(uint32_t prefixLen, uint32_t& accum); [[nodiscard]] nsresult OutputHeader(uint32_t index); [[nodiscard]] nsresult OutputHeader(const nsACString& name, const nsACString& value); [[nodiscard]] nsresult CopyHeaderString(uint32_t index, nsACString& name); - [[nodiscard]] nsresult CopyStringFromInput(uint32_t index, nsACString& val); + [[nodiscard]] nsresult CopyStringFromInput(uint32_t bytes, nsACString& val); uint8_t ExtractByte(uint8_t bitsLeft, uint32_t& bytesConsumed); - [[nodiscard]] nsresult CopyHuffmanStringFromInput(uint32_t index, + [[nodiscard]] nsresult CopyHuffmanStringFromInput(uint32_t bytes, nsACString& val); [[nodiscard]] nsresult DecodeHuffmanCharacter( const HuffmanIncomingTable* table, uint8_t& c, uint32_t& bytesConsumed, diff --git a/netwerk/protocol/http/Http2Push.cpp b/netwerk/protocol/http/Http2Push.cpp index 8e3b0be0cc8e..11d1800437f4 100644 --- a/netwerk/protocol/http/Http2Push.cpp +++ b/netwerk/protocol/http/Http2Push.cpp @@ -327,8 +327,9 @@ nsresult Http2PushedStream::GetBufferedData(char* buf, uint32_t count, nsresult rv = mBufferedPush->GetBufferedData(buf, count, countWritten); if (NS_FAILED(rv)) return rv; - if (!*countWritten) + if (!*countWritten) { rv = GetPushComplete() ? NS_BASE_STREAM_CLOSED : NS_BASE_STREAM_WOULD_BLOCK; + } return rv; } diff --git a/netwerk/protocol/http/Http2Push.h b/netwerk/protocol/http/Http2Push.h index f3f9fbac6f5d..7601b8c81156 100644 --- a/netwerk/protocol/http/Http2Push.h +++ b/netwerk/protocol/http/Http2Push.h @@ -37,7 +37,7 @@ class Http2PushedStream final : public Http2Stream { // The consumer stream is the synthetic pull stream hooked up to this push virtual Http2Stream* GetConsumerStream() override { return mConsumerStream; }; - void SetConsumerStream(Http2Stream* aStream); + void SetConsumerStream(Http2Stream* consumer); [[nodiscard]] bool GetHashKey(nsCString& key); // override of Http2Stream @@ -48,10 +48,10 @@ class Http2PushedStream final : public Http2Stream { void AdjustInitialWindow() override; nsIRequestContext* RequestContext() override { return mRequestContext; }; - void ConnectPushedStream(Http2Stream* consumer); + void ConnectPushedStream(Http2Stream* stream); [[nodiscard]] bool TryOnPush(); - [[nodiscard]] static bool TestOnPush(Http2Stream* consumer); + [[nodiscard]] static bool TestOnPush(Http2Stream* stream); virtual bool DeferCleanup(nsresult status) override; void SetDeferCleanupOnSuccess(bool val) { mDeferCleanupOnSuccess = val; } diff --git a/netwerk/protocol/http/Http2Session.cpp b/netwerk/protocol/http/Http2Session.cpp index ef3095fdb47d..6e58684d9662 100644 --- a/netwerk/protocol/http/Http2Session.cpp +++ b/netwerk/protocol/http/Http2Session.cpp @@ -284,7 +284,7 @@ void Http2Session::LogIO(Http2Session* self, Http2Stream* stream, } } -typedef nsresult (*Http2ControlFx)(Http2Session* self); +using Http2ControlFx = nsresult (*)(Http2Session*); static Http2ControlFx sControlFunctions[] = { nullptr, // type 0 data is not a control function Http2Session::RecvHeaders, @@ -307,8 +307,9 @@ bool Http2Session::RoomForMoreConcurrent() { } bool Http2Session::RoomForMoreStreams() { - if (mNextStreamID + mStreamTransactionHash.Count() * 2 > kMaxStreamID) + if (mNextStreamID + mStreamTransactionHash.Count() * 2 > kMaxStreamID) { return false; + } return !mShouldGoAway; } @@ -372,8 +373,9 @@ uint32_t Http2Session::ReadTimeoutTick(PRIntervalTime now) { for (uint32_t index = mPushedStreams.Length(); index > 0; --index) { Http2PushedStream* pushedStream = mPushedStreams[index - 1]; - if (timestampNow.IsNull()) + if (timestampNow.IsNull()) { timestampNow = TimeStamp::Now(); // lazy initializer + } // if stream finished, but is not connected, and its been like that for // long then cleanup the stream. @@ -1354,10 +1356,11 @@ nsresult Http2Session::RecvHeaders(Http2Session* self) { // frame to be HEADERS of the same ID bool endHeadersFlag = self->mInputFrameFlags & kFlag_END_HEADERS; - if (endHeadersFlag) + if (endHeadersFlag) { self->mExpectedHeaderID = 0; - else + } else { self->mExpectedHeaderID = self->mInputFrameID; + } uint32_t priorityLen = 0; if (self->mInputFrameFlags & kFlag_PRIORITY) { @@ -1404,8 +1407,9 @@ nsresult Http2Session::RecvHeaders(Http2Session* self) { "0x%X failed. NextStreamID = 0x%X\n", self, self->mInputFrameID, self->mNextStreamID)); - if (self->mInputFrameID >= self->mNextStreamID) + if (self->mInputFrameID >= self->mNextStreamID) { self->GenerateRstStream(PROTOCOL_ERROR, self->mInputFrameID); + } self->mDecompressBuffer.Append( &self->mInputFrameBuffer[kFrameHeaderBytes + paddingControlBytes + @@ -1541,7 +1545,8 @@ nsresult Http2Session::ResponseHeadersComplete() { CleanupStream(mInputFrameDataStream, NS_ERROR_NET_RESET, CANCEL_ERROR); ResetDownstreamState(); return NS_OK; - } else if (NS_FAILED(rv)) { + } + if (NS_FAILED(rv)) { return rv; } @@ -1940,7 +1945,8 @@ nsresult Http2Session::RecvPushPromise(Http2Session* self) { self->GenerateRstStream(PROTOCOL_ERROR, promisedID); self->ResetDownstreamState(); return NS_OK; - } else if (NS_FAILED(rv)) { + } + if (NS_FAILED(rv)) { // This is fatal to the session. self->mGoAwayReason = COMPRESSION_ERROR; return rv; @@ -1962,8 +1968,9 @@ nsresult Http2Session::RecvPushPromise(Http2Session* self) { return NS_ERROR_FAILURE; } - if (promisedID > self->mOutgoingGoAwayID) + if (promisedID > self->mOutgoingGoAwayID) { self->mOutgoingGoAwayID = promisedID; + } // Fake the request side of the pushed HTTP transaction. Sets up hash // key and origin @@ -2169,8 +2176,9 @@ nsresult Http2Session::RecvGoAway(Http2Session* self) { stream->Transaction()->DisableSpdy(); } self->CloseStream(stream, NS_ERROR_NET_RESET); - if (stream->HasRegisteredID()) + if (stream->HasRegisteredID()) { self->mStreamIDHash.Remove(stream->StreamID()); + } self->mStreamTransactionHash.Remove(stream->Transaction()); } @@ -2223,8 +2231,9 @@ nsresult Http2Session::RecvWindowUpdate(Http2Session* self) { LOG3(("Http2Session::RecvWindowUpdate %p lookup streamID 0x%X failed.\n", self, self->mInputFrameID)); // only resest the session if the ID is one we haven't ever opened - if (self->mInputFrameID >= self->mNextStreamID) + if (self->mInputFrameID >= self->mNextStreamID) { self->GenerateRstStream(PROTOCOL_ERROR, self->mInputFrameID); + } self->ResetDownstreamState(); return NS_OK; } @@ -2932,8 +2941,9 @@ nsresult Http2Session::ReadyToProcessDataFrame( ("Http2Session::ReadyToProcessDataFrame %p lookup streamID 0x%X " "failed. Next = 0x%X", this, mInputFrameID, mNextStreamID)); - if (mInputFrameID >= mNextStreamID) + if (mInputFrameID >= mNextStreamID) { GenerateRstStream(PROTOCOL_ERROR, mInputFrameID); + } ChangeDownstreamState(DISCARDING_DATA_FRAME); } else if (mInputFrameDataStream->RecvdFin() || mInputFrameDataStream->RecvdReset() || @@ -2943,8 +2953,9 @@ nsresult Http2Session::ReadyToProcessDataFrame( "Data arrived for already server closed stream.\n", this, mInputFrameID)); if (mInputFrameDataStream->RecvdFin() || - mInputFrameDataStream->RecvdReset()) + mInputFrameDataStream->RecvdReset()) { GenerateRstStream(STREAM_CLOSED_ERROR, mInputFrameID); + } ChangeDownstreamState(DISCARDING_DATA_FRAME); } else if (mInputFrameDataSize == 0 && !mInputFrameFinal) { // Only if non-final because the stream properly handles final frames of any @@ -3205,7 +3216,8 @@ nsresult Http2Session::WriteSegmentsAgain(nsAHttpSegmentWriter* writer, "frame", this, mInputFrameID)); return SessionError(PROTOCOL_ERROR); - } else if (1U + mPaddingLength == mInputFrameDataSize) { + } + if (1U + mPaddingLength == mInputFrameDataSize) { // This frame consists entirely of padding, we can just discard it LOG3( ("Http2Session::WriteSegments %p stream 0x%X frame with only padding", @@ -3373,7 +3385,7 @@ nsresult Http2Session::WriteSegmentsAgain(nsAHttpSegmentWriter* writer, Http2Stream* pushSink = streamToCleanup->GetConsumerStream(); if (pushSink) { bool enqueueSink = true; - for (auto s : mPushesReadyForRead) { + for (const auto& s : mPushesReadyForRead) { if (s == pushSink) { enqueueSink = false; break; @@ -3569,8 +3581,10 @@ nsresult Http2Session::ProcessSlowConsumer(Http2Stream* slowConsumer, void Http2Session::UpdateLocalStreamWindow(Http2Stream* stream, uint32_t bytes) { - if (!stream) // this is ok - it means there was a data frame for a rst stream + if (!stream) { // this is ok - it means there was a data frame for a rst + // stream return; + } // If this data packet was not for a valid or live stream then there // is no reason to mess with the flow control @@ -3593,8 +3607,9 @@ void Http2Session::UpdateLocalStreamWindow(Http2Stream* stream, if (!unacked) return; - if ((unacked < kMinimumToAck) && (localWindow > kEmergencyWindowThreshold)) + if ((unacked < kMinimumToAck) && (localWindow > kEmergencyWindowThreshold)) { return; + } if (!stream->HasSink()) { LOG3( @@ -3643,8 +3658,9 @@ void Http2Session::UpdateLocalSessionWindow(uint32_t bytes) { // Don't necessarily ack every data packet. Only do it // after a significant amount of data. if ((mLocalSessionWindow > (mInitialRwin - kMinimumToAck)) && - (mLocalSessionWindow > kEmergencyWindowThreshold)) + (mLocalSessionWindow > kEmergencyWindowThreshold)) { return; + } // Only send max bits of window updates at a time. uint64_t toack64 = mInitialRwin - mLocalSessionWindow; @@ -3828,8 +3844,9 @@ nsresult Http2Session::OnReadSegment(const char* buf, uint32_t count, // for other routines to use - but this is an all-or-nothing function, // so if it will not all fit just return WOULD_BLOCK - if ((mOutputQueueUsed + count) > (mOutputQueueSize - kQueueReserved)) + if ((mOutputQueueUsed + count) > (mOutputQueueSize - kQueueReserved)) { return NS_BASE_STREAM_WOULD_BLOCK; + } memcpy(mOutputQueueBuffer.get() + mOutputQueueUsed, buf, count); mOutputQueueUsed += count; @@ -3845,8 +3862,9 @@ nsresult Http2Session::CommitToSegmentSize(uint32_t count, if (mOutputQueueUsed && !mAttemptingEarlyData) FlushOutputQueue(); // would there be enough room to buffer this if needed? - if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved)) + if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved)) { return NS_OK; + } // if we are using part of our buffers already, try again later unless // forceCommitment is set. @@ -3858,8 +3876,9 @@ nsresult Http2Session::CommitToSegmentSize(uint32_t count, RealignOutputQueue(); // is there enough room now? - if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved)) + if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved)) { return NS_OK; + } } // resize the buffers as needed @@ -3933,8 +3952,9 @@ nsresult Http2Session::OnWriteSegment(char* buf, uint32_t count, } mInputFrameDataStream->UpdateTransportReadEvents(*countWritten); - if ((mInputFrameDataRead == mInputFrameDataSize) && !mInputFrameFinal) + if ((mInputFrameDataRead == mInputFrameDataSize) && !mInputFrameFinal) { ResetDownstreamState(); + } return rv; } @@ -4206,7 +4226,8 @@ nsresult Http2Session::ConfirmTLSProfile() { LOG3(("Http2Session::ConfirmTLSProfile %p FAILED due to DH %d < 2048\n", this, keybits)); return SessionError(INADEQUATE_SECURITY); - } else if (kea == ssl_kea_ecdh && keybits < 224) { // see rfc7540 9.2.1. + } + if (kea == ssl_kea_ecdh && keybits < 224) { // see rfc7540 9.2.1. LOG3(("Http2Session::ConfirmTLSProfile %p FAILED due to ECDH %d < 224\n", this, keybits)); return SessionError(INADEQUATE_SECURITY); @@ -4627,12 +4648,8 @@ bool Http2Session::CanAcceptWebsocket() { LOG3(("Http2Session::CanAcceptWebsocket %p enable=%d allow=%d processed=%d", this, mEnableWebsockets, mPeerAllowsWebsockets, mProcessedWaitingWebsockets)); - if (mEnableWebsockets && - (mPeerAllowsWebsockets || !mProcessedWaitingWebsockets)) { - return true; - } - - return false; + return mEnableWebsockets && + (mPeerAllowsWebsockets || !mProcessedWaitingWebsockets); } } // namespace net diff --git a/netwerk/protocol/http/Http2Session.h b/netwerk/protocol/http/Http2Session.h index e66bf73d79ac..b4c85b7d333f 100644 --- a/netwerk/protocol/http/Http2Session.h +++ b/netwerk/protocol/http/Http2Session.h @@ -226,7 +226,7 @@ class Http2Session final : public ASpdySession, // an overload of nsAHttpSegementReader [[nodiscard]] virtual nsresult CommitToSegmentSize( - uint32_t size, bool forceCommitment) override; + uint32_t count, bool forceCommitment) override; [[nodiscard]] nsresult BufferOutput(const char*, uint32_t, uint32_t*); void FlushOutputQueue(); uint32_t AmountOfOutputBuffered() { @@ -554,7 +554,8 @@ class Http2Session final : public ASpdySession, // remember them put them into mReadyForWrite queue when 0RTT finishes. nsTArray> mCannotDo0RTTStreams; - bool RealJoinConnection(const nsACString& hostname, int32_t port, bool jk); + bool RealJoinConnection(const nsACString& hostname, int32_t port, + bool justKidding); bool TestOriginFrame(const nsACString& name, int32_t port); bool mOriginFrameActivated; nsTHashMap mOriginFrame; diff --git a/netwerk/protocol/http/Http2Stream.cpp b/netwerk/protocol/http/Http2Stream.cpp index f0028ebd0736..e911c71216eb 100644 --- a/netwerk/protocol/http/Http2Stream.cpp +++ b/netwerk/protocol/http/Http2Stream.cpp @@ -170,8 +170,9 @@ nsresult Http2Stream::ReadSegments(nsAHttpSegmentReader* reader, uint32_t count, // Check to see if the transaction's request could be written out now. // If not, mark the stream for callback when writing can proceed. if (NS_SUCCEEDED(rv) && mUpstreamState == GENERATING_HEADERS && - !mRequestHeadersDone) + !mRequestHeadersDone) { mSession->TransactionHasDataToWrite(this); + } // mTxinlineFrameUsed represents any queued un-sent frame. It might // be 0 if there is no such frame, which is not a gurantee that we @@ -843,9 +844,10 @@ void Http2Stream::UpdateTransportSendEvents(uint32_t count) { mSocketTransport->SetSendBufferSize(bufferSize); } - if (mUpstreamState != SENDING_FIN_STREAM) + if (mUpstreamState != SENDING_FIN_STREAM) { mTransaction->OnTransportStatus(mSocketTransport, NS_NET_STATUS_SENDING_TO, mTotalSent); + } if (!mSentWaitingFor && !mRequestBodyLenRemaining) { mSentWaitingFor = 1; @@ -902,8 +904,9 @@ nsresult Http2Stream::TransmitFrame(const char* buf, uint32_t* countUsed, MOZ_ASSERT(!forceCommitment, "forceCommitment with WOULD_BLOCK"); mSession->TransactionHasDataToWrite(this); } - if (NS_FAILED(rv)) // this will include WOULD_BLOCK + if (NS_FAILED(rv)) { // this will include WOULD_BLOCK return rv; + } // This function calls mSegmentReader->OnReadSegment to report the actual // http/2 bytes through to the session object and then the HttpConnection @@ -1475,14 +1478,17 @@ nsresult Http2Stream::OnReadSegment(const char* buf, uint32_t count, // Its amazing we send anything at all. dataLength = std::min(count, mChunkSize); - if (dataLength > Http2Session::kMaxFrameData) + if (dataLength > Http2Session::kMaxFrameData) { dataLength = Http2Session::kMaxFrameData; + } - if (dataLength > mSession->ServerSessionWindow()) + if (dataLength > mSession->ServerSessionWindow()) { dataLength = static_cast(mSession->ServerSessionWindow()); + } - if (dataLength > mServerReceiveWindow) + if (dataLength > mServerReceiveWindow) { dataLength = static_cast(mServerReceiveWindow); + } LOG3( ("Http2Stream this=%p id 0x%X send calculation " diff --git a/netwerk/protocol/http/Http2Stream.h b/netwerk/protocol/http/Http2Stream.h index 01c01039e2b9..9265d56f15c2 100644 --- a/netwerk/protocol/http/Http2Stream.h +++ b/netwerk/protocol/http/Http2Stream.h @@ -172,7 +172,7 @@ class Http2Stream : public nsAHttpSegmentReader, // Mirrors nsAHttpTransaction bool Do0RTT(); - nsresult Finish0RTT(bool aRestart, bool aAlpnIgnored); + nsresult Finish0RTT(bool aRestart, bool aAlpnChanged); nsresult GetOriginAttributes(mozilla::OriginAttributes* oa); @@ -242,8 +242,8 @@ class Http2Stream : public nsAHttpSegmentReader, // The underlying socket transport object is needed to propogate some events nsISocketTransport* mSocketTransport; - uint8_t mPriorityWeight; // h2 weight - uint32_t mPriorityDependency; // h2 stream id this one depends on + uint8_t mPriorityWeight = 0; // h2 weight + uint32_t mPriorityDependency = 0; // h2 stream id this one depends on uint64_t mCurrentTopBrowsingContextId; uint64_t mTransactionTabId; @@ -325,7 +325,7 @@ class Http2Stream : public nsAHttpSegmentReader, // close by setting this to the max value. int64_t mRequestBodyLenRemaining; - uint32_t mPriority; // geckoish weight + uint32_t mPriority = 0; // geckoish weight // mClientReceiveWindow, mServerReceiveWindow, and mLocalUnacked are for flow // control. *window are signed because the race conditions in asynchronous diff --git a/netwerk/protocol/http/Http3Session.cpp b/netwerk/protocol/http/Http3Session.cpp index 9bbe6d8fea16..66e889626abd 100644 --- a/netwerk/protocol/http/Http3Session.cpp +++ b/netwerk/protocol/http/Http3Session.cpp @@ -360,7 +360,7 @@ nsresult Http3Session::ProcessEvents() { // We need an array to pick up header data or a resumption token. nsTArray data; - Http3Event event; + Http3Event event{}; event.tag = Http3Event::Tag::NoEvent; nsresult rv = mHttp3Connection->GetEvent(&event, data); @@ -745,9 +745,8 @@ bool Http3Session::AddStream(nsAHttpTransaction* aHttpTransaction, mCannotDo0RTTStreams.AppendElement(stream); } return true; - } else { - m0RTTStreams.AppendElement(stream); } + m0RTTStreams.AppendElement(stream); } if (!mFirstHttpTransaction && !IsConnected()) { @@ -1759,7 +1758,7 @@ void Http3Session::CloseConnectionTelemetry(CloseError& aError, bool aClosing) { Telemetry::Accumulate(Telemetry::HTTP3_CONNECTION_CLOSE_CODE_3, key, value); - Http3Stats stats; + Http3Stats stats{}; mHttp3Connection->GetStats(&stats); if (stats.packets_tx > 0) { diff --git a/netwerk/protocol/http/Http3Session.h b/netwerk/protocol/http/Http3Session.h index 9740da99c8f0..2159c1d5c85c 100644 --- a/netwerk/protocol/http/Http3Session.h +++ b/netwerk/protocol/http/Http3Session.h @@ -60,9 +60,9 @@ class Http3Session final : public nsAHttpTransaction, public nsAHttpConnection { // The folowing functions are used by Http3Stream: nsresult TryActivating(const nsACString& aMethod, const nsACString& aScheme, - const nsACString& aHost, const nsACString& aPath, - const nsACString& aHeaders, uint64_t* aStreamId, - Http3Stream* aStream); + const nsACString& aAuthorityHeader, + const nsACString& aPath, const nsACString& aHeaders, + uint64_t* aStreamId, Http3Stream* aStream); void CloseSendingSide(uint64_t aStreamId); nsresult SendRequestBody(uint64_t aStreamId, const char* buf, uint32_t count, uint32_t* countRead); diff --git a/netwerk/protocol/http/HttpBackgroundChannelChild.h b/netwerk/protocol/http/HttpBackgroundChannelChild.h index af9fba57f8d8..0bbabb070af2 100644 --- a/netwerk/protocol/http/HttpBackgroundChannelChild.h +++ b/netwerk/protocol/http/HttpBackgroundChannelChild.h @@ -139,7 +139,7 @@ class HttpBackgroundChannelChild final : public PHttpBackgroundChannelChild { ODASource mFirstODASource; // Indicate whether HttpChannelChild::ProcessOnStopRequest is called. - bool mOnStopRequestCalled; + bool mOnStopRequestCalled = false; // This is used when we receive the console report from parent process, but // still not get the OnStopRequest from socket process. diff --git a/netwerk/protocol/http/HttpBaseChannel.h b/netwerk/protocol/http/HttpBaseChannel.h index 85377ae3c449..c6517298c33f 100644 --- a/netwerk/protocol/http/HttpBaseChannel.h +++ b/netwerk/protocol/http/HttpBaseChannel.h @@ -495,8 +495,8 @@ class HttpBaseChannel : public nsHashPropertyBag, nsCOMPtr referrerInfo; Maybe timedChannel; nsCOMPtr uploadStream; - uint64_t uploadStreamLength; - bool uploadStreamHasHeaders; + uint64_t uploadStreamLength = 0; + bool uploadStreamHasHeaders = false; Maybe contentType; Maybe contentLength; @@ -1022,8 +1022,9 @@ inline void HttpAsyncAborter::HandleAsyncAbort() { mThis->DoNotifyListener(); // finally remove ourselves from the load group. - if (mThis->mLoadGroup) + if (mThis->mLoadGroup) { mThis->mLoadGroup->RemoveRequest(mThis, nullptr, mThis->mStatus); + } } template diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp index 0b937b63c9d3..abda75df734f 100644 --- a/netwerk/protocol/http/HttpChannelChild.cpp +++ b/netwerk/protocol/http/HttpChannelChild.cpp @@ -420,8 +420,9 @@ void HttpChannelChild::OnStartRequest( MOZ_ASSERT(!aRequestHeaders.HasHeader(nsHttp::Cookie)); MOZ_ASSERT(!nsHttpResponseHead(aResponseHead).HasHeader(nsHttp::Set_Cookie)); - if (aUseResponseHead && !mCanceled) + if (aUseResponseHead && !mCanceled) { mResponseHead = MakeUnique(aResponseHead); + } if (!aArgs.securityInfoSerialization().IsEmpty()) { [[maybe_unused]] nsresult rv = NS_DeserializeObject( @@ -1799,10 +1800,11 @@ HttpChannelChild::OnRedirectVerifyCallback(nsresult aResult) { targetLoadInfoForwarder.emplace(args); } - if (CanSend()) + if (CanSend()) { SendRedirect2Verify(aResult, *headerTuples, sourceRequestBlockingReason, targetLoadInfoForwarder, loadFlags, referrerInfo, redirectURI, corsPreflightArgs); + } return NS_OK; } diff --git a/netwerk/protocol/http/HttpChannelChild.h b/netwerk/protocol/http/HttpChannelChild.h index 09e6470cbd75..422f0bc3e238 100644 --- a/netwerk/protocol/http/HttpChannelChild.h +++ b/netwerk/protocol/http/HttpChannelChild.h @@ -204,7 +204,7 @@ class HttpChannelChild final : public PHttpChannelChild, // Callbacks while receiving OnTransportAndData/OnStopRequest/OnProgress/ // OnStatus/FlushedForDiversion/DivertMessages on background IPC channel. void ProcessOnTransportAndData(const nsresult& aChannelStatus, - const nsresult& aStatus, + const nsresult& aTransportStatus, const uint64_t& aOffset, const uint32_t& aCount, const nsCString& aData); @@ -397,7 +397,8 @@ class HttpChannelChild final : public PHttpChannelChild, const nsHttpHeaderArray& aResponseTrailers); void FailedAsyncOpen(const nsresult& status); void HandleAsyncAbort(); - void Redirect1Begin(const uint32_t& registrarId, const URIParams& newUri, + void Redirect1Begin(const uint32_t& registrarId, + const URIParams& newOriginalURI, const uint32_t& newLoadFlags, const uint32_t& redirectFlags, const ParentLoadInfoForwarderArgs& loadInfoForwarder, diff --git a/netwerk/protocol/http/HttpChannelParent.cpp b/netwerk/protocol/http/HttpChannelParent.cpp index 5fc171ada44e..408eceb332f9 100644 --- a/netwerk/protocol/http/HttpChannelParent.cpp +++ b/netwerk/protocol/http/HttpChannelParent.cpp @@ -438,7 +438,7 @@ bool HttpChannelParent::DoAsyncOpen( } httpChannel->SetTimingEnabled(true); if (mPBOverride != kPBOverride_Unset) { - httpChannel->SetPrivate(mPBOverride == kPBOverride_Private ? true : false); + httpChannel->SetPrivate(mPBOverride == kPBOverride_Private); } if (doResumeAt) httpChannel->ResumeAt(startPos, entityID); @@ -457,8 +457,9 @@ bool HttpChannelParent::DoAsyncOpen( httpChannel->SetTopWindowURI(topWindowUri); } - if (aLoadFlags != nsIRequest::LOAD_NORMAL) + if (aLoadFlags != nsIRequest::LOAD_NORMAL) { httpChannel->SetLoadFlags(aLoadFlags); + } if (aForceMainDocumentChannel) { httpChannel->SetIsMainDocumentChannel(true); @@ -512,7 +513,7 @@ bool HttpChannelParent::DoAsyncOpen( do_QueryInterface(static_cast(httpChannel.get())); if (cacheChannel) { cacheChannel->SetCacheKey(aCacheKey); - for (auto& data : aPreferredAlternativeTypes) { + for (const auto& data : aPreferredAlternativeTypes) { cacheChannel->PreferAlternativeDataType(data.type(), data.contentType(), data.deliverAltData()); } @@ -649,7 +650,7 @@ bool HttpChannelParent::ConnectChannel(const uint32_t& registrarId) { // redirected-to channel may not support PB nsCOMPtr pbChannel = do_QueryObject(mChannel); if (pbChannel) { - pbChannel->SetPrivate(mPBOverride == kPBOverride_Private ? true : false); + pbChannel->SetPrivate(mPBOverride == kPBOverride_Private); } } @@ -1128,7 +1129,7 @@ HttpChannelParent::OnStartRequest(nsIRequest* aRequest) { if (httpChannelImpl) { httpChannelImpl->GetCacheToken(getter_AddRefs(cacheEntry)); mCacheEntry = do_QueryInterface(cacheEntry); - args.cacheEntryAvailable() = mCacheEntry ? true : false; + args.cacheEntryAvailable() = static_cast(mCacheEntry); httpChannelImpl->GetCacheKey(&args.cacheKey()); httpChannelImpl->GetAlternativeDataType(args.altDataType()); diff --git a/netwerk/protocol/http/HttpChannelParent.h b/netwerk/protocol/http/HttpChannelParent.h index 0a37bbdc66de..0436a0d224fa 100644 --- a/netwerk/protocol/http/HttpChannelParent.h +++ b/netwerk/protocol/http/HttpChannelParent.h @@ -76,9 +76,10 @@ class HttpChannelParent final : public nsIInterfaceRequestor, NS_DECLARE_STATIC_IID_ACCESSOR(HTTP_CHANNEL_PARENT_IID) HttpChannelParent(dom::BrowserParent* iframeEmbedding, - nsILoadContext* aLoadContext, PBOverrideStatus aStatus); + nsILoadContext* aLoadContext, + PBOverrideStatus aOverrideStatus); - [[nodiscard]] bool Init(const HttpChannelCreationArgs& aOpenArgs); + [[nodiscard]] bool Init(const HttpChannelCreationArgs& aArgs); // Forwarded to nsHttpChannel::SetApplyConversion. void SetApplyConversion(bool aApplyConversion) { @@ -131,12 +132,12 @@ class HttpChannelParent final : public nsIInterfaceRequestor, protected: // used to connect redirected-to channel in parent with just created // ChildChannel. Used during redirects. - [[nodiscard]] bool ConnectChannel(const uint32_t& channelId); + [[nodiscard]] bool ConnectChannel(const uint32_t& registrarId); [[nodiscard]] bool DoAsyncOpen( const URIParams& uri, const Maybe& originalUri, const Maybe& docUri, nsIReferrerInfo* aReferrerInfo, - const Maybe& internalRedirectUri, + const Maybe& aAPIRedirectToURI, const Maybe& topWindowUri, const uint32_t& loadFlags, const RequestHeaderTuples& requestHeaders, const nsCString& requestMethod, const Maybe& uploadStream, const bool& uploadStreamHasHeaders, @@ -157,7 +158,7 @@ class HttpChannelParent final : public nsIInterfaceRequestor, const uint64_t& aContentWindowId, const nsTArray& aPreferredAlternativeTypes, - const uint64_t& aTopLevelOuterContentWindowId, + const uint64_t& aTopBrowsingContextId, const TimeStamp& aLaunchServiceWorkerStart, const TimeStamp& aLaunchServiceWorkerEnd, const TimeStamp& aDispatchFetchEventStart, diff --git a/netwerk/protocol/http/HttpConnectionMgrChild.cpp b/netwerk/protocol/http/HttpConnectionMgrChild.cpp index 41601d7fc14a..de059495d5bd 100644 --- a/netwerk/protocol/http/HttpConnectionMgrChild.cpp +++ b/netwerk/protocol/http/HttpConnectionMgrChild.cpp @@ -159,7 +159,7 @@ SpeculativeConnectionOverrider::GetAllow1918(bool* aAllow) { } // anonymous namespace mozilla::ipc::IPCResult HttpConnectionMgrChild::RecvSpeculativeConnect( - HttpConnectionInfoCloneArgs aConnInfo, + const HttpConnectionInfoCloneArgs& aConnInfo, Maybe aOverriderArgs, uint32_t aCaps, Maybe aTrans, const bool& aFetchHTTPSRR) { RefPtr cinfo = diff --git a/netwerk/protocol/http/HttpConnectionMgrChild.h b/netwerk/protocol/http/HttpConnectionMgrChild.h index c8a628a3b5e0..21b8043cba9d 100644 --- a/netwerk/protocol/http/HttpConnectionMgrChild.h +++ b/netwerk/protocol/http/HttpConnectionMgrChild.h @@ -37,7 +37,7 @@ class HttpConnectionMgrChild final : public PHttpConnectionMgrChild { mozilla::ipc::IPCResult RecvCancelTransaction(PHttpTransactionChild* aTrans, const nsresult& aReason); mozilla::ipc::IPCResult RecvSpeculativeConnect( - HttpConnectionInfoCloneArgs aConnInfo, + const HttpConnectionInfoCloneArgs& aConnInfo, Maybe aOverriderArgs, uint32_t aCaps, Maybe aTrans, const bool& aFetchHTTPSRR); diff --git a/netwerk/protocol/http/HttpConnectionUDP.cpp b/netwerk/protocol/http/HttpConnectionUDP.cpp index a1c3bb9bf53c..37a09d1bfbff 100644 --- a/netwerk/protocol/http/HttpConnectionUDP.cpp +++ b/netwerk/protocol/http/HttpConnectionUDP.cpp @@ -33,14 +33,7 @@ namespace net { // HttpConnectionUDP //----------------------------------------------------------------------------- -HttpConnectionUDP::HttpConnectionUDP() - : mHttpHandler(gHttpHandler), - mDontReuse(false), - mIsReused(false), - mLastTransactionExpectedNoContent(false), - mPriority(nsISupportsPriority::PRIORITY_NORMAL), - mForceSendPending(false), - mLastRequestBytesSentTime(0) { +HttpConnectionUDP::HttpConnectionUDP() : mHttpHandler(gHttpHandler) { LOG(("Creating HttpConnectionUDP @%p\n", this)); } @@ -656,17 +649,15 @@ NS_IMETHODIMP HttpConnectionUDP::OnStopListening(nsIUDPSocket* aSocket, nsresult HttpConnectionUDP::GetSelfAddr(NetAddr* addr) { if (mSelfAddr) { return mSelfAddr->GetNetAddr(addr); - } else { - return NS_ERROR_FAILURE; } + return NS_ERROR_FAILURE; } nsresult HttpConnectionUDP::GetPeerAddr(NetAddr* addr) { if (mPeerAddr) { return mPeerAddr->GetNetAddr(addr); - } else { - return NS_ERROR_FAILURE; } + return NS_ERROR_FAILURE; } bool HttpConnectionUDP::ResolvedByTRR() { return mResolvedByTRR; } diff --git a/netwerk/protocol/http/HttpConnectionUDP.h b/netwerk/protocol/http/HttpConnectionUDP.h index d00a6b9a6954..3b1a41a3f99a 100644 --- a/netwerk/protocol/http/HttpConnectionUDP.h +++ b/netwerk/protocol/http/HttpConnectionUDP.h @@ -96,21 +96,21 @@ class HttpConnectionUDP final : public HttpConnectionBase, RefPtr mInputOverflow; - bool mConnectedTransport; - bool mDontReuse; - bool mIsReused; - bool mLastTransactionExpectedNoContent; + bool mConnectedTransport = false; + bool mDontReuse = false; + bool mIsReused = false; + bool mLastTransactionExpectedNoContent = false; - int32_t mPriority; + int32_t mPriority = nsISupportsPriority::PRIORITY_NORMAL; private: // For ForceSend() static void ForceSendIO(nsITimer* aTimer, void* aClosure); [[nodiscard]] nsresult MaybeForceSendIO(); - bool mForceSendPending; + bool mForceSendPending = false; nsCOMPtr mForceSendTimer; - PRIntervalTime mLastRequestBytesSentTime; + PRIntervalTime mLastRequestBytesSentTime = 0; nsCOMPtr mSocket; nsCOMPtr mSelfAddr; diff --git a/netwerk/protocol/http/HttpLog.h b/netwerk/protocol/http/HttpLog.h index 0cb05e6afd30..5f8a78b939c7 100644 --- a/netwerk/protocol/http/HttpLog.h +++ b/netwerk/protocol/http/HttpLog.h @@ -53,7 +53,7 @@ extern LazyLogModule gHttpLog; MOZ_LOG(mozilla::net::gHttpLog, mozilla::LogLevel::Verbose, args) #define LOG(args) LOG4(args) #define LOGTIME(start, args) \ - MOZ_LOG_TIME(mozilla::net::gHttpLog, mozilla::LogLevel::Debug, &start, args) + MOZ_LOG_TIME(mozilla::net::gHttpLog, mozilla::LogLevel::Debug, &(start), args) #define LOG1_ENABLED() \ MOZ_LOG_TEST(mozilla::net::gHttpLog, mozilla::LogLevel::Error) diff --git a/netwerk/protocol/http/HttpTransactionChild.h b/netwerk/protocol/http/HttpTransactionChild.h index 89129d9db1b2..7d681db5c4b4 100644 --- a/netwerk/protocol/http/HttpTransactionChild.h +++ b/netwerk/protocol/http/HttpTransactionChild.h @@ -80,10 +80,10 @@ class HttpTransactionChild final : public PHttpTransactionChild, // Initialize the *real* nsHttpTransaction. See |nsHttpTransaction::Init| // for the parameters. [[nodiscard]] nsresult InitInternal( - uint32_t caps, const HttpConnectionInfoCloneArgs& aArgs, - nsHttpRequestHead* reqHeaders, - nsIInputStream* reqBody, // use the trick in bug 1277681 - uint64_t reqContentLength, bool reqBodyIncludesHeaders, + uint32_t caps, const HttpConnectionInfoCloneArgs& infoArgs, + nsHttpRequestHead* requestHead, + nsIInputStream* requestBody, // use the trick in bug 1277681 + uint64_t requestContentLength, bool requestBodyHasHeaders, uint64_t topLevelOuterContentWindowId, uint8_t httpTrafficCategory, uint64_t requestContextID, uint32_t classOfService, uint32_t initialRwin, bool responseTimeoutEnabled, uint64_t channelId, diff --git a/netwerk/protocol/http/HttpTransactionParent.cpp b/netwerk/protocol/http/HttpTransactionParent.cpp index b0052f5ad5d0..3ad267352d7e 100644 --- a/netwerk/protocol/http/HttpTransactionParent.cpp +++ b/netwerk/protocol/http/HttpTransactionParent.cpp @@ -33,7 +33,7 @@ NS_INTERFACE_MAP_END NS_IMETHODIMP_(MozExternalRefCountType) HttpTransactionParent::Release(void) { MOZ_ASSERT(int32_t(mRefCnt) > 0, "dup release"); - if (!mRefCnt.isThreadSafe) { + if (!::mozilla::ThreadSafeAutoRefCnt::isThreadSafe) { NS_ASSERT_OWNINGTHREAD(HttpTransactionParent); } diff --git a/netwerk/protocol/http/HttpTransactionParent.h b/netwerk/protocol/http/HttpTransactionParent.h index ec7b032c67db..6e29c1e09042 100644 --- a/netwerk/protocol/http/HttpTransactionParent.h +++ b/netwerk/protocol/http/HttpTransactionParent.h @@ -156,7 +156,7 @@ class HttpTransactionParent final : public PHttpTransactionParent, OnPushCallback mOnPushCallback; nsTArray mDataForSniffer; std::function mCallOnResume; - uint32_t mHTTPSSVCReceivedStage; + uint32_t mHTTPSSVCReceivedStage{}; RefPtr mConnInfo; bool mSupportsHTTP3 = false; }; diff --git a/netwerk/protocol/http/SpeculativeTransaction.cpp b/netwerk/protocol/http/SpeculativeTransaction.cpp index e57655f0cb27..ade64968decb 100644 --- a/netwerk/protocol/http/SpeculativeTransaction.cpp +++ b/netwerk/protocol/http/SpeculativeTransaction.cpp @@ -21,8 +21,6 @@ SpeculativeTransaction::SpeculativeTransaction( mTriedToWrite(false), mCloseCallback(std::move(aCallback)) {} -SpeculativeTransaction::~SpeculativeTransaction() {} - already_AddRefed SpeculativeTransaction::CreateWithNewConnInfo(nsHttpConnectionInfo* aConnInfo) { RefPtr trans = diff --git a/netwerk/protocol/http/SpeculativeTransaction.h b/netwerk/protocol/http/SpeculativeTransaction.h index c1fdc891dea0..851fe2b39fc7 100644 --- a/netwerk/protocol/http/SpeculativeTransaction.h +++ b/netwerk/protocol/http/SpeculativeTransaction.h @@ -52,7 +52,7 @@ class SpeculativeTransaction : public NullHttpTransaction { void InvokeCallback(); protected: - virtual ~SpeculativeTransaction(); + virtual ~SpeculativeTransaction() = default; private: Maybe mParallelSpeculativeConnectLimit; diff --git a/netwerk/protocol/http/TRRServiceChannel.cpp b/netwerk/protocol/http/TRRServiceChannel.cpp index 030a74d1eed6..6c719815b57d 100644 --- a/netwerk/protocol/http/TRRServiceChannel.cpp +++ b/netwerk/protocol/http/TRRServiceChannel.cpp @@ -445,8 +445,9 @@ nsresult TRRServiceChannel::BeginConnect() { // Adjust mCaps according to our request headers: // - If "Connection: close" is set as a request header, then do not bother // trying to establish a keep-alive connection. - if (mRequestHead.HasHeaderValue(nsHttp::Connection, "close")) + if (mRequestHead.HasHeaderValue(nsHttp::Connection, "close")) { mCaps &= ~(NS_HTTP_ALLOW_KEEPALIVE); + } if (gHttpHandler->CriticalRequestPrioritization()) { if (mClassOfService & nsIClassOfService::Leader) { @@ -496,8 +497,9 @@ nsresult TRRServiceChannel::ContinueOnBeforeConnect() { LOG(("TRRServiceChannel::ContinueOnBeforeConnect [this=%p]\n", this)); // ensure that we are using a valid hostname - if (!net_IsValidHostName(nsDependentCString(mConnectionInfo->Origin()))) + if (!net_IsValidHostName(nsDependentCString(mConnectionInfo->Origin()))) { return NS_ERROR_UNKNOWN_HOST; + } if (LoadIsTRRServiceChannel()) { mCaps |= NS_HTTP_LARGE_KEEPALIVE; @@ -806,8 +808,9 @@ nsresult TRRServiceChannel::CallOnStartRequest() { StoreOnStartRequestCalled(true); }); - if (mResponseHead && !mResponseHead->HasContentCharset()) + if (mResponseHead && !mResponseHead->HasContentCharset()) { mResponseHead->SetContentCharset(mContentCharsetHint); + } LOG((" calling mListener->OnStartRequest [this=%p, listener=%p]\n", this, mListener.get())); @@ -1338,10 +1341,11 @@ void TRRServiceChannel::DoAsyncAbort(nsresult aStatus) { NS_IMETHODIMP TRRServiceChannel::GetProxyInfo(nsIProxyInfo** result) { - if (!mConnectionInfo) + if (!mConnectionInfo) { *result = mProxyInfo; - else + } else { *result = mConnectionInfo->ProxyInfo(); + } NS_IF_ADDREF(*result); return NS_OK; } @@ -1431,82 +1435,91 @@ void TRRServiceChannel::DoNotifyListenerCleanup() {} NS_IMETHODIMP TRRServiceChannel::GetDomainLookupStart(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetDomainLookupStart(); - else + } else { *_retval = mTransactionTimings.domainLookupStart; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetDomainLookupEnd(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetDomainLookupEnd(); - else + } else { *_retval = mTransactionTimings.domainLookupEnd; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetConnectStart(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetConnectStart(); - else + } else { *_retval = mTransactionTimings.connectStart; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetTcpConnectEnd(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetTcpConnectEnd(); - else + } else { *_retval = mTransactionTimings.tcpConnectEnd; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetSecureConnectionStart(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetSecureConnectionStart(); - else + } else { *_retval = mTransactionTimings.secureConnectionStart; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetConnectEnd(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetConnectEnd(); - else + } else { *_retval = mTransactionTimings.connectEnd; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetRequestStart(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetRequestStart(); - else + } else { *_retval = mTransactionTimings.requestStart; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetResponseStart(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetResponseStart(); - else + } else { *_retval = mTransactionTimings.responseStart; + } return NS_OK; } NS_IMETHODIMP TRRServiceChannel::GetResponseEnd(TimeStamp* _retval) { - if (mTransaction) + if (mTransaction) { *_retval = mTransaction->GetResponseEnd(); - else + } else { *_retval = mTransactionTimings.responseEnd; + } return NS_OK; } diff --git a/netwerk/protocol/http/TunnelUtils.cpp b/netwerk/protocol/http/TunnelUtils.cpp index f22e24fbc834..73c0bbb54b38 100644 --- a/netwerk/protocol/http/TunnelUtils.cpp +++ b/netwerk/protocol/http/TunnelUtils.cpp @@ -883,7 +883,7 @@ class SocketOutWrapper : public nsIAsyncOutputStream, NS_IMETHOD Write(const char* aBuf, uint32_t aCount, uint32_t* _retval) override; virtual nsresult OnReadSegment(const char* segment, uint32_t count, - uint32_t* countRead) override; + uint32_t* countWritten) override; private: virtual ~SocketOutWrapper() = default; diff --git a/netwerk/protocol/http/TunnelUtils.h b/netwerk/protocol/http/TunnelUtils.h index 834d0888c336..8aa5898a1be2 100644 --- a/netwerk/protocol/http/TunnelUtils.h +++ b/netwerk/protocol/http/TunnelUtils.h @@ -158,7 +158,7 @@ class TLSFilterTransaction final : public nsAHttpTransaction, int32_t FilterInput(char* aBuf, int32_t aAmount); static PRStatus GetPeerName(PRFileDesc* fd, PRNetAddr* addr); - static PRStatus GetSocketOption(PRFileDesc* fd, PRSocketOptionData* data); + static PRStatus GetSocketOption(PRFileDesc* fd, PRSocketOptionData* aOpt); static PRStatus SetSocketOption(PRFileDesc* fd, const PRSocketOptionData* data); static int32_t FilterWrite(PRFileDesc* fd, const void* buf, int32_t amount); @@ -235,7 +235,7 @@ class SpdyConnectTransaction final : public NullHttpTransaction { uint32_t count, uint32_t* countWritten) final; nsHttpRequestHead* RequestHead() final; - void Close(nsresult reason) final; + void Close(nsresult code) final; // ConnectedReadyForInput() tests whether the spdy connect transaction is // attached to an nsHttpConnection that can properly deal with flow control, diff --git a/netwerk/protocol/http/nsAHttpConnection.h b/netwerk/protocol/http/nsAHttpConnection.h index 416ea18ba7c7..f1e47c8baa64 100644 --- a/netwerk/protocol/http/nsAHttpConnection.h +++ b/netwerk/protocol/http/nsAHttpConnection.h @@ -168,95 +168,95 @@ class nsAHttpConnection : public nsISupports { NS_DEFINE_STATIC_IID_ACCESSOR(nsAHttpConnection, NS_AHTTPCONNECTION_IID) -#define NS_DECL_NSAHTTPCONNECTION(fwdObject) \ - [[nodiscard]] nsresult OnHeadersAvailable( \ - nsAHttpTransaction*, nsHttpRequestHead*, nsHttpResponseHead*, \ - bool* reset) override; \ - void CloseTransaction(nsAHttpTransaction*, nsresult) override; \ - [[nodiscard]] nsresult TakeTransport( \ - nsISocketTransport**, nsIAsyncInputStream**, nsIAsyncOutputStream**) \ - override; \ - bool IsPersistent() override; \ - bool IsReused() override; \ - void DontReuse() override; \ - [[nodiscard]] nsresult PushBack(const char*, uint32_t) override; \ - already_AddRefed TakeHttpConnection() override; \ - already_AddRefed HttpConnection() override; \ - void TopBrowsingContextIdChanged(uint64_t id) override; \ - /* \ - Thes methods below have automatic definitions that just forward the \ - function to a lower level connection object \ - */ \ - void GetConnectionInfo(nsHttpConnectionInfo** result) override { \ - if (!(fwdObject)) { \ - *result = nullptr; \ - return; \ - } \ - return (fwdObject)->GetConnectionInfo(result); \ - } \ - void GetSecurityInfo(nsISupports** result) override { \ - if (!(fwdObject)) { \ - *result = nullptr; \ - return; \ - } \ - return (fwdObject)->GetSecurityInfo(result); \ - } \ - [[nodiscard]] nsresult ResumeSend() override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->ResumeSend(); \ - } \ - [[nodiscard]] nsresult ResumeRecv() override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->ResumeRecv(); \ - } \ - [[nodiscard]] nsresult ForceSend() override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->ForceSend(); \ - } \ - [[nodiscard]] nsresult ForceRecv() override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->ForceRecv(); \ - } \ - nsISocketTransport* Transport() override { \ - if (!(fwdObject)) return nullptr; \ - return (fwdObject)->Transport(); \ - } \ - HttpVersion Version() override { \ - return (fwdObject) ? (fwdObject)->Version() \ - : mozilla::net::HttpVersion::UNKNOWN; \ - } \ - bool IsProxyConnectInProgress() override { \ - return (!fwdObject) ? false : (fwdObject)->IsProxyConnectInProgress(); \ - } \ - bool LastTransactionExpectedNoContent() override { \ - return (!fwdObject) ? false \ - : (fwdObject)->LastTransactionExpectedNoContent(); \ - } \ - void SetLastTransactionExpectedNoContent(bool val) override { \ - if (fwdObject) (fwdObject)->SetLastTransactionExpectedNoContent(val); \ - } \ - int64_t BytesWritten() override { \ - return fwdObject ? (fwdObject)->BytesWritten() : 0; \ - } \ - void SetSecurityCallbacks(nsIInterfaceRequestor* aCallbacks) override { \ - if (fwdObject) (fwdObject)->SetSecurityCallbacks(aCallbacks); \ - } \ - void SetTrafficCategory(HttpTrafficCategory aCategory) override { \ - if (fwdObject) (fwdObject)->SetTrafficCategory(aCategory); \ - } \ - nsresult GetSelfAddr(NetAddr* addr) override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->GetSelfAddr(addr); \ - } \ - nsresult GetPeerAddr(NetAddr* addr) override { \ - if (!(fwdObject)) return NS_ERROR_FAILURE; \ - return (fwdObject)->GetPeerAddr(addr); \ - } \ - bool ResolvedByTRR() override { \ - return (!fwdObject) ? false : (fwdObject)->ResolvedByTRR(); \ - } \ - bool GetEchConfigUsed() override { \ - return (!fwdObject) ? false : (fwdObject)->GetEchConfigUsed(); \ +#define NS_DECL_NSAHTTPCONNECTION(fwdObject) \ + [[nodiscard]] nsresult OnHeadersAvailable( \ + nsAHttpTransaction*, nsHttpRequestHead*, nsHttpResponseHead*, \ + bool* reset) override; \ + void CloseTransaction(nsAHttpTransaction*, nsresult) override; \ + [[nodiscard]] nsresult TakeTransport( \ + nsISocketTransport**, nsIAsyncInputStream**, nsIAsyncOutputStream**) \ + override; \ + bool IsPersistent() override; \ + bool IsReused() override; \ + void DontReuse() override; \ + [[nodiscard]] nsresult PushBack(const char*, uint32_t) override; \ + already_AddRefed TakeHttpConnection() override; \ + already_AddRefed HttpConnection() override; \ + void TopBrowsingContextIdChanged(uint64_t id) override; \ + /* \ + Thes methods below have automatic definitions that just forward the \ + function to a lower level connection object \ + */ \ + void GetConnectionInfo(nsHttpConnectionInfo** result) override { \ + if (!(fwdObject)) { \ + *result = nullptr; \ + return; \ + } \ + return (fwdObject)->GetConnectionInfo(result); \ + } \ + void GetSecurityInfo(nsISupports** result) override { \ + if (!(fwdObject)) { \ + *result = nullptr; \ + return; \ + } \ + return (fwdObject)->GetSecurityInfo(result); \ + } \ + [[nodiscard]] nsresult ResumeSend() override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->ResumeSend(); \ + } \ + [[nodiscard]] nsresult ResumeRecv() override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->ResumeRecv(); \ + } \ + [[nodiscard]] nsresult ForceSend() override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->ForceSend(); \ + } \ + [[nodiscard]] nsresult ForceRecv() override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->ForceRecv(); \ + } \ + nsISocketTransport* Transport() override { \ + if (!(fwdObject)) return nullptr; \ + return (fwdObject)->Transport(); \ + } \ + HttpVersion Version() override { \ + return (fwdObject) ? (fwdObject)->Version() \ + : mozilla::net::HttpVersion::UNKNOWN; \ + } \ + bool IsProxyConnectInProgress() override { \ + return (!(fwdObject)) ? false : (fwdObject)->IsProxyConnectInProgress(); \ + } \ + bool LastTransactionExpectedNoContent() override { \ + return (!(fwdObject)) ? false \ + : (fwdObject)->LastTransactionExpectedNoContent(); \ + } \ + void SetLastTransactionExpectedNoContent(bool val) override { \ + if (fwdObject) (fwdObject)->SetLastTransactionExpectedNoContent(val); \ + } \ + int64_t BytesWritten() override { \ + return (fwdObject) ? (fwdObject)->BytesWritten() : 0; \ + } \ + void SetSecurityCallbacks(nsIInterfaceRequestor* aCallbacks) override { \ + if (fwdObject) (fwdObject)->SetSecurityCallbacks(aCallbacks); \ + } \ + void SetTrafficCategory(HttpTrafficCategory aCategory) override { \ + if (fwdObject) (fwdObject)->SetTrafficCategory(aCategory); \ + } \ + nsresult GetSelfAddr(NetAddr* addr) override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->GetSelfAddr(addr); \ + } \ + nsresult GetPeerAddr(NetAddr* addr) override { \ + if (!(fwdObject)) return NS_ERROR_FAILURE; \ + return (fwdObject)->GetPeerAddr(addr); \ + } \ + bool ResolvedByTRR() override { \ + return (!(fwdObject)) ? false : (fwdObject)->ResolvedByTRR(); \ + } \ + bool GetEchConfigUsed() override { \ + return (!(fwdObject)) ? false : (fwdObject)->GetEchConfigUsed(); \ } // ThrottleResponse deliberately ommited since we want different implementation diff --git a/netwerk/protocol/http/nsCORSListenerProxy.cpp b/netwerk/protocol/http/nsCORSListenerProxy.cpp index 4bfd1385ad16..313bb56ed0a5 100644 --- a/netwerk/protocol/http/nsCORSListenerProxy.cpp +++ b/netwerk/protocol/http/nsCORSListenerProxy.cpp @@ -152,7 +152,7 @@ class nsPreflightCache { void PurgeExpired(TimeStamp now); bool CheckRequest(const nsCString& aMethod, - const nsTArray& aCustomHeaders); + const nsTArray& aHeaders); nsCString mKey; nsTArray mMethods; @@ -282,7 +282,7 @@ nsPreflightCache::CacheEntry* nsPreflightCache::GetEntry( // Try to kick out all the expired entries. TimeStamp now = TimeStamp::NowLoRes(); for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) { - auto entry = iter.UserData(); + auto* entry = iter.UserData(); entry->PurgeExpired(now); if (entry->mHeaders.IsEmpty() && entry->mMethods.IsEmpty()) { diff --git a/netwerk/protocol/http/nsCORSListenerProxy.h b/netwerk/protocol/http/nsCORSListenerProxy.h index ea74f470e5e5..683efa196250 100644 --- a/netwerk/protocol/http/nsCORSListenerProxy.h +++ b/netwerk/protocol/http/nsCORSListenerProxy.h @@ -84,7 +84,7 @@ class nsCORSListenerProxy final : public nsIStreamListener, const mozilla::OriginAttributes& aOriginAttributes); [[nodiscard]] static nsresult StartCORSPreflight( nsIChannel* aRequestChannel, nsICorsPreflightCallback* aCallback, - nsTArray& aACUnsafeHeaders, nsIChannel** aPreflightChannel); + nsTArray& aUnsafeHeaders, nsIChannel** aPreflightChannel); ~nsCORSListenerProxy() = default; diff --git a/netwerk/protocol/http/nsHttp.h b/netwerk/protocol/http/nsHttp.h index 404bc003e616..81631dcc13a9 100644 --- a/netwerk/protocol/http/nsHttp.h +++ b/netwerk/protocol/http/nsHttp.h @@ -313,7 +313,7 @@ static inline uint32_t PRTimeToSeconds(PRTime t_usec) { #define NowInSeconds() PRTimeToSeconds(PR_Now()) // Round q-value to 2 decimal places; return 2 most significant digits as uint. -#define QVAL_TO_UINT(q) ((unsigned int)((q + 0.005) * 100.0)) +#define QVAL_TO_UINT(q) ((unsigned int)(((q) + 0.005) * 100.0)) #define HTTP_LWS " \t" #define HTTP_HEADER_VALUE_SEPS HTTP_LWS "," diff --git a/netwerk/protocol/http/nsHttpActivityDistributor.cpp b/netwerk/protocol/http/nsHttpActivityDistributor.cpp index 702ecfa71369..1117296e6ca8 100644 --- a/netwerk/protocol/http/nsHttpActivityDistributor.cpp +++ b/netwerk/protocol/http/nsHttpActivityDistributor.cpp @@ -19,8 +19,8 @@ namespace mozilla { namespace net { -typedef nsMainThreadPtrHolder ObserverHolder; -typedef nsMainThreadPtrHandle ObserverHandle; +using ObserverHolder = nsMainThreadPtrHolder; +using ObserverHandle = nsMainThreadPtrHandle; NS_IMPL_ISUPPORTS(nsHttpActivityDistributor, nsIHttpActivityDistributor, nsIHttpActivityObserver) diff --git a/netwerk/protocol/http/nsHttpActivityDistributor.h b/netwerk/protocol/http/nsHttpActivityDistributor.h index 81ff3bf251b5..8ad09f490240 100644 --- a/netwerk/protocol/http/nsHttpActivityDistributor.h +++ b/netwerk/protocol/http/nsHttpActivityDistributor.h @@ -15,8 +15,8 @@ namespace net { class nsHttpActivityDistributor : public nsIHttpActivityDistributor { public: - typedef nsTArray > - ObserverArray; + using ObserverArray = + nsTArray>; NS_DECL_THREADSAFE_ISUPPORTS NS_DECL_NSIHTTPACTIVITYOBSERVER NS_DECL_NSIHTTPACTIVITYDISTRIBUTOR diff --git a/netwerk/protocol/http/nsHttpChannel.h b/netwerk/protocol/http/nsHttpChannel.h index d3f77a9424e1..143a0afd625f 100644 --- a/netwerk/protocol/http/nsHttpChannel.h +++ b/netwerk/protocol/http/nsHttpChannel.h @@ -269,7 +269,7 @@ class nsHttpChannel final : public HttpBaseChannel, virtual ~nsHttpChannel(); private: - typedef nsresult (nsHttpChannel::*nsContinueRedirectionFunc)(nsresult result); + using nsContinueRedirectionFunc = nsresult (nsHttpChannel::*)(nsresult); // Directly call |aFunc| if the channel is not canceled and not suspended. // Otherwise, set |aFunc| to |mCallOnResume| and wait until the channel diff --git a/netwerk/protocol/http/nsHttpChunkedDecoder.cpp b/netwerk/protocol/http/nsHttpChunkedDecoder.cpp index 76bbd8280580..61e111703779 100644 --- a/netwerk/protocol/http/nsHttpChunkedDecoder.cpp +++ b/netwerk/protocol/http/nsHttpChunkedDecoder.cpp @@ -57,9 +57,9 @@ nsresult nsHttpChunkedDecoder::HandleChunkedContent( *contentRead += amt; buf += amt; - } else if (mReachedEOF) + } else if (mReachedEOF) { break; // done - else { + } else { uint32_t bytesConsumed = 0; nsresult rv = ParseChunkRemaining(buf, count, &bytesConsumed); diff --git a/netwerk/protocol/http/nsHttpChunkedDecoder.h b/netwerk/protocol/http/nsHttpChunkedDecoder.h index a1fb291df252..eed7e162719e 100644 --- a/netwerk/protocol/http/nsHttpChunkedDecoder.h +++ b/netwerk/protocol/http/nsHttpChunkedDecoder.h @@ -38,7 +38,7 @@ class nsHttpChunkedDecoder { private: [[nodiscard]] nsresult ParseChunkRemaining(char* buf, uint32_t count, - uint32_t* countRead); + uint32_t* bytesConsumed); private: UniquePtr mTrailers; diff --git a/netwerk/protocol/http/nsHttpConnection.cpp b/netwerk/protocol/http/nsHttpConnection.cpp index 1adee6aad34e..4cbec8fab681 100644 --- a/netwerk/protocol/http/nsHttpConnection.cpp +++ b/netwerk/protocol/http/nsHttpConnection.cpp @@ -851,8 +851,9 @@ void nsHttpConnection::SetupSSL() { LOG1(("nsHttpConnection::SetupSSL %p caps=0x%X %s\n", this, mTransactionCaps, mConnInfo->HashKey().get())); - if (mSetupSSLCalled) // do only once + if (mSetupSSLCalled) { // do only once return; + } mSetupSSLCalled = true; if (mNPNComplete) return; @@ -867,7 +868,7 @@ void nsHttpConnection::SetupSSL() { // if we are connected to the proxy with TLS, start the TLS // flow immediately without waiting for a CONNECT sequence. - DebugOnly rv; + DebugOnly rv{}; if (mInSpdyTunnel) { rv = InitSSLParams(false, true); } else { @@ -1231,10 +1232,11 @@ nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction* trans, bool explicitClose = responseHead->HasHeaderValue(nsHttp::Connection, "close") || responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "close"); - if (!explicitClose) + if (!explicitClose) { explicitKeepAlive = responseHead->HasHeaderValue(nsHttp::Connection, "keep-alive") || responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "keep-alive"); + } // deal with 408 Server Timeouts uint16_t responseStatus = responseHead->Status(); @@ -1260,10 +1262,7 @@ nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction* trans, if ((responseHead->Version() < HttpVersion::v1_1) || (requestHead->Version() < HttpVersion::v1_1)) { // HTTP/1.0 connections are by default NOT persistent - if (explicitKeepAlive) - mKeepAlive = true; - else - mKeepAlive = false; + mKeepAlive = explicitKeepAlive; } else { // HTTP/1.1 connections are by default persistent mKeepAlive = !explicitClose; @@ -1284,10 +1283,11 @@ nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction* trans, if (mUsingSpdyVersion == SpdyVersion::NONE) { const char* cp = nsCRT::strcasestr(keepAlive.get(), "timeout="); - if (cp) + if (cp) { mIdleTimeout = PR_SecondsToInterval((uint32_t)atoi(cp + 8)); - else + } else { mIdleTimeout = gHttpHandler->IdleTimeout() * mDefaultTimeoutFactor; + } cp = nsCRT::strcasestr(keepAlive.get(), "max="); if (cp) { @@ -1420,8 +1420,9 @@ nsresult nsHttpConnection::TakeTransport(nsISocketTransport** aTransport, nsIAsyncOutputStream** aOutputStream) { if (mUsingSpdyVersion != SpdyVersion::NONE) return NS_ERROR_FAILURE; if (mTransaction && !mTransaction->IsDone()) return NS_ERROR_IN_PROGRESS; - if (!(mSocketTransport && mSocketIn && mSocketOut)) + if (!(mSocketTransport && mSocketIn && mSocketOut)) { return NS_ERROR_NOT_INITIALIZED; + } if (mInputOverflow) mSocketIn = mInputOverflow.forget(); @@ -1863,11 +1864,11 @@ nsresult nsHttpConnection::OnReadSegment(const char* buf, uint32_t count, } nsresult rv = mSocketOut->Write(buf, count, countRead); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { mSocketOutCondition = rv; - else if (*countRead == 0) + } else if (*countRead == 0) { mSocketOutCondition = NS_BASE_STREAM_CLOSED; - else { + } else { mLastWriteTime = PR_IntervalNow(); mSocketOutCondition = NS_OK; // reset condition if (!mProxyConnectInProgress) mTotalBytesWritten += *countRead; @@ -2041,12 +2042,13 @@ nsresult nsHttpConnection::OnWriteSegment(char* buf, uint32_t count, } nsresult rv = mSocketIn->Read(buf, count, countWritten); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { mSocketInCondition = rv; - else if (*countWritten == 0) + } else if (*countWritten == 0) { mSocketInCondition = NS_BASE_STREAM_CLOSED; - else + } else { mSocketInCondition = NS_OK; // reset condition + } return mSocketInCondition; } @@ -2182,7 +2184,7 @@ nsresult nsHttpConnection::MakeConnectString(nsAHttpTransaction* trans, return NS_ERROR_NOT_INITIALIZED; } - DebugOnly rv; + DebugOnly rv{}; rv = nsHttpHandler::GenerateHostPort( nsDependentCString(trans->ConnectionInfo()->Origin()), diff --git a/netwerk/protocol/http/nsHttpConnection.h b/netwerk/protocol/http/nsHttpConnection.h index 5fc5ae6ef6e4..9c493ace39e6 100644 --- a/netwerk/protocol/http/nsHttpConnection.h +++ b/netwerk/protocol/http/nsHttpConnection.h @@ -219,10 +219,10 @@ class nsHttpConnection final : public HttpConnectionBase, void SetupSSL(); // Start the Spdy transaction handler when NPN indicates spdy/* - void StartSpdy(nsISSLSocketControl* ssl, SpdyVersion versionLevel); + void StartSpdy(nsISSLSocketControl* ssl, SpdyVersion spdyVersion); // Like the above, but do the bare minimum to do 0RTT data, so we can back // it out, if necessary - void Start0RTTSpdy(SpdyVersion versionLevel); + void Start0RTTSpdy(SpdyVersion spdyVersion); // Helpers for Start*Spdy nsresult TryTakeSubTransactions(nsTArray >& list); diff --git a/netwerk/protocol/http/nsHttpConnectionInfo.h b/netwerk/protocol/http/nsHttpConnectionInfo.h index e448081665f5..48a44faaa7ee 100644 --- a/netwerk/protocol/http/nsHttpConnectionInfo.h +++ b/netwerk/protocol/http/nsHttpConnectionInfo.h @@ -90,7 +90,7 @@ class nsHttpConnectionInfo final : public ARefBase { // mRoutedPort and mNPNToken will be replaced as well. already_AddRefed CloneAndAdoptHTTPSSVCRecord( nsISVCBRecord* aRecord) const; - void CloneAsDirectRoute(nsHttpConnectionInfo** outParam); + void CloneAsDirectRoute(nsHttpConnectionInfo** outCI); [[nodiscard]] nsresult CreateWildCard(nsHttpConnectionInfo** outParam); const char* ProxyHost() const { @@ -226,27 +226,28 @@ class nsHttpConnectionInfo final : public ARefBase { private: void Init(const nsACString& host, int32_t port, const nsACString& npnToken, const nsACString& username, nsProxyInfo* proxyInfo, - const OriginAttributes& originAttributes, bool EndToEndSSL, + const OriginAttributes& originAttributes, bool e2eSSL, bool aIsHttp3); void SetOriginServer(const nsACString& host, int32_t port); nsCString mOrigin; - int32_t mOriginPort; + int32_t mOriginPort = 0; nsCString mRoutedHost; int32_t mRoutedPort; nsCString mHashKey; nsCString mUsername; nsCOMPtr mProxyInfo; - bool mUsingHttpProxy; - bool mUsingHttpsProxy; - bool mEndToEndSSL; - bool mUsingConnect; // if will use CONNECT with http proxy + bool mUsingHttpProxy = false; + bool mUsingHttpsProxy = false; + bool mEndToEndSSL = false; + // if will use CONNECT with http proxy + bool mUsingConnect = false; nsCString mNPNToken; OriginAttributes mOriginAttributes; nsIRequest::TRRMode mTRRMode; - uint32_t mTlsFlags; + uint32_t mTlsFlags = 0; uint16_t mIsTrrServiceChannel : 1; uint16_t mIPv4Disabled : 1; uint16_t mIPv6Disabled : 1; @@ -254,7 +255,7 @@ class nsHttpConnectionInfo final : public ARefBase { bool mLessThanTls13; // This will be set to true if we negotiate less than // tls1.3. If the tls version is till not know or it // is 1.3 or greater the value will be false. - bool mIsHttp3; + bool mIsHttp3 = false; bool mHasIPHintAddress = false; nsCString mEchConfig; diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.cpp b/netwerk/protocol/http/nsHttpConnectionMgr.cpp index 76942658920c..f83124b51428 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp +++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp @@ -67,7 +67,7 @@ nsHttpConnectionMgr::nsHttpConnectionMgr() mThrottleReadLimit(0), mThrottleReadInterval(0), mThrottleHoldTime(0), - mThrottleMaxTime(0), + mThrottleMaxTime(nullptr), mBeConservativeForProxy(true), mIsShuttingDown(false), mNumActiveConns(0), @@ -248,8 +248,9 @@ void nsHttpConnectionMgr::PruneDeadConnectionsAfter(uint32_t timeInSeconds) { void nsHttpConnectionMgr::ConditionallyStopPruneDeadConnectionsTimer() { // Leave the timer in place if there are connections that potentially // need management - if (mNumIdleConns || (mNumActiveConns && gHttpHandler->IsSpdyEnabled())) + if (mNumIdleConns || (mNumActiveConns && gHttpHandler->IsSpdyEnabled())) { return; + } LOG(("nsHttpConnectionMgr::StopPruneDeadConnectionsTimer\n")); @@ -1234,8 +1235,9 @@ nsresult nsHttpConnectionMgr::MakeNewConnection( outerLoopEnd:; } - if (AtActiveConnectionLimit(ent, trans->Caps())) + if (AtActiveConnectionLimit(ent, trans->Caps())) { return NS_ERROR_NOT_AVAILABLE; + } nsresult rv = CreateTransport(ent, trans, trans->Caps(), false, false, @@ -1599,14 +1601,15 @@ nsresult nsHttpConnectionMgr::DispatchAbstractTransaction( void nsHttpConnectionMgr::ReportProxyTelemetry(ConnectionEntry* ent) { enum { PROXY_NONE = 1, PROXY_HTTP = 2, PROXY_SOCKS = 3, PROXY_HTTPS = 4 }; - if (!ent->mConnInfo->UsingProxy()) + if (!ent->mConnInfo->UsingProxy()) { Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_NONE); - else if (ent->mConnInfo->UsingHttpsProxy()) + } else if (ent->mConnInfo->UsingHttpsProxy()) { Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_HTTPS); - else if (ent->mConnInfo->UsingHttpProxy()) + } else if (ent->mConnInfo->UsingHttpProxy()) { Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_HTTP); - else + } else { Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_SOCKS); + } } nsresult nsHttpConnectionMgr::ProcessNewTransaction(nsHttpTransaction* trans) { @@ -3564,8 +3567,9 @@ void nsHttpConnectionMgr::NewIdleConnectionAdded(uint32_t timeToLive) { // If the added connection was first idle connection or has shortest // time to live among the watched connections, pruning dead // connections needs to be done when it can't be reused anymore. - if (!mTimer || NowInSeconds() + timeToLive < mTimeOfNextWakeUp) + if (!mTimer || NowInSeconds() + timeToLive < mTimeOfNextWakeUp) { PruneDeadConnectionsAfter(timeToLive); + } } void nsHttpConnectionMgr::DecrementNumIdleConns() { diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.h b/netwerk/protocol/http/nsHttpConnectionMgr.h index 3800c48ed00f..86ebb113fcd7 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.h +++ b/netwerk/protocol/http/nsHttpConnectionMgr.h @@ -37,7 +37,7 @@ struct HttpRetParams; // message handlers have this signature class nsHttpConnectionMgr; -typedef void (nsHttpConnectionMgr::*nsConnEventHandler)(int32_t, ARefBase*); +using nsConnEventHandler = void (nsHttpConnectionMgr::*)(int32_t, ARefBase*); class nsHttpConnectionMgr final : public HttpConnectionMgrShell, public nsIObserver { @@ -57,7 +57,7 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, //------------------------------------------------------------------------- [[nodiscard]] nsresult CancelTransactions(nsHttpConnectionInfo*, - nsresult reason); + nsresult code); //------------------------------------------------------------------------- // NOTE: functions below may be called only on the socket thread. @@ -267,8 +267,8 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, void RecvdConnect(); ConnectionEntry* GetOrCreateConnectionEntry( - nsHttpConnectionInfo*, bool allowWildCard, bool aNoHttp2, bool aNoHttp3, - bool* aAvailableForDispatchNow = nullptr); + nsHttpConnectionInfo*, bool prohibitWildCard, bool aNoHttp2, + bool aNoHttp3, bool* aAvailableForDispatchNow = nullptr); [[nodiscard]] nsresult MakeNewConnection( ConnectionEntry* ent, PendingTransactionInfo* pendingTransInfo); @@ -431,7 +431,7 @@ class nsHttpConnectionMgr final : public HttpConnectionMgrShell, // @param excludeActive: skip active tabid transactions. void ResumeReadOf( nsClassHashtable>>&, - bool excludeActive = false); + bool excludeForActiveTab = false); void ResumeReadOf(nsTArray>*); // Cached status of the active tab active transactions existence, diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp index 81373fbd5e8d..2ff4a656e0af 100644 --- a/netwerk/protocol/http/nsHttpHandler.cpp +++ b/netwerk/protocol/http/nsHttpHandler.cpp @@ -983,7 +983,7 @@ void nsHttpHandler::InitUserAgentComponents() { // Always return an "Intel" UA string, even on ARM64 macOS like Safari does. mOscpu = nsPrintfCString("Intel Mac OS X 10.%d", uaVersion); #elif defined(XP_UNIX) - struct utsname name; + struct utsname name {}; int ret = uname(&name); if (ret >= 0) { nsAutoCString buf; @@ -1016,10 +1016,11 @@ uint32_t nsHttpHandler::MaxSocketCount() { // starve other users. uint32_t maxCount = nsSocketTransportService::gMaxCount; - if (maxCount <= 8) + if (maxCount <= 8) { maxCount = 1; - else + } else { maxCount -= 8; + } return maxCount; } @@ -1106,14 +1107,16 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("keep-alive.timeout"))) { rv = Preferences::GetInt(HTTP_PREF("keep-alive.timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mIdleTimeout = PR_SecondsToInterval(clamped(val, 1, 0xffff)); + } } if (PREF_CHANGED(HTTP_PREF("request.max-attempts"))) { rv = Preferences::GetInt(HTTP_PREF("request.max-attempts"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mMaxRequestAttempts = (uint16_t)clamped(val, 1, 0xffff); + } } if (PREF_CHANGED(HTTP_PREF("request.max-start-delay"))) { @@ -1135,8 +1138,9 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("response.timeout"))) { rv = Preferences::GetInt(HTTP_PREF("response.timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mResponseTimeout = PR_SecondsToInterval(clamped(val, 0, 0xffff)); + } } if (PREF_CHANGED(HTTP_PREF("network-changed.timeout"))) { @@ -1240,20 +1244,22 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("fallback-connection-timeout"))) { rv = Preferences::GetInt(HTTP_PREF("fallback-connection-timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mFallbackSynTimeout = (uint16_t)clamped(val, 0, 10 * 60); + } } if (PREF_CHANGED(HTTP_PREF("version"))) { nsAutoCString httpVersion; Preferences::GetCString(HTTP_PREF("version"), httpVersion); if (!httpVersion.IsVoid()) { - if (httpVersion.EqualsLiteral("1.1")) + if (httpVersion.EqualsLiteral("1.1")) { mHttpVersion = HttpVersion::v1_1; - else if (httpVersion.EqualsLiteral("0.9")) + } else if (httpVersion.EqualsLiteral("0.9")) { mHttpVersion = HttpVersion::v0_9; - else + } else { mHttpVersion = HttpVersion::v1_0; + } } } @@ -1261,10 +1267,11 @@ void nsHttpHandler::PrefsChanged(const char* pref) { nsAutoCString httpVersion; Preferences::GetCString(HTTP_PREF("proxy.version"), httpVersion); if (!httpVersion.IsVoid()) { - if (httpVersion.EqualsLiteral("1.1")) + if (httpVersion.EqualsLiteral("1.1")) { mProxyHttpVersion = HttpVersion::v1_1; - else + } else { mProxyHttpVersion = HttpVersion::v1_0; + } // it does not make sense to issue a HTTP/0.9 request to a proxy server } } @@ -1310,9 +1317,9 @@ void nsHttpHandler::PrefsChanged(const char* pref) { nsAutoCString sval; rv = Preferences::GetCString(HTTP_PREF("default-socket-type"), sval); if (NS_SUCCEEDED(rv)) { - if (sval.IsEmpty()) + if (sval.IsEmpty()) { mDefaultSocketType.SetIsVoid(true); - else { + } else { // verify that this socket type is actually valid nsCOMPtr sps = nsSocketProviderService::GetOrCreate(); @@ -1350,8 +1357,9 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("phishy-userpass-length"))) { rv = Preferences::GetInt(HTTP_PREF("phishy-userpass-length"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mPhishyUserPassLength = (uint8_t)clamped(val, 0, 0xff); + } } if (PREF_CHANGED(HTTP_PREF("spdy.enabled"))) { @@ -1386,33 +1394,37 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("spdy.timeout"))) { rv = Preferences::GetInt(HTTP_PREF("spdy.timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mSpdyTimeout = PR_SecondsToInterval(clamped(val, 1, 0xffff)); + } } if (PREF_CHANGED(HTTP_PREF("spdy.chunk-size"))) { // keep this within http/2 ranges of 1 to 2^14-1 rv = Preferences::GetInt(HTTP_PREF("spdy.chunk-size"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mSpdySendingChunkSize = (uint32_t)clamped(val, 1, 0x3fff); + } } // The amount of idle seconds on a spdy connection before initiating a // server ping. 0 will disable. if (PREF_CHANGED(HTTP_PREF("spdy.ping-threshold"))) { rv = Preferences::GetInt(HTTP_PREF("spdy.ping-threshold"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mSpdyPingThreshold = PR_SecondsToInterval((uint16_t)clamped(val, 0, 0x7fffffff)); + } } // The amount of seconds to wait for a spdy ping response before // closing the session. if (PREF_CHANGED(HTTP_PREF("spdy.ping-timeout"))) { rv = Preferences::GetInt(HTTP_PREF("spdy.ping-timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mSpdyPingTimeout = PR_SecondsToInterval((uint16_t)clamped(val, 0, 0x7fffffff)); + } } if (PREF_CHANGED(HTTP_PREF("spdy.allow-push"))) { @@ -1470,8 +1482,9 @@ void nsHttpHandler::PrefsChanged(const char* pref) { // closing the session. if (PREF_CHANGED(HTTP_PREF("spdy.send-buffer-size"))) { rv = Preferences::GetInt(HTTP_PREF("spdy.send-buffer-size"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mSpdySendBufferSize = (uint32_t)clamped(val, 1500, 0x7fffffff); + } } if (PREF_CHANGED(HTTP_PREF("spdy.enable-hpack-dump"))) { @@ -1485,25 +1498,28 @@ void nsHttpHandler::PrefsChanged(const char* pref) { // established if (PREF_CHANGED(HTTP_PREF("connection-timeout"))) { rv = Preferences::GetInt(HTTP_PREF("connection-timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { // the pref is in seconds, but the variable is in milliseconds mConnectTimeout = clamped(val, 1, 0xffff) * PR_MSEC_PER_SEC; + } } // The maximum amount of time to wait for a tls handshake to finish. if (PREF_CHANGED(HTTP_PREF("tls-handshake-timeout"))) { rv = Preferences::GetInt(HTTP_PREF("tls-handshake-timeout"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { // the pref is in seconds, but the variable is in milliseconds mTLSHandshakeTimeout = clamped(val, 1, 0xffff) * PR_MSEC_PER_SEC; + } } // The maximum number of current global half open sockets allowable // for starting a new speculative connection. if (PREF_CHANGED(HTTP_PREF("speculative-parallel-limit"))) { rv = Preferences::GetInt(HTTP_PREF("speculative-parallel-limit"), &val); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { mParallelSpeculativeConnectLimit = (uint32_t)clamped(val, 0, 1024); + } } // Whether or not to block requests for non head js/css items (e.g. media) @@ -1735,15 +1751,17 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.short_lived_time"))) { rv = Preferences::GetInt(HTTP_PREF("tcp_keepalive.short_lived_time"), &val); - if (NS_SUCCEEDED(rv) && val > 0) + if (NS_SUCCEEDED(rv) && val > 0) { mTCPKeepaliveShortLivedTimeS = clamped(val, 1, 300); // Max 5 mins. + } } if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.short_lived_idle_time"))) { rv = Preferences::GetInt(HTTP_PREF("tcp_keepalive.short_lived_idle_time"), &val); - if (NS_SUCCEEDED(rv) && val > 0) + if (NS_SUCCEEDED(rv) && val > 0) { mTCPKeepaliveShortLivedIdleTimeS = clamped(val, 1, kMaxTCPKeepIdle); + } } // Keepalive values for Long-lived Connections. @@ -1758,8 +1776,9 @@ void nsHttpHandler::PrefsChanged(const char* pref) { if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.long_lived_idle_time"))) { rv = Preferences::GetInt(HTTP_PREF("tcp_keepalive.long_lived_idle_time"), &val); - if (NS_SUCCEEDED(rv) && val > 0) + if (NS_SUCCEEDED(rv) && val > 0) { mTCPKeepaliveLongLivedIdleTimeS = clamped(val, 1, kMaxTCPKeepIdle); + } } if (PREF_CHANGED(HTTP_PREF("enforce-framing.http1")) || @@ -2400,8 +2419,9 @@ nsresult nsHttpHandler::SpeculativeConnectInternal( nsCOMPtr loadContext = do_GetInterface(aCallbacks); uint32_t flags = 0; - if (loadContext && loadContext->UsePrivateBrowsing()) + if (loadContext && loadContext->UsePrivateBrowsing()) { flags |= nsISocketProvider::NO_PERMANENT_STORAGE; + } OriginAttributes originAttributes; // If the principal is given, we use the originAttributes from this @@ -2440,8 +2460,9 @@ nsresult nsHttpHandler::SpeculativeConnectInternal( } } // Ensure that this is HTTP or HTTPS, otherwise we don't do preconnect here - else if (!scheme.EqualsLiteral("http")) + else if (!scheme.EqualsLiteral("http")) { return NS_ERROR_UNEXPECTED; + } // Construct connection info object if (aURI->SchemeIs("https") && !mSpeculativeConnectEnabled) { @@ -2648,7 +2669,7 @@ void nsHttpHandler::NotifyActiveTabLoadOptimization() { SetLastActiveTabLoadOptimizationHit(TimeStamp::Now()); } -TimeStamp const nsHttpHandler::GetLastActiveTabLoadOptimizationHit() { +TimeStamp nsHttpHandler::GetLastActiveTabLoadOptimizationHit() { MutexAutoLock lock(mLastActiveTabLoadOptimizationLock); return mLastActiveTabLoadOptimizationHit; diff --git a/netwerk/protocol/http/nsHttpHandler.h b/netwerk/protocol/http/nsHttpHandler.h index 8e9ae4476ecb..40ec13ba5840 100644 --- a/netwerk/protocol/http/nsHttpHandler.h +++ b/netwerk/protocol/http/nsHttpHandler.h @@ -119,8 +119,7 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, [[nodiscard]] nsresult AddStandardRequestHeaders( nsHttpRequestHead*, bool isSecure, ExtContentPolicyType aContentPolicyType); - [[nodiscard]] nsresult AddConnectionHeader(nsHttpRequestHead*, - uint32_t capabilities); + [[nodiscard]] nsresult AddConnectionHeader(nsHttpRequestHead*, uint32_t caps); bool IsAcceptableEncoding(const char* encoding, bool isSecure); const nsCString& UserAgent(); @@ -353,7 +352,7 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, // provides the following helper routines for accessing those services: // [[nodiscard]] nsresult GetStreamConverterService(nsIStreamConverterService**); - [[nodiscard]] nsresult GetIOService(nsIIOService** service); + [[nodiscard]] nsresult GetIOService(nsIIOService** result); nsICookieService* GetCookieService(); // not addrefed nsISiteSecurityService* GetSSService(); @@ -470,7 +469,7 @@ class nsHttpHandler final : public nsIHttpProtocolHandler, // took place. Called only on the parent process and only updates // mLastActiveTabLoadOptimizationHit timestamp to now. void NotifyActiveTabLoadOptimization(); - TimeStamp const GetLastActiveTabLoadOptimizationHit(); + TimeStamp GetLastActiveTabLoadOptimizationHit(); void SetLastActiveTabLoadOptimizationHit(TimeStamp const& when); bool IsBeforeLastActiveTabLoadOptimization(TimeStamp const& when); diff --git a/netwerk/protocol/http/nsHttpTransaction.h b/netwerk/protocol/http/nsHttpTransaction.h index e1a05d713752..47b6ba44c87a 100644 --- a/netwerk/protocol/http/nsHttpTransaction.h +++ b/netwerk/protocol/http/nsHttpTransaction.h @@ -107,7 +107,7 @@ class nsHttpTransaction final : public nsAHttpTransaction, mPendingTime = now ? TimeStamp::Now() : TimeStamp(); } } - const TimeStamp GetPendingTime() { return mPendingTime; } + TimeStamp GetPendingTime() { return mPendingTime; } // overload of nsAHttpTransaction::RequestContext() nsIRequestContext* RequestContext() override { return mRequestContext.get(); } @@ -283,8 +283,9 @@ class nsHttpTransaction final : public nsAHttpTransaction, mCallbacks(aCallbacks) {} NS_IMETHOD Run() override { - if (mTrans->mConnection) + if (mTrans->mConnection) { mTrans->mConnection->SetSecurityCallbacks(mCallbacks); + } return NS_OK; } diff --git a/netwerk/protocol/http/nsServerTiming.h b/netwerk/protocol/http/nsServerTiming.h index ef6b9319a664..2db1887b806e 100644 --- a/netwerk/protocol/http/nsServerTiming.h +++ b/netwerk/protocol/http/nsServerTiming.h @@ -30,7 +30,7 @@ class nsServerTiming final : public nsIServerTiming { virtual ~nsServerTiming() = default; nsCString mName; - double mDuration; + double mDuration = 0; nsCString mDescription; }; diff --git a/netwerk/protocol/res/SubstitutingProtocolHandler.h b/netwerk/protocol/res/SubstitutingProtocolHandler.h index 28d0eae0a7f0..3dab910de598 100644 --- a/netwerk/protocol/res/SubstitutingProtocolHandler.h +++ b/netwerk/protocol/res/SubstitutingProtocolHandler.h @@ -45,7 +45,7 @@ class SubstitutingProtocolHandler { nsIURI* aBaseURI, nsIURI** aResult); [[nodiscard]] nsresult CollectSubstitutions( - nsTArray& aResources); + nsTArray& aMappings); protected: virtual ~SubstitutingProtocolHandler() = default; diff --git a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp index 1d44f3878914..605bcd100a74 100644 --- a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp +++ b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp @@ -316,15 +316,17 @@ nsViewSourceChannel::AsyncOpen(nsIStreamListener* aListener) { nsCOMPtr loadGroup; mChannel->GetLoadGroup(getter_AddRefs(loadGroup)); - if (loadGroup) + if (loadGroup) { loadGroup->AddRequest(static_cast(this), nullptr); + } nsresult rv = NS_OK; rv = mChannel->AsyncOpen(this); - if (NS_FAILED(rv) && loadGroup) + if (NS_FAILED(rv) && loadGroup) { loadGroup->RemoveRequest(static_cast(this), nullptr, rv); + } if (NS_SUCCEEDED(rv)) { // We do this here to make sure all notification callbacks changes have been @@ -384,7 +386,7 @@ nsViewSourceChannel::SetLoadFlags(uint32_t aLoadFlags) { // the win32 compiler fails to deal due to amiguous inheritance. // nsIChannel::LOAD_DOCUMENT_URI/nsIRequest::LOAD_FROM_CACHE also fails; the // Win32 compiler thinks that's supposed to be a method. - mIsDocument = (aLoadFlags & ::nsIChannel::LOAD_DOCUMENT_URI) ? true : false; + mIsDocument = (aLoadFlags & ::nsIChannel::LOAD_DOCUMENT_URI) != 0; nsresult rv = mChannel->SetLoadFlags((aLoadFlags | ::nsIRequest::LOAD_FROM_CACHE) & diff --git a/netwerk/protocol/websocket/BaseWebSocketChannel.cpp b/netwerk/protocol/websocket/BaseWebSocketChannel.cpp index af3037e270f8..f8b6708ab231 100644 --- a/netwerk/protocol/websocket/BaseWebSocketChannel.cpp +++ b/netwerk/protocol/websocket/BaseWebSocketChannel.cpp @@ -267,10 +267,11 @@ NS_IMETHODIMP BaseWebSocketChannel::GetScheme(nsACString& aScheme) { LOG(("BaseWebSocketChannel::GetScheme() %p\n", this)); - if (mEncrypted) + if (mEncrypted) { aScheme.AssignLiteral("wss"); - else + } else { aScheme.AssignLiteral("ws"); + } return NS_OK; } @@ -278,10 +279,11 @@ NS_IMETHODIMP BaseWebSocketChannel::GetDefaultPort(int32_t* aDefaultPort) { LOG(("BaseWebSocketChannel::GetDefaultPort() %p\n", this)); - if (mEncrypted) + if (mEncrypted) { *aDefaultPort = kDefaultWSSPort; - else + } else { *aDefaultPort = kDefaultWSPort; + } return NS_OK; } diff --git a/netwerk/protocol/websocket/WebSocketChannel.cpp b/netwerk/protocol/websocket/WebSocketChannel.cpp index dca897349f77..80315c6b4638 100644 --- a/netwerk/protocol/websocket/WebSocketChannel.cpp +++ b/netwerk/protocol/websocket/WebSocketChannel.cpp @@ -215,7 +215,8 @@ class FailDelayManager { // Any remaining expired entries will be deleted next time Lookup // finds nothing, which is the most common case anyway. break; - } else if (fail->IsExpired(rightNow)) { + } + if (fail->IsExpired(rightNow)) { mEntries.RemoveElementAt(i); } } @@ -481,14 +482,16 @@ class nsWSAdmissionManager { } int32_t IndexOf(nsCString& aStr) { - for (uint32_t i = 0; i < mQueue.Length(); i++) + for (uint32_t i = 0; i < mQueue.Length(); i++) { if (aStr == (mQueue[i])->mAddress) return i; + } return -1; } int32_t IndexOf(WebSocketChannel* aChannel) { - for (uint32_t i = 0; i < mQueue.Length(); i++) + for (uint32_t i = 0; i < mQueue.Length(); i++) { if (aChannel == (mQueue[i])->mChannel) return i; + } return -1; } @@ -888,10 +891,10 @@ class PMCECompression { bool mNoContextTakeover; bool mResetDeflater; bool mMessageDeflated; - z_stream mDeflater; - z_stream mInflater; + z_stream mDeflater{}; + z_stream mInflater{}; const static uint32_t kBufferLen = 4096; - uint8_t mBuffer[kBufferLen]; + uint8_t mBuffer[kBufferLen]{}; }; //----------------------------------------------------------------------------- @@ -1936,11 +1939,12 @@ void WebSocketChannel::PrimeNewOutgoingMessage() { MOZ_ASSERT(mCurrentOut->GetMsgType() == kMsgTypePong, "Not pong message!"); } else { mCurrentOut = mOutgoingPingMessages.PopFront(); - if (mCurrentOut) + if (mCurrentOut) { MOZ_ASSERT(mCurrentOut->GetMsgType() == kMsgTypePing, "Not ping message!"); - else + } else { mCurrentOut = mOutgoingMessages.PopFront(); + } } if (!mCurrentOut) return; @@ -2308,8 +2312,9 @@ void WebSocketChannel::DoStopSession(nsresult reason) { do { total += count; rv = mSocketIn->Read(buffer, 512, &count); - if (rv != NS_BASE_STREAM_WOULD_BLOCK && (NS_FAILED(rv) || count == 0)) + if (rv != NS_BASE_STREAM_WOULD_BLOCK && (NS_FAILED(rv) || count == 0)) { mTCPClosed = true; + } } while (NS_SUCCEEDED(rv) && count > 0 && total < 32000); } @@ -2936,8 +2941,9 @@ void WebSocketChannel::ReportConnectionTelemetry(nsresult aStatusCode) { if (pi) { nsAutoCString proxyType; pi->GetType(proxyType); - if (!proxyType.IsEmpty() && !proxyType.EqualsLiteral("direct")) + if (!proxyType.IsEmpty() && !proxyType.EqualsLiteral("direct")) { didProxy = true; + } } uint8_t value = @@ -2977,8 +2983,9 @@ WebSocketChannel::OnLookupComplete(nsICancelable* aRequest, nsCOMPtr record = do_QueryInterface(aRecord); MOZ_ASSERT(record); nsresult rv = record->GetNextAddrAsString(mAddress); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { LOG(("WebSocketChannel::OnLookupComplete: Failed GetNextAddr\n")); + } } LOG(("WebSocket OnLookupComplete: Proceeding to ConditionallyConnect\n")); @@ -3029,8 +3036,9 @@ NS_IMETHODIMP WebSocketChannel::GetInterface(const nsIID& iid, void** result) { LOG(("WebSocketChannel::GetInterface() %p\n", this)); - if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) + if (iid.Equals(NS_GET_IID(nsIChannelEventSink))) { return QueryInterface(iid, result); + } if (mCallbacks) return mCallbacks->GetInterface(iid, result); @@ -3074,9 +3082,10 @@ WebSocketChannel::AsyncOnChannelRedirect( if (mEncrypted && !newuriIsHttps) { nsAutoCString spec; - if (NS_SUCCEEDED(newuri->GetSpec(spec))) + if (NS_SUCCEEDED(newuri->GetSpec(spec))) { LOG(("WebSocketChannel: Redirect to %s violates encryption rule\n", spec.get())); + } return NS_ERROR_FAILURE; } @@ -3150,8 +3159,9 @@ WebSocketChannel::Notify(nsITimer* timer) { MOZ_ASSERT(OnSocketThread(), "not on socket thread"); mCloseTimer = nullptr; - if (mStopped || mServerClosed) /* no longer relevant */ + if (mStopped || mServerClosed) { /* no longer relevant */ return NS_OK; + } LOG(("WebSocketChannel:: Expecting Server Close - Timed Out\n")); AbortSession(NS_ERROR_NET_TIMEOUT); @@ -3160,8 +3170,9 @@ WebSocketChannel::Notify(nsITimer* timer) { mOpenTimer = nullptr; LOG(("WebSocketChannel:: Connection Timed Out\n")); - if (mStopped || mServerClosed) /* no longer relevant */ + if (mStopped || mServerClosed) { /* no longer relevant */ return NS_OK; + } AbortSession(NS_ERROR_NET_TIMEOUT); } else if (timer == mReconnectDelayTimer) { @@ -3221,8 +3232,9 @@ WebSocketChannel::GetSecurityInfo(nsISupports** aSecurityInfo) { MOZ_ASSERT(NS_IsMainThread(), "not main thread"); if (mTransport) { - if (NS_FAILED(mTransport->GetSecurityInfo(aSecurityInfo))) + if (NS_FAILED(mTransport->GetSecurityInfo(aSecurityInfo))) { *aSecurityInfo = nullptr; + } } return NS_OK; } @@ -3877,8 +3889,10 @@ WebSocketChannel::OnInputStreamReady(nsIAsyncInputStream* aStream) { LOG(("WebSocketChannel::OnInputStreamReady() %p\n", this)); MOZ_ASSERT(OnSocketThread(), "not on socket thread"); - if (!mSocketIn) // did we we clean up the socket after scheduling InputReady? + if (!mSocketIn) { // did we we clean up the socket after scheduling + // InputReady? return NS_OK; + } // this is after the http upgrade - so we are speaking websockets char buffer[2048]; diff --git a/netwerk/protocol/websocket/WebSocketChannel.h b/netwerk/protocol/websocket/WebSocketChannel.h index 950f76d0b15c..0a618ae01575 100644 --- a/netwerk/protocol/websocket/WebSocketChannel.h +++ b/netwerk/protocol/websocket/WebSocketChannel.h @@ -290,7 +290,7 @@ class WebSocketChannel : public BaseWebSocketChannel, nsDeque mOutgoingPongMessages; uint32_t mHdrOutToSend; uint8_t* mHdrOut; - uint8_t mOutHeader[kCopyBreak + 16]; + uint8_t mOutHeader[kCopyBreak + 16]{}; UniquePtr mPMCECompressor; uint32_t mDynamicOutputSize; uint8_t* mDynamicOutput; diff --git a/netwerk/protocol/websocket/WebSocketChannelChild.h b/netwerk/protocol/websocket/WebSocketChannelChild.h index 4be4ada669f0..1729ae34afd3 100644 --- a/netwerk/protocol/websocket/WebSocketChannelChild.h +++ b/netwerk/protocol/websocket/WebSocketChannelChild.h @@ -25,7 +25,7 @@ class WebSocketChannelChild final : public BaseWebSocketChannel, friend class PWebSocketChild; public: - explicit WebSocketChannelChild(bool aSecure); + explicit WebSocketChannelChild(bool aEncrypted); NS_DECL_THREADSAFE_ISUPPORTS @@ -54,7 +54,7 @@ class WebSocketChannelChild final : public BaseWebSocketChannel, mozilla::ipc::IPCResult RecvOnStart(const nsCString& aProtocol, const nsCString& aExtensions, const nsString& aEffectiveURL, - const bool& aSecure, + const bool& aEncrypted, const uint64_t& aHttpChannelId); mozilla::ipc::IPCResult RecvOnStop(const nsresult& aStatusCode); mozilla::ipc::IPCResult RecvOnMessageAvailable( @@ -66,7 +66,7 @@ class WebSocketChannelChild final : public BaseWebSocketChannel, const nsCString& aReason); void OnStart(const nsCString& aProtocol, const nsCString& aExtensions, - const nsString& aEffectiveURL, const bool& aSecure, + const nsString& aEffectiveURL, const bool& aEncrypted, const uint64_t& aHttpChannelId); void OnStop(const nsresult& aStatusCode); void OnMessageAvailable(const nsCString& aMsg); diff --git a/netwerk/protocol/websocket/WebSocketEventService.cpp b/netwerk/protocol/websocket/WebSocketEventService.cpp index ba5234682c36..6e9a89a00517 100644 --- a/netwerk/protocol/websocket/WebSocketEventService.cpp +++ b/netwerk/protocol/websocket/WebSocketEventService.cpp @@ -75,7 +75,7 @@ class WebSocketFrameRunnable final : public WebSocketBaseRunnable { private: virtual void DoWork(nsIWebSocketEventListener* aListener) override { - DebugOnly rv; + DebugOnly rv{}; if (mFrameSent) { rv = aListener->FrameSent(mWebSocketSerialID, mFrame); } else { diff --git a/netwerk/protocol/websocket/WebSocketEventService.h b/netwerk/protocol/websocket/WebSocketEventService.h index 7d7fd8613824..f2a465b5d2ad 100644 --- a/netwerk/protocol/websocket/WebSocketEventService.h +++ b/netwerk/protocol/websocket/WebSocketEventService.h @@ -89,7 +89,7 @@ class WebSocketEventService final : public nsIWebSocketEventService, bool HasListeners() const; void Shutdown(); - typedef nsTArray> WindowListeners; + using WindowListeners = nsTArray>; nsTHashMap mWebSocketImplMap; diff --git a/netwerk/protocol/websocket/WebSocketFrame.cpp b/netwerk/protocol/websocket/WebSocketFrame.cpp index c73c170c4950..c8032dfa333e 100644 --- a/netwerk/protocol/websocket/WebSocketFrame.cpp +++ b/netwerk/protocol/websocket/WebSocketFrame.cpp @@ -138,7 +138,7 @@ bool WebSocketFrameData::ReadIPCParams(const IPC::Message* aMessage, if (!ReadParam(aMessage, aIter, &bit)) { \ return false; \ } \ - x = bit; \ + (x) = bit; \ } ReadParamHelper(mFinBit); diff --git a/netwerk/protocol/websocket/WebSocketFrame.h b/netwerk/protocol/websocket/WebSocketFrame.h index 3f96d9a13165..62d37447c792 100644 --- a/netwerk/protocol/websocket/WebSocketFrame.h +++ b/netwerk/protocol/websocket/WebSocketFrame.h @@ -16,7 +16,7 @@ class PickleIterator; // Avoid including nsDOMNavigationTiming.h here, where the canonical definition // of DOMHighResTimeStamp resides. -typedef double DOMHighResTimeStamp; +using DOMHighResTimeStamp = double; namespace IPC { class Message; @@ -83,7 +83,7 @@ class WebSocketFrame final : public nsIWebSocketFrame { namespace IPC { template <> struct ParamTraits { - typedef mozilla::net::WebSocketFrameData paramType; + using paramType = mozilla::net::WebSocketFrameData; static void Write(Message* aMsg, const paramType& aParam) { aParam.WriteIPCParams(aMsg); diff --git a/netwerk/socket/nsSOCKSIOLayer.cpp b/netwerk/socket/nsSOCKSIOLayer.cpp index 0a16d6c7236f..130b35f387bf 100644 --- a/netwerk/socket/nsSOCKSIOLayer.cpp +++ b/netwerk/socket/nsSOCKSIOLayer.cpp @@ -320,7 +320,8 @@ class Buffer { Buffer WriteNetAddr(const NetAddr* aAddr) { if (aAddr->raw.family == AF_INET) { return Write(aAddr->inet.ip); - } else if (aAddr->raw.family == AF_INET6) { + } + if (aAddr->raw.family == AF_INET6) { return Write(aAddr->inet6.ip.u8); } MOZ_ASSERT_UNREACHABLE("Unknown address family"); @@ -563,7 +564,8 @@ PRStatus nsSOCKSSocketInfo::ConnectToProxy(PRFileDesc* fd) { if (c == PR_WOULD_BLOCK_ERROR || c == PR_IN_PROGRESS_ERROR) { mState = SOCKS_CONNECTING_TO_PROXY; return status; - } else if (IsLocalProxy()) { + } + if (IsLocalProxy()) { LOGERROR(("socks: connect to domain socket failed (%d)", c)); PR_SetError(PR_CONNECT_REFUSED_ERROR, 0); mState = SOCKS_FAILED; @@ -797,7 +799,8 @@ PRStatus nsSOCKSSocketInfo::ReadV5AuthResponse() { if (mProxyUsername.IsEmpty() && authMethod == 0x00) { // no auth LOGDEBUG(("socks5: server allows connection without authentication")); return WriteV5ConnectRequest(); - } else if (!mProxyUsername.IsEmpty() && authMethod == 0x02) { // username/pw + } + if (!mProxyUsername.IsEmpty() && authMethod == 0x02) { // username/pw LOGDEBUG(("socks5: auth method accepted by server")); return WriteV5UsernameRequest(); } else { // 0xFF signals error @@ -1246,7 +1249,8 @@ PRStatus nsSOCKSSocketInfo::ReadFromSocket(PRFileDesc* fd) { LOGERROR(("socks: proxy server closed connection")); HandshakeFinished(PR_CONNECT_REFUSED_ERROR); return PR_FAILURE; - } else if (PR_GetError() == PR_WOULD_BLOCK_ERROR) { + } + if (PR_GetError() == PR_WOULD_BLOCK_ERROR) { LOGDEBUG(("socks: ReadFromSocket(), want read")); } break; diff --git a/netwerk/socket/nsSOCKSSocketProvider.cpp b/netwerk/socket/nsSOCKSSocketProvider.cpp index 536e06c96211..9d54a6c737fb 100644 --- a/netwerk/socket/nsSOCKSSocketProvider.cpp +++ b/netwerk/socket/nsSOCKSSocketProvider.cpp @@ -21,10 +21,11 @@ nsresult nsSOCKSSocketProvider::CreateV4(nsISupports* aOuter, REFNSIID aIID, nsresult rv; nsCOMPtr inst = new nsSOCKSSocketProvider(NS_SOCKS_VERSION_4); - if (!inst) + if (!inst) { rv = NS_ERROR_OUT_OF_MEMORY; - else + } else { rv = inst->QueryInterface(aIID, aResult); + } return rv; } @@ -33,10 +34,11 @@ nsresult nsSOCKSSocketProvider::CreateV5(nsISupports* aOuter, REFNSIID aIID, nsresult rv; nsCOMPtr inst = new nsSOCKSSocketProvider(NS_SOCKS_VERSION_5); - if (!inst) + if (!inst) { rv = NS_ERROR_OUT_OF_MEMORY; - else + } else { rv = inst->QueryInterface(aIID, aResult); + } return rv; } diff --git a/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp b/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp index 1ab51adb827b..076ff492c524 100644 --- a/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp +++ b/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp @@ -195,8 +195,9 @@ bool mozTXTToHTMLConv::FindURLStart(const char16_t* aInString, IsAsciiDigit(aInString[uint32_t(i)]) || aInString[uint32_t(i)] == '+' || aInString[uint32_t(i)] == '-' || aInString[uint32_t(i)] == '.'); - i--) + i--) { ; + } if (++i >= 0 && uint32_t(i) < pos && IsAsciiAlpha(aInString[uint32_t(i)])) { start = uint32_t(i); @@ -219,8 +220,9 @@ bool mozTXTToHTMLConv::FindURLStart(const char16_t* aInString, !IsSpace(aInString[uint32_t(i)]) && (!isEmail || IsAscii(aInString[uint32_t(i)])) && (!isEmail || aInString[uint32_t(i)] != ')'); - i--) + i--) { ; + } if (++i >= 0 && uint32_t(i) < pos && (IsAsciiAlpha(aInString[uint32_t(i)]) || IsAsciiDigit(aInString[uint32_t(i)]))) { @@ -268,13 +270,15 @@ bool mozTXTToHTMLConv::FindURLEnd(const char16_t* aInString, // Allow IPv6 adresses like http://[1080::8:800:200C:417A]/foo. (aInString[i] == '[' && i > 2 && (aInString[i - 1] != '/' || aInString[i - 2] != '/')) || - IsSpace(aInString[i])) + IsSpace(aInString[i])) { break; + } // Disallow non-ascii-characters for email. // Currently correct, but revisit later after standards changed. if (isEmail && (aInString[i] == '(' || aInString[i] == '\'' || - !IsAscii(aInString[i]))) + !IsAscii(aInString[i]))) { break; + } if (aInString[i] == '(') seenOpeningParenthesis = true; if (aInString[i] == '[') seenOpeningSquareBracket = true; } @@ -283,8 +287,9 @@ bool mozTXTToHTMLConv::FindURLEnd(const char16_t* aInString, while (--i > pos && (aInString[i] == '.' || aInString[i] == ',' || aInString[i] == ';' || aInString[i] == '!' || aInString[i] == '?' || aInString[i] == '-' || - aInString[i] == ':' || aInString[i] == '\'')) + aInString[i] == ':' || aInString[i] == '\'')) { ; + } if (i > pos) { end = i; return true; @@ -452,8 +457,9 @@ bool mozTXTToHTMLConv::FindURL(const char16_t* aInString, int32_t aInLength, /* all modes but abbreviated are checked for text[pos] == ':', only abbreviated for '.', RFC2396E and abbreviated for '@' */ for (modetype iState = unknown; iState <= mozTXTToHTMLConv_lastMode; - iState = modetype(iState + 1)) + iState = modetype(iState + 1)) { state[iState] = aInString[pos] == ':' ? unchecked : invalid; + } switch (aInString[pos]) { case '@': state[RFC2396E] = unchecked; @@ -480,13 +486,17 @@ bool mozTXTToHTMLConv::FindURL(const char16_t* aInString, int32_t aInLength, uint32_t start, end; - if (state[check] == unchecked) - if (FindURLStart(aInString, aInLength, pos, check, start)) + if (state[check] == unchecked) { + if (FindURLStart(aInString, aInLength, pos, check, start)) { state[check] = startok; + } + } - if (state[check] == startok) - if (FindURLEnd(aInString, aInLength, pos, check, start, end)) + if (state[check] == startok) { + if (FindURLEnd(aInString, aInLength, pos, check, start, end)) { state[check] = endok; + } + } if (state[check] == endok) { nsAutoString txtURL, desc; @@ -536,8 +546,9 @@ bool mozTXTToHTMLConv::ItMatchesDelimited(const char16_t* aInString, ((before != LT_IGNORE || (after != LT_IGNORE && after != LT_DELIMITER)) && textLen < aRepLen + 1) || (before != LT_IGNORE && after != LT_IGNORE && after != LT_DELIMITER && - textLen < aRepLen + 2)) + textLen < aRepLen + 2)) { return false; + } uint32_t text0 = aInString[0]; if (aInLength > 1 && NS_IS_SURROGATE_PAIR(text0, aInString[1])) { @@ -558,22 +569,19 @@ bool mozTXTToHTMLConv::ItMatchesDelimited(const char16_t* aInString, textAfterPos = SURROGATE_TO_UCS4(textAfterPos, aInString[afterIndex + 1]); } - if ((before == LT_ALPHA && !IsAlpha(text0)) || - (before == LT_DIGIT && !IsDigit(text0)) || - (before == LT_DELIMITER && - (IsAlpha(text0) || IsDigit(text0) || text0 == *rep)) || - (after == LT_ALPHA && !IsAlpha(textAfterPos)) || - (after == LT_DIGIT && !IsDigit(textAfterPos)) || - (after == LT_DELIMITER && - (IsAlpha(textAfterPos) || IsDigit(textAfterPos) || - textAfterPos == *rep)) || - !Substring(Substring(aInString, aInString + aInLength), ignoreLen, - aRepLen) - .Equals(Substring(rep, rep + aRepLen), - nsCaseInsensitiveStringComparator)) - return false; - - return true; + return !((before == LT_ALPHA && !IsAlpha(text0)) || + (before == LT_DIGIT && !IsDigit(text0)) || + (before == LT_DELIMITER && + (IsAlpha(text0) || IsDigit(text0) || text0 == *rep)) || + (after == LT_ALPHA && !IsAlpha(textAfterPos)) || + (after == LT_DIGIT && !IsDigit(textAfterPos)) || + (after == LT_DELIMITER && + (IsAlpha(textAfterPos) || IsDigit(textAfterPos) || + textAfterPos == *rep)) || + !Substring(Substring(aInString, aInString + aInLength), ignoreLen, + aRepLen) + .Equals(Substring(rep, rep + aRepLen), + nsCaseInsensitiveStringComparator)); } uint32_t mozTXTToHTMLConv::NumberOfMatches(const char16_t* aInString, @@ -631,9 +639,8 @@ bool mozTXTToHTMLConv::StructPhraseHit( } // closing tag - else if (openTags > 0 && - ItMatchesDelimited(aInString, aInStringLength, tagTXT, aTagTXTLen, - LT_ALPHA, LT_DELIMITER)) { + if (openTags > 0 && ItMatchesDelimited(aInString, aInStringLength, tagTXT, + aTagTXTLen, LT_ALPHA, LT_DELIMITER)) { openTags--; aOutString.AppendLiteral(""); aOutString.Append(tagTXT); @@ -845,8 +852,9 @@ bool mozTXTToHTMLConv::GlyphHit(const char16_t* aInString, int32_t aInLength, (IsAsciiDigit(aInString[delimPos]) || (aInString[delimPos] == '.' && delimPos + 1 < aInLength && IsAsciiDigit(aInString[delimPos + 1]))); - delimPos++) + delimPos++) { ; + } if (delimPos < aInLength && IsAsciiAlpha(aInString[delimPos])) { return false; @@ -933,15 +941,16 @@ int32_t mozTXTToHTMLConv::CiteLevelTXT(const char16_t* line, uint32_t minlength = std::min(uint32_t(6), NS_strlen(indexString)); if (Substring(indexString, indexString + minlength) .Equals(Substring(u">From "_ns, 0, minlength), - nsCaseInsensitiveStringComparator)) + nsCaseInsensitiveStringComparator)) { // XXX RFC2646 moreCites = false; - else { + } else { result++; logLineStart = i; } - } else + } else { moreCites = false; + } } return result; @@ -1129,28 +1138,31 @@ mozTXTToHTMLConv::ScanHTML(const nsAString& input, uint32_t whattodo, // Make sure there's a white-space character after, not to match "abbr". { i = aInString.Find("", true, i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i += 4; + } } else if (Substring(aInString, i + 1, 3).LowerCaseEqualsASCII("!--")) // if out-commended code, skip until --> { i = aInString.Find("-->", false, i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i += 3; + } } else if (i + 6 < lengthOfInString && Substring(aInString, i + 1, 5).LowerCaseEqualsASCII("style") && canFollow.FindChar(aInString[i + 6]) != kNotFound) // if style tag, skip until { i = aInString.Find("", true, i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i += 8; + } } else if (i + 7 < lengthOfInString && Substring(aInString, i + 1, 6) .LowerCaseEqualsASCII("script") && @@ -1158,10 +1170,11 @@ mozTXTToHTMLConv::ScanHTML(const nsAString& input, uint32_t whattodo, // if script tag, skip until { i = aInString.Find("", true, i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i += 9; + } } else if (i + 5 < lengthOfInString && Substring(aInString, i + 1, 4).LowerCaseEqualsASCII("head") && canFollow.FindChar(aInString[i + 5]) != kNotFound) @@ -1169,17 +1182,19 @@ mozTXTToHTMLConv::ScanHTML(const nsAString& input, uint32_t whattodo, // Make sure not to match
. { i = aInString.Find("", true, i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i += 7; + } } else // just skip tag (attributes etc.) { i = aInString.FindChar('>', i); - if (i == kNotFound) + if (i == kNotFound) { i = lengthOfInString; - else + } else { i++; + } } aOutString.Append(&uniBuffer[start], i - start); } else { diff --git a/netwerk/streamconv/converters/mozTXTToHTMLConv.h b/netwerk/streamconv/converters/mozTXTToHTMLConv.h index 23c3dac30f31..2fbed474f463 100644 --- a/netwerk/streamconv/converters/mozTXTToHTMLConv.h +++ b/netwerk/streamconv/converters/mozTXTToHTMLConv.h @@ -237,7 +237,7 @@ class mozTXTToHTMLConv : public mozITXTToHTMLConv { bool StructPhraseHit(const char16_t* aInString, int32_t aInStringLength, bool col0, const char16_t* tagTXT, int32_t aTagTxtLen, const char* tagHTML, const char* attributeHTML, - nsAString& aOutputString, uint32_t& openTags); + nsAString& aOutString, uint32_t& openTags); /** @param text (in), col0 (in): see GlyphHit @@ -267,7 +267,7 @@ class mozTXTToHTMLConv : public mozITXTToHTMLConv { @return see StructPhraseHit */ bool GlyphHit(const char16_t* aInString, int32_t aInLength, bool col0, - nsAString& aOutString, int32_t& glyphTextLen); + nsAString& aOutputString, int32_t& glyphTextLen); /** Check if a given url should be linkified. diff --git a/netwerk/streamconv/converters/nsDirIndexParser.cpp b/netwerk/streamconv/converters/nsDirIndexParser.cpp index ed53cc45fb44..c4d9e160096e 100644 --- a/netwerk/streamconv/converters/nsDirIndexParser.cpp +++ b/netwerk/streamconv/converters/nsDirIndexParser.cpp @@ -94,10 +94,11 @@ nsresult nsDirIndexParser::Init() { nsresult rv; // XXX not threadsafe - if (gRefCntParser++ == 0) + if (gRefCntParser++ == 0) { rv = CallGetService(NS_ITEXTTOSUBURI_CONTRACTID, &gTextToSubURI); - else + } else { rv = NS_OK; + } return rv; } @@ -177,15 +178,17 @@ void nsDirIndexParser::ParseFormat(const char* aFormatStr) { mFormat[0] = -1; do { - while (*aFormatStr && nsCRT::IsAsciiSpace(char16_t(*aFormatStr))) + while (*aFormatStr && nsCRT::IsAsciiSpace(char16_t(*aFormatStr))) { ++aFormatStr; + } if (!*aFormatStr) break; nsAutoCString name; int32_t len = 0; - while (aFormatStr[len] && !nsCRT::IsAsciiSpace(char16_t(aFormatStr[len]))) + while (aFormatStr[len] && !nsCRT::IsAsciiSpace(char16_t(aFormatStr[len]))) { ++len; + } name.Append(aFormatStr, len); aFormatStr += len; @@ -312,10 +315,11 @@ void nsDirIndexParser::ParseData(nsIDirIndex* aIdx, char* aDataStr, case FIELD_CONTENTLENGTH: { int64_t len; int32_t status = PR_sscanf(value, "%lld", &len); - if (status == 1) + if (status == 1) { aIdx->SetSize(len); - else + } else { aIdx->SetSize(UINT64_MAX); // UINT64_MAX means unknown + } } break; case FIELD_LASTMODIFIED: { PRTime tm; diff --git a/netwerk/streamconv/converters/nsDirIndexParser.h b/netwerk/streamconv/converters/nsDirIndexParser.h index c2dfe3c160ab..3f3f5ea45124 100644 --- a/netwerk/streamconv/converters/nsDirIndexParser.h +++ b/netwerk/streamconv/converters/nsDirIndexParser.h @@ -55,10 +55,10 @@ class nsDirIndexParser : public nsIDirIndexParser { nsCString mBuf; int32_t mLineStart; bool mHasDescription; - int mFormat[8]; + int mFormat[8]{}; nsresult ProcessData(nsIRequest* aRequest, nsISupports* aCtxt); - void ParseFormat(const char* buf); + void ParseFormat(const char* aFormatStr); void ParseData(nsIDirIndex* aIdx, char* aDataStr, int32_t lineLen); struct Field { diff --git a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp index 2f8cfab56fdc..8a66b9144f6c 100644 --- a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp +++ b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp @@ -368,7 +368,8 @@ nsHTTPCompressConv::OnDataAvailable(nsIRequest* request, nsIInputStream* iStr, inflateEnd(&d_stream); mStreamEnded = true; break; - } else if (code == Z_OK) { + } + if (code == Z_OK) { if (bytesWritten) { rv = do_OnDataAvailable(request, nullptr, aSourceOffset, (char*)mOutBuffer, bytesWritten); @@ -450,7 +451,8 @@ nsHTTPCompressConv::OnDataAvailable(nsIRequest* request, nsIInputStream* iStr, inflateEnd(&d_stream); mStreamEnded = true; break; - } else if (code == Z_OK) { + } + if (code == Z_OK) { if (bytesWritten) { rv = do_OnDataAvailable(request, nullptr, aSourceOffset, (char*)mOutBuffer, bytesWritten); diff --git a/netwerk/streamconv/converters/nsHTTPCompressConv.h b/netwerk/streamconv/converters/nsHTTPCompressConv.h index 1ad34bbfabc9..77a2c2c8e758 100644 --- a/netwerk/streamconv/converters/nsHTTPCompressConv.h +++ b/netwerk/streamconv/converters/nsHTTPCompressConv.h @@ -43,13 +43,13 @@ class nsIStringInputStream; namespace mozilla { namespace net { -typedef enum { +using CompressMode = enum { HTTP_COMPRESS_GZIP, HTTP_COMPRESS_DEFLATE, HTTP_COMPRESS_COMPRESS, HTTP_COMPRESS_BROTLI, HTTP_COMPRESS_IDENTITY -} CompressMode; +}; class BrotliWrapper { public: @@ -60,11 +60,11 @@ class BrotliWrapper { mRequest(nullptr), mContext(nullptr), mSourceOffset(0) { - BrotliDecoderStateInit(&mState, 0, 0, 0); + BrotliDecoderStateInit(&mState, nullptr, nullptr, nullptr); } ~BrotliWrapper() { BrotliDecoderStateCleanup(&mState); } - BrotliDecoderState mState; + BrotliDecoderState mState{}; Atomic mTotalOut; nsresult mStatus; Atomic mBrotliStateIsStreamEnd; @@ -124,7 +124,7 @@ class nsHTTPCompressConv : public nsIStreamConverter, z_stream d_stream; unsigned mLen, hMode, mSkipCount, mFlags; - uint32_t check_header(nsIInputStream* iStr, uint32_t streamLen, nsresult* rv); + uint32_t check_header(nsIInputStream* iStr, uint32_t streamLen, nsresult* rs); Atomic mDecodedDataLength; diff --git a/netwerk/streamconv/converters/nsIndexedToHTML.cpp b/netwerk/streamconv/converters/nsIndexedToHTML.cpp index 56467bf01d82..b68a2d7eb3b3 100644 --- a/netwerk/streamconv/converters/nsIndexedToHTML.cpp +++ b/netwerk/streamconv/converters/nsIndexedToHTML.cpp @@ -657,8 +657,9 @@ nsIndexedToHTML::OnIndexAvailable(nsIRequest* aRequest, nsISupports* aCtxt, if (loc.IsEmpty()) { return NS_ERROR_ILLEGAL_VALUE; } - if (loc.First() == char16_t('.')) + if (loc.First() == char16_t('.')) { pushBuffer.AppendLiteral(" class=\"hidden-object\""); + } pushBuffer.AppendLiteral(">\n loadGroup; (void)mPartChannel->GetLoadGroup(getter_AddRefs(loadGroup)); - if (loadGroup) + if (loadGroup) { (void)loadGroup->RemoveRequest(mPartChannel, mContext, aStatus); + } } mPartChannel = nullptr; @@ -922,8 +923,9 @@ nsresult nsMultiMixedConv::SendData() { if (mContentLength != UINT64_MAX) { // make sure that we don't send more than the mContentLength // XXX why? perhaps the Content-Length header was actually wrong!! - if ((uint64_t(mRawDataLength) + mTotalSent) > mContentLength) + if ((uint64_t(mRawDataLength) + mTotalSent) > mContentLength) { mRawDataLength = static_cast(mContentLength - mTotalSent); + } if (mRawDataLength == 0) return NS_OK; } diff --git a/netwerk/streamconv/converters/nsMultiMixedConv.h b/netwerk/streamconv/converters/nsMultiMixedConv.h index feb93ff36073..0d567c31a72a 100644 --- a/netwerk/streamconv/converters/nsMultiMixedConv.h +++ b/netwerk/streamconv/converters/nsMultiMixedConv.h @@ -135,7 +135,7 @@ class nsMultiMixedConv : public nsIStreamConverter { explicit nsMultiMixedConv(); protected: - typedef mozilla::IncrementalTokenizer::Token Token; + using Token = mozilla::IncrementalTokenizer::Token; virtual ~nsMultiMixedConv() = default; @@ -220,7 +220,7 @@ class nsMultiMixedConv : public nsIStreamConverter { // of that data during a single tokenizer input feed. This is always // flushed right after we fed the tokenizer. nsACString::const_char_iterator mRawData; - nsACString::size_type mRawDataLength; + nsACString::size_type mRawDataLength{0}; // At the start we don't know if the server will be sending boundary with // or without the leading dashes. diff --git a/netwerk/streamconv/converters/nsUnknownDecoder.cpp b/netwerk/streamconv/converters/nsUnknownDecoder.cpp index 1d0735ec0183..698ba3357d8e 100644 --- a/netwerk/streamconv/converters/nsUnknownDecoder.cpp +++ b/netwerk/streamconv/converters/nsUnknownDecoder.cpp @@ -84,8 +84,9 @@ nsUnknownDecoder::nsUnknownDecoder() nsCOMPtr prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); if (prefs) { bool val; - if (NS_SUCCEEDED(prefs->GetBoolPref("security.requireHTMLsuffix", &val))) + if (NS_SUCCEEDED(prefs->GetBoolPref("security.requireHTMLsuffix", &val))) { mRequireHTMLsuffix = val; + } } } diff --git a/netwerk/streamconv/converters/nsUnknownDecoder.h b/netwerk/streamconv/converters/nsUnknownDecoder.h index 3c46d52414fd..783fc607641d 100644 --- a/netwerk/streamconv/converters/nsUnknownDecoder.h +++ b/netwerk/streamconv/converters/nsUnknownDecoder.h @@ -103,7 +103,7 @@ class nsUnknownDecoder : public nsIStreamConverter, * false otherwise */ struct nsSnifferEntry { - typedef bool (nsUnknownDecoder::*TypeSniffFunc)(nsIRequest* aRequest); + using TypeSniffFunc = bool (nsUnknownDecoder::*)(nsIRequest*); const char* mBytes; uint32_t mByteLen; diff --git a/netwerk/streamconv/nsStreamConverterService.cpp b/netwerk/streamconv/nsStreamConverterService.cpp index 4a8f15e3777d..85e0f6d9bee0 100644 --- a/netwerk/streamconv/nsStreamConverterService.cpp +++ b/netwerk/streamconv/nsStreamConverterService.cpp @@ -161,7 +161,7 @@ nsresult nsStreamConverterService::ParseFromTo(const char* aContractID, return NS_OK; } -typedef nsClassHashtable BFSHashTable; +using BFSHashTable = nsClassHashtable; // nsObjectHashtable enumerator functions. @@ -370,8 +370,9 @@ nsStreamConverterService::Convert(nsIInputStream* aFromStream, const char* aFromType, const char* aToType, nsISupports* aContext, nsIInputStream** _retval) { - if (!aFromStream || !aFromType || !aToType || !_retval) + if (!aFromStream || !aFromType || !aToType || !_retval) { return NS_ERROR_NULL_POINTER; + } nsresult rv; // first determine whether we can even handle this conversion @@ -448,8 +449,9 @@ nsStreamConverterService::AsyncConvertData(const char* aFromType, nsIStreamListener* aListener, nsISupports* aContext, nsIStreamListener** _retval) { - if (!aFromType || !aToType || !aListener || !_retval) + if (!aFromType || !aToType || !aListener || !_retval) { return NS_ERROR_NULL_POINTER; + } nsresult rv; diff --git a/netwerk/system/linux/nsNetworkLinkService.cpp b/netwerk/system/linux/nsNetworkLinkService.cpp index 52eabcda3fd7..5e59789dc0b7 100644 --- a/netwerk/system/linux/nsNetworkLinkService.cpp +++ b/netwerk/system/linux/nsNetworkLinkService.cpp @@ -134,8 +134,9 @@ nsresult nsNetworkLinkService::Shutdown() { // remove xpcom shutdown observer nsCOMPtr observerService = mozilla::services::GetObserverService(); - if (observerService) + if (observerService) { observerService->RemoveObserver(this, "xpcom-shutdown-threads"); + } if (mNetlinkSvc) { mNetlinkSvc->Shutdown(); diff --git a/netwerk/test/gtest/TestCookie.cpp b/netwerk/test/gtest/TestCookie.cpp index 1bbb0f0ef4ac..368915f99d57 100644 --- a/netwerk/test/gtest/TestCookie.cpp +++ b/netwerk/test/gtest/TestCookie.cpp @@ -749,7 +749,7 @@ TEST(TestCookie, TestCookieMain) do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv0); ASSERT_TRUE(NS_SUCCEEDED(rv0)); - nsCOMPtr cookieMgr2 = cookieMgr; + const nsCOMPtr& cookieMgr2 = cookieMgr; ASSERT_TRUE(cookieMgr2); mozilla::OriginAttributes attrs; @@ -797,10 +797,11 @@ TEST(TestCookie, TestCookieMain) for (const auto& cookie : cookies) { nsAutoCString name; cookie->GetName(name); - if (name.EqualsLiteral("test2")) + if (name.EqualsLiteral("test2")) { expiredCookie = cookie; - else if (name.EqualsLiteral("test3")) + } else if (name.EqualsLiteral("test3")) { newDomainCookie = cookie; + } } EXPECT_EQ(cookies.Length(), 3ul); // check the httpOnly attribute of the second cookie is honored diff --git a/netwerk/test/gtest/TestMozURL.cpp b/netwerk/test/gtest/TestMozURL.cpp index de0d69f28d75..60b93fc101f9 100644 --- a/netwerk/test/gtest/TestMozURL.cpp +++ b/netwerk/test/gtest/TestMozURL.cpp @@ -343,9 +343,7 @@ TEST(TestMozURL, UrlTestData) reader->parse(data.BeginReading(), data.EndReading(), &root, nullptr)); ASSERT_TRUE(root.isArray()); - for (uint32_t index = 0; index < root.size(); index++) { - const Json::Value& item = root[index]; - + for (auto& item : root) { if (!item.isObject()) { continue; } diff --git a/netwerk/test/gtest/TestPACMan.cpp b/netwerk/test/gtest/TestPACMan.cpp index 52a34b489762..de8cfe979e8d 100644 --- a/netwerk/test/gtest/TestPACMan.cpp +++ b/netwerk/test/gtest/TestPACMan.cpp @@ -1,3 +1,5 @@ +#include + #include "gtest/gtest.h" #include "nsServiceManagerUtils.h" #include "../../../xpcom/threads/nsThreadManager.h" @@ -12,7 +14,7 @@ #define TEST_ASSIGNED_PAC_URL "http://assignedpac/pac.dat" #define WPAD_PREF 4 #define NETWORK_PROXY_TYPE_PREF_NAME "network.proxy.type" -#define GETTING_NETWORK_PROXY_TYPE_FAILED -1 +#define GETTING_NETWORK_PROXY_TYPE_FAILED (-1) nsCString WPADOptionResult; @@ -146,7 +148,7 @@ class TestPACMan : public ::testing::Test { nsCOMPtr GetPACManDHCPCient() { return mPACMan->mDHCPClient; } void SetPACManDHCPCient(nsCOMPtr aValue) { - mPACMan->mDHCPClient = aValue; + mPACMan->mDHCPClient = std::move(aValue); } void AssertPACSpecEqualTo(const char* aExpected) { diff --git a/netwerk/test/gtest/TestServerTimingHeader.cpp b/netwerk/test/gtest/TestServerTimingHeader.cpp index 159e5bd7bc69..183726a44062 100644 --- a/netwerk/test/gtest/TestServerTimingHeader.cpp +++ b/netwerk/test/gtest/TestServerTimingHeader.cpp @@ -111,53 +111,53 @@ TEST(TestServerTimingHeader, HeaderParsing) // metric;desc="" --> '' testServerTimingHeader("metric;desc=\"\"", {{"metric", "0", ""}}); // metric;desc=\\\ --> '' - testServerTimingHeader("metric;desc=\\\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\\)", {{"metric", "0", ""}}); // metric;desc=\\" --> '' - testServerTimingHeader("metric;desc=\\\\\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\")", {{"metric", "0", ""}}); // metric;desc=\"\ --> '' - testServerTimingHeader("metric;desc=\\\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\"\)", {{"metric", "0", ""}}); // metric;desc=\"" --> '' - testServerTimingHeader("metric;desc=\\\"\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\"")", {{"metric", "0", ""}}); // metric;desc="\\ --> '' - testServerTimingHeader("metric;desc=\"\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="\\)", {{"metric", "0", ""}}); // metric;desc="\" --> '' - testServerTimingHeader("metric;desc=\"\\\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="\")", {{"metric", "0", ""}}); // metric;desc=""\ --> '' - testServerTimingHeader("metric;desc=\"\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=""\)", {{"metric", "0", ""}}); // metric;desc=""" --> '' - testServerTimingHeader("metric;desc=\"\"\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=""")", {{"metric", "0", ""}}); // metric;desc=\\\\ --> '' - testServerTimingHeader("metric;desc=\\\\\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\\\)", {{"metric", "0", ""}}); // metric;desc=\\\" --> '' - testServerTimingHeader("metric;desc=\\\\\\\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\\")", {{"metric", "0", ""}}); // metric;desc=\\"\ --> '' - testServerTimingHeader("metric;desc=\\\\\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\"\)", {{"metric", "0", ""}}); // metric;desc=\\"" --> '' - testServerTimingHeader("metric;desc=\\\\\"\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\\"")", {{"metric", "0", ""}}); // metric;desc=\"\\ --> '' - testServerTimingHeader("metric;desc=\\\"\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\"\\)", {{"metric", "0", ""}}); // metric;desc=\"\" --> '' - testServerTimingHeader("metric;desc=\\\"\\\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\"\")", {{"metric", "0", ""}}); // metric;desc=\""\ --> '' - testServerTimingHeader("metric;desc=\\\"\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\""\)", {{"metric", "0", ""}}); // metric;desc=\""" --> '' - testServerTimingHeader("metric;desc=\\\"\"\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=\""")", {{"metric", "0", ""}}); // metric;desc="\\\ --> '' - testServerTimingHeader("metric;desc=\"\\\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="\\\)", {{"metric", "0", ""}}); // metric;desc="\\" --> '\' - testServerTimingHeader("metric;desc=\"\\\\\"", {{"metric", "0", "\\"}}); + testServerTimingHeader(R"(metric;desc="\\")", {{"metric", "0", "\\"}}); // metric;desc="\"\ --> '' - testServerTimingHeader("metric;desc=\"\\\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="\"\)", {{"metric", "0", ""}}); // metric;desc="\"" --> '"' - testServerTimingHeader("metric;desc=\"\\\"\"", {{"metric", "0", "\""}}); + testServerTimingHeader(R"(metric;desc="\"")", {{"metric", "0", "\""}}); // metric;desc=""\\ --> '' - testServerTimingHeader("metric;desc=\"\"\\\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=""\\)", {{"metric", "0", ""}}); // metric;desc=""\" --> '' - testServerTimingHeader("metric;desc=\"\"\\\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc=""\")", {{"metric", "0", ""}}); // metric;desc="""\ --> '' - testServerTimingHeader("metric;desc=\"\"\"\\", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="""\)", {{"metric", "0", ""}}); // metric;desc="""" --> '' - testServerTimingHeader("metric;desc=\"\"\"\"", {{"metric", "0", ""}}); + testServerTimingHeader(R"(metric;desc="""")", {{"metric", "0", ""}}); // duplicate entry names testServerTimingHeader( @@ -229,9 +229,8 @@ TEST(TestServerTimingHeader, HeaderParsing) testServerTimingHeader(" total;dur=123.4 ", {{"total", "123.4", ""}}); // test cases for comma in quoted string - testServerTimingHeader( - " metric ; desc=\"descr\\\"\\\";,=iption\";dur=123.4", - {{"metric", "123.4", "descr\"\";,=iption"}}); + testServerTimingHeader(R"( metric ; desc="descr\"\";,=iption";dur=123.4)", + {{"metric", "123.4", "descr\"\";,=iption"}}); testServerTimingHeader( " metric2;dur=\"123.4\";;desc=\",;\\\",;,\";;, metric ; desc = \" " "\\\", ;\\\" \"; dur=123.4,", diff --git a/netwerk/test/gtest/TestSocketTransportService.cpp b/netwerk/test/gtest/TestSocketTransportService.cpp index ce8c301c7da6..db908471f228 100644 --- a/netwerk/test/gtest/TestSocketTransportService.cpp +++ b/netwerk/test/gtest/TestSocketTransportService.cpp @@ -16,7 +16,7 @@ TEST(TestSocketTransportService, PortRemappingPreferenceReading) do_GetService("@mozilla.org/network/socket-transport-service;1"); ASSERT_TRUE(service); - auto sts = gSocketTransportService; + auto* sts = gSocketTransportService; ASSERT_TRUE(sts); sts->Dispatch( diff --git a/netwerk/test/gtest/TestStandardURL.cpp b/netwerk/test/gtest/TestStandardURL.cpp index b6a6e71764b1..d852f4a80c94 100644 --- a/netwerk/test/gtest/TestStandardURL.cpp +++ b/netwerk/test/gtest/TestStandardURL.cpp @@ -189,8 +189,8 @@ TEST(TestStandardURL, NormalizeBad) "2.2.2.256", "2.2.-2.3", "+2.2.2.3", "13.0x2x2.2.3", "0x2x2.13.2.3"}; - for (uint32_t i = 0; i < sizeof(manual) / sizeof(manual[0]); i++) { - nsCString encHost(manual[i]); + for (auto& i : manual) { + nsCString encHost(i); ASSERT_EQ(NS_ERROR_FAILURE, Test_NormalizeIPv4(encHost, result)); } } @@ -223,8 +223,8 @@ TEST(TestStandardURL, From_test_standardurldotjs) "0X7F000001", "0X007F.0X0000.0X0000.0X0001", "000177.0.00000.0X0001"}; - for (uint32_t i = 0; i < sizeof(localIPv4s) / sizeof(localIPv4s[0]); i++) { - nsCString encHost(localIPv4s[i]); + for (auto& localIPv4 : localIPv4s) { + nsCString encHost(localIPv4); ASSERT_EQ(NS_OK, Test_NormalizeIPv4(encHost, result)); ASSERT_TRUE(result.EqualsLiteral("127.0.0.1")); } @@ -237,8 +237,8 @@ TEST(TestStandardURL, From_test_standardurldotjs) "2+3", "0.0.0.-1", "1.2.3.4..", "1..2", ".1.2.3.4"}; - for (uint32_t i = 0; i < sizeof(nonIPv4s) / sizeof(nonIPv4s[0]); i++) { - nsCString encHost(nonIPv4s[i]); + for (auto& nonIPv4 : nonIPv4s) { + nsCString encHost(nonIPv4); ASSERT_EQ(NS_ERROR_FAILURE, Test_NormalizeIPv4(encHost, result)); } } diff --git a/netwerk/test/gtest/TestUDPSocket.cpp b/netwerk/test/gtest/TestUDPSocket.cpp index 84d26fbedf04..b5a98223832a 100644 --- a/netwerk/test/gtest/TestUDPSocket.cpp +++ b/netwerk/test/gtest/TestUDPSocket.cpp @@ -108,8 +108,8 @@ UDPClientListener::OnPacketReceived(nsIUDPSocket* socket, ADD_FAILURE(); } return NS_OK; - } else if (TEST_OUTPUT_STREAM != phase || - !CheckMessageContent(message, RESPONSE)) { + } + if (TEST_OUTPUT_STREAM != phase || !CheckMessageContent(message, RESPONSE)) { mResult = NS_ERROR_FAILURE; } @@ -172,7 +172,8 @@ UDPServerListener::OnPacketReceived(nsIUDPSocket* socket, ADD_FAILURE(); } return NS_OK; - } else if (TEST_MULTICAST == phase && CheckMessageContent(message, REQUEST)) { + } + if (TEST_MULTICAST == phase && CheckMessageContent(message, REQUEST)) { mResult = NS_OK; } else if (TEST_SEND_API != phase || !CheckMessageContent(message, RESPONSE)) { diff --git a/netwerk/url-classifier/AsyncUrlChannelClassifier.cpp b/netwerk/url-classifier/AsyncUrlChannelClassifier.cpp index e4b5904c36e4..9681cfcce22a 100644 --- a/netwerk/url-classifier/AsyncUrlChannelClassifier.cpp +++ b/netwerk/url-classifier/AsyncUrlChannelClassifier.cpp @@ -374,7 +374,7 @@ void FeatureData::DoLookup(nsUrlClassifierDBServiceWorker* aWorkerClassifier) { "%d [this=%p]", isBlocklisted, this)); - if (isBlocklisted == false) { + if (!isBlocklisted) { // If one of the blocklist table matches the URI, we don't need to continue // with the others: the feature is blocklisted (but maybe also // entitylisted). diff --git a/netwerk/url-classifier/UrlClassifierCommon.cpp b/netwerk/url-classifier/UrlClassifierCommon.cpp index ffae78460f42..0d386229220c 100644 --- a/netwerk/url-classifier/UrlClassifierCommon.cpp +++ b/netwerk/url-classifier/UrlClassifierCommon.cpp @@ -583,12 +583,8 @@ bool UrlClassifierCommon::IsTrackingClassificationFlag(uint32_t aFlag) { // static bool UrlClassifierCommon::IsSocialTrackingClassificationFlag(uint32_t aFlag) { - if (aFlag & nsIClassifiedChannel::ClassificationFlags:: - CLASSIFIED_ANY_SOCIAL_TRACKING) { - return true; - } - - return false; + return (aFlag & nsIClassifiedChannel::ClassificationFlags:: + CLASSIFIED_ANY_SOCIAL_TRACKING) != 0; } // static diff --git a/netwerk/url-classifier/UrlClassifierFeatureBase.cpp b/netwerk/url-classifier/UrlClassifierFeatureBase.cpp index 07da1fd07374..1bbc7a652486 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureBase.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureBase.cpp @@ -17,7 +17,7 @@ namespace net { namespace { void OnPrefsChange(const char* aPrefName, void* aArray) { - auto array = static_cast*>(aArray); + auto* array = static_cast*>(aArray); MOZ_ASSERT(array); nsAutoCString value; diff --git a/netwerk/url-classifier/UrlClassifierFeatureFactory.h b/netwerk/url-classifier/UrlClassifierFeatureFactory.h index ab5affa65639..a3b823ac4928 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureFactory.h +++ b/netwerk/url-classifier/UrlClassifierFeatureFactory.h @@ -30,7 +30,7 @@ class UrlClassifierFeatureFactory final { static nsIUrlClassifierFeature* GetFeatureLoginReputation(); static already_AddRefed GetFeatureByName( - const nsACString& aFeatureName); + const nsACString& aName); static void GetFeatureNames(nsTArray& aArray); diff --git a/netwerk/url-classifier/UrlClassifierFeatureFlash.h b/netwerk/url-classifier/UrlClassifierFeatureFlash.h index ac91f9c59b7d..57d0919729d8 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureFlash.h +++ b/netwerk/url-classifier/UrlClassifierFeatureFlash.h @@ -16,7 +16,7 @@ class UrlClassifierFeatureFlash final : public UrlClassifierFeatureBase { public: struct FlashFeature; - static void GetFeatureNames(nsTArray& aNames); + static void GetFeatureNames(nsTArray& aArray); static void MaybeShutdown(); diff --git a/netwerk/url-classifier/UrlClassifierFeaturePhishingProtection.h b/netwerk/url-classifier/UrlClassifierFeaturePhishingProtection.h index d7a7ab92111c..d5498cbb720c 100644 --- a/netwerk/url-classifier/UrlClassifierFeaturePhishingProtection.h +++ b/netwerk/url-classifier/UrlClassifierFeaturePhishingProtection.h @@ -17,7 +17,7 @@ class UrlClassifierFeaturePhishingProtection final public: struct PhishingProtectionFeature; - static void GetFeatureNames(nsTArray& aNames); + static void GetFeatureNames(nsTArray& aArray); static void MaybeShutdown(); diff --git a/netwerk/url-classifier/nsChannelClassifier.cpp b/netwerk/url-classifier/nsChannelClassifier.cpp index 067aed88f7ae..574485bff410 100644 --- a/netwerk/url-classifier/nsChannelClassifier.cpp +++ b/netwerk/url-classifier/nsChannelClassifier.cpp @@ -68,7 +68,7 @@ StaticAutoPtr CachedPrefs::sInstance; // static void CachedPrefs::OnPrefsChange(const char* aPref, void* aPrefs) { - auto prefs = static_cast(aPrefs); + auto* prefs = static_cast(aPrefs); if (!strcmp(aPref, URLCLASSIFIER_EXCEPTION_HOSTNAMES)) { nsCString exceptionHostnames; diff --git a/netwerk/wifi/nsWifiAccessPoint.h b/netwerk/wifi/nsWifiAccessPoint.h index 7c1bc8f9362a..93b57583c7b3 100644 --- a/netwerk/wifi/nsWifiAccessPoint.h +++ b/netwerk/wifi/nsWifiAccessPoint.h @@ -24,9 +24,9 @@ class nsWifiAccessPoint final : public nsIWifiAccessPoint { nsWifiAccessPoint(); - char mMac[18]; + char mMac[18]{}; int mSignal; - char mSsid[33]; + char mSsid[33]{}; int mSsidLen; void setSignal(int signal) { mSignal = signal; } diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index b886c3c318be..5d938c67201e 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -104,7 +104,7 @@ NS_IMETHODIMP nsWifiMonitor::StopWatching(nsIWifiListener* aListener) { return NS_OK; } -typedef nsTArray> WifiListenerArray; +using WifiListenerArray = nsTArray>; class nsPassErrorToWifiListeners final : public nsIRunnable { public: @@ -146,8 +146,9 @@ NS_IMETHODIMP nsWifiMonitor::Run() { if (mKeepGoing && NS_FAILED(rv)) { doError = true; currentListeners = MakeUnique(mListeners.Length()); - for (uint32_t i = 0; i < mListeners.Length(); i++) + for (uint32_t i = 0; i < mListeners.Length(); i++) { currentListeners->AppendElement(mListeners[i].mListener); + } } mThreadComplete = true; } @@ -187,7 +188,7 @@ NS_IMPL_ISUPPORTS(nsCallWifiListeners, nsIRunnable) NS_IMETHODIMP nsCallWifiListeners::Run() { LOG(("About to send data to the wifi listeners\n")); - for (auto& listener : mListeners) { + for (const auto& listener : mListeners) { listener->OnChange(mAccessPoints); } return NS_OK;