BackgroundFileSaver.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "BackgroundFileSaver.h"
  6. #include "ScopedNSSTypes.h"
  7. #include "mozilla/Casting.h"
  8. #include "mozilla/Logging.h"
  9. #include "nsCOMArray.h"
  10. #include "nsIAsyncInputStream.h"
  11. #include "nsIFile.h"
  12. #include "nsIMutableArray.h"
  13. #include "nsIPipe.h"
  14. #include "nsIX509Cert.h"
  15. #include "nsIX509CertDB.h"
  16. #include "nsIX509CertList.h"
  17. #include "nsNetUtil.h"
  18. #include "nsThreadUtils.h"
  19. #include "pk11pub.h"
  20. #include "secoidt.h"
  21. #ifdef XP_WIN
  22. #include <windows.h>
  23. #include <softpub.h>
  24. #include <wintrust.h>
  25. #endif // XP_WIN
  26. namespace mozilla {
  27. namespace net {
  28. // MOZ_LOG=BackgroundFileSaver:5
  29. static LazyLogModule prlog("BackgroundFileSaver");
  30. #define LOG(args) MOZ_LOG(prlog, mozilla::LogLevel::Debug, args)
  31. #define LOG_ENABLED() MOZ_LOG_TEST(prlog, mozilla::LogLevel::Debug)
  32. ////////////////////////////////////////////////////////////////////////////////
  33. //// Globals
  34. /**
  35. * Buffer size for writing to the output file or reading from the input file.
  36. */
  37. #define BUFFERED_IO_SIZE (1024 * 32)
  38. /**
  39. * When this upper limit is reached, the original request is suspended.
  40. */
  41. #define REQUEST_SUSPEND_AT (1024 * 1024 * 4)
  42. /**
  43. * When this lower limit is reached, the original request is resumed.
  44. */
  45. #define REQUEST_RESUME_AT (1024 * 1024 * 2)
  46. ////////////////////////////////////////////////////////////////////////////////
  47. //// NotifyTargetChangeRunnable
  48. /**
  49. * Runnable object used to notify the control thread that file contents will now
  50. * be saved to the specified file.
  51. */
  52. class NotifyTargetChangeRunnable final : public Runnable
  53. {
  54. public:
  55. NotifyTargetChangeRunnable(BackgroundFileSaver *aSaver, nsIFile *aTarget)
  56. : mSaver(aSaver)
  57. , mTarget(aTarget)
  58. {
  59. }
  60. NS_IMETHOD Run() override
  61. {
  62. return mSaver->NotifyTargetChange(mTarget);
  63. }
  64. private:
  65. RefPtr<BackgroundFileSaver> mSaver;
  66. nsCOMPtr<nsIFile> mTarget;
  67. };
  68. ////////////////////////////////////////////////////////////////////////////////
  69. //// BackgroundFileSaver
  70. uint32_t BackgroundFileSaver::sThreadCount = 0;
  71. BackgroundFileSaver::BackgroundFileSaver()
  72. : mControlThread(nullptr)
  73. , mWorkerThread(nullptr)
  74. , mPipeOutputStream(nullptr)
  75. , mPipeInputStream(nullptr)
  76. , mObserver(nullptr)
  77. , mLock("BackgroundFileSaver.mLock")
  78. , mWorkerThreadAttentionRequested(false)
  79. , mFinishRequested(false)
  80. , mComplete(false)
  81. , mStatus(NS_OK)
  82. , mAppend(false)
  83. , mInitialTarget(nullptr)
  84. , mInitialTargetKeepPartial(false)
  85. , mRenamedTarget(nullptr)
  86. , mRenamedTargetKeepPartial(false)
  87. , mAsyncCopyContext(nullptr)
  88. , mSha256Enabled(false)
  89. , mSignatureInfoEnabled(false)
  90. , mActualTarget(nullptr)
  91. , mActualTargetKeepPartial(false)
  92. , mDigestContext(nullptr)
  93. {
  94. LOG(("Created BackgroundFileSaver [this = %p]", this));
  95. }
  96. BackgroundFileSaver::~BackgroundFileSaver()
  97. {
  98. LOG(("Destroying BackgroundFileSaver [this = %p]", this));
  99. nsNSSShutDownPreventionLock lock;
  100. if (isAlreadyShutDown()) {
  101. return;
  102. }
  103. destructorSafeDestroyNSSReference();
  104. shutdown(ShutdownCalledFrom::Object);
  105. }
  106. void
  107. BackgroundFileSaver::destructorSafeDestroyNSSReference()
  108. {
  109. mDigestContext = nullptr;
  110. }
  111. void
  112. BackgroundFileSaver::virtualDestroyNSSReference()
  113. {
  114. destructorSafeDestroyNSSReference();
  115. }
  116. // Called on the control thread.
  117. nsresult
  118. BackgroundFileSaver::Init()
  119. {
  120. MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread");
  121. nsresult rv;
  122. rv = NS_NewPipe2(getter_AddRefs(mPipeInputStream),
  123. getter_AddRefs(mPipeOutputStream), true, true, 0,
  124. HasInfiniteBuffer() ? UINT32_MAX : 0);
  125. NS_ENSURE_SUCCESS(rv, rv);
  126. rv = NS_GetCurrentThread(getter_AddRefs(mControlThread));
  127. NS_ENSURE_SUCCESS(rv, rv);
  128. rv = NS_NewThread(getter_AddRefs(mWorkerThread));
  129. NS_ENSURE_SUCCESS(rv, rv);
  130. sThreadCount++;
  131. return NS_OK;
  132. }
  133. // Called on the control thread.
  134. NS_IMETHODIMP
  135. BackgroundFileSaver::GetObserver(nsIBackgroundFileSaverObserver **aObserver)
  136. {
  137. NS_ENSURE_ARG_POINTER(aObserver);
  138. *aObserver = mObserver;
  139. NS_IF_ADDREF(*aObserver);
  140. return NS_OK;
  141. }
  142. // Called on the control thread.
  143. NS_IMETHODIMP
  144. BackgroundFileSaver::SetObserver(nsIBackgroundFileSaverObserver *aObserver)
  145. {
  146. mObserver = aObserver;
  147. return NS_OK;
  148. }
  149. // Called on the control thread.
  150. NS_IMETHODIMP
  151. BackgroundFileSaver::EnableAppend()
  152. {
  153. MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread");
  154. MutexAutoLock lock(mLock);
  155. mAppend = true;
  156. return NS_OK;
  157. }
  158. // Called on the control thread.
  159. NS_IMETHODIMP
  160. BackgroundFileSaver::SetTarget(nsIFile *aTarget, bool aKeepPartial)
  161. {
  162. NS_ENSURE_ARG(aTarget);
  163. {
  164. MutexAutoLock lock(mLock);
  165. if (!mInitialTarget) {
  166. aTarget->Clone(getter_AddRefs(mInitialTarget));
  167. mInitialTargetKeepPartial = aKeepPartial;
  168. } else {
  169. aTarget->Clone(getter_AddRefs(mRenamedTarget));
  170. mRenamedTargetKeepPartial = aKeepPartial;
  171. }
  172. }
  173. // After the worker thread wakes up because attention is requested, it will
  174. // rename or create the target file as requested, and start copying data.
  175. return GetWorkerThreadAttention(true);
  176. }
  177. // Called on the control thread.
  178. NS_IMETHODIMP
  179. BackgroundFileSaver::Finish(nsresult aStatus)
  180. {
  181. nsresult rv;
  182. // This will cause the NS_AsyncCopy operation, if it's in progress, to consume
  183. // all the data that is still in the pipe, and then finish.
  184. rv = mPipeOutputStream->Close();
  185. NS_ENSURE_SUCCESS(rv, rv);
  186. // Ensure that, when we get attention from the worker thread, if no pending
  187. // rename operation is waiting, the operation will complete.
  188. {
  189. MutexAutoLock lock(mLock);
  190. mFinishRequested = true;
  191. if (NS_SUCCEEDED(mStatus)) {
  192. mStatus = aStatus;
  193. }
  194. }
  195. // After the worker thread wakes up because attention is requested, it will
  196. // process the completion conditions, detect that completion is requested, and
  197. // notify the main thread of the completion. If this function was called with
  198. // a success code, we wait for the copy to finish before processing the
  199. // completion conditions, otherwise we interrupt the copy immediately.
  200. return GetWorkerThreadAttention(NS_FAILED(aStatus));
  201. }
  202. NS_IMETHODIMP
  203. BackgroundFileSaver::EnableSha256()
  204. {
  205. MOZ_ASSERT(NS_IsMainThread(),
  206. "Can't enable sha256 or initialize NSS off the main thread");
  207. // Ensure Personal Security Manager is initialized. This is required for
  208. // PK11_* operations to work.
  209. nsresult rv;
  210. nsCOMPtr<nsISupports> nssDummy = do_GetService("@mozilla.org/psm;1", &rv);
  211. NS_ENSURE_SUCCESS(rv, rv);
  212. mSha256Enabled = true;
  213. return NS_OK;
  214. }
  215. NS_IMETHODIMP
  216. BackgroundFileSaver::GetSha256Hash(nsACString& aHash)
  217. {
  218. MOZ_ASSERT(NS_IsMainThread(), "Can't inspect sha256 off the main thread");
  219. // We acquire a lock because mSha256 is written on the worker thread.
  220. MutexAutoLock lock(mLock);
  221. if (mSha256.IsEmpty()) {
  222. return NS_ERROR_NOT_AVAILABLE;
  223. }
  224. aHash = mSha256;
  225. return NS_OK;
  226. }
  227. NS_IMETHODIMP
  228. BackgroundFileSaver::EnableSignatureInfo()
  229. {
  230. MOZ_ASSERT(NS_IsMainThread(),
  231. "Can't enable signature extraction off the main thread");
  232. // Ensure Personal Security Manager is initialized.
  233. nsresult rv;
  234. nsCOMPtr<nsISupports> nssDummy = do_GetService("@mozilla.org/psm;1", &rv);
  235. NS_ENSURE_SUCCESS(rv, rv);
  236. mSignatureInfoEnabled = true;
  237. return NS_OK;
  238. }
  239. NS_IMETHODIMP
  240. BackgroundFileSaver::GetSignatureInfo(nsIArray** aSignatureInfo)
  241. {
  242. MOZ_ASSERT(NS_IsMainThread(), "Can't inspect signature off the main thread");
  243. // We acquire a lock because mSignatureInfo is written on the worker thread.
  244. MutexAutoLock lock(mLock);
  245. if (!mComplete || !mSignatureInfoEnabled) {
  246. return NS_ERROR_NOT_AVAILABLE;
  247. }
  248. nsCOMPtr<nsIMutableArray> sigArray = do_CreateInstance(NS_ARRAY_CONTRACTID);
  249. for (int i = 0; i < mSignatureInfo.Count(); ++i) {
  250. sigArray->AppendElement(mSignatureInfo[i], false);
  251. }
  252. *aSignatureInfo = sigArray;
  253. NS_IF_ADDREF(*aSignatureInfo);
  254. return NS_OK;
  255. }
  256. // Called on the control thread.
  257. nsresult
  258. BackgroundFileSaver::GetWorkerThreadAttention(bool aShouldInterruptCopy)
  259. {
  260. nsresult rv;
  261. MutexAutoLock lock(mLock);
  262. // We only require attention one time. If this function is called two times
  263. // before the worker thread wakes up, and the first has aShouldInterruptCopy
  264. // false and the second true, we won't forcibly interrupt the copy from the
  265. // control thread. However, that never happens, because calling Finish with a
  266. // success code is the only case that may result in aShouldInterruptCopy being
  267. // false. In that case, we won't call this function again, because consumers
  268. // should not invoke other methods on the control thread after calling Finish.
  269. // And in any case, Finish already closes one end of the pipe, causing the
  270. // copy to finish properly on its own.
  271. if (mWorkerThreadAttentionRequested) {
  272. return NS_OK;
  273. }
  274. if (!mAsyncCopyContext) {
  275. // Copy is not in progress, post an event to handle the change manually.
  276. rv = mWorkerThread->Dispatch(NewRunnableMethod(this,
  277. &BackgroundFileSaver::ProcessAttention),
  278. NS_DISPATCH_NORMAL);
  279. NS_ENSURE_SUCCESS(rv, rv);
  280. } else if (aShouldInterruptCopy) {
  281. // Interrupt the copy. The copy will be resumed, if needed, by the
  282. // ProcessAttention function, invoked by the AsyncCopyCallback function.
  283. NS_CancelAsyncCopy(mAsyncCopyContext, NS_ERROR_ABORT);
  284. }
  285. // Indicate that attention has been requested successfully, there is no need
  286. // to post another event until the worker thread processes the current one.
  287. mWorkerThreadAttentionRequested = true;
  288. return NS_OK;
  289. }
  290. // Called on the worker thread.
  291. // static
  292. void
  293. BackgroundFileSaver::AsyncCopyCallback(void *aClosure, nsresult aStatus)
  294. {
  295. BackgroundFileSaver *self = (BackgroundFileSaver *)aClosure;
  296. {
  297. MutexAutoLock lock(self->mLock);
  298. // Now that the copy was interrupted or terminated, any notification from
  299. // the control thread requires an event to be posted to the worker thread.
  300. self->mAsyncCopyContext = nullptr;
  301. // When detecting failures, ignore the status code we use to interrupt.
  302. if (NS_FAILED(aStatus) && aStatus != NS_ERROR_ABORT &&
  303. NS_SUCCEEDED(self->mStatus)) {
  304. self->mStatus = aStatus;
  305. }
  306. }
  307. (void)self->ProcessAttention();
  308. // We called NS_ADDREF_THIS when NS_AsyncCopy started, to keep the object
  309. // alive even if other references disappeared. At this point, we've finished
  310. // using the object and can safely release our reference.
  311. NS_RELEASE(self);
  312. }
  313. // Called on the worker thread.
  314. nsresult
  315. BackgroundFileSaver::ProcessAttention()
  316. {
  317. nsresult rv;
  318. // This function is called whenever the attention of the worker thread has
  319. // been requested. This may happen in these cases:
  320. // * We are about to start the copy for the first time. In this case, we are
  321. // called from an event posted on the worker thread from the control thread
  322. // by GetWorkerThreadAttention, and mAsyncCopyContext is null.
  323. // * We have interrupted the copy for some reason. In this case, we are
  324. // called by AsyncCopyCallback, and mAsyncCopyContext is null.
  325. // * We are currently executing ProcessStateChange, and attention is requested
  326. // by the control thread, for example because SetTarget or Finish have been
  327. // called. In this case, we are called from from an event posted through
  328. // GetWorkerThreadAttention. While mAsyncCopyContext was always null when
  329. // the event was posted, at this point mAsyncCopyContext may not be null
  330. // anymore, because ProcessStateChange may have started the copy before the
  331. // event that called this function was processed on the worker thread.
  332. // If mAsyncCopyContext is not null, we interrupt the copy and re-enter
  333. // through AsyncCopyCallback. This allows us to check if, for instance, we
  334. // should rename the target file. We will then restart the copy if needed.
  335. if (mAsyncCopyContext) {
  336. NS_CancelAsyncCopy(mAsyncCopyContext, NS_ERROR_ABORT);
  337. return NS_OK;
  338. }
  339. // Use the current shared state to determine the next operation to execute.
  340. rv = ProcessStateChange();
  341. if (NS_FAILED(rv)) {
  342. // If something failed while processing, terminate the operation now.
  343. {
  344. MutexAutoLock lock(mLock);
  345. if (NS_SUCCEEDED(mStatus)) {
  346. mStatus = rv;
  347. }
  348. }
  349. // Ensure we notify completion now that the operation failed.
  350. CheckCompletion();
  351. }
  352. return NS_OK;
  353. }
  354. // Called on the worker thread.
  355. nsresult
  356. BackgroundFileSaver::ProcessStateChange()
  357. {
  358. nsresult rv;
  359. // We might have been notified because the operation is complete, verify.
  360. if (CheckCompletion()) {
  361. return NS_OK;
  362. }
  363. // Get a copy of the current shared state for the worker thread.
  364. nsCOMPtr<nsIFile> initialTarget;
  365. bool initialTargetKeepPartial;
  366. nsCOMPtr<nsIFile> renamedTarget;
  367. bool renamedTargetKeepPartial;
  368. bool sha256Enabled;
  369. bool append;
  370. {
  371. MutexAutoLock lock(mLock);
  372. initialTarget = mInitialTarget;
  373. initialTargetKeepPartial = mInitialTargetKeepPartial;
  374. renamedTarget = mRenamedTarget;
  375. renamedTargetKeepPartial = mRenamedTargetKeepPartial;
  376. sha256Enabled = mSha256Enabled;
  377. append = mAppend;
  378. // From now on, another attention event needs to be posted if state changes.
  379. mWorkerThreadAttentionRequested = false;
  380. }
  381. // The initial target can only be null if it has never been assigned. In this
  382. // case, there is nothing to do since we never created any output file.
  383. if (!initialTarget) {
  384. return NS_OK;
  385. }
  386. // Determine if we are processing the attention request for the first time.
  387. bool isContinuation = !!mActualTarget;
  388. if (!isContinuation) {
  389. // Assign the target file for the first time.
  390. mActualTarget = initialTarget;
  391. mActualTargetKeepPartial = initialTargetKeepPartial;
  392. }
  393. // Verify whether we have actually been instructed to use a different file.
  394. // This may happen the first time this function is executed, if SetTarget was
  395. // called two times before the worker thread processed the attention request.
  396. bool equalToCurrent = false;
  397. if (renamedTarget) {
  398. rv = mActualTarget->Equals(renamedTarget, &equalToCurrent);
  399. NS_ENSURE_SUCCESS(rv, rv);
  400. if (!equalToCurrent)
  401. {
  402. // If we were asked to rename the file but the initial file did not exist,
  403. // we simply create the file in the renamed location. We avoid this check
  404. // if we have already started writing the output file ourselves.
  405. bool exists = true;
  406. if (!isContinuation) {
  407. rv = mActualTarget->Exists(&exists);
  408. NS_ENSURE_SUCCESS(rv, rv);
  409. }
  410. if (exists) {
  411. // We are moving the previous target file to a different location.
  412. nsCOMPtr<nsIFile> renamedTargetParentDir;
  413. rv = renamedTarget->GetParent(getter_AddRefs(renamedTargetParentDir));
  414. NS_ENSURE_SUCCESS(rv, rv);
  415. nsAutoString renamedTargetName;
  416. rv = renamedTarget->GetLeafName(renamedTargetName);
  417. NS_ENSURE_SUCCESS(rv, rv);
  418. // We must delete any existing target file before moving the current
  419. // one.
  420. rv = renamedTarget->Exists(&exists);
  421. NS_ENSURE_SUCCESS(rv, rv);
  422. if (exists) {
  423. rv = renamedTarget->Remove(false);
  424. NS_ENSURE_SUCCESS(rv, rv);
  425. }
  426. // Move the file. If this fails, we still reference the original file
  427. // in mActualTarget, so that it is deleted if requested. If this
  428. // succeeds, the nsIFile instance referenced by mActualTarget mutates
  429. // and starts pointing to the new file, but we'll discard the reference.
  430. rv = mActualTarget->MoveTo(renamedTargetParentDir, renamedTargetName);
  431. NS_ENSURE_SUCCESS(rv, rv);
  432. }
  433. // Now we can update the actual target file name.
  434. mActualTarget = renamedTarget;
  435. mActualTargetKeepPartial = renamedTargetKeepPartial;
  436. }
  437. }
  438. // Notify if the target file name actually changed.
  439. if (!equalToCurrent) {
  440. // We must clone the nsIFile instance because mActualTarget is not
  441. // immutable, it may change if the target is renamed later.
  442. nsCOMPtr<nsIFile> actualTargetToNotify;
  443. rv = mActualTarget->Clone(getter_AddRefs(actualTargetToNotify));
  444. NS_ENSURE_SUCCESS(rv, rv);
  445. RefPtr<NotifyTargetChangeRunnable> event =
  446. new NotifyTargetChangeRunnable(this, actualTargetToNotify);
  447. NS_ENSURE_TRUE(event, NS_ERROR_FAILURE);
  448. rv = mControlThread->Dispatch(event, NS_DISPATCH_NORMAL);
  449. NS_ENSURE_SUCCESS(rv, rv);
  450. }
  451. if (isContinuation) {
  452. // The pending rename operation might be the last task before finishing. We
  453. // may return here only if we have already created the target file.
  454. if (CheckCompletion()) {
  455. return NS_OK;
  456. }
  457. // Even if the operation did not complete, the pipe input stream may be
  458. // empty and may have been closed already. We detect this case using the
  459. // Available property, because it never returns an error if there is more
  460. // data to be consumed. If the pipe input stream is closed, we just exit
  461. // and wait for more calls like SetTarget or Finish to be invoked on the
  462. // control thread. However, we still truncate the file or create the
  463. // initial digest context if we are expected to do that.
  464. uint64_t available;
  465. rv = mPipeInputStream->Available(&available);
  466. if (NS_FAILED(rv)) {
  467. return NS_OK;
  468. }
  469. }
  470. // Create the digest context if requested and NSS hasn't been shut down.
  471. if (sha256Enabled && !mDigestContext) {
  472. nsNSSShutDownPreventionLock lock;
  473. if (!isAlreadyShutDown()) {
  474. mDigestContext = UniquePK11Context(
  475. PK11_CreateDigestContext(SEC_OID_SHA256));
  476. NS_ENSURE_TRUE(mDigestContext, NS_ERROR_OUT_OF_MEMORY);
  477. }
  478. }
  479. // When we are requested to append to an existing file, we should read the
  480. // existing data and ensure we include it as part of the final hash.
  481. if (mDigestContext && append && !isContinuation) {
  482. nsCOMPtr<nsIInputStream> inputStream;
  483. rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream),
  484. mActualTarget,
  485. PR_RDONLY | nsIFile::OS_READAHEAD);
  486. if (rv != NS_ERROR_FILE_NOT_FOUND) {
  487. NS_ENSURE_SUCCESS(rv, rv);
  488. char buffer[BUFFERED_IO_SIZE];
  489. while (true) {
  490. uint32_t count;
  491. rv = inputStream->Read(buffer, BUFFERED_IO_SIZE, &count);
  492. NS_ENSURE_SUCCESS(rv, rv);
  493. if (count == 0) {
  494. // We reached the end of the file.
  495. break;
  496. }
  497. nsNSSShutDownPreventionLock lock;
  498. if (isAlreadyShutDown()) {
  499. return NS_ERROR_NOT_AVAILABLE;
  500. }
  501. nsresult rv = MapSECStatus(
  502. PK11_DigestOp(mDigestContext.get(),
  503. BitwiseCast<unsigned char*, char*>(buffer),
  504. count));
  505. NS_ENSURE_SUCCESS(rv, rv);
  506. }
  507. rv = inputStream->Close();
  508. NS_ENSURE_SUCCESS(rv, rv);
  509. }
  510. }
  511. // We will append to the initial target file only if it was requested by the
  512. // caller, but we'll always append on subsequent accesses to the target file.
  513. int32_t creationIoFlags;
  514. if (isContinuation) {
  515. creationIoFlags = PR_APPEND;
  516. } else {
  517. creationIoFlags = (append ? PR_APPEND : PR_TRUNCATE) | PR_CREATE_FILE;
  518. }
  519. // Create the target file, or append to it if we already started writing it.
  520. // The 0600 permissions are used while the file is being downloaded, and for
  521. // interrupted downloads. Those may be located in the system temporary
  522. // directory, as well as the target directory, and generally have a ".part"
  523. // extension. Those part files should never be group or world-writable even
  524. // if the umask allows it.
  525. nsCOMPtr<nsIOutputStream> outputStream;
  526. rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream),
  527. mActualTarget,
  528. PR_WRONLY | creationIoFlags, 0600);
  529. NS_ENSURE_SUCCESS(rv, rv);
  530. outputStream = NS_BufferOutputStream(outputStream, BUFFERED_IO_SIZE);
  531. if (!outputStream) {
  532. return NS_ERROR_FAILURE;
  533. }
  534. // Wrap the output stream so that it feeds the digest context if needed.
  535. if (mDigestContext) {
  536. // No need to acquire the NSS lock here, DigestOutputStream must acquire it
  537. // in any case before each asynchronous write. Constructing the
  538. // DigestOutputStream cannot fail. Passing mDigestContext to
  539. // DigestOutputStream is safe, because BackgroundFileSaver always outlives
  540. // the outputStream. BackgroundFileSaver is reference-counted before the
  541. // call to AsyncCopy, and mDigestContext is never destroyed before
  542. // AsyncCopyCallback.
  543. outputStream = new DigestOutputStream(outputStream, mDigestContext.get());
  544. }
  545. // Start copying our input to the target file. No errors can be raised past
  546. // this point if the copy starts, since they should be handled by the thread.
  547. {
  548. MutexAutoLock lock(mLock);
  549. rv = NS_AsyncCopy(mPipeInputStream, outputStream, mWorkerThread,
  550. NS_ASYNCCOPY_VIA_READSEGMENTS, 4096, AsyncCopyCallback,
  551. this, false, true, getter_AddRefs(mAsyncCopyContext),
  552. GetProgressCallback());
  553. if (NS_FAILED(rv)) {
  554. NS_WARNING("NS_AsyncCopy failed.");
  555. mAsyncCopyContext = nullptr;
  556. return rv;
  557. }
  558. }
  559. // If the operation succeeded, we must ensure that we keep this object alive
  560. // for the entire duration of the copy, since only the raw pointer will be
  561. // provided as the argument of the AsyncCopyCallback function. We can add the
  562. // reference now, after NS_AsyncCopy returned, because it always starts
  563. // processing asynchronously, and there is no risk that the callback is
  564. // invoked before we reach this point. If the operation failed instead, then
  565. // AsyncCopyCallback will never be called.
  566. NS_ADDREF_THIS();
  567. return NS_OK;
  568. }
  569. // Called on the worker thread.
  570. bool
  571. BackgroundFileSaver::CheckCompletion()
  572. {
  573. nsresult rv;
  574. MOZ_ASSERT(!mAsyncCopyContext,
  575. "Should not be copying when checking completion conditions.");
  576. bool failed = true;
  577. {
  578. MutexAutoLock lock(mLock);
  579. if (mComplete) {
  580. return true;
  581. }
  582. // If an error occurred, we don't need to do the checks in this code block,
  583. // and the operation can be completed immediately with a failure code.
  584. if (NS_SUCCEEDED(mStatus)) {
  585. failed = false;
  586. // We did not incur in an error, so we must determine if we can stop now.
  587. // If the Finish method has not been called, we can just continue now.
  588. if (!mFinishRequested) {
  589. return false;
  590. }
  591. // We can only stop when all the operations requested by the control
  592. // thread have been processed. First, we check whether we have processed
  593. // the first SetTarget call, if any. Then, we check whether we have
  594. // processed any rename requested by subsequent SetTarget calls.
  595. if ((mInitialTarget && !mActualTarget) ||
  596. (mRenamedTarget && mRenamedTarget != mActualTarget)) {
  597. return false;
  598. }
  599. // If we still have data to write to the output file, allow the copy
  600. // operation to resume. The Available getter may return an error if one
  601. // of the pipe's streams has been already closed.
  602. uint64_t available;
  603. rv = mPipeInputStream->Available(&available);
  604. if (NS_SUCCEEDED(rv) && available != 0) {
  605. return false;
  606. }
  607. }
  608. mComplete = true;
  609. }
  610. // Ensure we notify completion now that the operation finished.
  611. // Do a best-effort attempt to remove the file if required.
  612. if (failed && mActualTarget && !mActualTargetKeepPartial) {
  613. (void)mActualTarget->Remove(false);
  614. }
  615. // Finish computing the hash
  616. if (!failed && mDigestContext) {
  617. nsNSSShutDownPreventionLock lock;
  618. if (!isAlreadyShutDown()) {
  619. Digest d;
  620. rv = d.End(SEC_OID_SHA256, mDigestContext);
  621. if (NS_SUCCEEDED(rv)) {
  622. MutexAutoLock lock(mLock);
  623. mSha256 =
  624. nsDependentCSubstring(BitwiseCast<char*, unsigned char*>(d.get().data),
  625. d.get().len);
  626. }
  627. }
  628. }
  629. // Compute the signature of the binary. ExtractSignatureInfo doesn't do
  630. // anything on non-Windows platforms except return an empty nsIArray.
  631. if (!failed && mActualTarget) {
  632. nsString filePath;
  633. mActualTarget->GetTarget(filePath);
  634. nsresult rv = ExtractSignatureInfo(filePath);
  635. if (NS_FAILED(rv)) {
  636. LOG(("Unable to extract signature information [this = %p].", this));
  637. } else {
  638. LOG(("Signature extraction success! [this = %p]", this));
  639. }
  640. }
  641. // Post an event to notify that the operation completed.
  642. if (NS_FAILED(mControlThread->Dispatch(NewRunnableMethod(this,
  643. &BackgroundFileSaver::NotifySaveComplete),
  644. NS_DISPATCH_NORMAL))) {
  645. NS_WARNING("Unable to post completion event to the control thread.");
  646. }
  647. return true;
  648. }
  649. // Called on the control thread.
  650. nsresult
  651. BackgroundFileSaver::NotifyTargetChange(nsIFile *aTarget)
  652. {
  653. if (mObserver) {
  654. (void)mObserver->OnTargetChange(this, aTarget);
  655. }
  656. return NS_OK;
  657. }
  658. // Called on the control thread.
  659. nsresult
  660. BackgroundFileSaver::NotifySaveComplete()
  661. {
  662. MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread");
  663. nsresult status;
  664. {
  665. MutexAutoLock lock(mLock);
  666. status = mStatus;
  667. }
  668. if (mObserver) {
  669. (void)mObserver->OnSaveComplete(this, status);
  670. }
  671. // At this point, the worker thread will not process any more events, and we
  672. // can shut it down. Shutting down a thread may re-enter the event loop on
  673. // this thread. This is not a problem in this case, since this function is
  674. // called by a top-level event itself, and we have already invoked the
  675. // completion observer callback. Re-entering the loop can only delay the
  676. // final release and destruction of this saver object, since we are keeping a
  677. // reference to it through the event object.
  678. mWorkerThread->Shutdown();
  679. sThreadCount--;
  680. return NS_OK;
  681. }
  682. nsresult
  683. BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath)
  684. {
  685. MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread");
  686. nsNSSShutDownPreventionLock nssLock;
  687. if (isAlreadyShutDown()) {
  688. return NS_ERROR_NOT_AVAILABLE;
  689. }
  690. {
  691. MutexAutoLock lock(mLock);
  692. if (!mSignatureInfoEnabled) {
  693. return NS_OK;
  694. }
  695. }
  696. nsresult rv;
  697. nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv);
  698. NS_ENSURE_SUCCESS(rv, rv);
  699. #ifdef XP_WIN
  700. // Setup the file to check.
  701. WINTRUST_FILE_INFO fileToCheck = {0};
  702. fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
  703. fileToCheck.pcwszFilePath = filePath.Data();
  704. fileToCheck.hFile = nullptr;
  705. fileToCheck.pgKnownSubject = nullptr;
  706. // We want to check it is signed and trusted.
  707. WINTRUST_DATA trustData = {0};
  708. trustData.cbStruct = sizeof(trustData);
  709. trustData.pPolicyCallbackData = nullptr;
  710. trustData.pSIPClientData = nullptr;
  711. trustData.dwUIChoice = WTD_UI_NONE;
  712. trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
  713. trustData.dwUnionChoice = WTD_CHOICE_FILE;
  714. trustData.dwStateAction = WTD_STATEACTION_VERIFY;
  715. trustData.hWVTStateData = nullptr;
  716. trustData.pwszURLReference = nullptr;
  717. // Disallow revocation checks over the network
  718. trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
  719. // no UI
  720. trustData.dwUIContext = 0;
  721. trustData.pFile = &fileToCheck;
  722. // The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate
  723. // chains up to a trusted root CA and has appropriate permissions to sign
  724. // code.
  725. GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
  726. // Check if the file is signed by something that is trusted. If the file is
  727. // not signed, this is a no-op.
  728. LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData);
  729. CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr;
  730. // According to the Windows documentation, we should check against 0 instead
  731. // of ERROR_SUCCESS, which is an HRESULT.
  732. if (ret == 0) {
  733. cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData);
  734. }
  735. if (cryptoProviderData) {
  736. // Lock because signature information is read on the main thread.
  737. MutexAutoLock lock(mLock);
  738. LOG(("Downloaded trusted and signed file [this = %p].", this));
  739. // A binary may have multiple signers. Each signer may have multiple certs
  740. // in the chain.
  741. for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) {
  742. const CERT_CHAIN_CONTEXT* certChainContext =
  743. cryptoProviderData->pasSigners[i].pChainContext;
  744. if (!certChainContext) {
  745. break;
  746. }
  747. for (DWORD j = 0; j < certChainContext->cChain; ++j) {
  748. const CERT_SIMPLE_CHAIN* certSimpleChain =
  749. certChainContext->rgpChain[j];
  750. if (!certSimpleChain) {
  751. break;
  752. }
  753. nsCOMPtr<nsIX509CertList> nssCertList =
  754. do_CreateInstance(NS_X509CERTLIST_CONTRACTID);
  755. if (!nssCertList) {
  756. break;
  757. }
  758. bool extractionSuccess = true;
  759. for (DWORD k = 0; k < certSimpleChain->cElement; ++k) {
  760. CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k];
  761. if (certChainElement->pCertContext->dwCertEncodingType !=
  762. X509_ASN_ENCODING) {
  763. continue;
  764. }
  765. nsCOMPtr<nsIX509Cert> nssCert = nullptr;
  766. rv = certDB->ConstructX509(
  767. reinterpret_cast<char *>(
  768. certChainElement->pCertContext->pbCertEncoded),
  769. certChainElement->pCertContext->cbCertEncoded,
  770. getter_AddRefs(nssCert));
  771. if (!nssCert) {
  772. extractionSuccess = false;
  773. LOG(("Couldn't create NSS cert [this = %p]", this));
  774. break;
  775. }
  776. nssCertList->AddCert(nssCert);
  777. nsString subjectName;
  778. nssCert->GetSubjectName(subjectName);
  779. LOG(("Adding cert %s [this = %p]",
  780. NS_ConvertUTF16toUTF8(subjectName).get(), this));
  781. }
  782. if (extractionSuccess) {
  783. mSignatureInfo.AppendObject(nssCertList);
  784. }
  785. }
  786. }
  787. // Free the provider data if cryptoProviderData is not null.
  788. trustData.dwStateAction = WTD_STATEACTION_CLOSE;
  789. WinVerifyTrust(nullptr, &policyGUID, &trustData);
  790. } else {
  791. LOG(("Downloaded unsigned or untrusted file [this = %p].", this));
  792. }
  793. #endif
  794. return NS_OK;
  795. }
  796. ////////////////////////////////////////////////////////////////////////////////
  797. //// BackgroundFileSaverOutputStream
  798. NS_IMPL_ISUPPORTS(BackgroundFileSaverOutputStream,
  799. nsIBackgroundFileSaver,
  800. nsIOutputStream,
  801. nsIAsyncOutputStream,
  802. nsIOutputStreamCallback)
  803. BackgroundFileSaverOutputStream::BackgroundFileSaverOutputStream()
  804. : BackgroundFileSaver()
  805. , mAsyncWaitCallback(nullptr)
  806. {
  807. }
  808. BackgroundFileSaverOutputStream::~BackgroundFileSaverOutputStream()
  809. {
  810. }
  811. bool
  812. BackgroundFileSaverOutputStream::HasInfiniteBuffer()
  813. {
  814. return false;
  815. }
  816. nsAsyncCopyProgressFun
  817. BackgroundFileSaverOutputStream::GetProgressCallback()
  818. {
  819. return nullptr;
  820. }
  821. NS_IMETHODIMP
  822. BackgroundFileSaverOutputStream::Close()
  823. {
  824. return mPipeOutputStream->Close();
  825. }
  826. NS_IMETHODIMP
  827. BackgroundFileSaverOutputStream::Flush()
  828. {
  829. return mPipeOutputStream->Flush();
  830. }
  831. NS_IMETHODIMP
  832. BackgroundFileSaverOutputStream::Write(const char *aBuf, uint32_t aCount,
  833. uint32_t *_retval)
  834. {
  835. return mPipeOutputStream->Write(aBuf, aCount, _retval);
  836. }
  837. NS_IMETHODIMP
  838. BackgroundFileSaverOutputStream::WriteFrom(nsIInputStream *aFromStream,
  839. uint32_t aCount, uint32_t *_retval)
  840. {
  841. return mPipeOutputStream->WriteFrom(aFromStream, aCount, _retval);
  842. }
  843. NS_IMETHODIMP
  844. BackgroundFileSaverOutputStream::WriteSegments(nsReadSegmentFun aReader,
  845. void *aClosure, uint32_t aCount,
  846. uint32_t *_retval)
  847. {
  848. return mPipeOutputStream->WriteSegments(aReader, aClosure, aCount, _retval);
  849. }
  850. NS_IMETHODIMP
  851. BackgroundFileSaverOutputStream::IsNonBlocking(bool *_retval)
  852. {
  853. return mPipeOutputStream->IsNonBlocking(_retval);
  854. }
  855. NS_IMETHODIMP
  856. BackgroundFileSaverOutputStream::CloseWithStatus(nsresult reason)
  857. {
  858. return mPipeOutputStream->CloseWithStatus(reason);
  859. }
  860. NS_IMETHODIMP
  861. BackgroundFileSaverOutputStream::AsyncWait(nsIOutputStreamCallback *aCallback,
  862. uint32_t aFlags,
  863. uint32_t aRequestedCount,
  864. nsIEventTarget *aEventTarget)
  865. {
  866. NS_ENSURE_STATE(!mAsyncWaitCallback);
  867. mAsyncWaitCallback = aCallback;
  868. return mPipeOutputStream->AsyncWait(this, aFlags, aRequestedCount,
  869. aEventTarget);
  870. }
  871. NS_IMETHODIMP
  872. BackgroundFileSaverOutputStream::OnOutputStreamReady(
  873. nsIAsyncOutputStream *aStream)
  874. {
  875. NS_ENSURE_STATE(mAsyncWaitCallback);
  876. nsCOMPtr<nsIOutputStreamCallback> asyncWaitCallback = nullptr;
  877. asyncWaitCallback.swap(mAsyncWaitCallback);
  878. return asyncWaitCallback->OnOutputStreamReady(this);
  879. }
  880. ////////////////////////////////////////////////////////////////////////////////
  881. //// BackgroundFileSaverStreamListener
  882. NS_IMPL_ISUPPORTS(BackgroundFileSaverStreamListener,
  883. nsIBackgroundFileSaver,
  884. nsIRequestObserver,
  885. nsIStreamListener)
  886. BackgroundFileSaverStreamListener::BackgroundFileSaverStreamListener()
  887. : BackgroundFileSaver()
  888. , mSuspensionLock("BackgroundFileSaverStreamListener.mSuspensionLock")
  889. , mReceivedTooMuchData(false)
  890. , mRequest(nullptr)
  891. , mRequestSuspended(false)
  892. {
  893. }
  894. BackgroundFileSaverStreamListener::~BackgroundFileSaverStreamListener()
  895. {
  896. }
  897. bool
  898. BackgroundFileSaverStreamListener::HasInfiniteBuffer()
  899. {
  900. return true;
  901. }
  902. nsAsyncCopyProgressFun
  903. BackgroundFileSaverStreamListener::GetProgressCallback()
  904. {
  905. return AsyncCopyProgressCallback;
  906. }
  907. NS_IMETHODIMP
  908. BackgroundFileSaverStreamListener::OnStartRequest(nsIRequest *aRequest,
  909. nsISupports *aContext)
  910. {
  911. NS_ENSURE_ARG(aRequest);
  912. return NS_OK;
  913. }
  914. NS_IMETHODIMP
  915. BackgroundFileSaverStreamListener::OnStopRequest(nsIRequest *aRequest,
  916. nsISupports *aContext,
  917. nsresult aStatusCode)
  918. {
  919. // If an error occurred, cancel the operation immediately. On success, wait
  920. // until the caller has determined whether the file should be renamed.
  921. if (NS_FAILED(aStatusCode)) {
  922. Finish(aStatusCode);
  923. }
  924. return NS_OK;
  925. }
  926. NS_IMETHODIMP
  927. BackgroundFileSaverStreamListener::OnDataAvailable(nsIRequest *aRequest,
  928. nsISupports *aContext,
  929. nsIInputStream *aInputStream,
  930. uint64_t aOffset,
  931. uint32_t aCount)
  932. {
  933. nsresult rv;
  934. NS_ENSURE_ARG(aRequest);
  935. // Read the requested data. Since the pipe has an infinite buffer, we don't
  936. // expect any write error to occur here.
  937. uint32_t writeCount;
  938. rv = mPipeOutputStream->WriteFrom(aInputStream, aCount, &writeCount);
  939. NS_ENSURE_SUCCESS(rv, rv);
  940. // If reading from the input stream fails for any reason, the pipe will return
  941. // a success code, but without reading all the data. Since we should be able
  942. // to read the requested data when OnDataAvailable is called, raise an error.
  943. if (writeCount < aCount) {
  944. NS_WARNING("Reading from the input stream should not have failed.");
  945. return NS_ERROR_UNEXPECTED;
  946. }
  947. bool stateChanged = false;
  948. {
  949. MutexAutoLock lock(mSuspensionLock);
  950. if (!mReceivedTooMuchData) {
  951. uint64_t available;
  952. nsresult rv = mPipeInputStream->Available(&available);
  953. if (NS_SUCCEEDED(rv) && available > REQUEST_SUSPEND_AT) {
  954. mReceivedTooMuchData = true;
  955. mRequest = aRequest;
  956. stateChanged = true;
  957. }
  958. }
  959. }
  960. if (stateChanged) {
  961. NotifySuspendOrResume();
  962. }
  963. return NS_OK;
  964. }
  965. // Called on the worker thread.
  966. // static
  967. void
  968. BackgroundFileSaverStreamListener::AsyncCopyProgressCallback(void *aClosure,
  969. uint32_t aCount)
  970. {
  971. BackgroundFileSaverStreamListener *self =
  972. (BackgroundFileSaverStreamListener *)aClosure;
  973. // Wait if the control thread is in the process of suspending or resuming.
  974. MutexAutoLock lock(self->mSuspensionLock);
  975. // This function is called when some bytes are consumed by NS_AsyncCopy. Each
  976. // time this happens, verify if a suspended request should be resumed, because
  977. // we have now consumed enough data.
  978. if (self->mReceivedTooMuchData) {
  979. uint64_t available;
  980. nsresult rv = self->mPipeInputStream->Available(&available);
  981. if (NS_FAILED(rv) || available < REQUEST_RESUME_AT) {
  982. self->mReceivedTooMuchData = false;
  983. // Post an event to verify if the request should be resumed.
  984. if (NS_FAILED(self->mControlThread->Dispatch(NewRunnableMethod(self,
  985. &BackgroundFileSaverStreamListener::NotifySuspendOrResume),
  986. NS_DISPATCH_NORMAL))) {
  987. NS_WARNING("Unable to post resume event to the control thread.");
  988. }
  989. }
  990. }
  991. }
  992. // Called on the control thread.
  993. nsresult
  994. BackgroundFileSaverStreamListener::NotifySuspendOrResume()
  995. {
  996. // Prevent the worker thread from changing state while processing.
  997. MutexAutoLock lock(mSuspensionLock);
  998. if (mReceivedTooMuchData) {
  999. if (!mRequestSuspended) {
  1000. // Try to suspend the request. If this fails, don't try to resume later.
  1001. if (NS_SUCCEEDED(mRequest->Suspend())) {
  1002. mRequestSuspended = true;
  1003. } else {
  1004. NS_WARNING("Unable to suspend the request.");
  1005. }
  1006. }
  1007. } else {
  1008. if (mRequestSuspended) {
  1009. // Resume the request only if we succeeded in suspending it.
  1010. if (NS_SUCCEEDED(mRequest->Resume())) {
  1011. mRequestSuspended = false;
  1012. } else {
  1013. NS_WARNING("Unable to resume the request.");
  1014. }
  1015. }
  1016. }
  1017. return NS_OK;
  1018. }
  1019. ////////////////////////////////////////////////////////////////////////////////
  1020. //// DigestOutputStream
  1021. NS_IMPL_ISUPPORTS(DigestOutputStream,
  1022. nsIOutputStream)
  1023. DigestOutputStream::DigestOutputStream(nsIOutputStream* aStream,
  1024. PK11Context* aContext) :
  1025. mOutputStream(aStream)
  1026. , mDigestContext(aContext)
  1027. {
  1028. MOZ_ASSERT(mDigestContext, "Can't have null digest context");
  1029. MOZ_ASSERT(mOutputStream, "Can't have null output stream");
  1030. }
  1031. DigestOutputStream::~DigestOutputStream()
  1032. {
  1033. nsNSSShutDownPreventionLock locker;
  1034. if (isAlreadyShutDown()) {
  1035. return;
  1036. }
  1037. shutdown(ShutdownCalledFrom::Object);
  1038. }
  1039. NS_IMETHODIMP
  1040. DigestOutputStream::Close()
  1041. {
  1042. return mOutputStream->Close();
  1043. }
  1044. NS_IMETHODIMP
  1045. DigestOutputStream::Flush()
  1046. {
  1047. return mOutputStream->Flush();
  1048. }
  1049. NS_IMETHODIMP
  1050. DigestOutputStream::Write(const char* aBuf, uint32_t aCount, uint32_t* retval)
  1051. {
  1052. nsNSSShutDownPreventionLock lock;
  1053. if (isAlreadyShutDown()) {
  1054. return NS_ERROR_NOT_AVAILABLE;
  1055. }
  1056. nsresult rv = MapSECStatus(
  1057. PK11_DigestOp(mDigestContext,
  1058. BitwiseCast<const unsigned char*, const char*>(aBuf),
  1059. aCount));
  1060. NS_ENSURE_SUCCESS(rv, rv);
  1061. return mOutputStream->Write(aBuf, aCount, retval);
  1062. }
  1063. NS_IMETHODIMP
  1064. DigestOutputStream::WriteFrom(nsIInputStream* aFromStream,
  1065. uint32_t aCount, uint32_t* retval)
  1066. {
  1067. // Not supported. We could read the stream to a buf, call DigestOp on the
  1068. // result, seek back and pass the stream on, but it's not worth it since our
  1069. // application (NS_AsyncCopy) doesn't invoke this on the sink.
  1070. MOZ_CRASH("DigestOutputStream::WriteFrom not implemented");
  1071. }
  1072. NS_IMETHODIMP
  1073. DigestOutputStream::WriteSegments(nsReadSegmentFun aReader,
  1074. void *aClosure, uint32_t aCount,
  1075. uint32_t *retval)
  1076. {
  1077. MOZ_CRASH("DigestOutputStream::WriteSegments not implemented");
  1078. }
  1079. NS_IMETHODIMP
  1080. DigestOutputStream::IsNonBlocking(bool *retval)
  1081. {
  1082. return mOutputStream->IsNonBlocking(retval);
  1083. }
  1084. #undef LOG_ENABLED
  1085. } // namespace net
  1086. } // namespace mozilla