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