blob: 0f6fc5cec1679cb5b652253db4553efe9f6fa7da [file] [log] [blame]
Alex Deymo5e3ea272016-01-28 13:42:23 -08001//
2// Copyright (C) 2016 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/update_attempter_android.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080018
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070021#include <memory>
Kelvin Zhanga43d6e82021-05-26 10:14:42 -040022#include <ostream>
Alex Deymo5e3ea272016-01-28 13:42:23 -080023#include <utility>
Daniel Zhengda4f7292022-09-02 22:59:32 +000024#include <vector>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025
Kelvin Zhang944cdac2023-12-12 12:55:27 -080026#include <android-base/parsebool.h>
Tianjie Xu90aaa102017-10-10 17:39:03 -070027#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090028#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080029#include <base/bind.h>
30#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080031#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070032#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080033#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080034#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070035#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080036
Amin Hassaniec7bc112020-10-29 16:47:58 -070037#include "update_engine/aosp/cleanup_previous_update_action.h"
Daniel Zhengda4f7292022-09-02 22:59:32 +000038#include "update_engine/common/clock.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080039#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070040#include "update_engine/common/daemon_state_interface.h"
41#include "update_engine/common/download_action.h"
Kelvin Zhangf8441982022-12-07 18:18:47 -080042#include "update_engine/common/error_code.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080043#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070044#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070045#include "update_engine/common/metrics_reporter_interface.h"
46#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080047#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070048#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080050#include "update_engine/payload_consumer/file_descriptor.h"
51#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000053#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080054#include "update_engine/payload_consumer/payload_constants.h"
55#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070056#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080057#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070058#include "update_engine/update_boot_flags_action.h"
Kelvin Zhangf92fe252023-03-28 10:55:47 -070059#include "update_engine/update_status.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080060#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080061
Alex Deymo14c0da82016-07-20 16:45:45 -070062#ifndef _UE_SIDELOAD
63// Do not include support for external HTTP(s) urls when building
64// update_engine_sideload.
65#include "update_engine/libcurl_http_fetcher.h"
66#endif
67
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090068using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080069using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070070using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080071using base::TimeDelta;
72using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080073using std::string;
74using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070075using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080076
77namespace chromeos_update_engine {
78
79namespace {
80
Alex Deymo0d298542016-03-30 18:31:49 -070081// Minimum threshold to broadcast an status update in progress and time.
82const double kBroadcastThresholdProgress = 0.01; // 1%
83const int kBroadcastThresholdSeconds = 10;
84
Daniel Zheng92f7d172023-06-22 14:31:37 -070085// Log and set the error on the passed ErrorPtr.
86bool LogAndSetGenericError(Error* error,
87 int line_number,
88 const char* file_name,
89 const string& reason) {
90 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
91 << ": " << reason;
92 error->line_number = line_number;
93 error->file_name = file_name;
94 error->message = reason;
95 error->error_code = ErrorCode::kError;
96 return false;
97}
Alex Deymo5e3ea272016-01-28 13:42:23 -080098
99// Log and set the error on the passed ErrorPtr.
Daniel Zheng92f7d172023-06-22 14:31:37 -0700100bool LogAndSetError(Error* error,
101 int line_number,
102 const char* file_name,
103 const string& reason,
104 ErrorCode error_code) {
105 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
106 << ": " << reason;
107 error->line_number = line_number;
108 error->file_name = file_name;
109 error->message = reason;
110 error->error_code = error_code;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800111 return false;
112}
113
Sen Jiangfe522822017-10-31 15:14:11 -0700114bool GetHeaderAsBool(const string& header, bool default_value) {
115 int value = 0;
116 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
117 return value == 1;
118 return default_value;
119}
120
Yifan Hongbd47d622019-12-13 14:59:58 -0800121bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
122 std::map<string, string>* headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700123 Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800124 for (const string& key_value_pair : key_value_pair_headers) {
125 string key;
126 string value;
127 if (!brillo::string_utils::SplitAtFirst(
128 key_value_pair, "=", &key, &value, false)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700129 return LogAndSetGenericError(error,
130 __LINE__,
131 __FILE__,
132 "Passed invalid header: " + key_value_pair);
Yifan Hongbd47d622019-12-13 14:59:58 -0800133 }
134 if (!headers->emplace(key, value).second)
Daniel Zheng92f7d172023-06-22 14:31:37 -0700135 return LogAndSetGenericError(
136 error, __LINE__, __FILE__, "Passed repeated key: " + key);
Yifan Hongbd47d622019-12-13 14:59:58 -0800137 }
138 return true;
139}
140
141// Unique identifier for the payload. An empty string means that the payload
142// can't be resumed.
143string GetPayloadId(const std::map<string, string>& headers) {
144 return (headers.count(kPayloadPropertyFileHash)
145 ? headers.at(kPayloadPropertyFileHash)
146 : "") +
147 (headers.count(kPayloadPropertyMetadataHash)
148 ? headers.at(kPayloadPropertyMetadataHash)
149 : "");
150}
151
Kelvin Zhang13020502023-08-02 15:18:40 -0700152std::string GetCurrentBuildVersion() {
153 // Example: [ro.build.fingerprint]:
154 // [generic/aosp_cf_x86_64_phone/vsoc_x86_64:VanillaIceCream/AOSP.MAIN/user08011303:userdebug/test-keys]
155 return android::base::GetProperty("ro.build.fingerprint", "");
156}
157
Alex Deymo5e3ea272016-01-28 13:42:23 -0800158} // namespace
159
160UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700161 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800162 PrefsInterface* prefs,
163 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000164 HardwareInterface* hardware,
165 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800166 : daemon_state_(daemon_state),
167 prefs_(prefs),
168 boot_control_(boot_control),
169 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000170 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700171 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800172 clock_(new Clock()),
173 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
174 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800175 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400176 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700177 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800178}
179
180UpdateAttempterAndroid::~UpdateAttempterAndroid() {
181 // Release ourselves as the ActionProcessor's delegate to prevent
182 // re-scheduling the updates due to the processing stopped.
183 processor_->set_delegate(nullptr);
184}
185
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400186[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
187 string boot_id;
188 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
189 string old_boot_id;
190 // If no previous boot id found, treat as a reboot and write boot ID.
191 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
192 return true;
193 }
194 return old_boot_id != boot_id;
195}
196
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400197std::ostream& operator<<(std::ostream& out, OTAResult result) {
198 switch (result) {
199 case OTAResult::NOT_ATTEMPTED:
200 out << "OTAResult::NOT_ATTEMPTED";
201 break;
202 case OTAResult::ROLLED_BACK:
203 out << "OTAResult::ROLLED_BACK";
204 break;
205 case OTAResult::UPDATED_NEED_REBOOT:
206 out << "OTAResult::UPDATED_NEED_REBOOT";
207 break;
208 case OTAResult::OTA_SUCCESSFUL:
209 out << "OTAResult::OTA_SUCCESSFUL";
210 break;
211 }
212 return out;
213}
214
Alex Deymo5e3ea272016-01-28 13:42:23 -0800215void UpdateAttempterAndroid::Init() {
216 // In case of update_engine restart without a reboot we need to restore the
217 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700218 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400219 LOG(INFO) << "Updated installed but update_engine is restarted without "
220 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800221 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700222 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400223 const auto result = GetOTAUpdateResult();
224 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800225 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400226 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400227 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400228 }
229
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700230#ifdef _UE_SIDELOAD
231 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
232 << "ApplyPayload will call it later.";
233#else
Yifan Hong90965502020-02-19 15:22:47 -0800234 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700235#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700236 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800237}
238
239bool UpdateAttempterAndroid::ApplyPayload(
240 const string& payload_url,
241 int64_t payload_offset,
242 int64_t payload_size,
243 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700244 Error* error) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800245 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800246 return LogAndSetError(error,
247 __LINE__,
248 __FILE__,
249 "An update already applied, waiting for reboot",
250 ErrorCode::kUpdateAlreadyInstalled);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800251 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700252 if (processor_->IsRunning()) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800253 return LogAndSetError(error,
254 __LINE__,
255 __FILE__,
256 "Already processing an update, cancel it first.",
257 ErrorCode::kUpdateProcessing);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800258 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100259 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800260
Alex Deymo218397f2016-02-04 23:55:10 -0800261 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800262 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
263 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800264 }
265
Yifan Hongbd47d622019-12-13 14:59:58 -0800266 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800267
268 // Setup the InstallPlan based on the request.
269 install_plan_ = InstallPlan();
270
271 install_plan_.download_url = payload_url;
272 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800273 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800274 InstallPlan::Payload payload;
275 payload.size = payload_size;
276 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800277 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800278 &payload.size)) {
279 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800280 }
281 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700282 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800283 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700284 LOG(WARNING) << "Unable to decode base64 file hash: "
285 << headers[kPayloadPropertyFileHash];
286 }
Alex Deymo218397f2016-02-04 23:55:10 -0800287 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800288 &payload.metadata_size)) {
289 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800290 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700291 // The |payload.type| is not used anymore since minor_version 3.
292 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800293 install_plan_.payloads.push_back(payload);
294
Alex Deymo5e3ea272016-01-28 13:42:23 -0800295 // The |public_key_rsa| key would override the public key stored on disk.
296 install_plan_.public_key_rsa = "";
297
298 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
299 install_plan_.is_resume = !payload_id.empty() &&
300 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
301 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700302 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700303 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
304
Alex Deymo5e3ea272016-01-28 13:42:23 -0800305 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
306 LOG(WARNING) << "Unable to save the update check response hash.";
307 }
308 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800309 install_plan_.source_slot = GetCurrentSlot();
310 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700311
Alex Deymofb905d92016-06-03 19:26:58 -0700312 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700313 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
314
Kelvin Zhang85a6d992023-10-23 10:40:58 -0700315 install_plan_.spl_downgrade =
316 GetHeaderAsBool(headers[kPayloadPropertySplDowngrade], false);
317
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000318 if (!IsProductionBuild()) {
319 install_plan_.disable_vabc =
320 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
321 }
322
Sen Jiangfe522822017-10-31 15:14:11 -0700323 install_plan_.switch_slot_on_reboot =
324 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
325
Tianjie Xu087de9d2019-11-01 17:11:22 -0700326 install_plan_.run_post_install =
327 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800328
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700329 // Skip writing verity if we're resuming and verity has already been written.
330 install_plan_.write_verity = true;
331 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
332 bool verity_written = false;
333 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
334 verity_written) {
335 install_plan_.write_verity = false;
336 }
337 }
338
Alex Deymo87792ea2016-07-25 15:40:36 -0700339 NetworkId network_id = kDefaultNetworkId;
340 if (!headers[kPayloadPropertyNetworkId].empty()) {
341 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
342 &network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700343 return LogAndSetGenericError(
Alex Deymo87792ea2016-07-25 15:40:36 -0700344 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700345 __LINE__,
346 __FILE__,
Alex Deymo87792ea2016-07-25 15:40:36 -0700347 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
348 }
349 if (!network_selector_->SetProcessNetwork(network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700350 return LogAndSetGenericError(
Sen Jiangcbd37c62017-09-12 15:04:35 -0700351 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700352 __LINE__,
353 __FILE__,
Sen Jiangcbd37c62017-09-12 15:04:35 -0700354 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700355 }
Daniel Zheng7ff60fd2024-01-29 08:38:17 -0800356 LOG(INFO) << "Using network ID: " << network_id;
Alex Deymo87792ea2016-07-25 15:40:36 -0700357 }
358
Alex Deymo5e3ea272016-01-28 13:42:23 -0800359 LOG(INFO) << "Using this install plan:";
360 install_plan_.Dump();
361
Amin Hassani667cf7b2018-07-25 14:32:00 -0700362 HttpFetcher* fetcher = nullptr;
363 if (FileFetcher::SupportedUrl(payload_url)) {
364 DLOG(INFO) << "Using FileFetcher for file URL.";
365 fetcher = new FileFetcher();
366 } else {
367#ifdef _UE_SIDELOAD
368 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800369 return false; // NOLINT, unreached but analyzer might not know.
370 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700371#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700372 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700373 if (!headers[kPayloadDownloadRetry].empty()) {
374 libcurl_fetcher->set_max_retry_count(
375 atoi(headers[kPayloadDownloadRetry].c_str()));
376 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700377 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
378 fetcher = libcurl_fetcher;
379#endif // _UE_SIDELOAD
380 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800381 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800382 if (!headers[kPayloadPropertyAuthorization].empty())
383 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
384 if (!headers[kPayloadPropertyUserAgent].empty())
385 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
386
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700387 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
388 LOG(INFO) << "Using proxy url from payload headers: "
389 << headers[kPayloadPropertyNetworkProxy];
390 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
391 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700392 if (!headers[kPayloadVABCNone].empty()) {
393 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000394 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800395 if (!headers[kPayloadEnableThreading].empty()) {
Kelvin Zhang944cdac2023-12-12 12:55:27 -0800396 const auto res = android::base::ParseBool(headers[kPayloadEnableThreading]);
397 if (res != android::base::ParseBoolResult::kError) {
398 install_plan_.enable_threading =
399 res == android::base::ParseBoolResult::kTrue;
400 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800401 }
402 if (!headers[kPayloadBatchedWrites].empty()) {
403 install_plan_.batched_writes = true;
404 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700405
Amin Hassani667cf7b2018-07-25 14:32:00 -0700406 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800407
Alex Deymo5e3ea272016-01-28 13:42:23 -0800408 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700409
410 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
411 // TODO(xunchang) report the metrics for unresumable updates
412
Amin Hassani667cf7b2018-07-25 14:32:00 -0700413 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800414 return true;
415}
416
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900417bool UpdateAttempterAndroid::ApplyPayload(
418 int fd,
419 int64_t payload_offset,
420 int64_t payload_size,
421 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700422 Error* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100423 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000424 // already running update will be terminated (existing file descriptor will be
425 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100426 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700427 return LogAndSetGenericError(
428 error,
429 __LINE__,
430 __FILE__,
431 "An update already applied, waiting for reboot");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100432 }
433 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700434 return LogAndSetGenericError(
435 error,
436 __LINE__,
437 __FILE__,
438 "Already processing an update, cancel it first.");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100439 }
440 DCHECK_EQ(status_, UpdateStatus::IDLE);
441
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900442 payload_fd_.reset(dup(fd));
443 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
444
445 return ApplyPayload(
446 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
447}
448
Daniel Zheng92f7d172023-06-22 14:31:37 -0700449bool UpdateAttempterAndroid::SuspendUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700450 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700451 return LogAndSetGenericError(
452 error, __LINE__, __FILE__, "No ongoing update to suspend.");
Alex Deymof2858572016-02-25 11:20:13 -0800453 processor_->SuspendProcessing();
454 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800455}
456
Daniel Zheng92f7d172023-06-22 14:31:37 -0700457bool UpdateAttempterAndroid::ResumeUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700458 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700459 return LogAndSetGenericError(
460 error, __LINE__, __FILE__, "No ongoing update to resume.");
Alex Deymof2858572016-02-25 11:20:13 -0800461 processor_->ResumeProcessing();
462 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800463}
464
Daniel Zheng92f7d172023-06-22 14:31:37 -0700465bool UpdateAttempterAndroid::CancelUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700466 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700467 return LogAndSetGenericError(
468 error, __LINE__, __FILE__, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800469 processor_->StopProcessing();
470 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800471}
472
Daniel Zheng92f7d172023-06-22 14:31:37 -0700473bool UpdateAttempterAndroid::ResetStatus(Error* error) {
Alex Deymo3b678db2016-02-09 11:50:06 -0800474 LOG(INFO) << "Attempting to reset state from "
475 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700476 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700477 return LogAndSetGenericError(
478 error,
479 __LINE__,
480 __FILE__,
481 "Already processing an update, cancel it first.");
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700482 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700483 if (status_ != UpdateStatus::IDLE &&
484 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700485 return LogAndSetGenericError(
486 error,
487 __LINE__,
488 __FILE__,
489 "Status reset not allowed in this state, please "
490 "cancel on going OTA first.");
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700491 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800492
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000493 if (apex_handler_android_ != nullptr) {
494 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
495 std::vector<ApexInfo> apex_infos_blank;
496 apex_handler_android_->AllocateSpace(apex_infos_blank);
497 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400498 // Remove the reboot marker so that if the machine is rebooted
499 // after resetting to idle state, it doesn't go back to
500 // UpdateStatus::UPDATED_NEED_REBOOT state.
501 if (!ClearUpdateCompletedMarker()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700502 return LogAndSetGenericError(error,
503 __LINE__,
504 __FILE__,
505 "Failed to reset the status because "
506 "ClearUpdateCompletedMarker() failed");
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400507 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700508 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
509 if (!resetShouldSwitchSlotOnReboot(error)) {
510 LOG(INFO) << "Failed to reset slot switch.";
511 return false;
512 }
513 LOG(INFO) << "Slot switch reset successful";
514 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700515 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
516 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000517 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700518 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700519 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800520}
521
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700522bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
523 if (a.size() != b.size()) {
524 return false;
525 }
526 return memcmp(a.data(), b.data(), a.size()) == 0;
527}
528bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
529 return !(a == b);
530}
531
Yifan Hongbd47d622019-12-13 14:59:58 -0800532bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
533 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700534 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800535 DeltaArchiveManifest* manifest,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700536 Error* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800537 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
538 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700539 return LogAndSetError(error,
540 __LINE__,
541 __FILE__,
542 "Failed to open " + metadata_filename,
543 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800544 }
545 brillo::Blob metadata(kMaxPayloadHeaderSize);
546 if (!fd->Read(metadata.data(), metadata.size())) {
547 return LogAndSetError(
548 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700549 __LINE__,
550 __FILE__,
551 "Failed to read payload header from " + metadata_filename,
552 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800553 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000554 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800555 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700556 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800557 MetadataParseResult::kSuccess) {
558 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700559 __LINE__,
560 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800561 "Failed to parse payload header: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700562 utils::ErrorCodeToString(errorcode),
563 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800564 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700565 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
566 payload_metadata.GetMetadataSignatureSize();
567 if (metadata_size < kMaxPayloadHeaderSize ||
568 metadata_size >
569 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800570 return LogAndSetError(
571 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700572 __LINE__,
573 __FILE__,
574 "Invalid metadata size: " + std::to_string(metadata_size),
575 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800576 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700577 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800578 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
579 metadata.size() - kMaxPayloadHeaderSize)) {
580 return LogAndSetError(
581 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700582 __LINE__,
583 __FILE__,
584 "Failed to read metadata and signature from " + metadata_filename,
585 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800586 }
587 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700588 if (!expected_metadata_hash.empty()) {
589 brillo::Blob metadata_hash;
590 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
591 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
592 if (metadata_hash != expected_metadata_hash) {
593 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700594 __LINE__,
595 __FILE__,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700596 "Metadata hash mismatch. Expected hash: " +
597 HexEncode(expected_metadata_hash) +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700598 " actual hash: " + HexEncode(metadata_hash),
599 ErrorCode::kDownloadManifestParseError);
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700600 } else {
601 LOG(INFO) << "Payload metadata hash check passed : "
602 << HexEncode(metadata_hash);
603 }
604 }
Sen Jiang08c6da12019-01-07 18:28:56 -0800605
Tianjie Xu7a78d632019-10-08 16:32:39 -0700606 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
607 constants::kUpdateCertificatesPath);
608 if (!payload_verifier) {
609 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700610 __LINE__,
611 __FILE__,
Tianjie Xu7a78d632019-10-08 16:32:39 -0700612 "Failed to create the payload verifier from " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700613 std::string(constants::kUpdateCertificatesPath),
614 ErrorCode::kDownloadManifestParseError);
Sen Jiang08c6da12019-01-07 18:28:56 -0800615 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700616 errorcode = payload_metadata.ValidateMetadataSignature(
617 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800618 if (errorcode != ErrorCode::kSuccess) {
619 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700620 __LINE__,
621 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800622 "Failed to validate metadata signature: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700623 utils::ErrorCodeToString(errorcode),
624 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800625 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800626 if (!payload_metadata.GetManifest(metadata, manifest)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700627 return LogAndSetError(error,
628 __LINE__,
629 __FILE__,
630 "Failed to parse manifest.",
631 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800632 }
633
Yifan Hongbd47d622019-12-13 14:59:58 -0800634 return true;
635}
636
637bool UpdateAttempterAndroid::VerifyPayloadApplicable(
Daniel Zheng92f7d172023-06-22 14:31:37 -0700638 const std::string& metadata_filename, Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800639 DeltaArchiveManifest manifest;
640 TEST_AND_RETURN_FALSE(
641 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
642
643 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000644 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800645
646 BootControlInterface::Slot current_slot = GetCurrentSlot();
Kelvin Zhang1815c4d2023-11-07 14:21:18 -0800647 if (current_slot < 0) {
648 return LogAndSetError(
649 error,
650 __LINE__,
651 __FILE__,
652 "Failed to get current slot " + std::to_string(current_slot),
653 ErrorCode::kDownloadStateInitializationError);
654 }
Sen Jiang8371c1c2018-02-01 13:46:39 -0800655 for (const PartitionUpdate& partition : manifest.partitions()) {
656 if (!partition.has_old_partition_info())
657 continue;
658 string partition_path;
659 if (!boot_control_->GetPartitionDevice(
660 partition.partition_name(), current_slot, &partition_path)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700661 return LogAndSetGenericError(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800662 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700663 __LINE__,
664 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800665 "Failed to get partition device for " + partition.partition_name());
666 }
667 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700668 return LogAndSetGenericError(
669 error, __LINE__, __FILE__, "Failed to open " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800670 }
671 for (const InstallOperation& operation : partition.operations()) {
672 if (!operation.has_src_sha256_hash())
673 continue;
674 brillo::Blob source_hash;
675 if (!fd_utils::ReadAndHashExtents(fd,
676 operation.src_extents(),
677 manifest.block_size(),
678 &source_hash)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700679 return LogAndSetGenericError(
680 error, __LINE__, __FILE__, "Failed to hash " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800681 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400682 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800683 source_hash, operation, fd, &errorcode)) {
684 return false;
685 }
686 }
687 fd->Close();
688 }
689 return true;
690}
691
Alex Deymo5e3ea272016-01-28 13:42:23 -0800692void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
693 ErrorCode code) {
694 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800695 metric_bytes_downloaded_.Flush(true);
696 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800697 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800698 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
699 TerminateUpdateAndNotify(code);
700 return;
701 }
702
Alex Deymo5990bf32016-07-19 17:01:41 -0700703 switch (code) {
704 case ErrorCode::kSuccess:
705 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400706 if (!WriteUpdateCompletedMarker()) {
707 LOG(ERROR) << "Failed to write update completion marker";
708 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700709 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800710
Alex Deymo5990bf32016-07-19 17:01:41 -0700711 LOG(INFO) << "Update successfully applied, waiting to reboot.";
712 break;
713
714 case ErrorCode::kFilesystemCopierError:
715 case ErrorCode::kNewRootfsVerificationError:
716 case ErrorCode::kNewKernelVerificationError:
717 case ErrorCode::kFilesystemVerifierError:
718 case ErrorCode::kDownloadStateInitializationError:
719 // Reset the ongoing update for these errors so it starts from the
720 // beginning next time.
721 DeltaPerformer::ResetUpdateProgress(prefs_, false);
722 LOG(INFO) << "Resetting update progress.";
723 break;
724
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700725 case ErrorCode::kPayloadTimestampError:
726 // SafetyNet logging, b/36232423
727 android_errorWriteLog(0x534e4554, "36232423");
728 break;
729
Alex Deymo5990bf32016-07-19 17:01:41 -0700730 default:
731 // Ignore all other error codes.
732 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700733 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800734
735 TerminateUpdateAndNotify(code);
736}
737
738void UpdateAttempterAndroid::ProcessingStopped(
739 const ActionProcessor* processor) {
740 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
741}
742
743void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
744 AbstractAction* action,
745 ErrorCode code) {
746 // Reset download progress regardless of whether or not the download
747 // action succeeded.
748 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800749 if (type == CleanupPreviousUpdateAction::StaticType() ||
750 (type == NoOpAction::StaticType() &&
751 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
752 cleanup_previous_update_code_ = code;
753 NotifyCleanupPreviousUpdateCallbacksAndClear();
754 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000755 // download_progress_ is actually used by other actions, such as
756 // filesystem_verify_action. Therefore we always clear it.
757 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700758 if (type == PostinstallRunnerAction::StaticType()) {
759 bool succeeded =
760 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
761 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
762 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800763 if (code != ErrorCode::kSuccess) {
764 // If an action failed, the ActionProcessor will cancel the whole thing.
765 return;
766 }
Yifan Hong83517502020-02-19 15:34:13 -0800767 if (type == UpdateBootFlagsAction::StaticType()) {
768 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
769 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800770 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400771 auto download_action = static_cast<DownloadAction*>(action);
772 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000773 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700774 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000775 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700776 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800777 }
778}
779
780void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
781 uint64_t bytes_received,
782 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700783 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800784 if (total)
785 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700786 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800787 download_progress_ = progress;
788 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700789 } else {
790 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800791 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700792
793 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800794 metric_bytes_downloaded_ += bytes_progressed;
795 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800796}
797
798bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
799 // TODO(deymo): Notify the DownloadAction that it should cancel the update
800 // download.
801 return false;
802}
803
804void UpdateAttempterAndroid::DownloadComplete() {
805 // Nothing needs to be done when the download completes.
806}
807
Alex Deymo0d298542016-03-30 18:31:49 -0700808void UpdateAttempterAndroid::ProgressUpdate(double progress) {
809 // Self throttle based on progress. Also send notifications if progress is
810 // too slow.
811 if (progress == 1.0 ||
812 progress - download_progress_ >= kBroadcastThresholdProgress ||
813 TimeTicks::Now() - last_notify_time_ >=
814 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
815 download_progress_ = progress;
816 SetStatusAndNotify(status_);
817 }
818}
819
Kelvin Zhang70eef232020-06-12 20:32:40 +0000820void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
821 assert(status_ == UpdateStatus::VERIFYING);
822 ProgressUpdate(progress);
823}
824
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825void UpdateAttempterAndroid::ScheduleProcessingStart() {
826 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700827 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800828 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700829 FROM_HERE,
830 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
831 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800832}
833
834void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
835 if (status_ == UpdateStatus::IDLE) {
836 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
837 return;
838 }
839
Yifan Hong90965502020-02-19 15:22:47 -0800840 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400841 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800842 LOG(INFO) << "Terminating cleanup previous update.";
843 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700844 for (auto observer : daemon_state_->service_observers())
845 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800846 return;
847 }
848
Yifan Hong9194ce82019-11-07 11:03:42 -0800849 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700850
Alex Deymo0d298542016-03-30 18:31:49 -0700851 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800852 UpdateStatus new_status =
853 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
854 : UpdateStatus::IDLE);
855 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900856 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800857
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700858 // The network id is only applicable to one download attempt and once it's
859 // done the network id should not be re-used anymore.
860 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
861 LOG(WARNING) << "Unable to unbind network.";
862 }
863
Alex Deymo5e3ea272016-01-28 13:42:23 -0800864 for (auto observer : daemon_state_->service_observers())
865 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700866
Tianjie Xu90aaa102017-10-10 17:39:03 -0700867 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
868 ClearMetricsPrefs();
869 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800870 // We should only reset the PayloadAttemptNumber if the update succeeds, or
871 // we switch to a different payload.
872 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700874 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800875 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700876 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800877}
878
879void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
880 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700881 size_t payload_size =
882 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700883 UpdateEngineStatus status_to_send = {.status = status_,
884 .progress = download_progress_,
885 .new_size_bytes = payload_size};
886
Alex Deymo5e3ea272016-01-28 13:42:23 -0800887 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700888 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800889 }
890 last_notify_time_ = TimeTicks::Now();
891}
892
Amin Hassani667cf7b2018-07-25 14:32:00 -0700893void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800894 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800895
896 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700897 auto update_boot_flags_action =
898 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800899 auto cleanup_previous_update_action =
900 boot_control_->GetDynamicPartitionControl()
901 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700902 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
903 auto download_action =
904 std::make_unique<DownloadAction>(prefs_,
905 boot_control_,
906 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700907 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700908 true /* interactive */,
909 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800910 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700911 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700912 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
913 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700914 auto postinstall_runner_action =
915 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000916 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700917 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800918
Alex Deymo5e3ea272016-01-28 13:42:23 -0800919 // Bond them together. We have to use the leaf-types when calling
920 // BondActions().
921 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700922 BondActions(download_action.get(), filesystem_verifier_action.get());
923 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800924 postinstall_runner_action.get());
925
Amin Hassani667cf7b2018-07-25 14:32:00 -0700926 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800927 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700928 processor_->EnqueueAction(std::move(install_plan_action));
929 processor_->EnqueueAction(std::move(download_action));
930 processor_->EnqueueAction(std::move(filesystem_verifier_action));
931 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800932}
933
Alex Deymo5e3ea272016-01-28 13:42:23 -0800934bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
935 string boot_id;
936 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800937 LOG(INFO) << "Writing update complete marker, slot "
938 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400939 TEST_AND_RETURN_FALSE(
940 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
941 TEST_AND_RETURN_FALSE(
942 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
943 return true;
944}
945
946bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
947 LOG(INFO) << "Clearing update complete marker.";
948 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
949 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800950 return true;
951}
952
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800953bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800954 // In case of an update_engine restart without a reboot, we stored the boot_id
955 // when the update was completed by setting a pref, so we can check whether
956 // the last update was on this boot or a previous one.
957 string boot_id;
958 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
959
960 string update_completed_on_boot_id;
961 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
962 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
963 &update_completed_on_boot_id) &&
964 update_completed_on_boot_id == boot_id);
965}
966
Tianjie Xu90aaa102017-10-10 17:39:03 -0700967// Collect and report the android metrics when we terminate the update.
968void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
969 ErrorCode error_code) {
970 int64_t attempt_number =
971 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
972 PayloadType payload_type = kPayloadTypeFull;
973 int64_t payload_size = 0;
974 for (const auto& p : install_plan_.payloads) {
975 if (p.type == InstallPayloadType::kDelta)
976 payload_type = kPayloadTypeDelta;
977 payload_size += p.size;
978 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700979 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
980 // function will be triggered, but payload_size in this case might be 0, if so
981 // skip reporting any metrics.
982 if (payload_size == 0) {
983 return;
984 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700985
986 metrics::AttemptResult attempt_result =
987 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700988 Time boot_time_start = Time::FromInternalValue(
989 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
990 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700991 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700992 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
993 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700994
995 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700996 static_cast<int>(attempt_number),
997 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700998 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700999 duration_uptime,
1000 payload_size,
1001 attempt_result,
1002 error_code);
1003
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001004 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001005 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
1006 current_bytes_downloaded,
1007 0,
1008 DownloadSource::kNumDownloadSources,
1009 metrics::DownloadErrorCode::kUnset,
1010 metrics::ConnectionType::kUnset);
1011
Tianjie Xu90aaa102017-10-10 17:39:03 -07001012 if (error_code == ErrorCode::kSuccess) {
1013 int64_t reboot_count =
1014 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1015 string build_version;
1016 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -07001017
1018 // For android metrics, we only care about the total bytes downloaded
1019 // for all sources; for now we assume the only download source is
1020 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001021 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001022 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
1023 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
1024 total_bytes_downloaded;
1025
1026 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -07001027 if (total_bytes_downloaded >= payload_size) {
1028 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -07001029 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -07001030 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
1031 } else {
1032 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
1033 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -07001034 }
Tianjie Xu21030c12019-08-14 13:00:23 -07001035
Tianjie Xu90aaa102017-10-10 17:39:03 -07001036 metrics_reporter_->ReportSuccessfulUpdateMetrics(
1037 static_cast<int>(attempt_number),
1038 0, // update abandoned count
1039 payload_type,
1040 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -07001041 num_bytes_downloaded,
1042 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001043 duration,
Sen Jiang8712e962018-05-08 12:12:28 -07001044 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001045 static_cast<int>(reboot_count),
1046 0); // url_switch_count
1047 }
1048}
1049
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001050bool UpdateAttempterAndroid::OTARebootSucceeded() const {
1051 const auto current_slot = boot_control_->GetCurrentSlot();
Kelvin Zhang13020502023-08-02 15:18:40 -07001052 const string current_version = GetCurrentBuildVersion();
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001053 int64_t previous_slot = -1;
1054 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
1055 string previous_version;
1056 TEST_AND_RETURN_FALSE(
1057 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
1058 if (previous_slot != current_slot) {
1059 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001060 << previous_version << " to " << current_version
1061 << ", previous slot: " << previous_slot
1062 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001063 if (previous_version == current_version) {
1064 LOG(INFO) << "Previous version is the same as current version, this is "
1065 "possibly a self-OTA.";
1066 }
1067 return true;
1068 } else {
1069 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
1070 "switch never happened, or system not rebooted at all.";
1071 if (previous_version != current_version) {
1072 LOG(INFO) << "Slot didn't change, but version changed from "
1073 << previous_version << " to " << current_version
1074 << " device could be flashed.";
1075 }
1076 return false;
1077 }
1078}
1079
1080OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
1081 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
1082 // existence of this pref is sufficient indicator. Given that we have to
1083 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001084 // |DeltaPerformer::ResetUpdateProgress| and
1085 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001086 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1087 auto system_rebooted = DidSystemReboot(prefs_);
1088 auto ota_successful = OTARebootSucceeded();
1089 if (ota_successful) {
1090 return OTAResult::OTA_SUCCESSFUL;
1091 }
1092 if (slot_switch_attempted) {
1093 if (system_rebooted) {
1094 // If we attempted slot switch, but still end up on the same slot, we
1095 // probably rolled back.
1096 return OTAResult::ROLLED_BACK;
1097 } else {
1098 return OTAResult::UPDATED_NEED_REBOOT;
1099 }
1100 }
1101 return OTAResult::NOT_ATTEMPTED;
1102}
1103
1104void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Kelvin Zhang13020502023-08-02 15:18:40 -07001105 const string current_version = GetCurrentBuildVersion();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001106 TEST_AND_RETURN(!current_version.empty());
1107
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001108 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1109 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001110 string current_boot_id;
1111 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1112 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001113 std::string slot_switch_indicator;
1114 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1115 if (slot_switch_indicator != current_boot_id) {
1116 ClearUpdateCompletedMarker();
1117 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001118
Tianjie Xu90aaa102017-10-10 17:39:03 -07001119 // If there's no record of previous version (e.g. due to a data wipe), we
1120 // save the info of current boot and skip the metrics report.
1121 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001122 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001123 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001124 ClearMetricsPrefs();
1125 return;
1126 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001127 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001128 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001129 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1130 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001131 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001132 int64_t reboot_count =
1133 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1134 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1135 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001136
1137 if (result == OTAResult::ROLLED_BACK) {
1138 // This will release all space previously allocated for apex
1139 // decompression. If we detect a rollback, we should release space and
1140 // return the space to user. Any subsequent attempt to install OTA will
1141 // allocate space again anyway.
1142 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1143 "deompression.";
1144 apex_handler_android_->AllocateSpace({});
1145 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1146 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001147 return;
1148 }
1149
1150 // Now that the build version changes, report the update metrics.
1151 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001152 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001153 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001154
1155 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1156 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1157 if (previous_attempt_exists) {
1158 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1159 }
1160
1161 metrics_utils::LoadAndReportTimeToReboot(
1162 metrics_reporter_.get(), prefs_, clock_.get());
1163 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001164
1165 // Also reset the update progress if the build version has changed.
1166 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1167 LOG(WARNING) << "Unable to reset the update progress.";
1168 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001169}
1170
1171// Save the update start time. Reset the reboot count and attempt number if the
1172// update isn't a resume; otherwise increment the attempt number.
1173void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1174 if (!is_resume) {
1175 metrics_utils::SetNumReboots(0, prefs_);
1176 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1177 } else {
1178 int64_t attempt_number =
1179 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1180 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1181 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001182 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1183 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001184 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001185}
1186
1187void UpdateAttempterAndroid::ClearMetricsPrefs() {
1188 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001189 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001190 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001191 prefs_->Delete(kPrefsSystemUpdatedMarker);
1192 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001193 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001194}
1195
Yifan Hongbd47d622019-12-13 14:59:58 -08001196BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1197 return boot_control_->GetCurrentSlot();
1198}
1199
1200BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1201 return GetCurrentSlot() == 0 ? 1 : 0;
1202}
1203
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001204uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1205 const std::string& metadata_filename,
1206 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001207 Error* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001208 std::map<string, string> headers;
1209 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1210 return 0;
1211 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001212 DeltaArchiveManifest manifest;
1213 brillo::Blob metadata_hash;
1214 if (!brillo::data_encoding::Base64Decode(
1215 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1216 metadata_hash.clear();
1217 }
1218 if (!VerifyPayloadParseManifest(
1219 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1220 return 0;
1221 }
Yifan Hong65613032020-01-09 17:52:13 -08001222
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001223 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1224 manifest.apex_info().end());
1225 uint64_t apex_size_required = 0;
1226 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001227 auto result = apex_handler_android_->CalculateSize(apex_infos);
1228 if (!result.ok()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001229 LogAndSetGenericError(
1230 error,
1231 __LINE__,
1232 __FILE__,
1233 "Failed to calculate size required for compressed APEX");
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001234 return 0;
1235 }
1236 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001237 }
1238
Yifan Hong65613032020-01-09 17:52:13 -08001239 string payload_id = GetPayloadId(headers);
1240 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -07001241 ErrorCode error_code{};
1242
Yifan Hong65613032020-01-09 17:52:13 -08001243 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1244 boot_control_,
1245 GetTargetSlot(),
1246 manifest,
1247 payload_id,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001248 &required_size,
1249 &error_code)) {
1250 if (error_code == ErrorCode::kOverlayfsenabledError) {
1251 LogAndSetError(error,
1252 __LINE__,
1253 __FILE__,
1254 "OverlayFS Shouldn't be enabled for OTA.",
1255 error_code);
1256 return 0;
1257 }
Yifan Hong65613032020-01-09 17:52:13 -08001258 if (required_size == 0) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001259 LogAndSetGenericError(
1260 error, __LINE__, __FILE__, "Failed to allocate space for payload.");
Yifan Hong65613032020-01-09 17:52:13 -08001261 return 0;
1262 } else {
1263 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001264 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001265 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001266 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001267 }
1268 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001269
1270 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001271 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001272 LOG(ERROR) << "Insufficient space for apex decompression: "
1273 << apex_size_required << " bytes";
1274 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001275 }
Yifan Hong65613032020-01-09 17:52:13 -08001276
1277 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001278 return 0;
1279}
1280
Yifan Hong40bb0d02020-02-24 17:33:14 -08001281void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1282 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001283 Error* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001284 if (cleanup_previous_update_code_.has_value()) {
1285 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1286 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1287 if (callback) {
1288 callback->OnCleanupComplete(
1289 static_cast<int32_t>(*cleanup_previous_update_code_));
1290 }
1291 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001292 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001293 if (callback) {
1294 auto callback_ptr = callback.get();
1295 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
Kelvin Zhang2f6c25a2023-07-05 12:49:34 -07001296 callback_ptr->RegisterForDeathNotifications([this, callback_ptr]() {
1297 RemoveCleanupPreviousUpdateCallback(callback_ptr);
1298 });
Yifan Hong40bb0d02020-02-24 17:33:14 -08001299 }
1300 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001301}
1302
Tianjie7f8f2ab2021-07-23 17:08:50 -07001303bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
Daniel Zheng92f7d172023-06-22 14:31:37 -07001304 const std::string& metadata_filename, Error* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001305 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001306 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001307 return LogAndSetGenericError(
1308 error,
1309 __LINE__,
1310 __FILE__,
1311 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001312 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001313 DeltaArchiveManifest manifest;
1314 TEST_AND_RETURN_FALSE(
1315 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1316
Kelvin Zhang20982a52021-08-13 12:31:16 -07001317 InstallPlan install_plan_;
1318 install_plan_.source_slot = GetCurrentSlot();
1319 install_plan_.target_slot = GetTargetSlot();
1320 // Don't do verity computation, just hash the partitions
1321 install_plan_.write_verity = false;
1322 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1323 install_plan_.run_post_install = false;
1324 install_plan_.is_resume = true;
1325
1326 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1327 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1328
Kelvin Zhang20982a52021-08-13 12:31:16 -07001329 auto postinstall_runner_action =
1330 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001331 postinstall_runner_action->set_delegate(this);
1332
Kelvin Zhangf8441982022-12-07 18:18:47 -08001333 // If last error code is kUpdatedButNotActive, we know that we reached this
1334 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1335 // call would have already performed filesystem verification, therefore, we
1336 // can safely skip the verification to save time.
1337 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001338 auto install_plan_action =
1339 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001340 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1341 processor_->EnqueueAction(std::move(install_plan_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001342 SetStatusAndNotify(UpdateStatus::FINALIZING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001343 } else {
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001344 ErrorCode error_code{};
Kelvin Zhang263a5402022-12-08 23:03:32 -08001345 if (!boot_control_->GetDynamicPartitionControl()
1346 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1347 GetTargetSlot(),
1348 manifest,
1349 false /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001350 nullptr,
1351 &error_code)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001352 return LogAndSetGenericError(
1353 error, __LINE__, __FILE__, "Failed to PreparePartitionsForUpdate");
Kelvin Zhang263a5402022-12-08 23:03:32 -08001354 }
Kelvin Zhang263a5402022-12-08 23:03:32 -08001355 if (!install_plan_.ParsePartitions(manifest.partitions(),
1356 boot_control_,
1357 manifest.block_size(),
1358 &error_code)) {
1359 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001360 __LINE__,
1361 __FILE__,
Kelvin Zhang263a5402022-12-08 23:03:32 -08001362 "Failed to LoadPartitionsFromSlots " +
Daniel Zheng92f7d172023-06-22 14:31:37 -07001363 utils::ErrorCodeToString(error_code),
1364 error_code);
Kelvin Zhang263a5402022-12-08 23:03:32 -08001365 }
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001366 auto install_plan_action =
1367 std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001368 auto filesystem_verifier_action =
1369 std::make_unique<FilesystemVerifierAction>(
1370 boot_control_->GetDynamicPartitionControl());
1371 filesystem_verifier_action->set_delegate(this);
1372 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1373 BondActions(filesystem_verifier_action.get(),
1374 postinstall_runner_action.get());
1375 processor_->EnqueueAction(std::move(install_plan_action));
1376 processor_->EnqueueAction(std::move(filesystem_verifier_action));
Kelvin Zhang19acf4f2024-01-08 21:18:28 +00001377 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhangf8441982022-12-07 18:18:47 -08001378 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001379
Kelvin Zhang20982a52021-08-13 12:31:16 -07001380 processor_->EnqueueAction(std::move(postinstall_runner_action));
1381 ScheduleProcessingStart();
1382 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001383}
1384
Daniel Zheng92f7d172023-06-22 14:31:37 -07001385bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(Error* error) {
Tianjie7f8f2ab2021-07-23 17:08:50 -07001386 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001387 return LogAndSetGenericError(
1388 error,
1389 __LINE__,
1390 __FILE__,
1391 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001392 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001393 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001394 // Update the boot flags so the current slot has higher priority.
1395 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001396 return LogAndSetGenericError(
1397 error, __LINE__, __FILE__, "Failed to SetActiveBootSlot");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001398 }
1399
1400 // Mark the current slot as successful again, since marking it as active
1401 // may reset the successful bit. We ignore the result of whether marking
1402 // the current slot as successful worked.
1403 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001404 return LogAndSetGenericError(
1405 error, __LINE__, __FILE__, "Failed to MarkBootSuccessfulAsync");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001406 }
1407
1408 // Resets the warm reset property since we won't switch the slot.
1409 hardware_->SetWarmReset(false);
1410
1411 // Resets the vbmeta digest.
1412 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1413 LOG(INFO) << "Slot switch cancelled.";
1414 SetStatusAndNotify(UpdateStatus::IDLE);
1415 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001416}
1417
Yifan Hong90965502020-02-19 15:22:47 -08001418void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1419 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1420 // is in progress, skip enqueueing the action.
1421 if (processor_->IsRunning()) {
1422 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1423 << "be done when the current update finishes.";
1424 return;
1425 }
1426 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1427 auto action =
1428 boot_control_->GetDynamicPartitionControl()
1429 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1430 processor_->EnqueueAction(std::move(action));
1431 processor_->set_delegate(this);
1432 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1433 processor_->StartProcessing();
1434}
1435
Yifan Hong40bb0d02020-02-24 17:33:14 -08001436void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1437 for (auto&& callback : cleanup_previous_update_callbacks_) {
1438 callback->OnCleanupProgressUpdate(progress);
1439 }
1440}
1441
1442void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1443 CHECK(cleanup_previous_update_code_.has_value());
1444 for (auto&& callback : cleanup_previous_update_callbacks_) {
1445 callback->OnCleanupComplete(
1446 static_cast<int32_t>(*cleanup_previous_update_code_));
1447 }
1448 cleanup_previous_update_callbacks_.clear();
1449}
1450
1451void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1452 CleanupSuccessfulUpdateCallbackInterface* callback) {
1453 auto end_it =
1454 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1455 cleanup_previous_update_callbacks_.end(),
1456 [&](const auto& e) { return e.get() == callback; });
1457 cleanup_previous_update_callbacks_.erase(
1458 end_it, cleanup_previous_update_callbacks_.end());
1459}
Yifan Hong90965502020-02-19 15:22:47 -08001460
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001461bool UpdateAttempterAndroid::IsProductionBuild() {
1462 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1463 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1464 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1465 return true;
1466 }
1467 return false;
1468}
1469
Alex Deymo5e3ea272016-01-28 13:42:23 -08001470} // namespace chromeos_update_engine