blob: b06d04e03b41b09aeb94f4936fcfadec164ddb02 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/payload_consumer/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070020#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include <algorithm>
23#include <cstring>
Yifan Hong537802d2018-08-15 13:15:42 -070024#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Tianjied3865d12020-06-03 15:25:17 -070026#include <set>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027#include <string>
Amin Hassanid87304c2017-08-29 11:40:03 -070028#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029#include <vector>
30
Ben Chan06c76a42014-09-05 08:21:06 -070031#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070032#include <base/format_macros.h>
Lann Martin39f57142017-07-14 09:18:42 -060033#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070034#include <base/strings/string_number_conversions.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/string_util.h>
36#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060037#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070038#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070039#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040#include <google/protobuf/repeated_field.h>
Amin Hassani02855c22017-09-06 22:34:50 -070041#include <puffin/puffpatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070042
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070044#include "update_engine/common/download_action.h"
Yifan Hong87029332020-09-01 17:20:08 -070045#include "update_engine/common/error_code.h"
46#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030048#include "update_engine/common/prefs_interface.h"
49#include "update_engine/common/subprocess.h"
50#include "update_engine/common/terminator.h"
Kelvin Zhang52cb1d72020-10-27 13:44:25 -040051#include "update_engine/common/utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080052#include "update_engine/payload_consumer/bzip_extent_writer.h"
Amin Hassania3fc20a2017-09-19 17:19:34 -070053#include "update_engine/payload_consumer/cached_file_descriptor.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070054#include "update_engine/payload_consumer/certificate_parser_interface.h"
Amin Hassanidb56be92017-09-06 12:41:23 -070055#include "update_engine/payload_consumer/extent_reader.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/payload_consumer/extent_writer.h"
Tianjied3865d12020-06-03 15:25:17 -070057#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040058#include "update_engine/payload_consumer/partition_writer.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070059#if USE_FEC
60#include "update_engine/payload_consumer/fec_file_descriptor.h"
61#endif // USE_FEC
Alex Deymoa48f6302016-11-04 15:49:53 -070062#include "update_engine/payload_consumer/file_descriptor_utils.h"
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +010063#include "update_engine/payload_consumer/mount_history.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080064#include "update_engine/payload_consumer/payload_constants.h"
65#include "update_engine/payload_consumer/payload_verifier.h"
66#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070067
Alex Deymo161c4a12014-05-16 15:56:21 -070068using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070069using std::min;
70using std::string;
71using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070072
73namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080074const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
75const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
76const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
77const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070078const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080079
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070080namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070081const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070082const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080083
Alex Vakulenkod2779df2014-06-16 13:19:00 -070084} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070085
Gilad Arnold8a86fa52013-01-15 12:35:05 -080086// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
87// arithmetic.
88static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
89 return part * norm / total;
90}
91
92void DeltaPerformer::LogProgress(const char* message_prefix) {
93 // Format operations total count and percentage.
94 string total_operations_str("?");
95 string completed_percentage_str("");
96 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -070097 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -080098 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -080099 completed_percentage_str = base::StringPrintf(
100 " (%" PRIu64 "%%)",
101 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800102 }
103
104 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800105 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800106 string payload_size_str("?");
107 string downloaded_percentage_str("");
108 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700109 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800110 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800111 downloaded_percentage_str = base::StringPrintf(
112 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800113 }
114
115 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
116 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800117 << completed_percentage_str << ", " << total_bytes_received_ << "/"
118 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800119 << downloaded_percentage_str << ", overall progress "
120 << overall_progress_ << "%";
121}
122
123void DeltaPerformer::UpdateOverallProgress(bool force_log,
124 const char* message_prefix) {
125 // Compute our download and overall progress.
126 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800127 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
128 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800129 // Only consider download progress if its total size is known; otherwise
130 // adjust the operations weight to compensate for the absence of download
131 // progress. Also, make sure to cap the download portion at
132 // kProgressDownloadWeight, in case we end up downloading more than we
133 // initially expected (this indicates a problem, but could generally happen).
134 // TODO(garnold) the correction of operations weight when we do not have the
135 // total payload size, as well as the conditional guard below, should both be
136 // eliminated once we ensure that the payload_size in the install plan is
137 // always given and is non-zero. This currently isn't the case during unit
138 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800139 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800140 unsigned actual_operations_weight = kProgressOperationsWeight;
141 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800142 new_overall_progress +=
143 min(static_cast<unsigned>(IntRatio(
144 total_bytes_received_, payload_size, kProgressDownloadWeight)),
145 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800146 else
147 actual_operations_weight += kProgressDownloadWeight;
148
149 // Only add completed operations if their total number is known; we definitely
150 // expect an update to have at least one operation, so the expectation is that
151 // this will eventually reach |actual_operations_weight|.
152 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800153 new_overall_progress += IntRatio(
154 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800155
156 // Progress ratio cannot recede, unless our assumptions about the total
157 // payload size, total number of operations, or the monotonicity of progress
158 // is breached.
159 if (new_overall_progress < overall_progress_) {
160 LOG(WARNING) << "progress counter receded from " << overall_progress_
161 << "% down to " << new_overall_progress << "%; this is a bug";
162 force_log = true;
163 }
164 overall_progress_ = new_overall_progress;
165
166 // Update chunk index, log as needed: if forced by called, or we completed a
167 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800168 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800169 unsigned curr_progress_chunk =
170 overall_progress_ * kProgressLogMaxChunks / 100;
171 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
172 curr_time > forced_progress_log_time_) {
173 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
174 LogProgress(message_prefix);
175 }
176 last_progress_chunk_ = curr_progress_chunk;
177}
178
Amin Hassani008c4582019-01-13 16:22:47 -0800179size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
180 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800181 size_t max) {
182 const size_t count = *count_p;
183 if (!count)
184 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700185 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800186 const char* bytes_start = *bytes_p;
187 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800188 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800189 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
190 *bytes_p = bytes_end;
191 *count_p = count - read_len;
192 return read_len;
193}
194
Amin Hassani008c4582019-01-13 16:22:47 -0800195bool DeltaPerformer::HandleOpResult(bool op_result,
196 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800197 ErrorCode* error) {
198 if (op_result)
199 return true;
200
201 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700202 << next_operation_num_ << ", which is the operation "
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400203 << GetPartitionOperationNum() << " in partition \""
Alex Deymo3d009062016-05-13 15:51:25 -0700204 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700205 if (*error == ErrorCode::kSuccess)
206 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800207 return false;
208}
209
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700210int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700211 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800212 LOG_IF(ERROR,
213 !payload_hash_calculator_.Finalize() ||
214 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800215 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800216 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700217 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
218 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800219 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800220 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700221 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700222}
223
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700224int DeltaPerformer::CloseCurrentPartition() {
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400225 if (!partition_writer_) {
226 return 0;
227 }
228 int err = partition_writer_->Close();
229 partition_writer_ = nullptr;
230 return err;
231}
232
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700233bool DeltaPerformer::OpenCurrentPartition() {
234 if (current_partition_ >= partitions_.size())
235 return false;
236
237 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700238 size_t num_previous_partitions =
239 install_plan_->partitions.size() - partitions_.size();
240 const InstallPlan::Partition& install_part =
241 install_plan_->partitions[num_previous_partitions + current_partition_];
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400242 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
Kelvin Zhangcfe694f2020-11-13 13:10:42 -0500243 partition_writer_ =
244 CreatePartitionWriter(partition,
245 install_part,
246 dynamic_control,
247 block_size_,
248 interactive_,
249 IsDynamicPartition(install_part.name));
Tianjie55abd3c2020-06-19 00:22:59 -0700250 // Open source fds if we have a delta payload, or for partitions in the
251 // partial update.
Tianjied3865d12020-06-03 15:25:17 -0700252 bool source_may_exist = manifest_.partial_update() ||
Tianjie55abd3c2020-06-19 00:22:59 -0700253 payload_->type == InstallPayloadType::kDelta;
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400254 const size_t partition_operation_num = GetPartitionOperationNum();
255
256 TEST_AND_RETURN_FALSE(partition_writer_->Init(
257 install_plan_, source_may_exist, partition_operation_num));
258 CheckpointUpdateProgress(true);
259 return true;
260}
261
262size_t DeltaPerformer::GetPartitionOperationNum() {
263 return next_operation_num_ -
264 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400265}
266
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700267namespace {
268
269void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700270 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800271 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
272 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700273}
274
Alex Deymo39910dc2015-11-09 17:04:30 -0800275void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700276 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800277 if (partition.has_old_partition_info()) {
278 LogPartitionInfoHash(partition.old_partition_info(),
279 "old " + partition.partition_name());
280 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700281 LogPartitionInfoHash(partition.new_partition_info(),
282 "new " + partition.partition_name());
283 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700284}
285
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700286} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700287
Sen Jiangb8060e42015-09-24 17:30:50 -0700288bool DeltaPerformer::IsHeaderParsed() const {
289 return metadata_size_ != 0;
290}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700291
Sen Jiang9c89e842018-02-02 13:51:21 -0800292MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700293 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700294 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700295
Sen Jiangb8060e42015-09-24 17:30:50 -0700296 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700297 MetadataParseResult result =
298 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800299 if (result != MetadataParseResult::kSuccess)
300 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700301
Sen Jiang9c89e842018-02-02 13:51:21 -0800302 metadata_size_ = payload_metadata_.GetMetadataSize();
303 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
304 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800305
306 // If the metadata size is present in install plan, check for it immediately
307 // even before waiting for that many number of bytes to be downloaded in the
308 // payload. This will prevent any attack which relies on us downloading data
309 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800310 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800311 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800312 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800313 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800314 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700315 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800316 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800317 }
318 }
Andrew3a7dc262019-12-19 11:38:08 -0800319
320 // Check that the |metadata signature size_| and |metadata_size_| are not
321 // very big numbers. This is necessary since |update_engine| needs to write
322 // these values into the buffer before being able to use them, and if an
323 // attacker sets these values to a very big number, the buffer will overflow
324 // and |update_engine| will crash. A simple way of solving this is to check
325 // that the size of both values is smaller than the payload itself.
326 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
327 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
328 << " or metadata signature(" << metadata_signature_size_ << ")"
329 << " is greater than the size of the payload"
330 << "(" << payload_->size << ")";
331 *error = ErrorCode::kDownloadInvalidMetadataSize;
332 return MetadataParseResult::kError;
333 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700334 }
335
336 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700337 // metadata and its signature (if exist) to be read in before we can parse it.
338 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800339 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700340
341 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700342 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700343 // that we just log once (instead of logging n times) if it takes n
344 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800345 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700346 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800347 } else {
348 // For mandatory-cases, we'd have already returned a kMetadataParseError
349 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
350 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800351 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800352 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800353 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800354 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700355
Amin Hassaniec7bc112020-10-29 16:47:58 -0700356 // NOLINTNEXTLINE(whitespace/braces)
Tianjie Xu7a78d632019-10-08 16:32:39 -0700357 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
358 if (!payload_verifier) {
359 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800360 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700361 if (perform_verification) {
362 return MetadataParseResult::kError;
363 }
364 } else {
365 // We have the full metadata in |payload|. Verify its integrity
366 // and authenticity based on the information we have in Omaha response.
367 *error = payload_metadata_.ValidateMetadataSignature(
368 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800369 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700370 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800371 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800372 // The autoupdate_CatchBadSignatures test checks for this string
373 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800374 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800375 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800376 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700377
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800378 // For non-mandatory cases, just send a UMA stat.
379 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700380 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700381 }
382
Gilad Arnolddaa27402014-01-23 11:56:17 -0800383 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800384 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800385 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700386 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800387 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800388 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800389
390 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800391 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800392}
393
Amin Hassani008c4582019-01-13 16:22:47 -0800394#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
395 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
396 "UpdateEngine.DownloadAction.InstallOperation::" _op_name ".Duration", \
Andrew9d5a61d2020-03-26 13:40:37 -0700397 (base::TimeTicks::Now() - _start_time), \
Amin Hassani008c4582019-01-13 16:22:47 -0800398 base::TimeDelta::FromMilliseconds(10), \
399 base::TimeDelta::FromMinutes(5), \
400 20);
Lann Martin39f57142017-07-14 09:18:42 -0600401
Don Garrette410e0f2011-11-10 15:39:01 -0800402// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800403// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700404// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800405bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700406 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700407 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800408
409 // Update the total byte downloaded count and the progress logs.
410 total_bytes_received_ += count;
411 UpdateOverallProgress(false, "Completed ");
412
Gilad Arnoldfe133932014-01-14 12:25:50 -0800413 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700414 // Read data up to the needed limit; this is either maximium payload header
415 // size, or the full metadata size (once it becomes known).
416 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800417 CopyDataToBuffer(
418 &c_bytes,
419 &count,
420 (do_read_header ? kMaxPayloadHeaderSize
421 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800422
Gilad Arnolddaa27402014-01-23 11:56:17 -0800423 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800424 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800425 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800426 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800427 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700428 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800429 continue;
430
Don Garrette410e0f2011-11-10 15:39:01 -0800431 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800432 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700433
434 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700435 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700436 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800437 manifest_valid_ = true;
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400438 if (!install_plan_->is_resume) {
Kelvin Zhangcf4600e2020-10-27 15:50:33 -0400439 auto begin = reinterpret_cast<const char*>(buffer_.data());
440 prefs_->SetString(kPrefsManifestBytes, {begin, buffer_.size()});
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400441 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700442
Gilad Arnoldfe133932014-01-14 12:25:50 -0800443 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800444 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700445
Sen Jiang57f91802017-11-14 17:42:13 -0800446 block_size_ = manifest_.block_size();
447
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700448 // This populates |partitions_| and the |install_plan.partitions| with the
449 // list of partitions from the manifest.
450 if (!ParseManifestPartitions(error))
451 return false;
452
Sen Jiang5ae865b2017-04-18 14:24:40 -0700453 // |install_plan.partitions| was filled in, nothing need to be done here if
454 // the payload was already applied, returns false to terminate http fetcher,
455 // but keep |error| as ErrorCode::kSuccess.
456 if (payload_->already_applied)
457 return false;
458
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700459 num_total_operations_ = 0;
460 for (const auto& partition : partitions_) {
461 num_total_operations_ += partition.operations_size();
462 acc_num_operations_.push_back(num_total_operations_);
463 }
464
Amin Hassani008c4582019-01-13 16:22:47 -0800465 LOG_IF(WARNING,
466 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700467 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800468 LOG_IF(WARNING,
469 !prefs_->SetInt64(kPrefsManifestSignatureSize,
470 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800471 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700472
Darin Petkov9b230572010-10-08 10:20:09 -0700473 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700474 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700475 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800476 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700477 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800478
Yifan Hong537802d2018-08-15 13:15:42 -0700479 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
480 if (!OpenCurrentPartition()) {
481 *error = ErrorCode::kInstallDeviceOpenError;
482 return false;
483 }
Allie Woodfdf00512015-03-02 13:34:55 -0800484 }
485
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800486 if (next_operation_num_ > 0)
487 UpdateOverallProgress(true, "Resuming after ");
488 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800490
491 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700492 // Check if we should cancel the current attempt for any reason.
493 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700494 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300495 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700496 return false;
497
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700498 // We know there are more operations to perform because we didn't reach the
499 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700500 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Kelvin Zhangec205cf2020-09-28 13:23:40 -0400501 if (partition_writer_) {
502 TEST_AND_RETURN_FALSE(partition_writer_->FinishedInstallOps());
503 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700504 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700505 // Skip until there are operations for current_partition_.
506 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
507 current_partition_++;
508 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700509 if (!OpenCurrentPartition()) {
510 *error = ErrorCode::kInstallDeviceOpenError;
511 return false;
512 }
513 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700514
Alex Deymoa12ee112015-08-12 22:19:32 -0700515 const InstallOperation& op =
Kelvin Zhang52cb1d72020-10-27 13:44:25 -0400516 partitions_[current_partition_].operations(GetPartitionOperationNum());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800517
518 CopyDataToBuffer(&c_bytes, &count, op.data_length());
519
520 // Check whether we received all of the next operation's data payload.
521 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700522 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700523
Jay Srinivasanf4318702012-09-24 11:56:24 -0700524 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700525 // Otherwise, keep the old behavior. This serves as a knob to disable
526 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800527 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
528 // we would have already failed in ParsePayloadMetadata method and thus not
529 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800530 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700531 // Note: Validate must be called only if CanPerformInstallOperation is
532 // called. Otherwise, we might be failing operations before even if there
533 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800534 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700535 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800536 if (install_plan_->hash_checks_mandatory) {
537 LOG(ERROR) << "Mandatory operation hash check failed";
538 return false;
539 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700540
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800541 // For non-mandatory cases, just send a UMA stat.
542 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700543 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700544 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700545 }
546
Darin Petkov45580e42010-10-08 14:02:40 -0700547 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700548 ScopedTerminatorExitUnblocker exit_unblocker =
549 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800550
Lann Martin39f57142017-07-14 09:18:42 -0600551 base::TimeTicks op_start_time = base::TimeTicks::Now();
552
Gilad Arnoldfe133932014-01-14 12:25:50 -0800553 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700554 switch (op.type()) {
555 case InstallOperation::REPLACE:
556 case InstallOperation::REPLACE_BZ:
557 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700558 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600559 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700560 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700561 case InstallOperation::ZERO:
562 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700563 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600564 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700565 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700566 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700567 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600568 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700569 break;
570 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800571 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700572 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600573 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700574 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700575 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700576 op_result = PerformPuffDiffOperation(op, error);
577 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800578 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700579 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700580 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700581 }
582 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800583 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800584
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700585 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800586 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800587 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700588 }
Sen Jiangf6813802015-11-03 21:27:29 -0800589
Saint Chou0a92a622020-07-29 14:25:35 +0000590 // In major version 2, we don't add unused operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800591 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000592 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800593 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800594 if (manifest_.signatures_offset() != buffer_offset_) {
595 LOG(ERROR) << "Payload signatures offset points to blob offset "
596 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800597 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800598 *error = ErrorCode::kDownloadPayloadVerificationError;
599 return false;
600 }
601 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
602 // Needs more data to cover entire signature.
603 if (buffer_.size() < manifest_.signatures_size())
604 return true;
605 if (!ExtractSignatureMessage()) {
606 LOG(ERROR) << "Extract payload signature failed.";
607 *error = ErrorCode::kDownloadPayloadVerificationError;
608 return false;
609 }
610 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800611 // Since we extracted the SignatureMessage we need to advance the
612 // checkpoint, otherwise we would reload the signature and try to extract
613 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800614 // This is the last checkpoint for an update, force this checkpoint to be
615 // saved.
616 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800617 }
618
Don Garrette410e0f2011-11-10 15:39:01 -0800619 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700620}
621
David Zeuthen8f191b22013-08-06 12:27:50 -0700622bool DeltaPerformer::IsManifestValid() {
623 return manifest_valid_;
624}
625
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700626bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Amin Hassani822d4852020-03-10 01:50:42 +0000627 partitions_.clear();
628 for (const PartitionUpdate& partition : manifest_.partitions()) {
629 partitions_.push_back(partition);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700630 }
631
Tianjied3865d12020-06-03 15:25:17 -0700632 // For VAB and partial updates, the partition preparation will copy the
633 // dynamic partitions metadata to the target metadata slot, and rename the
634 // slot suffix of the partitions in the metadata.
635 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
636 uint64_t required_size = 0;
637 if (!PreparePartitionsForUpdate(&required_size)) {
638 if (required_size > 0) {
639 *error = ErrorCode::kNotEnoughSpace;
640 } else {
641 *error = ErrorCode::kInstallDeviceOpenError;
642 }
643 return false;
644 }
645 }
646
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400647 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
648 CHECK_NE(dynamic_control, nullptr);
649 TEST_AND_RETURN_FALSE(dynamic_control->ListDynamicPartitionsForSlot(
650 install_plan_->target_slot, &dynamic_partitions_));
651
Tianjie55abd3c2020-06-19 00:22:59 -0700652 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000653 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700654 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
655 // partition.
656 if (manifest_.partial_update()) {
657 std::set<std::string> touched_partitions;
658 for (const auto& partition_update : partitions_) {
659 touched_partitions.insert(partition_update.partition_name());
660 }
661
Tianjie99d570d2020-06-04 14:57:19 -0700662 auto generator = partition_update_generator::Create(boot_control_,
663 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700664 std::vector<PartitionUpdate> untouched_static_partitions;
Tianjied3865d12020-06-03 15:25:17 -0700665 TEST_AND_RETURN_FALSE(
666 generator->GenerateOperationsForPartitionsNotInPayload(
667 install_plan_->source_slot,
668 install_plan_->target_slot,
669 touched_partitions,
Tianjie24f96092020-06-30 12:26:25 -0700670 &untouched_static_partitions));
671 partitions_.insert(partitions_.end(),
672 untouched_static_partitions.begin(),
673 untouched_static_partitions.end());
674
675 // Save the untouched dynamic partitions in install plan.
676 std::vector<std::string> dynamic_partitions;
677 if (!boot_control_->GetDynamicPartitionControl()
678 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
679 &dynamic_partitions)) {
680 LOG(ERROR) << "Failed to load dynamic partitions from slot "
681 << install_plan_->source_slot;
682 return false;
683 }
684 install_plan_->untouched_dynamic_partitions.clear();
685 for (const auto& name : dynamic_partitions) {
686 if (touched_partitions.find(name) == touched_partitions.end()) {
687 install_plan_->untouched_dynamic_partitions.push_back(name);
688 }
689 }
Tianjied3865d12020-06-03 15:25:17 -0700690 }
691
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700692 // Fill in the InstallPlan::partitions based on the partitions from the
693 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700694 for (const auto& partition : partitions_) {
695 InstallPlan::Partition install_part;
696 install_part.name = partition.partition_name();
697 install_part.run_postinstall =
698 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800699 if (install_part.run_postinstall) {
700 install_part.postinstall_path =
701 (partition.has_postinstall_path() ? partition.postinstall_path()
702 : kPostinstallDefaultScript);
703 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700704 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800705 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700706
707 if (partition.has_old_partition_info()) {
708 const PartitionInfo& info = partition.old_partition_info();
709 install_part.source_size = info.size();
710 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
711 }
712
713 if (!partition.has_new_partition_info()) {
714 LOG(ERROR) << "Unable to get new partition hash info on partition "
715 << install_part.name << ".";
716 *error = ErrorCode::kDownloadNewPartitionInfoError;
717 return false;
718 }
719 const PartitionInfo& info = partition.new_partition_info();
720 install_part.target_size = info.size();
721 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
722
Sen Jiang57f91802017-11-14 17:42:13 -0800723 install_part.block_size = block_size_;
724 if (partition.has_hash_tree_extent()) {
725 Extent extent = partition.hash_tree_data_extent();
726 install_part.hash_tree_data_offset = extent.start_block() * block_size_;
727 install_part.hash_tree_data_size = extent.num_blocks() * block_size_;
728 extent = partition.hash_tree_extent();
729 install_part.hash_tree_offset = extent.start_block() * block_size_;
730 install_part.hash_tree_size = extent.num_blocks() * block_size_;
731 uint64_t hash_tree_data_end =
732 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
733 if (install_part.hash_tree_offset < hash_tree_data_end) {
734 LOG(ERROR) << "Invalid hash tree extents, hash tree data ends at "
735 << hash_tree_data_end << ", but hash tree starts at "
736 << install_part.hash_tree_offset;
737 *error = ErrorCode::kDownloadNewPartitionInfoError;
738 return false;
739 }
740 install_part.hash_tree_algorithm = partition.hash_tree_algorithm();
741 install_part.hash_tree_salt.assign(partition.hash_tree_salt().begin(),
742 partition.hash_tree_salt().end());
743 }
744 if (partition.has_fec_extent()) {
745 Extent extent = partition.fec_data_extent();
746 install_part.fec_data_offset = extent.start_block() * block_size_;
747 install_part.fec_data_size = extent.num_blocks() * block_size_;
748 extent = partition.fec_extent();
749 install_part.fec_offset = extent.start_block() * block_size_;
750 install_part.fec_size = extent.num_blocks() * block_size_;
751 uint64_t fec_data_end =
752 install_part.fec_data_offset + install_part.fec_data_size;
753 if (install_part.fec_offset < fec_data_end) {
754 LOG(ERROR) << "Invalid fec extents, fec data ends at " << fec_data_end
755 << ", but fec starts at " << install_part.fec_offset;
756 *error = ErrorCode::kDownloadNewPartitionInfoError;
757 return false;
758 }
759 install_part.fec_roots = partition.fec_roots();
760 }
761
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700762 install_plan_->partitions.push_back(install_part);
763 }
764
Tianjied3865d12020-06-03 15:25:17 -0700765 // TODO(xunchang) only need to load the partitions for those in payload.
766 // Because we have already loaded the other once when generating SOURCE_COPY
767 // operations.
Alex Deymo542c19b2015-12-03 07:43:31 -0300768 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700769 LOG(ERROR) << "Unable to determine all the partition devices.";
770 *error = ErrorCode::kInstallDeviceOpenError;
771 return false;
772 }
773 LogPartitionInfo(partitions_);
774 return true;
775}
776
Yifan Hongb9d63572020-01-09 17:50:46 -0800777bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
778 // Call static PreparePartitionsForUpdate with hash from
779 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
780 // preallocated for is the same as the hash of payload being applied.
781 string update_check_response_hash;
782 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
783 &update_check_response_hash));
784 return PreparePartitionsForUpdate(prefs_,
785 boot_control_,
786 install_plan_->target_slot,
787 manifest_,
788 update_check_response_hash,
789 required_size);
790}
791
792bool DeltaPerformer::PreparePartitionsForUpdate(
793 PrefsInterface* prefs,
794 BootControlInterface* boot_control,
795 BootControlInterface::Slot target_slot,
796 const DeltaArchiveManifest& manifest,
797 const std::string& update_check_response_hash,
798 uint64_t* required_size) {
799 string last_hash;
800 ignore_result(
801 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
802
803 bool is_resume = !update_check_response_hash.empty() &&
804 last_hash == update_check_response_hash;
805
806 if (is_resume) {
807 LOG(INFO) << "Using previously prepared partitions for update. hash = "
808 << last_hash;
809 } else {
810 LOG(INFO) << "Preparing partitions for new update. last hash = "
811 << last_hash << ", new hash = " << update_check_response_hash;
812 }
813
814 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
815 boot_control->GetCurrentSlot(),
816 target_slot,
817 manifest,
818 !is_resume /* should update */,
819 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700820 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -0800821 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700822 return false;
823 }
Yifan Hongb9d63572020-01-09 17:50:46 -0800824
825 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
826 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -0700827 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700828
829 return true;
830}
831
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700832bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700833 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700834 // If we don't have a data blob we can apply it right away.
835 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700836 return true;
837
838 // See if we have the entire data blob in the buffer
839 if (operation.data_offset() < buffer_offset_) {
840 LOG(ERROR) << "we threw away data it seems?";
841 return false;
842 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700843
Gilad Arnoldfe133932014-01-14 12:25:50 -0800844 return (operation.data_offset() + operation.data_length() <=
845 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700846}
847
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700848bool DeltaPerformer::PerformReplaceOperation(
849 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700850 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700851 operation.type() == InstallOperation::REPLACE_BZ ||
852 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700853
854 // Since we delete data off the beginning of the buffer as we use it,
855 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700856 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700857
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400858 TEST_AND_RETURN_FALSE(partition_writer_->PerformReplaceOperation(
859 operation, buffer_.data(), buffer_.size()));
860 // Update buffer
861 DiscardBuffer(true, buffer_.size());
862 return true;
863}
864
Alex Deymo79715ad2015-10-02 14:27:53 -0700865bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700866 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700867 CHECK(operation.type() == InstallOperation::DISCARD ||
868 operation.type() == InstallOperation::ZERO);
869
870 // These operations have no blob.
871 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
872 TEST_AND_RETURN_FALSE(!operation.has_data_length());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400873
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400874 return partition_writer_->PerformZeroOrDiscardOperation(operation);
875}
Alex Deymo79715ad2015-10-02 14:27:53 -0700876
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400877bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
878 const InstallOperation& operation,
879 const FileDescriptorPtr source_fd,
880 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800881 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
882 operation.src_sha256_hash().end());
883 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -0700884 LOG(ERROR) << "The hash of the source data on disk for this operation "
885 << "doesn't match the expected value. This could mean that the "
886 << "delta update payload was targeted for another version, or "
887 << "that the source partition was modified after it was "
888 << "installed, for example, by mounting a filesystem.";
889 LOG(ERROR) << "Expected: sha256|hex = "
890 << base::HexEncode(expected_source_hash.data(),
891 expected_source_hash.size());
892 LOG(ERROR) << "Calculated: sha256|hex = "
893 << base::HexEncode(calculated_hash.data(),
894 calculated_hash.size());
895
896 vector<string> source_extents;
897 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100898 source_extents.push_back(
899 base::StringPrintf("%" PRIu64 ":%" PRIu64,
900 static_cast<uint64_t>(ext.start_block()),
901 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -0700902 }
903 LOG(ERROR) << "Operation source (offset:size) in blocks: "
904 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700905
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +0100906 // Log remount history if this device is an ext4 partition.
907 LogMountHistory(source_fd);
908
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700909 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800910 return false;
911 }
912 return true;
913}
914
Allie Wood9f6f0a52015-03-30 11:25:47 -0700915bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700916 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700917 if (operation.has_src_length())
918 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
919 if (operation.has_dst_length())
920 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400921 return partition_writer_->PerformSourceCopyOperation(operation, error);
922}
Allie Wood9f6f0a52015-03-30 11:25:47 -0700923
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700924bool DeltaPerformer::ExtentsToBsdiffPositionsString(
925 const RepeatedPtrField<Extent>& extents,
926 uint64_t block_size,
927 uint64_t full_length,
928 string* positions_string) {
929 string ret;
930 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700931 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700932 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100933 uint64_t this_length =
934 min(full_length - length,
935 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700936 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700937 length += this_length;
938 }
939 TEST_AND_RETURN_FALSE(length == full_length);
940 if (!ret.empty())
941 ret.resize(ret.size() - 1); // Strip trailing comma off
942 *positions_string = ret;
943 return true;
944}
945
Allie Wood9f6f0a52015-03-30 11:25:47 -0700946bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700947 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700948 // Since we delete data off the beginning of the buffer as we use it,
949 // the data we need should be exactly at the beginning of the buffer.
950 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
951 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
952 if (operation.has_src_length())
953 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
954 if (operation.has_dst_length())
955 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
956
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400957 TEST_AND_RETURN_FALSE(partition_writer_->PerformSourceBsdiffOperation(
958 operation, error, buffer_.data(), buffer_.size()));
959 DiscardBuffer(true, buffer_.size());
960 return true;
961}
962
Amin Hassani02855c22017-09-06 22:34:50 -0700963bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
964 ErrorCode* error) {
965 // Since we delete data off the beginning of the buffer as we use it,
966 // the data we need should be exactly at the beginning of the buffer.
967 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
968 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400969 TEST_AND_RETURN_FALSE(partition_writer_->PerformPuffDiffOperation(
970 operation, error, buffer_.data(), buffer_.size()));
971 DiscardBuffer(true, buffer_.size());
972 return true;
973}
Amin Hassani02855c22017-09-06 22:34:50 -0700974
Sen Jiangf6813802015-11-03 21:27:29 -0800975bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700976 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
977 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
978 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700979 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -0800980 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700981
Darin Petkovd7061ab2010-10-06 14:37:09 -0700982 LOG(INFO) << "Extracted signature data of size "
983 << manifest_.signatures_size() << " at "
984 << manifest_.signatures_offset();
985 return true;
986}
987
Sen Jiang08c6da12019-01-07 18:28:56 -0800988bool DeltaPerformer::GetPublicKey(string* out_public_key) {
989 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -0700990
Sen Jiang08c6da12019-01-07 18:28:56 -0800991 if (utils::FileExists(public_key_path_.c_str())) {
992 LOG(INFO) << "Verifying using public key: " << public_key_path_;
993 return utils::ReadFile(public_key_path_, out_public_key);
994 }
995
Kelvin Zhang50bac652020-09-28 15:51:41 -0400996 // If this is an official build then we are not allowed to use public key
997 // from Omaha response.
Sen Jiang08c6da12019-01-07 18:28:56 -0800998 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
999 LOG(INFO) << "Verifying using public key from Omaha response.";
1000 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1001 out_public_key);
1002 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001003 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001004 return true;
1005}
1006
Tianjie Xu7a78d632019-10-08 16:32:39 -07001007std::pair<std::unique_ptr<PayloadVerifier>, bool>
1008DeltaPerformer::CreatePayloadVerifier() {
1009 if (utils::FileExists(update_certificates_path_.c_str())) {
1010 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1011 return {
1012 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1013 true};
1014 }
1015
1016 string public_key;
1017 if (!GetPublicKey(&public_key)) {
1018 LOG(ERROR) << "Failed to read public key";
1019 return {nullptr, true};
1020 }
1021
1022 // Skips the verification if the public key is empty.
1023 if (public_key.empty()) {
1024 return {nullptr, false};
1025 }
1026 return {PayloadVerifier::CreateInstance(public_key), true};
1027}
1028
Gilad Arnold21504f02013-05-24 08:51:22 -07001029ErrorCode DeltaPerformer::ValidateManifest() {
Saint Chou0a92a622020-07-29 14:25:35 +00001030 // Perform assorted checks to validation check the manifest, make sure it
Don Garrettb8dd1d92013-11-22 17:40:02 -08001031 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +00001032 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
1033 manifest_.partitions().end(),
1034 [](const PartitionUpdate& partition) {
1035 return partition.has_old_partition_info();
1036 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001037
Alex Deymo64d98782016-02-05 18:03:48 -08001038 // The presence of an old partition hash is the sole indicator for a delta
Tianjief5baff42020-07-17 21:43:22 -07001039 // update. Also, always treat the partial update as delta so that we can
1040 // perform the minor version check correctly.
Alex Deymo64d98782016-02-05 18:03:48 -08001041 InstallPayloadType actual_payload_type =
Tianjief5baff42020-07-17 21:43:22 -07001042 (has_old_fields || manifest_.partial_update())
1043 ? InstallPayloadType::kDelta
1044 : InstallPayloadType::kFull;
Alex Deymo64d98782016-02-05 18:03:48 -08001045
Sen Jiangcdd52062017-05-18 15:33:10 -07001046 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001047 LOG(INFO) << "Detected a '"
1048 << InstallPayloadTypeToString(actual_payload_type)
1049 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001050 payload_->type = actual_payload_type;
1051 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001052 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001053 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001054 << "' payload but the downloaded manifest contains a '"
1055 << InstallPayloadTypeToString(actual_payload_type)
1056 << "' payload.";
1057 return ErrorCode::kPayloadMismatchedType;
1058 }
Alex Deymo64d98782016-02-05 18:03:48 -08001059 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001060 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001061 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001062 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1063 LOG(ERROR) << "Manifest contains minor version "
1064 << manifest_.minor_version()
1065 << ", but all full payloads should have version "
1066 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001068 }
1069 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001070 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1071 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001072 LOG(ERROR) << "Manifest contains minor version "
1073 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001074 << " not in the range of supported minor versions ["
1075 << kMinSupportedMinorPayloadVersion << ", "
1076 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001077 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001078 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001079 }
1080
Yifan Hong87029332020-09-01 17:20:08 -07001081 ErrorCode error_code = CheckTimestampError();
1082 if (error_code != ErrorCode::kSuccess) {
1083 if (error_code == ErrorCode::kPayloadTimestampError) {
1084 if (!hardware_->AllowDowngrade()) {
1085 return ErrorCode::kPayloadTimestampError;
1086 }
1087 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1088 " the payload with an older timestamp.";
1089 } else {
1090 LOG(ERROR) << "Timestamp check returned "
1091 << utils::ErrorCodeToString(error_code);
1092 return error_code;
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001093 }
Sen Jiang8e768e92017-06-28 17:13:19 -07001094 }
1095
Amin Hassani55c75412019-10-07 11:20:39 -07001096 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1097 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001098
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001099 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001100}
1101
Yifan Hong87029332020-09-01 17:20:08 -07001102ErrorCode DeltaPerformer::CheckTimestampError() const {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001103 bool is_partial_update =
1104 manifest_.has_partial_update() && manifest_.partial_update();
1105 const auto& partitions = manifest_.partitions();
Yifan Hong87029332020-09-01 17:20:08 -07001106
1107 // Check version field for a given PartitionUpdate object. If an error
1108 // is encountered, set |error_code| accordingly. If downgrade is detected,
Kelvin Zhang50bac652020-09-28 15:51:41 -04001109 // |downgrade_detected| is set. Return true if the program should continue
1110 // to check the next partition or not, or false if it should exit early due
1111 // to errors.
Yifan Hong87029332020-09-01 17:20:08 -07001112 auto&& timestamp_valid = [this](const PartitionUpdate& partition,
1113 bool allow_empty_version,
1114 bool* downgrade_detected) -> ErrorCode {
Tianjie19e55292020-10-19 21:49:37 -07001115 const auto& partition_name = partition.partition_name();
Yifan Hong87029332020-09-01 17:20:08 -07001116 if (!partition.has_version()) {
Tianjie19e55292020-10-19 21:49:37 -07001117 if (hardware_->GetVersionForLogging(partition_name).empty()) {
1118 LOG(INFO) << partition_name << " does't have version, skipping "
1119 << "downgrade check.";
1120 return ErrorCode::kSuccess;
1121 }
1122
Yifan Hong87029332020-09-01 17:20:08 -07001123 if (allow_empty_version) {
1124 return ErrorCode::kSuccess;
1125 }
1126 LOG(ERROR)
Tianjie19e55292020-10-19 21:49:37 -07001127 << "PartitionUpdate " << partition_name
1128 << " doesn't have a version field. Not allowed in partial updates.";
Yifan Hong87029332020-09-01 17:20:08 -07001129 return ErrorCode::kDownloadManifestParseError;
1130 }
1131
Tianjie19e55292020-10-19 21:49:37 -07001132 auto error_code =
1133 hardware_->IsPartitionUpdateValid(partition_name, partition.version());
Yifan Hong87029332020-09-01 17:20:08 -07001134 switch (error_code) {
1135 case ErrorCode::kSuccess:
1136 break;
1137 case ErrorCode::kPayloadTimestampError:
1138 *downgrade_detected = true;
Tianjie19e55292020-10-19 21:49:37 -07001139 LOG(WARNING) << "PartitionUpdate " << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001140 << " has an older version than partition on device.";
1141 break;
1142 default:
Tianjie19e55292020-10-19 21:49:37 -07001143 LOG(ERROR) << "IsPartitionUpdateValid(" << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001144 << ") returned" << utils::ErrorCodeToString(error_code);
1145 break;
1146 }
1147 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001148 };
Yifan Hong87029332020-09-01 17:20:08 -07001149
1150 bool downgrade_detected = false;
1151
Kelvin Zhangd7191032020-08-11 10:48:16 -04001152 if (is_partial_update) {
1153 // for partial updates, all partition MUST have valid timestamps
1154 // But max_timestamp can be empty
1155 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001156 auto error_code = timestamp_valid(
1157 partition, false /* allow_empty_version */, &downgrade_detected);
1158 if (error_code != ErrorCode::kSuccess &&
1159 error_code != ErrorCode::kPayloadTimestampError) {
1160 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001161 }
1162 }
Yifan Hong87029332020-09-01 17:20:08 -07001163 if (downgrade_detected) {
1164 return ErrorCode::kPayloadTimestampError;
1165 }
1166 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001167 }
Yifan Hong87029332020-09-01 17:20:08 -07001168
1169 // For non-partial updates, check max_timestamp first.
Kelvin Zhangd7191032020-08-11 10:48:16 -04001170 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1171 LOG(ERROR) << "The current OS build timestamp ("
1172 << hardware_->GetBuildTimestamp()
1173 << ") is newer than the maximum timestamp in the manifest ("
1174 << manifest_.max_timestamp() << ")";
Yifan Hong87029332020-09-01 17:20:08 -07001175 return ErrorCode::kPayloadTimestampError;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001176 }
1177 // Otherwise... partitions can have empty timestamps.
1178 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001179 auto error_code = timestamp_valid(
1180 partition, true /* allow_empty_version */, &downgrade_detected);
1181 if (error_code != ErrorCode::kSuccess &&
1182 error_code != ErrorCode::kPayloadTimestampError) {
1183 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001184 }
1185 }
Yifan Hong87029332020-09-01 17:20:08 -07001186 if (downgrade_detected) {
1187 return ErrorCode::kPayloadTimestampError;
1188 }
1189 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001190}
1191
David Zeuthena99981f2013-04-29 13:42:47 -07001192ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001193 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001194 if (!operation.data_sha256_hash().size()) {
1195 if (!operation.data_length()) {
Kelvin Zhang50bac652020-09-28 15:51:41 -04001196 // Operations that do not have any data blob won't have any operation
1197 // hash either. So, these operations are always considered validated
1198 // since the metadata that contains all the non-data-blob portions of
1199 // the operation has already been validated. This is true for both HTTP
1200 // and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001201 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001202 }
1203
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001204 // No hash is present for an operation that has data blobs. This shouldn't
1205 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001206 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001207 // hashes. So if it happens it means either we've turned operation hash
1208 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Saint Chou0a92a622020-07-29 14:25:35 +00001209 // One caveat though: The last operation is a unused signature operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001210 // that doesn't have a hash at the time the manifest is created. So we
1211 // should not complaint about that operation. This operation can be
1212 // recognized by the fact that it's offset is mentioned in the manifest.
1213 if (manifest_.signatures_offset() &&
1214 manifest_.signatures_offset() == operation.data_offset()) {
1215 LOG(INFO) << "Skipping hash verification for signature operation "
1216 << next_operation_num_ + 1;
1217 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001218 if (install_plan_->hash_checks_mandatory) {
1219 LOG(ERROR) << "Missing mandatory operation hash for operation "
1220 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001221 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001222 }
1223
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001224 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1225 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001226 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001227 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001228 }
1229
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001230 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 expected_op_hash.assign(operation.data_sha256_hash().data(),
1232 (operation.data_sha256_hash().data() +
1233 operation.data_sha256_hash().size()));
1234
Sen Jiang2703ef42017-03-16 13:36:21 -07001235 brillo::Blob calculated_op_hash;
1236 if (!HashCalculator::RawHashOfBytes(
1237 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001238 LOG(ERROR) << "Unable to compute actual hash of operation "
1239 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001241 }
1242
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001243 if (calculated_op_hash != expected_op_hash) {
1244 LOG(ERROR) << "Hash verification failed for operation "
1245 << next_operation_num_ << ". Expected hash = ";
1246 utils::HexDumpVector(expected_op_hash);
1247 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1248 << " bytes at offset: " << operation.data_offset() << " = ";
1249 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001251 }
1252
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001253 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001254}
1255
Amin Hassani008c4582019-01-13 16:22:47 -08001256#define TEST_AND_RETURN_VAL(_retval, _condition) \
1257 do { \
1258 if (!(_condition)) { \
1259 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1260 return _retval; \
1261 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001262 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001263
David Zeuthena99981f2013-04-29 13:42:47 -07001264ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001265 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001266 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001267 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001268 if (update_check_response_size !=
1269 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1270 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1271 << ") doesn't match metadata_size (" << metadata_size_
1272 << ") + metadata_signature_size (" << metadata_signature_size_
1273 << ") + buffer_offset (" << buffer_offset_ << ").";
1274 return ErrorCode::kPayloadSizeMismatchError;
1275 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001276
Amin Hassanie331f5a2020-10-06 15:53:29 -07001277 // Verifies the payload hash.
1278 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
1279 !payload_hash_calculator_.raw_hash().empty());
1280 TEST_AND_RETURN_VAL(
1281 ErrorCode::kPayloadHashMismatchError,
1282 payload_hash_calculator_.raw_hash() == update_check_response_hash);
1283
Amin Hassaniec7bc112020-10-29 16:47:58 -07001284 // NOLINTNEXTLINE(whitespace/braces)
Amin Hassanif624e112020-09-15 15:30:08 -07001285 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1286 if (!perform_verification) {
1287 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1288 return ErrorCode::kSuccess;
1289 }
1290 if (!payload_verifier) {
1291 LOG(ERROR) << "Failed to create the payload verifier.";
1292 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1293 }
1294
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001295 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001296 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001297 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001298 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001299 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001300
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001301 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001302 // The autoupdate_CatchBadSignatures test checks for this string
1303 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001304 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001305 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001306 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001307
David Zeuthene7f89172013-10-31 10:21:04 -07001308 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001309 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001310}
1311
Sen Jiangf6813802015-11-03 21:27:29 -08001312void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1313 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001314 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001315 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001316 buffer_offset_ += buffer_.size();
1317
1318 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001319 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1320 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001321
1322 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001323 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001324}
1325
Darin Petkov0406e402010-10-06 21:33:11 -07001326bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001327 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001328 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001329 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Amin Hassani008c4582019-01-13 16:22:47 -08001330 next_operation != kUpdateStateOperationInvalid && next_operation > 0))
Alex Deymo3310b222015-03-30 15:59:07 -07001331 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001332
1333 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001334 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1335 !interrupted_hash.empty() &&
1336 interrupted_hash == update_check_response_hash))
1337 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001338
Darin Petkov61426142010-10-08 11:04:55 -07001339 int64_t resumed_update_failures;
Kelvin Zhang50bac652020-09-28 15:51:41 -04001340 // Note that storing this value is optional, but if it is there it should
1341 // not be more than the limit.
Alex Deymof25eb492016-02-26 00:20:08 -08001342 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1343 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001344 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001345
Saint Chou0a92a622020-07-29 14:25:35 +00001346 // Validation check the rest.
Darin Petkov0406e402010-10-06 21:33:11 -07001347 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001348 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1349 next_data_offset >= 0))
1350 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001351
Darin Petkov437adc42010-10-07 13:12:24 -07001352 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001353 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1354 !sha256_context.empty()))
1355 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001356
1357 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001358 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1359 manifest_metadata_size > 0))
1360 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001361
Alex Deymof25eb492016-02-26 00:20:08 -08001362 int64_t manifest_signature_size = 0;
1363 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1364 &manifest_signature_size) &&
1365 manifest_signature_size >= 0))
1366 return false;
1367
Darin Petkov0406e402010-10-06 21:33:11 -07001368 return true;
1369}
1370
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001371bool DeltaPerformer::ResetUpdateProgress(
1372 PrefsInterface* prefs,
1373 bool quick,
1374 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07001375 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1376 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001377 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001378 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001379 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001380 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1381 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001382 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001383 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001384 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001385 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001386 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001387 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001388
1389 if (!skip_dynamic_partititon_metadata_updated) {
1390 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1391 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
1392 }
Darin Petkov9b230572010-10-08 10:20:09 -07001393 }
Darin Petkov73058b42010-10-06 16:32:19 -07001394 return true;
1395}
1396
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001397bool DeltaPerformer::ShouldCheckpoint() {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001398 base::TimeTicks curr_time = base::TimeTicks::Now();
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001399 if (curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001400 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001401 return true;
1402 }
1403 return false;
1404}
1405
1406bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
1407 if (!force && !ShouldCheckpoint()) {
Colin Howes0e452c92018-11-02 13:18:44 -07001408 return false;
1409 }
Darin Petkov9c0baf82010-10-07 13:44:48 -07001410 Terminator::set_exit_blocked(true);
Kelvin Zhang3265b312020-12-16 15:51:30 -05001411 if (last_updated_operation_num_ != next_operation_num_ || force) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001412 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001413 ResetUpdateProgress(prefs_, true);
Kelvin Zhangbb8e9992020-12-28 10:28:48 -05001414 if (!signatures_message_data_.empty()) {
1415 // Save the signature blob because if the update is interrupted after the
1416 // download phase we don't go through this path anymore. Some alternatives
1417 // to consider:
1418 //
1419 // 1. On resume, re-download the signature blob from the server and
1420 // re-verify it.
1421 //
1422 // 2. Verify the signature as soon as it's received and don't checkpoint
1423 // the blob and the signed sha-256 context.
1424 LOG_IF(WARNING,
1425 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
1426 signatures_message_data_))
1427 << "Unable to store the signature blob.";
1428 }
Amin Hassani008c4582019-01-13 16:22:47 -08001429 TEST_AND_RETURN_FALSE(prefs_->SetString(
1430 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001431 TEST_AND_RETURN_FALSE(
1432 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1433 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001434 TEST_AND_RETURN_FALSE(
1435 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001436 last_updated_operation_num_ = next_operation_num_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001437
1438 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001439 size_t partition_index = current_partition_;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001440 while (next_operation_num_ >= acc_num_operations_[partition_index]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001441 partition_index++;
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001442 }
Amin Hassani008c4582019-01-13 16:22:47 -08001443 const size_t partition_operation_num =
1444 next_operation_num_ -
1445 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001446 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001447 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001448 TEST_AND_RETURN_FALSE(
1449 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001450 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001451 TEST_AND_RETURN_FALSE(
1452 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001453 }
Kelvin Zhange4235b02020-11-23 13:57:51 -05001454 if (partition_writer_) {
1455 partition_writer_->CheckpointUpdateProgress(GetPartitionOperationNum());
1456 } else {
1457 CHECK_EQ(next_operation_num_, num_total_operations_)
1458 << "Partition writer is null, we are expected to finish all "
1459 "operations: "
1460 << next_operation_num_ << "/" << num_total_operations_;
1461 }
Darin Petkov0406e402010-10-06 21:33:11 -07001462 }
Amin Hassani008c4582019-01-13 16:22:47 -08001463 TEST_AND_RETURN_FALSE(
1464 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07001465 return true;
1466}
1467
Darin Petkov9b230572010-10-08 10:20:09 -07001468bool DeltaPerformer::PrimeUpdateState() {
1469 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001470
1471 int64_t next_operation = kUpdateStateOperationInvalid;
1472 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001473 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001474 // Initiating a new update, no more state needs to be initialized.
1475 return true;
1476 }
1477 next_operation_num_ = next_operation;
1478
1479 // Resuming an update -- load the rest of the update state.
1480 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001481 TEST_AND_RETURN_FALSE(
1482 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1483 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001484 buffer_offset_ = next_data_offset;
1485
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001486 // The signed hash context and the signature blob may be empty if the
1487 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001488 string signed_hash_context;
1489 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1490 &signed_hash_context)) {
1491 TEST_AND_RETURN_FALSE(
1492 signed_hash_calculator_.SetContext(signed_hash_context));
1493 }
1494
Sen Jiang9b2f1782019-01-24 14:27:50 -08001495 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001496
1497 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001498 TEST_AND_RETURN_FALSE(
1499 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1500 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001501
1502 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001503 TEST_AND_RETURN_FALSE(
1504 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1505 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001506 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001507
Alex Deymof25eb492016-02-26 00:20:08 -08001508 int64_t manifest_signature_size = 0;
1509 TEST_AND_RETURN_FALSE(
1510 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1511 manifest_signature_size >= 0);
1512 metadata_signature_size_ = manifest_signature_size;
1513
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001514 // Advance the download progress to reflect what doesn't need to be
1515 // re-downloaded.
1516 total_bytes_received_ += buffer_offset_;
1517
Darin Petkov61426142010-10-08 11:04:55 -07001518 // Speculatively count the resume as a failure.
1519 int64_t resumed_update_failures;
1520 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1521 resumed_update_failures++;
1522 } else {
1523 resumed_update_failures = 1;
1524 }
1525 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001526 return true;
1527}
1528
Kelvin Zhang94f51cc2020-09-25 11:34:49 -04001529bool DeltaPerformer::IsDynamicPartition(const std::string& part_name) {
1530 return std::find(dynamic_partitions_.begin(),
1531 dynamic_partitions_.end(),
1532 part_name) != dynamic_partitions_.end();
1533}
1534
Kelvin Zhangcfe694f2020-11-13 13:10:42 -05001535std::unique_ptr<PartitionWriter> DeltaPerformer::CreatePartitionWriter(
1536 const PartitionUpdate& partition_update,
1537 const InstallPlan::Partition& install_part,
1538 DynamicPartitionControlInterface* dynamic_control,
1539 size_t block_size,
1540 bool is_interactive,
1541 bool is_dynamic_partition) {
1542 return partition_writer::CreatePartitionWriter(
1543 partition_update,
1544 install_part,
1545 dynamic_control,
1546 block_size_,
1547 interactive_,
1548 IsDynamicPartition(install_part.name));
1549}
1550
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001551} // namespace chromeos_update_engine