nsDeleteDir.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim:set ts=2 sw=2 sts=2 et cindent: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include "nsDeleteDir.h"
  7. #include "nsIFile.h"
  8. #include "nsString.h"
  9. #include "mozilla/Telemetry.h"
  10. #include "nsITimer.h"
  11. #include "nsISimpleEnumerator.h"
  12. #include "nsAutoPtr.h"
  13. #include "nsThreadUtils.h"
  14. #include "nsISupportsPriority.h"
  15. #include "nsCacheUtils.h"
  16. #include "prtime.h"
  17. #include <time.h>
  18. using namespace mozilla;
  19. class nsBlockOnBackgroundThreadEvent : public Runnable {
  20. public:
  21. nsBlockOnBackgroundThreadEvent() {}
  22. NS_IMETHOD Run() override
  23. {
  24. MutexAutoLock lock(nsDeleteDir::gInstance->mLock);
  25. nsDeleteDir::gInstance->mNotified = true;
  26. nsDeleteDir::gInstance->mCondVar.Notify();
  27. return NS_OK;
  28. }
  29. };
  30. nsDeleteDir * nsDeleteDir::gInstance = nullptr;
  31. nsDeleteDir::nsDeleteDir()
  32. : mLock("nsDeleteDir.mLock"),
  33. mCondVar(mLock, "nsDeleteDir.mCondVar"),
  34. mNotified(false),
  35. mShutdownPending(false),
  36. mStopDeleting(false)
  37. {
  38. NS_ASSERTION(gInstance==nullptr, "multiple nsCacheService instances!");
  39. }
  40. nsDeleteDir::~nsDeleteDir()
  41. {
  42. gInstance = nullptr;
  43. }
  44. nsresult
  45. nsDeleteDir::Init()
  46. {
  47. if (gInstance)
  48. return NS_ERROR_ALREADY_INITIALIZED;
  49. gInstance = new nsDeleteDir();
  50. return NS_OK;
  51. }
  52. nsresult
  53. nsDeleteDir::Shutdown(bool finishDeleting)
  54. {
  55. if (!gInstance)
  56. return NS_ERROR_NOT_INITIALIZED;
  57. nsCOMArray<nsIFile> dirsToRemove;
  58. nsCOMPtr<nsIThread> thread;
  59. {
  60. MutexAutoLock lock(gInstance->mLock);
  61. NS_ASSERTION(!gInstance->mShutdownPending,
  62. "Unexpected state in nsDeleteDir::Shutdown()");
  63. gInstance->mShutdownPending = true;
  64. if (!finishDeleting)
  65. gInstance->mStopDeleting = true;
  66. // remove all pending timers
  67. for (int32_t i = gInstance->mTimers.Count(); i > 0; i--) {
  68. nsCOMPtr<nsITimer> timer = gInstance->mTimers[i-1];
  69. gInstance->mTimers.RemoveObjectAt(i-1);
  70. nsCOMArray<nsIFile> *arg;
  71. timer->GetClosure((reinterpret_cast<void**>(&arg)));
  72. timer->Cancel();
  73. if (finishDeleting)
  74. dirsToRemove.AppendObjects(*arg);
  75. // delete argument passed to the timer
  76. delete arg;
  77. }
  78. thread.swap(gInstance->mThread);
  79. if (thread) {
  80. // dispatch event and wait for it to run and notify us, so we know thread
  81. // has completed all work and can be shutdown
  82. nsCOMPtr<nsIRunnable> event = new nsBlockOnBackgroundThreadEvent();
  83. nsresult rv = thread->Dispatch(event, NS_DISPATCH_NORMAL);
  84. if (NS_FAILED(rv)) {
  85. NS_WARNING("Failed dispatching block-event");
  86. return NS_ERROR_UNEXPECTED;
  87. }
  88. gInstance->mNotified = false;
  89. while (!gInstance->mNotified) {
  90. gInstance->mCondVar.Wait();
  91. }
  92. nsShutdownThread::BlockingShutdown(thread);
  93. }
  94. }
  95. delete gInstance;
  96. for (int32_t i = 0; i < dirsToRemove.Count(); i++)
  97. dirsToRemove[i]->Remove(true);
  98. return NS_OK;
  99. }
  100. nsresult
  101. nsDeleteDir::InitThread()
  102. {
  103. if (mThread)
  104. return NS_OK;
  105. nsresult rv = NS_NewNamedThread("Cache Deleter", getter_AddRefs(mThread));
  106. if (NS_FAILED(rv)) {
  107. NS_WARNING("Can't create background thread");
  108. return rv;
  109. }
  110. nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mThread);
  111. if (p) {
  112. p->SetPriority(nsISupportsPriority::PRIORITY_LOWEST);
  113. }
  114. return NS_OK;
  115. }
  116. void
  117. nsDeleteDir::DestroyThread()
  118. {
  119. if (!mThread)
  120. return;
  121. if (mTimers.Count())
  122. // more work to do, so don't delete thread.
  123. return;
  124. nsShutdownThread::Shutdown(mThread);
  125. mThread = nullptr;
  126. }
  127. void
  128. nsDeleteDir::TimerCallback(nsITimer *aTimer, void *arg)
  129. {
  130. {
  131. MutexAutoLock lock(gInstance->mLock);
  132. int32_t idx = gInstance->mTimers.IndexOf(aTimer);
  133. if (idx == -1) {
  134. // Timer was canceled and removed during shutdown.
  135. return;
  136. }
  137. gInstance->mTimers.RemoveObjectAt(idx);
  138. }
  139. nsAutoPtr<nsCOMArray<nsIFile> > dirList;
  140. dirList = static_cast<nsCOMArray<nsIFile> *>(arg);
  141. bool shuttingDown = false;
  142. // Intentional extra braces to control variable sope.
  143. {
  144. // Low IO priority can only be set when running in the context of the
  145. // current thread. So this shouldn't be moved to where we set the priority
  146. // of the Cache deleter thread using the nsThread's NSPR priority constants.
  147. nsAutoLowPriorityIO autoLowPriority;
  148. for (int32_t i = 0; i < dirList->Count() && !shuttingDown; i++) {
  149. gInstance->RemoveDir((*dirList)[i], &shuttingDown);
  150. }
  151. }
  152. {
  153. MutexAutoLock lock(gInstance->mLock);
  154. gInstance->DestroyThread();
  155. }
  156. }
  157. nsresult
  158. nsDeleteDir::DeleteDir(nsIFile *dirIn, bool moveToTrash, uint32_t delay)
  159. {
  160. if (!gInstance)
  161. return NS_ERROR_NOT_INITIALIZED;
  162. nsresult rv;
  163. nsCOMPtr<nsIFile> trash, dir;
  164. // Need to make a clone of this since we don't want to modify the input
  165. // file object.
  166. rv = dirIn->Clone(getter_AddRefs(dir));
  167. if (NS_FAILED(rv))
  168. return rv;
  169. if (moveToTrash) {
  170. rv = GetTrashDir(dir, &trash);
  171. if (NS_FAILED(rv))
  172. return rv;
  173. nsAutoCString origLeaf;
  174. rv = trash->GetNativeLeafName(origLeaf);
  175. if (NS_FAILED(rv))
  176. return rv;
  177. // Append random number to the trash directory and check if it exists.
  178. srand(static_cast<unsigned>(PR_Now()));
  179. nsAutoCString leaf;
  180. for (int32_t i = 0; i < 10; i++) {
  181. leaf = origLeaf;
  182. leaf.AppendInt(rand());
  183. rv = trash->SetNativeLeafName(leaf);
  184. if (NS_FAILED(rv))
  185. return rv;
  186. bool exists;
  187. if (NS_SUCCEEDED(trash->Exists(&exists)) && !exists) {
  188. break;
  189. }
  190. leaf.Truncate();
  191. }
  192. // Fail if we didn't find unused trash directory within the limit
  193. if (!leaf.Length())
  194. return NS_ERROR_FAILURE;
  195. // Important: must rename directory w/o changing parent directory: else on
  196. // NTFS we'll wait (with cache lock) while nsIFile's ACL reset walks file
  197. // tree: was hanging GUI for *minutes* on large cache dirs.
  198. rv = dir->MoveToNative(nullptr, leaf);
  199. if (NS_FAILED(rv))
  200. return rv;
  201. } else {
  202. // we want to pass a clone of the original off to the worker thread.
  203. trash.swap(dir);
  204. }
  205. nsAutoPtr<nsCOMArray<nsIFile> > arg(new nsCOMArray<nsIFile>);
  206. arg->AppendObject(trash);
  207. rv = gInstance->PostTimer(arg, delay);
  208. if (NS_FAILED(rv))
  209. return rv;
  210. arg.forget();
  211. return NS_OK;
  212. }
  213. nsresult
  214. nsDeleteDir::GetTrashDir(nsIFile *target, nsCOMPtr<nsIFile> *result)
  215. {
  216. nsresult rv;
  217. {
  218. rv = target->Clone(getter_AddRefs(*result));
  219. }
  220. if (NS_FAILED(rv))
  221. return rv;
  222. nsAutoCString leaf;
  223. rv = (*result)->GetNativeLeafName(leaf);
  224. if (NS_FAILED(rv))
  225. return rv;
  226. leaf.AppendLiteral(".Trash");
  227. return (*result)->SetNativeLeafName(leaf);
  228. }
  229. nsresult
  230. nsDeleteDir::RemoveOldTrashes(nsIFile *cacheDir)
  231. {
  232. if (!gInstance)
  233. return NS_ERROR_NOT_INITIALIZED;
  234. nsresult rv;
  235. nsCOMPtr<nsIFile> trash;
  236. rv = GetTrashDir(cacheDir, &trash);
  237. if (NS_FAILED(rv))
  238. return rv;
  239. nsAutoString trashName;
  240. rv = trash->GetLeafName(trashName);
  241. if (NS_FAILED(rv))
  242. return rv;
  243. nsCOMPtr<nsIFile> parent;
  244. rv = cacheDir->GetParent(getter_AddRefs(parent));
  245. if (NS_FAILED(rv))
  246. return rv;
  247. nsCOMPtr<nsISimpleEnumerator> iter;
  248. rv = parent->GetDirectoryEntries(getter_AddRefs(iter));
  249. if (NS_FAILED(rv))
  250. return rv;
  251. bool more;
  252. nsCOMPtr<nsISupports> elem;
  253. nsAutoPtr<nsCOMArray<nsIFile> > dirList;
  254. while (NS_SUCCEEDED(iter->HasMoreElements(&more)) && more) {
  255. rv = iter->GetNext(getter_AddRefs(elem));
  256. if (NS_FAILED(rv))
  257. continue;
  258. nsCOMPtr<nsIFile> file = do_QueryInterface(elem);
  259. if (!file)
  260. continue;
  261. nsAutoString leafName;
  262. rv = file->GetLeafName(leafName);
  263. if (NS_FAILED(rv))
  264. continue;
  265. // match all names that begin with the trash name (i.e. "Cache.Trash")
  266. if (Substring(leafName, 0, trashName.Length()).Equals(trashName)) {
  267. if (!dirList)
  268. dirList = new nsCOMArray<nsIFile>;
  269. dirList->AppendObject(file);
  270. }
  271. }
  272. if (dirList) {
  273. rv = gInstance->PostTimer(dirList, 90000);
  274. if (NS_FAILED(rv))
  275. return rv;
  276. dirList.forget();
  277. }
  278. return NS_OK;
  279. }
  280. nsresult
  281. nsDeleteDir::PostTimer(void *arg, uint32_t delay)
  282. {
  283. nsresult rv;
  284. nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
  285. if (NS_FAILED(rv))
  286. return NS_ERROR_UNEXPECTED;
  287. MutexAutoLock lock(mLock);
  288. rv = InitThread();
  289. if (NS_FAILED(rv))
  290. return rv;
  291. rv = timer->SetTarget(mThread);
  292. if (NS_FAILED(rv))
  293. return rv;
  294. rv = timer->InitWithFuncCallback(TimerCallback, arg, delay,
  295. nsITimer::TYPE_ONE_SHOT);
  296. if (NS_FAILED(rv))
  297. return rv;
  298. mTimers.AppendObject(timer);
  299. return NS_OK;
  300. }
  301. nsresult
  302. nsDeleteDir::RemoveDir(nsIFile *file, bool *stopDeleting)
  303. {
  304. nsresult rv;
  305. bool isLink;
  306. rv = file->IsSymlink(&isLink);
  307. if (NS_FAILED(rv) || isLink)
  308. return NS_ERROR_UNEXPECTED;
  309. bool isDir;
  310. rv = file->IsDirectory(&isDir);
  311. if (NS_FAILED(rv))
  312. return rv;
  313. if (isDir) {
  314. nsCOMPtr<nsISimpleEnumerator> iter;
  315. rv = file->GetDirectoryEntries(getter_AddRefs(iter));
  316. if (NS_FAILED(rv))
  317. return rv;
  318. bool more;
  319. nsCOMPtr<nsISupports> elem;
  320. while (NS_SUCCEEDED(iter->HasMoreElements(&more)) && more) {
  321. rv = iter->GetNext(getter_AddRefs(elem));
  322. if (NS_FAILED(rv)) {
  323. NS_WARNING("Unexpected failure in nsDeleteDir::RemoveDir");
  324. continue;
  325. }
  326. nsCOMPtr<nsIFile> file2 = do_QueryInterface(elem);
  327. if (!file2) {
  328. NS_WARNING("Unexpected failure in nsDeleteDir::RemoveDir");
  329. continue;
  330. }
  331. RemoveDir(file2, stopDeleting);
  332. // No check for errors to remove as much as possible
  333. if (*stopDeleting)
  334. return NS_OK;
  335. }
  336. }
  337. file->Remove(false);
  338. // No check for errors to remove as much as possible
  339. MutexAutoLock lock(mLock);
  340. if (mStopDeleting)
  341. *stopDeleting = true;
  342. return NS_OK;
  343. }