blob: b4a3970cd73008cb789eab1d6691644bb23b79fa [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
Alex Deymo79715ad2015-10-02 14:27:53 -070019#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070020
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070021#include <algorithm>
Kelvin Zhang8ddadd32023-12-12 12:54:30 -080022#include <chrono>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070024#include <memory>
Tianjied3865d12020-06-03 15:25:17 -070025#include <set>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include <string>
Amin Hassanid87304c2017-08-29 11:40:03 -070027#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028#include <vector>
29
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000030#include <android-base/properties.h>
Kelvin Zhangbdba3542023-02-24 11:08:55 -080031#include <android-base/strings.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
Kelvin Zhangbfa10412023-03-17 11:19:14 -070043#include "libsnapshot/cow_format.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080044#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070045#include "update_engine/common/download_action.h"
Yifan Hong87029332020-09-01 17:20:08 -070046#include "update_engine/common/error_code.h"
47#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080048#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030049#include "update_engine/common/prefs_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030050#include "update_engine/common/terminator.h"
Kelvin Zhang52cb1d72020-10-27 13:44:25 -040051#include "update_engine/common/utils.h"
Tianjied3865d12020-06-03 15:25:17 -070052#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040053#include "update_engine/payload_consumer/partition_writer.h"
Daniel Zheng730ae9b2022-08-25 22:37:22 +000054#include "update_engine/update_metadata.pb.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070055#if USE_FEC
56#include "update_engine/payload_consumer/fec_file_descriptor.h"
57#endif // USE_FEC
Alex Deymo39910dc2015-11-09 17:04:30 -080058#include "update_engine/payload_consumer/payload_constants.h"
59#include "update_engine/payload_consumer/payload_verifier.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070060
Alex Deymo161c4a12014-05-16 15:56:21 -070061using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070062using std::min;
63using std::string;
64using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070065
66namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080067const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
68const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
69const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
70const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070071const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080072
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070073namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070074const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070075const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080076
Alex Vakulenkod2779df2014-06-16 13:19:00 -070077} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078
Gilad Arnold8a86fa52013-01-15 12:35:05 -080079// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
80// arithmetic.
81static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
82 return part * norm / total;
83}
84
85void DeltaPerformer::LogProgress(const char* message_prefix) {
86 // Format operations total count and percentage.
87 string total_operations_str("?");
88 string completed_percentage_str("");
89 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -070090 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -080091 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -080092 completed_percentage_str = base::StringPrintf(
93 " (%" PRIu64 "%%)",
94 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -080095 }
96
97 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -080098 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -080099 string payload_size_str("?");
100 string downloaded_percentage_str("");
101 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700102 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800103 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800104 downloaded_percentage_str = base::StringPrintf(
105 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800106 }
107
108 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
109 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800110 << completed_percentage_str << ", " << total_bytes_received_ << "/"
111 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800112 << downloaded_percentage_str << ", overall progress "
113 << overall_progress_ << "%";
114}
115
116void DeltaPerformer::UpdateOverallProgress(bool force_log,
117 const char* message_prefix) {
118 // Compute our download and overall progress.
119 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800120 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
121 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800122 // Only consider download progress if its total size is known; otherwise
123 // adjust the operations weight to compensate for the absence of download
124 // progress. Also, make sure to cap the download portion at
125 // kProgressDownloadWeight, in case we end up downloading more than we
126 // initially expected (this indicates a problem, but could generally happen).
127 // TODO(garnold) the correction of operations weight when we do not have the
128 // total payload size, as well as the conditional guard below, should both be
129 // eliminated once we ensure that the payload_size in the install plan is
130 // always given and is non-zero. This currently isn't the case during unit
131 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800132 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800133 unsigned actual_operations_weight = kProgressOperationsWeight;
134 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800135 new_overall_progress +=
136 min(static_cast<unsigned>(IntRatio(
137 total_bytes_received_, payload_size, kProgressDownloadWeight)),
138 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800139 else
140 actual_operations_weight += kProgressDownloadWeight;
141
142 // Only add completed operations if their total number is known; we definitely
143 // expect an update to have at least one operation, so the expectation is that
144 // this will eventually reach |actual_operations_weight|.
145 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800146 new_overall_progress += IntRatio(
147 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800148
149 // Progress ratio cannot recede, unless our assumptions about the total
150 // payload size, total number of operations, or the monotonicity of progress
151 // is breached.
152 if (new_overall_progress < overall_progress_) {
153 LOG(WARNING) << "progress counter receded from " << overall_progress_
154 << "% down to " << new_overall_progress << "%; this is a bug";
155 force_log = true;
156 }
157 overall_progress_ = new_overall_progress;
158
159 // Update chunk index, log as needed: if forced by called, or we completed a
160 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800161 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800162 unsigned curr_progress_chunk =
163 overall_progress_ * kProgressLogMaxChunks / 100;
164 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
165 curr_time > forced_progress_log_time_) {
166 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
167 LogProgress(message_prefix);
168 }
169 last_progress_chunk_ = curr_progress_chunk;
170}
171
Amin Hassani008c4582019-01-13 16:22:47 -0800172size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
173 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800174 size_t max) {
175 const size_t count = *count_p;
176 if (!count)
177 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700178 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800179 const char* bytes_start = *bytes_p;
180 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800181 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800182 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
183 *bytes_p = bytes_end;
184 *count_p = count - read_len;
185 return read_len;
186}
187
Amin Hassani008c4582019-01-13 16:22:47 -0800188bool DeltaPerformer::HandleOpResult(bool op_result,
189 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800190 ErrorCode* error) {
191 if (op_result)
192 return true;
193
194 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700195 << next_operation_num_ << ", which is the operation "
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400196 << GetPartitionOperationNum() << " in partition \""
Alex Deymo3d009062016-05-13 15:51:25 -0700197 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700198 if (*error == ErrorCode::kSuccess)
199 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800200 return false;
201}
202
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700203int DeltaPerformer::Close() {
Kelvin Zhang42f81b82022-10-04 10:43:08 -0700204 // Checkpoint update progress before canceling, so that subsequent attempts
205 // can resume from exactly where update_engine left last time.
206 CheckpointUpdateProgress(true);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700207 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800208 LOG_IF(ERROR,
209 !payload_hash_calculator_.Finalize() ||
210 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800211 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800212 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700213 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
214 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800215 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800216 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700217 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700218}
219
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700220int DeltaPerformer::CloseCurrentPartition() {
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400221 if (!partition_writer_) {
222 return 0;
223 }
224 int err = partition_writer_->Close();
225 partition_writer_ = nullptr;
226 return err;
227}
228
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700229bool DeltaPerformer::OpenCurrentPartition() {
230 if (current_partition_ >= partitions_.size())
231 return false;
232
233 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700234 size_t num_previous_partitions =
235 install_plan_->partitions.size() - partitions_.size();
236 const InstallPlan::Partition& install_part =
237 install_plan_->partitions[num_previous_partitions + current_partition_];
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400238 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500239 partition_writer_ = CreatePartitionWriter(
240 partition,
241 install_part,
242 dynamic_control,
243 block_size_,
244 interactive_,
245 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Tianjie55abd3c2020-06-19 00:22:59 -0700246 // Open source fds if we have a delta payload, or for partitions in the
247 // partial update.
Kelvin Zhangdf3c1952021-10-06 18:56:55 -0700248 const bool source_may_exist = manifest_.partial_update() ||
249 payload_->type == InstallPayloadType::kDelta;
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400250 const size_t partition_operation_num = GetPartitionOperationNum();
251
252 TEST_AND_RETURN_FALSE(partition_writer_->Init(
253 install_plan_, source_may_exist, partition_operation_num));
254 CheckpointUpdateProgress(true);
255 return true;
256}
257
258size_t DeltaPerformer::GetPartitionOperationNum() {
259 return next_operation_num_ -
260 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400261}
262
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700263namespace {
264
265void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Kelvin Zhang3fe49642021-10-04 15:35:02 -0700266 string sha256 = HexEncode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800267 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
268 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700269}
270
Alex Deymo39910dc2015-11-09 17:04:30 -0800271void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700272 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800273 if (partition.has_old_partition_info()) {
274 LogPartitionInfoHash(partition.old_partition_info(),
275 "old " + partition.partition_name());
276 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700277 LogPartitionInfoHash(partition.new_partition_info(),
278 "new " + partition.partition_name());
279 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700280}
281
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700282} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700283
Sen Jiangb8060e42015-09-24 17:30:50 -0700284bool DeltaPerformer::IsHeaderParsed() const {
285 return metadata_size_ != 0;
286}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700287
Sen Jiang9c89e842018-02-02 13:51:21 -0800288MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700289 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700290 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700291
Sen Jiangb8060e42015-09-24 17:30:50 -0700292 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700293 MetadataParseResult result =
294 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800295 if (result != MetadataParseResult::kSuccess)
296 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700297
Sen Jiang9c89e842018-02-02 13:51:21 -0800298 metadata_size_ = payload_metadata_.GetMetadataSize();
299 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
300 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800301
302 // If the metadata size is present in install plan, check for it immediately
303 // even before waiting for that many number of bytes to be downloaded in the
304 // payload. This will prevent any attack which relies on us downloading data
305 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800306 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800307 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800308 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800309 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800310 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700311 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800312 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800313 }
314 }
Andrew3a7dc262019-12-19 11:38:08 -0800315
316 // Check that the |metadata signature size_| and |metadata_size_| are not
317 // very big numbers. This is necessary since |update_engine| needs to write
318 // these values into the buffer before being able to use them, and if an
319 // attacker sets these values to a very big number, the buffer will overflow
320 // and |update_engine| will crash. A simple way of solving this is to check
321 // that the size of both values is smaller than the payload itself.
322 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
323 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
324 << " or metadata signature(" << metadata_signature_size_ << ")"
325 << " is greater than the size of the payload"
326 << "(" << payload_->size << ")";
327 *error = ErrorCode::kDownloadInvalidMetadataSize;
328 return MetadataParseResult::kError;
329 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700330 }
331
332 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700333 // metadata and its signature (if exist) to be read in before we can parse it.
334 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800335 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700336
337 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700338 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700339 // that we just log once (instead of logging n times) if it takes n
340 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800341 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700342 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800343 } else {
344 // For mandatory-cases, we'd have already returned a kMetadataParseError
345 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
346 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800347 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800348 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800349 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800350 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700351
Amin Hassaniec7bc112020-10-29 16:47:58 -0700352 // NOLINTNEXTLINE(whitespace/braces)
Tianjie Xu7a78d632019-10-08 16:32:39 -0700353 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
354 if (!payload_verifier) {
355 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800356 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700357 if (perform_verification) {
358 return MetadataParseResult::kError;
359 }
360 } else {
361 // We have the full metadata in |payload|. Verify its integrity
362 // and authenticity based on the information we have in Omaha response.
363 *error = payload_metadata_.ValidateMetadataSignature(
364 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800365 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700366 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800367 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800368 // The autoupdate_CatchBadSignatures test checks for this string
369 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800370 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800371 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800372 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700373
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800374 // For non-mandatory cases, just send a UMA stat.
375 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700376 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700377 }
378
Gilad Arnolddaa27402014-01-23 11:56:17 -0800379 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800380 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800381 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700382 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800383 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800384 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800385
386 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800387 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800388}
389
Tianjie8e0090d2021-08-30 22:35:21 -0700390#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
391 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
392 "UpdateEngine.DownloadAction.InstallOperation::" + string(_op_name) + \
393 ".Duration", \
394 (base::TimeTicks::Now() - _start_time), \
395 base::TimeDelta::FromMilliseconds(10), \
396 base::TimeDelta::FromMinutes(5), \
Amin Hassani008c4582019-01-13 16:22:47 -0800397 20);
Lann Martin39f57142017-07-14 09:18:42 -0600398
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800399bool DeltaPerformer::CheckSPLDowngrade() {
Kelvin Zhanga10fd5a2022-09-01 23:39:39 +0000400 if (!manifest_.has_security_patch_level()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800401 return true;
Kelvin Zhanga10fd5a2022-09-01 23:39:39 +0000402 }
Kelvin Zhang862c46c2022-09-02 17:01:12 +0000403 if (manifest_.security_patch_level().empty()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800404 return true;
Kelvin Zhang862c46c2022-09-02 17:01:12 +0000405 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000406 const auto new_spl = manifest_.security_patch_level();
407 const auto current_spl =
408 android::base::GetProperty("ro.build.version.security_patch", "");
409 if (current_spl.empty()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800410 LOG(WARNING) << "Failed to get ro.build.version.security_patch, unable to "
411 "determine if this OTA is a SPL downgrade. Assuming this "
412 "OTA is not SPL downgrade.";
413 return true;
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000414 }
415 if (new_spl < current_spl) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800416 const auto avb_state =
417 android::base::GetProperty("ro.boot.verifiedbootstate", "green");
418 if (android::base::EqualsIgnoreCase(avb_state, "green")) {
419 LOG(ERROR) << "Target build SPL " << new_spl
420 << " is older than current build's SPL " << current_spl
421 << ", this OTA is an SPL downgrade. Your device's "
422 "ro.boot.verifiedbootstate="
423 << avb_state
424 << ", it probably has a locked bootlaoder. Since a locked "
425 "bootloader will reject SPL downgrade no matter what, we "
426 "will reject this OTA.";
427 return false;
428 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000429 install_plan_->powerwash_required = true;
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800430 LOG(WARNING)
431 << "Target build SPL " << new_spl
432 << " is older than current build's SPL " << current_spl
433 << ", this OTA is an SPL downgrade. Data wipe will be required";
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000434 }
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800435 return true;
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000436}
437
Don Garrette410e0f2011-11-10 15:39:01 -0800438// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800439// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700440// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800441bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Daniel Zhengeede4c82023-06-13 11:21:06 -0700442 if (!error) {
443 return false;
444 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700445 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700446 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800447
448 // Update the total byte downloaded count and the progress logs.
449 total_bytes_received_ += count;
450 UpdateOverallProgress(false, "Completed ");
451
Gilad Arnoldfe133932014-01-14 12:25:50 -0800452 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700453 // Read data up to the needed limit; this is either maximium payload header
454 // size, or the full metadata size (once it becomes known).
455 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800456 CopyDataToBuffer(
457 &c_bytes,
458 &count,
459 (do_read_header ? kMaxPayloadHeaderSize
460 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800461
Gilad Arnolddaa27402014-01-23 11:56:17 -0800462 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800463 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800464 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800465 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800466 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700467 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800468 continue;
469
Don Garrette410e0f2011-11-10 15:39:01 -0800470 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800471 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700472
473 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700474 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700475 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800476 manifest_valid_ = true;
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400477 if (!install_plan_->is_resume) {
Kelvin Zhangcf4600e2020-10-27 15:50:33 -0400478 auto begin = reinterpret_cast<const char*>(buffer_.data());
479 prefs_->SetString(kPrefsManifestBytes, {begin, buffer_.size()});
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400480 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700481
Gilad Arnoldfe133932014-01-14 12:25:50 -0800482 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800483 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700484
Sen Jiang57f91802017-11-14 17:42:13 -0800485 block_size_ = manifest_.block_size();
486
Kelvin Zhang85a6d992023-10-23 10:40:58 -0700487 if (!install_plan_->spl_downgrade && !CheckSPLDowngrade()) {
Kelvin Zhangbdba3542023-02-24 11:08:55 -0800488 *error = ErrorCode::kPayloadTimestampError;
489 return false;
490 }
Kelvin Zhangcfc531f2022-08-24 17:58:53 +0000491
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000492 // update estimate_cow_size if VABC is disabled
493 // new_cow_size per partition = partition_size - (#blocks in Copy
494 // operations part of the partition)
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700495 if (install_plan_->vabc_none) {
Kelvin Zhang49c06b22023-12-16 13:39:55 -0800496 LOG(INFO) << "Setting Virtual AB Compression algorithm to none. This "
497 "would also disable VABC XOR as XOR only saves space if "
498 "compression is enabled.";
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000499 manifest_.mutable_dynamic_partition_metadata()
500 ->set_vabc_compression_param("none");
501 for (auto& partition : *manifest_.mutable_partitions()) {
Kelvin Zhang49c06b22023-12-16 13:39:55 -0800502 if (!partition.has_estimate_cow_size()) {
503 continue;
504 }
Daniel Zhengd4806f82022-12-19 18:22:20 +0000505 auto new_cow_size = partition.new_partition_info().size();
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000506 for (const auto& operation : partition.merge_operations()) {
507 if (operation.type() == CowMergeOperation::COW_COPY) {
508 new_cow_size -=
509 operation.dst_extent().num_blocks() * manifest_.block_size();
510 }
511 }
Kelvin Zhang49c06b22023-12-16 13:39:55 -0800512 // Remove all COW_XOR merge ops, as XOR without compression is useless.
513 // It increases CPU usage but does not reduce space usage at all.
514 auto&& merge_ops = *partition.mutable_merge_operations();
515 merge_ops.erase(std::remove_if(merge_ops.begin(),
516 merge_ops.end(),
517 [](const auto& op) {
518 return op.type() ==
519 CowMergeOperation::COW_XOR;
520 }),
521 merge_ops.end());
522
Kelvin Zhangbfa10412023-03-17 11:19:14 -0700523 // Every block written to COW device will come with a header which
524 // stores src/dst block info along with other data.
525 const auto cow_metadata_size = partition.new_partition_info().size() /
526 manifest_.block_size() *
527 sizeof(android::snapshot::CowOperation);
528 // update_engine will emit a label op every op or every two seconds,
529 // whichever one is longer. In the worst case, we add 1 label per
530 // InstallOp. So take size of label ops into account.
531 const auto label_ops_size = partition.operations_size() *
532 sizeof(android::snapshot::CowOperation);
533 // Adding extra 2MB headroom just for any unexpected space usage.
534 // If we overrun reserved COW size, entire OTA will fail
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000535 // and no way for user to retry OTA
Kelvin Zhangbfa10412023-03-17 11:19:14 -0700536 partition.set_estimate_cow_size(new_cow_size + (1024 * 1024 * 2) +
537 cow_metadata_size + label_ops_size);
Daniel Zheng5f07b222024-01-10 14:22:34 -0800538 // Setting op count max to 0 will defer to num_blocks as the op buffer
539 // size.
540 partition.set_estimate_op_count_max(0);
Kelvin Zhangbfa10412023-03-17 11:19:14 -0700541 LOG(INFO) << "New COW size for partition " << partition.partition_name()
542 << " is " << partition.estimate_cow_size();
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000543 }
544 }
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000545 if (install_plan_->disable_vabc) {
546 manifest_.mutable_dynamic_partition_metadata()->set_vabc_enabled(false);
547 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800548 if (install_plan_->enable_threading) {
549 manifest_.mutable_dynamic_partition_metadata()
550 ->mutable_vabc_feature_set()
Kelvin Zhang944cdac2023-12-12 12:55:27 -0800551 ->set_threaded(install_plan_->enable_threading.value());
Kelvin Zhangb1c05242023-12-14 13:49:53 -0800552 LOG(INFO) << "Attempting to "
553 << (install_plan_->enable_threading.value() ? "enable"
554 : "disable")
555 << " multi-threaded compression for VABC";
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800556 }
557 if (install_plan_->batched_writes) {
558 manifest_.mutable_dynamic_partition_metadata()
559 ->mutable_vabc_feature_set()
560 ->set_batch_writes(true);
561 LOG(INFO) << "Attempting to enable batched writes for VABC";
562 }
Daniel Zheng4565a2e2022-09-21 17:21:17 +0000563
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700564 // This populates |partitions_| and the |install_plan.partitions| with the
565 // list of partitions from the manifest.
566 if (!ParseManifestPartitions(error))
567 return false;
568
Sen Jiang5ae865b2017-04-18 14:24:40 -0700569 // |install_plan.partitions| was filled in, nothing need to be done here if
570 // the payload was already applied, returns false to terminate http fetcher,
571 // but keep |error| as ErrorCode::kSuccess.
572 if (payload_->already_applied)
573 return false;
574
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700575 num_total_operations_ = 0;
576 for (const auto& partition : partitions_) {
577 num_total_operations_ += partition.operations_size();
578 acc_num_operations_.push_back(num_total_operations_);
579 }
580
Amin Hassani008c4582019-01-13 16:22:47 -0800581 LOG_IF(WARNING,
582 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700583 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800584 LOG_IF(WARNING,
585 !prefs_->SetInt64(kPrefsManifestSignatureSize,
586 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800587 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700588
Darin Petkov9b230572010-10-08 10:20:09 -0700589 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700590 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700591 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800592 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700593 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800594
Yifan Hong537802d2018-08-15 13:15:42 -0700595 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
596 if (!OpenCurrentPartition()) {
597 *error = ErrorCode::kInstallDeviceOpenError;
598 return false;
599 }
Allie Woodfdf00512015-03-02 13:34:55 -0800600 }
601
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800602 if (next_operation_num_ > 0)
603 UpdateOverallProgress(true, "Resuming after ");
604 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700605 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800606
607 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700608 // Check if we should cancel the current attempt for any reason.
609 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700610 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300611 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700612 return false;
613
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700614 // We know there are more operations to perform because we didn't reach the
615 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700616 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400617 if (partition_writer_) {
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700618 if (!partition_writer_->FinishedInstallOps()) {
619 *error = ErrorCode::kDownloadWriteError;
620 return false;
621 }
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400622 }
Kelvin Zhangb1c05242023-12-14 13:49:53 -0800623 const auto err = CloseCurrentPartition();
624 if (err < 0) {
625 LOG(ERROR) << "Failed to close partition "
626 << partitions_[current_partition_].partition_name() << " "
627 << strerror(-err);
628 return false;
629 }
Yifan Hong537802d2018-08-15 13:15:42 -0700630 // Skip until there are operations for current_partition_.
631 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
632 current_partition_++;
633 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700634 if (!OpenCurrentPartition()) {
635 *error = ErrorCode::kInstallDeviceOpenError;
636 return false;
637 }
638 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700639
Alex Deymoa12ee112015-08-12 22:19:32 -0700640 const InstallOperation& op =
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400641 partitions_[current_partition_].operations(GetPartitionOperationNum());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800642
643 CopyDataToBuffer(&c_bytes, &count, op.data_length());
644
645 // Check whether we received all of the next operation's data payload.
646 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700647 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700648
Tianjie1205ea62020-07-09 17:04:28 -0700649 // Validate the operation unconditionally. This helps prevent the
650 // exploitation of vulnerabilities in the patching libraries, e.g. bspatch.
651 // The hash of the patch data for a given operation is embedded in the
652 // payload metadata; and thus has been verified against the public key on
653 // device.
654 // Note: Validate must be called only if CanPerformInstallOperation is
655 // called. Otherwise, we might be failing operations before even if there
656 // isn't sufficient data to compute the proper hash.
657 *error = ValidateOperationHash(op);
658 if (*error != ErrorCode::kSuccess) {
659 if (install_plan_->hash_checks_mandatory) {
660 LOG(ERROR) << "Mandatory operation hash check failed";
661 return false;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700662 }
Tianjie1205ea62020-07-09 17:04:28 -0700663
664 // For non-mandatory cases, just send a UMA stat.
665 LOG(WARNING) << "Ignoring operation validation errors";
666 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700667 }
668
Darin Petkov45580e42010-10-08 14:02:40 -0700669 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700670 ScopedTerminatorExitUnblocker exit_unblocker =
671 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800672
Lann Martin39f57142017-07-14 09:18:42 -0600673 base::TimeTicks op_start_time = base::TimeTicks::Now();
674
Daniel Zhengda4f7292022-09-02 22:59:32 +0000675 bool op_result{};
Tianjie8e0090d2021-08-30 22:35:21 -0700676 const string op_name = InstallOperationTypeName(op.type());
Alex Deymo2d621a32015-10-01 11:09:01 -0700677 switch (op.type()) {
678 case InstallOperation::REPLACE:
679 case InstallOperation::REPLACE_BZ:
680 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700681 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600682 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700683 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700684 case InstallOperation::ZERO:
685 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700686 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600687 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700688 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700689 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700690 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600691 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700692 break;
693 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800694 case InstallOperation::BROTLI_BSDIFF:
Amin Hassani49fdb092017-08-04 13:10:59 -0700695 case InstallOperation::PUFFDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700696 case InstallOperation::ZUCCHINI:
Kelvin Zhangcb2dc882021-11-22 09:26:50 -0800697 case InstallOperation::LZ4DIFF_PUFFDIFF:
698 case InstallOperation::LZ4DIFF_BSDIFF:
Tianjie8e0090d2021-08-30 22:35:21 -0700699 op_result = PerformDiffOperation(op, error);
700 OP_DURATION_HISTOGRAM(op_name, op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800701 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700702 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700703 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700704 }
Tianjie8e0090d2021-08-30 22:35:21 -0700705 if (!HandleOpResult(op_result, op_name.c_str(), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800706 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800707
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700708 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800709 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800710 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700711 }
Sen Jiangf6813802015-11-03 21:27:29 -0800712
Kelvin Zhang4f28a6c2021-01-14 14:04:57 -0500713 if (partition_writer_) {
714 TEST_AND_RETURN_FALSE(partition_writer_->FinishedInstallOps());
715 }
716 CloseCurrentPartition();
717
Saint Chou0a92a622020-07-29 14:25:35 +0000718 // In major version 2, we don't add unused operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800719 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000720 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800721 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800722 if (manifest_.signatures_offset() != buffer_offset_) {
723 LOG(ERROR) << "Payload signatures offset points to blob offset "
724 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800725 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800726 *error = ErrorCode::kDownloadPayloadVerificationError;
727 return false;
728 }
729 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
730 // Needs more data to cover entire signature.
731 if (buffer_.size() < manifest_.signatures_size())
732 return true;
733 if (!ExtractSignatureMessage()) {
734 LOG(ERROR) << "Extract payload signature failed.";
735 *error = ErrorCode::kDownloadPayloadVerificationError;
736 return false;
737 }
738 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800739 // Since we extracted the SignatureMessage we need to advance the
740 // checkpoint, otherwise we would reload the signature and try to extract
741 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800742 // This is the last checkpoint for an update, force this checkpoint to be
743 // saved.
744 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800745 }
746
Don Garrette410e0f2011-11-10 15:39:01 -0800747 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700748}
749
David Zeuthen8f191b22013-08-06 12:27:50 -0700750bool DeltaPerformer::IsManifestValid() {
751 return manifest_valid_;
752}
753
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700754bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700755 partitions_.assign(manifest_.partitions().begin(),
756 manifest_.partitions().end());
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700757
Tianjied3865d12020-06-03 15:25:17 -0700758 // For VAB and partial updates, the partition preparation will copy the
759 // dynamic partitions metadata to the target metadata slot, and rename the
760 // slot suffix of the partitions in the metadata.
761 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
762 uint64_t required_size = 0;
Daniel Zhengeede4c82023-06-13 11:21:06 -0700763 if (!PreparePartitionsForUpdate(&required_size, error)) {
764 if (*error == ErrorCode::kOverlayfsenabledError) {
765 return false;
766 } else if (required_size > 0) {
Tianjied3865d12020-06-03 15:25:17 -0700767 *error = ErrorCode::kNotEnoughSpace;
768 } else {
769 *error = ErrorCode::kInstallDeviceOpenError;
770 }
771 return false;
772 }
773 }
774
Tianjie55abd3c2020-06-19 00:22:59 -0700775 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000776 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700777 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
778 // partition.
779 if (manifest_.partial_update()) {
780 std::set<std::string> touched_partitions;
781 for (const auto& partition_update : partitions_) {
782 touched_partitions.insert(partition_update.partition_name());
783 }
784
Tianjie99d570d2020-06-04 14:57:19 -0700785 auto generator = partition_update_generator::Create(boot_control_,
786 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700787 std::vector<PartitionUpdate> untouched_static_partitions;
Kelvin Zhang430852d2023-05-25 17:00:24 -0700788 if (!generator->GenerateOperationsForPartitionsNotInPayload(
Tianjied3865d12020-06-03 15:25:17 -0700789 install_plan_->source_slot,
790 install_plan_->target_slot,
791 touched_partitions,
Kelvin Zhang430852d2023-05-25 17:00:24 -0700792 &untouched_static_partitions)) {
793 LOG(ERROR)
794 << "Failed to generate operations for partitions not in payload "
795 << android::base::Join(touched_partitions, ", ");
796 *error = ErrorCode::kDownloadStateInitializationError;
797 return false;
798 }
Tianjie24f96092020-06-30 12:26:25 -0700799 partitions_.insert(partitions_.end(),
800 untouched_static_partitions.begin(),
801 untouched_static_partitions.end());
802
803 // Save the untouched dynamic partitions in install plan.
804 std::vector<std::string> dynamic_partitions;
805 if (!boot_control_->GetDynamicPartitionControl()
806 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
Tianjie3a55fc22021-02-13 16:02:22 -0800807 boot_control_->GetCurrentSlot(),
Tianjie24f96092020-06-30 12:26:25 -0700808 &dynamic_partitions)) {
809 LOG(ERROR) << "Failed to load dynamic partitions from slot "
810 << install_plan_->source_slot;
811 return false;
812 }
813 install_plan_->untouched_dynamic_partitions.clear();
814 for (const auto& name : dynamic_partitions) {
815 if (touched_partitions.find(name) == touched_partitions.end()) {
816 install_plan_->untouched_dynamic_partitions.push_back(name);
817 }
818 }
Tianjied3865d12020-06-03 15:25:17 -0700819 }
820
Kelvin Zhang8ddadd32023-12-12 12:54:30 -0800821 const auto start = std::chrono::system_clock::now();
Kelvin Zhang20982a52021-08-13 12:31:16 -0700822 if (!install_plan_->ParsePartitions(
823 partitions_, boot_control_, block_size_, error)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700824 return false;
825 }
Kelvin Zhang8ddadd32023-12-12 12:54:30 -0800826 const auto duration = std::chrono::system_clock::now() - start;
827 LOG(INFO)
828 << "ParsePartitions done. took "
829 << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()
830 << " ms";
831
Kelvin Zhangab15beb2022-12-05 10:19:52 -0800832 auto&& has_verity = [](const auto& part) {
833 return part.fec_extent().num_blocks() > 0 ||
834 part.hash_tree_extent().num_blocks() > 0;
835 };
836 if (!std::any_of(partitions_.begin(), partitions_.end(), has_verity)) {
837 install_plan_->write_verity = false;
838 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700839
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700840 LogPartitionInfo(partitions_);
841 return true;
842}
843
Daniel Zhengeede4c82023-06-13 11:21:06 -0700844bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size,
845 ErrorCode* error) {
Yifan Hongb9d63572020-01-09 17:50:46 -0800846 // Call static PreparePartitionsForUpdate with hash from
847 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
848 // preallocated for is the same as the hash of payload being applied.
849 string update_check_response_hash;
850 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
851 &update_check_response_hash));
852 return PreparePartitionsForUpdate(prefs_,
853 boot_control_,
854 install_plan_->target_slot,
855 manifest_,
856 update_check_response_hash,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700857 required_size,
858 error);
Yifan Hongb9d63572020-01-09 17:50:46 -0800859}
860
861bool DeltaPerformer::PreparePartitionsForUpdate(
862 PrefsInterface* prefs,
863 BootControlInterface* boot_control,
864 BootControlInterface::Slot target_slot,
865 const DeltaArchiveManifest& manifest,
866 const std::string& update_check_response_hash,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700867 uint64_t* required_size,
868 ErrorCode* error) {
Yifan Hongb9d63572020-01-09 17:50:46 -0800869 string last_hash;
870 ignore_result(
871 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
872
873 bool is_resume = !update_check_response_hash.empty() &&
874 last_hash == update_check_response_hash;
875
876 if (is_resume) {
877 LOG(INFO) << "Using previously prepared partitions for update. hash = "
878 << last_hash;
879 } else {
880 LOG(INFO) << "Preparing partitions for new update. last hash = "
881 << last_hash << ", new hash = " << update_check_response_hash;
Kelvin Zhang51e08b92021-02-19 14:54:21 -0500882 ResetUpdateProgress(prefs, false);
Yifan Hongb9d63572020-01-09 17:50:46 -0800883 }
884
Kelvin Zhang8ddadd32023-12-12 12:54:30 -0800885 const auto start = std::chrono::system_clock::now();
Yifan Hongb9d63572020-01-09 17:50:46 -0800886 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
887 boot_control->GetCurrentSlot(),
888 target_slot,
889 manifest,
890 !is_resume /* should update */,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700891 required_size,
892 error)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700893 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Daniel Zhengeede4c82023-06-13 11:21:06 -0700894 << BootControlInterface::SlotName(target_slot) << " "
895 << utils::ErrorCodeToString(*error);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700896 return false;
897 }
Kelvin Zhang8ddadd32023-12-12 12:54:30 -0800898 const auto duration = std::chrono::system_clock::now() - start;
Yifan Hongb9d63572020-01-09 17:50:46 -0800899
900 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
901 update_check_response_hash));
Kelvin Zhang8ddadd32023-12-12 12:54:30 -0800902 LOG(INFO)
903 << "PreparePartitionsForUpdate done. took "
904 << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()
905 << " ms";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700906
907 return true;
908}
909
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700910bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700911 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700912 // If we don't have a data blob we can apply it right away.
913 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700914 return true;
915
916 // See if we have the entire data blob in the buffer
917 if (operation.data_offset() < buffer_offset_) {
918 LOG(ERROR) << "we threw away data it seems?";
919 return false;
920 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700921
Gilad Arnoldfe133932014-01-14 12:25:50 -0800922 return (operation.data_offset() + operation.data_length() <=
923 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700924}
925
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700926bool DeltaPerformer::PerformReplaceOperation(
927 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700928 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700929 operation.type() == InstallOperation::REPLACE_BZ ||
930 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700931
932 // Since we delete data off the beginning of the buffer as we use it,
933 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700934 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700935
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400936 TEST_AND_RETURN_FALSE(partition_writer_->PerformReplaceOperation(
937 operation, buffer_.data(), buffer_.size()));
938 // Update buffer
939 DiscardBuffer(true, buffer_.size());
940 return true;
941}
942
Alex Deymo79715ad2015-10-02 14:27:53 -0700943bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700944 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700945 CHECK(operation.type() == InstallOperation::DISCARD ||
946 operation.type() == InstallOperation::ZERO);
947
948 // These operations have no blob.
949 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
950 TEST_AND_RETURN_FALSE(!operation.has_data_length());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400951
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400952 return partition_writer_->PerformZeroOrDiscardOperation(operation);
953}
Alex Deymo79715ad2015-10-02 14:27:53 -0700954
Allie Wood9f6f0a52015-03-30 11:25:47 -0700955bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700956 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700957 if (operation.has_src_length())
958 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
959 if (operation.has_dst_length())
960 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400961 return partition_writer_->PerformSourceCopyOperation(operation, error);
962}
Allie Wood9f6f0a52015-03-30 11:25:47 -0700963
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700964bool DeltaPerformer::ExtentsToBsdiffPositionsString(
965 const RepeatedPtrField<Extent>& extents,
966 uint64_t block_size,
967 uint64_t full_length,
968 string* positions_string) {
969 string ret;
970 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700971 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700972 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100973 uint64_t this_length =
974 min(full_length - length,
975 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700976 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700977 length += this_length;
978 }
979 TEST_AND_RETURN_FALSE(length == full_length);
980 if (!ret.empty())
981 ret.resize(ret.size() - 1); // Strip trailing comma off
982 *positions_string = ret;
983 return true;
984}
985
Tianjie8e0090d2021-08-30 22:35:21 -0700986bool DeltaPerformer::PerformDiffOperation(const InstallOperation& operation,
987 ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700988 // Since we delete data off the beginning of the buffer as we use it,
989 // the data we need should be exactly at the beginning of the buffer.
990 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
991 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
992 if (operation.has_src_length())
993 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
994 if (operation.has_dst_length())
995 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
996
Tianjie8e0090d2021-08-30 22:35:21 -0700997 TEST_AND_RETURN_FALSE(partition_writer_->PerformDiffOperation(
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400998 operation, error, buffer_.data(), buffer_.size()));
999 DiscardBuffer(true, buffer_.size());
1000 return true;
1001}
Amin Hassani02855c22017-09-06 22:34:50 -07001002
Sen Jiangf6813802015-11-03 21:27:29 -08001003bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001004 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1005 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1006 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001007 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -08001008 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001009
Darin Petkovd7061ab2010-10-06 14:37:09 -07001010 LOG(INFO) << "Extracted signature data of size "
1011 << manifest_.signatures_size() << " at "
1012 << manifest_.signatures_offset();
1013 return true;
1014}
1015
Sen Jiang08c6da12019-01-07 18:28:56 -08001016bool DeltaPerformer::GetPublicKey(string* out_public_key) {
1017 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -07001018
Sen Jiang08c6da12019-01-07 18:28:56 -08001019 if (utils::FileExists(public_key_path_.c_str())) {
1020 LOG(INFO) << "Verifying using public key: " << public_key_path_;
1021 return utils::ReadFile(public_key_path_, out_public_key);
1022 }
1023
Kelvin Zhang50bac652020-09-28 15:51:41 -04001024 // If this is an official build then we are not allowed to use public key
1025 // from Omaha response.
Sen Jiang08c6da12019-01-07 18:28:56 -08001026 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
1027 LOG(INFO) << "Verifying using public key from Omaha response.";
1028 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1029 out_public_key);
1030 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001031 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001032 return true;
1033}
1034
Tianjie Xu7a78d632019-10-08 16:32:39 -07001035std::pair<std::unique_ptr<PayloadVerifier>, bool>
1036DeltaPerformer::CreatePayloadVerifier() {
1037 if (utils::FileExists(update_certificates_path_.c_str())) {
1038 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1039 return {
1040 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1041 true};
1042 }
1043
1044 string public_key;
1045 if (!GetPublicKey(&public_key)) {
1046 LOG(ERROR) << "Failed to read public key";
1047 return {nullptr, true};
1048 }
1049
1050 // Skips the verification if the public key is empty.
1051 if (public_key.empty()) {
1052 return {nullptr, false};
1053 }
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001054 LOG(INFO) << "Verifing using public key: " << public_key;
Tianjie Xu7a78d632019-10-08 16:32:39 -07001055 return {PayloadVerifier::CreateInstance(public_key), true};
1056}
1057
Gilad Arnold21504f02013-05-24 08:51:22 -07001058ErrorCode DeltaPerformer::ValidateManifest() {
Saint Chou0a92a622020-07-29 14:25:35 +00001059 // Perform assorted checks to validation check the manifest, make sure it
Don Garrettb8dd1d92013-11-22 17:40:02 -08001060 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +00001061 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
1062 manifest_.partitions().end(),
1063 [](const PartitionUpdate& partition) {
1064 return partition.has_old_partition_info();
1065 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001066
Alex Deymo64d98782016-02-05 18:03:48 -08001067 // The presence of an old partition hash is the sole indicator for a delta
Tianjief5baff42020-07-17 21:43:22 -07001068 // update. Also, always treat the partial update as delta so that we can
1069 // perform the minor version check correctly.
Alex Deymo64d98782016-02-05 18:03:48 -08001070 InstallPayloadType actual_payload_type =
Tianjief5baff42020-07-17 21:43:22 -07001071 (has_old_fields || manifest_.partial_update())
1072 ? InstallPayloadType::kDelta
1073 : InstallPayloadType::kFull;
Alex Deymo64d98782016-02-05 18:03:48 -08001074
Sen Jiangcdd52062017-05-18 15:33:10 -07001075 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001076 LOG(INFO) << "Detected a '"
1077 << InstallPayloadTypeToString(actual_payload_type)
1078 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001079 payload_->type = actual_payload_type;
1080 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001081 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001082 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001083 << "' payload but the downloaded manifest contains a '"
1084 << InstallPayloadTypeToString(actual_payload_type)
1085 << "' payload.";
1086 return ErrorCode::kPayloadMismatchedType;
1087 }
Alex Deymo64d98782016-02-05 18:03:48 -08001088 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001089 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001090 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001091 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1092 LOG(ERROR) << "Manifest contains minor version "
1093 << manifest_.minor_version()
1094 << ", but all full payloads should have version "
1095 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001096 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001097 }
1098 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001099 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1100 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001101 LOG(ERROR) << "Manifest contains minor version "
1102 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001103 << " not in the range of supported minor versions ["
1104 << kMinSupportedMinorPayloadVersion << ", "
1105 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001107 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001108 }
1109
Yifan Hong87029332020-09-01 17:20:08 -07001110 ErrorCode error_code = CheckTimestampError();
1111 if (error_code != ErrorCode::kSuccess) {
1112 if (error_code == ErrorCode::kPayloadTimestampError) {
1113 if (!hardware_->AllowDowngrade()) {
1114 return ErrorCode::kPayloadTimestampError;
1115 }
1116 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1117 " the payload with an older timestamp.";
1118 } else {
1119 LOG(ERROR) << "Timestamp check returned "
1120 << utils::ErrorCodeToString(error_code);
1121 return error_code;
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001122 }
Sen Jiang8e768e92017-06-28 17:13:19 -07001123 }
1124
Amin Hassani55c75412019-10-07 11:20:39 -07001125 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1126 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001127
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001128 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001129}
1130
Yifan Hong87029332020-09-01 17:20:08 -07001131ErrorCode DeltaPerformer::CheckTimestampError() const {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001132 bool is_partial_update =
1133 manifest_.has_partial_update() && manifest_.partial_update();
1134 const auto& partitions = manifest_.partitions();
Yifan Hong87029332020-09-01 17:20:08 -07001135
1136 // Check version field for a given PartitionUpdate object. If an error
1137 // is encountered, set |error_code| accordingly. If downgrade is detected,
Kelvin Zhang50bac652020-09-28 15:51:41 -04001138 // |downgrade_detected| is set. Return true if the program should continue
1139 // to check the next partition or not, or false if it should exit early due
1140 // to errors.
Yifan Hong87029332020-09-01 17:20:08 -07001141 auto&& timestamp_valid = [this](const PartitionUpdate& partition,
1142 bool allow_empty_version,
1143 bool* downgrade_detected) -> ErrorCode {
Tianjie19e55292020-10-19 21:49:37 -07001144 const auto& partition_name = partition.partition_name();
Yifan Hong87029332020-09-01 17:20:08 -07001145 if (!partition.has_version()) {
Tianjie19e55292020-10-19 21:49:37 -07001146 if (hardware_->GetVersionForLogging(partition_name).empty()) {
1147 LOG(INFO) << partition_name << " does't have version, skipping "
1148 << "downgrade check.";
1149 return ErrorCode::kSuccess;
1150 }
1151
Yifan Hong87029332020-09-01 17:20:08 -07001152 if (allow_empty_version) {
1153 return ErrorCode::kSuccess;
1154 }
1155 LOG(ERROR)
Tianjie19e55292020-10-19 21:49:37 -07001156 << "PartitionUpdate " << partition_name
1157 << " doesn't have a version field. Not allowed in partial updates.";
Yifan Hong87029332020-09-01 17:20:08 -07001158 return ErrorCode::kDownloadManifestParseError;
1159 }
1160
Tianjie19e55292020-10-19 21:49:37 -07001161 auto error_code =
1162 hardware_->IsPartitionUpdateValid(partition_name, partition.version());
Yifan Hong87029332020-09-01 17:20:08 -07001163 switch (error_code) {
1164 case ErrorCode::kSuccess:
1165 break;
1166 case ErrorCode::kPayloadTimestampError:
1167 *downgrade_detected = true;
Tianjie19e55292020-10-19 21:49:37 -07001168 LOG(WARNING) << "PartitionUpdate " << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001169 << " has an older version than partition on device.";
1170 break;
1171 default:
Tianjie19e55292020-10-19 21:49:37 -07001172 LOG(ERROR) << "IsPartitionUpdateValid(" << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001173 << ") returned" << utils::ErrorCodeToString(error_code);
1174 break;
1175 }
1176 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001177 };
Yifan Hong87029332020-09-01 17:20:08 -07001178
1179 bool downgrade_detected = false;
1180
Kelvin Zhangd7191032020-08-11 10:48:16 -04001181 if (is_partial_update) {
1182 // for partial updates, all partition MUST have valid timestamps
1183 // But max_timestamp can be empty
1184 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001185 auto error_code = timestamp_valid(
1186 partition, false /* allow_empty_version */, &downgrade_detected);
1187 if (error_code != ErrorCode::kSuccess &&
1188 error_code != ErrorCode::kPayloadTimestampError) {
1189 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001190 }
1191 }
Yifan Hong87029332020-09-01 17:20:08 -07001192 if (downgrade_detected) {
1193 return ErrorCode::kPayloadTimestampError;
1194 }
1195 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001196 }
Yifan Hong87029332020-09-01 17:20:08 -07001197
1198 // For non-partial updates, check max_timestamp first.
Kelvin Zhangd7191032020-08-11 10:48:16 -04001199 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1200 LOG(ERROR) << "The current OS build timestamp ("
1201 << hardware_->GetBuildTimestamp()
1202 << ") is newer than the maximum timestamp in the manifest ("
1203 << manifest_.max_timestamp() << ")";
Yifan Hong87029332020-09-01 17:20:08 -07001204 return ErrorCode::kPayloadTimestampError;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001205 }
1206 // Otherwise... partitions can have empty timestamps.
1207 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001208 auto error_code = timestamp_valid(
1209 partition, true /* allow_empty_version */, &downgrade_detected);
1210 if (error_code != ErrorCode::kSuccess &&
1211 error_code != ErrorCode::kPayloadTimestampError) {
1212 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001213 }
1214 }
Yifan Hong87029332020-09-01 17:20:08 -07001215 if (downgrade_detected) {
1216 return ErrorCode::kPayloadTimestampError;
1217 }
1218 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001219}
1220
David Zeuthena99981f2013-04-29 13:42:47 -07001221ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001222 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001223 if (!operation.data_sha256_hash().size()) {
1224 if (!operation.data_length()) {
Kelvin Zhang50bac652020-09-28 15:51:41 -04001225 // Operations that do not have any data blob won't have any operation
1226 // hash either. So, these operations are always considered validated
1227 // since the metadata that contains all the non-data-blob portions of
1228 // the operation has already been validated. This is true for both HTTP
1229 // and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001230 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 }
1232
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001233 // No hash is present for an operation that has data blobs. This shouldn't
1234 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001235 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001236 // hashes. So if it happens it means either we've turned operation hash
1237 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Saint Chou0a92a622020-07-29 14:25:35 +00001238 // One caveat though: The last operation is a unused signature operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001239 // that doesn't have a hash at the time the manifest is created. So we
1240 // should not complaint about that operation. This operation can be
1241 // recognized by the fact that it's offset is mentioned in the manifest.
1242 if (manifest_.signatures_offset() &&
1243 manifest_.signatures_offset() == operation.data_offset()) {
1244 LOG(INFO) << "Skipping hash verification for signature operation "
1245 << next_operation_num_ + 1;
1246 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001247 if (install_plan_->hash_checks_mandatory) {
1248 LOG(ERROR) << "Missing mandatory operation hash for operation "
1249 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001251 }
1252
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001253 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1254 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001255 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001256 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001257 }
1258
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001259 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001260 expected_op_hash.assign(operation.data_sha256_hash().data(),
1261 (operation.data_sha256_hash().data() +
1262 operation.data_sha256_hash().size()));
1263
Sen Jiang2703ef42017-03-16 13:36:21 -07001264 brillo::Blob calculated_op_hash;
1265 if (!HashCalculator::RawHashOfBytes(
1266 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001267 LOG(ERROR) << "Unable to compute actual hash of operation "
1268 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001269 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001270 }
1271
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001272 if (calculated_op_hash != expected_op_hash) {
1273 LOG(ERROR) << "Hash verification failed for operation "
Kelvin Zhangb9368922022-03-17 21:11:32 -07001274 << next_operation_num_
1275 << ". Expected hash = " << HexEncode(expected_op_hash);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001276 LOG(ERROR) << "Calculated hash over " << operation.data_length()
Kelvin Zhangb9368922022-03-17 21:11:32 -07001277 << " bytes at offset: " << operation.data_offset() << " = "
1278 << HexEncode(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001279 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001280 }
1281
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001282 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001283}
1284
Amin Hassani008c4582019-01-13 16:22:47 -08001285#define TEST_AND_RETURN_VAL(_retval, _condition) \
1286 do { \
1287 if (!(_condition)) { \
1288 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1289 return _retval; \
1290 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001291 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001292
David Zeuthena99981f2013-04-29 13:42:47 -07001293ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001294 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001295 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001296 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001297 if (update_check_response_size !=
1298 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1299 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1300 << ") doesn't match metadata_size (" << metadata_size_
1301 << ") + metadata_signature_size (" << metadata_signature_size_
1302 << ") + buffer_offset (" << buffer_offset_ << ").";
1303 return ErrorCode::kPayloadSizeMismatchError;
1304 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001305
Amin Hassanie331f5a2020-10-06 15:53:29 -07001306 // Verifies the payload hash.
1307 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
1308 !payload_hash_calculator_.raw_hash().empty());
Kelvin Zhangdf3c1952021-10-06 18:56:55 -07001309 if (payload_hash_calculator_.raw_hash() != update_check_response_hash) {
1310 LOG(ERROR) << "Actual hash: "
1311 << HexEncode(payload_hash_calculator_.raw_hash())
1312 << ", expected hash: " << HexEncode(update_check_response_hash);
1313 return ErrorCode::kPayloadHashMismatchError;
1314 }
Amin Hassanie331f5a2020-10-06 15:53:29 -07001315
Amin Hassaniec7bc112020-10-29 16:47:58 -07001316 // NOLINTNEXTLINE(whitespace/braces)
Amin Hassanif624e112020-09-15 15:30:08 -07001317 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1318 if (!perform_verification) {
1319 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1320 return ErrorCode::kSuccess;
1321 }
1322 if (!payload_verifier) {
1323 LOG(ERROR) << "Failed to create the payload verifier.";
1324 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1325 }
1326
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001327 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001328 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001329 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001330 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001331 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001332
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001333 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001334 // The autoupdate_CatchBadSignatures test checks for this string
1335 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001336 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001337 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001338 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001339
David Zeuthene7f89172013-10-31 10:21:04 -07001340 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001341 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001342}
1343
Sen Jiangf6813802015-11-03 21:27:29 -08001344void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1345 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001346 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001347 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001348 buffer_offset_ += buffer_.size();
1349
1350 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001351 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1352 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001353
1354 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001355 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001356}
1357
Darin Petkov0406e402010-10-06 21:33:11 -07001358bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001359 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001360 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001361 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001362 next_operation != kUpdateStateOperationInvalid && next_operation > 0)) {
1363 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateNextOperation
1364 << " invalid: " << next_operation;
Alex Deymo3310b222015-03-30 15:59:07 -07001365 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001366 }
Darin Petkov0406e402010-10-06 21:33:11 -07001367
1368 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001369 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1370 !interrupted_hash.empty() &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001371 interrupted_hash == update_check_response_hash)) {
1372 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateCheckResponseHash
1373 << " mismatch, last hash: " << interrupted_hash
1374 << ", current hash: " << update_check_response_hash << "";
Alex Deymo3310b222015-03-30 15:59:07 -07001375 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001376 }
Darin Petkov0406e402010-10-06 21:33:11 -07001377
Daniel Zhengda4f7292022-09-02 22:59:32 +00001378 int64_t resumed_update_failures{};
Kelvin Zhang50bac652020-09-28 15:51:41 -04001379 // Note that storing this value is optional, but if it is there it should
1380 // not be more than the limit.
Alex Deymof25eb492016-02-26 00:20:08 -08001381 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001382 resumed_update_failures > kMaxResumedUpdateFailures) {
1383 LOG(WARNING) << "Failed to resume update " << kPrefsResumedUpdateFailures
Kelvin Zhang8ddadd32023-12-12 12:54:30 -08001384 << " has value " << resumed_update_failures
1385 << " is over the limit " << kMaxResumedUpdateFailures;
Alex Deymo3310b222015-03-30 15:59:07 -07001386 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001387 }
Darin Petkov61426142010-10-08 11:04:55 -07001388
Saint Chou0a92a622020-07-29 14:25:35 +00001389 // Validation check the rest.
Darin Petkov0406e402010-10-06 21:33:11 -07001390 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001391 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001392 next_data_offset >= 0)) {
1393 LOG(WARNING) << "Failed to resume update "
1394 << kPrefsUpdateStateNextDataOffset
1395 << " invalid: " << next_data_offset;
Alex Deymo3310b222015-03-30 15:59:07 -07001396 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001397 }
Darin Petkov0406e402010-10-06 21:33:11 -07001398
Darin Petkov437adc42010-10-07 13:12:24 -07001399 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001400 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001401 !sha256_context.empty())) {
1402 LOG(WARNING) << "Failed to resume update " << kPrefsUpdateStateSHA256Context
1403 << " is empty.";
Alex Deymo3310b222015-03-30 15:59:07 -07001404 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001405 }
Darin Petkov0406e402010-10-06 21:33:11 -07001406
1407 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001408 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001409 manifest_metadata_size > 0)) {
1410 LOG(WARNING) << "Failed to resume update " << kPrefsManifestMetadataSize
1411 << " invalid: " << manifest_metadata_size;
Alex Deymo3310b222015-03-30 15:59:07 -07001412 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001413 }
Darin Petkov0406e402010-10-06 21:33:11 -07001414
Alex Deymof25eb492016-02-26 00:20:08 -08001415 int64_t manifest_signature_size = 0;
1416 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1417 &manifest_signature_size) &&
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001418 manifest_signature_size >= 0)) {
1419 LOG(WARNING) << "Failed to resume update " << kPrefsManifestSignatureSize
1420 << " invalid: " << manifest_signature_size;
Alex Deymof25eb492016-02-26 00:20:08 -08001421 return false;
Kelvin Zhang42f81b82022-10-04 10:43:08 -07001422 }
Alex Deymof25eb492016-02-26 00:20:08 -08001423
Darin Petkov0406e402010-10-06 21:33:11 -07001424 return true;
1425}
1426
Daniel Zhengf9784802023-06-08 08:39:48 -07001427bool DeltaPerformer::ResetUpdateProgress(
1428 PrefsInterface* prefs,
1429 bool quick,
1430 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07001431 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1432 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001433 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001434 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001435 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001436 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1437 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001438 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001439 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001440 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001441 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001442 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001443 prefs->Delete(kPrefsVerityWritten);
Daniel Zhengf9784802023-06-08 08:39:48 -07001444 if (!skip_dynamic_partititon_metadata_updated) {
1445 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1446 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
1447 }
Darin Petkov9b230572010-10-08 10:20:09 -07001448 }
Darin Petkov73058b42010-10-06 16:32:19 -07001449 return true;
1450}
1451
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001452bool DeltaPerformer::ShouldCheckpoint() {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001453 base::TimeTicks curr_time = base::TimeTicks::Now();
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001454 if (curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001455 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001456 return true;
1457 }
1458 return false;
1459}
1460
1461bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
1462 if (!force && !ShouldCheckpoint()) {
Colin Howes0e452c92018-11-02 13:18:44 -07001463 return false;
1464 }
Darin Petkov9c0baf82010-10-07 13:44:48 -07001465 Terminator::set_exit_blocked(true);
Daniel Zheng5eece042023-05-17 14:44:10 -07001466 LOG_IF(WARNING, !prefs_->StartTransaction())
1467 << "unable to start transaction in checkpointing";
1468 DEFER {
1469 prefs_->CancelTransaction();
1470 };
Kelvin Zhang3265b312020-12-16 15:51:30 -05001471 if (last_updated_operation_num_ != next_operation_num_ || force) {
Kelvin Zhangbb8e9992020-12-28 10:28:48 -05001472 if (!signatures_message_data_.empty()) {
1473 // Save the signature blob because if the update is interrupted after the
1474 // download phase we don't go through this path anymore. Some alternatives
1475 // to consider:
1476 //
1477 // 1. On resume, re-download the signature blob from the server and
1478 // re-verify it.
1479 //
1480 // 2. Verify the signature as soon as it's received and don't checkpoint
1481 // the blob and the signed sha-256 context.
1482 LOG_IF(WARNING,
1483 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
1484 signatures_message_data_))
1485 << "Unable to store the signature blob.";
1486 }
Amin Hassani008c4582019-01-13 16:22:47 -08001487 TEST_AND_RETURN_FALSE(prefs_->SetString(
1488 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001489 TEST_AND_RETURN_FALSE(
1490 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1491 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001492 TEST_AND_RETURN_FALSE(
1493 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001494 last_updated_operation_num_ = next_operation_num_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001495
1496 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001497 size_t partition_index = current_partition_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001498 while (next_operation_num_ >= acc_num_operations_[partition_index]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001499 partition_index++;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001500 }
Amin Hassani008c4582019-01-13 16:22:47 -08001501 const size_t partition_operation_num =
1502 next_operation_num_ -
1503 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001504 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001505 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001506 TEST_AND_RETURN_FALSE(
1507 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001508 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001509 TEST_AND_RETURN_FALSE(
1510 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001511 }
Kelvin Zhange4235b02020-11-23 13:57:51 -05001512 if (partition_writer_) {
1513 partition_writer_->CheckpointUpdateProgress(GetPartitionOperationNum());
1514 } else {
1515 CHECK_EQ(next_operation_num_, num_total_operations_)
1516 << "Partition writer is null, we are expected to finish all "
1517 "operations: "
1518 << next_operation_num_ << "/" << num_total_operations_;
1519 }
Darin Petkov0406e402010-10-06 21:33:11 -07001520 }
Amin Hassani008c4582019-01-13 16:22:47 -08001521 TEST_AND_RETURN_FALSE(
1522 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Daniel Zheng5eece042023-05-17 14:44:10 -07001523 if (!prefs_->SubmitTransaction()) {
1524 LOG(ERROR) << "Failed to submit transaction in checkpointing";
1525 }
Darin Petkov73058b42010-10-06 16:32:19 -07001526 return true;
1527}
1528
Darin Petkov9b230572010-10-08 10:20:09 -07001529bool DeltaPerformer::PrimeUpdateState() {
1530 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001531
1532 int64_t next_operation = kUpdateStateOperationInvalid;
1533 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001534 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001535 // Initiating a new update, no more state needs to be initialized.
1536 return true;
1537 }
1538 next_operation_num_ = next_operation;
1539
1540 // Resuming an update -- load the rest of the update state.
1541 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001542 TEST_AND_RETURN_FALSE(
1543 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1544 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001545 buffer_offset_ = next_data_offset;
1546
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001547 // The signed hash context and the signature blob may be empty if the
1548 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001549 string signed_hash_context;
1550 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1551 &signed_hash_context)) {
1552 TEST_AND_RETURN_FALSE(
1553 signed_hash_calculator_.SetContext(signed_hash_context));
1554 }
1555
Sen Jiang9b2f1782019-01-24 14:27:50 -08001556 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001557
1558 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001559 TEST_AND_RETURN_FALSE(
1560 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1561 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001562
1563 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001564 TEST_AND_RETURN_FALSE(
1565 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1566 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001567 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001568
Alex Deymof25eb492016-02-26 00:20:08 -08001569 int64_t manifest_signature_size = 0;
1570 TEST_AND_RETURN_FALSE(
1571 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1572 manifest_signature_size >= 0);
1573 metadata_signature_size_ = manifest_signature_size;
1574
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001575 // Advance the download progress to reflect what doesn't need to be
1576 // re-downloaded.
1577 total_bytes_received_ += buffer_offset_;
1578
Darin Petkov61426142010-10-08 11:04:55 -07001579 // Speculatively count the resume as a failure.
Daniel Zhengda4f7292022-09-02 22:59:32 +00001580 int64_t resumed_update_failures{};
Darin Petkov61426142010-10-08 11:04:55 -07001581 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1582 resumed_update_failures++;
1583 } else {
1584 resumed_update_failures = 1;
1585 }
1586 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001587 return true;
1588}
1589
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001590bool DeltaPerformer::IsDynamicPartition(const std::string& part_name,
1591 uint32_t slot) {
Tianjie3a55fc22021-02-13 16:02:22 -08001592 return boot_control_->GetDynamicPartitionControl()->IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001593 part_name, slot);
Kelvin Zhang94f51cc2020-09-25 11:34:49 -04001594}
1595
Kelvin Zhange52b6cd2021-02-09 15:28:40 -05001596std::unique_ptr<PartitionWriterInterface> DeltaPerformer::CreatePartitionWriter(
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001597 const PartitionUpdate& partition_update,
1598 const InstallPlan::Partition& install_part,
1599 DynamicPartitionControlInterface* dynamic_control,
1600 size_t block_size,
1601 bool is_interactive,
1602 bool is_dynamic_partition) {
1603 return partition_writer::CreatePartitionWriter(
1604 partition_update,
1605 install_part,
1606 dynamic_control,
1607 block_size_,
1608 interactive_,
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001609 IsDynamicPartition(install_part.name, install_plan_->target_slot));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001610}
1611
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001612} // namespace chromeos_update_engine