blob: 89c79f3b5767073994b1cddfda0177de3e027368 [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) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700485 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700486 return LogAndSetGenericError(
487 error, __LINE__, __FILE__, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800488 processor_->StopProcessing();
489 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800490}
491
Daniel Zheng92f7d172023-06-22 14:31:37 -0700492bool UpdateAttempterAndroid::ResetStatus(Error* error) {
Alex Deymo3b678db2016-02-09 11:50:06 -0800493 LOG(INFO) << "Attempting to reset state from "
494 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700495 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700496 return LogAndSetGenericError(
497 error,
498 __LINE__,
499 __FILE__,
500 "Already processing an update, cancel it first.");
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700501 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700502 if (status_ != UpdateStatus::IDLE &&
503 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700504 return LogAndSetGenericError(
505 error,
506 __LINE__,
507 __FILE__,
508 "Status reset not allowed in this state, please "
509 "cancel on going OTA first.");
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700510 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800511
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000512 if (apex_handler_android_ != nullptr) {
513 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
514 std::vector<ApexInfo> apex_infos_blank;
515 apex_handler_android_->AllocateSpace(apex_infos_blank);
516 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400517 // Remove the reboot marker so that if the machine is rebooted
518 // after resetting to idle state, it doesn't go back to
519 // UpdateStatus::UPDATED_NEED_REBOOT state.
520 if (!ClearUpdateCompletedMarker()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700521 return LogAndSetGenericError(error,
522 __LINE__,
523 __FILE__,
524 "Failed to reset the status because "
525 "ClearUpdateCompletedMarker() failed");
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400526 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700527 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
528 if (!resetShouldSwitchSlotOnReboot(error)) {
529 LOG(INFO) << "Failed to reset slot switch.";
530 return false;
531 }
532 LOG(INFO) << "Slot switch reset successful";
533 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700534 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
535 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000536 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700537 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700538 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800539}
540
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700541bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
542 if (a.size() != b.size()) {
543 return false;
544 }
545 return memcmp(a.data(), b.data(), a.size()) == 0;
546}
547bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
548 return !(a == b);
549}
550
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -0800551bool VerifyPayloadMetadata(Error* error,
552 std::string_view metadata,
553 const PayloadMetadata& payload_metadata) {
554 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
555 constants::kUpdateCertificatesPath);
556 if (!payload_verifier) {
557 return LogAndSetError(error,
558 __LINE__,
559 __FILE__,
560 "Failed to create the payload verifier from " +
561 std::string(constants::kUpdateCertificatesPath),
562 ErrorCode::kDownloadManifestParseError);
563 }
564 auto errorcode = payload_metadata.ValidateMetadataSignature(
565 metadata, "", *payload_verifier);
566 if (errorcode != ErrorCode::kSuccess) {
567 return LogAndSetError(error,
568 __LINE__,
569 __FILE__,
570 "Failed to validate metadata signature: " +
571 utils::ErrorCodeToString(errorcode),
572 errorcode);
573 }
574 return true;
575}
576
Yifan Hongbd47d622019-12-13 14:59:58 -0800577bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
578 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700579 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800580 DeltaArchiveManifest* manifest,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700581 Error* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800582 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
583 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700584 return LogAndSetError(error,
585 __LINE__,
586 __FILE__,
587 "Failed to open " + metadata_filename,
588 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800589 }
590 brillo::Blob metadata(kMaxPayloadHeaderSize);
591 if (!fd->Read(metadata.data(), metadata.size())) {
592 return LogAndSetError(
593 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700594 __LINE__,
595 __FILE__,
596 "Failed to read payload header from " + metadata_filename,
597 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800598 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000599 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800600 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700601 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800602 MetadataParseResult::kSuccess) {
603 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700604 __LINE__,
605 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800606 "Failed to parse payload header: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700607 utils::ErrorCodeToString(errorcode),
608 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800609 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700610 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
611 payload_metadata.GetMetadataSignatureSize();
612 if (metadata_size < kMaxPayloadHeaderSize ||
613 metadata_size >
614 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800615 return LogAndSetError(
616 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700617 __LINE__,
618 __FILE__,
619 "Invalid metadata size: " + std::to_string(metadata_size),
620 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800621 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700622 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800623 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
624 metadata.size() - kMaxPayloadHeaderSize)) {
625 return LogAndSetError(
626 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700627 __LINE__,
628 __FILE__,
629 "Failed to read metadata and signature from " + metadata_filename,
630 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800631 }
632 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700633 if (!expected_metadata_hash.empty()) {
634 brillo::Blob metadata_hash;
635 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
636 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
637 if (metadata_hash != expected_metadata_hash) {
638 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700639 __LINE__,
640 __FILE__,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700641 "Metadata hash mismatch. Expected hash: " +
642 HexEncode(expected_metadata_hash) +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700643 " actual hash: " + HexEncode(metadata_hash),
644 ErrorCode::kDownloadManifestParseError);
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700645 } else {
646 LOG(INFO) << "Payload metadata hash check passed : "
647 << HexEncode(metadata_hash);
648 }
649 }
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -0800650 TEST_AND_RETURN_FALSE(
651 VerifyPayloadMetadata(error, ToStringView(metadata), payload_metadata));
Sen Jiang08c6da12019-01-07 18:28:56 -0800652
Yifan Hongbd47d622019-12-13 14:59:58 -0800653 if (!payload_metadata.GetManifest(metadata, manifest)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700654 return LogAndSetError(error,
655 __LINE__,
656 __FILE__,
657 "Failed to parse manifest.",
658 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800659 }
660
Yifan Hongbd47d622019-12-13 14:59:58 -0800661 return true;
662}
663
664bool UpdateAttempterAndroid::VerifyPayloadApplicable(
Daniel Zheng92f7d172023-06-22 14:31:37 -0700665 const std::string& metadata_filename, Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800666 DeltaArchiveManifest manifest;
667 TEST_AND_RETURN_FALSE(
668 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
669
670 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000671 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800672
673 BootControlInterface::Slot current_slot = GetCurrentSlot();
Kelvin Zhang1815c4d2023-11-07 14:21:18 -0800674 if (current_slot < 0) {
675 return LogAndSetError(
676 error,
677 __LINE__,
678 __FILE__,
679 "Failed to get current slot " + std::to_string(current_slot),
680 ErrorCode::kDownloadStateInitializationError);
681 }
Sen Jiang8371c1c2018-02-01 13:46:39 -0800682 for (const PartitionUpdate& partition : manifest.partitions()) {
683 if (!partition.has_old_partition_info())
684 continue;
685 string partition_path;
686 if (!boot_control_->GetPartitionDevice(
687 partition.partition_name(), current_slot, &partition_path)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700688 return LogAndSetGenericError(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800689 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700690 __LINE__,
691 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800692 "Failed to get partition device for " + partition.partition_name());
693 }
694 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700695 return LogAndSetGenericError(
696 error, __LINE__, __FILE__, "Failed to open " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800697 }
698 for (const InstallOperation& operation : partition.operations()) {
699 if (!operation.has_src_sha256_hash())
700 continue;
701 brillo::Blob source_hash;
702 if (!fd_utils::ReadAndHashExtents(fd,
703 operation.src_extents(),
704 manifest.block_size(),
705 &source_hash)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700706 return LogAndSetGenericError(
707 error, __LINE__, __FILE__, "Failed to hash " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800708 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400709 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800710 source_hash, operation, fd, &errorcode)) {
711 return false;
712 }
713 }
714 fd->Close();
715 }
716 return true;
717}
718
Alex Deymo5e3ea272016-01-28 13:42:23 -0800719void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
720 ErrorCode code) {
721 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800722 metric_bytes_downloaded_.Flush(true);
723 metric_total_bytes_downloaded_.Flush(true);
Yifan Hong90965502020-02-19 15:22:47 -0800724 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
725 TerminateUpdateAndNotify(code);
726 return;
727 }
728
Alex Deymo5990bf32016-07-19 17:01:41 -0700729 switch (code) {
730 case ErrorCode::kSuccess:
731 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400732 if (!WriteUpdateCompletedMarker()) {
733 LOG(ERROR) << "Failed to write update completion marker";
734 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700735 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800736
Alex Deymo5990bf32016-07-19 17:01:41 -0700737 LOG(INFO) << "Update successfully applied, waiting to reboot.";
738 break;
739
740 case ErrorCode::kFilesystemCopierError:
741 case ErrorCode::kNewRootfsVerificationError:
742 case ErrorCode::kNewKernelVerificationError:
743 case ErrorCode::kFilesystemVerifierError:
744 case ErrorCode::kDownloadStateInitializationError:
745 // Reset the ongoing update for these errors so it starts from the
746 // beginning next time.
747 DeltaPerformer::ResetUpdateProgress(prefs_, false);
748 LOG(INFO) << "Resetting update progress.";
749 break;
750
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700751 case ErrorCode::kPayloadTimestampError:
752 // SafetyNet logging, b/36232423
753 android_errorWriteLog(0x534e4554, "36232423");
754 break;
755
Alex Deymo5990bf32016-07-19 17:01:41 -0700756 default:
757 // Ignore all other error codes.
758 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700759 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800760
761 TerminateUpdateAndNotify(code);
762}
763
764void UpdateAttempterAndroid::ProcessingStopped(
765 const ActionProcessor* processor) {
766 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
767}
768
769void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
770 AbstractAction* action,
771 ErrorCode code) {
772 // Reset download progress regardless of whether or not the download
773 // action succeeded.
774 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800775 if (type == CleanupPreviousUpdateAction::StaticType() ||
776 (type == NoOpAction::StaticType() &&
777 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
778 cleanup_previous_update_code_ = code;
779 NotifyCleanupPreviousUpdateCallbacksAndClear();
780 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000781 // download_progress_ is actually used by other actions, such as
782 // filesystem_verify_action. Therefore we always clear it.
783 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700784 if (type == PostinstallRunnerAction::StaticType()) {
785 bool succeeded =
786 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
787 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
788 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800789 if (code != ErrorCode::kSuccess) {
790 // If an action failed, the ActionProcessor will cancel the whole thing.
791 return;
792 }
Yifan Hong83517502020-02-19 15:34:13 -0800793 if (type == UpdateBootFlagsAction::StaticType()) {
794 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
795 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800796 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400797 auto download_action = static_cast<DownloadAction*>(action);
798 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000799 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700800 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000801 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700802 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800803 }
804}
805
806void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
807 uint64_t bytes_received,
808 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700809 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800810 if (total)
811 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700812 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800813 download_progress_ = progress;
814 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700815 } else {
816 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800817 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700818
819 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800820 metric_bytes_downloaded_ += bytes_progressed;
821 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800822}
823
824bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
825 // TODO(deymo): Notify the DownloadAction that it should cancel the update
826 // download.
827 return false;
828}
829
830void UpdateAttempterAndroid::DownloadComplete() {
831 // Nothing needs to be done when the download completes.
832}
833
Alex Deymo0d298542016-03-30 18:31:49 -0700834void UpdateAttempterAndroid::ProgressUpdate(double progress) {
835 // Self throttle based on progress. Also send notifications if progress is
836 // too slow.
837 if (progress == 1.0 ||
838 progress - download_progress_ >= kBroadcastThresholdProgress ||
839 TimeTicks::Now() - last_notify_time_ >=
840 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
841 download_progress_ = progress;
842 SetStatusAndNotify(status_);
843 }
844}
845
Kelvin Zhang70eef232020-06-12 20:32:40 +0000846void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
847 assert(status_ == UpdateStatus::VERIFYING);
848 ProgressUpdate(progress);
849}
850
Alex Deymo5e3ea272016-01-28 13:42:23 -0800851void UpdateAttempterAndroid::ScheduleProcessingStart() {
852 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700853 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800854 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700855 FROM_HERE,
856 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
857 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800858}
859
860void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
861 if (status_ == UpdateStatus::IDLE) {
862 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
863 return;
864 }
865
Yifan Hong90965502020-02-19 15:22:47 -0800866 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400867 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800868 LOG(INFO) << "Terminating cleanup previous update.";
869 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700870 for (auto observer : daemon_state_->service_observers())
871 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800872 return;
873 }
874
Yifan Hong9194ce82019-11-07 11:03:42 -0800875 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700876
Daniel Zheng57497982024-07-25 18:32:01 -0700877 for (auto observer : daemon_state_->service_observers())
878 observer->SendPayloadApplicationComplete(error_code);
879
Alex Deymo0d298542016-03-30 18:31:49 -0700880 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800881 UpdateStatus new_status =
882 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
883 : UpdateStatus::IDLE);
884 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900885 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800886
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700887 // The network id is only applicable to one download attempt and once it's
888 // done the network id should not be re-used anymore.
889 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
890 LOG(WARNING) << "Unable to unbind network.";
891 }
892
Tianjie Xu90aaa102017-10-10 17:39:03 -0700893 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
894 ClearMetricsPrefs();
895 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800896 // We should only reset the PayloadAttemptNumber if the update succeeds, or
897 // we switch to a different payload.
898 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700899 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700900 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800901 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700902 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800903}
904
905void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
906 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700907 size_t payload_size =
908 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700909 UpdateEngineStatus status_to_send = {.status = status_,
910 .progress = download_progress_,
911 .new_size_bytes = payload_size};
912
Alex Deymo5e3ea272016-01-28 13:42:23 -0800913 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700914 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800915 }
916 last_notify_time_ = TimeTicks::Now();
917}
918
Amin Hassani667cf7b2018-07-25 14:32:00 -0700919void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800920 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800921
922 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700923 auto update_boot_flags_action =
924 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800925 auto cleanup_previous_update_action =
926 boot_control_->GetDynamicPartitionControl()
927 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700928 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
929 auto download_action =
930 std::make_unique<DownloadAction>(prefs_,
931 boot_control_,
932 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700933 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700934 true /* interactive */,
935 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800936 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700937 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700938 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
939 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700940 auto postinstall_runner_action =
941 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000942 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700943 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800944
Alex Deymo5e3ea272016-01-28 13:42:23 -0800945 // Bond them together. We have to use the leaf-types when calling
946 // BondActions().
947 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700948 BondActions(download_action.get(), filesystem_verifier_action.get());
949 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800950 postinstall_runner_action.get());
951
Amin Hassani667cf7b2018-07-25 14:32:00 -0700952 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800953 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700954 processor_->EnqueueAction(std::move(install_plan_action));
955 processor_->EnqueueAction(std::move(download_action));
956 processor_->EnqueueAction(std::move(filesystem_verifier_action));
957 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800958}
959
Alex Deymo5e3ea272016-01-28 13:42:23 -0800960bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
961 string boot_id;
962 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800963 LOG(INFO) << "Writing update complete marker, slot "
964 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400965 TEST_AND_RETURN_FALSE(
966 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
967 TEST_AND_RETURN_FALSE(
968 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
969 return true;
970}
971
972bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
973 LOG(INFO) << "Clearing update complete marker.";
974 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
975 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800976 return true;
977}
978
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800979bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800980 // In case of an update_engine restart without a reboot, we stored the boot_id
981 // when the update was completed by setting a pref, so we can check whether
982 // the last update was on this boot or a previous one.
983 string boot_id;
984 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
985
986 string update_completed_on_boot_id;
987 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
988 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
989 &update_completed_on_boot_id) &&
990 update_completed_on_boot_id == boot_id);
991}
992
Tianjie Xu90aaa102017-10-10 17:39:03 -0700993// Collect and report the android metrics when we terminate the update.
994void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
995 ErrorCode error_code) {
996 int64_t attempt_number =
997 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
998 PayloadType payload_type = kPayloadTypeFull;
999 int64_t payload_size = 0;
1000 for (const auto& p : install_plan_.payloads) {
1001 if (p.type == InstallPayloadType::kDelta)
1002 payload_type = kPayloadTypeDelta;
1003 payload_size += p.size;
1004 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001005 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
1006 // function will be triggered, but payload_size in this case might be 0, if so
1007 // skip reporting any metrics.
1008 if (payload_size == 0) {
1009 return;
1010 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001011
1012 metrics::AttemptResult attempt_result =
1013 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001014 Time boot_time_start = Time::FromInternalValue(
1015 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
1016 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -07001017 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001018 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
1019 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001020
1021 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -07001022 static_cast<int>(attempt_number),
1023 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001024 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001025 duration_uptime,
1026 payload_size,
1027 attempt_result,
1028 error_code);
1029
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001030 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001031 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
1032 current_bytes_downloaded,
1033 0,
1034 DownloadSource::kNumDownloadSources,
1035 metrics::DownloadErrorCode::kUnset,
1036 metrics::ConnectionType::kUnset);
1037
Tianjie Xu90aaa102017-10-10 17:39:03 -07001038 if (error_code == ErrorCode::kSuccess) {
1039 int64_t reboot_count =
1040 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1041 string build_version;
1042 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -07001043
1044 // For android metrics, we only care about the total bytes downloaded
1045 // for all sources; for now we assume the only download source is
1046 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001047 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001048 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
1049 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
1050 total_bytes_downloaded;
1051
1052 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -07001053 if (total_bytes_downloaded >= payload_size) {
1054 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -07001055 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -07001056 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
1057 } else {
1058 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
1059 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -07001060 }
Tianjie Xu21030c12019-08-14 13:00:23 -07001061
Tianjie Xu90aaa102017-10-10 17:39:03 -07001062 metrics_reporter_->ReportSuccessfulUpdateMetrics(
1063 static_cast<int>(attempt_number),
1064 0, // update abandoned count
1065 payload_type,
1066 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -07001067 num_bytes_downloaded,
1068 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001069 duration,
Sen Jiang8712e962018-05-08 12:12:28 -07001070 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001071 static_cast<int>(reboot_count),
1072 0); // url_switch_count
1073 }
1074}
1075
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001076bool UpdateAttempterAndroid::OTARebootSucceeded() const {
1077 const auto current_slot = boot_control_->GetCurrentSlot();
Kelvin Zhang13020502023-08-02 15:18:40 -07001078 const string current_version = GetCurrentBuildVersion();
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001079 int64_t previous_slot = -1;
1080 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
1081 string previous_version;
1082 TEST_AND_RETURN_FALSE(
1083 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
1084 if (previous_slot != current_slot) {
1085 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001086 << previous_version << " to " << current_version
1087 << ", previous slot: " << previous_slot
1088 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001089 if (previous_version == current_version) {
1090 LOG(INFO) << "Previous version is the same as current version, this is "
1091 "possibly a self-OTA.";
1092 }
1093 return true;
1094 } else {
1095 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
1096 "switch never happened, or system not rebooted at all.";
1097 if (previous_version != current_version) {
1098 LOG(INFO) << "Slot didn't change, but version changed from "
1099 << previous_version << " to " << current_version
1100 << " device could be flashed.";
1101 }
1102 return false;
1103 }
1104}
1105
1106OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
1107 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
1108 // existence of this pref is sufficient indicator. Given that we have to
1109 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001110 // |DeltaPerformer::ResetUpdateProgress| and
1111 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001112 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1113 auto system_rebooted = DidSystemReboot(prefs_);
1114 auto ota_successful = OTARebootSucceeded();
1115 if (ota_successful) {
1116 return OTAResult::OTA_SUCCESSFUL;
1117 }
1118 if (slot_switch_attempted) {
1119 if (system_rebooted) {
1120 // If we attempted slot switch, but still end up on the same slot, we
1121 // probably rolled back.
1122 return OTAResult::ROLLED_BACK;
1123 } else {
1124 return OTAResult::UPDATED_NEED_REBOOT;
1125 }
1126 }
1127 return OTAResult::NOT_ATTEMPTED;
1128}
1129
1130void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Kelvin Zhang13020502023-08-02 15:18:40 -07001131 const string current_version = GetCurrentBuildVersion();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001132 TEST_AND_RETURN(!current_version.empty());
1133
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001134 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1135 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001136 string current_boot_id;
1137 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1138 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001139 std::string slot_switch_indicator;
1140 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1141 if (slot_switch_indicator != current_boot_id) {
1142 ClearUpdateCompletedMarker();
1143 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001144
Tianjie Xu90aaa102017-10-10 17:39:03 -07001145 // If there's no record of previous version (e.g. due to a data wipe), we
1146 // save the info of current boot and skip the metrics report.
1147 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001148 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001149 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001150 ClearMetricsPrefs();
1151 return;
1152 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001153 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001154 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001155 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1156 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001157 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001158 int64_t reboot_count =
1159 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1160 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1161 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001162
1163 if (result == OTAResult::ROLLED_BACK) {
1164 // This will release all space previously allocated for apex
1165 // decompression. If we detect a rollback, we should release space and
1166 // return the space to user. Any subsequent attempt to install OTA will
1167 // allocate space again anyway.
1168 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1169 "deompression.";
1170 apex_handler_android_->AllocateSpace({});
1171 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1172 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001173 return;
1174 }
1175
1176 // Now that the build version changes, report the update metrics.
1177 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001178 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001179 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001180
1181 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1182 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1183 if (previous_attempt_exists) {
1184 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1185 }
1186
1187 metrics_utils::LoadAndReportTimeToReboot(
1188 metrics_reporter_.get(), prefs_, clock_.get());
1189 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001190
1191 // Also reset the update progress if the build version has changed.
1192 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1193 LOG(WARNING) << "Unable to reset the update progress.";
1194 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001195}
1196
1197// Save the update start time. Reset the reboot count and attempt number if the
1198// update isn't a resume; otherwise increment the attempt number.
1199void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1200 if (!is_resume) {
1201 metrics_utils::SetNumReboots(0, prefs_);
1202 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1203 } else {
1204 int64_t attempt_number =
1205 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1206 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1207 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001208 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1209 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001210 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001211}
1212
1213void UpdateAttempterAndroid::ClearMetricsPrefs() {
1214 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001215 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001216 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001217 prefs_->Delete(kPrefsSystemUpdatedMarker);
1218 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001219 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001220}
1221
Yifan Hongbd47d622019-12-13 14:59:58 -08001222BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1223 return boot_control_->GetCurrentSlot();
1224}
1225
1226BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1227 return GetCurrentSlot() == 0 ? 1 : 0;
1228}
1229
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001230uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1231 const std::string& metadata_filename,
1232 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001233 Error* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001234 std::map<string, string> headers;
1235 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1236 return 0;
1237 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001238 DeltaArchiveManifest manifest;
1239 brillo::Blob metadata_hash;
1240 if (!brillo::data_encoding::Base64Decode(
1241 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1242 metadata_hash.clear();
1243 }
1244 if (!VerifyPayloadParseManifest(
1245 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1246 return 0;
1247 }
Yifan Hong65613032020-01-09 17:52:13 -08001248
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001249 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1250 manifest.apex_info().end());
1251 uint64_t apex_size_required = 0;
1252 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001253 auto result = apex_handler_android_->CalculateSize(apex_infos);
1254 if (!result.ok()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001255 LogAndSetGenericError(
1256 error,
1257 __LINE__,
1258 __FILE__,
1259 "Failed to calculate size required for compressed APEX");
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001260 return 0;
1261 }
1262 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001263 }
1264
Yifan Hong65613032020-01-09 17:52:13 -08001265 string payload_id = GetPayloadId(headers);
1266 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -07001267 ErrorCode error_code{};
1268
Yifan Hong65613032020-01-09 17:52:13 -08001269 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1270 boot_control_,
1271 GetTargetSlot(),
1272 manifest,
1273 payload_id,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001274 &required_size,
1275 &error_code)) {
1276 if (error_code == ErrorCode::kOverlayfsenabledError) {
1277 LogAndSetError(error,
1278 __LINE__,
1279 __FILE__,
1280 "OverlayFS Shouldn't be enabled for OTA.",
1281 error_code);
1282 return 0;
1283 }
Yifan Hong65613032020-01-09 17:52:13 -08001284 if (required_size == 0) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001285 LogAndSetGenericError(
1286 error, __LINE__, __FILE__, "Failed to allocate space for payload.");
Yifan Hong65613032020-01-09 17:52:13 -08001287 return 0;
1288 } else {
1289 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001290 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001291 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001292 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001293 }
1294 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001295
1296 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001297 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001298 LOG(ERROR) << "Insufficient space for apex decompression: "
1299 << apex_size_required << " bytes";
1300 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001301 }
Yifan Hong65613032020-01-09 17:52:13 -08001302
1303 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001304 return 0;
1305}
1306
Yifan Hong40bb0d02020-02-24 17:33:14 -08001307void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1308 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001309 Error* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001310 if (cleanup_previous_update_code_.has_value()) {
1311 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1312 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1313 if (callback) {
1314 callback->OnCleanupComplete(
1315 static_cast<int32_t>(*cleanup_previous_update_code_));
1316 }
1317 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001318 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001319 if (callback) {
1320 auto callback_ptr = callback.get();
1321 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
Kelvin Zhang2f6c25a2023-07-05 12:49:34 -07001322 callback_ptr->RegisterForDeathNotifications([this, callback_ptr]() {
1323 RemoveCleanupPreviousUpdateCallback(callback_ptr);
1324 });
Yifan Hong40bb0d02020-02-24 17:33:14 -08001325 }
1326 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001327}
1328
Tianjie7f8f2ab2021-07-23 17:08:50 -07001329bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
Daniel Zheng92f7d172023-06-22 14:31:37 -07001330 const std::string& metadata_filename, Error* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001331 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001332 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001333 return LogAndSetGenericError(
1334 error,
1335 __LINE__,
1336 __FILE__,
1337 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001338 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001339 DeltaArchiveManifest manifest;
1340 TEST_AND_RETURN_FALSE(
1341 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1342
Kelvin Zhang20982a52021-08-13 12:31:16 -07001343 InstallPlan install_plan_;
1344 install_plan_.source_slot = GetCurrentSlot();
1345 install_plan_.target_slot = GetTargetSlot();
1346 // Don't do verity computation, just hash the partitions
1347 install_plan_.write_verity = false;
1348 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1349 install_plan_.run_post_install = false;
1350 install_plan_.is_resume = true;
Kelvin Zhange227d992024-11-06 09:14:42 -08001351 // previous ApplyPayload() call may have requested powerwash, these
1352 // settings would be saved in `this->install_plan_`. Inherit that setting.
1353 install_plan_.powerwash_required = this->install_plan_.powerwash_required;
Kelvin Zhang20982a52021-08-13 12:31:16 -07001354
1355 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1356 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1357
Kelvin Zhang20982a52021-08-13 12:31:16 -07001358 auto postinstall_runner_action =
1359 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001360 postinstall_runner_action->set_delegate(this);
1361
Kelvin Zhang8ab0f412024-12-03 12:27:28 -08001362 // If |kPrefsPostInstallSucceeded| is set, we know that we reached this
1363 // state by calling applyPayload() That applyPayload() call would have
1364 // already performed filesystem verification, therefore, we
Kelvin Zhangf8441982022-12-07 18:18:47 -08001365 // can safely skip the verification to save time.
Kelvin Zhang8ab0f412024-12-03 12:27:28 -08001366 bool postinstall_succeeded = false;
1367 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded, &postinstall_succeeded) &&
1368 postinstall_succeeded) {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001369 auto install_plan_action =
1370 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001371 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1372 processor_->EnqueueAction(std::move(install_plan_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001373 SetStatusAndNotify(UpdateStatus::FINALIZING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001374 } else {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001375 ErrorCode error_code{};
Kelvin Zhang263a5402022-12-08 23:03:32 -08001376 if (!boot_control_->GetDynamicPartitionControl()
1377 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1378 GetTargetSlot(),
1379 manifest,
1380 false /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001381 nullptr,
1382 &error_code)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001383 return LogAndSetGenericError(
1384 error, __LINE__, __FILE__, "Failed to PreparePartitionsForUpdate");
Kelvin Zhang263a5402022-12-08 23:03:32 -08001385 }
Kelvin Zhang263a5402022-12-08 23:03:32 -08001386 if (!install_plan_.ParsePartitions(manifest.partitions(),
1387 boot_control_,
1388 manifest.block_size(),
1389 &error_code)) {
1390 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001391 __LINE__,
1392 __FILE__,
Kelvin Zhang263a5402022-12-08 23:03:32 -08001393 "Failed to LoadPartitionsFromSlots " +
Daniel Zheng92f7d172023-06-22 14:31:37 -07001394 utils::ErrorCodeToString(error_code),
1395 error_code);
Kelvin Zhang263a5402022-12-08 23:03:32 -08001396 }
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001397 auto install_plan_action =
1398 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001399 auto filesystem_verifier_action =
1400 std::make_unique<FilesystemVerifierAction>(
1401 boot_control_->GetDynamicPartitionControl());
1402 filesystem_verifier_action->set_delegate(this);
1403 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1404 BondActions(filesystem_verifier_action.get(),
1405 postinstall_runner_action.get());
1406 processor_->EnqueueAction(std::move(install_plan_action));
1407 processor_->EnqueueAction(std::move(filesystem_verifier_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001408 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001409 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001410
Kelvin Zhang20982a52021-08-13 12:31:16 -07001411 processor_->EnqueueAction(std::move(postinstall_runner_action));
1412 ScheduleProcessingStart();
1413 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001414}
1415
Daniel Zheng92f7d172023-06-22 14:31:37 -07001416bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(Error* error) {
Tianjie7f8f2ab2021-07-23 17:08:50 -07001417 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001418 return LogAndSetGenericError(
1419 error,
1420 __LINE__,
1421 __FILE__,
1422 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001423 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001424 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001425 // Update the boot flags so the current slot has higher priority.
1426 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001427 return LogAndSetGenericError(
1428 error, __LINE__, __FILE__, "Failed to SetActiveBootSlot");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001429 }
1430
1431 // Mark the current slot as successful again, since marking it as active
1432 // may reset the successful bit. We ignore the result of whether marking
1433 // the current slot as successful worked.
1434 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001435 return LogAndSetGenericError(
1436 error, __LINE__, __FILE__, "Failed to MarkBootSuccessfulAsync");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001437 }
1438
1439 // Resets the warm reset property since we won't switch the slot.
1440 hardware_->SetWarmReset(false);
1441
1442 // Resets the vbmeta digest.
1443 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1444 LOG(INFO) << "Slot switch cancelled.";
1445 SetStatusAndNotify(UpdateStatus::IDLE);
1446 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001447}
1448
Yifan Hong90965502020-02-19 15:22:47 -08001449void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1450 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1451 // is in progress, skip enqueueing the action.
1452 if (processor_->IsRunning()) {
1453 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1454 << "be done when the current update finishes.";
1455 return;
1456 }
1457 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1458 auto action =
1459 boot_control_->GetDynamicPartitionControl()
1460 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1461 processor_->EnqueueAction(std::move(action));
1462 processor_->set_delegate(this);
1463 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1464 processor_->StartProcessing();
1465}
1466
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001467bool ParsePayloadMetadata(Error* error,
1468 std::string_view manifest_bytes,
1469 DeltaArchiveManifest* manifest) {
1470 PayloadMetadata payload_metadata;
1471 ErrorCode errorcode{};
1472 if (payload_metadata.ParsePayloadHeader(manifest_bytes, &errorcode) !=
1473 MetadataParseResult::kSuccess) {
1474 return LogAndSetError(error,
1475 __LINE__,
1476 __FILE__,
1477 "Failed to parse payload header: " +
1478 utils::ErrorCodeToString(errorcode),
1479 errorcode);
1480 }
1481 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
1482 payload_metadata.GetMetadataSignatureSize();
1483 if (metadata_size < kMaxPayloadHeaderSize ||
1484 metadata_size > manifest_bytes.size()) {
1485 return LogAndSetError(error,
1486 __LINE__,
1487 __FILE__,
1488 "Invalid metadata size on cached manifest: " +
1489 std::to_string(metadata_size),
1490 ErrorCode::kDownloadManifestParseError);
1491 }
1492 TEST_AND_RETURN_FALSE(
1493 VerifyPayloadMetadata(error, manifest_bytes, payload_metadata));
1494
1495 if (!payload_metadata.GetManifest(manifest_bytes, manifest)) {
1496 return LogAndSetError(error,
1497 __LINE__,
1498 __FILE__,
1499 "Failed to parse manifest. Might need to install "
1500 "OTA first and re-try this API",
1501 ErrorCode::kDownloadManifestParseError);
1502 }
1503 return true;
1504}
1505
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001506bool UpdateAttempterAndroid::TriggerPostinstall(const std::string& partition,
1507 Error* error) {
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001508 if (processor_->IsRunning()) {
1509 return LogAndSetError(error,
1510 __LINE__,
1511 __FILE__,
1512 "Already processing an update, cancel it first.",
1513 ErrorCode::kUpdateProcessing);
1514 }
1515 bool postinstall_succeeded = false;
1516 if (!prefs_->GetBoolean(kPrefsPostInstallSucceeded, &postinstall_succeeded)) {
1517 return LogAndSetError(
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001518 error,
1519 __LINE__,
1520 __FILE__,
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001521 "Postinstall action did not run. "
1522 "OTA update must first reach the "
1523 "Postinstall phase(which verfies that all partitions can be mounted) "
1524 "before calling TriggerPostinstall",
1525 ErrorCode::kPostinstallRunnerError);
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001526 }
Kelvin Zhang44bcf1f2024-12-03 10:54:14 -08001527 if (!postinstall_succeeded) {
1528 return LogAndSetError(
1529 error,
1530 __LINE__,
1531 __FILE__,
1532 "Postinstall action did not complete successfully. "
1533 "OTA update must first reach the "
1534 "Postinstall phase(which verfies that all partitions can be mounted) "
1535 "before calling TriggerPostinstall",
1536 ErrorCode::kPostinstallRunnerError);
1537 }
1538
1539 InstallPlan install_plan;
1540 install_plan.source_slot = GetCurrentSlot();
1541 install_plan.target_slot = GetTargetSlot();
1542 install_plan.switch_slot_on_reboot = false;
1543 install_plan.run_post_install = true;
1544 install_plan.download_url =
1545 std::string(kPrefsManifestBytes) + ":" + install_plan_.download_url;
1546
1547 std::string manifest_bytes;
1548 // kPrefsManifestBytes is set during DownloadAction
1549 if (!prefs_->GetString(kPrefsManifestBytes, &manifest_bytes)) {
1550 return LogAndSetError(
1551 error,
1552 __LINE__,
1553 __FILE__,
1554 "Cached manifest not found. TriggerPostinstall can only be called "
1555 "after OTA get past at least FilesystemVerification stage",
1556 ErrorCode::kDownloadStateInitializationError);
1557 }
1558 DeltaArchiveManifest manifest;
1559 TEST_AND_RETURN_FALSE(ParsePayloadMetadata(error, manifest_bytes, &manifest));
1560 ErrorCode errorcode{};
1561 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1562 GetCurrentSlot(),
1563 GetTargetSlot(),
1564 manifest,
1565 false /* should update */,
1566 nullptr,
1567 &errorcode)) {
1568 return LogAndSetError(error,
1569 __LINE__,
1570 __FILE__,
1571 "Failed to PreparePartitionsForUpdate",
1572 errorcode);
1573 }
1574 std::vector<PartitionUpdate> partitions;
1575 std::copy_if(manifest.partitions().begin(),
1576 manifest.partitions().end(),
1577 std::back_inserter(partitions),
1578 [&partition](const PartitionUpdate& part) {
1579 return part.partition_name() == partition;
1580 });
1581 if (partitions.empty()) {
1582 return LogAndSetError(error,
1583 __LINE__,
1584 __FILE__,
1585 "Partition " + partition + " not found",
1586 ErrorCode::kDownloadStateInitializationError);
1587 }
1588 // We only want to trigger postinstall for a specific partition,
1589 // and since we already checked partitions array is non-empty, reading just
1590 // the first partition is enough.
1591 if (!partitions[0].has_postinstall_path() ||
1592 partitions[0].postinstall_path().empty()) {
1593 return LogAndSetError(error,
1594 __LINE__,
1595 __FILE__,
1596 "Partition " + partition +
1597 " does not have a postinstall script defined",
1598 ErrorCode::kDownloadStateInitializationError);
1599 }
1600 if (!install_plan.ParsePartitions(
1601 partitions, boot_control_, manifest.block_size(), &errorcode)) {
1602 return LogAndSetError(error,
1603 __LINE__,
1604 __FILE__,
1605 "Failed to parse manifest partitions. Might need "
1606 "to install OTA first and re-try this API",
1607 ErrorCode::kDownloadManifestParseError);
1608 }
1609 LOG(INFO) << "Trigger postinstall with this install plan: "
1610 << install_plan.ToString();
1611
1612 auto postinstall_runner_action =
1613 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1614 postinstall_runner_action->set_delegate(this);
1615
1616 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan);
1617 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1618 processor_->EnqueueAction(std::move(install_plan_action));
1619 processor_->EnqueueAction(std::move(postinstall_runner_action));
1620 SetStatusAndNotify(UpdateStatus::FINALIZING);
1621 ScheduleProcessingStart();
1622 return true;
Kelvin Zhang9c5baeb2024-11-05 13:42:32 -08001623}
1624
Yifan Hong40bb0d02020-02-24 17:33:14 -08001625void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1626 for (auto&& callback : cleanup_previous_update_callbacks_) {
1627 callback->OnCleanupProgressUpdate(progress);
1628 }
1629}
1630
1631void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1632 CHECK(cleanup_previous_update_code_.has_value());
1633 for (auto&& callback : cleanup_previous_update_callbacks_) {
1634 callback->OnCleanupComplete(
1635 static_cast<int32_t>(*cleanup_previous_update_code_));
1636 }
1637 cleanup_previous_update_callbacks_.clear();
1638}
1639
1640void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1641 CleanupSuccessfulUpdateCallbackInterface* callback) {
1642 auto end_it =
1643 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1644 cleanup_previous_update_callbacks_.end(),
1645 [&](const auto& e) { return e.get() == callback; });
1646 cleanup_previous_update_callbacks_.erase(
1647 end_it, cleanup_previous_update_callbacks_.end());
1648}
Yifan Hong90965502020-02-19 15:22:47 -08001649
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001650bool UpdateAttempterAndroid::IsProductionBuild() {
1651 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1652 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1653 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1654 return true;
1655 }
1656 return false;
1657}
1658
Alex Deymo5e3ea272016-01-28 13:42:23 -08001659} // namespace chromeos_update_engine