michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "pk11pub.h" michael@0: #include "prlog.h" michael@0: #include "ScopedNSSTypes.h" michael@0: #include "secoidt.h" michael@0: michael@0: #include "nsIAsyncInputStream.h" michael@0: #include "nsIFile.h" michael@0: #include "nsIMutableArray.h" michael@0: #include "nsIPipe.h" michael@0: #include "nsIX509Cert.h" michael@0: #include "nsIX509CertDB.h" michael@0: #include "nsIX509CertList.h" michael@0: #include "nsCOMArray.h" michael@0: #include "nsNetUtil.h" michael@0: #include "nsThreadUtils.h" michael@0: michael@0: #include "BackgroundFileSaver.h" michael@0: #include "mozilla/Telemetry.h" michael@0: michael@0: #ifdef XP_WIN michael@0: #include michael@0: #include michael@0: #include michael@0: #endif // XP_WIN michael@0: michael@0: namespace mozilla { michael@0: namespace net { michael@0: michael@0: // NSPR_LOG_MODULES=BackgroundFileSaver:5 michael@0: #if defined(PR_LOGGING) michael@0: PRLogModuleInfo *BackgroundFileSaver::prlog = nullptr; michael@0: #define LOG(args) PR_LOG(BackgroundFileSaver::prlog, PR_LOG_DEBUG, args) michael@0: #define LOG_ENABLED() PR_LOG_TEST(BackgroundFileSaver::prlog, 4) michael@0: #else michael@0: #define LOG(args) michael@0: #define LOG_ENABLED() (false) michael@0: #endif michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// Globals michael@0: michael@0: /** michael@0: * Buffer size for writing to the output file or reading from the input file. michael@0: */ michael@0: #define BUFFERED_IO_SIZE (1024 * 32) michael@0: michael@0: /** michael@0: * When this upper limit is reached, the original request is suspended. michael@0: */ michael@0: #define REQUEST_SUSPEND_AT (1024 * 1024 * 4) michael@0: michael@0: /** michael@0: * When this lower limit is reached, the original request is resumed. michael@0: */ michael@0: #define REQUEST_RESUME_AT (1024 * 1024 * 2) michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// NotifyTargetChangeRunnable michael@0: michael@0: /** michael@0: * Runnable object used to notify the control thread that file contents will now michael@0: * be saved to the specified file. michael@0: */ michael@0: class NotifyTargetChangeRunnable MOZ_FINAL : public nsRunnable michael@0: { michael@0: public: michael@0: NotifyTargetChangeRunnable(BackgroundFileSaver *aSaver, nsIFile *aTarget) michael@0: : mSaver(aSaver) michael@0: , mTarget(aTarget) michael@0: { michael@0: } michael@0: michael@0: NS_IMETHODIMP Run() michael@0: { michael@0: return mSaver->NotifyTargetChange(mTarget); michael@0: } michael@0: michael@0: private: michael@0: nsRefPtr mSaver; michael@0: nsCOMPtr mTarget; michael@0: }; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// BackgroundFileSaver michael@0: michael@0: uint32_t BackgroundFileSaver::sThreadCount = 0; michael@0: uint32_t BackgroundFileSaver::sTelemetryMaxThreadCount = 0; michael@0: michael@0: BackgroundFileSaver::BackgroundFileSaver() michael@0: : mControlThread(nullptr) michael@0: , mWorkerThread(nullptr) michael@0: , mPipeOutputStream(nullptr) michael@0: , mPipeInputStream(nullptr) michael@0: , mObserver(nullptr) michael@0: , mLock("BackgroundFileSaver.mLock") michael@0: , mWorkerThreadAttentionRequested(false) michael@0: , mFinishRequested(false) michael@0: , mComplete(false) michael@0: , mStatus(NS_OK) michael@0: , mAppend(false) michael@0: , mInitialTarget(nullptr) michael@0: , mInitialTargetKeepPartial(false) michael@0: , mRenamedTarget(nullptr) michael@0: , mRenamedTargetKeepPartial(false) michael@0: , mAsyncCopyContext(nullptr) michael@0: , mSha256Enabled(false) michael@0: , mSignatureInfoEnabled(false) michael@0: , mActualTarget(nullptr) michael@0: , mActualTargetKeepPartial(false) michael@0: , mDigestContext(nullptr) michael@0: { michael@0: #if defined(PR_LOGGING) michael@0: if (!prlog) michael@0: prlog = PR_NewLogModule("BackgroundFileSaver"); michael@0: #endif michael@0: LOG(("Created BackgroundFileSaver [this = %p]", this)); michael@0: } michael@0: michael@0: BackgroundFileSaver::~BackgroundFileSaver() michael@0: { michael@0: LOG(("Destroying BackgroundFileSaver [this = %p]", this)); michael@0: nsNSSShutDownPreventionLock lock; michael@0: if (isAlreadyShutDown()) { michael@0: return; michael@0: } michael@0: destructorSafeDestroyNSSReference(); michael@0: shutdown(calledFromObject); michael@0: } michael@0: michael@0: void michael@0: BackgroundFileSaver::destructorSafeDestroyNSSReference() michael@0: { michael@0: if (mDigestContext) { michael@0: mozilla::psm::PK11_DestroyContext_true(mDigestContext.forget()); michael@0: mDigestContext = nullptr; michael@0: } michael@0: } michael@0: michael@0: void michael@0: BackgroundFileSaver::virtualDestroyNSSReference() michael@0: { michael@0: destructorSafeDestroyNSSReference(); michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: nsresult michael@0: BackgroundFileSaver::Init() michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread"); michael@0: michael@0: nsresult rv; michael@0: michael@0: rv = NS_NewPipe2(getter_AddRefs(mPipeInputStream), michael@0: getter_AddRefs(mPipeOutputStream), true, true, 0, michael@0: HasInfiniteBuffer() ? UINT32_MAX : 0); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: rv = NS_GetCurrentThread(getter_AddRefs(mControlThread)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: rv = NS_NewThread(getter_AddRefs(mWorkerThread)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: sThreadCount++; michael@0: if (sThreadCount > sTelemetryMaxThreadCount) { michael@0: sTelemetryMaxThreadCount = sThreadCount; michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::GetObserver(nsIBackgroundFileSaverObserver **aObserver) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aObserver); michael@0: *aObserver = mObserver; michael@0: NS_IF_ADDREF(*aObserver); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::SetObserver(nsIBackgroundFileSaverObserver *aObserver) michael@0: { michael@0: mObserver = aObserver; michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::EnableAppend() michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread"); michael@0: michael@0: MutexAutoLock lock(mLock); michael@0: mAppend = true; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::SetTarget(nsIFile *aTarget, bool aKeepPartial) michael@0: { michael@0: NS_ENSURE_ARG(aTarget); michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: if (!mInitialTarget) { michael@0: aTarget->Clone(getter_AddRefs(mInitialTarget)); michael@0: mInitialTargetKeepPartial = aKeepPartial; michael@0: } else { michael@0: aTarget->Clone(getter_AddRefs(mRenamedTarget)); michael@0: mRenamedTargetKeepPartial = aKeepPartial; michael@0: } michael@0: } michael@0: michael@0: // After the worker thread wakes up because attention is requested, it will michael@0: // rename or create the target file as requested, and start copying data. michael@0: return GetWorkerThreadAttention(true); michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::Finish(nsresult aStatus) michael@0: { michael@0: nsresult rv; michael@0: michael@0: // This will cause the NS_AsyncCopy operation, if it's in progress, to consume michael@0: // all the data that is still in the pipe, and then finish. michael@0: rv = mPipeOutputStream->Close(); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // Ensure that, when we get attention from the worker thread, if no pending michael@0: // rename operation is waiting, the operation will complete. michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: mFinishRequested = true; michael@0: if (NS_SUCCEEDED(mStatus)) { michael@0: mStatus = aStatus; michael@0: } michael@0: } michael@0: michael@0: // After the worker thread wakes up because attention is requested, it will michael@0: // process the completion conditions, detect that completion is requested, and michael@0: // notify the main thread of the completion. If this function was called with michael@0: // a success code, we wait for the copy to finish before processing the michael@0: // completion conditions, otherwise we interrupt the copy immediately. michael@0: return GetWorkerThreadAttention(NS_FAILED(aStatus)); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::EnableSha256() michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), michael@0: "Can't enable sha256 or initialize NSS off the main thread"); michael@0: // Ensure Personal Security Manager is initialized. This is required for michael@0: // PK11_* operations to work. michael@0: nsresult rv; michael@0: nsCOMPtr nssDummy = do_GetService("@mozilla.org/psm;1", &rv); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: mSha256Enabled = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::GetSha256Hash(nsACString& aHash) michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), "Can't inspect sha256 off the main thread"); michael@0: // We acquire a lock because mSha256 is written on the worker thread. michael@0: MutexAutoLock lock(mLock); michael@0: if (mSha256.IsEmpty()) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: aHash = mSha256; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::EnableSignatureInfo() michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), michael@0: "Can't enable signature extraction off the main thread"); michael@0: // Ensure Personal Security Manager is initialized. michael@0: nsresult rv; michael@0: nsCOMPtr nssDummy = do_GetService("@mozilla.org/psm;1", &rv); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: mSignatureInfoEnabled = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaver::GetSignatureInfo(nsIArray** aSignatureInfo) michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), "Can't inspect signature off the main thread"); michael@0: // We acquire a lock because mSignatureInfo is written on the worker thread. michael@0: MutexAutoLock lock(mLock); michael@0: if (!mComplete || !mSignatureInfoEnabled) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: nsCOMPtr sigArray = do_CreateInstance(NS_ARRAY_CONTRACTID); michael@0: for (int i = 0; i < mSignatureInfo.Count(); ++i) { michael@0: sigArray->AppendElement(mSignatureInfo[i], false); michael@0: } michael@0: *aSignatureInfo = sigArray; michael@0: NS_IF_ADDREF(*aSignatureInfo); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: nsresult michael@0: BackgroundFileSaver::GetWorkerThreadAttention(bool aShouldInterruptCopy) michael@0: { michael@0: nsresult rv; michael@0: michael@0: MutexAutoLock lock(mLock); michael@0: michael@0: // We only require attention one time. If this function is called two times michael@0: // before the worker thread wakes up, and the first has aShouldInterruptCopy michael@0: // false and the second true, we won't forcibly interrupt the copy from the michael@0: // control thread. However, that never happens, because calling Finish with a michael@0: // success code is the only case that may result in aShouldInterruptCopy being michael@0: // false. In that case, we won't call this function again, because consumers michael@0: // should not invoke other methods on the control thread after calling Finish. michael@0: // And in any case, Finish already closes one end of the pipe, causing the michael@0: // copy to finish properly on its own. michael@0: if (mWorkerThreadAttentionRequested) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: if (!mAsyncCopyContext) { michael@0: // Copy is not in progress, post an event to handle the change manually. michael@0: nsCOMPtr event = michael@0: NS_NewRunnableMethod(this, &BackgroundFileSaver::ProcessAttention); michael@0: NS_ENSURE_TRUE(event, NS_ERROR_FAILURE); michael@0: michael@0: rv = mWorkerThread->Dispatch(event, NS_DISPATCH_NORMAL); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } else if (aShouldInterruptCopy) { michael@0: // Interrupt the copy. The copy will be resumed, if needed, by the michael@0: // ProcessAttention function, invoked by the AsyncCopyCallback function. michael@0: NS_CancelAsyncCopy(mAsyncCopyContext, NS_ERROR_ABORT); michael@0: } michael@0: michael@0: // Indicate that attention has been requested successfully, there is no need michael@0: // to post another event until the worker thread processes the current one. michael@0: mWorkerThreadAttentionRequested = true; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the worker thread. michael@0: // static michael@0: void michael@0: BackgroundFileSaver::AsyncCopyCallback(void *aClosure, nsresult aStatus) michael@0: { michael@0: BackgroundFileSaver *self = (BackgroundFileSaver *)aClosure; michael@0: { michael@0: MutexAutoLock lock(self->mLock); michael@0: michael@0: // Now that the copy was interrupted or terminated, any notification from michael@0: // the control thread requires an event to be posted to the worker thread. michael@0: self->mAsyncCopyContext = nullptr; michael@0: michael@0: // When detecting failures, ignore the status code we use to interrupt. michael@0: if (NS_FAILED(aStatus) && aStatus != NS_ERROR_ABORT && michael@0: NS_SUCCEEDED(self->mStatus)) { michael@0: self->mStatus = aStatus; michael@0: } michael@0: } michael@0: michael@0: (void)self->ProcessAttention(); michael@0: michael@0: // We called NS_ADDREF_THIS when NS_AsyncCopy started, to keep the object michael@0: // alive even if other references disappeared. At this point, we've finished michael@0: // using the object and can safely release our reference. michael@0: NS_RELEASE(self); michael@0: } michael@0: michael@0: // Called on the worker thread. michael@0: nsresult michael@0: BackgroundFileSaver::ProcessAttention() michael@0: { michael@0: nsresult rv; michael@0: michael@0: // This function is called whenever the attention of the worker thread has michael@0: // been requested. This may happen in these cases: michael@0: // * We are about to start the copy for the first time. In this case, we are michael@0: // called from an event posted on the worker thread from the control thread michael@0: // by GetWorkerThreadAttention, and mAsyncCopyContext is null. michael@0: // * We have interrupted the copy for some reason. In this case, we are michael@0: // called by AsyncCopyCallback, and mAsyncCopyContext is null. michael@0: // * We are currently executing ProcessStateChange, and attention is requested michael@0: // by the control thread, for example because SetTarget or Finish have been michael@0: // called. In this case, we are called from from an event posted through michael@0: // GetWorkerThreadAttention. While mAsyncCopyContext was always null when michael@0: // the event was posted, at this point mAsyncCopyContext may not be null michael@0: // anymore, because ProcessStateChange may have started the copy before the michael@0: // event that called this function was processed on the worker thread. michael@0: // If mAsyncCopyContext is not null, we interrupt the copy and re-enter michael@0: // through AsyncCopyCallback. This allows us to check if, for instance, we michael@0: // should rename the target file. We will then restart the copy if needed. michael@0: if (mAsyncCopyContext) { michael@0: NS_CancelAsyncCopy(mAsyncCopyContext, NS_ERROR_ABORT); michael@0: return NS_OK; michael@0: } michael@0: // Use the current shared state to determine the next operation to execute. michael@0: rv = ProcessStateChange(); michael@0: if (NS_FAILED(rv)) { michael@0: // If something failed while processing, terminate the operation now. michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: michael@0: if (NS_SUCCEEDED(mStatus)) { michael@0: mStatus = rv; michael@0: } michael@0: } michael@0: // Ensure we notify completion now that the operation failed. michael@0: CheckCompletion(); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the worker thread. michael@0: nsresult michael@0: BackgroundFileSaver::ProcessStateChange() michael@0: { michael@0: nsresult rv; michael@0: michael@0: // We might have been notified because the operation is complete, verify. michael@0: if (CheckCompletion()) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Get a copy of the current shared state for the worker thread. michael@0: nsCOMPtr initialTarget; michael@0: bool initialTargetKeepPartial; michael@0: nsCOMPtr renamedTarget; michael@0: bool renamedTargetKeepPartial; michael@0: bool sha256Enabled; michael@0: bool append; michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: michael@0: initialTarget = mInitialTarget; michael@0: initialTargetKeepPartial = mInitialTargetKeepPartial; michael@0: renamedTarget = mRenamedTarget; michael@0: renamedTargetKeepPartial = mRenamedTargetKeepPartial; michael@0: sha256Enabled = mSha256Enabled; michael@0: append = mAppend; michael@0: michael@0: // From now on, another attention event needs to be posted if state changes. michael@0: mWorkerThreadAttentionRequested = false; michael@0: } michael@0: michael@0: // The initial target can only be null if it has never been assigned. In this michael@0: // case, there is nothing to do since we never created any output file. michael@0: if (!initialTarget) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Determine if we are processing the attention request for the first time. michael@0: bool isContinuation = !!mActualTarget; michael@0: if (!isContinuation) { michael@0: // Assign the target file for the first time. michael@0: mActualTarget = initialTarget; michael@0: mActualTargetKeepPartial = initialTargetKeepPartial; michael@0: } michael@0: michael@0: // Verify whether we have actually been instructed to use a different file. michael@0: // This may happen the first time this function is executed, if SetTarget was michael@0: // called two times before the worker thread processed the attention request. michael@0: bool equalToCurrent = false; michael@0: if (renamedTarget) { michael@0: rv = mActualTarget->Equals(renamedTarget, &equalToCurrent); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: if (!equalToCurrent) michael@0: { michael@0: // If we were asked to rename the file but the initial file did not exist, michael@0: // we simply create the file in the renamed location. We avoid this check michael@0: // if we have already started writing the output file ourselves. michael@0: bool exists = true; michael@0: if (!isContinuation) { michael@0: rv = mActualTarget->Exists(&exists); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: if (exists) { michael@0: // We are moving the previous target file to a different location. michael@0: nsCOMPtr renamedTargetParentDir; michael@0: rv = renamedTarget->GetParent(getter_AddRefs(renamedTargetParentDir)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: nsAutoString renamedTargetName; michael@0: rv = renamedTarget->GetLeafName(renamedTargetName); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // We must delete any existing target file before moving the current michael@0: // one. michael@0: rv = renamedTarget->Exists(&exists); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: if (exists) { michael@0: rv = renamedTarget->Remove(false); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: // Move the file. If this fails, we still reference the original file michael@0: // in mActualTarget, so that it is deleted if requested. If this michael@0: // succeeds, the nsIFile instance referenced by mActualTarget mutates michael@0: // and starts pointing to the new file, but we'll discard the reference. michael@0: rv = mActualTarget->MoveTo(renamedTargetParentDir, renamedTargetName); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: // Now we can update the actual target file name. michael@0: mActualTarget = renamedTarget; michael@0: mActualTargetKeepPartial = renamedTargetKeepPartial; michael@0: } michael@0: } michael@0: michael@0: // Notify if the target file name actually changed. michael@0: if (!equalToCurrent) { michael@0: // We must clone the nsIFile instance because mActualTarget is not michael@0: // immutable, it may change if the target is renamed later. michael@0: nsCOMPtr actualTargetToNotify; michael@0: rv = mActualTarget->Clone(getter_AddRefs(actualTargetToNotify)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: nsRefPtr event = michael@0: new NotifyTargetChangeRunnable(this, actualTargetToNotify); michael@0: NS_ENSURE_TRUE(event, NS_ERROR_FAILURE); michael@0: michael@0: rv = mControlThread->Dispatch(event, NS_DISPATCH_NORMAL); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: if (isContinuation) { michael@0: // The pending rename operation might be the last task before finishing. We michael@0: // may return here only if we have already created the target file. michael@0: if (CheckCompletion()) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Even if the operation did not complete, the pipe input stream may be michael@0: // empty and may have been closed already. We detect this case using the michael@0: // Available property, because it never returns an error if there is more michael@0: // data to be consumed. If the pipe input stream is closed, we just exit michael@0: // and wait for more calls like SetTarget or Finish to be invoked on the michael@0: // control thread. However, we still truncate the file or create the michael@0: // initial digest context if we are expected to do that. michael@0: uint64_t available; michael@0: rv = mPipeInputStream->Available(&available); michael@0: if (NS_FAILED(rv)) { michael@0: return NS_OK; michael@0: } michael@0: } michael@0: michael@0: // Create the digest context if requested and NSS hasn't been shut down. michael@0: if (sha256Enabled && !mDigestContext) { michael@0: nsNSSShutDownPreventionLock lock; michael@0: if (!isAlreadyShutDown()) { michael@0: mDigestContext = michael@0: PK11_CreateDigestContext(static_cast(SEC_OID_SHA256)); michael@0: NS_ENSURE_TRUE(mDigestContext, NS_ERROR_OUT_OF_MEMORY); michael@0: } michael@0: } michael@0: michael@0: // When we are requested to append to an existing file, we should read the michael@0: // existing data and ensure we include it as part of the final hash. michael@0: if (mDigestContext && append && !isContinuation) { michael@0: nsCOMPtr inputStream; michael@0: rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), michael@0: mActualTarget, michael@0: PR_RDONLY | nsIFile::OS_READAHEAD); michael@0: if (rv != NS_ERROR_FILE_NOT_FOUND) { michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: char buffer[BUFFERED_IO_SIZE]; michael@0: while (true) { michael@0: uint32_t count; michael@0: rv = inputStream->Read(buffer, BUFFERED_IO_SIZE, &count); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: if (count == 0) { michael@0: // We reached the end of the file. michael@0: break; michael@0: } michael@0: michael@0: nsNSSShutDownPreventionLock lock; michael@0: if (isAlreadyShutDown()) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: michael@0: nsresult rv = MapSECStatus(PK11_DigestOp(mDigestContext, michael@0: uint8_t_ptr_cast(buffer), michael@0: count)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: rv = inputStream->Close(); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: } michael@0: michael@0: // We will append to the initial target file only if it was requested by the michael@0: // caller, but we'll always append on subsequent accesses to the target file. michael@0: int32_t creationIoFlags; michael@0: if (isContinuation) { michael@0: creationIoFlags = PR_APPEND; michael@0: } else { michael@0: creationIoFlags = (append ? PR_APPEND : PR_TRUNCATE) | PR_CREATE_FILE; michael@0: } michael@0: michael@0: // Create the target file, or append to it if we already started writing it. michael@0: nsCOMPtr outputStream; michael@0: rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), michael@0: mActualTarget, michael@0: PR_WRONLY | creationIoFlags, 0644); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: outputStream = NS_BufferOutputStream(outputStream, BUFFERED_IO_SIZE); michael@0: if (!outputStream) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: // Wrap the output stream so that it feeds the digest context if needed. michael@0: if (mDigestContext) { michael@0: // No need to acquire the NSS lock here, DigestOutputStream must acquire it michael@0: // in any case before each asynchronous write. Constructing the michael@0: // DigestOutputStream cannot fail. Passing mDigestContext to michael@0: // DigestOutputStream is safe, because BackgroundFileSaver always outlives michael@0: // the outputStream. BackgroundFileSaver is reference-counted before the michael@0: // call to AsyncCopy, and mDigestContext is never destroyed before michael@0: // AsyncCopyCallback. michael@0: outputStream = new DigestOutputStream(outputStream, mDigestContext); michael@0: } michael@0: michael@0: // Start copying our input to the target file. No errors can be raised past michael@0: // this point if the copy starts, since they should be handled by the thread. michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: michael@0: rv = NS_AsyncCopy(mPipeInputStream, outputStream, mWorkerThread, michael@0: NS_ASYNCCOPY_VIA_READSEGMENTS, 4096, AsyncCopyCallback, michael@0: this, false, true, getter_AddRefs(mAsyncCopyContext), michael@0: GetProgressCallback()); michael@0: if (NS_FAILED(rv)) { michael@0: NS_WARNING("NS_AsyncCopy failed."); michael@0: mAsyncCopyContext = nullptr; michael@0: return rv; michael@0: } michael@0: } michael@0: michael@0: // If the operation succeeded, we must ensure that we keep this object alive michael@0: // for the entire duration of the copy, since only the raw pointer will be michael@0: // provided as the argument of the AsyncCopyCallback function. We can add the michael@0: // reference now, after NS_AsyncCopy returned, because it always starts michael@0: // processing asynchronously, and there is no risk that the callback is michael@0: // invoked before we reach this point. If the operation failed instead, then michael@0: // AsyncCopyCallback will never be called. michael@0: NS_ADDREF_THIS(); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the worker thread. michael@0: bool michael@0: BackgroundFileSaver::CheckCompletion() michael@0: { michael@0: nsresult rv; michael@0: michael@0: MOZ_ASSERT(!mAsyncCopyContext, michael@0: "Should not be copying when checking completion conditions."); michael@0: michael@0: bool failed = true; michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: michael@0: if (mComplete) { michael@0: return true; michael@0: } michael@0: michael@0: // If an error occurred, we don't need to do the checks in this code block, michael@0: // and the operation can be completed immediately with a failure code. michael@0: if (NS_SUCCEEDED(mStatus)) { michael@0: failed = false; michael@0: michael@0: // We did not incur in an error, so we must determine if we can stop now. michael@0: // If the Finish method has not been called, we can just continue now. michael@0: if (!mFinishRequested) { michael@0: return false; michael@0: } michael@0: michael@0: // We can only stop when all the operations requested by the control michael@0: // thread have been processed. First, we check whether we have processed michael@0: // the first SetTarget call, if any. Then, we check whether we have michael@0: // processed any rename requested by subsequent SetTarget calls. michael@0: if ((mInitialTarget && !mActualTarget) || michael@0: (mRenamedTarget && mRenamedTarget != mActualTarget)) { michael@0: return false; michael@0: } michael@0: michael@0: // If we still have data to write to the output file, allow the copy michael@0: // operation to resume. The Available getter may return an error if one michael@0: // of the pipe's streams has been already closed. michael@0: uint64_t available; michael@0: rv = mPipeInputStream->Available(&available); michael@0: if (NS_SUCCEEDED(rv) && available != 0) { michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: mComplete = true; michael@0: } michael@0: michael@0: // Ensure we notify completion now that the operation finished. michael@0: // Do a best-effort attempt to remove the file if required. michael@0: if (failed && mActualTarget && !mActualTargetKeepPartial) { michael@0: (void)mActualTarget->Remove(false); michael@0: } michael@0: michael@0: // Finish computing the hash michael@0: if (!failed && mDigestContext) { michael@0: nsNSSShutDownPreventionLock lock; michael@0: if (!isAlreadyShutDown()) { michael@0: Digest d; michael@0: rv = d.End(SEC_OID_SHA256, mDigestContext); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: MutexAutoLock lock(mLock); michael@0: mSha256 = nsDependentCSubstring(char_ptr_cast(d.get().data), michael@0: d.get().len); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Compute the signature of the binary. ExtractSignatureInfo doesn't do michael@0: // anything on non-Windows platforms except return an empty nsIArray. michael@0: if (!failed && mActualTarget) { michael@0: nsString filePath; michael@0: mActualTarget->GetTarget(filePath); michael@0: nsresult rv = ExtractSignatureInfo(filePath); michael@0: if (NS_FAILED(rv)) { michael@0: LOG(("Unable to extract signature information [this = %p].", this)); michael@0: } else { michael@0: LOG(("Signature extraction success! [this = %p]", this)); michael@0: } michael@0: } michael@0: michael@0: // Post an event to notify that the operation completed. michael@0: nsCOMPtr event = michael@0: NS_NewRunnableMethod(this, &BackgroundFileSaver::NotifySaveComplete); michael@0: if (!event || michael@0: NS_FAILED(mControlThread->Dispatch(event, NS_DISPATCH_NORMAL))) { michael@0: NS_WARNING("Unable to post completion event to the control thread."); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: nsresult michael@0: BackgroundFileSaver::NotifyTargetChange(nsIFile *aTarget) michael@0: { michael@0: if (mObserver) { michael@0: (void)mObserver->OnTargetChange(this, aTarget); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: nsresult michael@0: BackgroundFileSaver::NotifySaveComplete() michael@0: { michael@0: MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread"); michael@0: michael@0: nsresult status; michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: status = mStatus; michael@0: } michael@0: michael@0: if (mObserver) { michael@0: (void)mObserver->OnSaveComplete(this, status); michael@0: } michael@0: michael@0: // At this point, the worker thread will not process any more events, and we michael@0: // can shut it down. Shutting down a thread may re-enter the event loop on michael@0: // this thread. This is not a problem in this case, since this function is michael@0: // called by a top-level event itself, and we have already invoked the michael@0: // completion observer callback. Re-entering the loop can only delay the michael@0: // final release and destruction of this saver object, since we are keeping a michael@0: // reference to it through the event object. michael@0: mWorkerThread->Shutdown(); michael@0: michael@0: sThreadCount--; michael@0: michael@0: // When there are no more active downloads, we consider the download session michael@0: // finished. We record the maximum number of concurrent downloads reached michael@0: // during the session in a telemetry histogram, and we reset the maximum michael@0: // thread counter for the next download session michael@0: if (sThreadCount == 0) { michael@0: Telemetry::Accumulate(Telemetry::BACKGROUNDFILESAVER_THREAD_COUNT, michael@0: sTelemetryMaxThreadCount); michael@0: sTelemetryMaxThreadCount = 0; michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath) michael@0: { michael@0: MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread"); michael@0: michael@0: nsNSSShutDownPreventionLock nssLock; michael@0: if (isAlreadyShutDown()) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: { michael@0: MutexAutoLock lock(mLock); michael@0: if (!mSignatureInfoEnabled) { michael@0: return NS_OK; michael@0: } michael@0: } michael@0: nsresult rv; michael@0: nsCOMPtr certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: #ifdef XP_WIN michael@0: // Setup the file to check. michael@0: WINTRUST_FILE_INFO fileToCheck = {0}; michael@0: fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO); michael@0: fileToCheck.pcwszFilePath = filePath.Data(); michael@0: fileToCheck.hFile = nullptr; michael@0: fileToCheck.pgKnownSubject = nullptr; michael@0: michael@0: // We want to check it is signed and trusted. michael@0: WINTRUST_DATA trustData = {0}; michael@0: trustData.cbStruct = sizeof(trustData); michael@0: trustData.pPolicyCallbackData = nullptr; michael@0: trustData.pSIPClientData = nullptr; michael@0: trustData.dwUIChoice = WTD_UI_NONE; michael@0: trustData.fdwRevocationChecks = WTD_REVOKE_NONE; michael@0: trustData.dwUnionChoice = WTD_CHOICE_FILE; michael@0: trustData.dwStateAction = WTD_STATEACTION_VERIFY; michael@0: trustData.hWVTStateData = nullptr; michael@0: trustData.pwszURLReference = nullptr; michael@0: // Disallow revocation checks over the network michael@0: trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL; michael@0: // no UI michael@0: trustData.dwUIContext = 0; michael@0: trustData.pFile = &fileToCheck; michael@0: michael@0: // The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate michael@0: // chains up to a trusted root CA and has appropriate permissions to sign michael@0: // code. michael@0: GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2; michael@0: // Check if the file is signed by something that is trusted. If the file is michael@0: // not signed, this is a no-op. michael@0: LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData); michael@0: CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr; michael@0: // According to the Windows documentation, we should check against 0 instead michael@0: // of ERROR_SUCCESS, which is an HRESULT. michael@0: if (ret == 0) { michael@0: cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData); michael@0: } michael@0: if (cryptoProviderData) { michael@0: // Lock because signature information is read on the main thread. michael@0: MutexAutoLock lock(mLock); michael@0: LOG(("Downloaded trusted and signed file [this = %p].", this)); michael@0: // A binary may have multiple signers. Each signer may have multiple certs michael@0: // in the chain. michael@0: for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) { michael@0: const CERT_CHAIN_CONTEXT* certChainContext = michael@0: cryptoProviderData->pasSigners[i].pChainContext; michael@0: if (!certChainContext) { michael@0: break; michael@0: } michael@0: for (DWORD j = 0; j < certChainContext->cChain; ++j) { michael@0: const CERT_SIMPLE_CHAIN* certSimpleChain = michael@0: certChainContext->rgpChain[j]; michael@0: if (!certSimpleChain) { michael@0: break; michael@0: } michael@0: nsCOMPtr nssCertList = michael@0: do_CreateInstance(NS_X509CERTLIST_CONTRACTID); michael@0: if (!nssCertList) { michael@0: break; michael@0: } michael@0: bool extractionSuccess = true; michael@0: for (DWORD k = 0; k < certSimpleChain->cElement; ++k) { michael@0: CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k]; michael@0: if (certChainElement->pCertContext->dwCertEncodingType != michael@0: X509_ASN_ENCODING) { michael@0: continue; michael@0: } michael@0: nsCOMPtr nssCert = nullptr; michael@0: rv = certDB->ConstructX509( michael@0: reinterpret_cast( michael@0: certChainElement->pCertContext->pbCertEncoded), michael@0: certChainElement->pCertContext->cbCertEncoded, michael@0: getter_AddRefs(nssCert)); michael@0: if (!nssCert) { michael@0: extractionSuccess = false; michael@0: LOG(("Couldn't create NSS cert [this = %p]", this)); michael@0: break; michael@0: } michael@0: nssCertList->AddCert(nssCert); michael@0: nsString subjectName; michael@0: nssCert->GetSubjectName(subjectName); michael@0: LOG(("Adding cert %s [this = %p]", michael@0: NS_ConvertUTF16toUTF8(subjectName).get(), this)); michael@0: } michael@0: if (extractionSuccess) { michael@0: mSignatureInfo.AppendObject(nssCertList); michael@0: } michael@0: } michael@0: } michael@0: // Free the provider data if cryptoProviderData is not null. michael@0: trustData.dwStateAction = WTD_STATEACTION_CLOSE; michael@0: WinVerifyTrust(nullptr, &policyGUID, &trustData); michael@0: } else { michael@0: LOG(("Downloaded unsigned or untrusted file [this = %p].", this)); michael@0: } michael@0: #endif michael@0: return NS_OK; michael@0: } michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// BackgroundFileSaverOutputStream michael@0: michael@0: NS_IMPL_ISUPPORTS(BackgroundFileSaverOutputStream, michael@0: nsIBackgroundFileSaver, michael@0: nsIOutputStream, michael@0: nsIAsyncOutputStream, michael@0: nsIOutputStreamCallback) michael@0: michael@0: BackgroundFileSaverOutputStream::BackgroundFileSaverOutputStream() michael@0: : BackgroundFileSaver() michael@0: , mAsyncWaitCallback(nullptr) michael@0: { michael@0: } michael@0: michael@0: BackgroundFileSaverOutputStream::~BackgroundFileSaverOutputStream() michael@0: { michael@0: } michael@0: michael@0: bool michael@0: BackgroundFileSaverOutputStream::HasInfiniteBuffer() michael@0: { michael@0: return false; michael@0: } michael@0: michael@0: nsAsyncCopyProgressFun michael@0: BackgroundFileSaverOutputStream::GetProgressCallback() michael@0: { michael@0: return nullptr; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::Close() michael@0: { michael@0: return mPipeOutputStream->Close(); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::Flush() michael@0: { michael@0: return mPipeOutputStream->Flush(); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::Write(const char *aBuf, uint32_t aCount, michael@0: uint32_t *_retval) michael@0: { michael@0: return mPipeOutputStream->Write(aBuf, aCount, _retval); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::WriteFrom(nsIInputStream *aFromStream, michael@0: uint32_t aCount, uint32_t *_retval) michael@0: { michael@0: return mPipeOutputStream->WriteFrom(aFromStream, aCount, _retval); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::WriteSegments(nsReadSegmentFun aReader, michael@0: void *aClosure, uint32_t aCount, michael@0: uint32_t *_retval) michael@0: { michael@0: return mPipeOutputStream->WriteSegments(aReader, aClosure, aCount, _retval); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::IsNonBlocking(bool *_retval) michael@0: { michael@0: return mPipeOutputStream->IsNonBlocking(_retval); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::CloseWithStatus(nsresult reason) michael@0: { michael@0: return mPipeOutputStream->CloseWithStatus(reason); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::AsyncWait(nsIOutputStreamCallback *aCallback, michael@0: uint32_t aFlags, michael@0: uint32_t aRequestedCount, michael@0: nsIEventTarget *aEventTarget) michael@0: { michael@0: NS_ENSURE_STATE(!mAsyncWaitCallback); michael@0: michael@0: mAsyncWaitCallback = aCallback; michael@0: michael@0: return mPipeOutputStream->AsyncWait(this, aFlags, aRequestedCount, michael@0: aEventTarget); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverOutputStream::OnOutputStreamReady( michael@0: nsIAsyncOutputStream *aStream) michael@0: { michael@0: NS_ENSURE_STATE(mAsyncWaitCallback); michael@0: michael@0: nsCOMPtr asyncWaitCallback = nullptr; michael@0: asyncWaitCallback.swap(mAsyncWaitCallback); michael@0: michael@0: return asyncWaitCallback->OnOutputStreamReady(this); michael@0: } michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// BackgroundFileSaverStreamListener michael@0: michael@0: NS_IMPL_ISUPPORTS(BackgroundFileSaverStreamListener, michael@0: nsIBackgroundFileSaver, michael@0: nsIRequestObserver, michael@0: nsIStreamListener) michael@0: michael@0: BackgroundFileSaverStreamListener::BackgroundFileSaverStreamListener() michael@0: : BackgroundFileSaver() michael@0: , mSuspensionLock("BackgroundFileSaverStreamListener.mSuspensionLock") michael@0: , mReceivedTooMuchData(false) michael@0: , mRequest(nullptr) michael@0: , mRequestSuspended(false) michael@0: { michael@0: } michael@0: michael@0: BackgroundFileSaverStreamListener::~BackgroundFileSaverStreamListener() michael@0: { michael@0: } michael@0: michael@0: bool michael@0: BackgroundFileSaverStreamListener::HasInfiniteBuffer() michael@0: { michael@0: return true; michael@0: } michael@0: michael@0: nsAsyncCopyProgressFun michael@0: BackgroundFileSaverStreamListener::GetProgressCallback() michael@0: { michael@0: return AsyncCopyProgressCallback; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverStreamListener::OnStartRequest(nsIRequest *aRequest, michael@0: nsISupports *aContext) michael@0: { michael@0: NS_ENSURE_ARG(aRequest); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverStreamListener::OnStopRequest(nsIRequest *aRequest, michael@0: nsISupports *aContext, michael@0: nsresult aStatusCode) michael@0: { michael@0: // If an error occurred, cancel the operation immediately. On success, wait michael@0: // until the caller has determined whether the file should be renamed. michael@0: if (NS_FAILED(aStatusCode)) { michael@0: Finish(aStatusCode); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: BackgroundFileSaverStreamListener::OnDataAvailable(nsIRequest *aRequest, michael@0: nsISupports *aContext, michael@0: nsIInputStream *aInputStream, michael@0: uint64_t aOffset, michael@0: uint32_t aCount) michael@0: { michael@0: nsresult rv; michael@0: michael@0: NS_ENSURE_ARG(aRequest); michael@0: michael@0: // Read the requested data. Since the pipe has an infinite buffer, we don't michael@0: // expect any write error to occur here. michael@0: uint32_t writeCount; michael@0: rv = mPipeOutputStream->WriteFrom(aInputStream, aCount, &writeCount); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // If reading from the input stream fails for any reason, the pipe will return michael@0: // a success code, but without reading all the data. Since we should be able michael@0: // to read the requested data when OnDataAvailable is called, raise an error. michael@0: if (writeCount < aCount) { michael@0: NS_WARNING("Reading from the input stream should not have failed."); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: bool stateChanged = false; michael@0: { michael@0: MutexAutoLock lock(mSuspensionLock); michael@0: michael@0: if (!mReceivedTooMuchData) { michael@0: uint64_t available; michael@0: nsresult rv = mPipeInputStream->Available(&available); michael@0: if (NS_SUCCEEDED(rv) && available > REQUEST_SUSPEND_AT) { michael@0: mReceivedTooMuchData = true; michael@0: mRequest = aRequest; michael@0: stateChanged = true; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (stateChanged) { michael@0: NotifySuspendOrResume(); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called on the worker thread. michael@0: // static michael@0: void michael@0: BackgroundFileSaverStreamListener::AsyncCopyProgressCallback(void *aClosure, michael@0: uint32_t aCount) michael@0: { michael@0: BackgroundFileSaverStreamListener *self = michael@0: (BackgroundFileSaverStreamListener *)aClosure; michael@0: michael@0: // Wait if the control thread is in the process of suspending or resuming. michael@0: MutexAutoLock lock(self->mSuspensionLock); michael@0: michael@0: // This function is called when some bytes are consumed by NS_AsyncCopy. Each michael@0: // time this happens, verify if a suspended request should be resumed, because michael@0: // we have now consumed enough data. michael@0: if (self->mReceivedTooMuchData) { michael@0: uint64_t available; michael@0: nsresult rv = self->mPipeInputStream->Available(&available); michael@0: if (NS_FAILED(rv) || available < REQUEST_RESUME_AT) { michael@0: self->mReceivedTooMuchData = false; michael@0: michael@0: // Post an event to verify if the request should be resumed. michael@0: nsCOMPtr event = NS_NewRunnableMethod(self, michael@0: &BackgroundFileSaverStreamListener::NotifySuspendOrResume); michael@0: if (!event || NS_FAILED(self->mControlThread->Dispatch(event, michael@0: NS_DISPATCH_NORMAL))) { michael@0: NS_WARNING("Unable to post resume event to the control thread."); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Called on the control thread. michael@0: nsresult michael@0: BackgroundFileSaverStreamListener::NotifySuspendOrResume() michael@0: { michael@0: // Prevent the worker thread from changing state while processing. michael@0: MutexAutoLock lock(mSuspensionLock); michael@0: michael@0: if (mReceivedTooMuchData) { michael@0: if (!mRequestSuspended) { michael@0: // Try to suspend the request. If this fails, don't try to resume later. michael@0: if (NS_SUCCEEDED(mRequest->Suspend())) { michael@0: mRequestSuspended = true; michael@0: } else { michael@0: NS_WARNING("Unable to suspend the request."); michael@0: } michael@0: } michael@0: } else { michael@0: if (mRequestSuspended) { michael@0: // Resume the request only if we succeeded in suspending it. michael@0: if (NS_SUCCEEDED(mRequest->Resume())) { michael@0: mRequestSuspended = false; michael@0: } else { michael@0: NS_WARNING("Unable to resume the request."); michael@0: } michael@0: } michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// DigestOutputStream michael@0: NS_IMPL_ISUPPORTS(DigestOutputStream, michael@0: nsIOutputStream) michael@0: michael@0: DigestOutputStream::DigestOutputStream(nsIOutputStream* aStream, michael@0: PK11Context* aContext) : michael@0: mOutputStream(aStream) michael@0: , mDigestContext(aContext) michael@0: { michael@0: MOZ_ASSERT(mDigestContext, "Can't have null digest context"); michael@0: MOZ_ASSERT(mOutputStream, "Can't have null output stream"); michael@0: } michael@0: michael@0: DigestOutputStream::~DigestOutputStream() michael@0: { michael@0: shutdown(calledFromObject); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::Close() michael@0: { michael@0: return mOutputStream->Close(); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::Flush() michael@0: { michael@0: return mOutputStream->Flush(); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::Write(const char* aBuf, uint32_t aCount, uint32_t* retval) michael@0: { michael@0: nsNSSShutDownPreventionLock lock; michael@0: if (isAlreadyShutDown()) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: michael@0: nsresult rv = MapSECStatus(PK11_DigestOp(mDigestContext, michael@0: uint8_t_ptr_cast(aBuf), aCount)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: return mOutputStream->Write(aBuf, aCount, retval); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::WriteFrom(nsIInputStream* aFromStream, michael@0: uint32_t aCount, uint32_t* retval) michael@0: { michael@0: // Not supported. We could read the stream to a buf, call DigestOp on the michael@0: // result, seek back and pass the stream on, but it's not worth it since our michael@0: // application (NS_AsyncCopy) doesn't invoke this on the sink. michael@0: MOZ_CRASH("DigestOutputStream::WriteFrom not implemented"); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::WriteSegments(nsReadSegmentFun aReader, michael@0: void *aClosure, uint32_t aCount, michael@0: uint32_t *retval) michael@0: { michael@0: MOZ_CRASH("DigestOutputStream::WriteSegments not implemented"); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: DigestOutputStream::IsNonBlocking(bool *retval) michael@0: { michael@0: return mOutputStream->IsNonBlocking(retval); michael@0: } michael@0: michael@0: } // namespace net michael@0: } // namespace mozilla