File: extension_updater.h

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 (440 lines) | stat: -rw-r--r-- 17,131 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_EXTENSIONS_UPDATER_EXTENSION_UPDATER_H_
#define CHROME_BROWSER_EXTENSIONS_UPDATER_EXTENSION_UPDATER_H_

#include <list>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>

#include "base/auto_reset.h"
#include "base/callback_list.h"
#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "base/unguessable_token.h"
#include "components/keyed_service/core/keyed_service.h"
#include "extensions/browser/extension_registry_observer.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/update_observer.h"
#include "extensions/browser/updater/extension_downloader.h"
#include "extensions/browser/updater/extension_downloader_delegate.h"
#include "extensions/browser/updater/extension_downloader_types.h"
#include "extensions/browser/updater/extension_update_data.h"
#include "extensions/browser/updater/update_service.h"
#include "extensions/buildflags/buildflags.h"
#include "extensions/common/extension_id.h"
#include "url/gurl.h"

static_assert(BUILDFLAG(ENABLE_EXTENSIONS_CORE));

class PrefService;
class Profile;
class ScopedProfileKeepAlive;

namespace content {
class BrowserContext;
}

namespace extensions {

class CorruptedExtensionReinstaller;
class CrxInstallError;
class CrxInstaller;
class DelayedInstallManager;
class Extension;
class ExtensionCache;
class ExtensionPrefs;
class ExtensionRegistrar;
class ExtensionRegistry;
class ExtensionSet;
struct ExtensionUpdateCheckParams;
class ExtensionUpdaterTest;
class ExternalInstallManager;
class PendingExtensionManager;

// A class for doing auto-updates of installed Extensions. Used like this:
//
// ExtensionUpdater* updater = ExtensionUpdater::Get(profile);
// updater->Start();
// ....
// updater->Stop();
class ExtensionUpdater : public KeyedService,
                         public ExtensionDownloaderDelegate {
 public:
  using FinishedCallback = base::OnceClosure;

  struct CheckParams {
    // Creates a default CheckParams instance that checks for all extensions.
    CheckParams();
    ~CheckParams();

    CheckParams(const CheckParams& other) = delete;
    CheckParams& operator=(const CheckParams& other) = delete;

    CheckParams(CheckParams&& other);
    CheckParams& operator=(CheckParams&& other);

    // The set of extensions that should be checked for updates. If empty
    // all extensions will be included in the update check.
    std::list<ExtensionId> ids;

    // Normally extension updates get installed only when the extension is idle.
    // Setting this to true causes any updates that are found to be installed
    // right away.
    bool install_immediately = false;

    // An extension update check can be originated by a user or by a scheduled
    // task. When the value of |fetch_priority| is FOREGROUND, the update
    // request was initiated by a user.
    DownloadFetchPriority fetch_priority = DownloadFetchPriority::kBackground;

    // If set, will be called when an update is found and before an attempt to
    // download and install it is made.
    UpdateFoundCallback update_found_callback;

    // Callback to call when the update check is complete. Can be null, if
    // you're not interested in when this happens.
    FinishedCallback callback;
  };

  // A class for use in tests to skip scheduled update checks for extensions
  // during the lifetime of an instance of it. Only one instance should be alive
  // at any given time.
  class ScopedSkipScheduledCheckForTest {
   public:
    ScopedSkipScheduledCheckForTest();

    ScopedSkipScheduledCheckForTest(const ScopedSkipScheduledCheckForTest&) =
        delete;
    ScopedSkipScheduledCheckForTest& operator=(
        const ScopedSkipScheduledCheckForTest&) = delete;

    ~ScopedSkipScheduledCheckForTest();
  };

  class CrxInstallerFactoryForTest {
   public:
    // Allows overriding the behavior of CreateUpdateInstaller().
    virtual scoped_refptr<CrxInstaller> CreateUpdateInstaller(
        const CRXFileInfo& file,
        bool file_ownership_passed) = 0;

    virtual ~CrxInstallerFactoryForTest() = default;
  };

  // Returns the ExtensionUpdater instance created by ExtensionUpdaterFactory.
  static ExtensionUpdater* Get(content::BrowserContext* browser_context);

  // Visible for testing. Production code should use Get() above.
  explicit ExtensionUpdater(Profile* profile);

  ExtensionUpdater(const ExtensionUpdater&) = delete;
  ExtensionUpdater& operator=(const ExtensionUpdater&) = delete;
  ~ExtensionUpdater() override;

  // Initializes and enables the updater. Does not start it. Use Start() for
  // that.
  void InitAndEnable(ExtensionPrefs* extension_prefs,
                     PrefService* prefs,
                     base::TimeDelta frequency,
                     ExtensionCache* cache,
                     const ExtensionDownloader::Factory& downloader_factory);

  // KeyedService:
  void Shutdown() override;

  // Starts the updater running.  Should be called at most once.
  void Start();

  // Stops the updater running, cancelling any outstanding update manifest and
  // crx downloads. Does not cancel any in-progress installs.
  void Stop();

  // Posts a task to do an update check.  Does nothing if there is
  // already a pending task that has not yet run.
  void CheckSoon();

  // Starts an update check right now, instead of waiting for the next
  // regularly scheduled check or a pending check from CheckSoon().
  void CheckNow(CheckParams params);

  // Returns true iff CheckSoon() has been called but the update check
  // hasn't been performed yet.  This is used mostly by tests; calling
  // code should just call CheckSoon().
  bool WillCheckSoon() const;

  // Creates an CrxInstaller to update an extension. Returns null if an update
  // is not possible. Eg: system shutdown or extension doesn't exist.
  // Public for testing.
  scoped_refptr<CrxInstaller> CreateUpdateInstaller(const CRXFileInfo& file,
                                                    bool file_ownership_passed);

  // Adds/removes update observers.
  void AddObserver(UpdateObserver* observer);
  void RemoveObserver(UpdateObserver* observer);

  // Notifies update observers for chrome update available.
  void NotifyChromeUpdateAvailable();

  // Notifies update observers that an app update is available.
  void NotifyAppUpdateAvailable(const Extension& extension);

  // Overrides the extension cache with |extension_cache| for testing.
  void SetExtensionCacheForTesting(ExtensionCache* extension_cache);

  // Overrides the extension downloader with |downloader| for testing.
  void SetExtensionDownloaderForTesting(
      std::unique_ptr<ExtensionDownloader> downloader);

  // After this is called, the next ExtensionUpdater instance to be started will
  // call CheckNow() instead of CheckSoon() for its initial update.
  static void UpdateImmediatelyForFirstRun();

  // For testing, changes the backoff policy for ExtensionDownloader's manifest
  // queue to get less initial delay and the tests don't time out.
  void SetBackoffPolicyForTesting(
      const net::BackoffEntry::Policy& backoff_policy);

  // Always fetch updates via update service, not the extension downloader.
  static base::AutoReset<bool> GetScopedUseUpdateServiceForTesting();

  // Set a callback to invoke when updating has started.
  void SetUpdatingStartedCallbackForTesting(base::RepeatingClosure callback);

  // A callback that is invoked when the next invocation of CxrInstaller
  // finishes (successfully or not).
  void SetCrxInstallerResultCallbackForTesting(
      ExtensionSystem::InstallUpdateCallback callback);

  bool enabled() const { return enabled_; }

  // Exists because some tests are not able to use the private constructor for
  // testing.
  void set_crx_installer_factory_for_test(CrxInstallerFactoryForTest* factory) {
    crx_installer_factory_for_test_ = factory;
  }

  void set_browser_terminating_for_test(bool value) {
    browser_terminating_ = value;
  }

 private:
  friend class ExtensionUpdaterFactory;
  friend class ExtensionUpdaterTest;
  friend class ExtensionUpdaterFileHandler;

  // FetchedCRXFile holds information about a CRX file we fetched to disk,
  // but have not yet installed.
  struct FetchedCRXFile {
    FetchedCRXFile();
    FetchedCRXFile(const CRXFileInfo& file,
                   bool file_ownership_passed,
                   const std::set<int>& request_ids,
                   InstallCallback callback);
    FetchedCRXFile(FetchedCRXFile&& other);
    FetchedCRXFile& operator=(FetchedCRXFile&& other);
    ~FetchedCRXFile();

    CRXFileInfo info;
    GURL download_url;
    bool file_ownership_passed;
    std::set<int> request_ids;
    InstallCallback callback;
    scoped_refptr<CrxInstaller> installer;
  };

  struct InProgressCheck {
    InProgressCheck();
    InProgressCheck(const InProgressCheck&) = delete;
    InProgressCheck& operator=(const InProgressCheck&) = delete;
    ~InProgressCheck();

    bool install_immediately = false;
    bool awaiting_update_service = false;
    UpdateFoundCallback update_found_callback;
    FinishedCallback callback;
    // Prevents the destruction of the Profile* while an update check is in
    // progress.
    // TODO(crbug.com/40174537): Find a way to pass the keepalive to
    // UpdateClient instead of holding it here.
    std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive;
    // The ids of extensions that have in-progress update checks.
    std::set<ExtensionId> in_progress_ids;
  };

  // Ensure that we have a valid ExtensionDownloader instance referenced by
  // |downloader|.
  void EnsureDownloaderCreated();

  // Schedules a task to call NextCheck after |frequency_| delay, plus
  // or minus 0 to 20% (to help spread load evenly on servers).
  void ScheduleNextCheck();

  // Add fetch records for extensions that are installed to the downloader,
  // ignoring |pending_ids| so the extension isn't fetched again.
  void AddToDownloader(const ExtensionSet* extensions,
                       const std::set<ExtensionId>& pending_ids,
                       int request_id,
                       DownloadFetchPriority fetch_priority,
                       ExtensionUpdateCheckParams* update_check_params);

  // Adds |extension| to the downloader, providing it with |fetch_priority|,
  // |request_id| and data extracted from the extension object.
  // |fetch_priority| parameter notifies the downloader the priority of this
  // extension update (either foreground or background).
  bool AddExtensionToDownloader(const Extension& extension,
                                int request_id,
                                DownloadFetchPriority fetch_priority);

  // Conduct a check as scheduled by ScheduleNextCheck.
  void NextCheck();

  // Posted by CheckSoon().
  void DoCheckSoon();

  // Implementation of ExtensionDownloaderDelegate.
  void OnExtensionDownloadStageChanged(const ExtensionId& id,
                                       Stage stage) override;
  void OnExtensionUpdateFound(const ExtensionId& id,
                              const std::set<int>& request_ids,
                              const base::Version& version) override;
  void OnExtensionDownloadCacheStatusRetrieved(const ExtensionId& id,
                                               CacheStatus status) override;
  void OnExtensionDownloadFailed(const ExtensionId& id,
                                 Error error,
                                 const PingResult& ping,
                                 const std::set<int>& request_ids,
                                 const FailureData& data) override;
  void OnExtensionDownloadRetry(const ExtensionId& id,
                                const FailureData& data) override;
  void OnExtensionDownloadFinished(const CRXFileInfo& file,
                                   bool file_ownership_passed,
                                   const GURL& download_url,
                                   const PingResult& ping,
                                   const std::set<int>& request_id,
                                   InstallCallback callback) override;
  bool GetPingDataForExtension(const ExtensionId& id,
                               DownloadPingData* ping_data) override;
  bool IsExtensionPending(const ExtensionId& id) override;
  bool GetExtensionExistingVersion(const ExtensionId& id,
                                   std::string* version) override;

  // Returns an `ExtensionUpdateData` prepopulated with the `pending_version`
  // and `pending_fingerprint` if there is a pending extension update.
  ExtensionUpdateData GetExtensionUpdateData(const ExtensionId& id);

  void UpdatePingData(const ExtensionId& id, const PingResult& ping_result);

  // Starts installing a crx file that has been fetched but not installed yet.
  void InstallCRXFile(FetchedCRXFile crx_file);

  // Send a notification that update checks are starting.
  void NotifyStarted();

  // Send a notification if we're finished updating.
  void NotifyIfFinished(int request_id);

  // |udpate_service_| will execute this function on finish.
  void OnUpdateServiceFinished(int request_id);

  void ExtensionCheckFinished(const ExtensionId& extension_id,
                              FinishedCallback callback);

  // Callback set in the crx installer and invoked when the crx file has passed
  // the expectations check. It takes the ownership of the file pointed to by
  // |crx_info|.
  void PutExtensionInCache(const CRXFileInfo& crx_info);

  // Deletes the crx file at |crx_path| if ownership is passed.
  void CleanUpCrxFileIfNeeded(const base::FilePath& crx_path,
                              bool file_ownership_passed);

  void OnInstallerDone(const base::UnguessableToken& token,
                       const std::optional<CrxInstallError>& error);

  // This function verifies if |extension_id| can be updated using
  // UpdateService.
  bool CanUseUpdateService(const ExtensionId& extension_id) const;

  // Called when the browser is terminating.
  void OnAppTerminating();

  // Returns the IDs of corrupted extensions scheduled for reinstall.
  std::set<ExtensionId> GetCorruptedExtensionIds() const;

  // Get the effective update URL for the extension. Normally this URL comes
  // from the extension manifest, but may be overridden by policies.
  GURL GetEffectiveUpdateURL(const Extension& extension) const;

  // Whether the updater is enabled (i.e. it's legal to call Start()).
  bool enabled_ = false;

  // Whether Start() has been called but not Stop().
  bool alive_ = false;

  // A closure passed into the ExtensionUpdater to teach it how to construct
  // new ExtensionDownloader instances.
  ExtensionDownloader::Factory downloader_factory_;

  // Fetches the crx files for the extensions that have an available update.
  std::unique_ptr<ExtensionDownloader> downloader_;

  base::ObserverList<UpdateObserver, /*check_empty=*/true>::Unchecked
      update_observers_;

  // Update service is responsible for updating Webstore extensions.
  // Note that |UpdateService| is a KeyedService class, which can only be
  // created through a |KeyedServiceFactory| singleton, thus |update_service_|
  // will be freed by the same factory singleton before the browser is
  // shutdown.
  raw_ptr<UpdateService> update_service_ = nullptr;

  base::TimeDelta frequency_;
  bool will_check_soon_ = false;

  raw_ptr<ExtensionPrefs> extension_prefs_ = nullptr;
  raw_ptr<PrefService> prefs_ = nullptr;
  raw_ptr<Profile> profile_ = nullptr;

  raw_ptr<ExtensionRegistry> registry_ = nullptr;
  raw_ptr<ExtensionRegistrar> registrar_ = nullptr;
  raw_ptr<DelayedInstallManager> delayed_install_manager_ = nullptr;
  raw_ptr<PendingExtensionManager> pending_extension_manager_ = nullptr;
  raw_ptr<ExternalInstallManager> external_install_manager_ = nullptr;
  raw_ptr<CorruptedExtensionReinstaller> corrupted_extension_reinstaller_ =
      nullptr;

  std::map<int, InProgressCheck> requests_in_progress_;
  int next_request_id_ = 0;

  // CRX installs that are currently in progress. Used to get the FetchedCRXFile
  // when OnInstallerDone is called.
  std::map<base::UnguessableToken, FetchedCRXFile> running_crx_installs_;

  raw_ptr<ExtensionCache> extension_cache_ = nullptr;

  base::RepeatingClosure updating_started_callback_;

  // Set when the browser is terminating. Prevents us from updating additional
  // extensions.
  bool browser_terminating_ = false;
  base::CallbackListSubscription on_app_terminating_subscription_;

  raw_ptr<CrxInstallerFactoryForTest> crx_installer_factory_for_test_ = nullptr;
  ExtensionSystem::InstallUpdateCallback installer_result_callback_for_testing_;

  base::WeakPtrFactory<ExtensionUpdater> weak_ptr_factory_{this};
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_UPDATER_EXTENSION_UPDATER_H_