blob: d5d5263d2934d6f624e1015c13ca29a4f78bc56a [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>
Ben Chan06c76a42014-09-05 08:21:06 -070032#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070033#include <base/format_macros.h>
Lann Martin39f57142017-07-14 09:18:42 -060034#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070035#include <base/strings/string_number_conversions.h>
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000036#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060037#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070038#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070039#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040#include <google/protobuf/repeated_field.h>
Amin Hassani02855c22017-09-06 22:34:50 -070041#include <puffin/puffpatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070042
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070044#include "update_engine/common/download_action.h"
Yifan Hong87029332020-09-01 17:20:08 -070045#include "update_engine/common/error_code.h"
46#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030048#include "update_engine/common/prefs_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030049#include "update_engine/common/terminator.h"
Kelvin Zhang52cb1d72020-10-27 13:44:25 -040050#include "update_engine/common/utils.h"
Tianjied3865d12020-06-03 15:25:17 -070051#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040052#include "update_engine/payload_consumer/partition_writer.h"
Daniel Zheng730ae9b2022-08-25 22:37:22 +000053#include "update_engine/update_metadata.pb.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070054#if USE_FEC
55#include "update_engine/payload_consumer/fec_file_descriptor.h"
56#endif // USE_FEC
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/payload_consumer/payload_constants.h"
58#include "update_engine/payload_consumer/payload_verifier.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070059
Alex Deymo161c4a12014-05-16 15:56:21 -070060using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070061using std::min;
62using std::string;
63using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070064
65namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080066const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
67const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
68const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
69const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070070const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080071
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070072namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070073const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070074const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080075
Alex Vakulenkod2779df2014-06-16 13:19:00 -070076} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070077
Gilad Arnold8a86fa52013-01-15 12:35:05 -080078// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
79// arithmetic.
80static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
81 return part * norm / total;
82}
83
84void DeltaPerformer::LogProgress(const char* message_prefix) {
85 // Format operations total count and percentage.
86 string total_operations_str("?");
87 string completed_percentage_str("");
88 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -070089 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -080090 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -080091 completed_percentage_str = base::StringPrintf(
92 " (%" PRIu64 "%%)",
93 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -080094 }
95
96 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -080097 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -080098 string payload_size_str("?");
99 string downloaded_percentage_str("");
100 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700101 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800102 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800103 downloaded_percentage_str = base::StringPrintf(
104 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800105 }
106
107 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
108 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800109 << completed_percentage_str << ", " << total_bytes_received_ << "/"
110 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800111 << downloaded_percentage_str << ", overall progress "
112 << overall_progress_ << "%";
113}
114
115void DeltaPerformer::UpdateOverallProgress(bool force_log,
116 const char* message_prefix) {
117 // Compute our download and overall progress.
118 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800119 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
120 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800121 // Only consider download progress if its total size is known; otherwise
122 // adjust the operations weight to compensate for the absence of download
123 // progress. Also, make sure to cap the download portion at
124 // kProgressDownloadWeight, in case we end up downloading more than we
125 // initially expected (this indicates a problem, but could generally happen).
126 // TODO(garnold) the correction of operations weight when we do not have the
127 // total payload size, as well as the conditional guard below, should both be
128 // eliminated once we ensure that the payload_size in the install plan is
129 // always given and is non-zero. This currently isn't the case during unit
130 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800131 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800132 unsigned actual_operations_weight = kProgressOperationsWeight;
133 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800134 new_overall_progress +=
135 min(static_cast<unsigned>(IntRatio(
136 total_bytes_received_, payload_size, kProgressDownloadWeight)),
137 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800138 else
139 actual_operations_weight += kProgressDownloadWeight;
140
141 // Only add completed operations if their total number is known; we definitely
142 // expect an update to have at least one operation, so the expectation is that
143 // this will eventually reach |actual_operations_weight|.
144 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800145 new_overall_progress += IntRatio(
146 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800147
148 // Progress ratio cannot recede, unless our assumptions about the total
149 // payload size, total number of operations, or the monotonicity of progress
150 // is breached.
151 if (new_overall_progress < overall_progress_) {
152 LOG(WARNING) << "progress counter receded from " << overall_progress_
153 << "% down to " << new_overall_progress << "%; this is a bug";
154 force_log = true;
155 }
156 overall_progress_ = new_overall_progress;
157
158 // Update chunk index, log as needed: if forced by called, or we completed a
159 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800160 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800161 unsigned curr_progress_chunk =
162 overall_progress_ * kProgressLogMaxChunks / 100;
163 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
164 curr_time > forced_progress_log_time_) {
165 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
166 LogProgress(message_prefix);
167 }
168 last_progress_chunk_ = curr_progress_chunk;
169}
170
Amin Hassani008c4582019-01-13 16:22:47 -0800171size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
172 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800173 size_t max) {
174 const size_t count = *count_p;
175 if (!count)
176 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700177 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800178 const char* bytes_start = *bytes_p;
179 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800180 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800181 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
182 *bytes_p = bytes_end;
183 *count_p = count - read_len;
184 return read_len;
185}
186
Amin Hassani008c4582019-01-13 16:22:47 -0800187bool DeltaPerformer::HandleOpResult(bool op_result,
188 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800189 ErrorCode* error) {
190 if (op_result)
191 return true;
192
193 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700194 << next_operation_num_ << ", which is the operation "
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400195 << GetPartitionOperationNum() << " in partition \""
Alex Deymo3d009062016-05-13 15:51:25 -0700196 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700197 if (*error == ErrorCode::kSuccess)
198 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800199 return false;
200}
201
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700202int DeltaPerformer::Close() {
Kelvin Zhang42f81b82022-10-04 10:43:08 -0700203 // Checkpoint update progress before canceling, so that subsequent attempts
204 // can resume from exactly where update_engine left last time.
205 CheckpointUpdateProgress(true);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700206 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800207 LOG_IF(ERROR,
208 !payload_hash_calculator_.Finalize() ||
209 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800210 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800211 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700212 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
213 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800214 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800215 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700216 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700217}
218
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700219int DeltaPerformer::CloseCurrentPartition() {
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400220 if (!partition_writer_) {
221 return 0;
222 }
223 int err = partition_writer_->Close();
224 partition_writer_ = nullptr;
225 return err;
226}
227
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700228bool DeltaPerformer::OpenCurrentPartition() {
229 if (current_partition_ >= partitions_.size())
230 return false;
231
232 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700233 size_t num_previous_partitions =
234 install_plan_->partitions.size() - partitions_.size();
235 const InstallPlan::Partition& install_part =
236 install_plan_->partitions[num_previous_partitions + current_partition_];
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400237 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500238 partition_writer_ = CreatePartitionWriter(
239 partition,
240 install_part,
241 dynamic_control,
242 block_size_,
243 interactive_,
244 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Tianjie55abd3c2020-06-19 00:22:59 -0700245 // Open source fds if we have a delta payload, or for partitions in the
246 // partial update.
Kelvin Zhangdf3c1952021-10-06 18:56:55 -0700247 const bool source_may_exist = manifest_.partial_update() ||
248 payload_->type == InstallPayloadType::kDelta;
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400249 const size_t partition_operation_num = GetPartitionOperationNum();
250
251 TEST_AND_RETURN_FALSE(partition_writer_->Init(
252 install_plan_, source_may_exist, partition_operation_num));
253 CheckpointUpdateProgress(true);
254 return true;
255}
256
257size_t DeltaPerformer::GetPartitionOperationNum() {
258 return next_operation_num_ -
259 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400260}
261
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700262namespace {
263
264void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Kelvin Zhang3fe49642021-10-04 15:35:02 -0700265 string sha256 = HexEncode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800266 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
267 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700268}
269
Alex Deymo39910dc2015-11-09 17:04:30 -0800270void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700271 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800272 if (partition.has_old_partition_info()) {
273 LogPartitionInfoHash(partition.old_partition_info(),
274 "old " + partition.partition_name());
275 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700276 LogPartitionInfoHash(partition.new_partition_info(),
277 "new " + partition.partition_name());
278 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700279}
280
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700281} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700282
Sen Jiangb8060e42015-09-24 17:30:50 -0700283bool DeltaPerformer::IsHeaderParsed() const {
284 return metadata_size_ != 0;
285}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700286
Sen Jiang9c89e842018-02-02 13:51:21 -0800287MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700288 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700289 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700290
Sen Jiangb8060e42015-09-24 17:30:50 -0700291 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700292 MetadataParseResult result =
293 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800294 if (result != MetadataParseResult::kSuccess)
295 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700296
Sen Jiang9c89e842018-02-02 13:51:21 -0800297 metadata_size_ = payload_metadata_.GetMetadataSize();
298 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
299 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800300
301 // If the metadata size is present in install plan, check for it immediately
302 // even before waiting for that many number of bytes to be downloaded in the
303 // payload. This will prevent any attack which relies on us downloading data
304 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800305 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800306 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800307 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800308 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800309 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700310 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800311 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800312 }
313 }
Andrew3a7dc262019-12-19 11:38:08 -0800314
315 // Check that the |metadata signature size_| and |metadata_size_| are not
316 // very big numbers. This is necessary since |update_engine| needs to write
317 // these values into the buffer before being able to use them, and if an
318 // attacker sets these values to a very big number, the buffer will overflow
319 // and |update_engine| will crash. A simple way of solving this is to check
320 // that the size of both values is smaller than the payload itself.
321 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
322 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
323 << " or metadata signature(" << metadata_signature_size_ << ")"
324 << " is greater than the size of the payload"
325 << "(" << payload_->size << ")";
326 *error = ErrorCode::kDownloadInvalidMetadataSize;
327 return MetadataParseResult::kError;
328 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700329 }
330
331 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700332 // metadata and its signature (if exist) to be read in before we can parse it.
333 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800334 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700335
336 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700337 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700338 // that we just log once (instead of logging n times) if it takes n
339 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800340 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700341 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800342 } else {
343 // For mandatory-cases, we'd have already returned a kMetadataParseError
344 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
345 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800346 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800347 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800348 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800349 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700350
Amin Hassaniec7bc112020-10-29 16:47:58 -0700351 // NOLINTNEXTLINE(whitespace/braces)
Tianjie Xu7a78d632019-10-08 16:32:39 -0700352 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
353 if (!payload_verifier) {
354 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800355 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700356 if (perform_verification) {
357 return MetadataParseResult::kError;
358 }
359 } else {
360 // We have the full metadata in |payload|. Verify its integrity
361 // and authenticity based on the information we have in Omaha response.
362 *error = payload_metadata_.ValidateMetadataSignature(
363 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800364 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700365 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800366 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800367 // The autoupdate_CatchBadSignatures test checks for this string
368 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800369 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800370 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800371 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700372
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800373 // For non-mandatory cases, just send a UMA stat.
374 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700375 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700376 }
377
Gilad Arnolddaa27402014-01-23 11:56:17 -0800378 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800379 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800380 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700381 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800382 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800383 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800384
385 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800386 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800387}
388
Tianjie8e0090d2021-08-30 22:35:21 -0700389#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
390 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
391 "UpdateEngine.DownloadAction.InstallOperation::" + string(_op_name) + \
392 ".Duration", \
393 (base::TimeTicks::Now() - _start_time), \
394 base::TimeDelta::FromMilliseconds(10), \
395 base::TimeDelta::FromMinutes(5), \
Amin Hassani008c4582019-01-13 16:22:47 -0800396 20);
Lann Martin39f57142017-07-14 09:18:42 -0600397
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000398void DeltaPerformer::CheckSPLDowngrade() {
Kelvin Zhanga10fd5a2022-09-01 23:39:39 +0000399 if (!manifest_.has_security_patch_level()) {
400 return;
401 }
Kelvin Zhang862c46c2022-09-02 17:01:12 +0000402 if (manifest_.security_patch_level().empty()) {
403 return;
404 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000405 const auto new_spl = manifest_.security_patch_level();
406 const auto current_spl =
407 android::base::GetProperty("ro.build.version.security_patch", "");
408 if (current_spl.empty()) {
409 LOG(ERROR) << "Failed to get ro.build.version.security_patch, unable to "
410 "determine if this OTA is a SPL downgrade.";
411 return;
412 }
413 if (new_spl < current_spl) {
414 install_plan_->powerwash_required = true;
415 LOG(INFO) << "Target build SPL " << new_spl
416 << " is older than current build's SPL " << current_spl
417 << ", this OTA is an SPL downgrade. Data wipe will be required";
418 }
419}
420
Don Garrette410e0f2011-11-10 15:39:01 -0800421// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800422// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700423// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800424bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700425 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700426 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800427
428 // Update the total byte downloaded count and the progress logs.
429 total_bytes_received_ += count;
430 UpdateOverallProgress(false, "Completed ");
431
Gilad Arnoldfe133932014-01-14 12:25:50 -0800432 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700433 // Read data up to the needed limit; this is either maximium payload header
434 // size, or the full metadata size (once it becomes known).
435 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800436 CopyDataToBuffer(
437 &c_bytes,
438 &count,
439 (do_read_header ? kMaxPayloadHeaderSize
440 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800441
Gilad Arnolddaa27402014-01-23 11:56:17 -0800442 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800443 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800444 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800445 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800446 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700447 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800448 continue;
449
Don Garrette410e0f2011-11-10 15:39:01 -0800450 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800451 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700452
453 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700454 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700455 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800456 manifest_valid_ = true;
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400457 if (!install_plan_->is_resume) {
Kelvin Zhangcf4600e2020-10-27 15:50:33 -0400458 auto begin = reinterpret_cast<const char*>(buffer_.data());
459 prefs_->SetString(kPrefsManifestBytes, {begin, buffer_.size()});
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400460 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700461
Gilad Arnoldfe133932014-01-14 12:25:50 -0800462 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800463 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700464
Sen Jiang57f91802017-11-14 17:42:13 -0800465 block_size_ = manifest_.block_size();
466
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000467 CheckSPLDowngrade();
468
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000469 // update estimate_cow_size if VABC is disabled
470 // new_cow_size per partition = partition_size - (#blocks in Copy
471 // operations part of the partition)
472 if (install_plan_->disable_vabc) {
473 LOG(INFO) << "Disabling VABC";
474 manifest_.mutable_dynamic_partition_metadata()
475 ->set_vabc_compression_param("none");
476 for (auto& partition : *manifest_.mutable_partitions()) {
Daniel Zhengd4806f82022-12-19 18:22:20 +0000477 auto new_cow_size = partition.new_partition_info().size();
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000478 for (const auto& operation : partition.merge_operations()) {
479 if (operation.type() == CowMergeOperation::COW_COPY) {
480 new_cow_size -=
481 operation.dst_extent().num_blocks() * manifest_.block_size();
482 }
483 }
484 // Adding extra 8MB headroom. OTA will sometimes write labels/metadata
485 // to COW image. If we overrun reserved COW size, entire OTA will fail
486 // and no way for user to retry OTA
487 partition.set_estimate_cow_size(new_cow_size + (1024 * 1024 * 8));
488 }
489 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800490 if (install_plan_->enable_threading) {
491 manifest_.mutable_dynamic_partition_metadata()
492 ->mutable_vabc_feature_set()
493 ->set_threaded(true);
494 LOG(INFO) << "Attempting to enable multi-threaded compression for VABC";
495 }
496 if (install_plan_->batched_writes) {
497 manifest_.mutable_dynamic_partition_metadata()
498 ->mutable_vabc_feature_set()
499 ->set_batch_writes(true);
500 LOG(INFO) << "Attempting to enable batched writes for VABC";
501 }
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000502
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700503 // This populates |partitions_| and the |install_plan.partitions| with the
504 // list of partitions from the manifest.
505 if (!ParseManifestPartitions(error))
506 return false;
507
Sen Jiang5ae865b2017-04-18 14:24:40 -0700508 // |install_plan.partitions| was filled in, nothing need to be done here if
509 // the payload was already applied, returns false to terminate http fetcher,
510 // but keep |error| as ErrorCode::kSuccess.
511 if (payload_->already_applied)
512 return false;
513
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700514 num_total_operations_ = 0;
515 for (const auto& partition : partitions_) {
516 num_total_operations_ += partition.operations_size();
517 acc_num_operations_.push_back(num_total_operations_);
518 }
519
Amin Hassani008c4582019-01-13 16:22:47 -0800520 LOG_IF(WARNING,
521 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700522 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800523 LOG_IF(WARNING,
524 !prefs_->SetInt64(kPrefsManifestSignatureSize,
525 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800526 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700527
Darin Petkov9b230572010-10-08 10:20:09 -0700528 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700529 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700530 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800531 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700532 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800533
Yifan Hong537802d2018-08-15 13:15:42 -0700534 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
535 if (!OpenCurrentPartition()) {
536 *error = ErrorCode::kInstallDeviceOpenError;
537 return false;
538 }
Allie Woodfdf00512015-03-02 13:34:55 -0800539 }
540
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800541 if (next_operation_num_ > 0)
542 UpdateOverallProgress(true, "Resuming after ");
543 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700544 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800545
546 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700547 // Check if we should cancel the current attempt for any reason.
548 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700549 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300550 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700551 return false;
552
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700553 // We know there are more operations to perform because we didn't reach the
554 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700555 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400556 if (partition_writer_) {
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700557 if (!partition_writer_->FinishedInstallOps()) {
558 *error = ErrorCode::kDownloadWriteError;
559 return false;
560 }
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400561 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700562 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700563 // Skip until there are operations for current_partition_.
564 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
565 current_partition_++;
566 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700567 if (!OpenCurrentPartition()) {
568 *error = ErrorCode::kInstallDeviceOpenError;
569 return false;
570 }
571 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700572
Alex Deymoa12ee112015-08-12 22:19:32 -0700573 const InstallOperation& op =
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400574 partitions_[current_partition_].operations(GetPartitionOperationNum());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800575
576 CopyDataToBuffer(&c_bytes, &count, op.data_length());
577
578 // Check whether we received all of the next operation's data payload.
579 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700580 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700581
Tianjie1205ea62020-07-09 17:04:28 -0700582 // Validate the operation unconditionally. This helps prevent the
583 // exploitation of vulnerabilities in the patching libraries, e.g. bspatch.
584 // The hash of the patch data for a given operation is embedded in the
585 // payload metadata; and thus has been verified against the public key on
586 // device.
587 // Note: Validate must be called only if CanPerformInstallOperation is
588 // called. Otherwise, we might be failing operations before even if there
589 // isn't sufficient data to compute the proper hash.
590 *error = ValidateOperationHash(op);
591 if (*error != ErrorCode::kSuccess) {
592 if (install_plan_->hash_checks_mandatory) {
593 LOG(ERROR) << "Mandatory operation hash check failed";
594 return false;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700595 }
Tianjie1205ea62020-07-09 17:04:28 -0700596
597 // For non-mandatory cases, just send a UMA stat.
598 LOG(WARNING) << "Ignoring operation validation errors";
599 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700600 }
601
Darin Petkov45580e42010-10-08 14:02:40 -0700602 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700603 ScopedTerminatorExitUnblocker exit_unblocker =
604 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800605
Lann Martin39f57142017-07-14 09:18:42 -0600606 base::TimeTicks op_start_time = base::TimeTicks::Now();
607
Daniel Zhengda4f7292022-09-02 22:59:32 +0000608 bool op_result{};
Tianjie8e0090d2021-08-30 22:35:21 -0700609 const string op_name = InstallOperationTypeName(op.type());
Alex Deymo2d621a32015-10-01 11:09:01 -0700610 switch (op.type()) {
611 case InstallOperation::REPLACE:
612 case InstallOperation::REPLACE_BZ:
613 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700614 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600615 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700616 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700617 case InstallOperation::ZERO:
618 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700619 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600620 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700621 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700622 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700623 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600624 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700625 break;
626 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800627 case InstallOperation::BROTLI_BSDIFF:
Amin Hassani49fdb092017-08-04 13:10:59 -0700628 case InstallOperation::PUFFDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700629 case InstallOperation::ZUCCHINI:
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800630 case InstallOperation::LZ4DIFF_PUFFDIFF:
631 case InstallOperation::LZ4DIFF_BSDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700632 op_result = PerformDiffOperation(op, error);
633 OP_DURATION_HISTOGRAM(op_name, op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800634 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700635 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700636 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700637 }
Tianjie8e0090d2021-08-30 22:35:21 -0700638 if (!HandleOpResult(op_result, op_name.c_str(), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800639 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800640
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700641 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800642 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800643 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700644 }
Sen Jiangf6813802015-11-03 21:27:29 -0800645
Kelvin Zhang4f28a6c2021-01-14 14:04:57 -0500646 if (partition_writer_) {
647 TEST_AND_RETURN_FALSE(partition_writer_->FinishedInstallOps());
648 }
649 CloseCurrentPartition();
650
Saint Chou0a92a622020-07-29 14:25:35 +0000651 // In major version 2, we don't add unused operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800652 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000653 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800654 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800655 if (manifest_.signatures_offset() != buffer_offset_) {
656 LOG(ERROR) << "Payload signatures offset points to blob offset "
657 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800658 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800659 *error = ErrorCode::kDownloadPayloadVerificationError;
660 return false;
661 }
662 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
663 // Needs more data to cover entire signature.
664 if (buffer_.size() < manifest_.signatures_size())
665 return true;
666 if (!ExtractSignatureMessage()) {
667 LOG(ERROR) << "Extract payload signature failed.";
668 *error = ErrorCode::kDownloadPayloadVerificationError;
669 return false;
670 }
671 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800672 // Since we extracted the SignatureMessage we need to advance the
673 // checkpoint, otherwise we would reload the signature and try to extract
674 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800675 // This is the last checkpoint for an update, force this checkpoint to be
676 // saved.
677 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800678 }
679
Don Garrette410e0f2011-11-10 15:39:01 -0800680 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700681}
682
David Zeuthen8f191b22013-08-06 12:27:50 -0700683bool DeltaPerformer::IsManifestValid() {
684 return manifest_valid_;
685}
686
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700687bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700688 partitions_.assign(manifest_.partitions().begin(),
689 manifest_.partitions().end());
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700690
Tianjied3865d12020-06-03 15:25:17 -0700691 // For VAB and partial updates, the partition preparation will copy the
692 // dynamic partitions metadata to the target metadata slot, and rename the
693 // slot suffix of the partitions in the metadata.
694 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
695 uint64_t required_size = 0;
696 if (!PreparePartitionsForUpdate(&required_size)) {
697 if (required_size > 0) {
698 *error = ErrorCode::kNotEnoughSpace;
699 } else {
700 *error = ErrorCode::kInstallDeviceOpenError;
701 }
702 return false;
703 }
704 }
705
Tianjie55abd3c2020-06-19 00:22:59 -0700706 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000707 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700708 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
709 // partition.
710 if (manifest_.partial_update()) {
711 std::set<std::string> touched_partitions;
712 for (const auto& partition_update : partitions_) {
713 touched_partitions.insert(partition_update.partition_name());
714 }
715
Tianjie99d570d2020-06-04 14:57:19 -0700716 auto generator = partition_update_generator::Create(boot_control_,
717 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700718 std::vector<PartitionUpdate> untouched_static_partitions;
Tianjied3865d12020-06-03 15:25:17 -0700719 TEST_AND_RETURN_FALSE(
720 generator->GenerateOperationsForPartitionsNotInPayload(
721 install_plan_->source_slot,
722 install_plan_->target_slot,
723 touched_partitions,
Tianjie24f96092020-06-30 12:26:25 -0700724 &untouched_static_partitions));
725 partitions_.insert(partitions_.end(),
726 untouched_static_partitions.begin(),
727 untouched_static_partitions.end());
728
729 // Save the untouched dynamic partitions in install plan.
730 std::vector<std::string> dynamic_partitions;
731 if (!boot_control_->GetDynamicPartitionControl()
732 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
Tianjie3a55fc22021-02-13 16:02:22 -0800733 boot_control_->GetCurrentSlot(),
Tianjie24f96092020-06-30 12:26:25 -0700734 &dynamic_partitions)) {
735 LOG(ERROR) << "Failed to load dynamic partitions from slot "
736 << install_plan_->source_slot;
737 return false;
738 }
739 install_plan_->untouched_dynamic_partitions.clear();
740 for (const auto& name : dynamic_partitions) {
741 if (touched_partitions.find(name) == touched_partitions.end()) {
742 install_plan_->untouched_dynamic_partitions.push_back(name);
743 }
744 }
Tianjied3865d12020-06-03 15:25:17 -0700745 }
746
Kelvin Zhang20982a52021-08-13 12:31:16 -0700747 if (!install_plan_->ParsePartitions(
748 partitions_, boot_control_, block_size_, error)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700749 return false;
750 }
Kelvin Zhangab15beb2022-12-05 10:19:52 -0800751 auto&& has_verity = [](const auto& part) {
752 return part.fec_extent().num_blocks() > 0 ||
753 part.hash_tree_extent().num_blocks() > 0;
754 };
755 if (!std::any_of(partitions_.begin(), partitions_.end(), has_verity)) {
756 install_plan_->write_verity = false;
757 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700758
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700759 LogPartitionInfo(partitions_);
760 return true;
761}
762
Yifan Hongb9d63572020-01-09 17:50:46 -0800763bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
764 // Call static PreparePartitionsForUpdate with hash from
765 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
766 // preallocated for is the same as the hash of payload being applied.
767 string update_check_response_hash;
768 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
769 &update_check_response_hash));
770 return PreparePartitionsForUpdate(prefs_,
771 boot_control_,
772 install_plan_->target_slot,
773 manifest_,
774 update_check_response_hash,
775 required_size);
776}
777
778bool DeltaPerformer::PreparePartitionsForUpdate(
779 PrefsInterface* prefs,
780 BootControlInterface* boot_control,
781 BootControlInterface::Slot target_slot,
782 const DeltaArchiveManifest& manifest,
783 const std::string& update_check_response_hash,
784 uint64_t* required_size) {
785 string last_hash;
786 ignore_result(
787 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
788
789 bool is_resume = !update_check_response_hash.empty() &&
790 last_hash == update_check_response_hash;
791
792 if (is_resume) {
793 LOG(INFO) << "Using previously prepared partitions for update. hash = "
794 << last_hash;
795 } else {
796 LOG(INFO) << "Preparing partitions for new update. last hash = "
797 << last_hash << ", new hash = " << update_check_response_hash;
Kelvin Zhang51e08b92021-02-19 14:54:21 -0500798 ResetUpdateProgress(prefs, false);
Yifan Hongb9d63572020-01-09 17:50:46 -0800799 }
800
801 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
802 boot_control->GetCurrentSlot(),
803 target_slot,
804 manifest,
805 !is_resume /* should update */,
806 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700807 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -0800808 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700809 return false;
810 }
Yifan Hongb9d63572020-01-09 17:50:46 -0800811
812 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
813 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -0700814 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700815
816 return true;
817}
818
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700819bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700820 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700821 // If we don't have a data blob we can apply it right away.
822 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700823 return true;
824
825 // See if we have the entire data blob in the buffer
826 if (operation.data_offset() < buffer_offset_) {
827 LOG(ERROR) << "we threw away data it seems?";
828 return false;
829 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700830
Gilad Arnoldfe133932014-01-14 12:25:50 -0800831 return (operation.data_offset() + operation.data_length() <=
832 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700833}
834
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700835bool DeltaPerformer::PerformReplaceOperation(
836 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700837 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700838 operation.type() == InstallOperation::REPLACE_BZ ||
839 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700840
841 // Since we delete data off the beginning of the buffer as we use it,
842 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700843 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700844
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400845 TEST_AND_RETURN_FALSE(partition_writer_->PerformReplaceOperation(
846 operation, buffer_.data(), buffer_.size()));
847 // Update buffer
848 DiscardBuffer(true, buffer_.size());
849 return true;
850}
851
Alex Deymo79715ad2015-10-02 14:27:53 -0700852bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700853 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700854 CHECK(operation.type() == InstallOperation::DISCARD ||
855 operation.type() == InstallOperation::ZERO);
856
857 // These operations have no blob.
858 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
859 TEST_AND_RETURN_FALSE(!operation.has_data_length());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400860
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400861 return partition_writer_->PerformZeroOrDiscardOperation(operation);
862}
Alex Deymo79715ad2015-10-02 14:27:53 -0700863
Allie Wood9f6f0a52015-03-30 11:25:47 -0700864bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700865 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700866 if (operation.has_src_length())
867 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
868 if (operation.has_dst_length())
869 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400870 return partition_writer_->PerformSourceCopyOperation(operation, error);
871}
Allie Wood9f6f0a52015-03-30 11:25:47 -0700872
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700873bool DeltaPerformer::ExtentsToBsdiffPositionsString(
874 const RepeatedPtrField<Extent>& extents,
875 uint64_t block_size,
876 uint64_t full_length,
877 string* positions_string) {
878 string ret;
879 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700880 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700881 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100882 uint64_t this_length =
883 min(full_length - length,
884 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700885 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700886 length += this_length;
887 }
888 TEST_AND_RETURN_FALSE(length == full_length);
889 if (!ret.empty())
890 ret.resize(ret.size() - 1); // Strip trailing comma off
891 *positions_string = ret;
892 return true;
893}
894
Tianjie8e0090d2021-08-30 22:35:21 -0700895bool DeltaPerformer::PerformDiffOperation(const InstallOperation& operation,
896 ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700897 // Since we delete data off the beginning of the buffer as we use it,
898 // the data we need should be exactly at the beginning of the buffer.
899 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
900 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
901 if (operation.has_src_length())
902 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
903 if (operation.has_dst_length())
904 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
905
Tianjie8e0090d2021-08-30 22:35:21 -0700906 TEST_AND_RETURN_FALSE(partition_writer_->PerformDiffOperation(
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400907 operation, error, buffer_.data(), buffer_.size()));
908 DiscardBuffer(true, buffer_.size());
909 return true;
910}
Amin Hassani02855c22017-09-06 22:34:50 -0700911
Sen Jiangf6813802015-11-03 21:27:29 -0800912bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700913 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
914 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
915 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700916 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -0800917 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700918
Darin Petkovd7061ab2010-10-06 14:37:09 -0700919 LOG(INFO) << "Extracted signature data of size "
920 << manifest_.signatures_size() << " at "
921 << manifest_.signatures_offset();
922 return true;
923}
924
Sen Jiang08c6da12019-01-07 18:28:56 -0800925bool DeltaPerformer::GetPublicKey(string* out_public_key) {
926 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -0700927
Sen Jiang08c6da12019-01-07 18:28:56 -0800928 if (utils::FileExists(public_key_path_.c_str())) {
929 LOG(INFO) << "Verifying using public key: " << public_key_path_;
930 return utils::ReadFile(public_key_path_, out_public_key);
931 }
932
Kelvin Zhang50bac652020-09-28 15:51:41 -0400933 // If this is an official build then we are not allowed to use public key
934 // from Omaha response.
Sen Jiang08c6da12019-01-07 18:28:56 -0800935 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
936 LOG(INFO) << "Verifying using public key from Omaha response.";
937 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
938 out_public_key);
939 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700940 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -0700941 return true;
942}
943
Tianjie Xu7a78d632019-10-08 16:32:39 -0700944std::pair<std::unique_ptr<PayloadVerifier>, bool>
945DeltaPerformer::CreatePayloadVerifier() {
946 if (utils::FileExists(update_certificates_path_.c_str())) {
947 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
948 return {
949 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
950 true};
951 }
952
953 string public_key;
954 if (!GetPublicKey(&public_key)) {
955 LOG(ERROR) << "Failed to read public key";
956 return {nullptr, true};
957 }
958
959 // Skips the verification if the public key is empty.
960 if (public_key.empty()) {
961 return {nullptr, false};
962 }
Kelvin Zhang3fe49642021-10-04 15:35:02 -0700963 LOG(INFO) << "Verifing using public key: " << public_key;
Tianjie Xu7a78d632019-10-08 16:32:39 -0700964 return {PayloadVerifier::CreateInstance(public_key), true};
965}
966
Gilad Arnold21504f02013-05-24 08:51:22 -0700967ErrorCode DeltaPerformer::ValidateManifest() {
Saint Chou0a92a622020-07-29 14:25:35 +0000968 // Perform assorted checks to validation check the manifest, make sure it
Don Garrettb8dd1d92013-11-22 17:40:02 -0800969 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +0000970 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
971 manifest_.partitions().end(),
972 [](const PartitionUpdate& partition) {
973 return partition.has_old_partition_info();
974 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -0700975
Alex Deymo64d98782016-02-05 18:03:48 -0800976 // The presence of an old partition hash is the sole indicator for a delta
Tianjief5baff42020-07-17 21:43:22 -0700977 // update. Also, always treat the partial update as delta so that we can
978 // perform the minor version check correctly.
Alex Deymo64d98782016-02-05 18:03:48 -0800979 InstallPayloadType actual_payload_type =
Tianjief5baff42020-07-17 21:43:22 -0700980 (has_old_fields || manifest_.partial_update())
981 ? InstallPayloadType::kDelta
982 : InstallPayloadType::kFull;
Alex Deymo64d98782016-02-05 18:03:48 -0800983
Sen Jiangcdd52062017-05-18 15:33:10 -0700984 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -0800985 LOG(INFO) << "Detected a '"
986 << InstallPayloadTypeToString(actual_payload_type)
987 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -0700988 payload_->type = actual_payload_type;
989 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -0800990 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -0700991 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -0800992 << "' payload but the downloaded manifest contains a '"
993 << InstallPayloadTypeToString(actual_payload_type)
994 << "' payload.";
995 return ErrorCode::kPayloadMismatchedType;
996 }
Alex Deymo64d98782016-02-05 18:03:48 -0800997 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -0700998 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -0800999 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001000 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1001 LOG(ERROR) << "Manifest contains minor version "
1002 << manifest_.minor_version()
1003 << ", but all full payloads should have version "
1004 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001005 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001006 }
1007 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001008 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1009 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001010 LOG(ERROR) << "Manifest contains minor version "
1011 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001012 << " not in the range of supported minor versions ["
1013 << kMinSupportedMinorPayloadVersion << ", "
1014 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001015 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001016 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001017 }
1018
Yifan Hong87029332020-09-01 17:20:08 -07001019 ErrorCode error_code = CheckTimestampError();
1020 if (error_code != ErrorCode::kSuccess) {
1021 if (error_code == ErrorCode::kPayloadTimestampError) {
1022 if (!hardware_->AllowDowngrade()) {
1023 return ErrorCode::kPayloadTimestampError;
1024 }
1025 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1026 " the payload with an older timestamp.";
1027 } else {
1028 LOG(ERROR) << "Timestamp check returned "
1029 << utils::ErrorCodeToString(error_code);
1030 return error_code;
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001031 }
Sen Jiang8e768e92017-06-28 17:13:19 -07001032 }
1033
Amin Hassani55c75412019-10-07 11:20:39 -07001034 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1035 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001036
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001037 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001038}
1039
Yifan Hong87029332020-09-01 17:20:08 -07001040ErrorCode DeltaPerformer::CheckTimestampError() const {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001041 bool is_partial_update =
1042 manifest_.has_partial_update() && manifest_.partial_update();
1043 const auto& partitions = manifest_.partitions();
Yifan Hong87029332020-09-01 17:20:08 -07001044
1045 // Check version field for a given PartitionUpdate object. If an error
1046 // is encountered, set |error_code| accordingly. If downgrade is detected,
Kelvin Zhang50bac652020-09-28 15:51:41 -04001047 // |downgrade_detected| is set. Return true if the program should continue
1048 // to check the next partition or not, or false if it should exit early due
1049 // to errors.
Yifan Hong87029332020-09-01 17:20:08 -07001050 auto&& timestamp_valid = [this](const PartitionUpdate& partition,
1051 bool allow_empty_version,
1052 bool* downgrade_detected) -> ErrorCode {
Tianjie19e55292020-10-19 21:49:37 -07001053 const auto& partition_name = partition.partition_name();
Yifan Hong87029332020-09-01 17:20:08 -07001054 if (!partition.has_version()) {
Tianjie19e55292020-10-19 21:49:37 -07001055 if (hardware_->GetVersionForLogging(partition_name).empty()) {
1056 LOG(INFO) << partition_name << " does't have version, skipping "
1057 << "downgrade check.";
1058 return ErrorCode::kSuccess;
1059 }
1060
Yifan Hong87029332020-09-01 17:20:08 -07001061 if (allow_empty_version) {
1062 return ErrorCode::kSuccess;
1063 }
1064 LOG(ERROR)
Tianjie19e55292020-10-19 21:49:37 -07001065 << "PartitionUpdate " << partition_name
1066 << " doesn't have a version field. Not allowed in partial updates.";
Yifan Hong87029332020-09-01 17:20:08 -07001067 return ErrorCode::kDownloadManifestParseError;
1068 }
1069
Tianjie19e55292020-10-19 21:49:37 -07001070 auto error_code =
1071 hardware_->IsPartitionUpdateValid(partition_name, partition.version());
Yifan Hong87029332020-09-01 17:20:08 -07001072 switch (error_code) {
1073 case ErrorCode::kSuccess:
1074 break;
1075 case ErrorCode::kPayloadTimestampError:
1076 *downgrade_detected = true;
Tianjie19e55292020-10-19 21:49:37 -07001077 LOG(WARNING) << "PartitionUpdate " << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001078 << " has an older version than partition on device.";
1079 break;
1080 default:
Tianjie19e55292020-10-19 21:49:37 -07001081 LOG(ERROR) << "IsPartitionUpdateValid(" << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001082 << ") returned" << utils::ErrorCodeToString(error_code);
1083 break;
1084 }
1085 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001086 };
Yifan Hong87029332020-09-01 17:20:08 -07001087
1088 bool downgrade_detected = false;
1089
Kelvin Zhangd7191032020-08-11 10:48:16 -04001090 if (is_partial_update) {
1091 // for partial updates, all partition MUST have valid timestamps
1092 // But max_timestamp can be empty
1093 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001094 auto error_code = timestamp_valid(
1095 partition, false /* allow_empty_version */, &downgrade_detected);
1096 if (error_code != ErrorCode::kSuccess &&
1097 error_code != ErrorCode::kPayloadTimestampError) {
1098 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001099 }
1100 }
Yifan Hong87029332020-09-01 17:20:08 -07001101 if (downgrade_detected) {
1102 return ErrorCode::kPayloadTimestampError;
1103 }
1104 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001105 }
Yifan Hong87029332020-09-01 17:20:08 -07001106
1107 // For non-partial updates, check max_timestamp first.
Kelvin Zhangd7191032020-08-11 10:48:16 -04001108 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1109 LOG(ERROR) << "The current OS build timestamp ("
1110 << hardware_->GetBuildTimestamp()
1111 << ") is newer than the maximum timestamp in the manifest ("
1112 << manifest_.max_timestamp() << ")";
Yifan Hong87029332020-09-01 17:20:08 -07001113 return ErrorCode::kPayloadTimestampError;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001114 }
1115 // Otherwise... partitions can have empty timestamps.
1116 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001117 auto error_code = timestamp_valid(
1118 partition, true /* allow_empty_version */, &downgrade_detected);
1119 if (error_code != ErrorCode::kSuccess &&
1120 error_code != ErrorCode::kPayloadTimestampError) {
1121 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001122 }
1123 }
Yifan Hong87029332020-09-01 17:20:08 -07001124 if (downgrade_detected) {
1125 return ErrorCode::kPayloadTimestampError;
1126 }
1127 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001128}
1129
David Zeuthena99981f2013-04-29 13:42:47 -07001130ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001131 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001132 if (!operation.data_sha256_hash().size()) {
1133 if (!operation.data_length()) {
Kelvin Zhang50bac652020-09-28 15:51:41 -04001134 // Operations that do not have any data blob won't have any operation
1135 // hash either. So, these operations are always considered validated
1136 // since the metadata that contains all the non-data-blob portions of
1137 // the operation has already been validated. This is true for both HTTP
1138 // and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001139 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001140 }
1141
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001142 // No hash is present for an operation that has data blobs. This shouldn't
1143 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001144 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001145 // hashes. So if it happens it means either we've turned operation hash
1146 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Saint Chou0a92a622020-07-29 14:25:35 +00001147 // One caveat though: The last operation is a unused signature operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001148 // that doesn't have a hash at the time the manifest is created. So we
1149 // should not complaint about that operation. This operation can be
1150 // recognized by the fact that it's offset is mentioned in the manifest.
1151 if (manifest_.signatures_offset() &&
1152 manifest_.signatures_offset() == operation.data_offset()) {
1153 LOG(INFO) << "Skipping hash verification for signature operation "
1154 << next_operation_num_ + 1;
1155 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001156 if (install_plan_->hash_checks_mandatory) {
1157 LOG(ERROR) << "Missing mandatory operation hash for operation "
1158 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001159 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001160 }
1161
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001162 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1163 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001164 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001165 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001166 }
1167
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001168 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001169 expected_op_hash.assign(operation.data_sha256_hash().data(),
1170 (operation.data_sha256_hash().data() +
1171 operation.data_sha256_hash().size()));
1172
Sen Jiang2703ef42017-03-16 13:36:21 -07001173 brillo::Blob calculated_op_hash;
1174 if (!HashCalculator::RawHashOfBytes(
1175 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001176 LOG(ERROR) << "Unable to compute actual hash of operation "
1177 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001178 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001179 }
1180
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001181 if (calculated_op_hash != expected_op_hash) {
1182 LOG(ERROR) << "Hash verification failed for operation "
Kelvin Zhangb9368922022-03-17 21:11:32 -07001183 << next_operation_num_
1184 << ". Expected hash = " << HexEncode(expected_op_hash);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001185 LOG(ERROR) << "Calculated hash over " << operation.data_length()
Kelvin Zhangb9368922022-03-17 21:11:32 -07001186 << " bytes at offset: " << operation.data_offset() << " = "
1187 << HexEncode(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001188 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001189 }
1190
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001191 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001192}
1193
Amin Hassani008c4582019-01-13 16:22:47 -08001194#define TEST_AND_RETURN_VAL(_retval, _condition) \
1195 do { \
1196 if (!(_condition)) { \
1197 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1198 return _retval; \
1199 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001200 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001201
David Zeuthena99981f2013-04-29 13:42:47 -07001202ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001203 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001204 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001205 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001206 if (update_check_response_size !=
1207 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1208 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1209 << ") doesn't match metadata_size (" << metadata_size_
1210 << ") + metadata_signature_size (" << metadata_signature_size_
1211 << ") + buffer_offset (" << buffer_offset_ << ").";
1212 return ErrorCode::kPayloadSizeMismatchError;
1213 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001214
Amin Hassanie331f5a2020-10-06 15:53:29 -07001215 // Verifies the payload hash.
1216 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
1217 !payload_hash_calculator_.raw_hash().empty());
Kelvin Zhangdf3c1952021-10-06 18:56:55 -07001218 if (payload_hash_calculator_.raw_hash() != update_check_response_hash) {
1219 LOG(ERROR) << "Actual hash: "
1220 << HexEncode(payload_hash_calculator_.raw_hash())
1221 << ", expected hash: " << HexEncode(update_check_response_hash);
1222 return ErrorCode::kPayloadHashMismatchError;
1223 }
Amin Hassanie331f5a2020-10-06 15:53:29 -07001224
Amin Hassaniec7bc112020-10-29 16:47:58 -07001225 // NOLINTNEXTLINE(whitespace/braces)
Amin Hassanif624e112020-09-15 15:30:08 -07001226 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1227 if (!perform_verification) {
1228 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1229 return ErrorCode::kSuccess;
1230 }
1231 if (!payload_verifier) {
1232 LOG(ERROR) << "Failed to create the payload verifier.";
1233 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1234 }
1235
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001236 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001237 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001238 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001239 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001240 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001241
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001242 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001243 // The autoupdate_CatchBadSignatures test checks for this string
1244 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001245 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001246 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001247 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001248
David Zeuthene7f89172013-10-31 10:21:04 -07001249 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001251}
1252
Sen Jiangf6813802015-11-03 21:27:29 -08001253void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1254 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001255 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001256 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001257 buffer_offset_ += buffer_.size();
1258
1259 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001260 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1261 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001262
1263 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001264 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001265}
1266
Darin Petkov0406e402010-10-06 21:33:11 -07001267bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001268 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001269 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001270 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001271 next_operation != kUpdateStateOperationInvalid && next_operation > 0)) {
1272 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateNextOperation
1273 << " invalid: " << next_operation;
Alex Deymo3310b222015-03-30 15:59:07 -07001274 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001275 }
Darin Petkov0406e402010-10-06 21:33:11 -07001276
1277 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001278 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1279 !interrupted_hash.empty() &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001280 interrupted_hash == update_check_response_hash)) {
1281 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateCheckResponseHash
1282 << " mismatch, last hash: " << interrupted_hash
1283 << ", current hash: " << update_check_response_hash << "";
Alex Deymo3310b222015-03-30 15:59:07 -07001284 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001285 }
Darin Petkov0406e402010-10-06 21:33:11 -07001286
Daniel Zhengda4f7292022-09-02 22:59:32 +00001287 int64_t resumed_update_failures{};
Kelvin Zhang50bac652020-09-28 15:51:41 -04001288 // Note that storing this value is optional, but if it is there it should
1289 // not be more than the limit.
Alex Deymof25eb492016-02-26 00:20:08 -08001290 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001291 resumed_update_failures > kMaxResumedUpdateFailures) {
1292 LOG(WARNING) << "Failed to resume update " << kPrefsResumedUpdateFailures
1293 << " invalid: " << resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001294 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001295 }
Darin Petkov61426142010-10-08 11:04:55 -07001296
Saint Chou0a92a622020-07-29 14:25:35 +00001297 // Validation check the rest.
Darin Petkov0406e402010-10-06 21:33:11 -07001298 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001299 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001300 next_data_offset >= 0)) {
1301 LOG(WARNING) << "Failed to resume update "
1302 << kPrefsUpdateStateNextDataOffset
1303 << " invalid: " << next_data_offset;
Alex Deymo3310b222015-03-30 15:59:07 -07001304 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001305 }
Darin Petkov0406e402010-10-06 21:33:11 -07001306
Darin Petkov437adc42010-10-07 13:12:24 -07001307 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001308 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001309 !sha256_context.empty())) {
1310 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateSHA256Context
1311 << " is empty.";
Alex Deymo3310b222015-03-30 15:59:07 -07001312 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001313 }
Darin Petkov0406e402010-10-06 21:33:11 -07001314
1315 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001316 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001317 manifest_metadata_size > 0)) {
1318 LOG(WARNING) << "Failed to resume update " << kPrefsManifestMetadataSize
1319 << " invalid: " << manifest_metadata_size;
Alex Deymo3310b222015-03-30 15:59:07 -07001320 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001321 }
Darin Petkov0406e402010-10-06 21:33:11 -07001322
Alex Deymof25eb492016-02-26 00:20:08 -08001323 int64_t manifest_signature_size = 0;
1324 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1325 &manifest_signature_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001326 manifest_signature_size >= 0)) {
1327 LOG(WARNING) << "Failed to resume update " << kPrefsManifestSignatureSize
1328 << " invalid: " << manifest_signature_size;
Alex Deymof25eb492016-02-26 00:20:08 -08001329 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001330 }
Alex Deymof25eb492016-02-26 00:20:08 -08001331
Darin Petkov0406e402010-10-06 21:33:11 -07001332 return true;
1333}
1334
Kelvin Zhang49170aa2022-11-28 10:55:16 -08001335bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001336 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1337 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001338 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001339 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001340 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001341 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1342 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001343 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001344 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001345 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001346 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001347 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001348 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001349
Kelvin Zhang49170aa2022-11-28 10:55:16 -08001350 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1351 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
Darin Petkov9b230572010-10-08 10:20:09 -07001352 }
Darin Petkov73058b42010-10-06 16:32:19 -07001353 return true;
1354}
1355
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001356bool DeltaPerformer::ShouldCheckpoint() {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001357 base::TimeTicks curr_time = base::TimeTicks::Now();
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001358 if (curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001359 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001360 return true;
1361 }
1362 return false;
1363}
1364
1365bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
1366 if (!force && !ShouldCheckpoint()) {
Colin Howes0e452c92018-11-02 13:18:44 -07001367 return false;
1368 }
Darin Petkov9c0baf82010-10-07 13:44:48 -07001369 Terminator::set_exit_blocked(true);
Kelvin Zhang3265b312020-12-16 15:51:30 -05001370 if (last_updated_operation_num_ != next_operation_num_ || force) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001371 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001372 ResetUpdateProgress(prefs_, true);
Kelvin Zhangbb8e9992020-12-28 10:28:48 -05001373 if (!signatures_message_data_.empty()) {
1374 // Save the signature blob because if the update is interrupted after the
1375 // download phase we don't go through this path anymore. Some alternatives
1376 // to consider:
1377 //
1378 // 1. On resume, re-download the signature blob from the server and
1379 // re-verify it.
1380 //
1381 // 2. Verify the signature as soon as it's received and don't checkpoint
1382 // the blob and the signed sha-256 context.
1383 LOG_IF(WARNING,
1384 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
1385 signatures_message_data_))
1386 << "Unable to store the signature blob.";
1387 }
Amin Hassani008c4582019-01-13 16:22:47 -08001388 TEST_AND_RETURN_FALSE(prefs_->SetString(
1389 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001390 TEST_AND_RETURN_FALSE(
1391 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1392 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001393 TEST_AND_RETURN_FALSE(
1394 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001395 last_updated_operation_num_ = next_operation_num_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001396
1397 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001398 size_t partition_index = current_partition_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001399 while (next_operation_num_ >= acc_num_operations_[partition_index]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001400 partition_index++;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001401 }
Amin Hassani008c4582019-01-13 16:22:47 -08001402 const size_t partition_operation_num =
1403 next_operation_num_ -
1404 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001405 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001406 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001407 TEST_AND_RETURN_FALSE(
1408 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001409 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001410 TEST_AND_RETURN_FALSE(
1411 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001412 }
Kelvin Zhange4235b02020-11-23 13:57:51 -05001413 if (partition_writer_) {
1414 partition_writer_->CheckpointUpdateProgress(GetPartitionOperationNum());
1415 } else {
1416 CHECK_EQ(next_operation_num_, num_total_operations_)
1417 << "Partition writer is null, we are expected to finish all "
1418 "operations: "
1419 << next_operation_num_ << "/" << num_total_operations_;
1420 }
Darin Petkov0406e402010-10-06 21:33:11 -07001421 }
Amin Hassani008c4582019-01-13 16:22:47 -08001422 TEST_AND_RETURN_FALSE(
1423 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07001424 return true;
1425}
1426
Darin Petkov9b230572010-10-08 10:20:09 -07001427bool DeltaPerformer::PrimeUpdateState() {
1428 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001429
1430 int64_t next_operation = kUpdateStateOperationInvalid;
1431 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001432 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001433 // Initiating a new update, no more state needs to be initialized.
1434 return true;
1435 }
1436 next_operation_num_ = next_operation;
1437
1438 // Resuming an update -- load the rest of the update state.
1439 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001440 TEST_AND_RETURN_FALSE(
1441 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1442 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001443 buffer_offset_ = next_data_offset;
1444
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001445 // The signed hash context and the signature blob may be empty if the
1446 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001447 string signed_hash_context;
1448 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1449 &signed_hash_context)) {
1450 TEST_AND_RETURN_FALSE(
1451 signed_hash_calculator_.SetContext(signed_hash_context));
1452 }
1453
Sen Jiang9b2f1782019-01-24 14:27:50 -08001454 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001455
1456 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001457 TEST_AND_RETURN_FALSE(
1458 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1459 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001460
1461 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001462 TEST_AND_RETURN_FALSE(
1463 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1464 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001465 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001466
Alex Deymof25eb492016-02-26 00:20:08 -08001467 int64_t manifest_signature_size = 0;
1468 TEST_AND_RETURN_FALSE(
1469 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1470 manifest_signature_size >= 0);
1471 metadata_signature_size_ = manifest_signature_size;
1472
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001473 // Advance the download progress to reflect what doesn't need to be
1474 // re-downloaded.
1475 total_bytes_received_ += buffer_offset_;
1476
Darin Petkov61426142010-10-08 11:04:55 -07001477 // Speculatively count the resume as a failure.
Daniel Zhengda4f7292022-09-02 22:59:32 +00001478 int64_t resumed_update_failures{};
Darin Petkov61426142010-10-08 11:04:55 -07001479 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1480 resumed_update_failures++;
1481 } else {
1482 resumed_update_failures = 1;
1483 }
1484 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001485 return true;
1486}
1487
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001488bool DeltaPerformer::IsDynamicPartition(const std::string& part_name,
1489 uint32_t slot) {
Tianjie3a55fc22021-02-13 16:02:22 -08001490 return boot_control_->GetDynamicPartitionControl()->IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001491 part_name, slot);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -04001492}
1493
Kelvin Zhange52b6cd2021-02-09 15:28:40 -05001494std::unique_ptr<PartitionWriterInterface> DeltaPerformer::CreatePartitionWriter(
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001495 const PartitionUpdate& partition_update,
1496 const InstallPlan::Partition& install_part,
1497 DynamicPartitionControlInterface* dynamic_control,
1498 size_t block_size,
1499 bool is_interactive,
1500 bool is_dynamic_partition) {
1501 return partition_writer::CreatePartitionWriter(
1502 partition_update,
1503 install_part,
1504 dynamic_control,
1505 block_size_,
1506 interactive_,
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001507 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001508}
1509
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001510} // namespace chromeos_update_engine