blob: 61348850afb6a237325b5f2c1f0f9fadf045ae4d [file] [log] [blame]
Alex Deymo5e3ea272016-01-28 13:42:23 -08001//
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
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/update_attempter_android.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080018
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070021#include <memory>
Kelvin Zhanga43d6e82021-05-26 10:14:42 -040022#include <ostream>
Alex Deymo5e3ea272016-01-28 13:42:23 -080023#include <utility>
Daniel Zhengda4f7292022-09-02 22:59:32 +000024#include <vector>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025
Tianjie Xu90aaa102017-10-10 17:39:03 -070026#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090027#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080028#include <base/bind.h>
29#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080030#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070031#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080032#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080033#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070034#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080035
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/aosp/cleanup_previous_update_action.h"
Daniel Zhengda4f7292022-09-02 22:59:32 +000037#include "update_engine/common/clock.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080038#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070039#include "update_engine/common/daemon_state_interface.h"
40#include "update_engine/common/download_action.h"
Kelvin Zhangf8441982022-12-07 18:18:47 -080041#include "update_engine/common/error_code.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070043#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070044#include "update_engine/common/metrics_reporter_interface.h"
45#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070047#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080048#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/file_descriptor.h"
50#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000052#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080053#include "update_engine/payload_consumer/payload_constants.h"
54#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070055#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080056#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070057#include "update_engine/update_boot_flags_action.h"
Kelvin Zhangf92fe252023-03-28 10:55:47 -070058#include "update_engine/update_status.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080059#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080060
Alex Deymo14c0da82016-07-20 16:45:45 -070061#ifndef _UE_SIDELOAD
62// Do not include support for external HTTP(s) urls when building
63// update_engine_sideload.
64#include "update_engine/libcurl_http_fetcher.h"
65#endif
66
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090067using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070069using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070using base::TimeDelta;
71using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080072using std::string;
73using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070074using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080075
76namespace chromeos_update_engine {
77
78namespace {
79
Alex Deymo0d298542016-03-30 18:31:49 -070080// Minimum threshold to broadcast an status update in progress and time.
81const double kBroadcastThresholdProgress = 0.01; // 1%
82const int kBroadcastThresholdSeconds = 10;
83
Alex Deymo5e3ea272016-01-28 13:42:23 -080084const char* const kErrorDomain = "update_engine";
85// TODO(deymo): Convert the different errors to a numeric value to report them
86// back on the service error.
87const char* const kGenericError = "generic_error";
88
89// Log and set the error on the passed ErrorPtr.
90bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070091 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080092 const string& reason) {
93 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
94 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
95 << reason;
96 return false;
97}
98
Sen Jiangfe522822017-10-31 15:14:11 -070099bool GetHeaderAsBool(const string& header, bool default_value) {
100 int value = 0;
101 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
102 return value == 1;
103 return default_value;
104}
105
Yifan Hongbd47d622019-12-13 14:59:58 -0800106bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
107 std::map<string, string>* headers,
108 brillo::ErrorPtr* error) {
109 for (const string& key_value_pair : key_value_pair_headers) {
110 string key;
111 string value;
112 if (!brillo::string_utils::SplitAtFirst(
113 key_value_pair, "=", &key, &value, false)) {
114 return LogAndSetError(
115 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
116 }
117 if (!headers->emplace(key, value).second)
118 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
119 }
120 return true;
121}
122
123// Unique identifier for the payload. An empty string means that the payload
124// can't be resumed.
125string GetPayloadId(const std::map<string, string>& headers) {
126 return (headers.count(kPayloadPropertyFileHash)
127 ? headers.at(kPayloadPropertyFileHash)
128 : "") +
129 (headers.count(kPayloadPropertyMetadataHash)
130 ? headers.at(kPayloadPropertyMetadataHash)
131 : "");
132}
133
Alex Deymo5e3ea272016-01-28 13:42:23 -0800134} // namespace
135
136UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700137 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800138 PrefsInterface* prefs,
139 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000140 HardwareInterface* hardware,
141 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800142 : daemon_state_(daemon_state),
143 prefs_(prefs),
144 boot_control_(boot_control),
145 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000146 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700147 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800148 clock_(new Clock()),
149 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
150 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800151 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400152 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700153 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800154}
155
156UpdateAttempterAndroid::~UpdateAttempterAndroid() {
157 // Release ourselves as the ActionProcessor's delegate to prevent
158 // re-scheduling the updates due to the processing stopped.
159 processor_->set_delegate(nullptr);
160}
161
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400162[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
163 string boot_id;
164 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
165 string old_boot_id;
166 // If no previous boot id found, treat as a reboot and write boot ID.
167 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
168 return true;
169 }
170 return old_boot_id != boot_id;
171}
172
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400173std::ostream& operator<<(std::ostream& out, OTAResult result) {
174 switch (result) {
175 case OTAResult::NOT_ATTEMPTED:
176 out << "OTAResult::NOT_ATTEMPTED";
177 break;
178 case OTAResult::ROLLED_BACK:
179 out << "OTAResult::ROLLED_BACK";
180 break;
181 case OTAResult::UPDATED_NEED_REBOOT:
182 out << "OTAResult::UPDATED_NEED_REBOOT";
183 break;
184 case OTAResult::OTA_SUCCESSFUL:
185 out << "OTAResult::OTA_SUCCESSFUL";
186 break;
187 }
188 return out;
189}
190
Alex Deymo5e3ea272016-01-28 13:42:23 -0800191void UpdateAttempterAndroid::Init() {
192 // In case of update_engine restart without a reboot we need to restore the
193 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700194 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400195 LOG(INFO) << "Updated installed but update_engine is restarted without "
196 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800197 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700198 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400199 const auto result = GetOTAUpdateResult();
200 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800201 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400202 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400203 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400204 }
205
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700206#ifdef _UE_SIDELOAD
207 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
208 << "ApplyPayload will call it later.";
209#else
Yifan Hong90965502020-02-19 15:22:47 -0800210 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700211#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700212 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800213}
214
215bool UpdateAttempterAndroid::ApplyPayload(
216 const string& payload_url,
217 int64_t payload_offset,
218 int64_t payload_size,
219 const vector<string>& key_value_pair_headers,
220 brillo::ErrorPtr* error) {
221 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
222 return LogAndSetError(
223 error, FROM_HERE, "An update already applied, waiting for reboot");
224 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700225 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800226 return LogAndSetError(
227 error, FROM_HERE, "Already processing an update, cancel it first.");
228 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100229 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800230
Alex Deymo218397f2016-02-04 23:55:10 -0800231 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800232 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
233 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800234 }
235
Yifan Hongbd47d622019-12-13 14:59:58 -0800236 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800237
238 // Setup the InstallPlan based on the request.
239 install_plan_ = InstallPlan();
240
241 install_plan_.download_url = payload_url;
242 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800243 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800244 InstallPlan::Payload payload;
245 payload.size = payload_size;
246 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800247 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800248 &payload.size)) {
249 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800250 }
251 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700252 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800253 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700254 LOG(WARNING) << "Unable to decode base64 file hash: "
255 << headers[kPayloadPropertyFileHash];
256 }
Alex Deymo218397f2016-02-04 23:55:10 -0800257 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800258 &payload.metadata_size)) {
259 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800260 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700261 // The |payload.type| is not used anymore since minor_version 3.
262 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800263 install_plan_.payloads.push_back(payload);
264
Alex Deymo5e3ea272016-01-28 13:42:23 -0800265 // The |public_key_rsa| key would override the public key stored on disk.
266 install_plan_.public_key_rsa = "";
267
268 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
269 install_plan_.is_resume = !payload_id.empty() &&
270 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
271 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700272 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700273 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
274
Alex Deymo5e3ea272016-01-28 13:42:23 -0800275 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
276 LOG(WARNING) << "Unable to save the update check response hash.";
277 }
278 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800279 install_plan_.source_slot = GetCurrentSlot();
280 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700281
Alex Deymofb905d92016-06-03 19:26:58 -0700282 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700283 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
284
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000285 if (!IsProductionBuild()) {
286 install_plan_.disable_vabc =
287 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
288 }
289
Sen Jiangfe522822017-10-31 15:14:11 -0700290 install_plan_.switch_slot_on_reboot =
291 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
292
Tianjie Xu087de9d2019-11-01 17:11:22 -0700293 install_plan_.run_post_install =
294 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800295
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700296 // Skip writing verity if we're resuming and verity has already been written.
297 install_plan_.write_verity = true;
298 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
299 bool verity_written = false;
300 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
301 verity_written) {
302 install_plan_.write_verity = false;
303 }
304 }
305
Alex Deymo87792ea2016-07-25 15:40:36 -0700306 NetworkId network_id = kDefaultNetworkId;
307 if (!headers[kPayloadPropertyNetworkId].empty()) {
308 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
309 &network_id)) {
310 return LogAndSetError(
311 error,
312 FROM_HERE,
313 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
314 }
315 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700316 return LogAndSetError(
317 error,
318 FROM_HERE,
319 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700320 }
321 }
322
Alex Deymo5e3ea272016-01-28 13:42:23 -0800323 LOG(INFO) << "Using this install plan:";
324 install_plan_.Dump();
325
Amin Hassani667cf7b2018-07-25 14:32:00 -0700326 HttpFetcher* fetcher = nullptr;
327 if (FileFetcher::SupportedUrl(payload_url)) {
328 DLOG(INFO) << "Using FileFetcher for file URL.";
329 fetcher = new FileFetcher();
330 } else {
331#ifdef _UE_SIDELOAD
332 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800333 return false; // NOLINT, unreached but analyzer might not know.
334 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700335#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700336 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700337 if (!headers[kPayloadDownloadRetry].empty()) {
338 libcurl_fetcher->set_max_retry_count(
339 atoi(headers[kPayloadDownloadRetry].c_str()));
340 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700341 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
342 fetcher = libcurl_fetcher;
343#endif // _UE_SIDELOAD
344 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800345 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800346 if (!headers[kPayloadPropertyAuthorization].empty())
347 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
348 if (!headers[kPayloadPropertyUserAgent].empty())
349 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
350
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700351 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
352 LOG(INFO) << "Using proxy url from payload headers: "
353 << headers[kPayloadPropertyNetworkProxy];
354 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
355 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700356 if (!headers[kPayloadVABCNone].empty()) {
357 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000358 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800359 if (!headers[kPayloadEnableThreading].empty()) {
360 install_plan_.enable_threading = true;
361 }
362 if (!headers[kPayloadBatchedWrites].empty()) {
363 install_plan_.batched_writes = true;
364 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700365
Amin Hassani667cf7b2018-07-25 14:32:00 -0700366 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800367
Alex Deymo5e3ea272016-01-28 13:42:23 -0800368 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700369
370 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
371 // TODO(xunchang) report the metrics for unresumable updates
372
Amin Hassani667cf7b2018-07-25 14:32:00 -0700373 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800374 return true;
375}
376
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900377bool UpdateAttempterAndroid::ApplyPayload(
378 int fd,
379 int64_t payload_offset,
380 int64_t payload_size,
381 const vector<string>& key_value_pair_headers,
382 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100383 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000384 // already running update will be terminated (existing file descriptor will be
385 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100386 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
387 return LogAndSetError(
388 error, FROM_HERE, "An update already applied, waiting for reboot");
389 }
390 if (processor_->IsRunning()) {
391 return LogAndSetError(
392 error, FROM_HERE, "Already processing an update, cancel it first.");
393 }
394 DCHECK_EQ(status_, UpdateStatus::IDLE);
395
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900396 payload_fd_.reset(dup(fd));
397 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
398
399 return ApplyPayload(
400 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
401}
402
Alex Deymo5e3ea272016-01-28 13:42:23 -0800403bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700404 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800405 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
406 processor_->SuspendProcessing();
407 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800408}
409
410bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700411 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800412 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
413 processor_->ResumeProcessing();
414 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800415}
416
417bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700418 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800419 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800420 processor_->StopProcessing();
421 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800422}
423
Alex Deymo3b678db2016-02-09 11:50:06 -0800424bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
425 LOG(INFO) << "Attempting to reset state from "
426 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700427 if (processor_->IsRunning()) {
428 return LogAndSetError(
429 error, FROM_HERE, "Already processing an update, cancel it first.");
430 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700431 if (status_ != UpdateStatus::IDLE &&
432 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
433 return LogAndSetError(error,
434 FROM_HERE,
435 "Status reset not allowed in this state, please "
436 "cancel on going OTA first.");
437 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800438
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000439 if (apex_handler_android_ != nullptr) {
440 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
441 std::vector<ApexInfo> apex_infos_blank;
442 apex_handler_android_->AllocateSpace(apex_infos_blank);
443 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400444 // Remove the reboot marker so that if the machine is rebooted
445 // after resetting to idle state, it doesn't go back to
446 // UpdateStatus::UPDATED_NEED_REBOOT state.
447 if (!ClearUpdateCompletedMarker()) {
448 return LogAndSetError(error,
449 FROM_HERE,
450 "Failed to reset the status because "
451 "ClearUpdateCompletedMarker() failed");
452 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700453 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
454 if (!resetShouldSwitchSlotOnReboot(error)) {
455 LOG(INFO) << "Failed to reset slot switch.";
456 return false;
457 }
458 LOG(INFO) << "Slot switch reset successful";
459 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700460 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
461 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000462 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700463 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700464 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800465}
466
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700467bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
468 if (a.size() != b.size()) {
469 return false;
470 }
471 return memcmp(a.data(), b.data(), a.size()) == 0;
472}
473bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
474 return !(a == b);
475}
476
Yifan Hongbd47d622019-12-13 14:59:58 -0800477bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
478 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700479 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800480 DeltaArchiveManifest* manifest,
481 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800482 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
483 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
484 return LogAndSetError(
485 error, FROM_HERE, "Failed to open " + metadata_filename);
486 }
487 brillo::Blob metadata(kMaxPayloadHeaderSize);
488 if (!fd->Read(metadata.data(), metadata.size())) {
489 return LogAndSetError(
490 error,
491 FROM_HERE,
492 "Failed to read payload header from " + metadata_filename);
493 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000494 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800495 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700496 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800497 MetadataParseResult::kSuccess) {
498 return LogAndSetError(error,
499 FROM_HERE,
500 "Failed to parse payload header: " +
501 utils::ErrorCodeToString(errorcode));
502 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700503 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
504 payload_metadata.GetMetadataSignatureSize();
505 if (metadata_size < kMaxPayloadHeaderSize ||
506 metadata_size >
507 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800508 return LogAndSetError(
509 error,
510 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700511 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800512 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700513 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800514 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
515 metadata.size() - kMaxPayloadHeaderSize)) {
516 return LogAndSetError(
517 error,
518 FROM_HERE,
519 "Failed to read metadata and signature from " + metadata_filename);
520 }
521 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700522 if (!expected_metadata_hash.empty()) {
523 brillo::Blob metadata_hash;
524 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
525 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
526 if (metadata_hash != expected_metadata_hash) {
527 return LogAndSetError(error,
528 FROM_HERE,
529 "Metadata hash mismatch. Expected hash: " +
530 HexEncode(expected_metadata_hash) +
531 " actual hash: " + HexEncode(metadata_hash));
532 } else {
533 LOG(INFO) << "Payload metadata hash check passed : "
534 << HexEncode(metadata_hash);
535 }
536 }
Sen Jiang08c6da12019-01-07 18:28:56 -0800537
Tianjie Xu7a78d632019-10-08 16:32:39 -0700538 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
539 constants::kUpdateCertificatesPath);
540 if (!payload_verifier) {
541 return LogAndSetError(error,
542 FROM_HERE,
543 "Failed to create the payload verifier from " +
544 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800545 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700546 errorcode = payload_metadata.ValidateMetadataSignature(
547 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800548 if (errorcode != ErrorCode::kSuccess) {
549 return LogAndSetError(error,
550 FROM_HERE,
551 "Failed to validate metadata signature: " +
552 utils::ErrorCodeToString(errorcode));
553 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800554 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800555 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
556 }
557
Yifan Hongbd47d622019-12-13 14:59:58 -0800558 return true;
559}
560
561bool UpdateAttempterAndroid::VerifyPayloadApplicable(
562 const std::string& metadata_filename, brillo::ErrorPtr* error) {
563 DeltaArchiveManifest manifest;
564 TEST_AND_RETURN_FALSE(
565 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
566
567 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000568 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800569
570 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800571 for (const PartitionUpdate& partition : manifest.partitions()) {
572 if (!partition.has_old_partition_info())
573 continue;
574 string partition_path;
575 if (!boot_control_->GetPartitionDevice(
576 partition.partition_name(), current_slot, &partition_path)) {
577 return LogAndSetError(
578 error,
579 FROM_HERE,
580 "Failed to get partition device for " + partition.partition_name());
581 }
582 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
583 return LogAndSetError(
584 error, FROM_HERE, "Failed to open " + partition_path);
585 }
586 for (const InstallOperation& operation : partition.operations()) {
587 if (!operation.has_src_sha256_hash())
588 continue;
589 brillo::Blob source_hash;
590 if (!fd_utils::ReadAndHashExtents(fd,
591 operation.src_extents(),
592 manifest.block_size(),
593 &source_hash)) {
594 return LogAndSetError(
595 error, FROM_HERE, "Failed to hash " + partition_path);
596 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400597 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800598 source_hash, operation, fd, &errorcode)) {
599 return false;
600 }
601 }
602 fd->Close();
603 }
604 return true;
605}
606
Alex Deymo5e3ea272016-01-28 13:42:23 -0800607void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
608 ErrorCode code) {
609 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800610 metric_bytes_downloaded_.Flush(true);
611 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800612 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800613 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
614 TerminateUpdateAndNotify(code);
615 return;
616 }
617
Alex Deymo5990bf32016-07-19 17:01:41 -0700618 switch (code) {
619 case ErrorCode::kSuccess:
620 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400621 if (!WriteUpdateCompletedMarker()) {
622 LOG(ERROR) << "Failed to write update completion marker";
623 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700624 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800625
Alex Deymo5990bf32016-07-19 17:01:41 -0700626 LOG(INFO) << "Update successfully applied, waiting to reboot.";
627 break;
628
629 case ErrorCode::kFilesystemCopierError:
630 case ErrorCode::kNewRootfsVerificationError:
631 case ErrorCode::kNewKernelVerificationError:
632 case ErrorCode::kFilesystemVerifierError:
633 case ErrorCode::kDownloadStateInitializationError:
634 // Reset the ongoing update for these errors so it starts from the
635 // beginning next time.
636 DeltaPerformer::ResetUpdateProgress(prefs_, false);
637 LOG(INFO) << "Resetting update progress.";
638 break;
639
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700640 case ErrorCode::kPayloadTimestampError:
641 // SafetyNet logging, b/36232423
642 android_errorWriteLog(0x534e4554, "36232423");
643 break;
644
Alex Deymo5990bf32016-07-19 17:01:41 -0700645 default:
646 // Ignore all other error codes.
647 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700648 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800649
650 TerminateUpdateAndNotify(code);
651}
652
653void UpdateAttempterAndroid::ProcessingStopped(
654 const ActionProcessor* processor) {
655 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
656}
657
658void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
659 AbstractAction* action,
660 ErrorCode code) {
661 // Reset download progress regardless of whether or not the download
662 // action succeeded.
663 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800664 if (type == CleanupPreviousUpdateAction::StaticType() ||
665 (type == NoOpAction::StaticType() &&
666 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
667 cleanup_previous_update_code_ = code;
668 NotifyCleanupPreviousUpdateCallbacksAndClear();
669 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000670 // download_progress_ is actually used by other actions, such as
671 // filesystem_verify_action. Therefore we always clear it.
672 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700673 if (type == PostinstallRunnerAction::StaticType()) {
674 bool succeeded =
675 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
676 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
677 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800678 if (code != ErrorCode::kSuccess) {
679 // If an action failed, the ActionProcessor will cancel the whole thing.
680 return;
681 }
Yifan Hong83517502020-02-19 15:34:13 -0800682 if (type == UpdateBootFlagsAction::StaticType()) {
683 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
684 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800685 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400686 auto download_action = static_cast<DownloadAction*>(action);
687 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000688 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700689 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000690 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700691 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800692 }
693}
694
695void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
696 uint64_t bytes_received,
697 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700698 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800699 if (total)
700 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700701 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800702 download_progress_ = progress;
703 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700704 } else {
705 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800706 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700707
708 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800709 metric_bytes_downloaded_ += bytes_progressed;
710 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800711}
712
713bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
714 // TODO(deymo): Notify the DownloadAction that it should cancel the update
715 // download.
716 return false;
717}
718
719void UpdateAttempterAndroid::DownloadComplete() {
720 // Nothing needs to be done when the download completes.
721}
722
Alex Deymo0d298542016-03-30 18:31:49 -0700723void UpdateAttempterAndroid::ProgressUpdate(double progress) {
724 // Self throttle based on progress. Also send notifications if progress is
725 // too slow.
726 if (progress == 1.0 ||
727 progress - download_progress_ >= kBroadcastThresholdProgress ||
728 TimeTicks::Now() - last_notify_time_ >=
729 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
730 download_progress_ = progress;
731 SetStatusAndNotify(status_);
732 }
733}
734
Kelvin Zhang70eef232020-06-12 20:32:40 +0000735void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
736 assert(status_ == UpdateStatus::VERIFYING);
737 ProgressUpdate(progress);
738}
739
Alex Deymo5e3ea272016-01-28 13:42:23 -0800740void UpdateAttempterAndroid::ScheduleProcessingStart() {
741 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700742 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800743 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700744 FROM_HERE,
745 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
746 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800747}
748
749void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
750 if (status_ == UpdateStatus::IDLE) {
751 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
752 return;
753 }
754
Yifan Hong90965502020-02-19 15:22:47 -0800755 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400756 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800757 LOG(INFO) << "Terminating cleanup previous update.";
758 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700759 for (auto observer : daemon_state_->service_observers())
760 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800761 return;
762 }
763
Yifan Hong9194ce82019-11-07 11:03:42 -0800764 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700765
Alex Deymo0d298542016-03-30 18:31:49 -0700766 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800767 UpdateStatus new_status =
768 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
769 : UpdateStatus::IDLE);
770 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900771 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800772
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700773 // The network id is only applicable to one download attempt and once it's
774 // done the network id should not be re-used anymore.
775 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
776 LOG(WARNING) << "Unable to unbind network.";
777 }
778
Alex Deymo5e3ea272016-01-28 13:42:23 -0800779 for (auto observer : daemon_state_->service_observers())
780 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700781
Tianjie Xu90aaa102017-10-10 17:39:03 -0700782 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
783 ClearMetricsPrefs();
784 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800785 // We should only reset the PayloadAttemptNumber if the update succeeds, or
786 // we switch to a different payload.
787 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700788 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700789 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800790 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700791 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800792}
793
794void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
795 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700796 size_t payload_size =
797 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700798 UpdateEngineStatus status_to_send = {.status = status_,
799 .progress = download_progress_,
800 .new_size_bytes = payload_size};
801
Alex Deymo5e3ea272016-01-28 13:42:23 -0800802 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700803 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800804 }
805 last_notify_time_ = TimeTicks::Now();
806}
807
Amin Hassani667cf7b2018-07-25 14:32:00 -0700808void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800809 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800810
811 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700812 auto update_boot_flags_action =
813 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800814 auto cleanup_previous_update_action =
815 boot_control_->GetDynamicPartitionControl()
816 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700817 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
818 auto download_action =
819 std::make_unique<DownloadAction>(prefs_,
820 boot_control_,
821 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700822 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700823 true /* interactive */,
824 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700826 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700827 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
828 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700829 auto postinstall_runner_action =
830 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000831 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700832 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800833
Alex Deymo5e3ea272016-01-28 13:42:23 -0800834 // Bond them together. We have to use the leaf-types when calling
835 // BondActions().
836 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700837 BondActions(download_action.get(), filesystem_verifier_action.get());
838 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800839 postinstall_runner_action.get());
840
Amin Hassani667cf7b2018-07-25 14:32:00 -0700841 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800842 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700843 processor_->EnqueueAction(std::move(install_plan_action));
844 processor_->EnqueueAction(std::move(download_action));
845 processor_->EnqueueAction(std::move(filesystem_verifier_action));
846 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800847}
848
Alex Deymo5e3ea272016-01-28 13:42:23 -0800849bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
850 string boot_id;
851 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800852 LOG(INFO) << "Writing update complete marker, slot "
853 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400854 TEST_AND_RETURN_FALSE(
855 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
856 TEST_AND_RETURN_FALSE(
857 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
858 return true;
859}
860
861bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
862 LOG(INFO) << "Clearing update complete marker.";
863 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
864 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800865 return true;
866}
867
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800868bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800869 // In case of an update_engine restart without a reboot, we stored the boot_id
870 // when the update was completed by setting a pref, so we can check whether
871 // the last update was on this boot or a previous one.
872 string boot_id;
873 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
874
875 string update_completed_on_boot_id;
876 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
877 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
878 &update_completed_on_boot_id) &&
879 update_completed_on_boot_id == boot_id);
880}
881
Tianjie Xu90aaa102017-10-10 17:39:03 -0700882// Collect and report the android metrics when we terminate the update.
883void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
884 ErrorCode error_code) {
885 int64_t attempt_number =
886 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
887 PayloadType payload_type = kPayloadTypeFull;
888 int64_t payload_size = 0;
889 for (const auto& p : install_plan_.payloads) {
890 if (p.type == InstallPayloadType::kDelta)
891 payload_type = kPayloadTypeDelta;
892 payload_size += p.size;
893 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700894 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
895 // function will be triggered, but payload_size in this case might be 0, if so
896 // skip reporting any metrics.
897 if (payload_size == 0) {
898 return;
899 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700900
901 metrics::AttemptResult attempt_result =
902 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700903 Time boot_time_start = Time::FromInternalValue(
904 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
905 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700906 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700907 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
908 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700909
910 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700911 static_cast<int>(attempt_number),
912 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700913 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700914 duration_uptime,
915 payload_size,
916 attempt_result,
917 error_code);
918
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800919 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700920 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
921 current_bytes_downloaded,
922 0,
923 DownloadSource::kNumDownloadSources,
924 metrics::DownloadErrorCode::kUnset,
925 metrics::ConnectionType::kUnset);
926
Tianjie Xu90aaa102017-10-10 17:39:03 -0700927 if (error_code == ErrorCode::kSuccess) {
928 int64_t reboot_count =
929 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
930 string build_version;
931 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700932
933 // For android metrics, we only care about the total bytes downloaded
934 // for all sources; for now we assume the only download source is
935 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800936 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700937 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
938 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
939 total_bytes_downloaded;
940
941 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700942 if (total_bytes_downloaded >= payload_size) {
943 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700944 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700945 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
946 } else {
947 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
948 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700949 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700950
Tianjie Xu90aaa102017-10-10 17:39:03 -0700951 metrics_reporter_->ReportSuccessfulUpdateMetrics(
952 static_cast<int>(attempt_number),
953 0, // update abandoned count
954 payload_type,
955 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700956 num_bytes_downloaded,
957 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700958 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700959 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700960 static_cast<int>(reboot_count),
961 0); // url_switch_count
962 }
963}
964
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400965bool UpdateAttempterAndroid::OTARebootSucceeded() const {
966 const auto current_slot = boot_control_->GetCurrentSlot();
967 const string current_version =
968 android::base::GetProperty("ro.build.version.incremental", "");
969 int64_t previous_slot = -1;
970 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
971 string previous_version;
972 TEST_AND_RETURN_FALSE(
973 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
974 if (previous_slot != current_slot) {
975 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800976 << previous_version << " to " << current_version
977 << ", previous slot: " << previous_slot
978 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400979 if (previous_version == current_version) {
980 LOG(INFO) << "Previous version is the same as current version, this is "
981 "possibly a self-OTA.";
982 }
983 return true;
984 } else {
985 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
986 "switch never happened, or system not rebooted at all.";
987 if (previous_version != current_version) {
988 LOG(INFO) << "Slot didn't change, but version changed from "
989 << previous_version << " to " << current_version
990 << " device could be flashed.";
991 }
992 return false;
993 }
994}
995
996OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
997 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
998 // existence of this pref is sufficient indicator. Given that we have to
999 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001000 // |DeltaPerformer::ResetUpdateProgress| and
1001 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001002 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1003 auto system_rebooted = DidSystemReboot(prefs_);
1004 auto ota_successful = OTARebootSucceeded();
1005 if (ota_successful) {
1006 return OTAResult::OTA_SUCCESSFUL;
1007 }
1008 if (slot_switch_attempted) {
1009 if (system_rebooted) {
1010 // If we attempted slot switch, but still end up on the same slot, we
1011 // probably rolled back.
1012 return OTAResult::ROLLED_BACK;
1013 } else {
1014 return OTAResult::UPDATED_NEED_REBOOT;
1015 }
1016 }
1017 return OTAResult::NOT_ATTEMPTED;
1018}
1019
1020void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001021 // Example: [ro.build.version.incremental]: [4292972]
1022 string current_version =
1023 android::base::GetProperty("ro.build.version.incremental", "");
1024 TEST_AND_RETURN(!current_version.empty());
1025
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001026 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1027 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001028 string current_boot_id;
1029 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1030 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001031 std::string slot_switch_indicator;
1032 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1033 if (slot_switch_indicator != current_boot_id) {
1034 ClearUpdateCompletedMarker();
1035 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001036
Tianjie Xu90aaa102017-10-10 17:39:03 -07001037 // If there's no record of previous version (e.g. due to a data wipe), we
1038 // save the info of current boot and skip the metrics report.
1039 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001040 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001041 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001042 ClearMetricsPrefs();
1043 return;
1044 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001045 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001046 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001047 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1048 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001049 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001050 int64_t reboot_count =
1051 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1052 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1053 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001054
1055 if (result == OTAResult::ROLLED_BACK) {
1056 // This will release all space previously allocated for apex
1057 // decompression. If we detect a rollback, we should release space and
1058 // return the space to user. Any subsequent attempt to install OTA will
1059 // allocate space again anyway.
1060 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1061 "deompression.";
1062 apex_handler_android_->AllocateSpace({});
1063 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1064 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001065 return;
1066 }
1067
1068 // Now that the build version changes, report the update metrics.
1069 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001070 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001071 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001072
1073 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1074 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1075 if (previous_attempt_exists) {
1076 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1077 }
1078
1079 metrics_utils::LoadAndReportTimeToReboot(
1080 metrics_reporter_.get(), prefs_, clock_.get());
1081 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001082
1083 // Also reset the update progress if the build version has changed.
1084 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1085 LOG(WARNING) << "Unable to reset the update progress.";
1086 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001087}
1088
1089// Save the update start time. Reset the reboot count and attempt number if the
1090// update isn't a resume; otherwise increment the attempt number.
1091void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1092 if (!is_resume) {
1093 metrics_utils::SetNumReboots(0, prefs_);
1094 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1095 } else {
1096 int64_t attempt_number =
1097 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1098 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1099 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001100 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1101 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001102 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001103}
1104
1105void UpdateAttempterAndroid::ClearMetricsPrefs() {
1106 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001107 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001108 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001109 prefs_->Delete(kPrefsSystemUpdatedMarker);
1110 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001111 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001112}
1113
Yifan Hongbd47d622019-12-13 14:59:58 -08001114BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1115 return boot_control_->GetCurrentSlot();
1116}
1117
1118BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1119 return GetCurrentSlot() == 0 ? 1 : 0;
1120}
1121
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001122uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1123 const std::string& metadata_filename,
1124 const vector<string>& key_value_pair_headers,
1125 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001126 std::map<string, string> headers;
1127 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1128 return 0;
1129 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001130 DeltaArchiveManifest manifest;
1131 brillo::Blob metadata_hash;
1132 if (!brillo::data_encoding::Base64Decode(
1133 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1134 metadata_hash.clear();
1135 }
1136 if (!VerifyPayloadParseManifest(
1137 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1138 return 0;
1139 }
Yifan Hong65613032020-01-09 17:52:13 -08001140
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001141 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1142 manifest.apex_info().end());
1143 uint64_t apex_size_required = 0;
1144 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001145 auto result = apex_handler_android_->CalculateSize(apex_infos);
1146 if (!result.ok()) {
1147 LogAndSetError(error,
1148 FROM_HERE,
1149 "Failed to calculate size required for compressed APEX");
1150 return 0;
1151 }
1152 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001153 }
1154
Yifan Hong65613032020-01-09 17:52:13 -08001155 string payload_id = GetPayloadId(headers);
1156 uint64_t required_size = 0;
1157 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1158 boot_control_,
1159 GetTargetSlot(),
1160 manifest,
1161 payload_id,
1162 &required_size)) {
1163 if (required_size == 0) {
1164 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1165 return 0;
1166 } else {
1167 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001168 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001169 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001170 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001171 }
1172 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001173
1174 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001175 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001176 LOG(ERROR) << "Insufficient space for apex decompression: "
1177 << apex_size_required << " bytes";
1178 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001179 }
Yifan Hong65613032020-01-09 17:52:13 -08001180
1181 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001182 return 0;
1183}
1184
Yifan Hong40bb0d02020-02-24 17:33:14 -08001185void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1186 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001187 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001188 if (cleanup_previous_update_code_.has_value()) {
1189 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1190 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1191 if (callback) {
1192 callback->OnCleanupComplete(
1193 static_cast<int32_t>(*cleanup_previous_update_code_));
1194 }
1195 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001196 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001197 if (callback) {
1198 auto callback_ptr = callback.get();
1199 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1200 callback_ptr->RegisterForDeathNotifications(
1201 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1202 base::Unretained(this),
1203 base::Unretained(callback_ptr)));
1204 }
1205 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001206}
1207
Tianjie7f8f2ab2021-07-23 17:08:50 -07001208bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1209 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001210 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001211 if (processor_->IsRunning()) {
1212 return LogAndSetError(
1213 error, FROM_HERE, "Already processing an update, cancel it first.");
1214 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001215 DeltaArchiveManifest manifest;
1216 TEST_AND_RETURN_FALSE(
1217 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1218
Kelvin Zhang20982a52021-08-13 12:31:16 -07001219 InstallPlan install_plan_;
1220 install_plan_.source_slot = GetCurrentSlot();
1221 install_plan_.target_slot = GetTargetSlot();
1222 // Don't do verity computation, just hash the partitions
1223 install_plan_.write_verity = false;
1224 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1225 install_plan_.run_post_install = false;
1226 install_plan_.is_resume = true;
1227
1228 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1229 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1230
Kelvin Zhang20982a52021-08-13 12:31:16 -07001231 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001232 auto postinstall_runner_action =
1233 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1234 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001235 postinstall_runner_action->set_delegate(this);
1236
Kelvin Zhangf8441982022-12-07 18:18:47 -08001237 // If last error code is kUpdatedButNotActive, we know that we reached this
1238 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1239 // call would have already performed filesystem verification, therefore, we
1240 // can safely skip the verification to save time.
1241 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1242 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1243 processor_->EnqueueAction(std::move(install_plan_action));
1244 } else {
Kelvin Zhang263a5402022-12-08 23:03:32 -08001245 if (!boot_control_->GetDynamicPartitionControl()
1246 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1247 GetTargetSlot(),
1248 manifest,
1249 false /* should update */,
1250 nullptr)) {
1251 return LogAndSetError(
1252 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1253 }
1254 ErrorCode error_code{};
1255 if (!install_plan_.ParsePartitions(manifest.partitions(),
1256 boot_control_,
1257 manifest.block_size(),
1258 &error_code)) {
1259 return LogAndSetError(error,
1260 FROM_HERE,
1261 "Failed to LoadPartitionsFromSlots " +
1262 utils::ErrorCodeToString(error_code));
1263 }
1264
Kelvin Zhangf8441982022-12-07 18:18:47 -08001265 auto filesystem_verifier_action =
1266 std::make_unique<FilesystemVerifierAction>(
1267 boot_control_->GetDynamicPartitionControl());
1268 filesystem_verifier_action->set_delegate(this);
1269 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1270 BondActions(filesystem_verifier_action.get(),
1271 postinstall_runner_action.get());
1272 processor_->EnqueueAction(std::move(install_plan_action));
1273 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1274 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001275
Kelvin Zhang20982a52021-08-13 12:31:16 -07001276 processor_->EnqueueAction(std::move(postinstall_runner_action));
1277 ScheduleProcessingStart();
1278 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001279}
1280
1281bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1282 brillo::ErrorPtr* error) {
1283 if (processor_->IsRunning()) {
1284 return LogAndSetError(
1285 error, FROM_HERE, "Already processing an update, cancel it first.");
1286 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001287 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001288 // Update the boot flags so the current slot has higher priority.
1289 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1290 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1291 }
1292
1293 // Mark the current slot as successful again, since marking it as active
1294 // may reset the successful bit. We ignore the result of whether marking
1295 // the current slot as successful worked.
1296 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1297 return LogAndSetError(
1298 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1299 }
1300
1301 // Resets the warm reset property since we won't switch the slot.
1302 hardware_->SetWarmReset(false);
1303
1304 // Resets the vbmeta digest.
1305 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1306 LOG(INFO) << "Slot switch cancelled.";
1307 SetStatusAndNotify(UpdateStatus::IDLE);
1308 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001309}
1310
Yifan Hong90965502020-02-19 15:22:47 -08001311void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1312 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1313 // is in progress, skip enqueueing the action.
1314 if (processor_->IsRunning()) {
1315 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1316 << "be done when the current update finishes.";
1317 return;
1318 }
1319 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1320 auto action =
1321 boot_control_->GetDynamicPartitionControl()
1322 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1323 processor_->EnqueueAction(std::move(action));
1324 processor_->set_delegate(this);
1325 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1326 processor_->StartProcessing();
1327}
1328
Yifan Hong40bb0d02020-02-24 17:33:14 -08001329void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1330 for (auto&& callback : cleanup_previous_update_callbacks_) {
1331 callback->OnCleanupProgressUpdate(progress);
1332 }
1333}
1334
1335void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1336 CHECK(cleanup_previous_update_code_.has_value());
1337 for (auto&& callback : cleanup_previous_update_callbacks_) {
1338 callback->OnCleanupComplete(
1339 static_cast<int32_t>(*cleanup_previous_update_code_));
1340 }
1341 cleanup_previous_update_callbacks_.clear();
1342}
1343
1344void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1345 CleanupSuccessfulUpdateCallbackInterface* callback) {
1346 auto end_it =
1347 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1348 cleanup_previous_update_callbacks_.end(),
1349 [&](const auto& e) { return e.get() == callback; });
1350 cleanup_previous_update_callbacks_.erase(
1351 end_it, cleanup_previous_update_callbacks_.end());
1352}
Yifan Hong90965502020-02-19 15:22:47 -08001353
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001354bool UpdateAttempterAndroid::IsProductionBuild() {
1355 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1356 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1357 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1358 return true;
1359 }
1360 return false;
1361}
1362
Alex Deymo5e3ea272016-01-28 13:42:23 -08001363} // namespace chromeos_update_engine