blob: b46f58412da2840c70a7a2463544a7b59b7503af [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>
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -080020#include <iterator>
Alex Deymo218397f2016-02-04 23:55:10 -080021#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070022#include <memory>
Kelvin Zhanga43d6e82021-05-26 10:14:42 -040023#include <ostream>
Alex Deymo5e3ea272016-01-28 13:42:23 -080024#include <utility>
Daniel Zhengda4f7292022-09-02 22:59:32 +000025#include <vector>
Alex Deymo5e3ea272016-01-28 13:42:23 -080026
Kelvin Zhang944cdac2023-12-12 12:55:27 -080027#include <android-base/parsebool.h>
Kokoa Matsuda3357e272024-10-18 13:59:05 +090028#include <android-base/parseint.h>
Tianjie Xu90aaa102017-10-10 17:39:03 -070029#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090030#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080031#include <base/bind.h>
32#include <base/logging.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070033#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080034#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080035#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070036#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080037
Amin Hassaniec7bc112020-10-29 16:47:58 -070038#include "update_engine/aosp/cleanup_previous_update_action.h"
Daniel Zhengda4f7292022-09-02 22:59:32 +000039#include "update_engine/common/clock.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080040#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070041#include "update_engine/common/daemon_state_interface.h"
42#include "update_engine/common/download_action.h"
Kelvin Zhangf8441982022-12-07 18:18:47 -080043#include "update_engine/common/error_code.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080044#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070045#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/common/metrics_reporter_interface.h"
47#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080048#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070049#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080050#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080051#include "update_engine/payload_consumer/file_descriptor.h"
52#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080053#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000054#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080055#include "update_engine/payload_consumer/payload_constants.h"
56#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070057#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080058#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070059#include "update_engine/update_boot_flags_action.h"
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -080060#include "update_engine/update_metadata.pb.h"
Kelvin Zhangf92fe252023-03-28 10:55:47 -070061#include "update_engine/update_status.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080062#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080063
Alex Deymo14c0da82016-07-20 16:45:45 -070064#ifndef _UE_SIDELOAD
65// Do not include support for external HTTP(s) urls when building
66// update_engine_sideload.
67#include "update_engine/libcurl_http_fetcher.h"
68#endif
69
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090070using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080071using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070072using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080073using base::TimeDelta;
74using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080075using std::string;
76using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070077using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080078
79namespace chromeos_update_engine {
80
81namespace {
82
Alex Deymo0d298542016-03-30 18:31:49 -070083// Minimum threshold to broadcast an status update in progress and time.
84const double kBroadcastThresholdProgress = 0.01; // 1%
85const int kBroadcastThresholdSeconds = 10;
86
Daniel Zheng92f7d172023-06-22 14:31:37 -070087// Log and set the error on the passed ErrorPtr.
88bool LogAndSetGenericError(Error* error,
89 int line_number,
90 const char* file_name,
91 const string& reason) {
92 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
93 << ": " << reason;
94 error->line_number = line_number;
95 error->file_name = file_name;
96 error->message = reason;
97 error->error_code = ErrorCode::kError;
98 return false;
99}
Alex Deymo5e3ea272016-01-28 13:42:23 -0800100
101// Log and set the error on the passed ErrorPtr.
Daniel Zheng92f7d172023-06-22 14:31:37 -0700102bool LogAndSetError(Error* error,
103 int line_number,
104 const char* file_name,
105 const string& reason,
106 ErrorCode error_code) {
107 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
108 << ": " << reason;
109 error->line_number = line_number;
110 error->file_name = file_name;
111 error->message = reason;
112 error->error_code = error_code;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800113 return false;
114}
115
Sen Jiangfe522822017-10-31 15:14:11 -0700116bool GetHeaderAsBool(const string& header, bool default_value) {
117 int value = 0;
Kokoa Matsuda3357e272024-10-18 13:59:05 +0900118 if (android::base::ParseInt(header, &value) && (value == 0 || value == 1))
Sen Jiangfe522822017-10-31 15:14:11 -0700119 return value == 1;
120 return default_value;
121}
122
Yifan Hongbd47d622019-12-13 14:59:58 -0800123bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
124 std::map<string, string>* headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700125 Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800126 for (const string& key_value_pair : key_value_pair_headers) {
127 string key;
128 string value;
129 if (!brillo::string_utils::SplitAtFirst(
130 key_value_pair, "=", &key, &value, false)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700131 return LogAndSetGenericError(error,
132 __LINE__,
133 __FILE__,
134 "Passed invalid header: " + key_value_pair);
Yifan Hongbd47d622019-12-13 14:59:58 -0800135 }
136 if (!headers->emplace(key, value).second)
Daniel Zheng92f7d172023-06-22 14:31:37 -0700137 return LogAndSetGenericError(
138 error, __LINE__, __FILE__, "Passed repeated key: " + key);
Yifan Hongbd47d622019-12-13 14:59:58 -0800139 }
140 return true;
141}
142
143// Unique identifier for the payload. An empty string means that the payload
144// can't be resumed.
145string GetPayloadId(const std::map<string, string>& headers) {
146 return (headers.count(kPayloadPropertyFileHash)
147 ? headers.at(kPayloadPropertyFileHash)
148 : "") +
149 (headers.count(kPayloadPropertyMetadataHash)
150 ? headers.at(kPayloadPropertyMetadataHash)
151 : "");
152}
153
Kelvin Zhang13020502023-08-02 15:18:40 -0700154std::string GetCurrentBuildVersion() {
155 // Example: [ro.build.fingerprint]:
156 // [generic/aosp_cf_x86_64_phone/vsoc_x86_64:VanillaIceCream/AOSP.MAIN/user08011303:userdebug/test-keys]
157 return android::base::GetProperty("ro.build.fingerprint", "");
158}
159
Alex Deymo5e3ea272016-01-28 13:42:23 -0800160} // namespace
161
162UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700163 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800164 PrefsInterface* prefs,
165 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000166 HardwareInterface* hardware,
167 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800168 : daemon_state_(daemon_state),
169 prefs_(prefs),
170 boot_control_(boot_control),
171 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000172 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700173 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800174 clock_(new Clock()),
175 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
176 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800177 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400178 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700179 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800180}
181
182UpdateAttempterAndroid::~UpdateAttempterAndroid() {
183 // Release ourselves as the ActionProcessor's delegate to prevent
184 // re-scheduling the updates due to the processing stopped.
185 processor_->set_delegate(nullptr);
186}
187
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400188[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
189 string boot_id;
190 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
191 string old_boot_id;
192 // If no previous boot id found, treat as a reboot and write boot ID.
193 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
194 return true;
195 }
196 return old_boot_id != boot_id;
197}
198
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400199std::ostream& operator<<(std::ostream& out, OTAResult result) {
200 switch (result) {
201 case OTAResult::NOT_ATTEMPTED:
202 out << "OTAResult::NOT_ATTEMPTED";
203 break;
204 case OTAResult::ROLLED_BACK:
205 out << "OTAResult::ROLLED_BACK";
206 break;
207 case OTAResult::UPDATED_NEED_REBOOT:
208 out << "OTAResult::UPDATED_NEED_REBOOT";
209 break;
210 case OTAResult::OTA_SUCCESSFUL:
211 out << "OTAResult::OTA_SUCCESSFUL";
212 break;
213 }
214 return out;
215}
216
Alex Deymo5e3ea272016-01-28 13:42:23 -0800217void UpdateAttempterAndroid::Init() {
218 // In case of update_engine restart without a reboot we need to restore the
219 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700220 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400221 LOG(INFO) << "Updated installed but update_engine is restarted without "
222 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800223 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700224 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400225 const auto result = GetOTAUpdateResult();
226 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800227 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400228 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400229 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400230 }
231
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700232#ifdef _UE_SIDELOAD
233 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
234 << "ApplyPayload will call it later.";
235#else
Yifan Hong90965502020-02-19 15:22:47 -0800236 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700237#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700238 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800239}
240
241bool UpdateAttempterAndroid::ApplyPayload(
242 const string& payload_url,
243 int64_t payload_offset,
244 int64_t payload_size,
245 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700246 Error* error) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800247 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800248 return LogAndSetError(error,
249 __LINE__,
250 __FILE__,
251 "An update already applied, waiting for reboot",
252 ErrorCode::kUpdateAlreadyInstalled);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800253 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700254 if (processor_->IsRunning()) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800255 return LogAndSetError(error,
256 __LINE__,
257 __FILE__,
258 "Already processing an update, cancel it first.",
259 ErrorCode::kUpdateProcessing);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800260 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100261 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800262
Alex Deymo218397f2016-02-04 23:55:10 -0800263 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800264 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
265 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800266 }
267
Yifan Hongbd47d622019-12-13 14:59:58 -0800268 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800269
270 // Setup the InstallPlan based on the request.
271 install_plan_ = InstallPlan();
272
273 install_plan_.download_url = payload_url;
274 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800275 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800276 InstallPlan::Payload payload;
277 payload.size = payload_size;
278 if (!payload.size) {
Kokoa Matsuda3357e272024-10-18 13:59:05 +0900279 if (!android::base::ParseUint<uint64_t>(headers[kPayloadPropertyFileSize],
280 &payload.size)) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800281 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800282 }
283 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700284 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800285 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700286 LOG(WARNING) << "Unable to decode base64 file hash: "
287 << headers[kPayloadPropertyFileHash];
288 }
Kokoa Matsuda3357e272024-10-18 13:59:05 +0900289 if (!android::base::ParseUint<uint64_t>(headers[kPayloadPropertyMetadataSize],
290 &payload.metadata_size)) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800291 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800292 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700293 // The |payload.type| is not used anymore since minor_version 3.
294 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800295 install_plan_.payloads.push_back(payload);
296
Alex Deymo5e3ea272016-01-28 13:42:23 -0800297 // The |public_key_rsa| key would override the public key stored on disk.
298 install_plan_.public_key_rsa = "";
299
300 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
301 install_plan_.is_resume = !payload_id.empty() &&
302 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
303 if (!install_plan_.is_resume) {
Kelvin Zhange70fa762024-07-18 09:14:54 -0700304 LOG(INFO) << "Starting a new update " << payload_url
305 << " size: " << payload_size << " offset: " << payload_offset;
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700306 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700307 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
308
Alex Deymo5e3ea272016-01-28 13:42:23 -0800309 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
310 LOG(WARNING) << "Unable to save the update check response hash.";
311 }
312 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800313 install_plan_.source_slot = GetCurrentSlot();
314 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700315
Alex Deymofb905d92016-06-03 19:26:58 -0700316 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700317 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
318
Kelvin Zhang85a6d992023-10-23 10:40:58 -0700319 install_plan_.spl_downgrade =
320 GetHeaderAsBool(headers[kPayloadPropertySplDowngrade], false);
321
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000322 if (!IsProductionBuild()) {
323 install_plan_.disable_vabc =
324 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
325 }
326
Sen Jiangfe522822017-10-31 15:14:11 -0700327 install_plan_.switch_slot_on_reboot =
328 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
329
Tianjie Xu087de9d2019-11-01 17:11:22 -0700330 install_plan_.run_post_install =
331 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800332
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700333 // Skip writing verity if we're resuming and verity has already been written.
334 install_plan_.write_verity = true;
335 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
336 bool verity_written = false;
337 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
338 verity_written) {
339 install_plan_.write_verity = false;
340 }
341 }
342
Alex Deymo87792ea2016-07-25 15:40:36 -0700343 NetworkId network_id = kDefaultNetworkId;
344 if (!headers[kPayloadPropertyNetworkId].empty()) {
Kokoa Matsuda3357e272024-10-18 13:59:05 +0900345 if (!android::base::ParseUint<uint64_t>(headers[kPayloadPropertyNetworkId],
346 &network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700347 return LogAndSetGenericError(
Alex Deymo87792ea2016-07-25 15:40:36 -0700348 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700349 __LINE__,
350 __FILE__,
Alex Deymo87792ea2016-07-25 15:40:36 -0700351 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
352 }
353 if (!network_selector_->SetProcessNetwork(network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700354 return LogAndSetGenericError(
Sen Jiangcbd37c62017-09-12 15:04:35 -0700355 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700356 __LINE__,
357 __FILE__,
Sen Jiangcbd37c62017-09-12 15:04:35 -0700358 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700359 }
Daniel Zheng7ff60fd2024-01-29 08:38:17 -0800360 LOG(INFO) << "Using network ID: " << network_id;
Alex Deymo87792ea2016-07-25 15:40:36 -0700361 }
362
Alex Deymo5e3ea272016-01-28 13:42:23 -0800363 LOG(INFO) << "Using this install plan:";
364 install_plan_.Dump();
365
Amin Hassani667cf7b2018-07-25 14:32:00 -0700366 HttpFetcher* fetcher = nullptr;
367 if (FileFetcher::SupportedUrl(payload_url)) {
368 DLOG(INFO) << "Using FileFetcher for file URL.";
369 fetcher = new FileFetcher();
370 } else {
371#ifdef _UE_SIDELOAD
372 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800373 return false; // NOLINT, unreached but analyzer might not know.
374 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700375#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700376 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700377 if (!headers[kPayloadDownloadRetry].empty()) {
378 libcurl_fetcher->set_max_retry_count(
379 atoi(headers[kPayloadDownloadRetry].c_str()));
380 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700381 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
382 fetcher = libcurl_fetcher;
383#endif // _UE_SIDELOAD
384 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800385 // Setup extra headers.
Daniel Zheng31d9e552024-08-08 09:56:14 -0700386 if (!headers[kPayloadPropertyAuthorization].empty()) {
Alex Deymofdd6dec2016-03-03 22:35:43 -0800387 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
Daniel Zheng31d9e552024-08-08 09:56:14 -0700388 }
389 if (!headers[kPayloadPropertyUserAgent].empty()) {
Alex Deymofdd6dec2016-03-03 22:35:43 -0800390 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
Daniel Zheng31d9e552024-08-08 09:56:14 -0700391 }
392 if (!headers[kPayloadPropertyHTTPExtras].empty()) {
393 auto entries =
394 android::base::Split(headers[kPayloadPropertyHTTPExtras], " ");
395 for (auto& entry : entries) {
Daniel Zheng0215aa72024-08-14 15:38:53 -0700396 auto parts = android::base::Split(entry, ";");
Daniel Zheng31d9e552024-08-08 09:56:14 -0700397 if (parts.size() != 2) {
398 LOG(ERROR)
399 << "HTTP headers are not in expected format. "
Daniel Zheng0215aa72024-08-14 15:38:53 -0700400 "headers[kPayloadPropertyHTTPExtras] = key1;val1 key2;val2";
Daniel Zheng31d9e552024-08-08 09:56:14 -0700401 continue;
402 }
403 fetcher->SetHeader(parts[0], parts[1]);
404 }
405 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700406 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
407 LOG(INFO) << "Using proxy url from payload headers: "
408 << headers[kPayloadPropertyNetworkProxy];
409 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
410 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700411 if (!headers[kPayloadVABCNone].empty()) {
412 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000413 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800414 if (!headers[kPayloadEnableThreading].empty()) {
Kelvin Zhang944cdac2023-12-12 12:55:27 -0800415 const auto res = android::base::ParseBool(headers[kPayloadEnableThreading]);
416 if (res != android::base::ParseBoolResult::kError) {
417 install_plan_.enable_threading =
418 res == android::base::ParseBoolResult::kTrue;
419 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800420 }
421 if (!headers[kPayloadBatchedWrites].empty()) {
422 install_plan_.batched_writes = true;
423 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700424
Amin Hassani667cf7b2018-07-25 14:32:00 -0700425 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800426
Alex Deymo5e3ea272016-01-28 13:42:23 -0800427 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700428
429 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
430 // TODO(xunchang) report the metrics for unresumable updates
431
Amin Hassani667cf7b2018-07-25 14:32:00 -0700432 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800433 return true;
434}
435
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900436bool UpdateAttempterAndroid::ApplyPayload(
437 int fd,
438 int64_t payload_offset,
439 int64_t payload_size,
440 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700441 Error* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100442 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000443 // already running update will be terminated (existing file descriptor will be
444 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100445 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700446 return LogAndSetGenericError(
447 error,
448 __LINE__,
449 __FILE__,
450 "An update already applied, waiting for reboot");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100451 }
452 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700453 return LogAndSetGenericError(
454 error,
455 __LINE__,
456 __FILE__,
457 "Already processing an update, cancel it first.");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100458 }
459 DCHECK_EQ(status_, UpdateStatus::IDLE);
460
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900461 payload_fd_.reset(dup(fd));
462 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
463
464 return ApplyPayload(
465 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
466}
467
Daniel Zheng92f7d172023-06-22 14:31:37 -0700468bool UpdateAttempterAndroid::SuspendUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700469 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700470 return LogAndSetGenericError(
471 error, __LINE__, __FILE__, "No ongoing update to suspend.");
Alex Deymof2858572016-02-25 11:20:13 -0800472 processor_->SuspendProcessing();
473 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800474}
475
Daniel Zheng92f7d172023-06-22 14:31:37 -0700476bool UpdateAttempterAndroid::ResumeUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700477 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700478 return LogAndSetGenericError(
479 error, __LINE__, __FILE__, "No ongoing update to resume.");
Alex Deymof2858572016-02-25 11:20:13 -0800480 processor_->ResumeProcessing();
481 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800482}
483
Daniel Zheng92f7d172023-06-22 14:31:37 -0700484bool UpdateAttempterAndroid::CancelUpdate(Error* error) {
Kelvin Zhang542d8362025-01-17 10:34:34 -0800485 auto action = processor_->current_action();
486 if (action != nullptr &&
487 action->Type() == CleanupPreviousUpdateAction::StaticType()) {
488 return LogAndSetError(
489 error,
490 __LINE__,
491 __FILE__,
492 "CleanupPreviousUpdateAction is running, this action cannot be "
493 "canceled. As it often performs critical merge operations after "
494 "reboot.",
495 ErrorCode::kRollbackNotPossible);
496 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700497 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700498 return LogAndSetGenericError(
499 error, __LINE__, __FILE__, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800500 processor_->StopProcessing();
501 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800502}
503
Daniel Zheng92f7d172023-06-22 14:31:37 -0700504bool UpdateAttempterAndroid::ResetStatus(Error* error) {
Alex Deymo3b678db2016-02-09 11:50:06 -0800505 LOG(INFO) << "Attempting to reset state from "
506 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700507 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700508 return LogAndSetGenericError(
509 error,
510 __LINE__,
511 __FILE__,
512 "Already processing an update, cancel it first.");
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700513 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700514 if (status_ != UpdateStatus::IDLE &&
515 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700516 return LogAndSetGenericError(
517 error,
518 __LINE__,
519 __FILE__,
520 "Status reset not allowed in this state, please "
521 "cancel on going OTA first.");
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700522 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800523
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000524 if (apex_handler_android_ != nullptr) {
525 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
526 std::vector<ApexInfo> apex_infos_blank;
527 apex_handler_android_->AllocateSpace(apex_infos_blank);
528 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400529 // Remove the reboot marker so that if the machine is rebooted
530 // after resetting to idle state, it doesn't go back to
531 // UpdateStatus::UPDATED_NEED_REBOOT state.
532 if (!ClearUpdateCompletedMarker()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700533 return LogAndSetGenericError(error,
534 __LINE__,
535 __FILE__,
536 "Failed to reset the status because "
537 "ClearUpdateCompletedMarker() failed");
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400538 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700539 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
540 if (!resetShouldSwitchSlotOnReboot(error)) {
541 LOG(INFO) << "Failed to reset slot switch.";
542 return false;
543 }
544 LOG(INFO) << "Slot switch reset successful";
545 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700546 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
547 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000548 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700549 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700550 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800551}
552
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700553bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
554 if (a.size() != b.size()) {
555 return false;
556 }
557 return memcmp(a.data(), b.data(), a.size()) == 0;
558}
559bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
560 return !(a == b);
561}
562
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -0800563bool VerifyPayloadMetadata(Error* error,
564 std::string_view metadata,
565 const PayloadMetadata& payload_metadata) {
566 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
567 constants::kUpdateCertificatesPath);
568 if (!payload_verifier) {
569 return LogAndSetError(error,
570 __LINE__,
571 __FILE__,
572 "Failed to create the payload verifier from " +
573 std::string(constants::kUpdateCertificatesPath),
574 ErrorCode::kDownloadManifestParseError);
575 }
576 auto errorcode = payload_metadata.ValidateMetadataSignature(
577 metadata, "", *payload_verifier);
578 if (errorcode != ErrorCode::kSuccess) {
579 return LogAndSetError(error,
580 __LINE__,
581 __FILE__,
582 "Failed to validate metadata signature: " +
583 utils::ErrorCodeToString(errorcode),
584 errorcode);
585 }
586 return true;
587}
588
Yifan Hongbd47d622019-12-13 14:59:58 -0800589bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
590 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700591 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800592 DeltaArchiveManifest* manifest,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700593 Error* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800594 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
595 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700596 return LogAndSetError(error,
597 __LINE__,
598 __FILE__,
599 "Failed to open " + metadata_filename,
600 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800601 }
602 brillo::Blob metadata(kMaxPayloadHeaderSize);
603 if (!fd->Read(metadata.data(), metadata.size())) {
604 return LogAndSetError(
605 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700606 __LINE__,
607 __FILE__,
608 "Failed to read payload header from " + metadata_filename,
609 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800610 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000611 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800612 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700613 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800614 MetadataParseResult::kSuccess) {
615 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700616 __LINE__,
617 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800618 "Failed to parse payload header: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700619 utils::ErrorCodeToString(errorcode),
620 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800621 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700622 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
623 payload_metadata.GetMetadataSignatureSize();
624 if (metadata_size < kMaxPayloadHeaderSize ||
625 metadata_size >
626 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800627 return LogAndSetError(
628 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700629 __LINE__,
630 __FILE__,
631 "Invalid metadata size: " + std::to_string(metadata_size),
632 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800633 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700634 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800635 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
636 metadata.size() - kMaxPayloadHeaderSize)) {
637 return LogAndSetError(
638 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700639 __LINE__,
640 __FILE__,
641 "Failed to read metadata and signature from " + metadata_filename,
642 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800643 }
644 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700645 if (!expected_metadata_hash.empty()) {
646 brillo::Blob metadata_hash;
647 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
648 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
649 if (metadata_hash != expected_metadata_hash) {
650 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700651 __LINE__,
652 __FILE__,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700653 "Metadata hash mismatch. Expected hash: " +
654 HexEncode(expected_metadata_hash) +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700655 " actual hash: " + HexEncode(metadata_hash),
656 ErrorCode::kDownloadManifestParseError);
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700657 } else {
658 LOG(INFO) << "Payload metadata hash check passed : "
659 << HexEncode(metadata_hash);
660 }
661 }
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -0800662 TEST_AND_RETURN_FALSE(
663 VerifyPayloadMetadata(error, ToStringView(metadata), payload_metadata));
Sen Jiang08c6da12019-01-07 18:28:56 -0800664
Yifan Hongbd47d622019-12-13 14:59:58 -0800665 if (!payload_metadata.GetManifest(metadata, manifest)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700666 return LogAndSetError(error,
667 __LINE__,
668 __FILE__,
669 "Failed to parse manifest.",
670 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800671 }
672
Yifan Hongbd47d622019-12-13 14:59:58 -0800673 return true;
674}
675
676bool UpdateAttempterAndroid::VerifyPayloadApplicable(
Daniel Zheng92f7d172023-06-22 14:31:37 -0700677 const std::string& metadata_filename, Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800678 DeltaArchiveManifest manifest;
679 TEST_AND_RETURN_FALSE(
680 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
681
682 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000683 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800684
685 BootControlInterface::Slot current_slot = GetCurrentSlot();
Kelvin Zhang1815c4d2023-11-07 14:21:18 -0800686 if (current_slot < 0) {
687 return LogAndSetError(
688 error,
689 __LINE__,
690 __FILE__,
691 "Failed to get current slot " + std::to_string(current_slot),
692 ErrorCode::kDownloadStateInitializationError);
693 }
Sen Jiang8371c1c2018-02-01 13:46:39 -0800694 for (const PartitionUpdate& partition : manifest.partitions()) {
695 if (!partition.has_old_partition_info())
696 continue;
697 string partition_path;
698 if (!boot_control_->GetPartitionDevice(
699 partition.partition_name(), current_slot, &partition_path)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700700 return LogAndSetGenericError(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800701 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700702 __LINE__,
703 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800704 "Failed to get partition device for " + partition.partition_name());
705 }
706 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700707 return LogAndSetGenericError(
708 error, __LINE__, __FILE__, "Failed to open " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800709 }
710 for (const InstallOperation& operation : partition.operations()) {
711 if (!operation.has_src_sha256_hash())
712 continue;
713 brillo::Blob source_hash;
714 if (!fd_utils::ReadAndHashExtents(fd,
715 operation.src_extents(),
716 manifest.block_size(),
717 &source_hash)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700718 return LogAndSetGenericError(
719 error, __LINE__, __FILE__, "Failed to hash " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800720 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400721 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800722 source_hash, operation, fd, &errorcode)) {
723 return false;
724 }
725 }
726 fd->Close();
727 }
728 return true;
729}
730
Alex Deymo5e3ea272016-01-28 13:42:23 -0800731void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
732 ErrorCode code) {
733 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800734 metric_bytes_downloaded_.Flush(true);
735 metric_total_bytes_downloaded_.Flush(true);
Yifan Hong90965502020-02-19 15:22:47 -0800736 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
737 TerminateUpdateAndNotify(code);
738 return;
739 }
740
Alex Deymo5990bf32016-07-19 17:01:41 -0700741 switch (code) {
742 case ErrorCode::kSuccess:
743 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400744 if (!WriteUpdateCompletedMarker()) {
745 LOG(ERROR) << "Failed to write update completion marker";
746 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700747 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800748
Alex Deymo5990bf32016-07-19 17:01:41 -0700749 LOG(INFO) << "Update successfully applied, waiting to reboot.";
750 break;
751
752 case ErrorCode::kFilesystemCopierError:
753 case ErrorCode::kNewRootfsVerificationError:
754 case ErrorCode::kNewKernelVerificationError:
755 case ErrorCode::kFilesystemVerifierError:
756 case ErrorCode::kDownloadStateInitializationError:
757 // Reset the ongoing update for these errors so it starts from the
758 // beginning next time.
759 DeltaPerformer::ResetUpdateProgress(prefs_, false);
760 LOG(INFO) << "Resetting update progress.";
761 break;
762
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700763 case ErrorCode::kPayloadTimestampError:
764 // SafetyNet logging, b/36232423
765 android_errorWriteLog(0x534e4554, "36232423");
766 break;
767
Alex Deymo5990bf32016-07-19 17:01:41 -0700768 default:
769 // Ignore all other error codes.
770 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700771 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800772
773 TerminateUpdateAndNotify(code);
774}
775
776void UpdateAttempterAndroid::ProcessingStopped(
777 const ActionProcessor* processor) {
778 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
779}
780
781void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
782 AbstractAction* action,
783 ErrorCode code) {
784 // Reset download progress regardless of whether or not the download
785 // action succeeded.
786 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800787 if (type == CleanupPreviousUpdateAction::StaticType() ||
788 (type == NoOpAction::StaticType() &&
789 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
790 cleanup_previous_update_code_ = code;
791 NotifyCleanupPreviousUpdateCallbacksAndClear();
792 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000793 // download_progress_ is actually used by other actions, such as
794 // filesystem_verify_action. Therefore we always clear it.
795 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700796 if (type == PostinstallRunnerAction::StaticType()) {
797 bool succeeded =
798 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
799 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
800 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800801 if (code != ErrorCode::kSuccess) {
802 // If an action failed, the ActionProcessor will cancel the whole thing.
803 return;
804 }
Yifan Hong83517502020-02-19 15:34:13 -0800805 if (type == UpdateBootFlagsAction::StaticType()) {
806 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
807 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800808 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400809 auto download_action = static_cast<DownloadAction*>(action);
810 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000811 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700812 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000813 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700814 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800815 }
816}
817
818void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
819 uint64_t bytes_received,
820 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700821 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800822 if (total)
823 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700824 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825 download_progress_ = progress;
826 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700827 } else {
828 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800829 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700830
831 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800832 metric_bytes_downloaded_ += bytes_progressed;
833 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800834}
835
836bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
837 // TODO(deymo): Notify the DownloadAction that it should cancel the update
838 // download.
839 return false;
840}
841
842void UpdateAttempterAndroid::DownloadComplete() {
843 // Nothing needs to be done when the download completes.
844}
845
Alex Deymo0d298542016-03-30 18:31:49 -0700846void UpdateAttempterAndroid::ProgressUpdate(double progress) {
847 // Self throttle based on progress. Also send notifications if progress is
848 // too slow.
849 if (progress == 1.0 ||
850 progress - download_progress_ >= kBroadcastThresholdProgress ||
851 TimeTicks::Now() - last_notify_time_ >=
852 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
853 download_progress_ = progress;
854 SetStatusAndNotify(status_);
855 }
856}
857
Kelvin Zhang70eef232020-06-12 20:32:40 +0000858void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
859 assert(status_ == UpdateStatus::VERIFYING);
860 ProgressUpdate(progress);
861}
862
Alex Deymo5e3ea272016-01-28 13:42:23 -0800863void UpdateAttempterAndroid::ScheduleProcessingStart() {
864 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700865 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800866 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700867 FROM_HERE,
868 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
869 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800870}
871
872void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
873 if (status_ == UpdateStatus::IDLE) {
874 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
875 return;
876 }
877
Yifan Hong90965502020-02-19 15:22:47 -0800878 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400879 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800880 LOG(INFO) << "Terminating cleanup previous update.";
881 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700882 for (auto observer : daemon_state_->service_observers())
883 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800884 return;
885 }
886
Yifan Hong9194ce82019-11-07 11:03:42 -0800887 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700888
Daniel Zheng57497982024-07-25 18:32:01 -0700889 for (auto observer : daemon_state_->service_observers())
890 observer->SendPayloadApplicationComplete(error_code);
891
Alex Deymo0d298542016-03-30 18:31:49 -0700892 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800893 UpdateStatus new_status =
894 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
895 : UpdateStatus::IDLE);
896 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900897 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800898
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700899 // The network id is only applicable to one download attempt and once it's
900 // done the network id should not be re-used anymore.
901 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
902 LOG(WARNING) << "Unable to unbind network.";
903 }
904
Tianjie Xu90aaa102017-10-10 17:39:03 -0700905 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
906 ClearMetricsPrefs();
907 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800908 // We should only reset the PayloadAttemptNumber if the update succeeds, or
909 // we switch to a different payload.
910 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700911 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700912 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800913 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700914 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800915}
916
917void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
918 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700919 size_t payload_size =
920 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700921 UpdateEngineStatus status_to_send = {.status = status_,
922 .progress = download_progress_,
923 .new_size_bytes = payload_size};
924
Alex Deymo5e3ea272016-01-28 13:42:23 -0800925 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700926 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800927 }
928 last_notify_time_ = TimeTicks::Now();
929}
930
Amin Hassani667cf7b2018-07-25 14:32:00 -0700931void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800932 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800933
934 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700935 auto update_boot_flags_action =
936 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800937 auto cleanup_previous_update_action =
938 boot_control_->GetDynamicPartitionControl()
939 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700940 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
941 auto download_action =
942 std::make_unique<DownloadAction>(prefs_,
943 boot_control_,
944 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700945 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700946 true /* interactive */,
947 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800948 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700949 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700950 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
951 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700952 auto postinstall_runner_action =
953 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000954 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700955 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800956
Alex Deymo5e3ea272016-01-28 13:42:23 -0800957 // Bond them together. We have to use the leaf-types when calling
958 // BondActions().
959 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700960 BondActions(download_action.get(), filesystem_verifier_action.get());
961 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800962 postinstall_runner_action.get());
963
Amin Hassani667cf7b2018-07-25 14:32:00 -0700964 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800965 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700966 processor_->EnqueueAction(std::move(install_plan_action));
967 processor_->EnqueueAction(std::move(download_action));
968 processor_->EnqueueAction(std::move(filesystem_verifier_action));
969 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800970}
971
Alex Deymo5e3ea272016-01-28 13:42:23 -0800972bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
973 string boot_id;
974 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800975 LOG(INFO) << "Writing update complete marker, slot "
976 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400977 TEST_AND_RETURN_FALSE(
978 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
979 TEST_AND_RETURN_FALSE(
980 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
981 return true;
982}
983
984bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
985 LOG(INFO) << "Clearing update complete marker.";
986 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
987 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800988 return true;
989}
990
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800991bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800992 // In case of an update_engine restart without a reboot, we stored the boot_id
993 // when the update was completed by setting a pref, so we can check whether
994 // the last update was on this boot or a previous one.
995 string boot_id;
996 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
997
998 string update_completed_on_boot_id;
999 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
1000 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
1001 &update_completed_on_boot_id) &&
1002 update_completed_on_boot_id == boot_id);
1003}
1004
Tianjie Xu90aaa102017-10-10 17:39:03 -07001005// Collect and report the android metrics when we terminate the update.
1006void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
1007 ErrorCode error_code) {
1008 int64_t attempt_number =
1009 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1010 PayloadType payload_type = kPayloadTypeFull;
1011 int64_t payload_size = 0;
1012 for (const auto& p : install_plan_.payloads) {
1013 if (p.type == InstallPayloadType::kDelta)
1014 payload_type = kPayloadTypeDelta;
1015 payload_size += p.size;
1016 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001017 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
1018 // function will be triggered, but payload_size in this case might be 0, if so
1019 // skip reporting any metrics.
1020 if (payload_size == 0) {
1021 return;
1022 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001023
1024 metrics::AttemptResult attempt_result =
1025 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001026 Time boot_time_start = Time::FromInternalValue(
1027 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
1028 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -07001029 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001030 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
1031 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001032
1033 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -07001034 static_cast<int>(attempt_number),
1035 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001036 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001037 duration_uptime,
1038 payload_size,
1039 attempt_result,
1040 error_code);
1041
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001042 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001043 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
1044 current_bytes_downloaded,
1045 0,
1046 DownloadSource::kNumDownloadSources,
1047 metrics::DownloadErrorCode::kUnset,
1048 metrics::ConnectionType::kUnset);
1049
Tianjie Xu90aaa102017-10-10 17:39:03 -07001050 if (error_code == ErrorCode::kSuccess) {
1051 int64_t reboot_count =
1052 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1053 string build_version;
1054 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -07001055
1056 // For android metrics, we only care about the total bytes downloaded
1057 // for all sources; for now we assume the only download source is
1058 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001059 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001060 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
1061 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
1062 total_bytes_downloaded;
1063
1064 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -07001065 if (total_bytes_downloaded >= payload_size) {
1066 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -07001067 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -07001068 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
1069 } else {
1070 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
1071 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -07001072 }
Tianjie Xu21030c12019-08-14 13:00:23 -07001073
Tianjie Xu90aaa102017-10-10 17:39:03 -07001074 metrics_reporter_->ReportSuccessfulUpdateMetrics(
1075 static_cast<int>(attempt_number),
1076 0, // update abandoned count
1077 payload_type,
1078 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -07001079 num_bytes_downloaded,
1080 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001081 duration,
Sen Jiang8712e962018-05-08 12:12:28 -07001082 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001083 static_cast<int>(reboot_count),
1084 0); // url_switch_count
1085 }
1086}
1087
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001088bool UpdateAttempterAndroid::OTARebootSucceeded() const {
1089 const auto current_slot = boot_control_->GetCurrentSlot();
Kelvin Zhang13020502023-08-02 15:18:40 -07001090 const string current_version = GetCurrentBuildVersion();
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001091 int64_t previous_slot = -1;
1092 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
1093 string previous_version;
1094 TEST_AND_RETURN_FALSE(
1095 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
1096 if (previous_slot != current_slot) {
1097 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001098 << previous_version << " to " << current_version
1099 << ", previous slot: " << previous_slot
1100 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001101 if (previous_version == current_version) {
1102 LOG(INFO) << "Previous version is the same as current version, this is "
1103 "possibly a self-OTA.";
1104 }
1105 return true;
1106 } else {
1107 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
1108 "switch never happened, or system not rebooted at all.";
1109 if (previous_version != current_version) {
1110 LOG(INFO) << "Slot didn't change, but version changed from "
1111 << previous_version << " to " << current_version
1112 << " device could be flashed.";
1113 }
1114 return false;
1115 }
1116}
1117
1118OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
1119 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
1120 // existence of this pref is sufficient indicator. Given that we have to
1121 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001122 // |DeltaPerformer::ResetUpdateProgress| and
1123 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001124 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1125 auto system_rebooted = DidSystemReboot(prefs_);
1126 auto ota_successful = OTARebootSucceeded();
1127 if (ota_successful) {
1128 return OTAResult::OTA_SUCCESSFUL;
1129 }
1130 if (slot_switch_attempted) {
1131 if (system_rebooted) {
1132 // If we attempted slot switch, but still end up on the same slot, we
1133 // probably rolled back.
1134 return OTAResult::ROLLED_BACK;
1135 } else {
1136 return OTAResult::UPDATED_NEED_REBOOT;
1137 }
1138 }
1139 return OTAResult::NOT_ATTEMPTED;
1140}
1141
1142void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Kelvin Zhang13020502023-08-02 15:18:40 -07001143 const string current_version = GetCurrentBuildVersion();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001144 TEST_AND_RETURN(!current_version.empty());
1145
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001146 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1147 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001148 string current_boot_id;
1149 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1150 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001151 std::string slot_switch_indicator;
1152 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1153 if (slot_switch_indicator != current_boot_id) {
1154 ClearUpdateCompletedMarker();
1155 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001156
Tianjie Xu90aaa102017-10-10 17:39:03 -07001157 // If there's no record of previous version (e.g. due to a data wipe), we
1158 // save the info of current boot and skip the metrics report.
1159 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001160 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001161 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001162 ClearMetricsPrefs();
1163 return;
1164 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001165 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001166 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001167 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1168 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001169 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001170 int64_t reboot_count =
1171 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1172 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1173 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001174
1175 if (result == OTAResult::ROLLED_BACK) {
1176 // This will release all space previously allocated for apex
1177 // decompression. If we detect a rollback, we should release space and
1178 // return the space to user. Any subsequent attempt to install OTA will
1179 // allocate space again anyway.
1180 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1181 "deompression.";
1182 apex_handler_android_->AllocateSpace({});
1183 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1184 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001185 return;
1186 }
1187
1188 // Now that the build version changes, report the update metrics.
1189 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001190 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001191 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001192
1193 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1194 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1195 if (previous_attempt_exists) {
1196 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1197 }
1198
1199 metrics_utils::LoadAndReportTimeToReboot(
1200 metrics_reporter_.get(), prefs_, clock_.get());
1201 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001202
1203 // Also reset the update progress if the build version has changed.
1204 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1205 LOG(WARNING) << "Unable to reset the update progress.";
1206 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001207}
1208
1209// Save the update start time. Reset the reboot count and attempt number if the
1210// update isn't a resume; otherwise increment the attempt number.
1211void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1212 if (!is_resume) {
1213 metrics_utils::SetNumReboots(0, prefs_);
1214 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1215 } else {
1216 int64_t attempt_number =
1217 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1218 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1219 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001220 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1221 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001222 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001223}
1224
1225void UpdateAttempterAndroid::ClearMetricsPrefs() {
1226 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001227 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001228 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001229 prefs_->Delete(kPrefsSystemUpdatedMarker);
1230 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001231 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001232}
1233
Yifan Hongbd47d622019-12-13 14:59:58 -08001234BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1235 return boot_control_->GetCurrentSlot();
1236}
1237
1238BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1239 return GetCurrentSlot() == 0 ? 1 : 0;
1240}
1241
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001242uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1243 const std::string& metadata_filename,
1244 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001245 Error* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001246 std::map<string, string> headers;
1247 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1248 return 0;
1249 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001250 DeltaArchiveManifest manifest;
1251 brillo::Blob metadata_hash;
1252 if (!brillo::data_encoding::Base64Decode(
1253 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1254 metadata_hash.clear();
1255 }
1256 if (!VerifyPayloadParseManifest(
1257 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1258 return 0;
1259 }
Yifan Hong65613032020-01-09 17:52:13 -08001260
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001261 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1262 manifest.apex_info().end());
1263 uint64_t apex_size_required = 0;
1264 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001265 auto result = apex_handler_android_->CalculateSize(apex_infos);
1266 if (!result.ok()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001267 LogAndSetGenericError(
1268 error,
1269 __LINE__,
1270 __FILE__,
1271 "Failed to calculate size required for compressed APEX");
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001272 return 0;
1273 }
1274 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001275 }
1276
Yifan Hong65613032020-01-09 17:52:13 -08001277 string payload_id = GetPayloadId(headers);
1278 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -07001279 ErrorCode error_code{};
1280
Yifan Hong65613032020-01-09 17:52:13 -08001281 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1282 boot_control_,
1283 GetTargetSlot(),
1284 manifest,
1285 payload_id,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001286 &required_size,
1287 &error_code)) {
1288 if (error_code == ErrorCode::kOverlayfsenabledError) {
1289 LogAndSetError(error,
1290 __LINE__,
1291 __FILE__,
1292 "OverlayFS Shouldn't be enabled for OTA.",
1293 error_code);
1294 return 0;
1295 }
Yifan Hong65613032020-01-09 17:52:13 -08001296 if (required_size == 0) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001297 LogAndSetGenericError(
1298 error, __LINE__, __FILE__, "Failed to allocate space for payload.");
Yifan Hong65613032020-01-09 17:52:13 -08001299 return 0;
1300 } else {
1301 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001302 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001303 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001304 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001305 }
1306 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001307
1308 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001309 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001310 LOG(ERROR) << "Insufficient space for apex decompression: "
1311 << apex_size_required << " bytes";
1312 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001313 }
Yifan Hong65613032020-01-09 17:52:13 -08001314
1315 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001316 return 0;
1317}
1318
Yifan Hong40bb0d02020-02-24 17:33:14 -08001319void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1320 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001321 Error* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001322 if (cleanup_previous_update_code_.has_value()) {
1323 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1324 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1325 if (callback) {
1326 callback->OnCleanupComplete(
1327 static_cast<int32_t>(*cleanup_previous_update_code_));
1328 }
1329 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001330 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001331 if (callback) {
1332 auto callback_ptr = callback.get();
1333 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
Kelvin Zhang2f6c25a2023-07-05 12:49:34 -07001334 callback_ptr->RegisterForDeathNotifications([this, callback_ptr]() {
1335 RemoveCleanupPreviousUpdateCallback(callback_ptr);
1336 });
Yifan Hong40bb0d02020-02-24 17:33:14 -08001337 }
1338 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001339}
1340
Tianjie7f8f2ab2021-07-23 17:08:50 -07001341bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
Daniel Zheng92f7d172023-06-22 14:31:37 -07001342 const std::string& metadata_filename, Error* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001343 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001344 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001345 return LogAndSetGenericError(
1346 error,
1347 __LINE__,
1348 __FILE__,
1349 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001350 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001351 DeltaArchiveManifest manifest;
1352 TEST_AND_RETURN_FALSE(
1353 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1354
Kelvin Zhang20982a52021-08-13 12:31:16 -07001355 InstallPlan install_plan_;
1356 install_plan_.source_slot = GetCurrentSlot();
1357 install_plan_.target_slot = GetTargetSlot();
1358 // Don't do verity computation, just hash the partitions
1359 install_plan_.write_verity = false;
1360 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1361 install_plan_.run_post_install = false;
1362 install_plan_.is_resume = true;
Kelvin Zhange227d992024-11-06 09:14:42 -08001363 // previous ApplyPayload() call may have requested powerwash, these
1364 // settings would be saved in `this->install_plan_`. Inherit that setting.
1365 install_plan_.powerwash_required = this->install_plan_.powerwash_required;
Kelvin Zhang67b43782025-02-10 11:06:22 -08001366 install_plan_.switch_slot_on_reboot = true;
Kelvin Zhang20982a52021-08-13 12:31:16 -07001367
1368 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1369 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1370
Kelvin Zhang20982a52021-08-13 12:31:16 -07001371 auto postinstall_runner_action =
1372 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001373 postinstall_runner_action->set_delegate(this);
1374
Kelvin Zhang8ab0f412024-12-03 12:27:28 -08001375 // If |kPrefsPostInstallSucceeded| is set, we know that we reached this
1376 // state by calling applyPayload() That applyPayload() call would have
1377 // already performed filesystem verification, therefore, we
Kelvin Zhangf8441982022-12-07 18:18:47 -08001378 // can safely skip the verification to save time.
Kelvin Zhang8ab0f412024-12-03 12:27:28 -08001379 bool postinstall_succeeded = false;
1380 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded, &postinstall_succeeded) &&
1381 postinstall_succeeded) {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001382 auto install_plan_action =
1383 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001384 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1385 processor_->EnqueueAction(std::move(install_plan_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001386 SetStatusAndNotify(UpdateStatus::FINALIZING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001387 } else {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001388 ErrorCode error_code{};
Kelvin Zhang263a5402022-12-08 23:03:32 -08001389 if (!boot_control_->GetDynamicPartitionControl()
1390 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1391 GetTargetSlot(),
1392 manifest,
1393 false /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001394 nullptr,
1395 &error_code)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001396 return LogAndSetGenericError(
1397 error, __LINE__, __FILE__, "Failed to PreparePartitionsForUpdate");
Kelvin Zhang263a5402022-12-08 23:03:32 -08001398 }
Kelvin Zhang263a5402022-12-08 23:03:32 -08001399 if (!install_plan_.ParsePartitions(manifest.partitions(),
1400 boot_control_,
1401 manifest.block_size(),
1402 &error_code)) {
1403 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001404 __LINE__,
1405 __FILE__,
Kelvin Zhang263a5402022-12-08 23:03:32 -08001406 "Failed to LoadPartitionsFromSlots " +
Daniel Zheng92f7d172023-06-22 14:31:37 -07001407 utils::ErrorCodeToString(error_code),
1408 error_code);
Kelvin Zhang263a5402022-12-08 23:03:32 -08001409 }
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001410 auto install_plan_action =
1411 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001412 auto filesystem_verifier_action =
1413 std::make_unique<FilesystemVerifierAction>(
1414 boot_control_->GetDynamicPartitionControl());
1415 filesystem_verifier_action->set_delegate(this);
1416 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1417 BondActions(filesystem_verifier_action.get(),
1418 postinstall_runner_action.get());
1419 processor_->EnqueueAction(std::move(install_plan_action));
1420 processor_->EnqueueAction(std::move(filesystem_verifier_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001421 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001422 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001423
Kelvin Zhang20982a52021-08-13 12:31:16 -07001424 processor_->EnqueueAction(std::move(postinstall_runner_action));
1425 ScheduleProcessingStart();
1426 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001427}
1428
Daniel Zheng92f7d172023-06-22 14:31:37 -07001429bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(Error* error) {
Tianjie7f8f2ab2021-07-23 17:08:50 -07001430 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001431 return LogAndSetGenericError(
1432 error,
1433 __LINE__,
1434 __FILE__,
1435 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001436 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001437 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001438 // Update the boot flags so the current slot has higher priority.
1439 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001440 return LogAndSetGenericError(
1441 error, __LINE__, __FILE__, "Failed to SetActiveBootSlot");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001442 }
1443
1444 // Mark the current slot as successful again, since marking it as active
1445 // may reset the successful bit. We ignore the result of whether marking
1446 // the current slot as successful worked.
1447 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001448 return LogAndSetGenericError(
1449 error, __LINE__, __FILE__, "Failed to MarkBootSuccessfulAsync");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001450 }
1451
1452 // Resets the warm reset property since we won't switch the slot.
1453 hardware_->SetWarmReset(false);
1454
1455 // Resets the vbmeta digest.
1456 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1457 LOG(INFO) << "Slot switch cancelled.";
1458 SetStatusAndNotify(UpdateStatus::IDLE);
1459 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001460}
1461
Yifan Hong90965502020-02-19 15:22:47 -08001462void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1463 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1464 // is in progress, skip enqueueing the action.
1465 if (processor_->IsRunning()) {
1466 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1467 << "be done when the current update finishes.";
1468 return;
1469 }
1470 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1471 auto action =
1472 boot_control_->GetDynamicPartitionControl()
1473 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1474 processor_->EnqueueAction(std::move(action));
1475 processor_->set_delegate(this);
1476 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1477 processor_->StartProcessing();
1478}
1479
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001480bool ParsePayloadMetadata(Error* error,
1481 std::string_view manifest_bytes,
1482 DeltaArchiveManifest* manifest) {
1483 PayloadMetadata payload_metadata;
1484 ErrorCode errorcode{};
1485 if (payload_metadata.ParsePayloadHeader(manifest_bytes, &errorcode) !=
1486 MetadataParseResult::kSuccess) {
1487 return LogAndSetError(error,
1488 __LINE__,
1489 __FILE__,
1490 "Failed to parse payload header: " +
1491 utils::ErrorCodeToString(errorcode),
1492 errorcode);
1493 }
1494 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
1495 payload_metadata.GetMetadataSignatureSize();
1496 if (metadata_size < kMaxPayloadHeaderSize ||
1497 metadata_size > manifest_bytes.size()) {
1498 return LogAndSetError(error,
1499 __LINE__,
1500 __FILE__,
1501 "Invalid metadata size on cached manifest: " +
1502 std::to_string(metadata_size),
1503 ErrorCode::kDownloadManifestParseError);
1504 }
1505 TEST_AND_RETURN_FALSE(
1506 VerifyPayloadMetadata(error, manifest_bytes, payload_metadata));
1507
1508 if (!payload_metadata.GetManifest(manifest_bytes, manifest)) {
1509 return LogAndSetError(error,
1510 __LINE__,
1511 __FILE__,
1512 "Failed to parse manifest. Might need to install "
1513 "OTA first and re-try this API",
1514 ErrorCode::kDownloadManifestParseError);
1515 }
1516 return true;
1517}
1518
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001519bool UpdateAttempterAndroid::TriggerPostinstall(const std::string& partition,
1520 Error* error) {
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001521 if (processor_->IsRunning()) {
1522 return LogAndSetError(error,
1523 __LINE__,
1524 __FILE__,
1525 "Already processing an update, cancel it first.",
1526 ErrorCode::kUpdateProcessing);
1527 }
1528 bool postinstall_succeeded = false;
1529 if (!prefs_->GetBoolean(kPrefsPostInstallSucceeded, &postinstall_succeeded)) {
1530 return LogAndSetError(
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001531 error,
1532 __LINE__,
1533 __FILE__,
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001534 "Postinstall action did not run. "
1535 "OTA update must first reach the "
1536 "Postinstall phase(which verfies that all partitions can be mounted) "
1537 "before calling TriggerPostinstall",
1538 ErrorCode::kPostinstallRunnerError);
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001539 }
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001540 if (!postinstall_succeeded) {
1541 return LogAndSetError(
1542 error,
1543 __LINE__,
1544 __FILE__,
1545 "Postinstall action did not complete successfully. "
1546 "OTA update must first reach the "
1547 "Postinstall phase(which verfies that all partitions can be mounted) "
1548 "before calling TriggerPostinstall",
1549 ErrorCode::kPostinstallRunnerError);
1550 }
1551
1552 InstallPlan install_plan;
1553 install_plan.source_slot = GetCurrentSlot();
1554 install_plan.target_slot = GetTargetSlot();
1555 install_plan.switch_slot_on_reboot = false;
1556 install_plan.run_post_install = true;
1557 install_plan.download_url =
1558 std::string(kPrefsManifestBytes) + ":" + install_plan_.download_url;
1559
1560 std::string manifest_bytes;
1561 // kPrefsManifestBytes is set during DownloadAction
1562 if (!prefs_->GetString(kPrefsManifestBytes, &manifest_bytes)) {
1563 return LogAndSetError(
1564 error,
1565 __LINE__,
1566 __FILE__,
1567 "Cached manifest not found. TriggerPostinstall can only be called "
1568 "after OTA get past at least FilesystemVerification stage",
1569 ErrorCode::kDownloadStateInitializationError);
1570 }
1571 DeltaArchiveManifest manifest;
1572 TEST_AND_RETURN_FALSE(ParsePayloadMetadata(error, manifest_bytes, &manifest));
1573 ErrorCode errorcode{};
1574 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1575 GetCurrentSlot(),
1576 GetTargetSlot(),
1577 manifest,
1578 false /* should update */,
1579 nullptr,
1580 &errorcode)) {
1581 return LogAndSetError(error,
1582 __LINE__,
1583 __FILE__,
1584 "Failed to PreparePartitionsForUpdate",
1585 errorcode);
1586 }
1587 std::vector<PartitionUpdate> partitions;
1588 std::copy_if(manifest.partitions().begin(),
1589 manifest.partitions().end(),
1590 std::back_inserter(partitions),
1591 [&partition](const PartitionUpdate& part) {
1592 return part.partition_name() == partition;
1593 });
1594 if (partitions.empty()) {
1595 return LogAndSetError(error,
1596 __LINE__,
1597 __FILE__,
1598 "Partition " + partition + " not found",
1599 ErrorCode::kDownloadStateInitializationError);
1600 }
1601 // We only want to trigger postinstall for a specific partition,
1602 // and since we already checked partitions array is non-empty, reading just
1603 // the first partition is enough.
1604 if (!partitions[0].has_postinstall_path() ||
1605 partitions[0].postinstall_path().empty()) {
1606 return LogAndSetError(error,
1607 __LINE__,
1608 __FILE__,
1609 "Partition " + partition +
1610 " does not have a postinstall script defined",
1611 ErrorCode::kDownloadStateInitializationError);
1612 }
1613 if (!install_plan.ParsePartitions(
1614 partitions, boot_control_, manifest.block_size(), &errorcode)) {
1615 return LogAndSetError(error,
1616 __LINE__,
1617 __FILE__,
1618 "Failed to parse manifest partitions. Might need "
1619 "to install OTA first and re-try this API",
1620 ErrorCode::kDownloadManifestParseError);
1621 }
1622 LOG(INFO) << "Trigger postinstall with this install plan: "
1623 << install_plan.ToString();
1624
1625 auto postinstall_runner_action =
1626 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1627 postinstall_runner_action->set_delegate(this);
1628
1629 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan);
1630 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1631 processor_->EnqueueAction(std::move(install_plan_action));
1632 processor_->EnqueueAction(std::move(postinstall_runner_action));
1633 SetStatusAndNotify(UpdateStatus::FINALIZING);
1634 ScheduleProcessingStart();
1635 return true;
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001636}
1637
Yifan Hong40bb0d02020-02-24 17:33:14 -08001638void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1639 for (auto&& callback : cleanup_previous_update_callbacks_) {
1640 callback->OnCleanupProgressUpdate(progress);
1641 }
1642}
1643
1644void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1645 CHECK(cleanup_previous_update_code_.has_value());
1646 for (auto&& callback : cleanup_previous_update_callbacks_) {
1647 callback->OnCleanupComplete(
1648 static_cast<int32_t>(*cleanup_previous_update_code_));
1649 }
1650 cleanup_previous_update_callbacks_.clear();
1651}
1652
1653void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1654 CleanupSuccessfulUpdateCallbackInterface* callback) {
1655 auto end_it =
1656 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1657 cleanup_previous_update_callbacks_.end(),
1658 [&](const auto& e) { return e.get() == callback; });
1659 cleanup_previous_update_callbacks_.erase(
1660 end_it, cleanup_previous_update_callbacks_.end());
1661}
Yifan Hong90965502020-02-19 15:22:47 -08001662
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001663bool UpdateAttempterAndroid::IsProductionBuild() {
1664 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1665 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1666 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1667 return true;
1668 }
1669 return false;
1670}
1671
Alex Deymo5e3ea272016-01-28 13:42:23 -08001672} // namespace chromeos_update_engine