blob: 0f4b2e4bb6c0aab0433f8775012c0d42e4f0b49b [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
Kelvin Zhang13020502023-08-02 15:18:40 -0700151std::string GetCurrentBuildVersion() {
152 // Example: [ro.build.fingerprint]:
153 // [generic/aosp_cf_x86_64_phone/vsoc_x86_64:VanillaIceCream/AOSP.MAIN/user08011303:userdebug/test-keys]
154 return android::base::GetProperty("ro.build.fingerprint", "");
155}
156
Alex Deymo5e3ea272016-01-28 13:42:23 -0800157} // namespace
158
159UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700160 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800161 PrefsInterface* prefs,
162 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000163 HardwareInterface* hardware,
164 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800165 : daemon_state_(daemon_state),
166 prefs_(prefs),
167 boot_control_(boot_control),
168 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000169 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700170 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800171 clock_(new Clock()),
172 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
173 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800174 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400175 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700176 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800177}
178
179UpdateAttempterAndroid::~UpdateAttempterAndroid() {
180 // Release ourselves as the ActionProcessor's delegate to prevent
181 // re-scheduling the updates due to the processing stopped.
182 processor_->set_delegate(nullptr);
183}
184
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400185[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
186 string boot_id;
187 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
188 string old_boot_id;
189 // If no previous boot id found, treat as a reboot and write boot ID.
190 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
191 return true;
192 }
193 return old_boot_id != boot_id;
194}
195
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400196std::ostream& operator<<(std::ostream& out, OTAResult result) {
197 switch (result) {
198 case OTAResult::NOT_ATTEMPTED:
199 out << "OTAResult::NOT_ATTEMPTED";
200 break;
201 case OTAResult::ROLLED_BACK:
202 out << "OTAResult::ROLLED_BACK";
203 break;
204 case OTAResult::UPDATED_NEED_REBOOT:
205 out << "OTAResult::UPDATED_NEED_REBOOT";
206 break;
207 case OTAResult::OTA_SUCCESSFUL:
208 out << "OTAResult::OTA_SUCCESSFUL";
209 break;
210 }
211 return out;
212}
213
Alex Deymo5e3ea272016-01-28 13:42:23 -0800214void UpdateAttempterAndroid::Init() {
215 // In case of update_engine restart without a reboot we need to restore the
216 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700217 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400218 LOG(INFO) << "Updated installed but update_engine is restarted without "
219 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800220 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700221 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400222 const auto result = GetOTAUpdateResult();
223 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800224 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400225 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400226 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400227 }
228
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700229#ifdef _UE_SIDELOAD
230 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
231 << "ApplyPayload will call it later.";
232#else
Yifan Hong90965502020-02-19 15:22:47 -0800233 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700234#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700235 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800236}
237
238bool UpdateAttempterAndroid::ApplyPayload(
239 const string& payload_url,
240 int64_t payload_offset,
241 int64_t payload_size,
242 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700243 Error* error) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800244 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800245 return LogAndSetError(error,
246 __LINE__,
247 __FILE__,
248 "An update already applied, waiting for reboot",
249 ErrorCode::kUpdateAlreadyInstalled);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800250 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700251 if (processor_->IsRunning()) {
Kelvin Zhangbe0a3492023-12-04 09:18:15 -0800252 return LogAndSetError(error,
253 __LINE__,
254 __FILE__,
255 "Already processing an update, cancel it first.",
256 ErrorCode::kUpdateProcessing);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800257 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100258 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800259
Alex Deymo218397f2016-02-04 23:55:10 -0800260 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800261 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
262 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800263 }
264
Yifan Hongbd47d622019-12-13 14:59:58 -0800265 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800266
267 // Setup the InstallPlan based on the request.
268 install_plan_ = InstallPlan();
269
270 install_plan_.download_url = payload_url;
271 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800272 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800273 InstallPlan::Payload payload;
274 payload.size = payload_size;
275 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800276 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800277 &payload.size)) {
278 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800279 }
280 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700281 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800282 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700283 LOG(WARNING) << "Unable to decode base64 file hash: "
284 << headers[kPayloadPropertyFileHash];
285 }
Alex Deymo218397f2016-02-04 23:55:10 -0800286 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800287 &payload.metadata_size)) {
288 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800289 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700290 // The |payload.type| is not used anymore since minor_version 3.
291 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800292 install_plan_.payloads.push_back(payload);
293
Alex Deymo5e3ea272016-01-28 13:42:23 -0800294 // The |public_key_rsa| key would override the public key stored on disk.
295 install_plan_.public_key_rsa = "";
296
297 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
298 install_plan_.is_resume = !payload_id.empty() &&
299 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
300 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700301 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700302 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
303
Alex Deymo5e3ea272016-01-28 13:42:23 -0800304 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
305 LOG(WARNING) << "Unable to save the update check response hash.";
306 }
307 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800308 install_plan_.source_slot = GetCurrentSlot();
309 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700310
Alex Deymofb905d92016-06-03 19:26:58 -0700311 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700312 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
313
Kelvin Zhang85a6d992023-10-23 10:40:58 -0700314 install_plan_.spl_downgrade =
315 GetHeaderAsBool(headers[kPayloadPropertySplDowngrade], false);
316
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000317 if (!IsProductionBuild()) {
318 install_plan_.disable_vabc =
319 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
320 }
321
Sen Jiangfe522822017-10-31 15:14:11 -0700322 install_plan_.switch_slot_on_reboot =
323 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
324
Tianjie Xu087de9d2019-11-01 17:11:22 -0700325 install_plan_.run_post_install =
326 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800327
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700328 // Skip writing verity if we're resuming and verity has already been written.
329 install_plan_.write_verity = true;
330 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
331 bool verity_written = false;
332 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
333 verity_written) {
334 install_plan_.write_verity = false;
335 }
336 }
337
Alex Deymo87792ea2016-07-25 15:40:36 -0700338 NetworkId network_id = kDefaultNetworkId;
339 if (!headers[kPayloadPropertyNetworkId].empty()) {
340 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
341 &network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700342 return LogAndSetGenericError(
Alex Deymo87792ea2016-07-25 15:40:36 -0700343 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700344 __LINE__,
345 __FILE__,
Alex Deymo87792ea2016-07-25 15:40:36 -0700346 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
347 }
348 if (!network_selector_->SetProcessNetwork(network_id)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700349 return LogAndSetGenericError(
Sen Jiangcbd37c62017-09-12 15:04:35 -0700350 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700351 __LINE__,
352 __FILE__,
Sen Jiangcbd37c62017-09-12 15:04:35 -0700353 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700354 }
355 }
356
Alex Deymo5e3ea272016-01-28 13:42:23 -0800357 LOG(INFO) << "Using this install plan:";
358 install_plan_.Dump();
359
Amin Hassani667cf7b2018-07-25 14:32:00 -0700360 HttpFetcher* fetcher = nullptr;
361 if (FileFetcher::SupportedUrl(payload_url)) {
362 DLOG(INFO) << "Using FileFetcher for file URL.";
363 fetcher = new FileFetcher();
364 } else {
365#ifdef _UE_SIDELOAD
366 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800367 return false; // NOLINT, unreached but analyzer might not know.
368 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700369#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700370 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700371 if (!headers[kPayloadDownloadRetry].empty()) {
372 libcurl_fetcher->set_max_retry_count(
373 atoi(headers[kPayloadDownloadRetry].c_str()));
374 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700375 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
376 fetcher = libcurl_fetcher;
377#endif // _UE_SIDELOAD
378 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800379 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800380 if (!headers[kPayloadPropertyAuthorization].empty())
381 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
382 if (!headers[kPayloadPropertyUserAgent].empty())
383 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
384
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700385 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
386 LOG(INFO) << "Using proxy url from payload headers: "
387 << headers[kPayloadPropertyNetworkProxy];
388 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
389 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700390 if (!headers[kPayloadVABCNone].empty()) {
391 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000392 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800393 if (!headers[kPayloadEnableThreading].empty()) {
394 install_plan_.enable_threading = true;
395 }
396 if (!headers[kPayloadBatchedWrites].empty()) {
397 install_plan_.batched_writes = true;
398 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700399
Amin Hassani667cf7b2018-07-25 14:32:00 -0700400 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800401
Alex Deymo5e3ea272016-01-28 13:42:23 -0800402 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700403
404 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
405 // TODO(xunchang) report the metrics for unresumable updates
406
Amin Hassani667cf7b2018-07-25 14:32:00 -0700407 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800408 return true;
409}
410
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900411bool UpdateAttempterAndroid::ApplyPayload(
412 int fd,
413 int64_t payload_offset,
414 int64_t payload_size,
415 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700416 Error* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100417 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000418 // already running update will be terminated (existing file descriptor will be
419 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100420 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700421 return LogAndSetGenericError(
422 error,
423 __LINE__,
424 __FILE__,
425 "An update already applied, waiting for reboot");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100426 }
427 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700428 return LogAndSetGenericError(
429 error,
430 __LINE__,
431 __FILE__,
432 "Already processing an update, cancel it first.");
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100433 }
434 DCHECK_EQ(status_, UpdateStatus::IDLE);
435
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900436 payload_fd_.reset(dup(fd));
437 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
438
439 return ApplyPayload(
440 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
441}
442
Daniel Zheng92f7d172023-06-22 14:31:37 -0700443bool UpdateAttempterAndroid::SuspendUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700444 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700445 return LogAndSetGenericError(
446 error, __LINE__, __FILE__, "No ongoing update to suspend.");
Alex Deymof2858572016-02-25 11:20:13 -0800447 processor_->SuspendProcessing();
448 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800449}
450
Daniel Zheng92f7d172023-06-22 14:31:37 -0700451bool UpdateAttempterAndroid::ResumeUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700452 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700453 return LogAndSetGenericError(
454 error, __LINE__, __FILE__, "No ongoing update to resume.");
Alex Deymof2858572016-02-25 11:20:13 -0800455 processor_->ResumeProcessing();
456 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800457}
458
Daniel Zheng92f7d172023-06-22 14:31:37 -0700459bool UpdateAttempterAndroid::CancelUpdate(Error* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700460 if (!processor_->IsRunning())
Daniel Zheng92f7d172023-06-22 14:31:37 -0700461 return LogAndSetGenericError(
462 error, __LINE__, __FILE__, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800463 processor_->StopProcessing();
464 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800465}
466
Daniel Zheng92f7d172023-06-22 14:31:37 -0700467bool UpdateAttempterAndroid::ResetStatus(Error* error) {
Alex Deymo3b678db2016-02-09 11:50:06 -0800468 LOG(INFO) << "Attempting to reset state from "
469 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700470 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700471 return LogAndSetGenericError(
472 error,
473 __LINE__,
474 __FILE__,
475 "Already processing an update, cancel it first.");
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700476 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700477 if (status_ != UpdateStatus::IDLE &&
478 status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700479 return LogAndSetGenericError(
480 error,
481 __LINE__,
482 __FILE__,
483 "Status reset not allowed in this state, please "
484 "cancel on going OTA first.");
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700485 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800486
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000487 if (apex_handler_android_ != nullptr) {
488 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
489 std::vector<ApexInfo> apex_infos_blank;
490 apex_handler_android_->AllocateSpace(apex_infos_blank);
491 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400492 // Remove the reboot marker so that if the machine is rebooted
493 // after resetting to idle state, it doesn't go back to
494 // UpdateStatus::UPDATED_NEED_REBOOT state.
495 if (!ClearUpdateCompletedMarker()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700496 return LogAndSetGenericError(error,
497 __LINE__,
498 __FILE__,
499 "Failed to reset the status because "
500 "ClearUpdateCompletedMarker() failed");
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400501 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700502 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
503 if (!resetShouldSwitchSlotOnReboot(error)) {
504 LOG(INFO) << "Failed to reset slot switch.";
505 return false;
506 }
507 LOG(INFO) << "Slot switch reset successful";
508 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700509 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
510 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000511 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700512 }
Kelvin Zhangf92fe252023-03-28 10:55:47 -0700513 return true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800514}
515
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700516bool operator==(const std::vector<unsigned char>& a, std::string_view b) {
517 if (a.size() != b.size()) {
518 return false;
519 }
520 return memcmp(a.data(), b.data(), a.size()) == 0;
521}
522bool operator!=(const std::vector<unsigned char>& a, std::string_view b) {
523 return !(a == b);
524}
525
Yifan Hongbd47d622019-12-13 14:59:58 -0800526bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
527 const std::string& metadata_filename,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700528 std::string_view expected_metadata_hash,
Yifan Hongbd47d622019-12-13 14:59:58 -0800529 DeltaArchiveManifest* manifest,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700530 Error* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800531 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
532 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700533 return LogAndSetError(error,
534 __LINE__,
535 __FILE__,
536 "Failed to open " + metadata_filename,
537 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800538 }
539 brillo::Blob metadata(kMaxPayloadHeaderSize);
540 if (!fd->Read(metadata.data(), metadata.size())) {
541 return LogAndSetError(
542 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700543 __LINE__,
544 __FILE__,
545 "Failed to read payload header from " + metadata_filename,
546 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800547 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000548 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800549 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700550 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800551 MetadataParseResult::kSuccess) {
552 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700553 __LINE__,
554 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800555 "Failed to parse payload header: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700556 utils::ErrorCodeToString(errorcode),
557 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800558 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700559 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
560 payload_metadata.GetMetadataSignatureSize();
561 if (metadata_size < kMaxPayloadHeaderSize ||
562 metadata_size >
563 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800564 return LogAndSetError(
565 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700566 __LINE__,
567 __FILE__,
568 "Invalid metadata size: " + std::to_string(metadata_size),
569 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800570 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700571 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800572 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
573 metadata.size() - kMaxPayloadHeaderSize)) {
574 return LogAndSetError(
575 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700576 __LINE__,
577 __FILE__,
578 "Failed to read metadata and signature from " + metadata_filename,
579 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800580 }
581 fd->Close();
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700582 if (!expected_metadata_hash.empty()) {
583 brillo::Blob metadata_hash;
584 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfBytes(
585 metadata.data(), payload_metadata.GetMetadataSize(), &metadata_hash));
586 if (metadata_hash != expected_metadata_hash) {
587 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700588 __LINE__,
589 __FILE__,
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700590 "Metadata hash mismatch. Expected hash: " +
591 HexEncode(expected_metadata_hash) +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700592 " actual hash: " + HexEncode(metadata_hash),
593 ErrorCode::kDownloadManifestParseError);
Kelvin Zhangabb082f2023-04-27 20:46:06 -0700594 } else {
595 LOG(INFO) << "Payload metadata hash check passed : "
596 << HexEncode(metadata_hash);
597 }
598 }
Sen Jiang08c6da12019-01-07 18:28:56 -0800599
Tianjie Xu7a78d632019-10-08 16:32:39 -0700600 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
601 constants::kUpdateCertificatesPath);
602 if (!payload_verifier) {
603 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700604 __LINE__,
605 __FILE__,
Tianjie Xu7a78d632019-10-08 16:32:39 -0700606 "Failed to create the payload verifier from " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700607 std::string(constants::kUpdateCertificatesPath),
608 ErrorCode::kDownloadManifestParseError);
Sen Jiang08c6da12019-01-07 18:28:56 -0800609 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700610 errorcode = payload_metadata.ValidateMetadataSignature(
611 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800612 if (errorcode != ErrorCode::kSuccess) {
613 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700614 __LINE__,
615 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800616 "Failed to validate metadata signature: " +
Daniel Zheng92f7d172023-06-22 14:31:37 -0700617 utils::ErrorCodeToString(errorcode),
618 errorcode);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800619 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800620 if (!payload_metadata.GetManifest(metadata, manifest)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700621 return LogAndSetError(error,
622 __LINE__,
623 __FILE__,
624 "Failed to parse manifest.",
625 ErrorCode::kDownloadManifestParseError);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800626 }
627
Yifan Hongbd47d622019-12-13 14:59:58 -0800628 return true;
629}
630
631bool UpdateAttempterAndroid::VerifyPayloadApplicable(
Daniel Zheng92f7d172023-06-22 14:31:37 -0700632 const std::string& metadata_filename, Error* error) {
Yifan Hongbd47d622019-12-13 14:59:58 -0800633 DeltaArchiveManifest manifest;
634 TEST_AND_RETURN_FALSE(
635 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
636
637 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000638 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800639
640 BootControlInterface::Slot current_slot = GetCurrentSlot();
Kelvin Zhang1815c4d2023-11-07 14:21:18 -0800641 if (current_slot < 0) {
642 return LogAndSetError(
643 error,
644 __LINE__,
645 __FILE__,
646 "Failed to get current slot " + std::to_string(current_slot),
647 ErrorCode::kDownloadStateInitializationError);
648 }
Sen Jiang8371c1c2018-02-01 13:46:39 -0800649 for (const PartitionUpdate& partition : manifest.partitions()) {
650 if (!partition.has_old_partition_info())
651 continue;
652 string partition_path;
653 if (!boot_control_->GetPartitionDevice(
654 partition.partition_name(), current_slot, &partition_path)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700655 return LogAndSetGenericError(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800656 error,
Daniel Zheng92f7d172023-06-22 14:31:37 -0700657 __LINE__,
658 __FILE__,
Sen Jiang8371c1c2018-02-01 13:46:39 -0800659 "Failed to get partition device for " + partition.partition_name());
660 }
661 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700662 return LogAndSetGenericError(
663 error, __LINE__, __FILE__, "Failed to open " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800664 }
665 for (const InstallOperation& operation : partition.operations()) {
666 if (!operation.has_src_sha256_hash())
667 continue;
668 brillo::Blob source_hash;
669 if (!fd_utils::ReadAndHashExtents(fd,
670 operation.src_extents(),
671 manifest.block_size(),
672 &source_hash)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -0700673 return LogAndSetGenericError(
674 error, __LINE__, __FILE__, "Failed to hash " + partition_path);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800675 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400676 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800677 source_hash, operation, fd, &errorcode)) {
678 return false;
679 }
680 }
681 fd->Close();
682 }
683 return true;
684}
685
Alex Deymo5e3ea272016-01-28 13:42:23 -0800686void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
687 ErrorCode code) {
688 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800689 metric_bytes_downloaded_.Flush(true);
690 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800691 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800692 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
693 TerminateUpdateAndNotify(code);
694 return;
695 }
696
Alex Deymo5990bf32016-07-19 17:01:41 -0700697 switch (code) {
698 case ErrorCode::kSuccess:
699 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400700 if (!WriteUpdateCompletedMarker()) {
701 LOG(ERROR) << "Failed to write update completion marker";
702 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700703 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800704
Alex Deymo5990bf32016-07-19 17:01:41 -0700705 LOG(INFO) << "Update successfully applied, waiting to reboot.";
706 break;
707
708 case ErrorCode::kFilesystemCopierError:
709 case ErrorCode::kNewRootfsVerificationError:
710 case ErrorCode::kNewKernelVerificationError:
711 case ErrorCode::kFilesystemVerifierError:
712 case ErrorCode::kDownloadStateInitializationError:
713 // Reset the ongoing update for these errors so it starts from the
714 // beginning next time.
715 DeltaPerformer::ResetUpdateProgress(prefs_, false);
716 LOG(INFO) << "Resetting update progress.";
717 break;
718
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700719 case ErrorCode::kPayloadTimestampError:
720 // SafetyNet logging, b/36232423
721 android_errorWriteLog(0x534e4554, "36232423");
722 break;
723
Alex Deymo5990bf32016-07-19 17:01:41 -0700724 default:
725 // Ignore all other error codes.
726 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700727 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800728
729 TerminateUpdateAndNotify(code);
730}
731
732void UpdateAttempterAndroid::ProcessingStopped(
733 const ActionProcessor* processor) {
734 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
735}
736
737void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
738 AbstractAction* action,
739 ErrorCode code) {
740 // Reset download progress regardless of whether or not the download
741 // action succeeded.
742 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800743 if (type == CleanupPreviousUpdateAction::StaticType() ||
744 (type == NoOpAction::StaticType() &&
745 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
746 cleanup_previous_update_code_ = code;
747 NotifyCleanupPreviousUpdateCallbacksAndClear();
748 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000749 // download_progress_ is actually used by other actions, such as
750 // filesystem_verify_action. Therefore we always clear it.
751 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700752 if (type == PostinstallRunnerAction::StaticType()) {
753 bool succeeded =
754 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
755 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
756 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757 if (code != ErrorCode::kSuccess) {
758 // If an action failed, the ActionProcessor will cancel the whole thing.
759 return;
760 }
Yifan Hong83517502020-02-19 15:34:13 -0800761 if (type == UpdateBootFlagsAction::StaticType()) {
762 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
763 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800764 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400765 auto download_action = static_cast<DownloadAction*>(action);
766 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000767 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700768 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000769 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700770 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800771 }
772}
773
774void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
775 uint64_t bytes_received,
776 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700777 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800778 if (total)
779 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700780 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800781 download_progress_ = progress;
782 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700783 } else {
784 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800785 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700786
787 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800788 metric_bytes_downloaded_ += bytes_progressed;
789 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800790}
791
792bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
793 // TODO(deymo): Notify the DownloadAction that it should cancel the update
794 // download.
795 return false;
796}
797
798void UpdateAttempterAndroid::DownloadComplete() {
799 // Nothing needs to be done when the download completes.
800}
801
Alex Deymo0d298542016-03-30 18:31:49 -0700802void UpdateAttempterAndroid::ProgressUpdate(double progress) {
803 // Self throttle based on progress. Also send notifications if progress is
804 // too slow.
805 if (progress == 1.0 ||
806 progress - download_progress_ >= kBroadcastThresholdProgress ||
807 TimeTicks::Now() - last_notify_time_ >=
808 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
809 download_progress_ = progress;
810 SetStatusAndNotify(status_);
811 }
812}
813
Kelvin Zhang70eef232020-06-12 20:32:40 +0000814void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
815 assert(status_ == UpdateStatus::VERIFYING);
816 ProgressUpdate(progress);
817}
818
Alex Deymo5e3ea272016-01-28 13:42:23 -0800819void UpdateAttempterAndroid::ScheduleProcessingStart() {
820 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700821 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800822 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700823 FROM_HERE,
824 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
825 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800826}
827
828void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
829 if (status_ == UpdateStatus::IDLE) {
830 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
831 return;
832 }
833
Yifan Hong90965502020-02-19 15:22:47 -0800834 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400835 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800836 LOG(INFO) << "Terminating cleanup previous update.";
837 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700838 for (auto observer : daemon_state_->service_observers())
839 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800840 return;
841 }
842
Yifan Hong9194ce82019-11-07 11:03:42 -0800843 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700844
Alex Deymo0d298542016-03-30 18:31:49 -0700845 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800846 UpdateStatus new_status =
847 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
848 : UpdateStatus::IDLE);
849 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900850 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800851
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700852 // The network id is only applicable to one download attempt and once it's
853 // done the network id should not be re-used anymore.
854 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
855 LOG(WARNING) << "Unable to unbind network.";
856 }
857
Alex Deymo5e3ea272016-01-28 13:42:23 -0800858 for (auto observer : daemon_state_->service_observers())
859 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700860
Tianjie Xu90aaa102017-10-10 17:39:03 -0700861 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
862 ClearMetricsPrefs();
863 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800864 // We should only reset the PayloadAttemptNumber if the update succeeds, or
865 // we switch to a different payload.
866 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700867 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700868 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800869 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700870 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800871}
872
873void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
874 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700875 size_t payload_size =
876 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700877 UpdateEngineStatus status_to_send = {.status = status_,
878 .progress = download_progress_,
879 .new_size_bytes = payload_size};
880
Alex Deymo5e3ea272016-01-28 13:42:23 -0800881 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700882 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800883 }
884 last_notify_time_ = TimeTicks::Now();
885}
886
Amin Hassani667cf7b2018-07-25 14:32:00 -0700887void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800888 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800889
890 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700891 auto update_boot_flags_action =
892 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800893 auto cleanup_previous_update_action =
894 boot_control_->GetDynamicPartitionControl()
895 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700896 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
897 auto download_action =
898 std::make_unique<DownloadAction>(prefs_,
899 boot_control_,
900 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700901 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700902 true /* interactive */,
903 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800904 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700905 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700906 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
907 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700908 auto postinstall_runner_action =
909 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000910 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700911 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800912
Alex Deymo5e3ea272016-01-28 13:42:23 -0800913 // Bond them together. We have to use the leaf-types when calling
914 // BondActions().
915 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700916 BondActions(download_action.get(), filesystem_verifier_action.get());
917 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800918 postinstall_runner_action.get());
919
Amin Hassani667cf7b2018-07-25 14:32:00 -0700920 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800921 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700922 processor_->EnqueueAction(std::move(install_plan_action));
923 processor_->EnqueueAction(std::move(download_action));
924 processor_->EnqueueAction(std::move(filesystem_verifier_action));
925 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800926}
927
Alex Deymo5e3ea272016-01-28 13:42:23 -0800928bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
929 string boot_id;
930 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800931 LOG(INFO) << "Writing update complete marker, slot "
932 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400933 TEST_AND_RETURN_FALSE(
934 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
935 TEST_AND_RETURN_FALSE(
936 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
937 return true;
938}
939
940bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
941 LOG(INFO) << "Clearing update complete marker.";
942 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
943 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800944 return true;
945}
946
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800947bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800948 // In case of an update_engine restart without a reboot, we stored the boot_id
949 // when the update was completed by setting a pref, so we can check whether
950 // the last update was on this boot or a previous one.
951 string boot_id;
952 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
953
954 string update_completed_on_boot_id;
955 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
956 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
957 &update_completed_on_boot_id) &&
958 update_completed_on_boot_id == boot_id);
959}
960
Tianjie Xu90aaa102017-10-10 17:39:03 -0700961// Collect and report the android metrics when we terminate the update.
962void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
963 ErrorCode error_code) {
964 int64_t attempt_number =
965 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
966 PayloadType payload_type = kPayloadTypeFull;
967 int64_t payload_size = 0;
968 for (const auto& p : install_plan_.payloads) {
969 if (p.type == InstallPayloadType::kDelta)
970 payload_type = kPayloadTypeDelta;
971 payload_size += p.size;
972 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700973 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
974 // function will be triggered, but payload_size in this case might be 0, if so
975 // skip reporting any metrics.
976 if (payload_size == 0) {
977 return;
978 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700979
980 metrics::AttemptResult attempt_result =
981 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700982 Time boot_time_start = Time::FromInternalValue(
983 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
984 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700985 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700986 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
987 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700988
989 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700990 static_cast<int>(attempt_number),
991 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700992 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700993 duration_uptime,
994 payload_size,
995 attempt_result,
996 error_code);
997
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800998 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700999 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
1000 current_bytes_downloaded,
1001 0,
1002 DownloadSource::kNumDownloadSources,
1003 metrics::DownloadErrorCode::kUnset,
1004 metrics::ConnectionType::kUnset);
1005
Tianjie Xu90aaa102017-10-10 17:39:03 -07001006 if (error_code == ErrorCode::kSuccess) {
1007 int64_t reboot_count =
1008 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1009 string build_version;
1010 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -07001011
1012 // For android metrics, we only care about the total bytes downloaded
1013 // for all sources; for now we assume the only download source is
1014 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001015 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -07001016 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
1017 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
1018 total_bytes_downloaded;
1019
1020 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -07001021 if (total_bytes_downloaded >= payload_size) {
1022 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -07001023 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -07001024 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
1025 } else {
1026 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
1027 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -07001028 }
Tianjie Xu21030c12019-08-14 13:00:23 -07001029
Tianjie Xu90aaa102017-10-10 17:39:03 -07001030 metrics_reporter_->ReportSuccessfulUpdateMetrics(
1031 static_cast<int>(attempt_number),
1032 0, // update abandoned count
1033 payload_type,
1034 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -07001035 num_bytes_downloaded,
1036 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -07001037 duration,
Sen Jiang8712e962018-05-08 12:12:28 -07001038 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -07001039 static_cast<int>(reboot_count),
1040 0); // url_switch_count
1041 }
1042}
1043
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001044bool UpdateAttempterAndroid::OTARebootSucceeded() const {
1045 const auto current_slot = boot_control_->GetCurrentSlot();
Kelvin Zhang13020502023-08-02 15:18:40 -07001046 const string current_version = GetCurrentBuildVersion();
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001047 int64_t previous_slot = -1;
1048 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
1049 string previous_version;
1050 TEST_AND_RETURN_FALSE(
1051 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
1052 if (previous_slot != current_slot) {
1053 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001054 << previous_version << " to " << current_version
1055 << ", previous slot: " << previous_slot
1056 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001057 if (previous_version == current_version) {
1058 LOG(INFO) << "Previous version is the same as current version, this is "
1059 "possibly a self-OTA.";
1060 }
1061 return true;
1062 } else {
1063 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
1064 "switch never happened, or system not rebooted at all.";
1065 if (previous_version != current_version) {
1066 LOG(INFO) << "Slot didn't change, but version changed from "
1067 << previous_version << " to " << current_version
1068 << " device could be flashed.";
1069 }
1070 return false;
1071 }
1072}
1073
1074OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
1075 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
1076 // existence of this pref is sufficient indicator. Given that we have to
1077 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001078 // |DeltaPerformer::ResetUpdateProgress| and
1079 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001080 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
1081 auto system_rebooted = DidSystemReboot(prefs_);
1082 auto ota_successful = OTARebootSucceeded();
1083 if (ota_successful) {
1084 return OTAResult::OTA_SUCCESSFUL;
1085 }
1086 if (slot_switch_attempted) {
1087 if (system_rebooted) {
1088 // If we attempted slot switch, but still end up on the same slot, we
1089 // probably rolled back.
1090 return OTAResult::ROLLED_BACK;
1091 } else {
1092 return OTAResult::UPDATED_NEED_REBOOT;
1093 }
1094 }
1095 return OTAResult::NOT_ATTEMPTED;
1096}
1097
1098void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Kelvin Zhang13020502023-08-02 15:18:40 -07001099 const string current_version = GetCurrentBuildVersion();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001100 TEST_AND_RETURN(!current_version.empty());
1101
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001102 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1103 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001104 string current_boot_id;
1105 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1106 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001107 std::string slot_switch_indicator;
1108 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1109 if (slot_switch_indicator != current_boot_id) {
1110 ClearUpdateCompletedMarker();
1111 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001112
Tianjie Xu90aaa102017-10-10 17:39:03 -07001113 // If there's no record of previous version (e.g. due to a data wipe), we
1114 // save the info of current boot and skip the metrics report.
1115 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001116 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001117 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001118 ClearMetricsPrefs();
1119 return;
1120 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001121 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001122 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001123 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1124 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001125 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001126 int64_t reboot_count =
1127 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1128 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1129 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001130
1131 if (result == OTAResult::ROLLED_BACK) {
1132 // This will release all space previously allocated for apex
1133 // decompression. If we detect a rollback, we should release space and
1134 // return the space to user. Any subsequent attempt to install OTA will
1135 // allocate space again anyway.
1136 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1137 "deompression.";
1138 apex_handler_android_->AllocateSpace({});
1139 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1140 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001141 return;
1142 }
1143
1144 // Now that the build version changes, report the update metrics.
1145 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001146 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001147 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001148
1149 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1150 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1151 if (previous_attempt_exists) {
1152 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1153 }
1154
1155 metrics_utils::LoadAndReportTimeToReboot(
1156 metrics_reporter_.get(), prefs_, clock_.get());
1157 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001158
1159 // Also reset the update progress if the build version has changed.
1160 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1161 LOG(WARNING) << "Unable to reset the update progress.";
1162 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001163}
1164
1165// Save the update start time. Reset the reboot count and attempt number if the
1166// update isn't a resume; otherwise increment the attempt number.
1167void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1168 if (!is_resume) {
1169 metrics_utils::SetNumReboots(0, prefs_);
1170 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1171 } else {
1172 int64_t attempt_number =
1173 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1174 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1175 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001176 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1177 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001178 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001179}
1180
1181void UpdateAttempterAndroid::ClearMetricsPrefs() {
1182 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001183 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001184 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001185 prefs_->Delete(kPrefsSystemUpdatedMarker);
1186 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001187 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001188}
1189
Yifan Hongbd47d622019-12-13 14:59:58 -08001190BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1191 return boot_control_->GetCurrentSlot();
1192}
1193
1194BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1195 return GetCurrentSlot() == 0 ? 1 : 0;
1196}
1197
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001198uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1199 const std::string& metadata_filename,
1200 const vector<string>& key_value_pair_headers,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001201 Error* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001202 std::map<string, string> headers;
1203 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1204 return 0;
1205 }
Kelvin Zhangabb082f2023-04-27 20:46:06 -07001206 DeltaArchiveManifest manifest;
1207 brillo::Blob metadata_hash;
1208 if (!brillo::data_encoding::Base64Decode(
1209 headers[kPayloadPropertyMetadataHash], &metadata_hash)) {
1210 metadata_hash.clear();
1211 }
1212 if (!VerifyPayloadParseManifest(
1213 metadata_filename, ToStringView(metadata_hash), &manifest, error)) {
1214 return 0;
1215 }
Yifan Hong65613032020-01-09 17:52:13 -08001216
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001217 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1218 manifest.apex_info().end());
1219 uint64_t apex_size_required = 0;
1220 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001221 auto result = apex_handler_android_->CalculateSize(apex_infos);
1222 if (!result.ok()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001223 LogAndSetGenericError(
1224 error,
1225 __LINE__,
1226 __FILE__,
1227 "Failed to calculate size required for compressed APEX");
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001228 return 0;
1229 }
1230 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001231 }
1232
Yifan Hong65613032020-01-09 17:52:13 -08001233 string payload_id = GetPayloadId(headers);
1234 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -07001235 ErrorCode error_code{};
1236
Yifan Hong65613032020-01-09 17:52:13 -08001237 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1238 boot_control_,
1239 GetTargetSlot(),
1240 manifest,
1241 payload_id,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001242 &required_size,
1243 &error_code)) {
1244 if (error_code == ErrorCode::kOverlayfsenabledError) {
1245 LogAndSetError(error,
1246 __LINE__,
1247 __FILE__,
1248 "OverlayFS Shouldn't be enabled for OTA.",
1249 error_code);
1250 return 0;
1251 }
Yifan Hong65613032020-01-09 17:52:13 -08001252 if (required_size == 0) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001253 LogAndSetGenericError(
1254 error, __LINE__, __FILE__, "Failed to allocate space for payload.");
Yifan Hong65613032020-01-09 17:52:13 -08001255 return 0;
1256 } else {
1257 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001258 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001259 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001260 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001261 }
1262 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001263
1264 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001265 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001266 LOG(ERROR) << "Insufficient space for apex decompression: "
1267 << apex_size_required << " bytes";
1268 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001269 }
Yifan Hong65613032020-01-09 17:52:13 -08001270
1271 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001272 return 0;
1273}
1274
Yifan Hong40bb0d02020-02-24 17:33:14 -08001275void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1276 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001277 Error* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001278 if (cleanup_previous_update_code_.has_value()) {
1279 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1280 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1281 if (callback) {
1282 callback->OnCleanupComplete(
1283 static_cast<int32_t>(*cleanup_previous_update_code_));
1284 }
1285 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001286 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001287 if (callback) {
1288 auto callback_ptr = callback.get();
1289 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
Kelvin Zhang2f6c25a2023-07-05 12:49:34 -07001290 callback_ptr->RegisterForDeathNotifications([this, callback_ptr]() {
1291 RemoveCleanupPreviousUpdateCallback(callback_ptr);
1292 });
Yifan Hong40bb0d02020-02-24 17:33:14 -08001293 }
1294 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001295}
1296
Tianjie7f8f2ab2021-07-23 17:08:50 -07001297bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
Daniel Zheng92f7d172023-06-22 14:31:37 -07001298 const std::string& metadata_filename, Error* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001299 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001300 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001301 return LogAndSetGenericError(
1302 error,
1303 __LINE__,
1304 __FILE__,
1305 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001306 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001307 DeltaArchiveManifest manifest;
1308 TEST_AND_RETURN_FALSE(
1309 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1310
Kelvin Zhang20982a52021-08-13 12:31:16 -07001311 InstallPlan install_plan_;
1312 install_plan_.source_slot = GetCurrentSlot();
1313 install_plan_.target_slot = GetTargetSlot();
1314 // Don't do verity computation, just hash the partitions
1315 install_plan_.write_verity = false;
1316 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1317 install_plan_.run_post_install = false;
1318 install_plan_.is_resume = true;
1319
1320 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1321 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1322
Kelvin Zhang20982a52021-08-13 12:31:16 -07001323 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001324 auto postinstall_runner_action =
1325 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1326 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001327 postinstall_runner_action->set_delegate(this);
Daniel Zhengeede4c82023-06-13 11:21:06 -07001328 ErrorCode error_code{};
Kelvin Zhang20982a52021-08-13 12:31:16 -07001329
Kelvin Zhangf8441982022-12-07 18:18:47 -08001330 // If last error code is kUpdatedButNotActive, we know that we reached this
1331 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1332 // call would have already performed filesystem verification, therefore, we
1333 // can safely skip the verification to save time.
1334 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1335 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1336 processor_->EnqueueAction(std::move(install_plan_action));
1337 } else {
Kelvin Zhang263a5402022-12-08 23:03:32 -08001338 if (!boot_control_->GetDynamicPartitionControl()
1339 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1340 GetTargetSlot(),
1341 manifest,
1342 false /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -07001343 nullptr,
1344 &error_code)) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001345 return LogAndSetGenericError(
1346 error, __LINE__, __FILE__, "Failed to PreparePartitionsForUpdate");
Kelvin Zhang263a5402022-12-08 23:03:32 -08001347 }
Kelvin Zhang263a5402022-12-08 23:03:32 -08001348 if (!install_plan_.ParsePartitions(manifest.partitions(),
1349 boot_control_,
1350 manifest.block_size(),
1351 &error_code)) {
1352 return LogAndSetError(error,
Daniel Zheng92f7d172023-06-22 14:31:37 -07001353 __LINE__,
1354 __FILE__,
Kelvin Zhang263a5402022-12-08 23:03:32 -08001355 "Failed to LoadPartitionsFromSlots " +
Daniel Zheng92f7d172023-06-22 14:31:37 -07001356 utils::ErrorCodeToString(error_code),
1357 error_code);
Kelvin Zhang263a5402022-12-08 23:03:32 -08001358 }
1359
Kelvin Zhangf8441982022-12-07 18:18:47 -08001360 auto filesystem_verifier_action =
1361 std::make_unique<FilesystemVerifierAction>(
1362 boot_control_->GetDynamicPartitionControl());
1363 filesystem_verifier_action->set_delegate(this);
1364 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1365 BondActions(filesystem_verifier_action.get(),
1366 postinstall_runner_action.get());
1367 processor_->EnqueueAction(std::move(install_plan_action));
1368 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1369 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001370
Kelvin Zhang20982a52021-08-13 12:31:16 -07001371 processor_->EnqueueAction(std::move(postinstall_runner_action));
1372 ScheduleProcessingStart();
1373 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001374}
1375
Daniel Zheng92f7d172023-06-22 14:31:37 -07001376bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(Error* error) {
Tianjie7f8f2ab2021-07-23 17:08:50 -07001377 if (processor_->IsRunning()) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001378 return LogAndSetGenericError(
1379 error,
1380 __LINE__,
1381 __FILE__,
1382 "Already processing an update, cancel it first.");
Tianjie7f8f2ab2021-07-23 17:08:50 -07001383 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001384 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001385 // Update the boot flags so the current slot has higher priority.
1386 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001387 return LogAndSetGenericError(
1388 error, __LINE__, __FILE__, "Failed to SetActiveBootSlot");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001389 }
1390
1391 // Mark the current slot as successful again, since marking it as active
1392 // may reset the successful bit. We ignore the result of whether marking
1393 // the current slot as successful worked.
1394 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
Daniel Zheng92f7d172023-06-22 14:31:37 -07001395 return LogAndSetGenericError(
1396 error, __LINE__, __FILE__, "Failed to MarkBootSuccessfulAsync");
Kelvin Zhang20982a52021-08-13 12:31:16 -07001397 }
1398
1399 // Resets the warm reset property since we won't switch the slot.
1400 hardware_->SetWarmReset(false);
1401
1402 // Resets the vbmeta digest.
1403 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1404 LOG(INFO) << "Slot switch cancelled.";
1405 SetStatusAndNotify(UpdateStatus::IDLE);
1406 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001407}
1408
Yifan Hong90965502020-02-19 15:22:47 -08001409void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1410 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1411 // is in progress, skip enqueueing the action.
1412 if (processor_->IsRunning()) {
1413 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1414 << "be done when the current update finishes.";
1415 return;
1416 }
1417 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1418 auto action =
1419 boot_control_->GetDynamicPartitionControl()
1420 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1421 processor_->EnqueueAction(std::move(action));
1422 processor_->set_delegate(this);
1423 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1424 processor_->StartProcessing();
1425}
1426
Yifan Hong40bb0d02020-02-24 17:33:14 -08001427void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1428 for (auto&& callback : cleanup_previous_update_callbacks_) {
1429 callback->OnCleanupProgressUpdate(progress);
1430 }
1431}
1432
1433void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1434 CHECK(cleanup_previous_update_code_.has_value());
1435 for (auto&& callback : cleanup_previous_update_callbacks_) {
1436 callback->OnCleanupComplete(
1437 static_cast<int32_t>(*cleanup_previous_update_code_));
1438 }
1439 cleanup_previous_update_callbacks_.clear();
1440}
1441
1442void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1443 CleanupSuccessfulUpdateCallbackInterface* callback) {
1444 auto end_it =
1445 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1446 cleanup_previous_update_callbacks_.end(),
1447 [&](const auto& e) { return e.get() == callback; });
1448 cleanup_previous_update_callbacks_.erase(
1449 end_it, cleanup_previous_update_callbacks_.end());
1450}
Yifan Hong90965502020-02-19 15:22:47 -08001451
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001452bool UpdateAttempterAndroid::IsProductionBuild() {
1453 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1454 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1455 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1456 return true;
1457 }
1458 return false;
1459}
1460
Alex Deymo5e3ea272016-01-28 13:42:23 -08001461} // namespace chromeos_update_engine