update_client.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_UPDATE_CLIENT_UPDATE_CLIENT_H_
  5. #define COMPONENTS_UPDATE_CLIENT_UPDATE_CLIENT_H_
  6. #include <stdint.h>
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #include <vector>
  11. #include "base/callback_forward.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/version.h"
  14. #include "components/crx_file/crx_verifier.h"
  15. #include "components/update_client/update_client_errors.h"
  16. #include "third_party/abseil-cpp/absl/types/optional.h"
  17. // The UpdateClient class is a facade with a simple interface. The interface
  18. // exposes a few APIs to install a CRX or update a group of CRXs.
  19. //
  20. // The difference between a CRX install and a CRX update is relatively minor.
  21. // The terminology going forward will use the word "update" to cover both
  22. // install and update scenarios, except where details regarding the install
  23. // case are relevant.
  24. //
  25. // Handling an update consists of a series of actions such as sending an update
  26. // check to the server, followed by parsing the server response, identifying
  27. // the CRXs that require an update, downloading the differential update if
  28. // it is available, unpacking and patching the differential update, then
  29. // falling back to trying a similar set of actions using the full update.
  30. // At the end of this process, completion pings are sent to the server,
  31. // as needed, for the CRXs which had updates.
  32. //
  33. // As a general idea, this code handles the action steps needed to update
  34. // a group of components serially, one step at a time. However, concurrent
  35. // execution of calls to UpdateClient::Update is possible, therefore,
  36. // queuing of updates could happen in some cases. More below.
  37. //
  38. // The UpdateClient class features a subject-observer interface to observe
  39. // the CRX state changes during an update.
  40. //
  41. // The threading model for this code assumes that most of the code in the
  42. // public interface runs on a SingleThreadTaskRunner.
  43. // This task runner corresponds to the browser UI thread in many cases. There
  44. // are parts of the installer interface that run on blocking task runners, which
  45. // are usually threads in a thread pool.
  46. //
  47. // Using the UpdateClient is relatively easy. This assumes that the client
  48. // of this code has already implemented the observer interface as needed, and
  49. // can provide an installer, as described below.
  50. //
  51. // std::unique_ptr<UpdateClient> update_client(UpdateClientFactory(...));
  52. // update_client->AddObserver(&observer);
  53. // std::vector<std::string> ids;
  54. // ids.push_back(...));
  55. // update_client->Update(ids, base::BindOnce(...), base::BindOnce(...));
  56. //
  57. // UpdateClient::Update takes two callbacks as parameters. First callback
  58. // allows the client of this code to provide an instance of CrxComponent
  59. // data structure that specifies additional parameters of the update.
  60. // CrxComponent has a CrxInstaller data member, which must be provided by the
  61. // callers of this class. The second callback indicates that this non-blocking
  62. // call has completed.
  63. //
  64. // There could be several ways of triggering updates for a CRX, user-initiated,
  65. // or timer-based. Since the execution of updates is concurrent, the parameters
  66. // for the update must be provided right before the update is handled.
  67. // Otherwise, the version of the CRX set in the CrxComponent may not be correct.
  68. //
  69. // The UpdateClient public interface includes two functions: Install and
  70. // Update. These functions correspond to installing one CRX immediately as a
  71. // foreground activity (Install), and updating a group of CRXs silently in the
  72. // background (Update). This distinction is important. Background updates are
  73. // queued up and their actions run serially, one at a time, for the purpose of
  74. // conserving local resources such as CPU, network, and I/O.
  75. // On the other hand, installs are never queued up but run concurrently, as
  76. // requested by the user.
  77. //
  78. // The update client introduces a runtime constraint regarding interleaving
  79. // updates and installs. If installs or updates for a given CRX are in progress,
  80. // then installs for the same CRX will fail with a specific error.
  81. //
  82. // Implementation details.
  83. //
  84. // The implementation details below are not relevant to callers of this
  85. // code. However, these design notes are relevant to the owners and maintainers
  86. // of this module.
  87. //
  88. // The design for the update client consists of a number of abstractions
  89. // such as: task, update engine, update context, and action.
  90. // The execution model for these abstractions is simple. They usually expose
  91. // a public, non-blocking Run function, and they invoke a callback when
  92. // the Run function has completed.
  93. //
  94. // A task is the unit of work for the UpdateClient. A task is associated
  95. // with a single call of the Update function. A task represents a group
  96. // of CRXs that are updated together.
  97. //
  98. // The UpdateClient is responsible for the queuing of tasks, if queuing is
  99. // needed.
  100. //
  101. // When the task runs, it calls the update engine to handle the updates for
  102. // the CRXs associated with the task. The UpdateEngine is the abstraction
  103. // responsible for breaking down the update in a set of discrete steps, which
  104. // are implemented as actions, and running the actions.
  105. //
  106. // The UpdateEngine maintains a set of UpdateContext instances. Each of
  107. // these instances maintains the update state for all the CRXs belonging to
  108. // a given task. The UpdateContext contains a queue of CRX ids.
  109. // The UpdateEngine will handle updates for the CRXs in the order they appear
  110. // in the queue, until the queue is empty.
  111. //
  112. // The update state for each CRX is maintained in a container of CrxUpdateItem*.
  113. // As actions run, each action updates the CRX state, represented by one of
  114. // these CrxUpdateItem* instances.
  115. //
  116. // Although the UpdateEngine can and will run update tasks concurrently, the
  117. // actions of a task are run sequentially.
  118. //
  119. // The Action is a polymorphic type. There is some code reuse for convenience,
  120. // implemented as a mixin. The polymorphic behavior of some of the actions
  121. // is achieved using a template method.
  122. //
  123. // State changes of a CRX could generate events, which are observed using a
  124. // subject-observer interface.
  125. //
  126. // The actions chain up. In some sense, the actions implement a state machine,
  127. // as the CRX undergoes a series of state transitions in the process of
  128. // being checked for updates and applying the update.
  129. class PrefRegistrySimple;
  130. namespace base {
  131. class FilePath;
  132. }
  133. namespace crx_file {
  134. enum class VerifierFormat;
  135. }
  136. namespace update_client {
  137. class Configurator;
  138. enum class Error;
  139. struct CrxUpdateItem;
  140. enum class ComponentState {
  141. kNew,
  142. kChecking,
  143. kCanUpdate,
  144. kDownloadingDiff,
  145. kDownloading,
  146. kDownloaded,
  147. kUpdatingDiff,
  148. kUpdating,
  149. kUpdated,
  150. kUpToDate,
  151. kUpdateError,
  152. kUninstalled,
  153. kRegistration,
  154. kRun,
  155. kLastStatus
  156. };
  157. // Defines an interface for a generic CRX installer.
  158. class CrxInstaller : public base::RefCountedThreadSafe<CrxInstaller> {
  159. public:
  160. // Contains the result of the Install operation.
  161. struct Result {
  162. Result() = default;
  163. explicit Result(int error, int extended_error = 0)
  164. : error(error), extended_error(extended_error) {}
  165. explicit Result(InstallError error, int extended_error = 0)
  166. : error(static_cast<int>(error)), extended_error(extended_error) {}
  167. int error = 0; // 0 indicates that install has been successful.
  168. int extended_error = 0;
  169. // Localized text displayed to the user, if applicable.
  170. std::string installer_text;
  171. // Shell command run at the end of the install, if applicable. This string
  172. // must be escaped to be a command line.
  173. std::string installer_cmd_line;
  174. };
  175. struct InstallParams {
  176. InstallParams(const std::string& run,
  177. const std::string& arguments,
  178. const std::string& server_install_data);
  179. std::string run;
  180. std::string arguments;
  181. std::string server_install_data;
  182. };
  183. using ProgressCallback = base::RepeatingCallback<void(int progress)>;
  184. using Callback = base::OnceCallback<void(const Result& result)>;
  185. // Called on the main thread when there was a problem unpacking or
  186. // verifying the CRX. |error| is a non-zero value which is only meaningful
  187. // to the caller.
  188. virtual void OnUpdateError(int error) = 0;
  189. // Called by the update service when a CRX has been unpacked
  190. // and it is ready to be installed. This method may be called from a
  191. // sequence other than the main sequence.
  192. // |unpack_path| contains the temporary directory with all the unpacked CRX
  193. // files.
  194. // |pubkey| contains the public key of the CRX in the PEM format, without the
  195. // header and the footer.
  196. // |install_params| is an optional parameter which provides the name and the
  197. // arguments for a binary program which is invoked as part of the install or
  198. // update flows.
  199. // |progress_callback| reports installer progress. This callback must be run
  200. // directly instead of posting it.
  201. // |callback| must be the last callback invoked and it indicates that the
  202. // install flow has completed.
  203. virtual void Install(const base::FilePath& unpack_path,
  204. const std::string& public_key,
  205. std::unique_ptr<InstallParams> install_params,
  206. ProgressCallback progress_callback,
  207. Callback callback) = 0;
  208. // Sets |installed_file| to the full path to the installed |file|. |file| is
  209. // the filename of the file in this CRX. Returns false if this is
  210. // not possible (the file has been removed or modified, or its current
  211. // location is unknown). Otherwise, it returns true.
  212. virtual bool GetInstalledFile(const std::string& file,
  213. base::FilePath* installed_file) = 0;
  214. // Called when a CRX has been unregistered and all versions should
  215. // be uninstalled from disk. Returns true if uninstallation is supported,
  216. // and false otherwise.
  217. virtual bool Uninstall() = 0;
  218. protected:
  219. friend class base::RefCountedThreadSafe<CrxInstaller>;
  220. virtual ~CrxInstaller() = default;
  221. };
  222. // Defines an interface to handle |action| elements in the update response.
  223. // The current implementation only handles run actions bound to a CRX, meaning
  224. // that such CRX is unpacked and an executable file, contained inside the CRX,
  225. // is run, then the results of the invocation are collected by the callback.
  226. class ActionHandler : public base::RefCountedThreadSafe<ActionHandler> {
  227. public:
  228. using Callback =
  229. base::OnceCallback<void(bool succeeded, int error_code, int extra_code1)>;
  230. virtual void Handle(const base::FilePath& action,
  231. const std::string& session_id,
  232. Callback callback) = 0;
  233. protected:
  234. friend class base::RefCountedThreadSafe<ActionHandler>;
  235. virtual ~ActionHandler() = default;
  236. };
  237. // A dictionary of installer-specific, arbitrary name-value pairs, which
  238. // may be used in the update checks requests.
  239. using InstallerAttributes = std::map<std::string, std::string>;
  240. struct CrxComponent {
  241. CrxComponent();
  242. CrxComponent(const CrxComponent& other);
  243. ~CrxComponent();
  244. // Optional SHA256 hash of the CRX's public key. If not supplied, the
  245. // unpacker can accept any CRX for this app, provided that the CRX meets the
  246. // VerifierFormat requirements specified by the service's configurator.
  247. // Callers that know or need a specific developer signature on acceptable CRX
  248. // files must provide this.
  249. std::vector<uint8_t> pk_hash;
  250. scoped_refptr<CrxInstaller> installer;
  251. scoped_refptr<ActionHandler> action_handler;
  252. std::string app_id;
  253. // The current version if the CRX is updated. Otherwise, "0" or "0.0" if
  254. // the CRX is installed.
  255. base::Version version;
  256. // Optional. This additional parameter ("ap") is sent to the server, which
  257. // often uses it to distinguish between variants of the software that were
  258. // chosen at install time.
  259. std::string ap;
  260. // If nonempty, the brand is an uppercase 4-letter string that describes the
  261. // flavor, branding, or provenance of the software.
  262. std::string brand;
  263. // If populated, the `install_data_index` is sent to the update server as part
  264. // of the `data` element. The server will provide corresponding installer data
  265. // in the update response. This data is then provided to the installer when
  266. // running it.
  267. std::string install_data_index;
  268. std::string fingerprint; // Optional.
  269. std::string name; // Optional.
  270. // Optional.
  271. // Valid values for the name part of an attribute match
  272. // ^[-_a-zA-Z0-9]{1,256}$ and valid values the value part of an attribute
  273. // match ^[-.,;+_=$a-zA-Z0-9]{0,256}$ .
  274. InstallerAttributes installer_attributes;
  275. // Specifies that the CRX can be background-downloaded in some cases.
  276. // The default for this value is |true|.
  277. bool allows_background_download = true;
  278. // Specifies that the update checks and pings associated with this component
  279. // require confidentiality. The default for this value is |true|. As a side
  280. // note, the confidentiality of the downloads is enforced by the server,
  281. // which only returns secure download URLs in this case.
  282. bool requires_network_encryption = true;
  283. // Specifies the strength of package validation required for the item.
  284. crx_file::VerifierFormat crx_format_requirement =
  285. crx_file::VerifierFormat::CRX3_WITH_PUBLISHER_PROOF;
  286. // True if and only if this item may be updated.
  287. bool updates_enabled = true;
  288. // Reasons why this component/extension is disabled.
  289. std::vector<int> disabled_reasons;
  290. // Information about where the component/extension was installed from.
  291. // For extension, this information is set from the update service, which
  292. // gets the install source from the update URL.
  293. std::string install_source;
  294. // Information about where the component/extension was loaded from.
  295. // For extensions, this information is inferred from the extension
  296. // registry.
  297. std::string install_location;
  298. // Information about the channel to send to the update server when updating
  299. // the component. This optional field is typically populated by policy and is
  300. // only populated on managed devices.
  301. std::string channel;
  302. // A version prefix sent to the server in the case of version pinning. The
  303. // server should not respond with an update to a version that does not match
  304. // this prefix. If no prefix is specified, the client will accept any version.
  305. std::string target_version_prefix;
  306. // An indicator sent to the server to advise whether it may perform a version
  307. // downgrade of this item.
  308. bool rollback_allowed = false;
  309. // An indicator sent to the server to advise whether it may perform an
  310. // over-install on this item.
  311. bool same_version_update_allowed = false;
  312. };
  313. // Called when a non-blocking call of UpdateClient completes.
  314. using Callback = base::OnceCallback<void(Error error)>;
  315. // All methods are safe to call only from the browser's main thread. Once an
  316. // instance of this class is created, the reference to it must be released
  317. // only after the thread pools of the browser process have been destroyed and
  318. // the browser process has gone single-threaded.
  319. class UpdateClient : public base::RefCountedThreadSafe<UpdateClient> {
  320. public:
  321. // Returns `CrxComponent` instances corresponding to the component ids
  322. // passed as an argument to the callback. The order of components in the input
  323. // and output vectors must match. If the instance of the `CrxComponent` is not
  324. // available for some reason, implementors of the callback must not skip
  325. // skip the component, and instead, they must insert a `nullopt` value in
  326. // the output vector.
  327. using CrxDataCallback =
  328. base::OnceCallback<std::vector<absl::optional<CrxComponent>>(
  329. const std::vector<std::string>& ids)>;
  330. // Called when state changes occur during an Install or Update call.
  331. using CrxStateChangeCallback =
  332. base::RepeatingCallback<void(CrxUpdateItem item)>;
  333. // Defines an interface to observe the UpdateClient. It provides
  334. // notifications when state changes occur for the service itself or for the
  335. // registered CRXs.
  336. class Observer {
  337. public:
  338. enum class Events {
  339. // Sent before the update client does an update check.
  340. COMPONENT_CHECKING_FOR_UPDATES = 1,
  341. // Sent when there is a new version of a registered CRX. The CRX will be
  342. // downloaded after the notification unless the update client inserts
  343. // a wait because of a throttling policy.
  344. COMPONENT_UPDATE_FOUND,
  345. // Sent when a CRX is in the update queue but it can't be acted on
  346. // right away, because the update client spaces out CRX updates due to a
  347. // throttling policy.
  348. COMPONENT_WAIT,
  349. // Sent after the new CRX has been downloaded but before the install
  350. // or the upgrade is attempted.
  351. COMPONENT_UPDATE_READY,
  352. // Sent when a CRX has been successfully updated.
  353. COMPONENT_UPDATED,
  354. // Sent when a CRX has not been updated because there was no update
  355. // available for this component.
  356. COMPONENT_ALREADY_UP_TO_DATE,
  357. // Sent when an error ocurred during an update for any reason, including
  358. // the update check itself failed, or the download of the update payload
  359. // failed, or applying the update failed.
  360. COMPONENT_UPDATE_ERROR,
  361. // Sent when CRX bytes are being downloaded.
  362. COMPONENT_UPDATE_DOWNLOADING,
  363. // Sent when install progress is received from the CRX installer.
  364. COMPONENT_UPDATE_UPDATING,
  365. };
  366. virtual ~Observer() = default;
  367. // Called by the update client when a state change happens.
  368. // If an |id| is specified, then the event is fired on behalf of the
  369. // specific CRX. The implementors of this interface are
  370. // expected to filter the relevant events based on the id of the CRX.
  371. virtual void OnEvent(Events event, const std::string& id) = 0;
  372. };
  373. // Adds an observer for this class. An observer should not be added more
  374. // than once. The caller retains the ownership of the observer object.
  375. virtual void AddObserver(Observer* observer) = 0;
  376. // Removes an observer. It is safe for an observer to be removed while
  377. // the observers are being notified.
  378. virtual void RemoveObserver(Observer* observer) = 0;
  379. // Installs the specified CRX. Calls back on |callback| after the
  380. // update has been handled. Provides state change notifications through
  381. // invocations of the optional |crx_state_change_callback| callback.
  382. // The |error| parameter of the |callback| contains an error code in the case
  383. // of a run-time error, or 0 if the install has been handled successfully.
  384. // Overlapping calls of this function are executed concurrently, as long as
  385. // the id parameter is different, meaning that installs of different
  386. // components are parallelized.
  387. // The |Install| function is intended to be used for foreground installs of
  388. // one CRX. These cases are usually associated with on-demand install
  389. // scenarios, which are triggered by user actions. Installs are never
  390. // queued up.
  391. // Returns a closure that can be called to cancel the installation.
  392. virtual base::RepeatingClosure Install(
  393. const std::string& id,
  394. CrxDataCallback crx_data_callback,
  395. CrxStateChangeCallback crx_state_change_callback,
  396. Callback callback) = 0;
  397. // Updates the specified CRXs. Calls back on |crx_data_callback| before the
  398. // update is attempted to give the caller the opportunity to provide the
  399. // instances of CrxComponent to be used for this update. Provides state change
  400. // notifications through invocations of the optional
  401. // |crx_state_change_callback| callback.
  402. // The |Update| function is intended to be used for background updates of
  403. // several CRXs. Overlapping calls to this function result in a queuing
  404. // behavior, and the execution of each call is serialized. In addition,
  405. // updates are always queued up when installs are running. The |is_foreground|
  406. // parameter must be set to true if the invocation of this function is a
  407. // result of a user initiated update.
  408. virtual void Update(const std::vector<std::string>& ids,
  409. CrxDataCallback crx_data_callback,
  410. CrxStateChangeCallback crx_state_change_callback,
  411. bool is_foreground,
  412. Callback callback) = 0;
  413. // Sends an uninstall ping for `crx_component`. `reason` is sent to the server
  414. // to indicate the cause of the uninstallation. The current implementation of
  415. // this function only sends a best-effort ping. It has no other side effects
  416. // regarding installs or updates done through an instance of this class.
  417. virtual void SendUninstallPing(const CrxComponent& crx_component,
  418. int reason,
  419. Callback callback) = 0;
  420. // Returns status details about a CRX update. The function returns true in
  421. // case of success and false in case of errors, such as |id| was
  422. // invalid or not known.
  423. virtual bool GetCrxUpdateState(const std::string& id,
  424. CrxUpdateItem* update_item) const = 0;
  425. // Returns true if the |id| is found in any running task.
  426. virtual bool IsUpdating(const std::string& id) const = 0;
  427. // Cancels the queued updates and makes a best effort to stop updates in
  428. // progress as soon as possible. Some updates may not be stopped, in which
  429. // case, the updates will run to completion. Calling this function has no
  430. // effect if updates are not currently executed or queued up.
  431. virtual void Stop() = 0;
  432. protected:
  433. friend class base::RefCountedThreadSafe<UpdateClient>;
  434. virtual ~UpdateClient() = default;
  435. };
  436. // Creates an instance of the update client.
  437. scoped_refptr<UpdateClient> UpdateClientFactory(
  438. scoped_refptr<Configurator> config);
  439. // This must be called prior to the construction of any Configurator that
  440. // contains a PrefService.
  441. void RegisterPrefs(PrefRegistrySimple* registry);
  442. // This must be called prior to the construction of any Configurator that
  443. // needs access to local user profiles.
  444. // This function is mostly used for ExtensionUpdater, which requires update
  445. // info from user profiles.
  446. void RegisterProfilePrefs(PrefRegistrySimple* registry);
  447. } // namespace update_client
  448. #endif // COMPONENTS_UPDATE_CLIENT_UPDATE_CLIENT_H_