blob: a3974ab376e2bac5d874347393d9f6fc6ff19c6c [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>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025#include <base/bind.h>
26#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080027#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070028#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080029#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080030#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070031#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080032
33#include "update_engine/common/constants.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080034#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070035#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080036#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070037#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070038#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070039#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070040#include "update_engine/network_selector.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080041#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080042#include "update_engine/payload_consumer/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080043#include "update_engine/payload_consumer/file_descriptor.h"
44#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080045#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/payload_constants.h"
47#include "update_engine/payload_consumer/payload_metadata.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080048#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070049#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080050#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051
Alex Deymo14c0da82016-07-20 16:45:45 -070052#ifndef _UE_SIDELOAD
53// Do not include support for external HTTP(s) urls when building
54// update_engine_sideload.
55#include "update_engine/libcurl_http_fetcher.h"
56#endif
57
Alex Deymo5e3ea272016-01-28 13:42:23 -080058using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070059using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080060using base::TimeDelta;
61using base::TimeTicks;
62using std::shared_ptr;
63using std::string;
64using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070065using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080066
67namespace chromeos_update_engine {
68
69namespace {
70
Alex Deymo0d298542016-03-30 18:31:49 -070071// Minimum threshold to broadcast an status update in progress and time.
72const double kBroadcastThresholdProgress = 0.01; // 1%
73const int kBroadcastThresholdSeconds = 10;
74
Alex Deymo5e3ea272016-01-28 13:42:23 -080075const char* const kErrorDomain = "update_engine";
76// TODO(deymo): Convert the different errors to a numeric value to report them
77// back on the service error.
78const char* const kGenericError = "generic_error";
79
80// Log and set the error on the passed ErrorPtr.
81bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070082 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080083 const string& reason) {
84 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
85 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
86 << reason;
87 return false;
88}
89
Sen Jiangfe522822017-10-31 15:14:11 -070090bool GetHeaderAsBool(const string& header, bool default_value) {
91 int value = 0;
92 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
93 return value == 1;
94 return default_value;
95}
96
Alex Deymo5e3ea272016-01-28 13:42:23 -080097} // namespace
98
99UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700100 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800101 PrefsInterface* prefs,
102 BootControlInterface* boot_control,
103 HardwareInterface* hardware)
104 : daemon_state_(daemon_state),
105 prefs_(prefs),
106 boot_control_(boot_control),
107 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700108 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700109 clock_(new Clock()) {
110 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700111 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800112}
113
114UpdateAttempterAndroid::~UpdateAttempterAndroid() {
115 // Release ourselves as the ActionProcessor's delegate to prevent
116 // re-scheduling the updates due to the processing stopped.
117 processor_->set_delegate(nullptr);
118}
119
120void UpdateAttempterAndroid::Init() {
121 // In case of update_engine restart without a reboot we need to restore the
122 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700123 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800124 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700125 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800126 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700127 UpdatePrefsAndReportUpdateMetricsOnReboot();
128 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800129}
130
131bool UpdateAttempterAndroid::ApplyPayload(
132 const string& payload_url,
133 int64_t payload_offset,
134 int64_t payload_size,
135 const vector<string>& key_value_pair_headers,
136 brillo::ErrorPtr* error) {
137 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
138 return LogAndSetError(
139 error, FROM_HERE, "An update already applied, waiting for reboot");
140 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700141 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800142 return LogAndSetError(
143 error, FROM_HERE, "Already processing an update, cancel it first.");
144 }
145 DCHECK(status_ == UpdateStatus::IDLE);
146
Alex Deymo218397f2016-02-04 23:55:10 -0800147 std::map<string, string> headers;
148 for (const string& key_value_pair : key_value_pair_headers) {
149 string key;
150 string value;
151 if (!brillo::string_utils::SplitAtFirst(
152 key_value_pair, "=", &key, &value, false)) {
153 return LogAndSetError(
154 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
155 }
156 if (!headers.emplace(key, value).second)
157 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
158 }
159
160 // Unique identifier for the payload. An empty string means that the payload
161 // can't be resumed.
162 string payload_id = (headers[kPayloadPropertyFileHash] +
163 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800164
165 // Setup the InstallPlan based on the request.
166 install_plan_ = InstallPlan();
167
168 install_plan_.download_url = payload_url;
169 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800170 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800171 InstallPlan::Payload payload;
172 payload.size = payload_size;
173 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800174 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800175 &payload.size)) {
176 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800177 }
178 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700179 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800180 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700181 LOG(WARNING) << "Unable to decode base64 file hash: "
182 << headers[kPayloadPropertyFileHash];
183 }
Alex Deymo218397f2016-02-04 23:55:10 -0800184 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800185 &payload.metadata_size)) {
186 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800187 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700188 // The |payload.type| is not used anymore since minor_version 3.
189 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800190 install_plan_.payloads.push_back(payload);
191
Alex Deymo5e3ea272016-01-28 13:42:23 -0800192 // The |public_key_rsa| key would override the public key stored on disk.
193 install_plan_.public_key_rsa = "";
194
195 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
196 install_plan_.is_resume = !payload_id.empty() &&
197 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
198 if (!install_plan_.is_resume) {
199 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
200 LOG(WARNING) << "Unable to reset the update progress.";
201 }
202 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
203 LOG(WARNING) << "Unable to save the update check response hash.";
204 }
205 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800206 install_plan_.source_slot = boot_control_->GetCurrentSlot();
207 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700208
Alex Deymofb905d92016-06-03 19:26:58 -0700209 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700210 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
211
212 install_plan_.switch_slot_on_reboot =
213 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
214
215 install_plan_.run_post_install = true;
216 // Optionally skip post install if and only if:
217 // a) we're resuming
218 // b) post install has already succeeded before
219 // c) RUN_POST_INSTALL is set to 0.
220 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
221 bool post_install_succeeded = false;
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700222 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded,
223 &post_install_succeeded) &&
224 post_install_succeeded) {
Sen Jiangfe522822017-10-31 15:14:11 -0700225 install_plan_.run_post_install =
226 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
227 }
228 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800229
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700230 // Skip writing verity if we're resuming and verity has already been written.
231 install_plan_.write_verity = true;
232 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
233 bool verity_written = false;
234 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
235 verity_written) {
236 install_plan_.write_verity = false;
237 }
238 }
239
Alex Deymo87792ea2016-07-25 15:40:36 -0700240 NetworkId network_id = kDefaultNetworkId;
241 if (!headers[kPayloadPropertyNetworkId].empty()) {
242 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
243 &network_id)) {
244 return LogAndSetError(
245 error,
246 FROM_HERE,
247 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
248 }
249 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700250 return LogAndSetError(
251 error,
252 FROM_HERE,
253 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700254 }
255 }
256
Alex Deymo5e3ea272016-01-28 13:42:23 -0800257 LOG(INFO) << "Using this install plan:";
258 install_plan_.Dump();
259
Amin Hassani667cf7b2018-07-25 14:32:00 -0700260 HttpFetcher* fetcher = nullptr;
261 if (FileFetcher::SupportedUrl(payload_url)) {
262 DLOG(INFO) << "Using FileFetcher for file URL.";
263 fetcher = new FileFetcher();
264 } else {
265#ifdef _UE_SIDELOAD
266 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
267#else
268 LibcurlHttpFetcher* libcurl_fetcher =
269 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
270 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
271 fetcher = libcurl_fetcher;
272#endif // _UE_SIDELOAD
273 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800274 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800275 if (!headers[kPayloadPropertyAuthorization].empty())
276 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
277 if (!headers[kPayloadPropertyUserAgent].empty())
278 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
279
Amin Hassani667cf7b2018-07-25 14:32:00 -0700280 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800281
Alex Deymo5e3ea272016-01-28 13:42:23 -0800282 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700283
284 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
285 // TODO(xunchang) report the metrics for unresumable updates
286
Amin Hassani667cf7b2018-07-25 14:32:00 -0700287 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800288 return true;
289}
290
291bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700292 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800293 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
294 processor_->SuspendProcessing();
295 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800296}
297
298bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700299 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800300 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
301 processor_->ResumeProcessing();
302 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800303}
304
305bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700306 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800307 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800308 processor_->StopProcessing();
309 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800310}
311
Alex Deymo3b678db2016-02-09 11:50:06 -0800312bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
313 LOG(INFO) << "Attempting to reset state from "
314 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
315
316 switch (status_) {
317 case UpdateStatus::IDLE:
318 return true;
319
320 case UpdateStatus::UPDATED_NEED_REBOOT: {
321 // Remove the reboot marker so that if the machine is rebooted
322 // after resetting to idle state, it doesn't go back to
323 // UpdateStatus::UPDATED_NEED_REBOOT state.
324 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700325 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800326
327 // Update the boot flags so the current slot has higher priority.
328 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
329 ret_value = false;
330
Alex Deymo52590332016-11-29 18:29:13 -0800331 // Mark the current slot as successful again, since marking it as active
332 // may reset the successful bit. We ignore the result of whether marking
333 // the current slot as successful worked.
334 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
335 ret_value = false;
336
Alex Deymo3b678db2016-02-09 11:50:06 -0800337 if (!ret_value) {
338 return LogAndSetError(
339 error,
340 FROM_HERE,
341 "Failed to reset the status to ");
342 }
343
344 SetStatusAndNotify(UpdateStatus::IDLE);
345 LOG(INFO) << "Reset status successful";
346 return true;
347 }
348
349 default:
350 return LogAndSetError(
351 error,
352 FROM_HERE,
353 "Reset not allowed in this state. Cancel the ongoing update first");
354 }
355}
356
Sen Jiang8371c1c2018-02-01 13:46:39 -0800357bool UpdateAttempterAndroid::VerifyPayloadApplicable(
358 const std::string& metadata_filename, brillo::ErrorPtr* error) {
359 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
360 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
361 return LogAndSetError(
362 error, FROM_HERE, "Failed to open " + metadata_filename);
363 }
364 brillo::Blob metadata(kMaxPayloadHeaderSize);
365 if (!fd->Read(metadata.data(), metadata.size())) {
366 return LogAndSetError(
367 error,
368 FROM_HERE,
369 "Failed to read payload header from " + metadata_filename);
370 }
371 ErrorCode errorcode;
372 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700373 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800374 MetadataParseResult::kSuccess) {
375 return LogAndSetError(error,
376 FROM_HERE,
377 "Failed to parse payload header: " +
378 utils::ErrorCodeToString(errorcode));
379 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700380 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
381 payload_metadata.GetMetadataSignatureSize();
382 if (metadata_size < kMaxPayloadHeaderSize ||
383 metadata_size >
384 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800385 return LogAndSetError(
386 error,
387 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700388 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800389 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700390 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800391 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
392 metadata.size() - kMaxPayloadHeaderSize)) {
393 return LogAndSetError(
394 error,
395 FROM_HERE,
396 "Failed to read metadata and signature from " + metadata_filename);
397 }
398 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800399
400 string public_key;
401 if (!utils::ReadFile(constants::kUpdatePayloadPublicKeyPath, &public_key)) {
402 return LogAndSetError(error, FROM_HERE, "Failed to read public key.");
403 }
404 errorcode =
405 payload_metadata.ValidateMetadataSignature(metadata, "", public_key);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800406 if (errorcode != ErrorCode::kSuccess) {
407 return LogAndSetError(error,
408 FROM_HERE,
409 "Failed to validate metadata signature: " +
410 utils::ErrorCodeToString(errorcode));
411 }
412 DeltaArchiveManifest manifest;
413 if (!payload_metadata.GetManifest(metadata, &manifest)) {
414 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
415 }
416
417 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
418 for (const PartitionUpdate& partition : manifest.partitions()) {
419 if (!partition.has_old_partition_info())
420 continue;
421 string partition_path;
422 if (!boot_control_->GetPartitionDevice(
423 partition.partition_name(), current_slot, &partition_path)) {
424 return LogAndSetError(
425 error,
426 FROM_HERE,
427 "Failed to get partition device for " + partition.partition_name());
428 }
429 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
430 return LogAndSetError(
431 error, FROM_HERE, "Failed to open " + partition_path);
432 }
433 for (const InstallOperation& operation : partition.operations()) {
434 if (!operation.has_src_sha256_hash())
435 continue;
436 brillo::Blob source_hash;
437 if (!fd_utils::ReadAndHashExtents(fd,
438 operation.src_extents(),
439 manifest.block_size(),
440 &source_hash)) {
441 return LogAndSetError(
442 error, FROM_HERE, "Failed to hash " + partition_path);
443 }
444 if (!DeltaPerformer::ValidateSourceHash(
445 source_hash, operation, fd, &errorcode)) {
446 return false;
447 }
448 }
449 fd->Close();
450 }
451 return true;
452}
453
Alex Deymo5e3ea272016-01-28 13:42:23 -0800454void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
455 ErrorCode code) {
456 LOG(INFO) << "Processing Done.";
457
Alex Deymo5990bf32016-07-19 17:01:41 -0700458 switch (code) {
459 case ErrorCode::kSuccess:
460 // Update succeeded.
461 WriteUpdateCompletedMarker();
462 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800463
Alex Deymo5990bf32016-07-19 17:01:41 -0700464 LOG(INFO) << "Update successfully applied, waiting to reboot.";
465 break;
466
467 case ErrorCode::kFilesystemCopierError:
468 case ErrorCode::kNewRootfsVerificationError:
469 case ErrorCode::kNewKernelVerificationError:
470 case ErrorCode::kFilesystemVerifierError:
471 case ErrorCode::kDownloadStateInitializationError:
472 // Reset the ongoing update for these errors so it starts from the
473 // beginning next time.
474 DeltaPerformer::ResetUpdateProgress(prefs_, false);
475 LOG(INFO) << "Resetting update progress.";
476 break;
477
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700478 case ErrorCode::kPayloadTimestampError:
479 // SafetyNet logging, b/36232423
480 android_errorWriteLog(0x534e4554, "36232423");
481 break;
482
Alex Deymo5990bf32016-07-19 17:01:41 -0700483 default:
484 // Ignore all other error codes.
485 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700486 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800487
488 TerminateUpdateAndNotify(code);
489}
490
491void UpdateAttempterAndroid::ProcessingStopped(
492 const ActionProcessor* processor) {
493 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
494}
495
496void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
497 AbstractAction* action,
498 ErrorCode code) {
499 // Reset download progress regardless of whether or not the download
500 // action succeeded.
501 const string type = action->Type();
502 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700503 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800504 }
Sen Jiangfe522822017-10-31 15:14:11 -0700505 if (type == PostinstallRunnerAction::StaticType()) {
506 bool succeeded =
507 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
508 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
509 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800510 if (code != ErrorCode::kSuccess) {
511 // If an action failed, the ActionProcessor will cancel the whole thing.
512 return;
513 }
514 if (type == DownloadAction::StaticType()) {
515 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700516 } else if (type == FilesystemVerifierAction::StaticType()) {
517 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800518 }
519}
520
521void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
522 uint64_t bytes_received,
523 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700524 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800525 if (total)
526 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700527 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800528 download_progress_ = progress;
529 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700530 } else {
531 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800532 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700533
534 // Update the bytes downloaded in prefs.
535 int64_t current_bytes_downloaded =
536 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
537 int64_t total_bytes_downloaded =
538 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
539 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
540 current_bytes_downloaded + bytes_progressed);
541 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
542 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800543}
544
545bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
546 // TODO(deymo): Notify the DownloadAction that it should cancel the update
547 // download.
548 return false;
549}
550
551void UpdateAttempterAndroid::DownloadComplete() {
552 // Nothing needs to be done when the download completes.
553}
554
Alex Deymo0d298542016-03-30 18:31:49 -0700555void UpdateAttempterAndroid::ProgressUpdate(double progress) {
556 // Self throttle based on progress. Also send notifications if progress is
557 // too slow.
558 if (progress == 1.0 ||
559 progress - download_progress_ >= kBroadcastThresholdProgress ||
560 TimeTicks::Now() - last_notify_time_ >=
561 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
562 download_progress_ = progress;
563 SetStatusAndNotify(status_);
564 }
565}
566
Alex Deymo5e3ea272016-01-28 13:42:23 -0800567void UpdateAttempterAndroid::ScheduleProcessingStart() {
568 LOG(INFO) << "Scheduling an action processor start.";
569 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700570 FROM_HERE,
571 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
572 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800573}
574
575void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
576 if (status_ == UpdateStatus::IDLE) {
577 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
578 return;
579 }
580
Yifan Hong537802d2018-08-15 13:15:42 -0700581 boot_control_->Cleanup();
582
Alex Deymo0d298542016-03-30 18:31:49 -0700583 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800584 UpdateStatus new_status =
585 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
586 : UpdateStatus::IDLE);
587 SetStatusAndNotify(new_status);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800588
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700589 // The network id is only applicable to one download attempt and once it's
590 // done the network id should not be re-used anymore.
591 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
592 LOG(WARNING) << "Unable to unbind network.";
593 }
594
Alex Deymo5e3ea272016-01-28 13:42:23 -0800595 for (auto observer : daemon_state_->service_observers())
596 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700597
Tianjie Xu90aaa102017-10-10 17:39:03 -0700598 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
599 ClearMetricsPrefs();
600 if (error_code == ErrorCode::kSuccess) {
601 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700602 // Clear the total bytes downloaded if and only if the update succeeds.
603 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700604 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800605}
606
607void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
608 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700609 size_t payload_size =
610 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700611 UpdateEngineStatus status_to_send = {.status = status_,
612 .progress = download_progress_,
613 .new_size_bytes = payload_size};
614
Alex Deymo5e3ea272016-01-28 13:42:23 -0800615 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700616 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800617 }
618 last_notify_time_ = TimeTicks::Now();
619}
620
Amin Hassani667cf7b2018-07-25 14:32:00 -0700621void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800622 CHECK(!processor_->IsRunning());
623 processor_->set_delegate(this);
624
625 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700626 auto update_boot_flags_action =
627 std::make_unique<UpdateBootFlagsAction>(boot_control_);
628 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
629 auto download_action =
630 std::make_unique<DownloadAction>(prefs_,
631 boot_control_,
632 hardware_,
633 nullptr, // system_state, not used.
634 fetcher, // passes ownership
635 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800636 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700637 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700638 auto filesystem_verifier_action =
639 std::make_unique<FilesystemVerifierAction>();
640 auto postinstall_runner_action =
641 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700642 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800643
Alex Deymo5e3ea272016-01-28 13:42:23 -0800644 // Bond them together. We have to use the leaf-types when calling
645 // BondActions().
646 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700647 BondActions(download_action.get(), filesystem_verifier_action.get());
648 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800649 postinstall_runner_action.get());
650
Amin Hassani667cf7b2018-07-25 14:32:00 -0700651 processor_->EnqueueAction(std::move(update_boot_flags_action));
652 processor_->EnqueueAction(std::move(install_plan_action));
653 processor_->EnqueueAction(std::move(download_action));
654 processor_->EnqueueAction(std::move(filesystem_verifier_action));
655 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800656}
657
Alex Deymo5e3ea272016-01-28 13:42:23 -0800658bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
659 string boot_id;
660 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
661 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
662 return true;
663}
664
665bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
666 // In case of an update_engine restart without a reboot, we stored the boot_id
667 // when the update was completed by setting a pref, so we can check whether
668 // the last update was on this boot or a previous one.
669 string boot_id;
670 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
671
672 string update_completed_on_boot_id;
673 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
674 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
675 &update_completed_on_boot_id) &&
676 update_completed_on_boot_id == boot_id);
677}
678
Tianjie Xu90aaa102017-10-10 17:39:03 -0700679// Collect and report the android metrics when we terminate the update.
680void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
681 ErrorCode error_code) {
682 int64_t attempt_number =
683 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
684 PayloadType payload_type = kPayloadTypeFull;
685 int64_t payload_size = 0;
686 for (const auto& p : install_plan_.payloads) {
687 if (p.type == InstallPayloadType::kDelta)
688 payload_type = kPayloadTypeDelta;
689 payload_size += p.size;
690 }
691
692 metrics::AttemptResult attempt_result =
693 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700694 Time boot_time_start = Time::FromInternalValue(
695 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
696 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700697 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700698 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
699 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700700
701 metrics_reporter_->ReportUpdateAttemptMetrics(
702 nullptr, // system_state
703 static_cast<int>(attempt_number),
704 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700705 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700706 duration_uptime,
707 payload_size,
708 attempt_result,
709 error_code);
710
Tianjie Xud4777a12017-10-24 14:54:18 -0700711 int64_t current_bytes_downloaded =
712 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
713 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
714 current_bytes_downloaded,
715 0,
716 DownloadSource::kNumDownloadSources,
717 metrics::DownloadErrorCode::kUnset,
718 metrics::ConnectionType::kUnset);
719
Tianjie Xu90aaa102017-10-10 17:39:03 -0700720 if (error_code == ErrorCode::kSuccess) {
721 int64_t reboot_count =
722 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
723 string build_version;
724 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700725
726 // For android metrics, we only care about the total bytes downloaded
727 // for all sources; for now we assume the only download source is
728 // HttpsServer.
729 int64_t total_bytes_downloaded =
730 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
731 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
732 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
733 total_bytes_downloaded;
734
735 int download_overhead_percentage = 0;
736 if (current_bytes_downloaded > 0) {
737 download_overhead_percentage =
738 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
739 current_bytes_downloaded;
740 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700741 metrics_reporter_->ReportSuccessfulUpdateMetrics(
742 static_cast<int>(attempt_number),
743 0, // update abandoned count
744 payload_type,
745 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700746 num_bytes_downloaded,
747 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700748 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700749 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700750 static_cast<int>(reboot_count),
751 0); // url_switch_count
752 }
753}
754
755void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
756 string current_boot_id;
757 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
758 // Example: [ro.build.version.incremental]: [4292972]
759 string current_version =
760 android::base::GetProperty("ro.build.version.incremental", "");
761 TEST_AND_RETURN(!current_version.empty());
762
763 // If there's no record of previous version (e.g. due to a data wipe), we
764 // save the info of current boot and skip the metrics report.
765 if (!prefs_->Exists(kPrefsPreviousVersion)) {
766 prefs_->SetString(kPrefsBootId, current_boot_id);
767 prefs_->SetString(kPrefsPreviousVersion, current_version);
768 ClearMetricsPrefs();
769 return;
770 }
771 string previous_version;
772 // update_engine restarted under the same build.
773 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
774 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
775 previous_version == current_version) {
776 string last_boot_id;
777 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
778 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
779 last_boot_id != current_boot_id);
780 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
781 // set when we start a new update.
782 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
783 prefs_->SetString(kPrefsBootId, current_boot_id);
784 int64_t reboot_count =
785 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
786 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
787 }
788 return;
789 }
790
791 // Now that the build version changes, report the update metrics.
792 // TODO(xunchang) check the build version is larger than the previous one.
793 prefs_->SetString(kPrefsBootId, current_boot_id);
794 prefs_->SetString(kPrefsPreviousVersion, current_version);
795
796 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
797 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
798 if (previous_attempt_exists) {
799 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
800 }
801
802 metrics_utils::LoadAndReportTimeToReboot(
803 metrics_reporter_.get(), prefs_, clock_.get());
804 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800805
806 // Also reset the update progress if the build version has changed.
807 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
808 LOG(WARNING) << "Unable to reset the update progress.";
809 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700810}
811
812// Save the update start time. Reset the reboot count and attempt number if the
813// update isn't a resume; otherwise increment the attempt number.
814void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
815 if (!is_resume) {
816 metrics_utils::SetNumReboots(0, prefs_);
817 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
818 } else {
819 int64_t attempt_number =
820 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
821 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
822 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700823 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
824 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700825}
826
827void UpdateAttempterAndroid::ClearMetricsPrefs() {
828 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700829 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700830 prefs_->Delete(kPrefsNumReboots);
831 prefs_->Delete(kPrefsPayloadAttemptNumber);
832 prefs_->Delete(kPrefsSystemUpdatedMarker);
833 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700834 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700835}
836
Alex Deymo5e3ea272016-01-28 13:42:23 -0800837} // namespace chromeos_update_engine