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