1 //
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/aosp/update_attempter_android.h"
18
19 #include <algorithm>
20 #include <map>
21 #include <memory>
22 #include <ostream>
23 #include <utility>
24
25 #include <android-base/properties.h>
26 #include <android-base/unique_fd.h>
27 #include <base/bind.h>
28 #include <base/logging.h>
29 #include <base/strings/string_number_conversions.h>
30 #include <brillo/data_encoding.h>
31 #include <brillo/message_loops/message_loop.h>
32 #include <brillo/strings/string_utils.h>
33 #include <log/log_safetynet.h>
34
35 #include "update_engine/aosp/cleanup_previous_update_action.h"
36 #include "update_engine/common/constants.h"
37 #include "update_engine/common/daemon_state_interface.h"
38 #include "update_engine/common/download_action.h"
39 #include "update_engine/common/error_code_utils.h"
40 #include "update_engine/common/file_fetcher.h"
41 #include "update_engine/common/metrics_reporter_interface.h"
42 #include "update_engine/common/network_selector.h"
43 #include "update_engine/common/utils.h"
44 #include "update_engine/metrics_utils.h"
45 #include "update_engine/payload_consumer/certificate_parser_interface.h"
46 #include "update_engine/payload_consumer/delta_performer.h"
47 #include "update_engine/payload_consumer/file_descriptor.h"
48 #include "update_engine/payload_consumer/file_descriptor_utils.h"
49 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
50 #include "update_engine/payload_consumer/payload_constants.h"
51 #include "update_engine/payload_consumer/payload_metadata.h"
52 #include "update_engine/payload_consumer/payload_verifier.h"
53 #include "update_engine/payload_consumer/postinstall_runner_action.h"
54 #include "update_engine/update_boot_flags_action.h"
55 #include "update_engine/update_status_utils.h"
56
57 #ifndef _UE_SIDELOAD
58 // Do not include support for external HTTP(s) urls when building
59 // update_engine_sideload.
60 #include "update_engine/libcurl_http_fetcher.h"
61 #endif
62
63 using android::base::unique_fd;
64 using base::Bind;
65 using base::Time;
66 using base::TimeDelta;
67 using base::TimeTicks;
68 using std::string;
69 using std::vector;
70 using update_engine::UpdateEngineStatus;
71
72 namespace chromeos_update_engine {
73
74 namespace {
75
76 // Minimum threshold to broadcast an status update in progress and time.
77 const double kBroadcastThresholdProgress = 0.01; // 1%
78 const int kBroadcastThresholdSeconds = 10;
79
80 const char* const kErrorDomain = "update_engine";
81 // TODO(deymo): Convert the different errors to a numeric value to report them
82 // back on the service error.
83 const char* const kGenericError = "generic_error";
84
85 // Log and set the error on the passed ErrorPtr.
LogAndSetError(brillo::ErrorPtr * error,const base::Location & location,const string & reason)86 bool LogAndSetError(brillo::ErrorPtr* error,
87 const base::Location& location,
88 const string& reason) {
89 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
90 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
91 << reason;
92 return false;
93 }
94
GetHeaderAsBool(const string & header,bool default_value)95 bool GetHeaderAsBool(const string& header, bool default_value) {
96 int value = 0;
97 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
98 return value == 1;
99 return default_value;
100 }
101
ParseKeyValuePairHeaders(const vector<string> & key_value_pair_headers,std::map<string,string> * headers,brillo::ErrorPtr * error)102 bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
103 std::map<string, string>* headers,
104 brillo::ErrorPtr* error) {
105 for (const string& key_value_pair : key_value_pair_headers) {
106 string key;
107 string value;
108 if (!brillo::string_utils::SplitAtFirst(
109 key_value_pair, "=", &key, &value, false)) {
110 return LogAndSetError(
111 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
112 }
113 if (!headers->emplace(key, value).second)
114 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
115 }
116 return true;
117 }
118
119 // Unique identifier for the payload. An empty string means that the payload
120 // can't be resumed.
GetPayloadId(const std::map<string,string> & headers)121 string GetPayloadId(const std::map<string, string>& headers) {
122 return (headers.count(kPayloadPropertyFileHash)
123 ? headers.at(kPayloadPropertyFileHash)
124 : "") +
125 (headers.count(kPayloadPropertyMetadataHash)
126 ? headers.at(kPayloadPropertyMetadataHash)
127 : "");
128 }
129
130 } // namespace
131
UpdateAttempterAndroid(DaemonStateInterface * daemon_state,PrefsInterface * prefs,BootControlInterface * boot_control,HardwareInterface * hardware,std::unique_ptr<ApexHandlerInterface> apex_handler)132 UpdateAttempterAndroid::UpdateAttempterAndroid(
133 DaemonStateInterface* daemon_state,
134 PrefsInterface* prefs,
135 BootControlInterface* boot_control,
136 HardwareInterface* hardware,
137 std::unique_ptr<ApexHandlerInterface> apex_handler)
138 : daemon_state_(daemon_state),
139 prefs_(prefs),
140 boot_control_(boot_control),
141 hardware_(hardware),
142 apex_handler_android_(std::move(apex_handler)),
143 processor_(new ActionProcessor()),
144 clock_(new Clock()) {
145 metrics_reporter_ = metrics::CreateMetricsReporter(
146 boot_control_->GetDynamicPartitionControl(), &install_plan_);
147 network_selector_ = network::CreateNetworkSelector();
148 }
149
~UpdateAttempterAndroid()150 UpdateAttempterAndroid::~UpdateAttempterAndroid() {
151 // Release ourselves as the ActionProcessor's delegate to prevent
152 // re-scheduling the updates due to the processing stopped.
153 processor_->set_delegate(nullptr);
154 }
155
DidSystemReboot(PrefsInterface * prefs)156 [[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
157 string boot_id;
158 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
159 string old_boot_id;
160 // If no previous boot id found, treat as a reboot and write boot ID.
161 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
162 return true;
163 }
164 return old_boot_id != boot_id;
165 }
166
operator <<(std::ostream & out,OTAResult result)167 std::ostream& operator<<(std::ostream& out, OTAResult result) {
168 switch (result) {
169 case OTAResult::NOT_ATTEMPTED:
170 out << "OTAResult::NOT_ATTEMPTED";
171 break;
172 case OTAResult::ROLLED_BACK:
173 out << "OTAResult::ROLLED_BACK";
174 break;
175 case OTAResult::UPDATED_NEED_REBOOT:
176 out << "OTAResult::UPDATED_NEED_REBOOT";
177 break;
178 case OTAResult::OTA_SUCCESSFUL:
179 out << "OTAResult::OTA_SUCCESSFUL";
180 break;
181 }
182 return out;
183 }
184
Init()185 void UpdateAttempterAndroid::Init() {
186 // In case of update_engine restart without a reboot we need to restore the
187 // reboot needed state.
188 if (UpdateCompletedOnThisBoot()) {
189 LOG(INFO) << "Updated installed but update_engine is restarted without "
190 "device reboot. Resuming old state.";
191 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
192 } else {
193 const auto result = GetOTAUpdateResult();
194 LOG(INFO) << result;
195 SetStatusAndNotify(UpdateStatus::IDLE);
196 if (DidSystemReboot(prefs_)) {
197 UpdateStateAfterReboot(result);
198 }
199
200 #ifdef _UE_SIDELOAD
201 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
202 << "ApplyPayload will call it later.";
203 #else
204 ScheduleCleanupPreviousUpdate();
205 #endif
206 }
207 }
208
ApplyPayload(const string & payload_url,int64_t payload_offset,int64_t payload_size,const vector<string> & key_value_pair_headers,brillo::ErrorPtr * error)209 bool UpdateAttempterAndroid::ApplyPayload(
210 const string& payload_url,
211 int64_t payload_offset,
212 int64_t payload_size,
213 const vector<string>& key_value_pair_headers,
214 brillo::ErrorPtr* error) {
215 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
216 return LogAndSetError(
217 error, FROM_HERE, "An update already applied, waiting for reboot");
218 }
219 if (processor_->IsRunning()) {
220 return LogAndSetError(
221 error, FROM_HERE, "Already processing an update, cancel it first.");
222 }
223 DCHECK_EQ(status_, UpdateStatus::IDLE);
224
225 std::map<string, string> headers;
226 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
227 return false;
228 }
229
230 string payload_id = GetPayloadId(headers);
231
232 // Setup the InstallPlan based on the request.
233 install_plan_ = InstallPlan();
234
235 install_plan_.download_url = payload_url;
236 install_plan_.version = "";
237 base_offset_ = payload_offset;
238 InstallPlan::Payload payload;
239 payload.size = payload_size;
240 if (!payload.size) {
241 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
242 &payload.size)) {
243 payload.size = 0;
244 }
245 }
246 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
247 &payload.hash)) {
248 LOG(WARNING) << "Unable to decode base64 file hash: "
249 << headers[kPayloadPropertyFileHash];
250 }
251 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
252 &payload.metadata_size)) {
253 payload.metadata_size = 0;
254 }
255 // The |payload.type| is not used anymore since minor_version 3.
256 payload.type = InstallPayloadType::kUnknown;
257 install_plan_.payloads.push_back(payload);
258
259 // The |public_key_rsa| key would override the public key stored on disk.
260 install_plan_.public_key_rsa = "";
261
262 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
263 install_plan_.is_resume = !payload_id.empty() &&
264 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
265 if (!install_plan_.is_resume) {
266 boot_control_->GetDynamicPartitionControl()->Cleanup();
267 // No need to reset dynamic_partititon_metadata_updated. If previous calls
268 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
269 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
270 // applied.
271 if (!DeltaPerformer::ResetUpdateProgress(
272 prefs_,
273 false /* quick */,
274 true /* skip_dynamic_partititon_metadata_updated */)) {
275 LOG(WARNING) << "Unable to reset the update progress.";
276 }
277 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
278 LOG(WARNING) << "Unable to save the update check response hash.";
279 }
280 }
281 install_plan_.source_slot = GetCurrentSlot();
282 install_plan_.target_slot = GetTargetSlot();
283
284 install_plan_.powerwash_required =
285 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
286
287 install_plan_.switch_slot_on_reboot =
288 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
289
290 install_plan_.run_post_install =
291 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
292
293 // Skip writing verity if we're resuming and verity has already been written.
294 install_plan_.write_verity = true;
295 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
296 bool verity_written = false;
297 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
298 verity_written) {
299 install_plan_.write_verity = false;
300 }
301 }
302
303 NetworkId network_id = kDefaultNetworkId;
304 if (!headers[kPayloadPropertyNetworkId].empty()) {
305 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
306 &network_id)) {
307 return LogAndSetError(
308 error,
309 FROM_HERE,
310 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
311 }
312 if (!network_selector_->SetProcessNetwork(network_id)) {
313 return LogAndSetError(
314 error,
315 FROM_HERE,
316 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
317 }
318 }
319
320 LOG(INFO) << "Using this install plan:";
321 install_plan_.Dump();
322
323 HttpFetcher* fetcher = nullptr;
324 if (FileFetcher::SupportedUrl(payload_url)) {
325 DLOG(INFO) << "Using FileFetcher for file URL.";
326 fetcher = new FileFetcher();
327 } else {
328 #ifdef _UE_SIDELOAD
329 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
330 #else
331 LibcurlHttpFetcher* libcurl_fetcher =
332 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
333 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
334 fetcher = libcurl_fetcher;
335 #endif // _UE_SIDELOAD
336 }
337 // Setup extra headers.
338 if (!headers[kPayloadPropertyAuthorization].empty())
339 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
340 if (!headers[kPayloadPropertyUserAgent].empty())
341 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
342
343 BuildUpdateActions(fetcher);
344
345 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
346
347 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
348 // TODO(xunchang) report the metrics for unresumable updates
349
350 ScheduleProcessingStart();
351 return true;
352 }
353
ApplyPayload(int fd,int64_t payload_offset,int64_t payload_size,const vector<string> & key_value_pair_headers,brillo::ErrorPtr * error)354 bool UpdateAttempterAndroid::ApplyPayload(
355 int fd,
356 int64_t payload_offset,
357 int64_t payload_size,
358 const vector<string>& key_value_pair_headers,
359 brillo::ErrorPtr* error) {
360 // update_engine state must be checked before modifying payload_fd_ otherwise
361 // already running update will be terminated (existing file descriptor will be
362 // closed)
363 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
364 return LogAndSetError(
365 error, FROM_HERE, "An update already applied, waiting for reboot");
366 }
367 if (processor_->IsRunning()) {
368 return LogAndSetError(
369 error, FROM_HERE, "Already processing an update, cancel it first.");
370 }
371 DCHECK_EQ(status_, UpdateStatus::IDLE);
372
373 payload_fd_.reset(dup(fd));
374 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
375
376 return ApplyPayload(
377 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
378 }
379
SuspendUpdate(brillo::ErrorPtr * error)380 bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
381 if (!processor_->IsRunning())
382 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
383 processor_->SuspendProcessing();
384 return true;
385 }
386
ResumeUpdate(brillo::ErrorPtr * error)387 bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
388 if (!processor_->IsRunning())
389 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
390 processor_->ResumeProcessing();
391 return true;
392 }
393
CancelUpdate(brillo::ErrorPtr * error)394 bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
395 if (!processor_->IsRunning())
396 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
397 processor_->StopProcessing();
398 return true;
399 }
400
ResetStatus(brillo::ErrorPtr * error)401 bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
402 LOG(INFO) << "Attempting to reset state from "
403 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
404 if (processor_->IsRunning()) {
405 return LogAndSetError(
406 error, FROM_HERE, "Already processing an update, cancel it first.");
407 }
408
409 if (apex_handler_android_ != nullptr) {
410 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
411 std::vector<ApexInfo> apex_infos_blank;
412 apex_handler_android_->AllocateSpace(apex_infos_blank);
413 }
414 // Remove the reboot marker so that if the machine is rebooted
415 // after resetting to idle state, it doesn't go back to
416 // UpdateStatus::UPDATED_NEED_REBOOT state.
417 if (!ClearUpdateCompletedMarker()) {
418 return LogAndSetError(error,
419 FROM_HERE,
420 "Failed to reset the status because "
421 "ClearUpdateCompletedMarker() failed");
422 }
423
424 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
425 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
426 << "space might not be freed.";
427 }
428 switch (status_) {
429 case UpdateStatus::IDLE: {
430 return true;
431 }
432
433 case UpdateStatus::UPDATED_NEED_REBOOT: {
434 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
435 if (ret_value) {
436 LOG(INFO) << "Reset status successful";
437 }
438 return ret_value;
439 }
440
441 default:
442 return LogAndSetError(
443 error,
444 FROM_HERE,
445 "Reset not allowed in this state. Cancel the ongoing update first");
446 }
447 }
448
VerifyPayloadParseManifest(const std::string & metadata_filename,DeltaArchiveManifest * manifest,brillo::ErrorPtr * error)449 bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
450 const std::string& metadata_filename,
451 DeltaArchiveManifest* manifest,
452 brillo::ErrorPtr* error) {
453 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
454 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
455 return LogAndSetError(
456 error, FROM_HERE, "Failed to open " + metadata_filename);
457 }
458 brillo::Blob metadata(kMaxPayloadHeaderSize);
459 if (!fd->Read(metadata.data(), metadata.size())) {
460 return LogAndSetError(
461 error,
462 FROM_HERE,
463 "Failed to read payload header from " + metadata_filename);
464 }
465 ErrorCode errorcode;
466 PayloadMetadata payload_metadata;
467 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
468 MetadataParseResult::kSuccess) {
469 return LogAndSetError(error,
470 FROM_HERE,
471 "Failed to parse payload header: " +
472 utils::ErrorCodeToString(errorcode));
473 }
474 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
475 payload_metadata.GetMetadataSignatureSize();
476 if (metadata_size < kMaxPayloadHeaderSize ||
477 metadata_size >
478 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
479 return LogAndSetError(
480 error,
481 FROM_HERE,
482 "Invalid metadata size: " + std::to_string(metadata_size));
483 }
484 metadata.resize(metadata_size);
485 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
486 metadata.size() - kMaxPayloadHeaderSize)) {
487 return LogAndSetError(
488 error,
489 FROM_HERE,
490 "Failed to read metadata and signature from " + metadata_filename);
491 }
492 fd->Close();
493
494 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
495 constants::kUpdateCertificatesPath);
496 if (!payload_verifier) {
497 return LogAndSetError(error,
498 FROM_HERE,
499 "Failed to create the payload verifier from " +
500 std::string(constants::kUpdateCertificatesPath));
501 }
502 errorcode = payload_metadata.ValidateMetadataSignature(
503 metadata, "", *payload_verifier);
504 if (errorcode != ErrorCode::kSuccess) {
505 return LogAndSetError(error,
506 FROM_HERE,
507 "Failed to validate metadata signature: " +
508 utils::ErrorCodeToString(errorcode));
509 }
510 if (!payload_metadata.GetManifest(metadata, manifest)) {
511 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
512 }
513
514 return true;
515 }
516
VerifyPayloadApplicable(const std::string & metadata_filename,brillo::ErrorPtr * error)517 bool UpdateAttempterAndroid::VerifyPayloadApplicable(
518 const std::string& metadata_filename, brillo::ErrorPtr* error) {
519 DeltaArchiveManifest manifest;
520 TEST_AND_RETURN_FALSE(
521 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
522
523 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
524 ErrorCode errorcode;
525
526 BootControlInterface::Slot current_slot = GetCurrentSlot();
527 for (const PartitionUpdate& partition : manifest.partitions()) {
528 if (!partition.has_old_partition_info())
529 continue;
530 string partition_path;
531 if (!boot_control_->GetPartitionDevice(
532 partition.partition_name(), current_slot, &partition_path)) {
533 return LogAndSetError(
534 error,
535 FROM_HERE,
536 "Failed to get partition device for " + partition.partition_name());
537 }
538 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
539 return LogAndSetError(
540 error, FROM_HERE, "Failed to open " + partition_path);
541 }
542 for (const InstallOperation& operation : partition.operations()) {
543 if (!operation.has_src_sha256_hash())
544 continue;
545 brillo::Blob source_hash;
546 if (!fd_utils::ReadAndHashExtents(fd,
547 operation.src_extents(),
548 manifest.block_size(),
549 &source_hash)) {
550 return LogAndSetError(
551 error, FROM_HERE, "Failed to hash " + partition_path);
552 }
553 if (!PartitionWriter::ValidateSourceHash(
554 source_hash, operation, fd, &errorcode)) {
555 return false;
556 }
557 }
558 fd->Close();
559 }
560 return true;
561 }
562
ProcessingDone(const ActionProcessor * processor,ErrorCode code)563 void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
564 ErrorCode code) {
565 LOG(INFO) << "Processing Done.";
566
567 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
568 TerminateUpdateAndNotify(code);
569 return;
570 }
571
572 switch (code) {
573 case ErrorCode::kSuccess:
574 // Update succeeded.
575 if (!WriteUpdateCompletedMarker()) {
576 LOG(ERROR) << "Failed to write update completion marker";
577 }
578 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
579
580 LOG(INFO) << "Update successfully applied, waiting to reboot.";
581 break;
582
583 case ErrorCode::kFilesystemCopierError:
584 case ErrorCode::kNewRootfsVerificationError:
585 case ErrorCode::kNewKernelVerificationError:
586 case ErrorCode::kFilesystemVerifierError:
587 case ErrorCode::kDownloadStateInitializationError:
588 // Reset the ongoing update for these errors so it starts from the
589 // beginning next time.
590 DeltaPerformer::ResetUpdateProgress(prefs_, false);
591 LOG(INFO) << "Resetting update progress.";
592 break;
593
594 case ErrorCode::kPayloadTimestampError:
595 // SafetyNet logging, b/36232423
596 android_errorWriteLog(0x534e4554, "36232423");
597 break;
598
599 default:
600 // Ignore all other error codes.
601 break;
602 }
603
604 TerminateUpdateAndNotify(code);
605 }
606
ProcessingStopped(const ActionProcessor * processor)607 void UpdateAttempterAndroid::ProcessingStopped(
608 const ActionProcessor* processor) {
609 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
610 }
611
ActionCompleted(ActionProcessor * processor,AbstractAction * action,ErrorCode code)612 void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
613 AbstractAction* action,
614 ErrorCode code) {
615 // Reset download progress regardless of whether or not the download
616 // action succeeded.
617 const string type = action->Type();
618 if (type == CleanupPreviousUpdateAction::StaticType() ||
619 (type == NoOpAction::StaticType() &&
620 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
621 cleanup_previous_update_code_ = code;
622 NotifyCleanupPreviousUpdateCallbacksAndClear();
623 }
624 // download_progress_ is actually used by other actions, such as
625 // filesystem_verify_action. Therefore we always clear it.
626 download_progress_ = 0;
627 if (type == PostinstallRunnerAction::StaticType()) {
628 bool succeeded =
629 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
630 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
631 }
632 if (code != ErrorCode::kSuccess) {
633 // If an action failed, the ActionProcessor will cancel the whole thing.
634 return;
635 }
636 if (type == UpdateBootFlagsAction::StaticType()) {
637 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
638 }
639 if (type == DownloadAction::StaticType()) {
640 auto download_action = static_cast<DownloadAction*>(action);
641 install_plan_ = *download_action->install_plan();
642 SetStatusAndNotify(UpdateStatus::VERIFYING);
643 } else if (type == FilesystemVerifierAction::StaticType()) {
644 SetStatusAndNotify(UpdateStatus::FINALIZING);
645 prefs_->SetBoolean(kPrefsVerityWritten, true);
646 }
647 }
648
BytesReceived(uint64_t bytes_progressed,uint64_t bytes_received,uint64_t total)649 void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
650 uint64_t bytes_received,
651 uint64_t total) {
652 double progress = 0;
653 if (total)
654 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
655 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
656 download_progress_ = progress;
657 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
658 } else {
659 ProgressUpdate(progress);
660 }
661
662 // Update the bytes downloaded in prefs.
663 int64_t current_bytes_downloaded =
664 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
665 int64_t total_bytes_downloaded =
666 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
667 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
668 current_bytes_downloaded + bytes_progressed);
669 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
670 total_bytes_downloaded + bytes_progressed);
671 }
672
ShouldCancel(ErrorCode * cancel_reason)673 bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
674 // TODO(deymo): Notify the DownloadAction that it should cancel the update
675 // download.
676 return false;
677 }
678
DownloadComplete()679 void UpdateAttempterAndroid::DownloadComplete() {
680 // Nothing needs to be done when the download completes.
681 }
682
ProgressUpdate(double progress)683 void UpdateAttempterAndroid::ProgressUpdate(double progress) {
684 // Self throttle based on progress. Also send notifications if progress is
685 // too slow.
686 if (progress == 1.0 ||
687 progress - download_progress_ >= kBroadcastThresholdProgress ||
688 TimeTicks::Now() - last_notify_time_ >=
689 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
690 download_progress_ = progress;
691 SetStatusAndNotify(status_);
692 }
693 }
694
OnVerifyProgressUpdate(double progress)695 void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
696 assert(status_ == UpdateStatus::VERIFYING);
697 ProgressUpdate(progress);
698 }
699
ScheduleProcessingStart()700 void UpdateAttempterAndroid::ScheduleProcessingStart() {
701 LOG(INFO) << "Scheduling an action processor start.";
702 processor_->set_delegate(this);
703 brillo::MessageLoop::current()->PostTask(
704 FROM_HERE,
705 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
706 base::Unretained(processor_.get())));
707 }
708
TerminateUpdateAndNotify(ErrorCode error_code)709 void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
710 if (status_ == UpdateStatus::IDLE) {
711 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
712 return;
713 }
714
715 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
716 ClearUpdateCompletedMarker();
717 LOG(INFO) << "Terminating cleanup previous update.";
718 SetStatusAndNotify(UpdateStatus::IDLE);
719 for (auto observer : daemon_state_->service_observers())
720 observer->SendPayloadApplicationComplete(error_code);
721 return;
722 }
723
724 boot_control_->GetDynamicPartitionControl()->Cleanup();
725
726 download_progress_ = 0;
727 UpdateStatus new_status =
728 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
729 : UpdateStatus::IDLE);
730 SetStatusAndNotify(new_status);
731 payload_fd_.reset();
732
733 // The network id is only applicable to one download attempt and once it's
734 // done the network id should not be re-used anymore.
735 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
736 LOG(WARNING) << "Unable to unbind network.";
737 }
738
739 for (auto observer : daemon_state_->service_observers())
740 observer->SendPayloadApplicationComplete(error_code);
741
742 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
743 ClearMetricsPrefs();
744 if (error_code == ErrorCode::kSuccess) {
745 // We should only reset the PayloadAttemptNumber if the update succeeds, or
746 // we switch to a different payload.
747 prefs_->Delete(kPrefsPayloadAttemptNumber);
748 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
749 // Clear the total bytes downloaded if and only if the update succeeds.
750 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
751 }
752 }
753
SetStatusAndNotify(UpdateStatus status)754 void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
755 status_ = status;
756 size_t payload_size =
757 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
758 UpdateEngineStatus status_to_send = {.status = status_,
759 .progress = download_progress_,
760 .new_size_bytes = payload_size};
761
762 for (auto observer : daemon_state_->service_observers()) {
763 observer->SendStatusUpdate(status_to_send);
764 }
765 last_notify_time_ = TimeTicks::Now();
766 }
767
BuildUpdateActions(HttpFetcher * fetcher)768 void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
769 CHECK(!processor_->IsRunning());
770
771 // Actions:
772 auto update_boot_flags_action =
773 std::make_unique<UpdateBootFlagsAction>(boot_control_);
774 auto cleanup_previous_update_action =
775 boot_control_->GetDynamicPartitionControl()
776 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
777 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
778 auto download_action =
779 std::make_unique<DownloadAction>(prefs_,
780 boot_control_,
781 hardware_,
782 fetcher, // passes ownership
783 true /* interactive */,
784 update_certificates_path_);
785 download_action->set_delegate(this);
786 download_action->set_base_offset(base_offset_);
787 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
788 boot_control_->GetDynamicPartitionControl());
789 auto postinstall_runner_action =
790 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
791 filesystem_verifier_action->set_delegate(this);
792 postinstall_runner_action->set_delegate(this);
793
794 // Bond them together. We have to use the leaf-types when calling
795 // BondActions().
796 BondActions(install_plan_action.get(), download_action.get());
797 BondActions(download_action.get(), filesystem_verifier_action.get());
798 BondActions(filesystem_verifier_action.get(),
799 postinstall_runner_action.get());
800
801 processor_->EnqueueAction(std::move(update_boot_flags_action));
802 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
803 processor_->EnqueueAction(std::move(install_plan_action));
804 processor_->EnqueueAction(std::move(download_action));
805 processor_->EnqueueAction(std::move(filesystem_verifier_action));
806 processor_->EnqueueAction(std::move(postinstall_runner_action));
807 }
808
WriteUpdateCompletedMarker()809 bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
810 LOG(INFO) << "Writing update complete marker.";
811 string boot_id;
812 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
813 TEST_AND_RETURN_FALSE(
814 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
815 TEST_AND_RETURN_FALSE(
816 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
817 return true;
818 }
819
ClearUpdateCompletedMarker()820 bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
821 LOG(INFO) << "Clearing update complete marker.";
822 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
823 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
824 return true;
825 }
826
UpdateCompletedOnThisBoot()827 bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
828 // In case of an update_engine restart without a reboot, we stored the boot_id
829 // when the update was completed by setting a pref, so we can check whether
830 // the last update was on this boot or a previous one.
831 string boot_id;
832 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
833
834 string update_completed_on_boot_id;
835 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
836 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
837 &update_completed_on_boot_id) &&
838 update_completed_on_boot_id == boot_id);
839 }
840
841 // Collect and report the android metrics when we terminate the update.
CollectAndReportUpdateMetricsOnUpdateFinished(ErrorCode error_code)842 void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
843 ErrorCode error_code) {
844 int64_t attempt_number =
845 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
846 PayloadType payload_type = kPayloadTypeFull;
847 int64_t payload_size = 0;
848 for (const auto& p : install_plan_.payloads) {
849 if (p.type == InstallPayloadType::kDelta)
850 payload_type = kPayloadTypeDelta;
851 payload_size += p.size;
852 }
853 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
854 // function will be triggered, but payload_size in this case might be 0, if so
855 // skip reporting any metrics.
856 if (payload_size == 0) {
857 return;
858 }
859
860 metrics::AttemptResult attempt_result =
861 metrics_utils::GetAttemptResult(error_code);
862 Time boot_time_start = Time::FromInternalValue(
863 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
864 Time monotonic_time_start = Time::FromInternalValue(
865 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
866 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
867 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
868
869 metrics_reporter_->ReportUpdateAttemptMetrics(
870 static_cast<int>(attempt_number),
871 payload_type,
872 duration,
873 duration_uptime,
874 payload_size,
875 attempt_result,
876 error_code);
877
878 int64_t current_bytes_downloaded =
879 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
880 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
881 current_bytes_downloaded,
882 0,
883 DownloadSource::kNumDownloadSources,
884 metrics::DownloadErrorCode::kUnset,
885 metrics::ConnectionType::kUnset);
886
887 if (error_code == ErrorCode::kSuccess) {
888 int64_t reboot_count =
889 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
890 string build_version;
891 prefs_->GetString(kPrefsPreviousVersion, &build_version);
892
893 // For android metrics, we only care about the total bytes downloaded
894 // for all sources; for now we assume the only download source is
895 // HttpsServer.
896 int64_t total_bytes_downloaded =
897 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
898 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
899 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
900 total_bytes_downloaded;
901
902 int download_overhead_percentage = 0;
903 if (total_bytes_downloaded >= payload_size) {
904 CHECK_GT(payload_size, 0);
905 download_overhead_percentage =
906 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
907 } else {
908 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
909 << " is smaller than the payload size " << payload_size;
910 }
911
912 metrics_reporter_->ReportSuccessfulUpdateMetrics(
913 static_cast<int>(attempt_number),
914 0, // update abandoned count
915 payload_type,
916 payload_size,
917 num_bytes_downloaded,
918 download_overhead_percentage,
919 duration,
920 duration_uptime,
921 static_cast<int>(reboot_count),
922 0); // url_switch_count
923 }
924 }
925
OTARebootSucceeded() const926 bool UpdateAttempterAndroid::OTARebootSucceeded() const {
927 const auto current_slot = boot_control_->GetCurrentSlot();
928 const string current_version =
929 android::base::GetProperty("ro.build.version.incremental", "");
930 int64_t previous_slot = -1;
931 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
932 string previous_version;
933 TEST_AND_RETURN_FALSE(
934 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
935 if (previous_slot != current_slot) {
936 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
937 << previous_version << " to " << current_version;
938 if (previous_version == current_version) {
939 LOG(INFO) << "Previous version is the same as current version, this is "
940 "possibly a self-OTA.";
941 }
942 return true;
943 } else {
944 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
945 "switch never happened, or system not rebooted at all.";
946 if (previous_version != current_version) {
947 LOG(INFO) << "Slot didn't change, but version changed from "
948 << previous_version << " to " << current_version
949 << " device could be flashed.";
950 }
951 return false;
952 }
953 }
954
GetOTAUpdateResult() const955 OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
956 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
957 // existence of this pref is sufficient indicator. Given that we have to
958 // delete this pref after checking it. This is done in
959 // |DeltaPerformer::ResetUpdateProgress|
960 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
961 auto system_rebooted = DidSystemReboot(prefs_);
962 auto ota_successful = OTARebootSucceeded();
963 if (ota_successful) {
964 return OTAResult::OTA_SUCCESSFUL;
965 }
966 if (slot_switch_attempted) {
967 if (system_rebooted) {
968 // If we attempted slot switch, but still end up on the same slot, we
969 // probably rolled back.
970 return OTAResult::ROLLED_BACK;
971 } else {
972 return OTAResult::UPDATED_NEED_REBOOT;
973 }
974 }
975 return OTAResult::NOT_ATTEMPTED;
976 }
977
UpdateStateAfterReboot(const OTAResult result)978 void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
979 // Example: [ro.build.version.incremental]: [4292972]
980 string current_version =
981 android::base::GetProperty("ro.build.version.incremental", "");
982 TEST_AND_RETURN(!current_version.empty());
983
984 // |UpdateStateAfterReboot()| is only called after system reboot, so record
985 // boot id unconditionally
986 string current_boot_id;
987 TEST_AND_RETURN(utils::GetBootId(¤t_boot_id));
988 prefs_->SetString(kPrefsBootId, current_boot_id);
989
990 // If there's no record of previous version (e.g. due to a data wipe), we
991 // save the info of current boot and skip the metrics report.
992 if (!prefs_->Exists(kPrefsPreviousVersion)) {
993 prefs_->SetString(kPrefsPreviousVersion, current_version);
994 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
995 ClearMetricsPrefs();
996 return;
997 }
998 // update_engine restarted under the same build and same slot.
999 if (result != OTAResult::OTA_SUCCESSFUL) {
1000 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1001 // set when we start a new update.
1002 if (prefs_->Exists(kPrefsNumReboots)) {
1003 int64_t reboot_count =
1004 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1005 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1006 }
1007
1008 if (result == OTAResult::ROLLED_BACK) {
1009 // This will release all space previously allocated for apex
1010 // decompression. If we detect a rollback, we should release space and
1011 // return the space to user. Any subsequent attempt to install OTA will
1012 // allocate space again anyway.
1013 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1014 "deompression.";
1015 apex_handler_android_->AllocateSpace({});
1016 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1017 }
1018 return;
1019 }
1020
1021 // Now that the build version changes, report the update metrics.
1022 // TODO(xunchang) check the build version is larger than the previous one.
1023 prefs_->SetString(kPrefsPreviousVersion, current_version);
1024 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
1025
1026 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1027 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1028 if (previous_attempt_exists) {
1029 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1030 }
1031
1032 metrics_utils::LoadAndReportTimeToReboot(
1033 metrics_reporter_.get(), prefs_, clock_.get());
1034 ClearMetricsPrefs();
1035
1036 // Also reset the update progress if the build version has changed.
1037 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1038 LOG(WARNING) << "Unable to reset the update progress.";
1039 }
1040 }
1041
1042 // Save the update start time. Reset the reboot count and attempt number if the
1043 // update isn't a resume; otherwise increment the attempt number.
UpdatePrefsOnUpdateStart(bool is_resume)1044 void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1045 if (!is_resume) {
1046 metrics_utils::SetNumReboots(0, prefs_);
1047 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1048 } else {
1049 int64_t attempt_number =
1050 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1051 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1052 }
1053 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1054 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
1055 ClearUpdateCompletedMarker();
1056 }
1057
ClearMetricsPrefs()1058 void UpdateAttempterAndroid::ClearMetricsPrefs() {
1059 CHECK(prefs_);
1060 prefs_->Delete(kPrefsCurrentBytesDownloaded);
1061 prefs_->Delete(kPrefsNumReboots);
1062 prefs_->Delete(kPrefsSystemUpdatedMarker);
1063 prefs_->Delete(kPrefsUpdateTimestampStart);
1064 prefs_->Delete(kPrefsUpdateBootTimestampStart);
1065 }
1066
GetCurrentSlot() const1067 BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1068 return boot_control_->GetCurrentSlot();
1069 }
1070
GetTargetSlot() const1071 BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1072 return GetCurrentSlot() == 0 ? 1 : 0;
1073 }
1074
AllocateSpaceForPayload(const std::string & metadata_filename,const vector<string> & key_value_pair_headers,brillo::ErrorPtr * error)1075 uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1076 const std::string& metadata_filename,
1077 const vector<string>& key_value_pair_headers,
1078 brillo::ErrorPtr* error) {
1079 DeltaArchiveManifest manifest;
1080 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1081 return 0;
1082 }
1083 std::map<string, string> headers;
1084 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1085 return 0;
1086 }
1087
1088 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1089 manifest.apex_info().end());
1090 uint64_t apex_size_required = 0;
1091 if (apex_handler_android_ != nullptr) {
1092 auto result = apex_handler_android_->CalculateSize(apex_infos);
1093 if (!result.ok()) {
1094 LogAndSetError(error,
1095 FROM_HERE,
1096 "Failed to calculate size required for compressed APEX");
1097 return 0;
1098 }
1099 apex_size_required = *result;
1100 }
1101
1102 string payload_id = GetPayloadId(headers);
1103 uint64_t required_size = 0;
1104 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1105 boot_control_,
1106 GetTargetSlot(),
1107 manifest,
1108 payload_id,
1109 &required_size)) {
1110 if (required_size == 0) {
1111 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1112 return 0;
1113 } else {
1114 LOG(ERROR) << "Insufficient space for payload: " << required_size
1115 << " bytes, apex decompression: " << apex_size_required
1116 << " bytes";
1117 return required_size + apex_size_required;
1118 }
1119 }
1120
1121 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
1122 !apex_handler_android_->AllocateSpace(apex_infos)) {
1123 LOG(ERROR) << "Insufficient space for apex decompression: "
1124 << apex_size_required << " bytes";
1125 return apex_size_required;
1126 }
1127
1128 LOG(INFO) << "Successfully allocated space for payload.";
1129 return 0;
1130 }
1131
CleanupSuccessfulUpdate(std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,brillo::ErrorPtr * error)1132 void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1133 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
1134 brillo::ErrorPtr* error) {
1135 if (cleanup_previous_update_code_.has_value()) {
1136 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1137 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1138 if (callback) {
1139 callback->OnCleanupComplete(
1140 static_cast<int32_t>(*cleanup_previous_update_code_));
1141 }
1142 return;
1143 }
1144 if (callback) {
1145 auto callback_ptr = callback.get();
1146 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1147 callback_ptr->RegisterForDeathNotifications(
1148 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1149 base::Unretained(this),
1150 base::Unretained(callback_ptr)));
1151 }
1152 ScheduleCleanupPreviousUpdate();
1153 }
1154
setShouldSwitchSlotOnReboot(const std::string & metadata_filename,brillo::ErrorPtr * error)1155 bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1156 const std::string& metadata_filename, brillo::ErrorPtr* error) {
1157 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
1158 if (processor_->IsRunning()) {
1159 return LogAndSetError(
1160 error, FROM_HERE, "Already processing an update, cancel it first.");
1161 }
1162 DeltaArchiveManifest manifest;
1163 TEST_AND_RETURN_FALSE(
1164 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1165
1166 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1167 GetCurrentSlot(),
1168 GetTargetSlot(),
1169 manifest,
1170 false /* should update */,
1171 nullptr)) {
1172 return LogAndSetError(
1173 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1174 }
1175 InstallPlan install_plan_;
1176 install_plan_.source_slot = GetCurrentSlot();
1177 install_plan_.target_slot = GetTargetSlot();
1178 // Don't do verity computation, just hash the partitions
1179 install_plan_.write_verity = false;
1180 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1181 install_plan_.run_post_install = false;
1182 install_plan_.is_resume = true;
1183
1184 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1185 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1186
1187 ErrorCode error_code;
1188 if (!install_plan_.ParsePartitions(manifest.partitions(),
1189 boot_control_,
1190 manifest.block_size(),
1191 &error_code)) {
1192 return LogAndSetError(error,
1193 FROM_HERE,
1194 "Failed to LoadPartitionsFromSlots " +
1195 utils::ErrorCodeToString(error_code));
1196 }
1197
1198 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1199 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1200 boot_control_->GetDynamicPartitionControl());
1201 auto postinstall_runner_action =
1202 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1203 SetStatusAndNotify(UpdateStatus::VERIFYING);
1204 filesystem_verifier_action->set_delegate(this);
1205 postinstall_runner_action->set_delegate(this);
1206
1207 // Bond them together. We have to use the leaf-types when calling
1208 // BondActions().
1209 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1210 BondActions(filesystem_verifier_action.get(),
1211 postinstall_runner_action.get());
1212
1213 processor_->EnqueueAction(std::move(install_plan_action));
1214 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1215 processor_->EnqueueAction(std::move(postinstall_runner_action));
1216 ScheduleProcessingStart();
1217 return true;
1218 }
1219
resetShouldSwitchSlotOnReboot(brillo::ErrorPtr * error)1220 bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1221 brillo::ErrorPtr* error) {
1222 if (processor_->IsRunning()) {
1223 return LogAndSetError(
1224 error, FROM_HERE, "Already processing an update, cancel it first.");
1225 }
1226 // Update the boot flags so the current slot has higher priority.
1227 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1228 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1229 }
1230
1231 // Mark the current slot as successful again, since marking it as active
1232 // may reset the successful bit. We ignore the result of whether marking
1233 // the current slot as successful worked.
1234 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1235 return LogAndSetError(
1236 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1237 }
1238
1239 // Resets the warm reset property since we won't switch the slot.
1240 hardware_->SetWarmReset(false);
1241
1242 // Resets the vbmeta digest.
1243 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1244 LOG(INFO) << "Slot switch cancelled.";
1245 SetStatusAndNotify(UpdateStatus::IDLE);
1246 return true;
1247 }
1248
ScheduleCleanupPreviousUpdate()1249 void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1250 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1251 // is in progress, skip enqueueing the action.
1252 if (processor_->IsRunning()) {
1253 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1254 << "be done when the current update finishes.";
1255 return;
1256 }
1257 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1258 auto action =
1259 boot_control_->GetDynamicPartitionControl()
1260 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1261 processor_->EnqueueAction(std::move(action));
1262 processor_->set_delegate(this);
1263 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1264 processor_->StartProcessing();
1265 }
1266
OnCleanupProgressUpdate(double progress)1267 void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1268 for (auto&& callback : cleanup_previous_update_callbacks_) {
1269 callback->OnCleanupProgressUpdate(progress);
1270 }
1271 }
1272
NotifyCleanupPreviousUpdateCallbacksAndClear()1273 void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1274 CHECK(cleanup_previous_update_code_.has_value());
1275 for (auto&& callback : cleanup_previous_update_callbacks_) {
1276 callback->OnCleanupComplete(
1277 static_cast<int32_t>(*cleanup_previous_update_code_));
1278 }
1279 cleanup_previous_update_callbacks_.clear();
1280 }
1281
RemoveCleanupPreviousUpdateCallback(CleanupSuccessfulUpdateCallbackInterface * callback)1282 void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1283 CleanupSuccessfulUpdateCallbackInterface* callback) {
1284 auto end_it =
1285 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1286 cleanup_previous_update_callbacks_.end(),
1287 [&](const auto& e) { return e.get() == callback; });
1288 cleanup_previous_update_callbacks_.erase(
1289 end_it, cleanup_previous_update_callbacks_.end());
1290 }
1291
1292 } // namespace chromeos_update_engine
1293