blob: 2e0232b5a27e4ffde568b13b0ab7aaaf6a45e7dc [file] [log] [blame]
Alex Deymo5e3ea272016-01-28 13:42:23 -08001//
2// Copyright (C) 2016 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/update_attempter_android.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080018
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070021#include <memory>
Kelvin Zhanga43d6e82021-05-26 10:14:42 -040022#include <ostream>
Alex Deymo5e3ea272016-01-28 13:42:23 -080023#include <utility>
Daniel Zhengda4f7292022-09-02 22:59:32 +000024#include <vector>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025
Tianjie Xu90aaa102017-10-10 17:39:03 -070026#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090027#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080028#include <base/bind.h>
29#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080030#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070031#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080032#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080033#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070034#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080035
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/aosp/cleanup_previous_update_action.h"
Daniel Zhengda4f7292022-09-02 22:59:32 +000037#include "update_engine/common/clock.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080038#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070039#include "update_engine/common/daemon_state_interface.h"
40#include "update_engine/common/download_action.h"
Kelvin Zhangf8441982022-12-07 18:18:47 -080041#include "update_engine/common/error_code.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070043#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070044#include "update_engine/common/metrics_reporter_interface.h"
45#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070047#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080048#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/file_descriptor.h"
50#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000052#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080053#include "update_engine/payload_consumer/payload_constants.h"
54#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070055#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080056#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070057#include "update_engine/update_boot_flags_action.h"
Kelvin Zhangf92fe252023-03-28 10:55:47 -070058#include "update_engine/update_status.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080059#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080060
Alex Deymo14c0da82016-07-20 16:45:45 -070061#ifndef _UE_SIDELOAD
62// Do not include support for external HTTP(s) urls when building
63// update_engine_sideload.
64#include "update_engine/libcurl_http_fetcher.h"
65#endif
66
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090067using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070069using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070using base::TimeDelta;
71using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080072using std::string;
73using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070074using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080075
76namespace chromeos_update_engine {
77
78namespace {
79
Alex Deymo0d298542016-03-30 18:31:49 -070080// Minimum threshold to broadcast an status update in progress and time.
81const double kBroadcastThresholdProgress = 0.01; // 1%
82const int kBroadcastThresholdSeconds = 10;
83
Daniel Zheng92f7d172023-06-22 14:31:37 -070084// Log and set the error on the passed ErrorPtr.
85bool LogAndSetGenericError(Error* error,
86 int line_number,
87 const char* file_name,
88 const string& reason) {
89 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
90 << ": " << reason;
91 error->line_number = line_number;
92 error->file_name = file_name;
93 error->message = reason;
94 error->error_code = ErrorCode::kError;
95 return false;
96}
Alex Deymo5e3ea272016-01-28 13:42:23 -080097
98// Log and set the error on the passed ErrorPtr.
Daniel Zheng92f7d172023-06-22 14:31:37 -070099bool LogAndSetError(Error* error,
100 int line_number,
101 const char* file_name,
102 const string& reason,
103 ErrorCode error_code) {
104 LOG(ERROR) << "Replying with failure: " << file_name << " " << line_number
105 << ": " << reason;
106 error->line_number = line_number;
107 error->file_name = file_name;
108 error->message = reason;
109 error->error_code = error_code;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800110 return false;
111}
112
Sen Jiangfe522822017-10-31 15:14:11 -0700113bool GetHeaderAsBool(const string& header, bool default_value) {
114 int value = 0;
115 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
116 return value == 1;
117 return default_value;
118}
119
Yifan Hongbd47d622019-12-13 14:59:58 -0800120bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
121 std::map<string, string>* headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700122 Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800123 for (const string& key_value_pair : key_value_pair_headers) {
124 string key;
125 string value;
126 if (!brillo::string_utils::SplitAtFirst(
127 key_value_pair, "=", &key, &value, false)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700128 return LogAndSetGenericError(error,
129 __LINE__,
130 __FILE__,
131 "Passed invalid header: " + key_value_pair);
Yifan Hongbd47d622019-12-13 14:59:58 -0800132 }
133 if (!headers->emplace(key, value).second)
Daniel Zheng92f7d172023-06-22 14:31:37 -0700134 return LogAndSetGenericError(
135 error, __LINE__, __FILE__, "Passed repeated key: " + key);
Yifan Hongbd47d622019-12-13 14:59:58 -0800136 }
137 return true;
138}
139
140// Unique identifier for the payload. An empty string means that the payload
141// can't be resumed.
142string GetPayloadId(const std::map<string, string>& headers) {
143 return (headers.count(kPayloadPropertyFileHash)
144 ? headers.at(kPayloadPropertyFileHash)
145 : "") +
146 (headers.count(kPayloadPropertyMetadataHash)
147 ? headers.at(kPayloadPropertyMetadataHash)
148 : "");
149}
150
Alex Deymo5e3ea272016-01-28 13:42:23 -0800151} // namespace
152
153UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700154 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800155 PrefsInterface* prefs,
156 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000157 HardwareInterface* hardware,
158 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800159 : daemon_state_(daemon_state),
160 prefs_(prefs),
161 boot_control_(boot_control),
162 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000163 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700164 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800165 clock_(new Clock()),
166 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
167 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800168 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400169 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700170 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800171}
172
173UpdateAttempterAndroid::~UpdateAttempterAndroid() {
174 // Release ourselves as the ActionProcessor's delegate to prevent
175 // re-scheduling the updates due to the processing stopped.
176 processor_->set_delegate(nullptr);
177}
178
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400179[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
180 string boot_id;
181 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
182 string old_boot_id;
183 // If no previous boot id found, treat as a reboot and write boot ID.
184 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
185 return true;
186 }
187 return old_boot_id != boot_id;
188}
189
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400190std::ostream& operator<<(std::ostream& out, OTAResult result) {
191 switch (result) {
192 case OTAResult::NOT_ATTEMPTED:
193 out << "OTAResult::NOT_ATTEMPTED";
194 break;
195 case OTAResult::ROLLED_BACK:
196 out << "OTAResult::ROLLED_BACK";
197 break;
198 case OTAResult::UPDATED_NEED_REBOOT:
199 out << "OTAResult::UPDATED_NEED_REBOOT";
200 break;
201 case OTAResult::OTA_SUCCESSFUL:
202 out << "OTAResult::OTA_SUCCESSFUL";
203 break;
204 }
205 return out;
206}
207
Alex Deymo5e3ea272016-01-28 13:42:23 -0800208void UpdateAttempterAndroid::Init() {
209 // In case of update_engine restart without a reboot we need to restore the
210 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700211 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400212 LOG(INFO) << "Updated installed but update_engine is restarted without "
213 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800214 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700215 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400216 const auto result = GetOTAUpdateResult();
217 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800218 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400219 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400220 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400221 }
222
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700223#ifdef _UE_SIDELOAD
224 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
225 << "ApplyPayload will call it later.";
226#else
Yifan Hong90965502020-02-19 15:22:47 -0800227 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700228#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700229 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800230}
231
232bool UpdateAttempterAndroid::ApplyPayload(
233 const string& payload_url,
234 int64_t payload_offset,
235 int64_t payload_size,
236 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700237 Error* error) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800238 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700239 return LogAndSetGenericError(
240 error,
241 __LINE__,
242 __FILE__,
243 "An update already applied, waiting for reboot");
Alex Deymo5e3ea272016-01-28 13:42:23 -0800244 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700245 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700246 return LogAndSetGenericError(
247 error,
248 __LINE__,
249 __FILE__,
250 "Already processing an update, cancel it first.");
Alex Deymo5e3ea272016-01-28 13:42:23 -0800251 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100252 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800253
Alex Deymo218397f2016-02-04 23:55:10 -0800254 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800255 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
256 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800257 }
258
Yifan Hongbd47d622019-12-13 14:59:58 -0800259 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800260
261 // Setup the InstallPlan based on the request.
262 install_plan_ = InstallPlan();
263
264 install_plan_.download_url = payload_url;
265 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800266 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800267 InstallPlan::Payload payload;
268 payload.size = payload_size;
269 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800270 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800271 &payload.size)) {
272 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800273 }
274 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700275 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800276 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700277 LOG(WARNING) << "Unable to decode base64 file hash: "
278 << headers[kPayloadPropertyFileHash];
279 }
Alex Deymo218397f2016-02-04 23:55:10 -0800280 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800281 &payload.metadata_size)) {
282 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800283 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700284 // The |payload.type| is not used anymore since minor_version 3.
285 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800286 install_plan_.payloads.push_back(payload);
287
Alex Deymo5e3ea272016-01-28 13:42:23 -0800288 // The |public_key_rsa| key would override the public key stored on disk.
289 install_plan_.public_key_rsa = "";
290
291 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
292 install_plan_.is_resume = !payload_id.empty() &&
293 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
294 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700295 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700296 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
297
Alex Deymo5e3ea272016-01-28 13:42:23 -0800298 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
299 LOG(WARNING) << "Unable to save the update check response hash.";
300 }
301 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800302 install_plan_.source_slot = GetCurrentSlot();
303 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700304
Alex Deymofb905d92016-06-03 19:26:58 -0700305 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700306 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
307
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000308 if (!IsProductionBuild()) {
309 install_plan_.disable_vabc =
310 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
311 }
312
Sen Jiangfe522822017-10-31 15:14:11 -0700313 install_plan_.switch_slot_on_reboot =
314 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
315
Tianjie Xu087de9d2019-11-01 17:11:22 -0700316 install_plan_.run_post_install =
317 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800318
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700319 // Skip writing verity if we're resuming and verity has already been written.
320 install_plan_.write_verity = true;
321 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
322 bool verity_written = false;
323 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
324 verity_written) {
325 install_plan_.write_verity = false;
326 }
327 }
328
Alex Deymo87792ea2016-07-25 15:40:36 -0700329 NetworkId network_id = kDefaultNetworkId;
330 if (!headers[kPayloadPropertyNetworkId].empty()) {
331 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
332 &network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700333 return LogAndSetGenericError(
Alex Deymo87792ea2016-07-25 15:40:36 -0700334 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700335 __LINE__,
336 __FILE__,
Alex Deymo87792ea2016-07-25 15:40:36 -0700337 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
338 }
339 if (!network_selector_->SetProcessNetwork(network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700340 return LogAndSetGenericError(
Sen Jiangcbd37c62017-09-12 15:04:35 -0700341 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700342 __LINE__,
343 __FILE__,
Sen Jiangcbd37c62017-09-12 15:04:35 -0700344 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700345 }
346 }
347
Alex Deymo5e3ea272016-01-28 13:42:23 -0800348 LOG(INFO) << "Using this install plan:";
349 install_plan_.Dump();
350
Amin Hassani667cf7b2018-07-25 14:32:00 -0700351 HttpFetcher* fetcher = nullptr;
352 if (FileFetcher::SupportedUrl(payload_url)) {
353 DLOG(INFO) << "Using FileFetcher for file URL.";
354 fetcher = new FileFetcher();
355 } else {
356#ifdef _UE_SIDELOAD
357 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800358 return false; // NOLINT, unreached but analyzer might not know.
359 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700360#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700361 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700362 if (!headers[kPayloadDownloadRetry].empty()) {
363 libcurl_fetcher->set_max_retry_count(
364 atoi(headers[kPayloadDownloadRetry].c_str()));
365 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700366 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
367 fetcher = libcurl_fetcher;
368#endif // _UE_SIDELOAD
369 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800370 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800371 if (!headers[kPayloadPropertyAuthorization].empty())
372 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
373 if (!headers[kPayloadPropertyUserAgent].empty())
374 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
375
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700376 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
377 LOG(INFO) << "Using proxy url from payload headers: "
378 << headers[kPayloadPropertyNetworkProxy];
379 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
380 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700381 if (!headers[kPayloadVABCNone].empty()) {
382 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000383 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800384 if (!headers[kPayloadEnableThreading].empty()) {
385 install_plan_.enable_threading = true;
386 }
387 if (!headers[kPayloadBatchedWrites].empty()) {
388 install_plan_.batched_writes = true;
389 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700390
Amin Hassani667cf7b2018-07-25 14:32:00 -0700391 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800392
Alex Deymo5e3ea272016-01-28 13:42:23 -0800393 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700394
395 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
396 // TODO(xunchang) report the metrics for unresumable updates
397
Amin Hassani667cf7b2018-07-25 14:32:00 -0700398 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800399 return true;
400}
401
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900402bool UpdateAttempterAndroid::ApplyPayload(
403 int fd,
404 int64_t payload_offset,
405 int64_t payload_size,
406 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700407 Error* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100408 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000409 // already running update will be terminated (existing file descriptor will be
410 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100411 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700412 return LogAndSetGenericError(
413 error,
414 __LINE__,
415 __FILE__,
416 "An update already applied, waiting for reboot");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100417 }
418 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700419 return LogAndSetGenericError(
420 error,
421 __LINE__,
422 __FILE__,
423 "Already processing an update, cancel it first.");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100424 }
425 DCHECK_EQ(status_, UpdateStatus::IDLE);
426
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900427 payload_fd_.reset(dup(fd));
428 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
429
430 return ApplyPayload(
431 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
432}
433
Daniel Zheng92f7d172023-06-22 14:31:37 -0700434bool UpdateAttempterAndroid::SuspendUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700435 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700436 return LogAndSetGenericError(
437 error, __LINE__, __FILE__, "No ongoing update to suspend.");
Alex Deymof2858572016-02-25 11:20:13 -0800438 processor_->SuspendProcessing();
439 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800440}
441
Daniel Zheng92f7d172023-06-22 14:31:37 -0700442bool UpdateAttempterAndroid::ResumeUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700443 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700444 return LogAndSetGenericError(
445 error, __LINE__, __FILE__, "No ongoing update to resume.");
Alex Deymof2858572016-02-25 11:20:13 -0800446 processor_->ResumeProcessing();
447 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800448}
449
Daniel Zheng92f7d172023-06-22 14:31:37 -0700450bool UpdateAttempterAndroid::CancelUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700451 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700452 return LogAndSetGenericError(
453 error, __LINE__, __FILE__, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800454 processor_->StopProcessing();
455 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800456}
457
Daniel Zheng92f7d172023-06-22 14:31:37 -0700458bool UpdateAttempterAndroid::ResetStatus(Error* error) {
Alex Deymo3b678db2016-02-09 11:50:06 -0800459 LOG(INFO) << "Attempting to reset state from "
460 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700461 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700462 return LogAndSetGenericError(
463 error,
464 __LINE__,
465 __FILE__,
466 "Already processing an update, cancel it first.");
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700467 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700468 if (status_ != UpdateStatus::IDLE &&
469 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700470 return LogAndSetGenericError(
471 error,
472 __LINE__,
473 __FILE__,
474 "Status reset not allowed in this state, please "
475 "cancel on going OTA first.");
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700476 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800477
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000478 if (apex_handler_android_ != nullptr) {
479 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
480 std::vector<ApexInfo> apex_infos_blank;
481 apex_handler_android_->AllocateSpace(apex_infos_blank);
482 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400483 // Remove the reboot marker so that if the machine is rebooted
484 // after resetting to idle state, it doesn't go back to
485 // UpdateStatus::UPDATED_NEED_REBOOT state.
486 if (!ClearUpdateCompletedMarker()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700487 return LogAndSetGenericError(error,
488 __LINE__,
489 __FILE__,
490 "Failed to reset the status because "
491 "ClearUpdateCompletedMarker() failed");
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400492 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700493 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
494 if (!resetShouldSwitchSlotOnReboot(error)) {
495 LOG(INFO) << "Failed to reset slot switch.";
496 return false;
497 }
498 LOG(INFO) << "Slot switch reset successful";
499 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700500 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
501 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000502 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700503 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700504 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800505}
506
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700507bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
508 if (a.size() != b.size()) {
509 return false;
510 }
511 return memcmp(a.data(), b.data(), a.size()) == 0;
512}
513bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
514 return !(a == b);
515}
516
Yifan Hongbd47d622019-12-13 14:59:58 -0800517bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
518 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700519 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800520 DeltaArchiveManifest* manifest,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700521 Error* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800522 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
523 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700524 return LogAndSetError(error,
525 __LINE__,
526 __FILE__,
527 "Failed to open " + metadata_filename,
528 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800529 }
530 brillo::Blob metadata(kMaxPayloadHeaderSize);
531 if (!fd->Read(metadata.data(), metadata.size())) {
532 return LogAndSetError(
533 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700534 __LINE__,
535 __FILE__,
536 "Failed to read payload header from " + metadata_filename,
537 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800538 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000539 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800540 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700541 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800542 MetadataParseResult::kSuccess) {
543 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700544 __LINE__,
545 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800546 "Failed to parse payload header: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700547 utils::ErrorCodeToString(errorcode),
548 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800549 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700550 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
551 payload_metadata.GetMetadataSignatureSize();
552 if (metadata_size < kMaxPayloadHeaderSize ||
553 metadata_size >
554 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800555 return LogAndSetError(
556 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700557 __LINE__,
558 __FILE__,
559 "Invalid metadata size: " + std::to_string(metadata_size),
560 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800561 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700562 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800563 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
564 metadata.size() - kMaxPayloadHeaderSize)) {
565 return LogAndSetError(
566 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700567 __LINE__,
568 __FILE__,
569 "Failed to read metadata and signature from " + metadata_filename,
570 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800571 }
572 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700573 if (!expected_metadata_hash.empty()) {
574 brillo::Blob metadata_hash;
575 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
576 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
577 if (metadata_hash != expected_metadata_hash) {
578 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700579 __LINE__,
580 __FILE__,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700581 "Metadata hash mismatch. Expected hash: " +
582 HexEncode(expected_metadata_hash) +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700583 " actual hash: " + HexEncode(metadata_hash),
584 ErrorCode::kDownloadManifestParseError);
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700585 } else {
586 LOG(INFO) << "Payload metadata hash check passed : "
587 << HexEncode(metadata_hash);
588 }
589 }
Sen Jiang08c6da12019-01-07 18:28:56 -0800590
Tianjie Xu7a78d632019-10-08 16:32:39 -0700591 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
592 constants::kUpdateCertificatesPath);
593 if (!payload_verifier) {
594 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700595 __LINE__,
596 __FILE__,
Tianjie Xu7a78d632019-10-08 16:32:39 -0700597 "Failed to create the payload verifier from " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700598 std::string(constants::kUpdateCertificatesPath),
599 ErrorCode::kDownloadManifestParseError);
Sen Jiang08c6da12019-01-07 18:28:56 -0800600 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700601 errorcode = payload_metadata.ValidateMetadataSignature(
602 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800603 if (errorcode != ErrorCode::kSuccess) {
604 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700605 __LINE__,
606 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800607 "Failed to validate metadata signature: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700608 utils::ErrorCodeToString(errorcode),
609 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800610 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800611 if (!payload_metadata.GetManifest(metadata, manifest)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700612 return LogAndSetError(error,
613 __LINE__,
614 __FILE__,
615 "Failed to parse manifest.",
616 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800617 }
618
Yifan Hongbd47d622019-12-13 14:59:58 -0800619 return true;
620}
621
622bool UpdateAttempterAndroid::VerifyPayloadApplicable(
Daniel Zheng92f7d172023-06-22 14:31:37 -0700623 const std::string& metadata_filename, Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800624 DeltaArchiveManifest manifest;
625 TEST_AND_RETURN_FALSE(
626 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
627
628 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000629 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800630
631 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800632 for (const PartitionUpdate& partition : manifest.partitions()) {
633 if (!partition.has_old_partition_info())
634 continue;
635 string partition_path;
636 if (!boot_control_->GetPartitionDevice(
637 partition.partition_name(), current_slot, &partition_path)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700638 return LogAndSetGenericError(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800639 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700640 __LINE__,
641 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800642 "Failed to get partition device for " + partition.partition_name());
643 }
644 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700645 return LogAndSetGenericError(
646 error, __LINE__, __FILE__, "Failed to open " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800647 }
648 for (const InstallOperation& operation : partition.operations()) {
649 if (!operation.has_src_sha256_hash())
650 continue;
651 brillo::Blob source_hash;
652 if (!fd_utils::ReadAndHashExtents(fd,
653 operation.src_extents(),
654 manifest.block_size(),
655 &source_hash)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700656 return LogAndSetGenericError(
657 error, __LINE__, __FILE__, "Failed to hash " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800658 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400659 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800660 source_hash, operation, fd, &errorcode)) {
661 return false;
662 }
663 }
664 fd->Close();
665 }
666 return true;
667}
668
Alex Deymo5e3ea272016-01-28 13:42:23 -0800669void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
670 ErrorCode code) {
671 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800672 metric_bytes_downloaded_.Flush(true);
673 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800674 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800675 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
676 TerminateUpdateAndNotify(code);
677 return;
678 }
679
Alex Deymo5990bf32016-07-19 17:01:41 -0700680 switch (code) {
681 case ErrorCode::kSuccess:
682 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400683 if (!WriteUpdateCompletedMarker()) {
684 LOG(ERROR) << "Failed to write update completion marker";
685 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700686 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800687
Alex Deymo5990bf32016-07-19 17:01:41 -0700688 LOG(INFO) << "Update successfully applied, waiting to reboot.";
689 break;
690
691 case ErrorCode::kFilesystemCopierError:
692 case ErrorCode::kNewRootfsVerificationError:
693 case ErrorCode::kNewKernelVerificationError:
694 case ErrorCode::kFilesystemVerifierError:
695 case ErrorCode::kDownloadStateInitializationError:
696 // Reset the ongoing update for these errors so it starts from the
697 // beginning next time.
698 DeltaPerformer::ResetUpdateProgress(prefs_, false);
699 LOG(INFO) << "Resetting update progress.";
700 break;
701
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700702 case ErrorCode::kPayloadTimestampError:
703 // SafetyNet logging, b/36232423
704 android_errorWriteLog(0x534e4554, "36232423");
705 break;
706
Alex Deymo5990bf32016-07-19 17:01:41 -0700707 default:
708 // Ignore all other error codes.
709 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700710 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800711
712 TerminateUpdateAndNotify(code);
713}
714
715void UpdateAttempterAndroid::ProcessingStopped(
716 const ActionProcessor* processor) {
717 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
718}
719
720void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
721 AbstractAction* action,
722 ErrorCode code) {
723 // Reset download progress regardless of whether or not the download
724 // action succeeded.
725 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800726 if (type == CleanupPreviousUpdateAction::StaticType() ||
727 (type == NoOpAction::StaticType() &&
728 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
729 cleanup_previous_update_code_ = code;
730 NotifyCleanupPreviousUpdateCallbacksAndClear();
731 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000732 // download_progress_ is actually used by other actions, such as
733 // filesystem_verify_action. Therefore we always clear it.
734 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700735 if (type == PostinstallRunnerAction::StaticType()) {
736 bool succeeded =
737 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
738 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
739 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800740 if (code != ErrorCode::kSuccess) {
741 // If an action failed, the ActionProcessor will cancel the whole thing.
742 return;
743 }
Yifan Hong83517502020-02-19 15:34:13 -0800744 if (type == UpdateBootFlagsAction::StaticType()) {
745 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
746 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800747 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400748 auto download_action = static_cast<DownloadAction*>(action);
749 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000750 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700751 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000752 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700753 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800754 }
755}
756
757void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
758 uint64_t bytes_received,
759 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700760 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800761 if (total)
762 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700763 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800764 download_progress_ = progress;
765 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700766 } else {
767 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800768 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700769
770 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800771 metric_bytes_downloaded_ += bytes_progressed;
772 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800773}
774
775bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
776 // TODO(deymo): Notify the DownloadAction that it should cancel the update
777 // download.
778 return false;
779}
780
781void UpdateAttempterAndroid::DownloadComplete() {
782 // Nothing needs to be done when the download completes.
783}
784
Alex Deymo0d298542016-03-30 18:31:49 -0700785void UpdateAttempterAndroid::ProgressUpdate(double progress) {
786 // Self throttle based on progress. Also send notifications if progress is
787 // too slow.
788 if (progress == 1.0 ||
789 progress - download_progress_ >= kBroadcastThresholdProgress ||
790 TimeTicks::Now() - last_notify_time_ >=
791 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
792 download_progress_ = progress;
793 SetStatusAndNotify(status_);
794 }
795}
796
Kelvin Zhang70eef232020-06-12 20:32:40 +0000797void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
798 assert(status_ == UpdateStatus::VERIFYING);
799 ProgressUpdate(progress);
800}
801
Alex Deymo5e3ea272016-01-28 13:42:23 -0800802void UpdateAttempterAndroid::ScheduleProcessingStart() {
803 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700804 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800805 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700806 FROM_HERE,
807 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
808 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800809}
810
811void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
812 if (status_ == UpdateStatus::IDLE) {
813 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
814 return;
815 }
816
Yifan Hong90965502020-02-19 15:22:47 -0800817 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400818 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800819 LOG(INFO) << "Terminating cleanup previous update.";
820 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700821 for (auto observer : daemon_state_->service_observers())
822 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800823 return;
824 }
825
Yifan Hong9194ce82019-11-07 11:03:42 -0800826 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700827
Alex Deymo0d298542016-03-30 18:31:49 -0700828 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800829 UpdateStatus new_status =
830 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
831 : UpdateStatus::IDLE);
832 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900833 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800834
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700835 // The network id is only applicable to one download attempt and once it's
836 // done the network id should not be re-used anymore.
837 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
838 LOG(WARNING) << "Unable to unbind network.";
839 }
840
Alex Deymo5e3ea272016-01-28 13:42:23 -0800841 for (auto observer : daemon_state_->service_observers())
842 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700843
Tianjie Xu90aaa102017-10-10 17:39:03 -0700844 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
845 ClearMetricsPrefs();
846 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800847 // We should only reset the PayloadAttemptNumber if the update succeeds, or
848 // we switch to a different payload.
849 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700850 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700851 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800852 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700853 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800854}
855
856void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
857 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700858 size_t payload_size =
859 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700860 UpdateEngineStatus status_to_send = {.status = status_,
861 .progress = download_progress_,
862 .new_size_bytes = payload_size};
863
Alex Deymo5e3ea272016-01-28 13:42:23 -0800864 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700865 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800866 }
867 last_notify_time_ = TimeTicks::Now();
868}
869
Amin Hassani667cf7b2018-07-25 14:32:00 -0700870void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800871 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800872
873 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700874 auto update_boot_flags_action =
875 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800876 auto cleanup_previous_update_action =
877 boot_control_->GetDynamicPartitionControl()
878 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700879 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
880 auto download_action =
881 std::make_unique<DownloadAction>(prefs_,
882 boot_control_,
883 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700884 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700885 true /* interactive */,
886 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800887 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700888 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700889 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
890 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700891 auto postinstall_runner_action =
892 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000893 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700894 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800895
Alex Deymo5e3ea272016-01-28 13:42:23 -0800896 // Bond them together. We have to use the leaf-types when calling
897 // BondActions().
898 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700899 BondActions(download_action.get(), filesystem_verifier_action.get());
900 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800901 postinstall_runner_action.get());
902
Amin Hassani667cf7b2018-07-25 14:32:00 -0700903 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800904 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700905 processor_->EnqueueAction(std::move(install_plan_action));
906 processor_->EnqueueAction(std::move(download_action));
907 processor_->EnqueueAction(std::move(filesystem_verifier_action));
908 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800909}
910
Alex Deymo5e3ea272016-01-28 13:42:23 -0800911bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
912 string boot_id;
913 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800914 LOG(INFO) << "Writing update complete marker, slot "
915 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400916 TEST_AND_RETURN_FALSE(
917 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
918 TEST_AND_RETURN_FALSE(
919 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
920 return true;
921}
922
923bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
924 LOG(INFO) << "Clearing update complete marker.";
925 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
926 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800927 return true;
928}
929
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800930bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800931 // In case of an update_engine restart without a reboot, we stored the boot_id
932 // when the update was completed by setting a pref, so we can check whether
933 // the last update was on this boot or a previous one.
934 string boot_id;
935 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
936
937 string update_completed_on_boot_id;
938 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
939 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
940 &update_completed_on_boot_id) &&
941 update_completed_on_boot_id == boot_id);
942}
943
Tianjie Xu90aaa102017-10-10 17:39:03 -0700944// Collect and report the android metrics when we terminate the update.
945void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
946 ErrorCode error_code) {
947 int64_t attempt_number =
948 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
949 PayloadType payload_type = kPayloadTypeFull;
950 int64_t payload_size = 0;
951 for (const auto& p : install_plan_.payloads) {
952 if (p.type == InstallPayloadType::kDelta)
953 payload_type = kPayloadTypeDelta;
954 payload_size += p.size;
955 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700956 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
957 // function will be triggered, but payload_size in this case might be 0, if so
958 // skip reporting any metrics.
959 if (payload_size == 0) {
960 return;
961 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700962
963 metrics::AttemptResult attempt_result =
964 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700965 Time boot_time_start = Time::FromInternalValue(
966 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
967 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700968 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700969 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
970 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700971
972 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700973 static_cast<int>(attempt_number),
974 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700975 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700976 duration_uptime,
977 payload_size,
978 attempt_result,
979 error_code);
980
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800981 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700982 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
983 current_bytes_downloaded,
984 0,
985 DownloadSource::kNumDownloadSources,
986 metrics::DownloadErrorCode::kUnset,
987 metrics::ConnectionType::kUnset);
988
Tianjie Xu90aaa102017-10-10 17:39:03 -0700989 if (error_code == ErrorCode::kSuccess) {
990 int64_t reboot_count =
991 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
992 string build_version;
993 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700994
995 // For android metrics, we only care about the total bytes downloaded
996 // for all sources; for now we assume the only download source is
997 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800998 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700999 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
1000 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
1001 total_bytes_downloaded;
1002
1003 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -07001004 if (total_bytes_downloaded >= payload_size) {
1005 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -07001006 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -07001007 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
1008 } else {
1009 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
1010 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -07001011 }
Tianjie Xu21030c12019-08-14 13:00:23 -07001012
Tianjie Xu90aaa102017-10-10 17:39:03 -07001013 metrics_reporter_->ReportSuccessfulUpdateMetrics(
1014 static_cast<int>(attempt_number),
1015 0, // update abandoned count
1016 payload_type,
1017 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -07001018 num_bytes_downloaded,
1019 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001020 duration,
Sen Jiang8712e962018-05-08 12:12:28 -07001021 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001022 static_cast<int>(reboot_count),
1023 0); // url_switch_count
1024 }
1025}
1026
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001027bool UpdateAttempterAndroid::OTARebootSucceeded() const {
1028 const auto current_slot = boot_control_->GetCurrentSlot();
1029 const string current_version =
1030 android::base::GetProperty("ro.build.version.incremental", "");
1031 int64_t previous_slot = -1;
1032 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
1033 string previous_version;
1034 TEST_AND_RETURN_FALSE(
1035 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
1036 if (previous_slot != current_slot) {
1037 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001038 << previous_version << " to " << current_version
1039 << ", previous slot: " << previous_slot
1040 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001041 if (previous_version == current_version) {
1042 LOG(INFO) << "Previous version is the same as current version, this is "
1043 "possibly a self-OTA.";
1044 }
1045 return true;
1046 } else {
1047 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
1048 "switch never happened, or system not rebooted at all.";
1049 if (previous_version != current_version) {
1050 LOG(INFO) << "Slot didn't change, but version changed from "
1051 << previous_version << " to " << current_version
1052 << " device could be flashed.";
1053 }
1054 return false;
1055 }
1056}
1057
1058OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
1059 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
1060 // existence of this pref is sufficient indicator. Given that we have to
1061 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001062 // |DeltaPerformer::ResetUpdateProgress| and
1063 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001064 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1065 auto system_rebooted = DidSystemReboot(prefs_);
1066 auto ota_successful = OTARebootSucceeded();
1067 if (ota_successful) {
1068 return OTAResult::OTA_SUCCESSFUL;
1069 }
1070 if (slot_switch_attempted) {
1071 if (system_rebooted) {
1072 // If we attempted slot switch, but still end up on the same slot, we
1073 // probably rolled back.
1074 return OTAResult::ROLLED_BACK;
1075 } else {
1076 return OTAResult::UPDATED_NEED_REBOOT;
1077 }
1078 }
1079 return OTAResult::NOT_ATTEMPTED;
1080}
1081
1082void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001083 // Example: [ro.build.version.incremental]: [4292972]
1084 string current_version =
1085 android::base::GetProperty("ro.build.version.incremental", "");
1086 TEST_AND_RETURN(!current_version.empty());
1087
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001088 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1089 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001090 string current_boot_id;
1091 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1092 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001093 std::string slot_switch_indicator;
1094 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1095 if (slot_switch_indicator != current_boot_id) {
1096 ClearUpdateCompletedMarker();
1097 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001098
Tianjie Xu90aaa102017-10-10 17:39:03 -07001099 // If there's no record of previous version (e.g. due to a data wipe), we
1100 // save the info of current boot and skip the metrics report.
1101 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001102 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001103 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001104 ClearMetricsPrefs();
1105 return;
1106 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001107 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001108 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001109 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1110 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001111 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001112 int64_t reboot_count =
1113 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1114 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1115 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001116
1117 if (result == OTAResult::ROLLED_BACK) {
1118 // This will release all space previously allocated for apex
1119 // decompression. If we detect a rollback, we should release space and
1120 // return the space to user. Any subsequent attempt to install OTA will
1121 // allocate space again anyway.
1122 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1123 "deompression.";
1124 apex_handler_android_->AllocateSpace({});
1125 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1126 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001127 return;
1128 }
1129
1130 // Now that the build version changes, report the update metrics.
1131 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001132 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001133 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001134
1135 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1136 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1137 if (previous_attempt_exists) {
1138 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1139 }
1140
1141 metrics_utils::LoadAndReportTimeToReboot(
1142 metrics_reporter_.get(), prefs_, clock_.get());
1143 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001144
1145 // Also reset the update progress if the build version has changed.
1146 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1147 LOG(WARNING) << "Unable to reset the update progress.";
1148 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001149}
1150
1151// Save the update start time. Reset the reboot count and attempt number if the
1152// update isn't a resume; otherwise increment the attempt number.
1153void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1154 if (!is_resume) {
1155 metrics_utils::SetNumReboots(0, prefs_);
1156 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1157 } else {
1158 int64_t attempt_number =
1159 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1160 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1161 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001162 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1163 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001164 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001165}
1166
1167void UpdateAttempterAndroid::ClearMetricsPrefs() {
1168 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001169 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001170 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001171 prefs_->Delete(kPrefsSystemUpdatedMarker);
1172 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001173 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001174}
1175
Yifan Hongbd47d622019-12-13 14:59:58 -08001176BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1177 return boot_control_->GetCurrentSlot();
1178}
1179
1180BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1181 return GetCurrentSlot() == 0 ? 1 : 0;
1182}
1183
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001184uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1185 const std::string& metadata_filename,
1186 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001187 Error* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001188 std::map<string, string> headers;
1189 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1190 return 0;
1191 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001192 DeltaArchiveManifest manifest;
1193 brillo::Blob metadata_hash;
1194 if (!brillo::data_encoding::Base64Decode(
1195 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1196 metadata_hash.clear();
1197 }
1198 if (!VerifyPayloadParseManifest(
1199 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1200 return 0;
1201 }
Yifan Hong65613032020-01-09 17:52:13 -08001202
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001203 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1204 manifest.apex_info().end());
1205 uint64_t apex_size_required = 0;
1206 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001207 auto result = apex_handler_android_->CalculateSize(apex_infos);
1208 if (!result.ok()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001209 LogAndSetGenericError(
1210 error,
1211 __LINE__,
1212 __FILE__,
1213 "Failed to calculate size required for compressed APEX");
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001214 return 0;
1215 }
1216 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001217 }
1218
Yifan Hong65613032020-01-09 17:52:13 -08001219 string payload_id = GetPayloadId(headers);
1220 uint64_t required_size = 0;
1221 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1222 boot_control_,
1223 GetTargetSlot(),
1224 manifest,
1225 payload_id,
1226 &required_size)) {
1227 if (required_size == 0) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001228 LogAndSetGenericError(
1229 error, __LINE__, __FILE__, "Failed to allocate space for payload.");
Yifan Hong65613032020-01-09 17:52:13 -08001230 return 0;
1231 } else {
1232 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001233 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001234 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001235 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001236 }
1237 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001238
1239 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001240 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001241 LOG(ERROR) << "Insufficient space for apex decompression: "
1242 << apex_size_required << " bytes";
1243 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001244 }
Yifan Hong65613032020-01-09 17:52:13 -08001245
1246 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001247 return 0;
1248}
1249
Yifan Hong40bb0d02020-02-24 17:33:14 -08001250void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1251 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001252 Error* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001253 if (cleanup_previous_update_code_.has_value()) {
1254 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1255 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1256 if (callback) {
1257 callback->OnCleanupComplete(
1258 static_cast<int32_t>(*cleanup_previous_update_code_));
1259 }
1260 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001261 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001262 if (callback) {
1263 auto callback_ptr = callback.get();
1264 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1265 callback_ptr->RegisterForDeathNotifications(
1266 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1267 base::Unretained(this),
1268 base::Unretained(callback_ptr)));
1269 }
1270 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001271}
1272
Tianjie7f8f2ab2021-07-23 17:08:50 -07001273bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
Daniel Zheng92f7d172023-06-22 14:31:37 -07001274 const std::string& metadata_filename, Error* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001275 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001276 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001277 return LogAndSetGenericError(
1278 error,
1279 __LINE__,
1280 __FILE__,
1281 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001282 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001283 DeltaArchiveManifest manifest;
1284 TEST_AND_RETURN_FALSE(
1285 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1286
Kelvin Zhang20982a52021-08-13 12:31:16 -07001287 InstallPlan install_plan_;
1288 install_plan_.source_slot = GetCurrentSlot();
1289 install_plan_.target_slot = GetTargetSlot();
1290 // Don't do verity computation, just hash the partitions
1291 install_plan_.write_verity = false;
1292 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1293 install_plan_.run_post_install = false;
1294 install_plan_.is_resume = true;
1295
1296 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1297 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1298
Kelvin Zhang20982a52021-08-13 12:31:16 -07001299 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001300 auto postinstall_runner_action =
1301 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1302 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001303 postinstall_runner_action->set_delegate(this);
1304
Kelvin Zhangf8441982022-12-07 18:18:47 -08001305 // If last error code is kUpdatedButNotActive, we know that we reached this
1306 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1307 // call would have already performed filesystem verification, therefore, we
1308 // can safely skip the verification to save time.
1309 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1310 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1311 processor_->EnqueueAction(std::move(install_plan_action));
1312 } else {
Kelvin Zhang263a5402022-12-08 23:03:32 -08001313 if (!boot_control_->GetDynamicPartitionControl()
1314 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1315 GetTargetSlot(),
1316 manifest,
1317 false /* should update */,
1318 nullptr)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001319 return LogAndSetGenericError(
1320 error, __LINE__, __FILE__, "Failed to PreparePartitionsForUpdate");
Kelvin Zhang263a5402022-12-08 23:03:32 -08001321 }
1322 ErrorCode error_code{};
1323 if (!install_plan_.ParsePartitions(manifest.partitions(),
1324 boot_control_,
1325 manifest.block_size(),
1326 &error_code)) {
1327 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001328 __LINE__,
1329 __FILE__,
Kelvin Zhang263a5402022-12-08 23:03:32 -08001330 "Failed to LoadPartitionsFromSlots " +
Daniel Zheng92f7d172023-06-22 14:31:37 -07001331 utils::ErrorCodeToString(error_code),
1332 error_code);
Kelvin Zhang263a5402022-12-08 23:03:32 -08001333 }
1334
Kelvin Zhangf8441982022-12-07 18:18:47 -08001335 auto filesystem_verifier_action =
1336 std::make_unique<FilesystemVerifierAction>(
1337 boot_control_->GetDynamicPartitionControl());
1338 filesystem_verifier_action->set_delegate(this);
1339 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1340 BondActions(filesystem_verifier_action.get(),
1341 postinstall_runner_action.get());
1342 processor_->EnqueueAction(std::move(install_plan_action));
1343 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1344 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001345
Kelvin Zhang20982a52021-08-13 12:31:16 -07001346 processor_->EnqueueAction(std::move(postinstall_runner_action));
1347 ScheduleProcessingStart();
1348 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001349}
1350
Daniel Zheng92f7d172023-06-22 14:31:37 -07001351bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(Error* error) {
Tianjie7f8f2ab2021-07-23 17:08:50 -07001352 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001353 return LogAndSetGenericError(
1354 error,
1355 __LINE__,
1356 __FILE__,
1357 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001358 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001359 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001360 // Update the boot flags so the current slot has higher priority.
1361 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001362 return LogAndSetGenericError(
1363 error, __LINE__, __FILE__, "Failed to SetActiveBootSlot");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001364 }
1365
1366 // Mark the current slot as successful again, since marking it as active
1367 // may reset the successful bit. We ignore the result of whether marking
1368 // the current slot as successful worked.
1369 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001370 return LogAndSetGenericError(
1371 error, __LINE__, __FILE__, "Failed to MarkBootSuccessfulAsync");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001372 }
1373
1374 // Resets the warm reset property since we won't switch the slot.
1375 hardware_->SetWarmReset(false);
1376
1377 // Resets the vbmeta digest.
1378 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1379 LOG(INFO) << "Slot switch cancelled.";
1380 SetStatusAndNotify(UpdateStatus::IDLE);
1381 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001382}
1383
Yifan Hong90965502020-02-19 15:22:47 -08001384void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1385 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1386 // is in progress, skip enqueueing the action.
1387 if (processor_->IsRunning()) {
1388 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1389 << "be done when the current update finishes.";
1390 return;
1391 }
1392 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1393 auto action =
1394 boot_control_->GetDynamicPartitionControl()
1395 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1396 processor_->EnqueueAction(std::move(action));
1397 processor_->set_delegate(this);
1398 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1399 processor_->StartProcessing();
1400}
1401
Yifan Hong40bb0d02020-02-24 17:33:14 -08001402void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1403 for (auto&& callback : cleanup_previous_update_callbacks_) {
1404 callback->OnCleanupProgressUpdate(progress);
1405 }
1406}
1407
1408void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1409 CHECK(cleanup_previous_update_code_.has_value());
1410 for (auto&& callback : cleanup_previous_update_callbacks_) {
1411 callback->OnCleanupComplete(
1412 static_cast<int32_t>(*cleanup_previous_update_code_));
1413 }
1414 cleanup_previous_update_callbacks_.clear();
1415}
1416
1417void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1418 CleanupSuccessfulUpdateCallbackInterface* callback) {
1419 auto end_it =
1420 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1421 cleanup_previous_update_callbacks_.end(),
1422 [&](const auto& e) { return e.get() == callback; });
1423 cleanup_previous_update_callbacks_.erase(
1424 end_it, cleanup_previous_update_callbacks_.end());
1425}
Yifan Hong90965502020-02-19 15:22:47 -08001426
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001427bool UpdateAttempterAndroid::IsProductionBuild() {
1428 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1429 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1430 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1431 return true;
1432 }
1433 return false;
1434}
1435
Alex Deymo5e3ea272016-01-28 13:42:23 -08001436} // namespace chromeos_update_engine