Bug 1714307 - Autofix static-analysis warnings in netwerk/ r=necko-reviewers,kershaw

Differential Revision: https://phabricator.services.mozilla.com/D116701
This commit is contained in:
Valentin Gosu 2021-06-04 12:35:16 +00:00
parent 048781b3b9
commit d595491cc7
201 changed files with 1462 additions and 1253 deletions

View File

@ -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) \

View File

@ -90,8 +90,9 @@ EventTokenBucket::EventTokenBucket(uint32_t eventsPerSecond, uint32_t burstSize)
nsresult rv;
nsCOMPtr<nsIEventTarget> sts;
nsCOMPtr<nsIIOService> 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();

View File

@ -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();

View File

@ -29,7 +29,7 @@ namespace net {
#define IO_ACTIVITY_ENABLED_PREF "io.activity.enabled"
typedef nsTHashMap<nsCStringHashKey, dom::IOActivityDataDictionary> Activities;
using Activities = nsTHashMap<nsCStringHashKey, dom::IOActivityDataDictionary>;
// IOActivityMonitor has several roles:
// - maintains an IOActivity per resource and updates it

View File

@ -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);

View File

@ -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);
}

View File

@ -48,7 +48,7 @@ nsresult LoadInfoArgsToLoadInfo(
namespace net {
typedef nsTArray<nsCOMPtr<nsIRedirectHistoryEntry>> RedirectHistoryArray;
using RedirectHistoryArray = nsTArray<nsCOMPtr<nsIRedirectHistoryEntry>>;
/**
* 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;

View File

@ -29,7 +29,7 @@ class MemoryDownloader final : public nsIStreamListener {
NS_DECL_NSIREQUESTOBSERVER
NS_DECL_NSISTREAMLISTENER
typedef mozilla::UniquePtr<FallibleTArray<uint8_t>> Data;
using Data = mozilla::UniquePtr<FallibleTArray<uint8_t>>;
class IObserver : public nsISupports {
public:

View File

@ -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() ||
return !(NS_FAILED(rv) || nat64PrefixPref.IsEmpty() ||
NS_FAILED(prefix->InitFromString(nat64PrefixPref)) ||
prefix->raw.family != PR_AF_INET6) {
return false;
}
return true;
prefix->raw.family != PR_AF_INET6);
}
static inline bool NAT64PrefixCompare(const NetAddr& prefix1,

View File

@ -18,7 +18,7 @@ static PRIOMethods* sNetworkDataCountLayerMethodsPtr = nullptr;
class NetworkDataCountSecret {
public:
NetworkDataCountSecret() {}
NetworkDataCountSecret() = default;
uint64_t mSentBytes = 0;
uint64_t mReceivedBytes = 0;

View File

@ -10,7 +10,7 @@
namespace mozilla {
namespace net {
typedef nsTHashMap<nsCStringHashKey, nsCString> AddrMapType;
using AddrMapType = nsTHashMap<nsCStringHashKey, nsCString>;
nsresult DoListAddresses(AddrMapType& aAddrMap);

View File

@ -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) {

View File

@ -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<Predictor::Action> 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<Telemetry::PREDICTOR_LEARN_ATTEMPTS> 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

View File

@ -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:

View File

@ -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<nsIDNSAddrRecord> 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);

View File

@ -61,7 +61,7 @@ class RequestContext final : public nsIRequestContext, public nsITimerCallback {
Atomic<uint32_t> mBlockingTransactionCount;
UniquePtr<SpdyPushCache> mSpdyCache;
typedef nsCOMPtr<nsIRequestTailUnblockCallback> PendingTailRequest;
using PendingTailRequest = nsCOMPtr<nsIRequestTailUnblockCallback>;
// Number of known opened non-tailed requets
uint32_t mNonTailRequests;
// Queue of requests that have been tailed, when conditions are met

View File

@ -73,7 +73,7 @@ class SSLTokensCache : public nsIMemoryReporter {
void Reset();
nsCString mKey;
PRUint32 mExpirationTime;
PRUint32 mExpirationTime = 0;
nsTArray<uint8_t> mToken;
SessionCacheInfo mSessionCacheInfo;
};

View File

@ -26,7 +26,7 @@ class SimpleBufferPage : public LinkedListElement<SimpleBufferPage> {
private:
friend class SimpleBuffer;
char mBuffer[kSimpleBufferPageSize];
char mBuffer[kSimpleBufferPageSize]{0};
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();

View File

@ -122,7 +122,8 @@ inline already_AddRefed<nsIChannel> NS_NewSimpleChannel(
using namespace mozilla;
auto callbacks = MakeUnique<net::SimpleChannelCallbacksImpl<F1, F2, T>>(
std::move(aStartAsyncRead), std::move(aOpenContentStream), context);
std::forward<F1>(aStartAsyncRead), std::forward<F2>(aOpenContentStream),
context);
return net::NS_NewSimpleChannelInternal(aURI, aLoadInfo,
std::move(callbacks));
@ -140,7 +141,7 @@ inline already_AddRefed<nsIChannel> NS_NewSimpleChannel(nsIURI* aURI,
};
return NS_NewSimpleChannel(aURI, aLoadInfo, context,
std::move(aStartAsyncRead),
std::forward<F1>(aStartAsyncRead),
std::move(openContentStream));
}

View File

@ -241,8 +241,9 @@ ThrottleQueue::ThrottleQueue()
nsresult rv;
nsCOMPtr<nsIEventTarget> sts;
nsCOMPtr<nsIIOService> 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<RefPtr<mozilla::net::ThrottleInputStream>>::NoIndex) {
mAsyncEvents.AppendElement(aStream);
if (!mTimerArmed) {

View File

@ -46,7 +46,7 @@ class ThrottleQueue : public nsIInputChannelThrottleQueue,
struct ThrottleEntry {
TimeStamp mTime;
uint32_t mBytesRead;
uint32_t mBytesRead = 0;
};
nsTArray<ThrottleEntry> mReadEvents;

View File

@ -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<nsIChannel*>(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

View File

@ -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; }

View File

@ -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

View File

@ -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,14 +882,16 @@ 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;
}

View File

@ -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<nsIFile> localFile;
int32_t ioFlags;
int32_t perm;
int32_t ioFlags = 0;
int32_t perm = 0;
};
/**

View File

@ -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,25 +1524,28 @@ 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);
}
}
}
}
}
MutexAutoLock lock(mMutex);
mRestrictedPortList.Assign(std::move(restrictedPortList));
@ -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);

View File

@ -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);

View File

@ -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,8 +529,9 @@ 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
// Content-Range: bytes 0-299999/25604694
@ -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;
}

View File

@ -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,18 +572,19 @@ uint32_t nsInputStreamPump::OnStateTransfer() {
NS_ERROR("OnDataAvailable implementation consumed no data");
mStatus = NS_ERROR_UNEXPECTED;
}
} else
} else {
mStreamOffset += odaAvail; // assume ODA behaved well
}
}
}
// an error returned from Available or OnDataAvailable should cause us to
// 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;

View File

@ -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.

View File

@ -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<nsIRequest*>* aArray) {
for (auto iter = aTable->Iter(); !iter.Done(); iter.Next()) {
auto e = static_cast<RequestMapEntry*>(iter.Get());
auto* e = static_cast<RequestMapEntry*>(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<RequestMapEntry*>(mRequests.Add(request, fallible));
auto* entry = static_cast<RequestMapEntry*>(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<RequestMapEntry*>(mRequests.Search(request));
auto* entry = static_cast<RequestMapEntry*>(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<RequestMapEntry*>(iter.Get());
auto* e = static_cast<RequestMapEntry*>(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<RequestMapEntry*>(iter.Get());
auto* e = static_cast<RequestMapEntry*>(iter.Get());
RescheduleRequest(e->mKey, aDelta);
}
}

View File

@ -68,8 +68,8 @@ class nsMIMEInputStream : public nsIMIMEInputStream,
struct MOZ_STACK_CLASS ReadSegmentsState {
nsCOMPtr<nsIInputStream> mThisStream;
nsWriteSegmentFun mWriter;
void* mClosure;
nsWriteSegmentFun mWriter{nullptr};
void* mClosure{nullptr};
};
static nsresult ReadSegCb(nsIInputStream* aIn, void* aClosure,
const char* aFromRawSegment, uint32_t aToOffset,

View File

@ -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")) {

View File

@ -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<nsIIDNService> 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<nsIProtocolProxyService> 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<nsIContentSniffer> ContentSnifferCache;
using ContentSnifferCache = nsCategoryCache<nsIContentSniffer>;
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 {

View File

@ -81,7 +81,7 @@ already_AddRefed<nsINetUtil> do_GetNetUtil(nsresult* error = nullptr);
// private little helper function... don't call this directly!
nsresult net_EnsureIOService(nsIIOService** ios, nsCOMPtr<nsIIOService>& 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,

View File

@ -327,10 +327,11 @@ void PendingPACQuery::Complete(nsresult status, const nsACString& pacString) {
if (!mCallback) return;
RefPtr<ExecuteCallback> 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<ExecuteCallback> 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;
}

View File

@ -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

View File

@ -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;

View File

@ -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<nsresult(nsAsyncResolveRequest*, nsIProxyInfo*, bool)>
Callback;
using Callback =
std::function<nsresult(nsAsyncResolveRequest*, nsIProxyInfo*, bool)>;
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<nsProxyInfo> pi = do_QueryInterface(aProxy);
@ -1699,7 +1719,7 @@ nsProtocolProxyService::GetFailoverForProxy(nsIProxyInfo* aProxy, nsIURI* aURI,
namespace { // anon
class ProxyFilterPositionComparator {
typedef RefPtr<nsProtocolProxyService::FilterLink> FilterLinkRef;
using FilterLinkRef = RefPtr<nsProtocolProxyService::FilterLink>;
public:
bool Equals(const FilterLinkRef& a, const FilterLinkRef& b) const {
@ -1711,7 +1731,7 @@ class ProxyFilterPositionComparator {
};
class ProxyFilterObjectComparator {
typedef RefPtr<nsProtocolProxyService::FilterLink> FilterLinkRef;
using FilterLinkRef = RefPtr<nsProtocolProxyService::FilterLink>;
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<nsIURI> 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,14 +2232,16 @@ 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) {
rv = NewProxyInfo_Internal(type, *host, port, ""_ns, ""_ns, ""_ns, ""_ns,
@ -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

View File

@ -25,7 +25,7 @@ class nsISystemProxySettings;
namespace mozilla {
namespace net {
typedef nsTHashMap<nsCStringHashKey, uint32_t> nsFailedProxyTable;
using nsFailedProxyTable = nsTHashMap<nsCStringHashKey, uint32_t>;
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<nsIProxyInfo> proxyInfo,
const nsProtocolInfo& info, nsCOMPtr<nsIProxyInfo> 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;
};

View File

@ -22,7 +22,7 @@ namespace net {
//-----------------------------------------------------------------------------
typedef void (nsServerSocket::*nsServerSocketFunc)(void);
using nsServerSocketFunc = void (nsServerSocket::*)();
static nsresult PostEvent(nsServerSocket* s, nsServerSocketFunc func) {
nsCOMPtr<nsIRunnable> 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<int32_t>(NetworkEndian::readUint16(&port));
return NS_OK;

View File

@ -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<nsIEventTarget> mListenerTarget;
bool mAttached;
bool mKeepWhenOffline;

View File

@ -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.

View File

@ -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,11 +436,12 @@ 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,11 +640,12 @@ 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<nsCString>& 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<nsISocketProvider> 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 = "<IP-to-string failed>"_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) {
} else if (PR_IS_CONNECTED_ERROR == code) {
//
// we are connected!
//
@ -1591,10 +1608,11 @@ 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<uint32_t>(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<uint32_t>(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;
}

View File

@ -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,13 +344,15 @@ 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]{0};
// linger options to use when closing
bool mLingerPolarity;
@ -402,32 +404,36 @@ 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
void TraceInBuf(const char* buf, int32_t n);

View File

@ -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,11 +1327,12 @@ nsresult nsSocketTransportService::DoPollIteration(TimeDuration* pollDuration) {
static_cast<uint32_t>(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]);
}
}
{
MutexAutoLock lock(mLock);
@ -1404,9 +1409,10 @@ 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]);
}
}
{
MutexAutoLock lock(mLock);
@ -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<SocketInfo>* 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<SocketInfo>* data,
void nsSocketTransportService::GetSocketConnections(
nsTArray<SocketInfo>* 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() {

View File

@ -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<Tuple<uint16_t, uint16_t, uint16_t>> TPortRemapping;
using TPortRemapping = CopyableTArray<Tuple<uint16_t, uint16_t, uint16_t>>;
Maybe<TPortRemapping> mPortRemapping;
// Called on the socket thread to apply the mapping build on the main thread

View File

@ -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) {

View File

@ -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);

View File

@ -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,9 +176,10 @@ 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;
}

View File

@ -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);
}

View File

@ -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,11 +228,12 @@ 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 ? */
for (; (*fwdPtr != '\0') && (*fwdPtr != '?') && (*fwdPtr != '#'); ++fwdPtr) {
@ -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--)
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<uint8_t>(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<decltype(end)>(end),
std::reverse_iterator<decltype(newStart)>(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<uint8_t>(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<decltype(end)>(end),
std::reverse_iterator<decltype(newStart)>(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);

View File

@ -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

View File

@ -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;

View File

@ -39,7 +39,7 @@ NS_IMPL_ISUPPORTS(nsNoAuthURLParser, nsIURLParser)
#define OFFSET_RESULT(component, offset) \
PR_BEGIN_MACRO \
if (component##Pos) *component##Pos += offset; \
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 = <directory><filename>.<extension>
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,10 +556,11 @@ nsAuthURLParser::ParseServerInfo(const char* serverinfo, int32_t serverinfoLen,
nsresult err;
*port = buf.ToInteger(&err);
if (NS_FAILED(err) || *port < 0 ||
*port > std::numeric_limits<uint16_t>::max())
*port > std::numeric_limits<uint16_t>::max()) {
return NS_ERROR_MALFORMED_URI;
}
}
}
} else {
// serverinfo = <hostname>
SET_RESULT(hostname, 0, serverinfoLen);
@ -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;
}

View File

@ -33,14 +33,14 @@
using namespace mozilla;
typedef nsCategoryCache<nsIContentSniffer> ContentSnifferCache;
using ContentSnifferCache = nsCategoryCache<nsIContentSniffer>;
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

View File

@ -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;
}

View File

@ -47,7 +47,7 @@ class nsDeleteDir {
/**
* Returns the trash directory corresponding to the given directory.
*/
static nsresult GetTrashDir(nsIFile* dir, nsCOMPtr<nsIFile>* result);
static nsresult GetTrashDir(nsIFile* target, nsCOMPtr<nsIFile>* result);
/**
* Remove all trashes left from previous run. This function does nothing when

View File

@ -30,8 +30,7 @@
#include <math.h>
#include <algorithm>
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

View File

@ -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();

View File

@ -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<uint32_t>(aStatus)));
DebugOnly<bool> found;
DebugOnly<bool> 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

View File

@ -10,8 +10,7 @@
#include "mozilla/IntegerPrintfMacros.h"
namespace mozilla {
namespace net {
namespace mozilla::net {
#define kMinBufSize 512
@ -836,5 +835,4 @@ mozilla::Atomic<uint32_t, ReleaseAcquire>& CacheFileChunk::ChunksMemoryUsage()
return mIsPriority ? prioChunksMemoryUsage : chunksMemoryUsage;
}
} // namespace net
} // namespace mozilla
} // namespace mozilla::net

View File

@ -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);

View File

@ -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

View File

@ -20,9 +20,9 @@ class CacheIndexIterator;
struct CacheFileContextEvictorEntry {
nsCOMPtr<nsILoadContextInfo> mInfo;
bool mPinned;
bool mPinned = false;
nsString mOrigin; // it can be empty
PRTime mTimeStamp; // in milliseconds
PRTime mTimeStamp = 0; // in milliseconds
RefPtr<CacheIndexIterator> mIterator;
};

View File

@ -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<bool> found;
DebugOnly<bool> found{};
found = mHandles.RemoveElement(aHandle);
MOZ_ASSERT(found);
}
@ -287,7 +282,7 @@ CacheFileHandles::HandleHashKey::GetNewestHandle() {
}
void CacheFileHandles::HandleHashKey::GetHandles(
nsTArray<RefPtr<CacheFileHandle> >& aResult) {
nsTArray<RefPtr<CacheFileHandle>>& 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<RefPtr<CacheFileHandle> >* _retval) {
nsTArray<RefPtr<CacheFileHandle>>* _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<RefPtr<CacheFileHandle> >* _retval) {
nsTArray<RefPtr<CacheFileHandle>>* _retval) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) {
RefPtr<CacheFileHandle> 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<RefPtr<CacheFileHandle> > array;
nsTArray<RefPtr<CacheFileHandle>> 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<CacheFileIOListener> mCallback;
RefPtr<CacheFileIOManager> mIOMan;
@ -850,7 +845,7 @@ class DoomFileByKeyEvent : public Runnable {
}
protected:
SHA1Sum::Hash mHash;
SHA1Sum::Hash mHash{};
nsCOMPtr<CacheFileIOListener> mCallback;
RefPtr<CacheFileIOManager> mIOMan;
};
@ -1209,7 +1204,7 @@ void CacheFileIOManager::ShutdownInternal() {
}
// close all handles and delete all associated files
nsTArray<RefPtr<CacheFileHandle> > handles;
nsTArray<RefPtr<CacheFileHandle>> handles;
mHandles.GetAllHandles(&handles);
handles.AppendElements(mSpecialHandles);
@ -1422,7 +1417,7 @@ nsresult CacheFileIOManager::ScheduleMetadataWriteInternal(CacheFile* aFile) {
}
if (mScheduledMetadataWrites.IndexOf(aFile) !=
mScheduledMetadataWrites.NoIndex) {
nsTArray<RefPtr<mozilla::net::CacheFile>>::NoIndex) {
return NS_OK;
}
@ -1471,7 +1466,7 @@ nsresult CacheFileIOManager::ShutdownMetadataWriteScheduling() {
void CacheFileIOManager::ShutdownMetadataWriteSchedulingInternal() {
MOZ_ASSERT(IsOnIOThreadOrCeased());
nsTArray<RefPtr<CacheFile> > files = std::move(mScheduledMetadataWrites);
nsTArray<RefPtr<CacheFile>> 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<RefPtr<CacheFile> > files = std::move(mScheduledMetadataWrites);
nsTArray<RefPtr<CacheFile>> 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<bool> found;
DebugOnly<bool> found{};
found = mHandlesByLastUsed.RemoveElement(aHandle);
MOZ_ASSERT(found);
}
@ -2965,7 +2960,7 @@ nsresult CacheFileIOManager::EvictAllInternal() {
}
// Doom all active handles
nsTArray<RefPtr<CacheFileHandle> > handles;
nsTArray<RefPtr<CacheFileHandle>> 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<RefPtr<CacheFileHandle> > handles;
nsTArray<RefPtr<CacheFileHandle>> 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<bool> found;
DebugOnly<bool> 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

View File

@ -139,7 +139,7 @@ class CacheFileHandles {
already_AddRefed<CacheFileHandle> NewHandle(const SHA1Sum::Hash*,
bool aPriority,
CacheFileHandle::PinningStatus);
void RemoveHandle(CacheFileHandle* aHandlle);
void RemoveHandle(CacheFileHandle* aHandle);
void GetAllHandles(nsTArray<RefPtr<CacheFileHandle> >* _retval);
void GetActiveHandles(nsTArray<RefPtr<CacheFileHandle> >* _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);

View File

@ -10,8 +10,7 @@
#include "nsThreadUtils.h"
#include <algorithm>
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

View File

@ -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<nsresult> rv;
DebugOnly<nsresult> 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<nsresult> rv;
DebugOnly<nsresult> 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

View File

@ -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;

View File

@ -12,8 +12,7 @@
#include "mozilla/DebugOnly.h"
#include <algorithm>
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

View File

@ -14,9 +14,7 @@
#include <algorithm>
#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

View File

@ -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,

View File

@ -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

View File

@ -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);

View File

@ -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<nsIRunnable> 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

View File

@ -36,7 +36,7 @@ class CacheIOThread final : public nsIThreadObserver {
CacheIOThread();
typedef nsTArray<nsCOMPtr<nsIRunnable>> EventQueue;
using EventQueue = nsTArray<nsCOMPtr<nsIRunnable>>;
enum ELevel : uint32_t {
OPEN_PRIORITY,

View File

@ -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

View File

@ -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() &&
return !aInfo->IsPrivate() &&
GetOriginAttrsHash(*aInfo->OriginAttributesPtr()) ==
aRec->Get()->mOriginAttrsHash &&
aInfo->IsAnonymous() == !!(aRec->Get()->mFlags & kAnonymousMask)) {
return true;
}
return false;
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]{0};
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]{0};
#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,

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -18,8 +18,7 @@
#include <time.h>
#include <math.h>
namespace mozilla {
namespace net {
namespace mozilla::net {
StaticRefPtr<CacheObserver> 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<CacheStorageService> 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

View File

@ -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<nsCStringHashKey, CacheEntry> TCacheEntryTable;
using TCacheEntryTable = nsRefPtrHashtable<nsCStringHashKey, CacheEntry>;
class CacheEntryTable : public TCacheEntryTable {
public:
enum EType { MEMORY_ONLY, ALL_ENTRIES };

View File

@ -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<nsCStringHashKey, CacheEntryTable> GlobalEntryTables;
using GlobalEntryTables = nsClassHashtable<nsCStringHashKey, CacheEntryTable>;
/**
* Keeps tables of entries. There is one entries table for each distinct load
@ -316,9 +315,10 @@ class WalkMemoryCacheRunnable : public WalkCacheRunnable {
}
virtual ~WalkMemoryCacheRunnable() {
if (mCallback)
if (mCallback) {
ProxyReleaseMainThread("WalkMemoryCacheRunnable::mCallback", mCallback);
}
}
virtual void OnEntryInfo(const nsACString& aURISpec,
const nsACString& aIdEnhance, int64_t aDataSize,
@ -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

View File

@ -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.

View File

@ -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

View File

@ -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<nsICookie> xpcCookie = do_QueryInterface(aSubject);
MOZ_ASSERT(xpcCookie);
auto cookie = static_cast<Cookie*>(xpcCookie.get());
auto* cookie = static_cast<Cookie*>(xpcCookie.get());
if (!cookie->IsSession() && !aOldCookieIsSession) {
return;
}

View File

@ -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 <value>
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);

View File

@ -40,7 +40,7 @@ void CookieServiceParent::RemoveBatchDeletedCookies(nsIArray* aCookieList) {
nsTArray<OriginAttributes> attrsList;
for (uint32_t i = 0; i < len; i++) {
nsCOMPtr<nsICookie> xpcCookie = do_QueryElementAt(aCookieList, i);
auto cookie = static_cast<Cookie*>(xpcCookie.get());
auto* cookie = static_cast<Cookie*>(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<Cookie*>(aCookie);
auto* cookie = static_cast<Cookie*>(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<Cookie*>(aCookie);
auto* cookie = static_cast<Cookie*>(aCookie);
const OriginAttributes& attrs = cookie->OriginAttributesRef();
CookieStruct cookieStruct = cookie->ToIPC();
if (cookie->IsHttpOnly()) {

View File

@ -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> 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);

View File

@ -27,8 +27,8 @@ class Cookie;
class CookieEntry : public CookieKey {
public:
// Hash methods
typedef nsTArray<RefPtr<Cookie>> ArrayType;
typedef ArrayType::index_type IndexType;
using ArrayType = nsTArray<RefPtr<Cookie>>;
using IndexType = ArrayType::index_type;
explicit CookieEntry(KeyTypePointer aKey) : CookieKey(aKey) {}

View File

@ -59,7 +59,7 @@ struct StreamFilterRequest {
}
}
RefPtr<ChildEndpointPromise::Private> mPromise;
base::ProcessId mChildProcessId;
base::ProcessId mChildProcessId = 0;
mozilla::ipc::Endpoint<extensions::PStreamFilterChild> mChildEndpoint;
};
} // namespace net
@ -119,9 +119,8 @@ class DocumentLoadListener : public nsIInterfaceRequestor,
bool mSwitchedProcess = false;
};
typedef MozPromise<OpenPromiseSucceededType, OpenPromiseFailedType,
true /* isExclusive */>
OpenPromise;
using OpenPromise =
MozPromise<OpenPromiseSucceededType, OpenPromiseFailedType, true>;
// Interface which may be provided when performing an <object> or <embed> load
// with `DocumentLoadListener`, to allow upgrading the Object load to a proper
@ -169,7 +168,7 @@ class DocumentLoadListener : public nsIInterfaceRequestor,
nsDOMNavigationTiming* aTiming, Maybe<dom::ClientInfo>&& 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<ReportSecurityMessageParams,
LogBlockedCORSRequestParams,
LogMimeTypeMismatchParams>
SecurityWarningFunction;
using SecurityWarningFunction =
mozilla::Variant<ReportSecurityMessageParams, LogBlockedCORSRequestParams,
LogMimeTypeMismatchParams>;
nsTArray<SecurityWarningFunction> mSecurityWarningFunctions;
struct OnStartRequestParams {
@ -454,9 +451,9 @@ class DocumentLoadListener : public nsIInterfaceRequestor,
struct OnAfterLastPartParams {
nsresult status;
};
typedef mozilla::Variant<OnStartRequestParams, OnDataAvailableParams,
OnStopRequestParams, OnAfterLastPartParams>
StreamListenerFunction;
using StreamListenerFunction =
mozilla::Variant<OnStartRequestParams, OnDataAvailableParams,
OnStopRequestParams, OnAfterLastPartParams>;
// 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

View File

@ -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);
}

View File

@ -23,8 +23,8 @@ class SocketProcessBridgeChild final : public PSocketProcessBridgeChild,
NS_DECL_NSIOBSERVER
static already_AddRefed<SocketProcessBridgeChild> GetSingleton();
typedef MozPromise<RefPtr<SocketProcessBridgeChild>, nsCString, false>
GetPromise;
using GetPromise =
MozPromise<RefPtr<SocketProcessBridgeChild>, nsCString, false>;
static RefPtr<GetPromise> GetSocketProcessBridge();
mozilla::ipc::IPCResult RecvTest();

View File

@ -148,11 +148,7 @@ bool SocketProcessChild::Init(base::ProcessId aParentPid,
// Initialize DNS Service here, since it needs to be done in main thread.
nsCOMPtr<nsIDNSService> 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) {

View File

@ -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);

View File

@ -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;

View File

@ -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,11 +517,12 @@ 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.
if (*valueEnd) str++;
@ -684,16 +691,18 @@ 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) {
// prefer simple 5987 format over 2231 with continuations
@ -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,12 +1098,13 @@ 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));
}
}
}
}
nsresult DecodeQOrBase64Str(const char* aEncoded, size_t aLen, char aQOrBase64,
@ -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 {

Some files were not shown because too many files have changed in this diff Show More