File: crx_cache.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (360 lines) | stat: -rw-r--r-- 12,472 bytes parent folder | download | duplicates (5)
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// 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 "components/update_client/crx_cache.h"

#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "base/check.h"
#include "base/containers/contains.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/path_service.h"
#include "base/sequence_checker.h"
#include "base/strings/strcat.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequence_bound.h"
#include "base/types/expected.h"
#include "components/prefs/json_pref_store.h"
#include "components/update_client/update_client_errors.h"
#include "third_party/abseil-cpp/absl/container/flat_hash_set.h"

namespace update_client {

// Intended to be used in a base::SequenceBound: functions may block.
class CrxCacheSynchronous {
 public:
  virtual ~CrxCacheSynchronous() = default;
  virtual std::multimap<std::string, std::string> ListHashesByAppId() const = 0;
  virtual base::expected<base::FilePath, UnpackerError> GetByHash(
      const std::string& hash) const = 0;
  virtual base::expected<base::FilePath, UnpackerError> GetByFp(
      const std::string& fp) const = 0;
  virtual base::expected<base::FilePath, UnpackerError> Put(
      const base::FilePath& file,
      const std::string& app_id,
      const std::string& hash,
      const std::string& fp) = 0;
  virtual void RemoveAll(const std::string& app_id) = 0;
  virtual void RemoveIfNot(const std::vector<std::string>& app_ids) = 0;
};

// CrxCacheImpl uses a metadata.json file of the following format:
// {
//   "hashes": {
//     "hash1": {"appid": "appid1", "fp": "fingerprint1"},
//     "hash2": {"appid": "appid1", "fp": "fingerprint1"},
//      ...
//   }
// }
// and stores files at:
//   cache_root/hash1
//   cache_root/hash2
//   ...
class CrxCacheImpl : public CrxCacheSynchronous {
 public:
  CrxCacheImpl(const CrxCacheImpl&) = delete;
  CrxCacheImpl& operator=(const CrxCacheImpl&) = delete;

  explicit CrxCacheImpl(const base::FilePath& cache_root);
  ~CrxCacheImpl() override;

  // Overrides for CrxCacheSynchronous:
  std::multimap<std::string, std::string> ListHashesByAppId() const override;
  base::expected<base::FilePath, UnpackerError> GetByHash(
      const std::string& hash) const override;
  base::expected<base::FilePath, UnpackerError> GetByFp(
      const std::string& fp) const override;
  base::expected<base::FilePath, UnpackerError> Put(
      const base::FilePath& file,
      const std::string& app_id,
      const std::string& hash,
      const std::string& fp) override;
  void RemoveAll(const std::string& app_id) override;
  void RemoveIfNot(const std::vector<std::string>& app_ids) override;

 private:
  void Remove(const std::string& hash);

  SEQUENCE_CHECKER(sequence_checker_);
  const base::FilePath cache_root_;
  scoped_refptr<JsonPrefStore> metadata_;
};

CrxCacheImpl::CrxCacheImpl(const base::FilePath& cache_root)
    : cache_root_(cache_root),
      metadata_(base::MakeRefCounted<JsonPrefStore>(
          cache_root_.Append(FILE_PATH_LITERAL("metadata.json")))) {
  base::CreateDirectory(cache_root_);
  metadata_->ReadPrefs();
  absl::flat_hash_set<std::string> expected_basenames({"metadata.json"});
  absl::flat_hash_set<std::string> found_basenames;
  const base::Value* hashes_key = nullptr;
  if (!metadata_->GetValue("hashes", &hashes_key) || !hashes_key->is_dict()) {
    base::Value::Dict empty_dict;
    metadata_->SetValue("hashes", base::Value(std::move(empty_dict)), 0);
    CHECK(metadata_->GetValue("hashes", &hashes_key) && hashes_key->is_dict());
  }
  for (const auto [hash, value] : hashes_key->GetDict()) {
    expected_basenames.insert(hash);
  }

  // Remove files that are missing metadata entries.
  base::FileEnumerator(cache_root_, false, base::FileEnumerator::FILES)
      .ForEach([&expected_basenames,
                &found_basenames](const base::FilePath& file_path) {
        if (!base::Contains(expected_basenames,
                            file_path.BaseName().AsUTF8Unsafe())) {
          base::DeleteFile(file_path);
        } else {
          found_basenames.insert(file_path.BaseName().AsUTF8Unsafe());
        }
      });

  // Remove metadata entries that are missing files.
  for (const auto& hash : expected_basenames) {
    if (!base::Contains(found_basenames, hash)) {
      Remove(hash);
    }
  }
}

// Note: `~JsonPrefStore` calls `JsonPrefStore::CommitPendingWrite()`.
CrxCacheImpl::~CrxCacheImpl() = default;

std::multimap<std::string, std::string> CrxCacheImpl::ListHashesByAppId()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  std::multimap<std::string, std::string> hashes;
  const base::Value* hashes_key = nullptr;
  if (!metadata_->GetValue("hashes", &hashes_key) || !hashes_key->is_dict()) {
    return hashes;
  }
  for (const auto [hash, value] : hashes_key->GetDict()) {
    if (value.is_dict()) {
      const std::string* item_appid = value.GetDict().FindString("appid");
      if (item_appid) {
        hashes.insert({*item_appid, hash});
      }
    }
  }
  return hashes;
}

base::expected<base::FilePath, UnpackerError> CrxCacheImpl::GetByHash(
    const std::string& hash) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  const base::Value* hashes_key = nullptr;
  if (!metadata_->GetValue("hashes", &hashes_key) || !hashes_key->is_dict()) {
    return base::unexpected(UnpackerError::kCrxCacheMetadataCorrupted);
  }
  if (!hashes_key->GetDict().contains(hash)) {
    return base::unexpected(UnpackerError::kCrxCacheFileNotCached);
  }
  return cache_root_.AppendUTF8(hash);
}

base::expected<base::FilePath, UnpackerError> CrxCacheImpl::GetByFp(
    const std::string& fp) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  const base::Value* hashes_key = nullptr;
  if (!metadata_->GetValue("hashes", &hashes_key) || !hashes_key->is_dict()) {
    return base::unexpected(UnpackerError::kCrxCacheMetadataCorrupted);
  }
  for (const auto [hash, value] : hashes_key->GetDict()) {
    if (value.is_dict()) {
      const std::string* item_fp = value.GetDict().FindString("fp");
      if (item_fp && fp == *item_fp) {
        return cache_root_.AppendUTF8(hash);
      }
    }
  }
  return base::unexpected(UnpackerError::kCrxCacheFileNotCached);
}

base::expected<base::FilePath, UnpackerError> CrxCacheImpl::Put(
    const base::FilePath& file,
    const std::string& app_id,
    const std::string& hash,
    const std::string& fp) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::FilePath dest = cache_root_.AppendUTF8(hash);
  if (file == dest) {
    return dest;  // Already cached.
  }

  RemoveAll(app_id);
  if (!base::CreateDirectory(cache_root_)) {
    return base::unexpected(UnpackerError::kFailedToCreateCacheDir);
  }
  if (!base::Move(file, dest)) {
    return base::unexpected(UnpackerError::kFailedToAddToCache);
  }

  // Update metadata.
  base::Value::Dict data;
  data.Set("appid", app_id);
  data.Set("fp", fp);
  metadata_->SetValue(base::StrCat({"hashes.", hash}),
                      base::Value(std::move(data)), 0);
  return dest;
}

void CrxCacheImpl::RemoveAll(const std::string& app_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  absl::flat_hash_set<std::string> eviction_hashes;
  const base::Value* hashes_key = nullptr;
  if (!metadata_->GetValue("hashes", &hashes_key) || !hashes_key->is_dict()) {
    return;
  }
  for (const auto [hash, value] : hashes_key->GetDict()) {
    if (value.is_dict()) {
      const std::string* item_app_id = value.GetDict().FindString("appid");
      if (item_app_id && app_id == *item_app_id) {
        eviction_hashes.insert(hash);
      }
    }
  }
  for (const auto& hash : eviction_hashes) {
    Remove(hash);
  }
}

void CrxCacheImpl::RemoveIfNot(const std::vector<std::string>& app_ids) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  absl::flat_hash_set<std::string> retained_ids(app_ids.begin(), app_ids.end());
  for (const auto& [id, hash] : ListHashesByAppId()) {
    if (!base::Contains(retained_ids, id)) {
      RemoveAll(id);
    }
  }
}

void CrxCacheImpl::Remove(const std::string& hash) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::DeleteFile(cache_root_.AppendUTF8(hash));
  metadata_->RemoveValue(base::StrCat({"hashes.", hash}), 0);
}

// CrxCacheError implements CrxCache but always returns an error.
class CrxCacheError : public CrxCacheSynchronous {
 public:
  CrxCacheError(const CrxCacheError&) = delete;
  CrxCacheError& operator=(const CrxCacheError&) = delete;

  CrxCacheError() = default;
  ~CrxCacheError() override = default;

  // Overrides for CrxCache:
  std::multimap<std::string, std::string> ListHashesByAppId() const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return {};
  }
  base::expected<base::FilePath, UnpackerError> GetByHash(
      const std::string& hash) const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return base::unexpected(UnpackerError::kCrxCacheNotProvided);
  }
  base::expected<base::FilePath, UnpackerError> GetByFp(
      const std::string& fp) const override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return base::unexpected(UnpackerError::kCrxCacheNotProvided);
  }
  base::expected<base::FilePath, UnpackerError> Put(
      const base::FilePath& file,
      const std::string& app_id,
      const std::string& hash,
      const std::string& fp) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return base::unexpected(UnpackerError::kCrxCacheNotProvided);
  }
  void RemoveAll(const std::string& app_id) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }
  void RemoveIfNot(const std::vector<std::string>& app_ids) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }

 private:
  SEQUENCE_CHECKER(sequence_checker_);
};

CrxCache::CrxCache(std::optional<base::FilePath> path) {
  if (path) {
    delegate_ = base::SequenceBound<CrxCacheImpl>(
        base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}), *path);
  } else {
    delegate_ = base::SequenceBound<CrxCacheError>(
        base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}));
  }
}

CrxCache::~CrxCache() = default;

void CrxCache::ListHashesByAppId(
    base::OnceCallback<void(const std::multimap<std::string, std::string>&)>
        callback) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::ListHashesByAppId)
      .Then(std::move(callback));
}

void CrxCache::GetByHash(
    const std::string& hash,
    base::OnceCallback<void(base::expected<base::FilePath, UnpackerError>)>
        callback) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::GetByHash)
      .WithArgs(hash)
      .Then(std::move(callback));
}

void CrxCache::GetByFp(
    const std::string& fp,
    base::OnceCallback<void(base::expected<base::FilePath, UnpackerError>)>
        callback) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::GetByFp)
      .WithArgs(fp)
      .Then(std::move(callback));
}

void CrxCache::Put(
    const base::FilePath& file,
    const std::string& app_id,
    const std::string& hash,
    const std::string& fp,
    base::OnceCallback<void(base::expected<base::FilePath, UnpackerError>)>
        callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::Put)
      .WithArgs(file, app_id, hash, fp)
      .Then(std::move(callback));
}

void CrxCache::RemoveAll(const std::string& app_id,
                         base::OnceClosure callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::RemoveAll)
      .WithArgs(app_id)
      .Then(std::move(callback));
}

void CrxCache::RemoveIfNot(const std::vector<std::string>& app_ids,
                           base::OnceClosure callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  delegate_.AsyncCall(&CrxCacheSynchronous::RemoveIfNot)
      .WithArgs(app_ids)
      .Then(std::move(callback));
}

}  // namespace update_client