blob: 97c53ec9278f665468585168a36713c0b5d634b0 [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
17#include "update_engine/update_attempter_android.h"
18
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070021#include <memory>
Alex Deymo5e3ea272016-01-28 13:42:23 -080022#include <utility>
23
Tianjie Xu90aaa102017-10-10 17:39:03 -070024#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090025#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080026#include <base/bind.h>
27#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080028#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070029#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080030#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080031#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070032#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080033
34#include "update_engine/common/constants.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080035#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070036#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080037#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070038#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070039#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070040#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070041#include "update_engine/network_selector.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080043#include "update_engine/payload_consumer/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080044#include "update_engine/payload_consumer/file_descriptor.h"
45#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/payload_constants.h"
48#include "update_engine/payload_consumer/payload_metadata.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080049#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070050#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080051#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052
Alex Deymo14c0da82016-07-20 16:45:45 -070053#ifndef _UE_SIDELOAD
54// Do not include support for external HTTP(s) urls when building
55// update_engine_sideload.
56#include "update_engine/libcurl_http_fetcher.h"
57#endif
58
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090059using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080060using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070061using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080062using base::TimeDelta;
63using base::TimeTicks;
64using std::shared_ptr;
65using std::string;
66using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070067using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068
69namespace chromeos_update_engine {
70
71namespace {
72
Alex Deymo0d298542016-03-30 18:31:49 -070073// Minimum threshold to broadcast an status update in progress and time.
74const double kBroadcastThresholdProgress = 0.01; // 1%
75const int kBroadcastThresholdSeconds = 10;
76
Alex Deymo5e3ea272016-01-28 13:42:23 -080077const char* const kErrorDomain = "update_engine";
78// TODO(deymo): Convert the different errors to a numeric value to report them
79// back on the service error.
80const char* const kGenericError = "generic_error";
81
82// Log and set the error on the passed ErrorPtr.
83bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070084 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080085 const string& reason) {
86 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
87 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
88 << reason;
89 return false;
90}
91
Sen Jiangfe522822017-10-31 15:14:11 -070092bool GetHeaderAsBool(const string& header, bool default_value) {
93 int value = 0;
94 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
95 return value == 1;
96 return default_value;
97}
98
Alex Deymo5e3ea272016-01-28 13:42:23 -080099} // namespace
100
101UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700102 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800103 PrefsInterface* prefs,
104 BootControlInterface* boot_control,
105 HardwareInterface* hardware)
106 : daemon_state_(daemon_state),
107 prefs_(prefs),
108 boot_control_(boot_control),
109 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700110 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700111 clock_(new Clock()) {
112 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700113 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800114}
115
116UpdateAttempterAndroid::~UpdateAttempterAndroid() {
117 // Release ourselves as the ActionProcessor's delegate to prevent
118 // re-scheduling the updates due to the processing stopped.
119 processor_->set_delegate(nullptr);
120}
121
122void UpdateAttempterAndroid::Init() {
123 // In case of update_engine restart without a reboot we need to restore the
124 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700125 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800126 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700127 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800128 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700129 UpdatePrefsAndReportUpdateMetricsOnReboot();
130 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800131}
132
133bool UpdateAttempterAndroid::ApplyPayload(
134 const string& payload_url,
135 int64_t payload_offset,
136 int64_t payload_size,
137 const vector<string>& key_value_pair_headers,
138 brillo::ErrorPtr* error) {
139 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
140 return LogAndSetError(
141 error, FROM_HERE, "An update already applied, waiting for reboot");
142 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700143 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800144 return LogAndSetError(
145 error, FROM_HERE, "Already processing an update, cancel it first.");
146 }
147 DCHECK(status_ == UpdateStatus::IDLE);
148
Alex Deymo218397f2016-02-04 23:55:10 -0800149 std::map<string, string> headers;
150 for (const string& key_value_pair : key_value_pair_headers) {
151 string key;
152 string value;
153 if (!brillo::string_utils::SplitAtFirst(
154 key_value_pair, "=", &key, &value, false)) {
155 return LogAndSetError(
156 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
157 }
158 if (!headers.emplace(key, value).second)
159 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
160 }
161
162 // Unique identifier for the payload. An empty string means that the payload
163 // can't be resumed.
164 string payload_id = (headers[kPayloadPropertyFileHash] +
165 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800166
167 // Setup the InstallPlan based on the request.
168 install_plan_ = InstallPlan();
169
170 install_plan_.download_url = payload_url;
171 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800172 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800173 InstallPlan::Payload payload;
174 payload.size = payload_size;
175 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800176 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800177 &payload.size)) {
178 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800179 }
180 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700181 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800182 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700183 LOG(WARNING) << "Unable to decode base64 file hash: "
184 << headers[kPayloadPropertyFileHash];
185 }
Alex Deymo218397f2016-02-04 23:55:10 -0800186 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800187 &payload.metadata_size)) {
188 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800189 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700190 // The |payload.type| is not used anymore since minor_version 3.
191 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800192 install_plan_.payloads.push_back(payload);
193
Alex Deymo5e3ea272016-01-28 13:42:23 -0800194 // The |public_key_rsa| key would override the public key stored on disk.
195 install_plan_.public_key_rsa = "";
196
197 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
198 install_plan_.is_resume = !payload_id.empty() &&
199 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
200 if (!install_plan_.is_resume) {
201 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
202 LOG(WARNING) << "Unable to reset the update progress.";
203 }
204 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
205 LOG(WARNING) << "Unable to save the update check response hash.";
206 }
207 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800208 install_plan_.source_slot = boot_control_->GetCurrentSlot();
209 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700210
Alex Deymofb905d92016-06-03 19:26:58 -0700211 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700212 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
213
214 install_plan_.switch_slot_on_reboot =
215 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
216
217 install_plan_.run_post_install = true;
218 // Optionally skip post install if and only if:
219 // a) we're resuming
220 // b) post install has already succeeded before
221 // c) RUN_POST_INSTALL is set to 0.
222 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
223 bool post_install_succeeded = false;
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700224 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded,
225 &post_install_succeeded) &&
226 post_install_succeeded) {
Sen Jiangfe522822017-10-31 15:14:11 -0700227 install_plan_.run_post_install =
228 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
229 }
230 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800231
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700232 // Skip writing verity if we're resuming and verity has already been written.
233 install_plan_.write_verity = true;
234 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
235 bool verity_written = false;
236 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
237 verity_written) {
238 install_plan_.write_verity = false;
239 }
240 }
241
Alex Deymo87792ea2016-07-25 15:40:36 -0700242 NetworkId network_id = kDefaultNetworkId;
243 if (!headers[kPayloadPropertyNetworkId].empty()) {
244 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
245 &network_id)) {
246 return LogAndSetError(
247 error,
248 FROM_HERE,
249 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
250 }
251 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700252 return LogAndSetError(
253 error,
254 FROM_HERE,
255 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700256 }
257 }
258
Alex Deymo5e3ea272016-01-28 13:42:23 -0800259 LOG(INFO) << "Using this install plan:";
260 install_plan_.Dump();
261
Amin Hassani667cf7b2018-07-25 14:32:00 -0700262 HttpFetcher* fetcher = nullptr;
263 if (FileFetcher::SupportedUrl(payload_url)) {
264 DLOG(INFO) << "Using FileFetcher for file URL.";
265 fetcher = new FileFetcher();
266 } else {
267#ifdef _UE_SIDELOAD
268 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
269#else
270 LibcurlHttpFetcher* libcurl_fetcher =
271 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
272 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
273 fetcher = libcurl_fetcher;
274#endif // _UE_SIDELOAD
275 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800276 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800277 if (!headers[kPayloadPropertyAuthorization].empty())
278 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
279 if (!headers[kPayloadPropertyUserAgent].empty())
280 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
281
Amin Hassani667cf7b2018-07-25 14:32:00 -0700282 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800283
Alex Deymo5e3ea272016-01-28 13:42:23 -0800284 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700285
286 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
287 // TODO(xunchang) report the metrics for unresumable updates
288
Amin Hassani667cf7b2018-07-25 14:32:00 -0700289 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800290 return true;
291}
292
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900293bool UpdateAttempterAndroid::ApplyPayload(
294 int fd,
295 int64_t payload_offset,
296 int64_t payload_size,
297 const vector<string>& key_value_pair_headers,
298 brillo::ErrorPtr* error) {
299 payload_fd_.reset(dup(fd));
300 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
301
302 return ApplyPayload(
303 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
304}
305
Alex Deymo5e3ea272016-01-28 13:42:23 -0800306bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700307 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800308 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
309 processor_->SuspendProcessing();
310 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800311}
312
313bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700314 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800315 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
316 processor_->ResumeProcessing();
317 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800318}
319
320bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700321 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800322 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800323 processor_->StopProcessing();
324 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800325}
326
Alex Deymo3b678db2016-02-09 11:50:06 -0800327bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
328 LOG(INFO) << "Attempting to reset state from "
329 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
330
331 switch (status_) {
332 case UpdateStatus::IDLE:
333 return true;
334
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800335 case UpdateStatus::UPDATED_NEED_REBOOT: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800336 // Remove the reboot marker so that if the machine is rebooted
337 // after resetting to idle state, it doesn't go back to
338 // UpdateStatus::UPDATED_NEED_REBOOT state.
339 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700340 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800341
342 // Update the boot flags so the current slot has higher priority.
343 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
344 ret_value = false;
345
Alex Deymo52590332016-11-29 18:29:13 -0800346 // Mark the current slot as successful again, since marking it as active
347 // may reset the successful bit. We ignore the result of whether marking
348 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800349 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800350 ret_value = false;
351
Alex Deymo3b678db2016-02-09 11:50:06 -0800352 if (!ret_value) {
353 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800354 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800355 }
356
357 SetStatusAndNotify(UpdateStatus::IDLE);
358 LOG(INFO) << "Reset status successful";
359 return true;
360 }
361
362 default:
363 return LogAndSetError(
364 error,
365 FROM_HERE,
366 "Reset not allowed in this state. Cancel the ongoing update first");
367 }
368}
369
Sen Jiang8371c1c2018-02-01 13:46:39 -0800370bool UpdateAttempterAndroid::VerifyPayloadApplicable(
371 const std::string& metadata_filename, brillo::ErrorPtr* error) {
372 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
373 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
374 return LogAndSetError(
375 error, FROM_HERE, "Failed to open " + metadata_filename);
376 }
377 brillo::Blob metadata(kMaxPayloadHeaderSize);
378 if (!fd->Read(metadata.data(), metadata.size())) {
379 return LogAndSetError(
380 error,
381 FROM_HERE,
382 "Failed to read payload header from " + metadata_filename);
383 }
384 ErrorCode errorcode;
385 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700386 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800387 MetadataParseResult::kSuccess) {
388 return LogAndSetError(error,
389 FROM_HERE,
390 "Failed to parse payload header: " +
391 utils::ErrorCodeToString(errorcode));
392 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700393 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
394 payload_metadata.GetMetadataSignatureSize();
395 if (metadata_size < kMaxPayloadHeaderSize ||
396 metadata_size >
397 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800398 return LogAndSetError(
399 error,
400 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700401 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800402 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700403 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800404 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
405 metadata.size() - kMaxPayloadHeaderSize)) {
406 return LogAndSetError(
407 error,
408 FROM_HERE,
409 "Failed to read metadata and signature from " + metadata_filename);
410 }
411 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800412
413 string public_key;
414 if (!utils::ReadFile(constants::kUpdatePayloadPublicKeyPath, &public_key)) {
415 return LogAndSetError(error, FROM_HERE, "Failed to read public key.");
416 }
417 errorcode =
418 payload_metadata.ValidateMetadataSignature(metadata, "", public_key);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800419 if (errorcode != ErrorCode::kSuccess) {
420 return LogAndSetError(error,
421 FROM_HERE,
422 "Failed to validate metadata signature: " +
423 utils::ErrorCodeToString(errorcode));
424 }
425 DeltaArchiveManifest manifest;
426 if (!payload_metadata.GetManifest(metadata, &manifest)) {
427 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
428 }
429
430 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
431 for (const PartitionUpdate& partition : manifest.partitions()) {
432 if (!partition.has_old_partition_info())
433 continue;
434 string partition_path;
435 if (!boot_control_->GetPartitionDevice(
436 partition.partition_name(), current_slot, &partition_path)) {
437 return LogAndSetError(
438 error,
439 FROM_HERE,
440 "Failed to get partition device for " + partition.partition_name());
441 }
442 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
443 return LogAndSetError(
444 error, FROM_HERE, "Failed to open " + partition_path);
445 }
446 for (const InstallOperation& operation : partition.operations()) {
447 if (!operation.has_src_sha256_hash())
448 continue;
449 brillo::Blob source_hash;
450 if (!fd_utils::ReadAndHashExtents(fd,
451 operation.src_extents(),
452 manifest.block_size(),
453 &source_hash)) {
454 return LogAndSetError(
455 error, FROM_HERE, "Failed to hash " + partition_path);
456 }
457 if (!DeltaPerformer::ValidateSourceHash(
458 source_hash, operation, fd, &errorcode)) {
459 return false;
460 }
461 }
462 fd->Close();
463 }
464 return true;
465}
466
Alex Deymo5e3ea272016-01-28 13:42:23 -0800467void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
468 ErrorCode code) {
469 LOG(INFO) << "Processing Done.";
470
Alex Deymo5990bf32016-07-19 17:01:41 -0700471 switch (code) {
472 case ErrorCode::kSuccess:
473 // Update succeeded.
474 WriteUpdateCompletedMarker();
475 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800476
Alex Deymo5990bf32016-07-19 17:01:41 -0700477 LOG(INFO) << "Update successfully applied, waiting to reboot.";
478 break;
479
480 case ErrorCode::kFilesystemCopierError:
481 case ErrorCode::kNewRootfsVerificationError:
482 case ErrorCode::kNewKernelVerificationError:
483 case ErrorCode::kFilesystemVerifierError:
484 case ErrorCode::kDownloadStateInitializationError:
485 // Reset the ongoing update for these errors so it starts from the
486 // beginning next time.
487 DeltaPerformer::ResetUpdateProgress(prefs_, false);
488 LOG(INFO) << "Resetting update progress.";
489 break;
490
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700491 case ErrorCode::kPayloadTimestampError:
492 // SafetyNet logging, b/36232423
493 android_errorWriteLog(0x534e4554, "36232423");
494 break;
495
Alex Deymo5990bf32016-07-19 17:01:41 -0700496 default:
497 // Ignore all other error codes.
498 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700499 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800500
501 TerminateUpdateAndNotify(code);
502}
503
504void UpdateAttempterAndroid::ProcessingStopped(
505 const ActionProcessor* processor) {
506 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
507}
508
509void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
510 AbstractAction* action,
511 ErrorCode code) {
512 // Reset download progress regardless of whether or not the download
513 // action succeeded.
514 const string type = action->Type();
515 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700516 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800517 }
Sen Jiangfe522822017-10-31 15:14:11 -0700518 if (type == PostinstallRunnerAction::StaticType()) {
519 bool succeeded =
520 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
521 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
522 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800523 if (code != ErrorCode::kSuccess) {
524 // If an action failed, the ActionProcessor will cancel the whole thing.
525 return;
526 }
527 if (type == DownloadAction::StaticType()) {
528 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700529 } else if (type == FilesystemVerifierAction::StaticType()) {
530 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800531 }
532}
533
534void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
535 uint64_t bytes_received,
536 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700537 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800538 if (total)
539 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700540 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800541 download_progress_ = progress;
542 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700543 } else {
544 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800545 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700546
547 // Update the bytes downloaded in prefs.
548 int64_t current_bytes_downloaded =
549 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
550 int64_t total_bytes_downloaded =
551 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
552 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
553 current_bytes_downloaded + bytes_progressed);
554 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
555 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800556}
557
558bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
559 // TODO(deymo): Notify the DownloadAction that it should cancel the update
560 // download.
561 return false;
562}
563
564void UpdateAttempterAndroid::DownloadComplete() {
565 // Nothing needs to be done when the download completes.
566}
567
Alex Deymo0d298542016-03-30 18:31:49 -0700568void UpdateAttempterAndroid::ProgressUpdate(double progress) {
569 // Self throttle based on progress. Also send notifications if progress is
570 // too slow.
571 if (progress == 1.0 ||
572 progress - download_progress_ >= kBroadcastThresholdProgress ||
573 TimeTicks::Now() - last_notify_time_ >=
574 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
575 download_progress_ = progress;
576 SetStatusAndNotify(status_);
577 }
578}
579
Alex Deymo5e3ea272016-01-28 13:42:23 -0800580void UpdateAttempterAndroid::ScheduleProcessingStart() {
581 LOG(INFO) << "Scheduling an action processor start.";
582 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700583 FROM_HERE,
584 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
585 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800586}
587
588void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
589 if (status_ == UpdateStatus::IDLE) {
590 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
591 return;
592 }
593
Yifan Hong537802d2018-08-15 13:15:42 -0700594 boot_control_->Cleanup();
595
Alex Deymo0d298542016-03-30 18:31:49 -0700596 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800597 UpdateStatus new_status =
598 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
599 : UpdateStatus::IDLE);
600 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900601 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800602
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700603 // The network id is only applicable to one download attempt and once it's
604 // done the network id should not be re-used anymore.
605 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
606 LOG(WARNING) << "Unable to unbind network.";
607 }
608
Alex Deymo5e3ea272016-01-28 13:42:23 -0800609 for (auto observer : daemon_state_->service_observers())
610 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700611
Tianjie Xu90aaa102017-10-10 17:39:03 -0700612 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
613 ClearMetricsPrefs();
614 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800615 // We should only reset the PayloadAttemptNumber if the update succeeds, or
616 // we switch to a different payload.
617 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700618 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700619 // Clear the total bytes downloaded if and only if the update succeeds.
620 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700621 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800622}
623
624void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
625 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700626 size_t payload_size =
627 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700628 UpdateEngineStatus status_to_send = {.status = status_,
629 .progress = download_progress_,
630 .new_size_bytes = payload_size};
631
Alex Deymo5e3ea272016-01-28 13:42:23 -0800632 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700633 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800634 }
635 last_notify_time_ = TimeTicks::Now();
636}
637
Amin Hassani667cf7b2018-07-25 14:32:00 -0700638void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800639 CHECK(!processor_->IsRunning());
640 processor_->set_delegate(this);
641
642 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700643 auto update_boot_flags_action =
644 std::make_unique<UpdateBootFlagsAction>(boot_control_);
645 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
646 auto download_action =
647 std::make_unique<DownloadAction>(prefs_,
648 boot_control_,
649 hardware_,
650 nullptr, // system_state, not used.
651 fetcher, // passes ownership
652 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700654 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700655 auto filesystem_verifier_action =
656 std::make_unique<FilesystemVerifierAction>();
657 auto postinstall_runner_action =
658 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700659 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800660
Alex Deymo5e3ea272016-01-28 13:42:23 -0800661 // Bond them together. We have to use the leaf-types when calling
662 // BondActions().
663 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700664 BondActions(download_action.get(), filesystem_verifier_action.get());
665 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800666 postinstall_runner_action.get());
667
Amin Hassani667cf7b2018-07-25 14:32:00 -0700668 processor_->EnqueueAction(std::move(update_boot_flags_action));
669 processor_->EnqueueAction(std::move(install_plan_action));
670 processor_->EnqueueAction(std::move(download_action));
671 processor_->EnqueueAction(std::move(filesystem_verifier_action));
672 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800673}
674
Alex Deymo5e3ea272016-01-28 13:42:23 -0800675bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
676 string boot_id;
677 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
678 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
679 return true;
680}
681
682bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
683 // In case of an update_engine restart without a reboot, we stored the boot_id
684 // when the update was completed by setting a pref, so we can check whether
685 // the last update was on this boot or a previous one.
686 string boot_id;
687 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
688
689 string update_completed_on_boot_id;
690 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
691 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
692 &update_completed_on_boot_id) &&
693 update_completed_on_boot_id == boot_id);
694}
695
Tianjie Xu90aaa102017-10-10 17:39:03 -0700696// Collect and report the android metrics when we terminate the update.
697void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
698 ErrorCode error_code) {
699 int64_t attempt_number =
700 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
701 PayloadType payload_type = kPayloadTypeFull;
702 int64_t payload_size = 0;
703 for (const auto& p : install_plan_.payloads) {
704 if (p.type == InstallPayloadType::kDelta)
705 payload_type = kPayloadTypeDelta;
706 payload_size += p.size;
707 }
708
709 metrics::AttemptResult attempt_result =
710 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700711 Time boot_time_start = Time::FromInternalValue(
712 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
713 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700714 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700715 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
716 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700717
718 metrics_reporter_->ReportUpdateAttemptMetrics(
719 nullptr, // system_state
720 static_cast<int>(attempt_number),
721 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700722 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700723 duration_uptime,
724 payload_size,
725 attempt_result,
726 error_code);
727
Tianjie Xud4777a12017-10-24 14:54:18 -0700728 int64_t current_bytes_downloaded =
729 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
730 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
731 current_bytes_downloaded,
732 0,
733 DownloadSource::kNumDownloadSources,
734 metrics::DownloadErrorCode::kUnset,
735 metrics::ConnectionType::kUnset);
736
Tianjie Xu90aaa102017-10-10 17:39:03 -0700737 if (error_code == ErrorCode::kSuccess) {
738 int64_t reboot_count =
739 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
740 string build_version;
741 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700742
743 // For android metrics, we only care about the total bytes downloaded
744 // for all sources; for now we assume the only download source is
745 // HttpsServer.
746 int64_t total_bytes_downloaded =
747 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
748 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
749 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
750 total_bytes_downloaded;
751
752 int download_overhead_percentage = 0;
753 if (current_bytes_downloaded > 0) {
754 download_overhead_percentage =
755 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
756 current_bytes_downloaded;
757 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700758 metrics_reporter_->ReportSuccessfulUpdateMetrics(
759 static_cast<int>(attempt_number),
760 0, // update abandoned count
761 payload_type,
762 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700763 num_bytes_downloaded,
764 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700765 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700766 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700767 static_cast<int>(reboot_count),
768 0); // url_switch_count
769 }
770}
771
772void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
773 string current_boot_id;
774 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
775 // Example: [ro.build.version.incremental]: [4292972]
776 string current_version =
777 android::base::GetProperty("ro.build.version.incremental", "");
778 TEST_AND_RETURN(!current_version.empty());
779
780 // If there's no record of previous version (e.g. due to a data wipe), we
781 // save the info of current boot and skip the metrics report.
782 if (!prefs_->Exists(kPrefsPreviousVersion)) {
783 prefs_->SetString(kPrefsBootId, current_boot_id);
784 prefs_->SetString(kPrefsPreviousVersion, current_version);
785 ClearMetricsPrefs();
786 return;
787 }
788 string previous_version;
789 // update_engine restarted under the same build.
790 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
791 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
792 previous_version == current_version) {
793 string last_boot_id;
794 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
795 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
796 last_boot_id != current_boot_id);
797 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
798 // set when we start a new update.
799 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
800 prefs_->SetString(kPrefsBootId, current_boot_id);
801 int64_t reboot_count =
802 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
803 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
804 }
805 return;
806 }
807
808 // Now that the build version changes, report the update metrics.
809 // TODO(xunchang) check the build version is larger than the previous one.
810 prefs_->SetString(kPrefsBootId, current_boot_id);
811 prefs_->SetString(kPrefsPreviousVersion, current_version);
812
813 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
814 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
815 if (previous_attempt_exists) {
816 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
817 }
818
819 metrics_utils::LoadAndReportTimeToReboot(
820 metrics_reporter_.get(), prefs_, clock_.get());
821 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800822
823 // Also reset the update progress if the build version has changed.
824 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
825 LOG(WARNING) << "Unable to reset the update progress.";
826 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700827}
828
829// Save the update start time. Reset the reboot count and attempt number if the
830// update isn't a resume; otherwise increment the attempt number.
831void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
832 if (!is_resume) {
833 metrics_utils::SetNumReboots(0, prefs_);
834 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
835 } else {
836 int64_t attempt_number =
837 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
838 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
839 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700840 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
841 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700842}
843
844void UpdateAttempterAndroid::ClearMetricsPrefs() {
845 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700846 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700847 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700848 prefs_->Delete(kPrefsSystemUpdatedMarker);
849 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700850 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700851}
852
Alex Deymo5e3ea272016-01-28 13:42:23 -0800853} // namespace chromeos_update_engine