1 //
2 // Copyright (C) 2016 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef UPDATE_ENGINE_AOSP_UPDATE_ATTEMPTER_ANDROID_H_
18 #define UPDATE_ENGINE_AOSP_UPDATE_ATTEMPTER_ANDROID_H_
19 
20 #include <stdint.h>
21 
22 #include <memory>
23 #include <string>
24 #include <vector>
25 
26 #include <android-base/unique_fd.h>
27 #include <base/time/time.h>
28 
29 #include "update_engine/aosp/apex_handler_interface.h"
30 #include "update_engine/aosp/service_delegate_android_interface.h"
31 #include "update_engine/client_library/include/update_engine/update_status.h"
32 #include "update_engine/common/action_processor.h"
33 #include "update_engine/common/boot_control_interface.h"
34 #include "update_engine/common/clock_interface.h"
35 #include "update_engine/common/daemon_state_interface.h"
36 #include "update_engine/common/download_action.h"
37 #include "update_engine/common/error_code.h"
38 #include "update_engine/common/hardware_interface.h"
39 #include "update_engine/common/metrics_reporter_interface.h"
40 #include "update_engine/common/network_selector_interface.h"
41 #include "update_engine/common/prefs_interface.h"
42 #include "update_engine/metrics_utils.h"
43 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
44 #include "update_engine/payload_consumer/postinstall_runner_action.h"
45 
46 namespace chromeos_update_engine {
47 
48 enum class OTAResult {
49   NOT_ATTEMPTED,
50   ROLLED_BACK,
51   UPDATED_NEED_REBOOT,
52   OTA_SUCCESSFUL,
53 };
54 
55 class UpdateAttempterAndroid
56     : public ServiceDelegateAndroidInterface,
57       public ActionProcessorDelegate,
58       public DownloadActionDelegate,
59       public FilesystemVerifyDelegate,
60       public PostinstallRunnerAction::DelegateInterface,
61       public CleanupPreviousUpdateActionDelegateInterface {
62  public:
63   using UpdateStatus = update_engine::UpdateStatus;
64 
65   UpdateAttempterAndroid(DaemonStateInterface* daemon_state,
66                          PrefsInterface* prefs,
67                          BootControlInterface* boot_control_,
68                          HardwareInterface* hardware_,
69                          std::unique_ptr<ApexHandlerInterface> apex_handler);
70   ~UpdateAttempterAndroid() override;
71 
72   // Further initialization to be done post construction.
73   void Init();
74 
75   // ServiceDelegateAndroidInterface overrides.
76   bool ApplyPayload(const std::string& payload_url,
77                     int64_t payload_offset,
78                     int64_t payload_size,
79                     const std::vector<std::string>& key_value_pair_headers,
80                     Error* error) override;
81   bool ApplyPayload(int fd,
82                     int64_t payload_offset,
83                     int64_t payload_size,
84                     const std::vector<std::string>& key_value_pair_headers,
85                     Error* error) override;
86   bool SuspendUpdate(Error* error) override;
87   bool ResumeUpdate(Error* error) override;
88   bool CancelUpdate(Error* error) override;
89   bool ResetStatus(Error* error) override;
90   bool VerifyPayloadApplicable(const std::string& metadata_filename,
91                                Error* error) override;
92   uint64_t AllocateSpaceForPayload(
93       const std::string& metadata_filename,
94       const std::vector<std::string>& key_value_pair_headers,
95       Error* error) override;
96   void CleanupSuccessfulUpdate(
97       std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
98       Error* error) override;
99   bool setShouldSwitchSlotOnReboot(const std::string& metadata_filename,
100                                    Error* error) override;
101   bool resetShouldSwitchSlotOnReboot(Error* error) override;
102 
103   // ActionProcessorDelegate methods:
104   void ProcessingDone(const ActionProcessor* processor,
105                       ErrorCode code) override;
106   void ProcessingStopped(const ActionProcessor* processor) override;
107   void ActionCompleted(ActionProcessor* processor,
108                        AbstractAction* action,
109                        ErrorCode code) override;
110 
111   // DownloadActionDelegate overrides.
112   void BytesReceived(uint64_t bytes_progressed,
113                      uint64_t bytes_received,
114                      uint64_t total) override;
115   bool ShouldCancel(ErrorCode* cancel_reason) override;
116   void DownloadComplete() override;
117 
118   // FilesystemVerifyDelegate overrides
119   void OnVerifyProgressUpdate(double progress) override;
120 
121   // PostinstallRunnerAction::DelegateInterface
122   void ProgressUpdate(double progress) override;
123 
124   // CleanupPreviousUpdateActionDelegateInterface
125   void OnCleanupProgressUpdate(double progress) override;
126 
127   // Check the result of an OTA update. Intended to be called after reboot, this
128   // will use prefs on disk to determine if OTA was installed, or rolledback.
129   [[nodiscard]] OTAResult GetOTAUpdateResult() const;
130   // Intended to be called:
131   // 1. When system rebooted and slot switch is attempted
132   // 2. When a new update is started
133   // 3. When user called |ResetStatus()|
134   bool ClearUpdateCompletedMarker();
135 
set_update_certificates_path(const std::string & update_certificates_path)136   void set_update_certificates_path(
137       const std::string& update_certificates_path) {
138     update_certificates_path_ = update_certificates_path;
139   }
140 
141  private:
142   friend class UpdateAttempterAndroidTest;
143 
144   // Return |true| only if slot switched successfully after an OTA reboot.
145   // This will return |false| if an downgrade OTA is applied. Because after a
146   // downgrade OTA, we wipe /data, and there's no way for update_engine to
147   // "remember" that a downgrade OTA took place.
148   [[nodiscard]] bool OTARebootSucceeded() const;
149 
150   // Schedules an event loop callback to start the action processor. This is
151   // scheduled asynchronously to unblock the event loop.
152   void ScheduleProcessingStart();
153 
154   // Notifies an update request completed with the given error |code| to all
155   // observers.
156   void TerminateUpdateAndNotify(ErrorCode error_code);
157 
158   // Sets the status to the given |status| and notifies a status update to
159   // all observers.
160   void SetStatusAndNotify(UpdateStatus status);
161 
162   // Helper method to construct the sequence of actions to be performed for
163   // applying an update using a given HttpFetcher. The ownership of |fetcher| is
164   // passed to this function.
165   void BuildUpdateActions(HttpFetcher* fetcher);
166 
167   // Writes to the processing completed marker. Does nothing if
168   // |update_completed_marker_| is empty.
169   [[nodiscard]] bool WriteUpdateCompletedMarker();
170 
171   // Returns whether a slot switch was attempted in the current boot.
172   [[nodiscard]] bool UpdateCompletedOnThisBoot() const;
173 
174   // Prefs to use for metrics report
175   // |kPrefsPayloadAttemptNumber|: number of update attempts for the current
176   // payload_id.
177   // |KprefsNumReboots|: number of reboots when applying the current update.
178   // |kPrefsSystemUpdatedMarker|: end timestamp of the last successful update.
179   // |kPrefsUpdateTimestampStart|: start timestamp in monotonic time of the
180   // current update.
181   // |kPrefsUpdateBootTimestampStart|: start timestamp in boot time of
182   // the current update.
183   // |kPrefsCurrentBytesDownloaded|: number of bytes downloaded for the current
184   // payload_id.
185   // |kPrefsTotalBytesDownloaded|: number of bytes downloaded in total since
186   // the last successful update.
187 
188   // Metrics report function to call:
189   //   |ReportUpdateAttemptMetrics|
190   //   |ReportSuccessfulUpdateMetrics|
191   // Prefs to update:
192   //   |kPrefsSystemUpdatedMarker|
193   void CollectAndReportUpdateMetricsOnUpdateFinished(ErrorCode error_code);
194 
195   // This function is called after update_engine is started after device
196   // reboots. If update_engine is restarted w/o device reboot, this function
197   // would not be called.
198 
199   // Metrics report function to call:
200   //   |ReportAbnormallyTerminatedUpdateAttemptMetrics|
201   //   |ReportTimeToRebootMetrics|
202   // Prefs to update:
203   //   |kPrefsBootId|, |kPrefsPreviousVersion|
204   void UpdateStateAfterReboot(OTAResult result);
205 
206   // Prefs to update:
207   //   |kPrefsPayloadAttemptNumber|, |kPrefsUpdateTimestampStart|,
208   //   |kPrefsUpdateBootTimestampStart|
209   void UpdatePrefsOnUpdateStart(bool is_resume);
210 
211   // Prefs to delete:
212   //   |kPrefsNumReboots|, |kPrefsCurrentBytesDownloaded|
213   //   |kPrefsSystemUpdatedMarker|, |kPrefsUpdateTimestampStart|,
214   //   |kPrefsUpdateBootTimestampStart|
215   void ClearMetricsPrefs();
216 
217   // Return source and target slots for update.
218   BootControlInterface::Slot GetCurrentSlot() const;
219   BootControlInterface::Slot GetTargetSlot() const;
220 
221   // Helper of public VerifyPayloadApplicable. Return the parsed manifest in
222   // |manifest|.
223   static bool VerifyPayloadParseManifest(const std::string& metadata_filename,
224                                          std::string_view metadata_hash,
225                                          DeltaArchiveManifest* manifest,
226                                          Error* error);
VerifyPayloadParseManifest(const std::string & metadata_filename,DeltaArchiveManifest * manifest,Error * error)227   static bool VerifyPayloadParseManifest(const std::string& metadata_filename,
228                                          DeltaArchiveManifest* manifest,
229                                          Error* error) {
230     return VerifyPayloadParseManifest(metadata_filename, "", manifest, error);
231   }
232 
233   // Enqueue and run a CleanupPreviousUpdateAction.
234   void ScheduleCleanupPreviousUpdate();
235 
236   // Notify and clear |cleanup_previous_update_callbacks_|.
237   void NotifyCleanupPreviousUpdateCallbacksAndClear();
238 
239   // Remove |callback| from |cleanup_previous_update_callbacks_|.
240   void RemoveCleanupPreviousUpdateCallback(
241       CleanupSuccessfulUpdateCallbackInterface* callback);
242 
243   bool IsProductionBuild();
244 
245   DaemonStateInterface* daemon_state_;
246 
247   // DaemonStateAndroid pointers.
248   PrefsInterface* prefs_;
249   BootControlInterface* boot_control_;
250   HardwareInterface* hardware_;
251 
252   std::unique_ptr<ApexHandlerInterface> apex_handler_android_;
253 
254   // Last status notification timestamp used for throttling. Use monotonic
255   // TimeTicks to ensure that notifications are sent even if the system clock is
256   // set back in the middle of an update.
257   base::TimeTicks last_notify_time_;
258 
259   // The processor for running Actions.
260   std::unique_ptr<ActionProcessor> processor_;
261 
262   // The InstallPlan used during the ongoing update.
263   InstallPlan install_plan_;
264 
265   // For status:
266   UpdateStatus status_{UpdateStatus::IDLE};
267   double download_progress_{0.0};
268 
269   // The offset in the payload file where the CrAU part starts.
270   int64_t base_offset_{0};
271 
272   // Helper class to select the network to use during the update.
273   std::unique_ptr<NetworkSelectorInterface> network_selector_;
274 
275   std::unique_ptr<ClockInterface> clock_;
276 
277   std::unique_ptr<MetricsReporterInterface> metrics_reporter_;
278 
279   ::android::base::unique_fd payload_fd_;
280 
281   std::vector<std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface>>
282       cleanup_previous_update_callbacks_;
283   // Result of previous CleanupPreviousUpdateAction. Nullopt If
284   // CleanupPreviousUpdateAction has not been executed.
285   std::optional<ErrorCode> cleanup_previous_update_code_{std::nullopt};
286 
287   // The path to the zip file with X509 certificates.
288   std::string update_certificates_path_{constants::kUpdateCertificatesPath};
289   ErrorCode last_error_{ErrorCode::kSuccess};
290 
291   metrics_utils::PersistedValue<int64_t> metric_bytes_downloaded_;
292   metrics_utils::PersistedValue<int64_t> metric_total_bytes_downloaded_;
293 
294   DISALLOW_COPY_AND_ASSIGN(UpdateAttempterAndroid);
295 };
296 
297 }  // namespace chromeos_update_engine
298 
299 #endif  // UPDATE_ENGINE_AOSP_UPDATE_ATTEMPTER_ANDROID_H_
300