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