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