blob: 267805e2c9251f2e7246f26bee58329f718cf565 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 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//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/payload_consumer/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070020#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include <algorithm>
23#include <cstring>
Yifan Hong537802d2018-08-15 13:15:42 -070024#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Tianjied3865d12020-06-03 15:25:17 -070026#include <set>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027#include <string>
Amin Hassanid87304c2017-08-29 11:40:03 -070028#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029#include <vector>
30
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000031#include <android-base/properties.h>
Kelvin Zhangbdba3542023-02-24 11:08:55 -080032#include <android-base/strings.h>
Ben Chan06c76a42014-09-05 08:21:06 -070033#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070034#include <base/format_macros.h>
Lann Martin39f57142017-07-14 09:18:42 -060035#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070036#include <base/strings/string_number_conversions.h>
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000037#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060038#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070039#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070040#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070041#include <google/protobuf/repeated_field.h>
Amin Hassani02855c22017-09-06 22:34:50 -070042#include <puffin/puffpatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043
Kelvin Zhangbfa10412023-03-17 11:19:14 -070044#include "libsnapshot/cow_format.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080045#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/common/download_action.h"
Yifan Hong87029332020-09-01 17:20:08 -070047#include "update_engine/common/error_code.h"
48#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030050#include "update_engine/common/prefs_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030051#include "update_engine/common/terminator.h"
Kelvin Zhang52cb1d72020-10-27 13:44:25 -040052#include "update_engine/common/utils.h"
Tianjied3865d12020-06-03 15:25:17 -070053#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040054#include "update_engine/payload_consumer/partition_writer.h"
Daniel Zheng730ae9b2022-08-25 22:37:22 +000055#include "update_engine/update_metadata.pb.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070056#if USE_FEC
57#include "update_engine/payload_consumer/fec_file_descriptor.h"
58#endif // USE_FEC
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/payload_consumer/payload_constants.h"
60#include "update_engine/payload_consumer/payload_verifier.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070061
Alex Deymo161c4a12014-05-16 15:56:21 -070062using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070063using std::min;
64using std::string;
65using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066
67namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080068const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
69const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
70const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
71const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070072const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080073
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070074namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070075const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070076const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080077
Alex Vakulenkod2779df2014-06-16 13:19:00 -070078} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079
Gilad Arnold8a86fa52013-01-15 12:35:05 -080080// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
81// arithmetic.
82static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
83 return part * norm / total;
84}
85
86void DeltaPerformer::LogProgress(const char* message_prefix) {
87 // Format operations total count and percentage.
88 string total_operations_str("?");
89 string completed_percentage_str("");
90 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -070091 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -080092 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -080093 completed_percentage_str = base::StringPrintf(
94 " (%" PRIu64 "%%)",
95 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -080096 }
97
98 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -080099 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800100 string payload_size_str("?");
101 string downloaded_percentage_str("");
102 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700103 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800104 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800105 downloaded_percentage_str = base::StringPrintf(
106 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800107 }
108
109 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
110 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800111 << completed_percentage_str << ", " << total_bytes_received_ << "/"
112 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800113 << downloaded_percentage_str << ", overall progress "
114 << overall_progress_ << "%";
115}
116
117void DeltaPerformer::UpdateOverallProgress(bool force_log,
118 const char* message_prefix) {
119 // Compute our download and overall progress.
120 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800121 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
122 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800123 // Only consider download progress if its total size is known; otherwise
124 // adjust the operations weight to compensate for the absence of download
125 // progress. Also, make sure to cap the download portion at
126 // kProgressDownloadWeight, in case we end up downloading more than we
127 // initially expected (this indicates a problem, but could generally happen).
128 // TODO(garnold) the correction of operations weight when we do not have the
129 // total payload size, as well as the conditional guard below, should both be
130 // eliminated once we ensure that the payload_size in the install plan is
131 // always given and is non-zero. This currently isn't the case during unit
132 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800133 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800134 unsigned actual_operations_weight = kProgressOperationsWeight;
135 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800136 new_overall_progress +=
137 min(static_cast<unsigned>(IntRatio(
138 total_bytes_received_, payload_size, kProgressDownloadWeight)),
139 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800140 else
141 actual_operations_weight += kProgressDownloadWeight;
142
143 // Only add completed operations if their total number is known; we definitely
144 // expect an update to have at least one operation, so the expectation is that
145 // this will eventually reach |actual_operations_weight|.
146 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800147 new_overall_progress += IntRatio(
148 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800149
150 // Progress ratio cannot recede, unless our assumptions about the total
151 // payload size, total number of operations, or the monotonicity of progress
152 // is breached.
153 if (new_overall_progress < overall_progress_) {
154 LOG(WARNING) << "progress counter receded from " << overall_progress_
155 << "% down to " << new_overall_progress << "%; this is a bug";
156 force_log = true;
157 }
158 overall_progress_ = new_overall_progress;
159
160 // Update chunk index, log as needed: if forced by called, or we completed a
161 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800162 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800163 unsigned curr_progress_chunk =
164 overall_progress_ * kProgressLogMaxChunks / 100;
165 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
166 curr_time > forced_progress_log_time_) {
167 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
168 LogProgress(message_prefix);
169 }
170 last_progress_chunk_ = curr_progress_chunk;
171}
172
Amin Hassani008c4582019-01-13 16:22:47 -0800173size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
174 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800175 size_t max) {
176 const size_t count = *count_p;
177 if (!count)
178 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700179 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800180 const char* bytes_start = *bytes_p;
181 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800182 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800183 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
184 *bytes_p = bytes_end;
185 *count_p = count - read_len;
186 return read_len;
187}
188
Amin Hassani008c4582019-01-13 16:22:47 -0800189bool DeltaPerformer::HandleOpResult(bool op_result,
190 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800191 ErrorCode* error) {
192 if (op_result)
193 return true;
194
195 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700196 << next_operation_num_ << ", which is the operation "
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400197 << GetPartitionOperationNum() << " in partition \""
Alex Deymo3d009062016-05-13 15:51:25 -0700198 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700199 if (*error == ErrorCode::kSuccess)
200 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800201 return false;
202}
203
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700204int DeltaPerformer::Close() {
Kelvin Zhang42f81b82022-10-04 10:43:08 -0700205 // Checkpoint update progress before canceling, so that subsequent attempts
206 // can resume from exactly where update_engine left last time.
207 CheckpointUpdateProgress(true);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700208 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800209 LOG_IF(ERROR,
210 !payload_hash_calculator_.Finalize() ||
211 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800212 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800213 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700214 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
215 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800216 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800217 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700218 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700219}
220
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700221int DeltaPerformer::CloseCurrentPartition() {
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400222 if (!partition_writer_) {
223 return 0;
224 }
225 int err = partition_writer_->Close();
226 partition_writer_ = nullptr;
227 return err;
228}
229
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700230bool DeltaPerformer::OpenCurrentPartition() {
231 if (current_partition_ >= partitions_.size())
232 return false;
233
234 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700235 size_t num_previous_partitions =
236 install_plan_->partitions.size() - partitions_.size();
237 const InstallPlan::Partition& install_part =
238 install_plan_->partitions[num_previous_partitions + current_partition_];
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400239 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500240 partition_writer_ = CreatePartitionWriter(
241 partition,
242 install_part,
243 dynamic_control,
244 block_size_,
245 interactive_,
246 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Tianjie55abd3c2020-06-19 00:22:59 -0700247 // Open source fds if we have a delta payload, or for partitions in the
248 // partial update.
Kelvin Zhangdf3c1952021-10-06 18:56:55 -0700249 const bool source_may_exist = manifest_.partial_update() ||
250 payload_->type == InstallPayloadType::kDelta;
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400251 const size_t partition_operation_num = GetPartitionOperationNum();
252
253 TEST_AND_RETURN_FALSE(partition_writer_->Init(
254 install_plan_, source_may_exist, partition_operation_num));
255 CheckpointUpdateProgress(true);
256 return true;
257}
258
259size_t DeltaPerformer::GetPartitionOperationNum() {
260 return next_operation_num_ -
261 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400262}
263
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700264namespace {
265
266void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Kelvin Zhang3fe49642021-10-04 15:35:02 -0700267 string sha256 = HexEncode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800268 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
269 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700270}
271
Alex Deymo39910dc2015-11-09 17:04:30 -0800272void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700273 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800274 if (partition.has_old_partition_info()) {
275 LogPartitionInfoHash(partition.old_partition_info(),
276 "old " + partition.partition_name());
277 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700278 LogPartitionInfoHash(partition.new_partition_info(),
279 "new " + partition.partition_name());
280 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700281}
282
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700283} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700284
Sen Jiangb8060e42015-09-24 17:30:50 -0700285bool DeltaPerformer::IsHeaderParsed() const {
286 return metadata_size_ != 0;
287}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700288
Sen Jiang9c89e842018-02-02 13:51:21 -0800289MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700290 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700291 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700292
Sen Jiangb8060e42015-09-24 17:30:50 -0700293 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700294 MetadataParseResult result =
295 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800296 if (result != MetadataParseResult::kSuccess)
297 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700298
Sen Jiang9c89e842018-02-02 13:51:21 -0800299 metadata_size_ = payload_metadata_.GetMetadataSize();
300 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
301 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800302
303 // If the metadata size is present in install plan, check for it immediately
304 // even before waiting for that many number of bytes to be downloaded in the
305 // payload. This will prevent any attack which relies on us downloading data
306 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800307 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800308 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800309 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800310 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800311 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700312 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800313 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800314 }
315 }
Andrew3a7dc262019-12-19 11:38:08 -0800316
317 // Check that the |metadata signature size_| and |metadata_size_| are not
318 // very big numbers. This is necessary since |update_engine| needs to write
319 // these values into the buffer before being able to use them, and if an
320 // attacker sets these values to a very big number, the buffer will overflow
321 // and |update_engine| will crash. A simple way of solving this is to check
322 // that the size of both values is smaller than the payload itself.
323 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
324 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
325 << " or metadata signature(" << metadata_signature_size_ << ")"
326 << " is greater than the size of the payload"
327 << "(" << payload_->size << ")";
328 *error = ErrorCode::kDownloadInvalidMetadataSize;
329 return MetadataParseResult::kError;
330 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700331 }
332
333 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700334 // metadata and its signature (if exist) to be read in before we can parse it.
335 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800336 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337
338 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700339 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700340 // that we just log once (instead of logging n times) if it takes n
341 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800342 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700343 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800344 } else {
345 // For mandatory-cases, we'd have already returned a kMetadataParseError
346 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
347 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800348 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800349 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800350 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800351 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700352
Amin Hassaniec7bc112020-10-29 16:47:58 -0700353 // NOLINTNEXTLINE(whitespace/braces)
Tianjie Xu7a78d632019-10-08 16:32:39 -0700354 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
355 if (!payload_verifier) {
356 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800357 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700358 if (perform_verification) {
359 return MetadataParseResult::kError;
360 }
361 } else {
362 // We have the full metadata in |payload|. Verify its integrity
363 // and authenticity based on the information we have in Omaha response.
364 *error = payload_metadata_.ValidateMetadataSignature(
365 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800366 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700367 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800368 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800369 // The autoupdate_CatchBadSignatures test checks for this string
370 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800371 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800372 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800373 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700374
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800375 // For non-mandatory cases, just send a UMA stat.
376 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700377 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700378 }
379
Gilad Arnolddaa27402014-01-23 11:56:17 -0800380 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800381 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800382 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700383 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800384 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800385 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800386
387 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800388 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800389}
390
Tianjie8e0090d2021-08-30 22:35:21 -0700391#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
392 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
393 "UpdateEngine.DownloadAction.InstallOperation::" + string(_op_name) + \
394 ".Duration", \
395 (base::TimeTicks::Now() - _start_time), \
396 base::TimeDelta::FromMilliseconds(10), \
397 base::TimeDelta::FromMinutes(5), \
Amin Hassani008c4582019-01-13 16:22:47 -0800398 20);
Lann Martin39f57142017-07-14 09:18:42 -0600399
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800400bool DeltaPerformer::CheckSPLDowngrade() {
Kelvin Zhanga10fd5a2022-09-01 23:39:39 +0000401 if (!manifest_.has_security_patch_level()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800402 return true;
Kelvin Zhanga10fd5a2022-09-01 23:39:39 +0000403 }
Kelvin Zhang862c46c2022-09-02 17:01:12 +0000404 if (manifest_.security_patch_level().empty()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800405 return true;
Kelvin Zhang862c46c2022-09-02 17:01:12 +0000406 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000407 const auto new_spl = manifest_.security_patch_level();
408 const auto current_spl =
409 android::base::GetProperty("ro.build.version.security_patch", "");
410 if (current_spl.empty()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800411 LOG(WARNING) << "Failed to get ro.build.version.security_patch, unable to "
412 "determine if this OTA is a SPL downgrade. Assuming this "
413 "OTA is not SPL downgrade.";
414 return true;
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000415 }
416 if (new_spl < current_spl) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800417 const auto avb_state =
418 android::base::GetProperty("ro.boot.verifiedbootstate", "green");
419 if (android::base::EqualsIgnoreCase(avb_state, "green")) {
420 LOG(ERROR) << "Target build SPL " << new_spl
421 << " is older than current build's SPL " << current_spl
422 << ", this OTA is an SPL downgrade. Your device's "
423 "ro.boot.verifiedbootstate="
424 << avb_state
425 << ", it probably has a locked bootlaoder. Since a locked "
426 "bootloader will reject SPL downgrade no matter what, we "
427 "will reject this OTA.";
428 return false;
429 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000430 install_plan_->powerwash_required = true;
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800431 LOG(WARNING)
432 << "Target build SPL " << new_spl
433 << " is older than current build's SPL " << current_spl
434 << ", this OTA is an SPL downgrade. Data wipe will be required";
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000435 }
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800436 return true;
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000437}
438
Don Garrette410e0f2011-11-10 15:39:01 -0800439// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800440// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700441// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800442bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Daniel Zhengeede4c82023-06-13 11:21:06 -0700443 if (!error) {
444 return false;
445 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700446 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700447 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800448
449 // Update the total byte downloaded count and the progress logs.
450 total_bytes_received_ += count;
451 UpdateOverallProgress(false, "Completed ");
452
Gilad Arnoldfe133932014-01-14 12:25:50 -0800453 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700454 // Read data up to the needed limit; this is either maximium payload header
455 // size, or the full metadata size (once it becomes known).
456 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800457 CopyDataToBuffer(
458 &c_bytes,
459 &count,
460 (do_read_header ? kMaxPayloadHeaderSize
461 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800462
Gilad Arnolddaa27402014-01-23 11:56:17 -0800463 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800464 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800465 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800466 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800467 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700468 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800469 continue;
470
Don Garrette410e0f2011-11-10 15:39:01 -0800471 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800472 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700473
474 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700475 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700476 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800477 manifest_valid_ = true;
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400478 if (!install_plan_->is_resume) {
Kelvin Zhangcf4600e2020-10-27 15:50:33 -0400479 auto begin = reinterpret_cast<const char*>(buffer_.data());
480 prefs_->SetString(kPrefsManifestBytes, {begin, buffer_.size()});
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400481 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700482
Gilad Arnoldfe133932014-01-14 12:25:50 -0800483 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800484 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700485
Sen Jiang57f91802017-11-14 17:42:13 -0800486 block_size_ = manifest_.block_size();
487
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800488 if (!CheckSPLDowngrade()) {
489 *error = ErrorCode::kPayloadTimestampError;
490 return false;
491 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000492
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000493 // update estimate_cow_size if VABC is disabled
494 // new_cow_size per partition = partition_size - (#blocks in Copy
495 // operations part of the partition)
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700496 if (install_plan_->vabc_none) {
497 LOG(INFO) << "Setting Virtual AB Compression algorithm to none";
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000498 manifest_.mutable_dynamic_partition_metadata()
499 ->set_vabc_compression_param("none");
500 for (auto& partition : *manifest_.mutable_partitions()) {
Daniel Zhengd4806f82022-12-19 18:22:20 +0000501 auto new_cow_size = partition.new_partition_info().size();
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000502 for (const auto& operation : partition.merge_operations()) {
503 if (operation.type() == CowMergeOperation::COW_COPY) {
504 new_cow_size -=
505 operation.dst_extent().num_blocks() * manifest_.block_size();
506 }
507 }
Kelvin Zhangbfa10412023-03-17 11:19:14 -0700508 // Every block written to COW device will come with a header which
509 // stores src/dst block info along with other data.
510 const auto cow_metadata_size = partition.new_partition_info().size() /
511 manifest_.block_size() *
512 sizeof(android::snapshot::CowOperation);
513 // update_engine will emit a label op every op or every two seconds,
514 // whichever one is longer. In the worst case, we add 1 label per
515 // InstallOp. So take size of label ops into account.
516 const auto label_ops_size = partition.operations_size() *
517 sizeof(android::snapshot::CowOperation);
518 // Adding extra 2MB headroom just for any unexpected space usage.
519 // If we overrun reserved COW size, entire OTA will fail
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000520 // and no way for user to retry OTA
Kelvin Zhangbfa10412023-03-17 11:19:14 -0700521 partition.set_estimate_cow_size(new_cow_size + (1024 * 1024 * 2) +
522 cow_metadata_size + label_ops_size);
523 LOG(INFO) << "New COW size for partition " << partition.partition_name()
524 << " is " << partition.estimate_cow_size();
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000525 }
526 }
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000527 if (install_plan_->disable_vabc) {
528 manifest_.mutable_dynamic_partition_metadata()->set_vabc_enabled(false);
529 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800530 if (install_plan_->enable_threading) {
531 manifest_.mutable_dynamic_partition_metadata()
532 ->mutable_vabc_feature_set()
533 ->set_threaded(true);
534 LOG(INFO) << "Attempting to enable multi-threaded compression for VABC";
535 }
536 if (install_plan_->batched_writes) {
537 manifest_.mutable_dynamic_partition_metadata()
538 ->mutable_vabc_feature_set()
539 ->set_batch_writes(true);
540 LOG(INFO) << "Attempting to enable batched writes for VABC";
541 }
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000542
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700543 // This populates |partitions_| and the |install_plan.partitions| with the
544 // list of partitions from the manifest.
545 if (!ParseManifestPartitions(error))
546 return false;
547
Sen Jiang5ae865b2017-04-18 14:24:40 -0700548 // |install_plan.partitions| was filled in, nothing need to be done here if
549 // the payload was already applied, returns false to terminate http fetcher,
550 // but keep |error| as ErrorCode::kSuccess.
551 if (payload_->already_applied)
552 return false;
553
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700554 num_total_operations_ = 0;
555 for (const auto& partition : partitions_) {
556 num_total_operations_ += partition.operations_size();
557 acc_num_operations_.push_back(num_total_operations_);
558 }
559
Amin Hassani008c4582019-01-13 16:22:47 -0800560 LOG_IF(WARNING,
561 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700562 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800563 LOG_IF(WARNING,
564 !prefs_->SetInt64(kPrefsManifestSignatureSize,
565 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800566 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700567
Darin Petkov9b230572010-10-08 10:20:09 -0700568 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700569 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700570 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800571 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700572 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800573
Yifan Hong537802d2018-08-15 13:15:42 -0700574 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
575 if (!OpenCurrentPartition()) {
576 *error = ErrorCode::kInstallDeviceOpenError;
577 return false;
578 }
Allie Woodfdf00512015-03-02 13:34:55 -0800579 }
580
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800581 if (next_operation_num_ > 0)
582 UpdateOverallProgress(true, "Resuming after ");
583 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700584 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800585
586 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700587 // Check if we should cancel the current attempt for any reason.
588 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700589 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300590 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700591 return false;
592
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700593 // We know there are more operations to perform because we didn't reach the
594 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700595 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400596 if (partition_writer_) {
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700597 if (!partition_writer_->FinishedInstallOps()) {
598 *error = ErrorCode::kDownloadWriteError;
599 return false;
600 }
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400601 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700602 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700603 // Skip until there are operations for current_partition_.
604 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
605 current_partition_++;
606 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700607 if (!OpenCurrentPartition()) {
608 *error = ErrorCode::kInstallDeviceOpenError;
609 return false;
610 }
611 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700612
Alex Deymoa12ee112015-08-12 22:19:32 -0700613 const InstallOperation& op =
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400614 partitions_[current_partition_].operations(GetPartitionOperationNum());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800615
616 CopyDataToBuffer(&c_bytes, &count, op.data_length());
617
618 // Check whether we received all of the next operation's data payload.
619 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700620 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700621
Tianjie1205ea62020-07-09 17:04:28 -0700622 // Validate the operation unconditionally. This helps prevent the
623 // exploitation of vulnerabilities in the patching libraries, e.g. bspatch.
624 // The hash of the patch data for a given operation is embedded in the
625 // payload metadata; and thus has been verified against the public key on
626 // device.
627 // Note: Validate must be called only if CanPerformInstallOperation is
628 // called. Otherwise, we might be failing operations before even if there
629 // isn't sufficient data to compute the proper hash.
630 *error = ValidateOperationHash(op);
631 if (*error != ErrorCode::kSuccess) {
632 if (install_plan_->hash_checks_mandatory) {
633 LOG(ERROR) << "Mandatory operation hash check failed";
634 return false;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700635 }
Tianjie1205ea62020-07-09 17:04:28 -0700636
637 // For non-mandatory cases, just send a UMA stat.
638 LOG(WARNING) << "Ignoring operation validation errors";
639 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700640 }
641
Darin Petkov45580e42010-10-08 14:02:40 -0700642 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700643 ScopedTerminatorExitUnblocker exit_unblocker =
644 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800645
Lann Martin39f57142017-07-14 09:18:42 -0600646 base::TimeTicks op_start_time = base::TimeTicks::Now();
647
Daniel Zhengda4f7292022-09-02 22:59:32 +0000648 bool op_result{};
Tianjie8e0090d2021-08-30 22:35:21 -0700649 const string op_name = InstallOperationTypeName(op.type());
Alex Deymo2d621a32015-10-01 11:09:01 -0700650 switch (op.type()) {
651 case InstallOperation::REPLACE:
652 case InstallOperation::REPLACE_BZ:
653 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700654 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600655 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700656 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700657 case InstallOperation::ZERO:
658 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700659 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600660 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700661 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700662 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700663 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600664 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700665 break;
666 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800667 case InstallOperation::BROTLI_BSDIFF:
Amin Hassani49fdb092017-08-04 13:10:59 -0700668 case InstallOperation::PUFFDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700669 case InstallOperation::ZUCCHINI:
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800670 case InstallOperation::LZ4DIFF_PUFFDIFF:
671 case InstallOperation::LZ4DIFF_BSDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700672 op_result = PerformDiffOperation(op, error);
673 OP_DURATION_HISTOGRAM(op_name, op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800674 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700675 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700676 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700677 }
Tianjie8e0090d2021-08-30 22:35:21 -0700678 if (!HandleOpResult(op_result, op_name.c_str(), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800679 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800680
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700681 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800682 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800683 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700684 }
Sen Jiangf6813802015-11-03 21:27:29 -0800685
Kelvin Zhang4f28a6c2021-01-14 14:04:57 -0500686 if (partition_writer_) {
687 TEST_AND_RETURN_FALSE(partition_writer_->FinishedInstallOps());
688 }
689 CloseCurrentPartition();
690
Saint Chou0a92a622020-07-29 14:25:35 +0000691 // In major version 2, we don't add unused operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800692 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000693 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800694 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800695 if (manifest_.signatures_offset() != buffer_offset_) {
696 LOG(ERROR) << "Payload signatures offset points to blob offset "
697 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800698 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800699 *error = ErrorCode::kDownloadPayloadVerificationError;
700 return false;
701 }
702 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
703 // Needs more data to cover entire signature.
704 if (buffer_.size() < manifest_.signatures_size())
705 return true;
706 if (!ExtractSignatureMessage()) {
707 LOG(ERROR) << "Extract payload signature failed.";
708 *error = ErrorCode::kDownloadPayloadVerificationError;
709 return false;
710 }
711 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800712 // Since we extracted the SignatureMessage we need to advance the
713 // checkpoint, otherwise we would reload the signature and try to extract
714 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800715 // This is the last checkpoint for an update, force this checkpoint to be
716 // saved.
717 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800718 }
719
Don Garrette410e0f2011-11-10 15:39:01 -0800720 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700721}
722
David Zeuthen8f191b22013-08-06 12:27:50 -0700723bool DeltaPerformer::IsManifestValid() {
724 return manifest_valid_;
725}
726
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700727bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700728 partitions_.assign(manifest_.partitions().begin(),
729 manifest_.partitions().end());
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700730
Tianjied3865d12020-06-03 15:25:17 -0700731 // For VAB and partial updates, the partition preparation will copy the
732 // dynamic partitions metadata to the target metadata slot, and rename the
733 // slot suffix of the partitions in the metadata.
734 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
735 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -0700736 if (!PreparePartitionsForUpdate(&required_size, error)) {
737 if (*error == ErrorCode::kOverlayfsenabledError) {
738 return false;
739 } else if (required_size > 0) {
Tianjied3865d12020-06-03 15:25:17 -0700740 *error = ErrorCode::kNotEnoughSpace;
741 } else {
742 *error = ErrorCode::kInstallDeviceOpenError;
743 }
744 return false;
745 }
746 }
747
Tianjie55abd3c2020-06-19 00:22:59 -0700748 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000749 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700750 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
751 // partition.
752 if (manifest_.partial_update()) {
753 std::set<std::string> touched_partitions;
754 for (const auto& partition_update : partitions_) {
755 touched_partitions.insert(partition_update.partition_name());
756 }
757
Tianjie99d570d2020-06-04 14:57:19 -0700758 auto generator = partition_update_generator::Create(boot_control_,
759 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700760 std::vector<PartitionUpdate> untouched_static_partitions;
Kelvin Zhang430852d2023-05-25 17:00:24 -0700761 if (!generator->GenerateOperationsForPartitionsNotInPayload(
Tianjied3865d12020-06-03 15:25:17 -0700762 install_plan_->source_slot,
763 install_plan_->target_slot,
764 touched_partitions,
Kelvin Zhang430852d2023-05-25 17:00:24 -0700765 &untouched_static_partitions)) {
766 LOG(ERROR)
767 << "Failed to generate operations for partitions not in payload "
768 << android::base::Join(touched_partitions, ", ");
769 *error = ErrorCode::kDownloadStateInitializationError;
770 return false;
771 }
Tianjie24f96092020-06-30 12:26:25 -0700772 partitions_.insert(partitions_.end(),
773 untouched_static_partitions.begin(),
774 untouched_static_partitions.end());
775
776 // Save the untouched dynamic partitions in install plan.
777 std::vector<std::string> dynamic_partitions;
778 if (!boot_control_->GetDynamicPartitionControl()
779 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
Tianjie3a55fc22021-02-13 16:02:22 -0800780 boot_control_->GetCurrentSlot(),
Tianjie24f96092020-06-30 12:26:25 -0700781 &dynamic_partitions)) {
782 LOG(ERROR) << "Failed to load dynamic partitions from slot "
783 << install_plan_->source_slot;
784 return false;
785 }
786 install_plan_->untouched_dynamic_partitions.clear();
787 for (const auto& name : dynamic_partitions) {
788 if (touched_partitions.find(name) == touched_partitions.end()) {
789 install_plan_->untouched_dynamic_partitions.push_back(name);
790 }
791 }
Tianjied3865d12020-06-03 15:25:17 -0700792 }
793
Kelvin Zhang20982a52021-08-13 12:31:16 -0700794 if (!install_plan_->ParsePartitions(
795 partitions_, boot_control_, block_size_, error)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700796 return false;
797 }
Kelvin Zhangab15beb2022-12-05 10:19:52 -0800798 auto&& has_verity = [](const auto& part) {
799 return part.fec_extent().num_blocks() > 0 ||
800 part.hash_tree_extent().num_blocks() > 0;
801 };
802 if (!std::any_of(partitions_.begin(), partitions_.end(), has_verity)) {
803 install_plan_->write_verity = false;
804 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700805
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700806 LogPartitionInfo(partitions_);
807 return true;
808}
809
Daniel Zhengeede4c82023-06-13 11:21:06 -0700810bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size,
811 ErrorCode* error) {
Yifan Hongb9d63572020-01-09 17:50:46 -0800812 // Call static PreparePartitionsForUpdate with hash from
813 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
814 // preallocated for is the same as the hash of payload being applied.
815 string update_check_response_hash;
816 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
817 &update_check_response_hash));
818 return PreparePartitionsForUpdate(prefs_,
819 boot_control_,
820 install_plan_->target_slot,
821 manifest_,
822 update_check_response_hash,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700823 required_size,
824 error);
Yifan Hongb9d63572020-01-09 17:50:46 -0800825}
826
827bool DeltaPerformer::PreparePartitionsForUpdate(
828 PrefsInterface* prefs,
829 BootControlInterface* boot_control,
830 BootControlInterface::Slot target_slot,
831 const DeltaArchiveManifest& manifest,
832 const std::string& update_check_response_hash,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700833 uint64_t* required_size,
834 ErrorCode* error) {
Yifan Hongb9d63572020-01-09 17:50:46 -0800835 string last_hash;
836 ignore_result(
837 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
838
839 bool is_resume = !update_check_response_hash.empty() &&
840 last_hash == update_check_response_hash;
841
842 if (is_resume) {
843 LOG(INFO) << "Using previously prepared partitions for update. hash = "
844 << last_hash;
845 } else {
846 LOG(INFO) << "Preparing partitions for new update. last hash = "
847 << last_hash << ", new hash = " << update_check_response_hash;
Kelvin Zhang51e08b92021-02-19 14:54:21 -0500848 ResetUpdateProgress(prefs, false);
Yifan Hongb9d63572020-01-09 17:50:46 -0800849 }
850
851 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
852 boot_control->GetCurrentSlot(),
853 target_slot,
854 manifest,
855 !is_resume /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700856 required_size,
857 error)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700858 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Daniel Zhengeede4c82023-06-13 11:21:06 -0700859 << BootControlInterface::SlotName(target_slot) << " "
860 << utils::ErrorCodeToString(*error);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700861 return false;
862 }
Yifan Hongb9d63572020-01-09 17:50:46 -0800863
864 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
865 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -0700866 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700867
868 return true;
869}
870
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700871bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700872 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700873 // If we don't have a data blob we can apply it right away.
874 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700875 return true;
876
877 // See if we have the entire data blob in the buffer
878 if (operation.data_offset() < buffer_offset_) {
879 LOG(ERROR) << "we threw away data it seems?";
880 return false;
881 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700882
Gilad Arnoldfe133932014-01-14 12:25:50 -0800883 return (operation.data_offset() + operation.data_length() <=
884 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700885}
886
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700887bool DeltaPerformer::PerformReplaceOperation(
888 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700889 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700890 operation.type() == InstallOperation::REPLACE_BZ ||
891 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700892
893 // Since we delete data off the beginning of the buffer as we use it,
894 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700895 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700896
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400897 TEST_AND_RETURN_FALSE(partition_writer_->PerformReplaceOperation(
898 operation, buffer_.data(), buffer_.size()));
899 // Update buffer
900 DiscardBuffer(true, buffer_.size());
901 return true;
902}
903
Alex Deymo79715ad2015-10-02 14:27:53 -0700904bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700905 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700906 CHECK(operation.type() == InstallOperation::DISCARD ||
907 operation.type() == InstallOperation::ZERO);
908
909 // These operations have no blob.
910 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
911 TEST_AND_RETURN_FALSE(!operation.has_data_length());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400912
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400913 return partition_writer_->PerformZeroOrDiscardOperation(operation);
914}
Alex Deymo79715ad2015-10-02 14:27:53 -0700915
Allie Wood9f6f0a52015-03-30 11:25:47 -0700916bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700917 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700918 if (operation.has_src_length())
919 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
920 if (operation.has_dst_length())
921 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400922 return partition_writer_->PerformSourceCopyOperation(operation, error);
923}
Allie Wood9f6f0a52015-03-30 11:25:47 -0700924
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700925bool DeltaPerformer::ExtentsToBsdiffPositionsString(
926 const RepeatedPtrField<Extent>& extents,
927 uint64_t block_size,
928 uint64_t full_length,
929 string* positions_string) {
930 string ret;
931 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700932 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700933 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100934 uint64_t this_length =
935 min(full_length - length,
936 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700937 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700938 length += this_length;
939 }
940 TEST_AND_RETURN_FALSE(length == full_length);
941 if (!ret.empty())
942 ret.resize(ret.size() - 1); // Strip trailing comma off
943 *positions_string = ret;
944 return true;
945}
946
Tianjie8e0090d2021-08-30 22:35:21 -0700947bool DeltaPerformer::PerformDiffOperation(const InstallOperation& operation,
948 ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700949 // Since we delete data off the beginning of the buffer as we use it,
950 // the data we need should be exactly at the beginning of the buffer.
951 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
952 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
953 if (operation.has_src_length())
954 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
955 if (operation.has_dst_length())
956 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
957
Tianjie8e0090d2021-08-30 22:35:21 -0700958 TEST_AND_RETURN_FALSE(partition_writer_->PerformDiffOperation(
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400959 operation, error, buffer_.data(), buffer_.size()));
960 DiscardBuffer(true, buffer_.size());
961 return true;
962}
Amin Hassani02855c22017-09-06 22:34:50 -0700963
Sen Jiangf6813802015-11-03 21:27:29 -0800964bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700965 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
966 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
967 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700968 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -0800969 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700970
Darin Petkovd7061ab2010-10-06 14:37:09 -0700971 LOG(INFO) << "Extracted signature data of size "
972 << manifest_.signatures_size() << " at "
973 << manifest_.signatures_offset();
974 return true;
975}
976
Sen Jiang08c6da12019-01-07 18:28:56 -0800977bool DeltaPerformer::GetPublicKey(string* out_public_key) {
978 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -0700979
Sen Jiang08c6da12019-01-07 18:28:56 -0800980 if (utils::FileExists(public_key_path_.c_str())) {
981 LOG(INFO) << "Verifying using public key: " << public_key_path_;
982 return utils::ReadFile(public_key_path_, out_public_key);
983 }
984
Kelvin Zhang50bac652020-09-28 15:51:41 -0400985 // If this is an official build then we are not allowed to use public key
986 // from Omaha response.
Sen Jiang08c6da12019-01-07 18:28:56 -0800987 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
988 LOG(INFO) << "Verifying using public key from Omaha response.";
989 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
990 out_public_key);
991 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700992 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -0700993 return true;
994}
995
Tianjie Xu7a78d632019-10-08 16:32:39 -0700996std::pair<std::unique_ptr<PayloadVerifier>, bool>
997DeltaPerformer::CreatePayloadVerifier() {
998 if (utils::FileExists(update_certificates_path_.c_str())) {
999 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1000 return {
1001 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1002 true};
1003 }
1004
1005 string public_key;
1006 if (!GetPublicKey(&public_key)) {
1007 LOG(ERROR) << "Failed to read public key";
1008 return {nullptr, true};
1009 }
1010
1011 // Skips the verification if the public key is empty.
1012 if (public_key.empty()) {
1013 return {nullptr, false};
1014 }
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001015 LOG(INFO) << "Verifing using public key: " << public_key;
Tianjie Xu7a78d632019-10-08 16:32:39 -07001016 return {PayloadVerifier::CreateInstance(public_key), true};
1017}
1018
Gilad Arnold21504f02013-05-24 08:51:22 -07001019ErrorCode DeltaPerformer::ValidateManifest() {
Saint Chou0a92a622020-07-29 14:25:35 +00001020 // Perform assorted checks to validation check the manifest, make sure it
Don Garrettb8dd1d92013-11-22 17:40:02 -08001021 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +00001022 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
1023 manifest_.partitions().end(),
1024 [](const PartitionUpdate& partition) {
1025 return partition.has_old_partition_info();
1026 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001027
Alex Deymo64d98782016-02-05 18:03:48 -08001028 // The presence of an old partition hash is the sole indicator for a delta
Tianjief5baff42020-07-17 21:43:22 -07001029 // update. Also, always treat the partial update as delta so that we can
1030 // perform the minor version check correctly.
Alex Deymo64d98782016-02-05 18:03:48 -08001031 InstallPayloadType actual_payload_type =
Tianjief5baff42020-07-17 21:43:22 -07001032 (has_old_fields || manifest_.partial_update())
1033 ? InstallPayloadType::kDelta
1034 : InstallPayloadType::kFull;
Alex Deymo64d98782016-02-05 18:03:48 -08001035
Sen Jiangcdd52062017-05-18 15:33:10 -07001036 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001037 LOG(INFO) << "Detected a '"
1038 << InstallPayloadTypeToString(actual_payload_type)
1039 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001040 payload_->type = actual_payload_type;
1041 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001042 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001043 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001044 << "' payload but the downloaded manifest contains a '"
1045 << InstallPayloadTypeToString(actual_payload_type)
1046 << "' payload.";
1047 return ErrorCode::kPayloadMismatchedType;
1048 }
Alex Deymo64d98782016-02-05 18:03:48 -08001049 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001050 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001051 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001052 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1053 LOG(ERROR) << "Manifest contains minor version "
1054 << manifest_.minor_version()
1055 << ", but all full payloads should have version "
1056 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001057 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001058 }
1059 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001060 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1061 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001062 LOG(ERROR) << "Manifest contains minor version "
1063 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001064 << " not in the range of supported minor versions ["
1065 << kMinSupportedMinorPayloadVersion << ", "
1066 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001068 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001069 }
1070
Yifan Hong87029332020-09-01 17:20:08 -07001071 ErrorCode error_code = CheckTimestampError();
1072 if (error_code != ErrorCode::kSuccess) {
1073 if (error_code == ErrorCode::kPayloadTimestampError) {
1074 if (!hardware_->AllowDowngrade()) {
1075 return ErrorCode::kPayloadTimestampError;
1076 }
1077 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1078 " the payload with an older timestamp.";
1079 } else {
1080 LOG(ERROR) << "Timestamp check returned "
1081 << utils::ErrorCodeToString(error_code);
1082 return error_code;
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001083 }
Sen Jiang8e768e92017-06-28 17:13:19 -07001084 }
1085
Amin Hassani55c75412019-10-07 11:20:39 -07001086 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1087 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001088
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001090}
1091
Yifan Hong87029332020-09-01 17:20:08 -07001092ErrorCode DeltaPerformer::CheckTimestampError() const {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001093 bool is_partial_update =
1094 manifest_.has_partial_update() && manifest_.partial_update();
1095 const auto& partitions = manifest_.partitions();
Yifan Hong87029332020-09-01 17:20:08 -07001096
1097 // Check version field for a given PartitionUpdate object. If an error
1098 // is encountered, set |error_code| accordingly. If downgrade is detected,
Kelvin Zhang50bac652020-09-28 15:51:41 -04001099 // |downgrade_detected| is set. Return true if the program should continue
1100 // to check the next partition or not, or false if it should exit early due
1101 // to errors.
Yifan Hong87029332020-09-01 17:20:08 -07001102 auto&& timestamp_valid = [this](const PartitionUpdate& partition,
1103 bool allow_empty_version,
1104 bool* downgrade_detected) -> ErrorCode {
Tianjie19e55292020-10-19 21:49:37 -07001105 const auto& partition_name = partition.partition_name();
Yifan Hong87029332020-09-01 17:20:08 -07001106 if (!partition.has_version()) {
Tianjie19e55292020-10-19 21:49:37 -07001107 if (hardware_->GetVersionForLogging(partition_name).empty()) {
1108 LOG(INFO) << partition_name << " does't have version, skipping "
1109 << "downgrade check.";
1110 return ErrorCode::kSuccess;
1111 }
1112
Yifan Hong87029332020-09-01 17:20:08 -07001113 if (allow_empty_version) {
1114 return ErrorCode::kSuccess;
1115 }
1116 LOG(ERROR)
Tianjie19e55292020-10-19 21:49:37 -07001117 << "PartitionUpdate " << partition_name
1118 << " doesn't have a version field. Not allowed in partial updates.";
Yifan Hong87029332020-09-01 17:20:08 -07001119 return ErrorCode::kDownloadManifestParseError;
1120 }
1121
Tianjie19e55292020-10-19 21:49:37 -07001122 auto error_code =
1123 hardware_->IsPartitionUpdateValid(partition_name, partition.version());
Yifan Hong87029332020-09-01 17:20:08 -07001124 switch (error_code) {
1125 case ErrorCode::kSuccess:
1126 break;
1127 case ErrorCode::kPayloadTimestampError:
1128 *downgrade_detected = true;
Tianjie19e55292020-10-19 21:49:37 -07001129 LOG(WARNING) << "PartitionUpdate " << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001130 << " has an older version than partition on device.";
1131 break;
1132 default:
Tianjie19e55292020-10-19 21:49:37 -07001133 LOG(ERROR) << "IsPartitionUpdateValid(" << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001134 << ") returned" << utils::ErrorCodeToString(error_code);
1135 break;
1136 }
1137 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001138 };
Yifan Hong87029332020-09-01 17:20:08 -07001139
1140 bool downgrade_detected = false;
1141
Kelvin Zhangd7191032020-08-11 10:48:16 -04001142 if (is_partial_update) {
1143 // for partial updates, all partition MUST have valid timestamps
1144 // But max_timestamp can be empty
1145 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001146 auto error_code = timestamp_valid(
1147 partition, false /* allow_empty_version */, &downgrade_detected);
1148 if (error_code != ErrorCode::kSuccess &&
1149 error_code != ErrorCode::kPayloadTimestampError) {
1150 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001151 }
1152 }
Yifan Hong87029332020-09-01 17:20:08 -07001153 if (downgrade_detected) {
1154 return ErrorCode::kPayloadTimestampError;
1155 }
1156 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001157 }
Yifan Hong87029332020-09-01 17:20:08 -07001158
1159 // For non-partial updates, check max_timestamp first.
Kelvin Zhangd7191032020-08-11 10:48:16 -04001160 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1161 LOG(ERROR) << "The current OS build timestamp ("
1162 << hardware_->GetBuildTimestamp()
1163 << ") is newer than the maximum timestamp in the manifest ("
1164 << manifest_.max_timestamp() << ")";
Yifan Hong87029332020-09-01 17:20:08 -07001165 return ErrorCode::kPayloadTimestampError;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001166 }
1167 // Otherwise... partitions can have empty timestamps.
1168 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001169 auto error_code = timestamp_valid(
1170 partition, true /* allow_empty_version */, &downgrade_detected);
1171 if (error_code != ErrorCode::kSuccess &&
1172 error_code != ErrorCode::kPayloadTimestampError) {
1173 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001174 }
1175 }
Yifan Hong87029332020-09-01 17:20:08 -07001176 if (downgrade_detected) {
1177 return ErrorCode::kPayloadTimestampError;
1178 }
1179 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001180}
1181
David Zeuthena99981f2013-04-29 13:42:47 -07001182ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001183 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001184 if (!operation.data_sha256_hash().size()) {
1185 if (!operation.data_length()) {
Kelvin Zhang50bac652020-09-28 15:51:41 -04001186 // Operations that do not have any data blob won't have any operation
1187 // hash either. So, these operations are always considered validated
1188 // since the metadata that contains all the non-data-blob portions of
1189 // the operation has already been validated. This is true for both HTTP
1190 // and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001191 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001192 }
1193
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001194 // No hash is present for an operation that has data blobs. This shouldn't
1195 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001196 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001197 // hashes. So if it happens it means either we've turned operation hash
1198 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Saint Chou0a92a622020-07-29 14:25:35 +00001199 // One caveat though: The last operation is a unused signature operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001200 // that doesn't have a hash at the time the manifest is created. So we
1201 // should not complaint about that operation. This operation can be
1202 // recognized by the fact that it's offset is mentioned in the manifest.
1203 if (manifest_.signatures_offset() &&
1204 manifest_.signatures_offset() == operation.data_offset()) {
1205 LOG(INFO) << "Skipping hash verification for signature operation "
1206 << next_operation_num_ + 1;
1207 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001208 if (install_plan_->hash_checks_mandatory) {
1209 LOG(ERROR) << "Missing mandatory operation hash for operation "
1210 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001211 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001212 }
1213
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001214 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1215 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001216 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001217 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001218 }
1219
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001220 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001221 expected_op_hash.assign(operation.data_sha256_hash().data(),
1222 (operation.data_sha256_hash().data() +
1223 operation.data_sha256_hash().size()));
1224
Sen Jiang2703ef42017-03-16 13:36:21 -07001225 brillo::Blob calculated_op_hash;
1226 if (!HashCalculator::RawHashOfBytes(
1227 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001228 LOG(ERROR) << "Unable to compute actual hash of operation "
1229 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001230 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 }
1232
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001233 if (calculated_op_hash != expected_op_hash) {
1234 LOG(ERROR) << "Hash verification failed for operation "
Kelvin Zhangb9368922022-03-17 21:11:32 -07001235 << next_operation_num_
1236 << ". Expected hash = " << HexEncode(expected_op_hash);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001237 LOG(ERROR) << "Calculated hash over " << operation.data_length()
Kelvin Zhangb9368922022-03-17 21:11:32 -07001238 << " bytes at offset: " << operation.data_offset() << " = "
1239 << HexEncode(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001241 }
1242
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001243 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001244}
1245
Amin Hassani008c4582019-01-13 16:22:47 -08001246#define TEST_AND_RETURN_VAL(_retval, _condition) \
1247 do { \
1248 if (!(_condition)) { \
1249 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1250 return _retval; \
1251 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001252 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001253
David Zeuthena99981f2013-04-29 13:42:47 -07001254ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001255 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001256 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001257 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001258 if (update_check_response_size !=
1259 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1260 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1261 << ") doesn't match metadata_size (" << metadata_size_
1262 << ") + metadata_signature_size (" << metadata_signature_size_
1263 << ") + buffer_offset (" << buffer_offset_ << ").";
1264 return ErrorCode::kPayloadSizeMismatchError;
1265 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001266
Amin Hassanie331f5a2020-10-06 15:53:29 -07001267 // Verifies the payload hash.
1268 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
1269 !payload_hash_calculator_.raw_hash().empty());
Kelvin Zhangdf3c1952021-10-06 18:56:55 -07001270 if (payload_hash_calculator_.raw_hash() != update_check_response_hash) {
1271 LOG(ERROR) << "Actual hash: "
1272 << HexEncode(payload_hash_calculator_.raw_hash())
1273 << ", expected hash: " << HexEncode(update_check_response_hash);
1274 return ErrorCode::kPayloadHashMismatchError;
1275 }
Amin Hassanie331f5a2020-10-06 15:53:29 -07001276
Amin Hassaniec7bc112020-10-29 16:47:58 -07001277 // NOLINTNEXTLINE(whitespace/braces)
Amin Hassanif624e112020-09-15 15:30:08 -07001278 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1279 if (!perform_verification) {
1280 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1281 return ErrorCode::kSuccess;
1282 }
1283 if (!payload_verifier) {
1284 LOG(ERROR) << "Failed to create the payload verifier.";
1285 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1286 }
1287
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001288 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001289 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001290 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001291 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001292 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001293
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001294 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001295 // The autoupdate_CatchBadSignatures test checks for this string
1296 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001297 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001298 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001299 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001300
David Zeuthene7f89172013-10-31 10:21:04 -07001301 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001302 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001303}
1304
Sen Jiangf6813802015-11-03 21:27:29 -08001305void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1306 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001307 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001308 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001309 buffer_offset_ += buffer_.size();
1310
1311 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001312 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1313 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001314
1315 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001316 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001317}
1318
Darin Petkov0406e402010-10-06 21:33:11 -07001319bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001320 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001321 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001322 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001323 next_operation != kUpdateStateOperationInvalid && next_operation > 0)) {
1324 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateNextOperation
1325 << " invalid: " << next_operation;
Alex Deymo3310b222015-03-30 15:59:07 -07001326 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001327 }
Darin Petkov0406e402010-10-06 21:33:11 -07001328
1329 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001330 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1331 !interrupted_hash.empty() &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001332 interrupted_hash == update_check_response_hash)) {
1333 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateCheckResponseHash
1334 << " mismatch, last hash: " << interrupted_hash
1335 << ", current hash: " << update_check_response_hash << "";
Alex Deymo3310b222015-03-30 15:59:07 -07001336 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001337 }
Darin Petkov0406e402010-10-06 21:33:11 -07001338
Daniel Zhengda4f7292022-09-02 22:59:32 +00001339 int64_t resumed_update_failures{};
Kelvin Zhang50bac652020-09-28 15:51:41 -04001340 // Note that storing this value is optional, but if it is there it should
1341 // not be more than the limit.
Alex Deymof25eb492016-02-26 00:20:08 -08001342 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001343 resumed_update_failures > kMaxResumedUpdateFailures) {
1344 LOG(WARNING) << "Failed to resume update " << kPrefsResumedUpdateFailures
1345 << " invalid: " << resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001346 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001347 }
Darin Petkov61426142010-10-08 11:04:55 -07001348
Saint Chou0a92a622020-07-29 14:25:35 +00001349 // Validation check the rest.
Darin Petkov0406e402010-10-06 21:33:11 -07001350 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001351 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001352 next_data_offset >= 0)) {
1353 LOG(WARNING) << "Failed to resume update "
1354 << kPrefsUpdateStateNextDataOffset
1355 << " invalid: " << next_data_offset;
Alex Deymo3310b222015-03-30 15:59:07 -07001356 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001357 }
Darin Petkov0406e402010-10-06 21:33:11 -07001358
Darin Petkov437adc42010-10-07 13:12:24 -07001359 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001360 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001361 !sha256_context.empty())) {
1362 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateSHA256Context
1363 << " is empty.";
Alex Deymo3310b222015-03-30 15:59:07 -07001364 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001365 }
Darin Petkov0406e402010-10-06 21:33:11 -07001366
1367 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001368 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001369 manifest_metadata_size > 0)) {
1370 LOG(WARNING) << "Failed to resume update " << kPrefsManifestMetadataSize
1371 << " invalid: " << manifest_metadata_size;
Alex Deymo3310b222015-03-30 15:59:07 -07001372 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001373 }
Darin Petkov0406e402010-10-06 21:33:11 -07001374
Alex Deymof25eb492016-02-26 00:20:08 -08001375 int64_t manifest_signature_size = 0;
1376 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1377 &manifest_signature_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001378 manifest_signature_size >= 0)) {
1379 LOG(WARNING) << "Failed to resume update " << kPrefsManifestSignatureSize
1380 << " invalid: " << manifest_signature_size;
Alex Deymof25eb492016-02-26 00:20:08 -08001381 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001382 }
Alex Deymof25eb492016-02-26 00:20:08 -08001383
Darin Petkov0406e402010-10-06 21:33:11 -07001384 return true;
1385}
1386
Daniel Zhengf9784802023-06-08 08:39:48 -07001387bool DeltaPerformer::ResetUpdateProgress(
1388 PrefsInterface* prefs,
1389 bool quick,
1390 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07001391 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1392 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001393 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001394 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001395 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001396 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1397 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001398 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001399 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001400 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001401 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001402 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001403 prefs->Delete(kPrefsVerityWritten);
Daniel Zhengf9784802023-06-08 08:39:48 -07001404 if (!skip_dynamic_partititon_metadata_updated) {
1405 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1406 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
1407 }
Darin Petkov9b230572010-10-08 10:20:09 -07001408 }
Darin Petkov73058b42010-10-06 16:32:19 -07001409 return true;
1410}
1411
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001412bool DeltaPerformer::ShouldCheckpoint() {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001413 base::TimeTicks curr_time = base::TimeTicks::Now();
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001414 if (curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001415 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001416 return true;
1417 }
1418 return false;
1419}
1420
1421bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
1422 if (!force && !ShouldCheckpoint()) {
Colin Howes0e452c92018-11-02 13:18:44 -07001423 return false;
1424 }
Darin Petkov9c0baf82010-10-07 13:44:48 -07001425 Terminator::set_exit_blocked(true);
Daniel Zheng5eece042023-05-17 14:44:10 -07001426 LOG_IF(WARNING, !prefs_->StartTransaction())
1427 << "unable to start transaction in checkpointing";
1428 DEFER {
1429 prefs_->CancelTransaction();
1430 };
Kelvin Zhang3265b312020-12-16 15:51:30 -05001431 if (last_updated_operation_num_ != next_operation_num_ || force) {
Kelvin Zhangbb8e9992020-12-28 10:28:48 -05001432 if (!signatures_message_data_.empty()) {
1433 // Save the signature blob because if the update is interrupted after the
1434 // download phase we don't go through this path anymore. Some alternatives
1435 // to consider:
1436 //
1437 // 1. On resume, re-download the signature blob from the server and
1438 // re-verify it.
1439 //
1440 // 2. Verify the signature as soon as it's received and don't checkpoint
1441 // the blob and the signed sha-256 context.
1442 LOG_IF(WARNING,
1443 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
1444 signatures_message_data_))
1445 << "Unable to store the signature blob.";
1446 }
Amin Hassani008c4582019-01-13 16:22:47 -08001447 TEST_AND_RETURN_FALSE(prefs_->SetString(
1448 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001449 TEST_AND_RETURN_FALSE(
1450 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1451 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001452 TEST_AND_RETURN_FALSE(
1453 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001454 last_updated_operation_num_ = next_operation_num_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001455
1456 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001457 size_t partition_index = current_partition_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001458 while (next_operation_num_ >= acc_num_operations_[partition_index]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001459 partition_index++;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001460 }
Amin Hassani008c4582019-01-13 16:22:47 -08001461 const size_t partition_operation_num =
1462 next_operation_num_ -
1463 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001464 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001465 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001466 TEST_AND_RETURN_FALSE(
1467 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001468 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001469 TEST_AND_RETURN_FALSE(
1470 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001471 }
Kelvin Zhange4235b02020-11-23 13:57:51 -05001472 if (partition_writer_) {
1473 partition_writer_->CheckpointUpdateProgress(GetPartitionOperationNum());
1474 } else {
1475 CHECK_EQ(next_operation_num_, num_total_operations_)
1476 << "Partition writer is null, we are expected to finish all "
1477 "operations: "
1478 << next_operation_num_ << "/" << num_total_operations_;
1479 }
Darin Petkov0406e402010-10-06 21:33:11 -07001480 }
Amin Hassani008c4582019-01-13 16:22:47 -08001481 TEST_AND_RETURN_FALSE(
1482 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Daniel Zheng5eece042023-05-17 14:44:10 -07001483 if (!prefs_->SubmitTransaction()) {
1484 LOG(ERROR) << "Failed to submit transaction in checkpointing";
1485 }
Darin Petkov73058b42010-10-06 16:32:19 -07001486 return true;
1487}
1488
Darin Petkov9b230572010-10-08 10:20:09 -07001489bool DeltaPerformer::PrimeUpdateState() {
1490 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001491
1492 int64_t next_operation = kUpdateStateOperationInvalid;
1493 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001494 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001495 // Initiating a new update, no more state needs to be initialized.
1496 return true;
1497 }
1498 next_operation_num_ = next_operation;
1499
1500 // Resuming an update -- load the rest of the update state.
1501 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001502 TEST_AND_RETURN_FALSE(
1503 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1504 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001505 buffer_offset_ = next_data_offset;
1506
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001507 // The signed hash context and the signature blob may be empty if the
1508 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001509 string signed_hash_context;
1510 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1511 &signed_hash_context)) {
1512 TEST_AND_RETURN_FALSE(
1513 signed_hash_calculator_.SetContext(signed_hash_context));
1514 }
1515
Sen Jiang9b2f1782019-01-24 14:27:50 -08001516 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001517
1518 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001519 TEST_AND_RETURN_FALSE(
1520 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1521 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001522
1523 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001524 TEST_AND_RETURN_FALSE(
1525 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1526 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001527 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001528
Alex Deymof25eb492016-02-26 00:20:08 -08001529 int64_t manifest_signature_size = 0;
1530 TEST_AND_RETURN_FALSE(
1531 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1532 manifest_signature_size >= 0);
1533 metadata_signature_size_ = manifest_signature_size;
1534
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001535 // Advance the download progress to reflect what doesn't need to be
1536 // re-downloaded.
1537 total_bytes_received_ += buffer_offset_;
1538
Darin Petkov61426142010-10-08 11:04:55 -07001539 // Speculatively count the resume as a failure.
Daniel Zhengda4f7292022-09-02 22:59:32 +00001540 int64_t resumed_update_failures{};
Darin Petkov61426142010-10-08 11:04:55 -07001541 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1542 resumed_update_failures++;
1543 } else {
1544 resumed_update_failures = 1;
1545 }
1546 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001547 return true;
1548}
1549
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001550bool DeltaPerformer::IsDynamicPartition(const std::string& part_name,
1551 uint32_t slot) {
Tianjie3a55fc22021-02-13 16:02:22 -08001552 return boot_control_->GetDynamicPartitionControl()->IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001553 part_name, slot);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -04001554}
1555
Kelvin Zhange52b6cd2021-02-09 15:28:40 -05001556std::unique_ptr<PartitionWriterInterface> DeltaPerformer::CreatePartitionWriter(
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001557 const PartitionUpdate& partition_update,
1558 const InstallPlan::Partition& install_part,
1559 DynamicPartitionControlInterface* dynamic_control,
1560 size_t block_size,
1561 bool is_interactive,
1562 bool is_dynamic_partition) {
1563 return partition_writer::CreatePartitionWriter(
1564 partition_update,
1565 install_part,
1566 dynamic_control,
1567 block_size_,
1568 interactive_,
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001569 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001570}
1571
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001572} // namespace chromeos_update_engine