File: nuke_profile_directory_utils.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (175 lines) | stat: -rw-r--r-- 6,925 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/nuke_profile_directory_utils.h"

#include <map>

#include "base/check_op.h"
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/values_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"

namespace {

// Used in metrics for NukeProfileFromDisk(). Keep in sync with enums.xml.
//
// Entries should not be renumbered and numeric values should never be reused.
//
// Note: there are maximum 3 attempts to nuke a profile.
enum class NukeProfileResult {
  // Success values. Make sure they are consecutive.
  kSuccessFirstAttempt = 0,
  kSuccessSecondAttempt = 1,
  kSuccessThirdAttempt = 2,

  // Failure values. Make sure they are consecutive.
  kFailureFirstAttempt = 10,
  kFailureSecondAttempt = 11,
  kFailureThirdAttempt = 12,
  kMaxValue = kFailureThirdAttempt,
};

const size_t kNukeProfileMaxRetryCount = 3;

// Profile deletion can pass through two stages:
enum class ProfileDeletionStage {
  // At SCHEDULING stage some actions are made before profile deletion,
  // where one of them is the closure of browser windows. Deletion is cancelled
  // if the user choose explicitly not to close any of the tabs.
  SCHEDULING,
  // At MARKED stage profile can be safely removed from disk.
  MARKED
};

using ProfileDeletionMap = std::map<base::FilePath, ProfileDeletionStage>;
ProfileDeletionMap& ProfilesToDelete() {
  static base::NoDestructor<ProfileDeletionMap> profiles_to_delete;
  return *profiles_to_delete;
}

NukeProfileResult GetNukeProfileResult(size_t retry_count, bool success) {
  DCHECK_LT(retry_count, kNukeProfileMaxRetryCount);
  const size_t value =
      retry_count +
      static_cast<size_t>(success ? NukeProfileResult::kSuccessFirstAttempt
                                  : NukeProfileResult::kFailureFirstAttempt);
  DCHECK_LE(value, static_cast<size_t>(NukeProfileResult::kMaxValue));
  return static_cast<NukeProfileResult>(value);
}

// Implementation of NukeProfileFromDisk(), retrying at most |max_retry_count|
// times on failure. |retry_count| (initially 0) keeps track of the
// number of attempts so far.
void NukeProfileFromDiskImpl(const base::FilePath& profile_path,
                             size_t retry_count,
                             size_t max_retry_count,
                             base::OnceClosure done_callback) {
  // TODO(crbug.com/40756611): Make FileSystemProxy/FileSystemImpl expose its
  // LockTable, and/or fire events when locks are released. That way we could
  // wait for all the locks in |profile_path| to be released, rather than having
  // this retry logic.
  const base::TimeDelta kRetryDelay = base::Seconds(1);

  // Delete both the profile directory and its corresponding cache.
  base::FilePath cache_path;
  chrome::GetUserCacheDirectory(profile_path, &cache_path);

  bool success = base::DeletePathRecursively(profile_path);
  success = base::DeletePathRecursively(cache_path) && success;

  base::UmaHistogramEnumeration("Profile.NukeFromDisk.Result",
                                GetNukeProfileResult(retry_count, success));

  if (!success && retry_count < max_retry_count - 1) {
    // Failed, try again in |kRetryDelay| seconds.
    base::ThreadPool::PostDelayedTask(
        FROM_HERE,
        {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
         base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
        base::BindOnce(&NukeProfileFromDiskImpl, profile_path, retry_count + 1,
                       max_retry_count, std::move(done_callback)),
        kRetryDelay);
    return;
  }

  if (done_callback) {
    content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
                                                 std::move(done_callback));
  }
}

}  // namespace

void NukeDeletedProfilesFromDisk() {
  for (const auto& item : ProfilesToDelete()) {
    if (item.second == ProfileDeletionStage::MARKED) {
      NukeProfileFromDiskImpl(item.first, /*retry_count=*/0,
                              /*max_retry_count=*/1, base::OnceClosure());
    }
  }
  ProfilesToDelete().clear();
}

void NukeProfileFromDisk(const base::FilePath& profile_path,
                         base::OnceClosure done_callback) {
  NukeProfileFromDiskImpl(profile_path, /*retry_count=*/0,
                          kNukeProfileMaxRetryCount, std::move(done_callback));
}

bool IsProfileDirectoryMarkedForDeletion(const base::FilePath& profile_path) {
  const auto it = ProfilesToDelete().find(profile_path);
  return it != ProfilesToDelete().end() &&
         it->second == ProfileDeletionStage::MARKED;
}

void CancelProfileDeletion(const base::FilePath& path) {
  DCHECK(!base::Contains(ProfilesToDelete(), path) ||
         ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING);
  ProfilesToDelete().erase(path);
  ProfileMetrics::LogProfileDeleteUser(ProfileMetrics::DELETE_PROFILE_ABORTED);
}

// Schedule a profile for deletion if it isn't already scheduled.
// Returns whether the profile has been newly scheduled.
bool ScheduleProfileDirectoryForDeletion(const base::FilePath& path) {
  if (base::Contains(ProfilesToDelete(), path))
    return false;
  ProfilesToDelete()[path] = ProfileDeletionStage::SCHEDULING;
  return true;
}

void MarkProfileDirectoryForDeletion(const base::FilePath& path) {
  DCHECK(!base::Contains(ProfilesToDelete(), path) ||
         ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING);
  ProfilesToDelete()[path] = ProfileDeletionStage::MARKED;
  // Remember that this profile was deleted and files should have been deleted
  // on shutdown. In case of a crash remaining files are removed on next start.
  ScopedListPrefUpdate deleted_profiles(g_browser_process->local_state(),
                                        prefs::kProfilesDeleted);
  deleted_profiles->Append(base::FilePathToValue(path));

  // Set profile as ephemeral.
  ProfileAttributesEntry* entry = g_browser_process->profile_manager()
                                      ->GetProfileAttributesStorage()
                                      .GetProfileAttributesWithPath(path);
  if (!entry->IsEphemeral()) {
    entry->SetIsEphemeral(true);
    entry->SetIsOmitted(true);
  }
}