blob: 30bd1ef5cc755b69f8771aa85f19f4176199f412 [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"
Alex Deymo39910dc2015-11-09 17:04:30 -080051#include "update_engine/payload_consumer/bzip_extent_writer.h"
Amin Hassania3fc20a2017-09-19 17:19:34 -070052#include "update_engine/payload_consumer/cached_file_descriptor.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070053#include "update_engine/payload_consumer/certificate_parser_interface.h"
Amin Hassanidb56be92017-09-06 12:41:23 -070054#include "update_engine/payload_consumer/extent_reader.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/payload_consumer/extent_writer.h"
Tianjied3865d12020-06-03 15:25:17 -070056#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Kelvin Zhang50bac652020-09-28 15:51:41 -040057#include "update_engine/payload_consumer/partition_writer.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070058#if USE_FEC
59#include "update_engine/payload_consumer/fec_file_descriptor.h"
60#endif // USE_FEC
Alex Deymoa48f6302016-11-04 15:49:53 -070061#include "update_engine/payload_consumer/file_descriptor_utils.h"
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +010062#include "update_engine/payload_consumer/mount_history.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080063#include "update_engine/payload_consumer/payload_constants.h"
64#include "update_engine/payload_consumer/payload_verifier.h"
65#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066
Alex Deymo161c4a12014-05-16 15:56:21 -070067using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068using std::min;
69using std::string;
70using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070071
72namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080073const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
74const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
75const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
76const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070077const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080078
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070080const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070081const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080082
Alex Vakulenkod2779df2014-06-16 13:19:00 -070083} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070084
Gilad Arnold8a86fa52013-01-15 12:35:05 -080085// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
86// arithmetic.
87static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
88 return part * norm / total;
89}
90
91void DeltaPerformer::LogProgress(const char* message_prefix) {
92 // Format operations total count and percentage.
93 string total_operations_str("?");
94 string completed_percentage_str("");
95 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -070096 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -080097 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -080098 completed_percentage_str = base::StringPrintf(
99 " (%" PRIu64 "%%)",
100 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800101 }
102
103 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800104 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800105 string payload_size_str("?");
106 string downloaded_percentage_str("");
107 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700108 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800109 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800110 downloaded_percentage_str = base::StringPrintf(
111 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800112 }
113
114 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
115 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800116 << completed_percentage_str << ", " << total_bytes_received_ << "/"
117 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800118 << downloaded_percentage_str << ", overall progress "
119 << overall_progress_ << "%";
120}
121
122void DeltaPerformer::UpdateOverallProgress(bool force_log,
123 const char* message_prefix) {
124 // Compute our download and overall progress.
125 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800126 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
127 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800128 // Only consider download progress if its total size is known; otherwise
129 // adjust the operations weight to compensate for the absence of download
130 // progress. Also, make sure to cap the download portion at
131 // kProgressDownloadWeight, in case we end up downloading more than we
132 // initially expected (this indicates a problem, but could generally happen).
133 // TODO(garnold) the correction of operations weight when we do not have the
134 // total payload size, as well as the conditional guard below, should both be
135 // eliminated once we ensure that the payload_size in the install plan is
136 // always given and is non-zero. This currently isn't the case during unit
137 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800138 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800139 unsigned actual_operations_weight = kProgressOperationsWeight;
140 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800141 new_overall_progress +=
142 min(static_cast<unsigned>(IntRatio(
143 total_bytes_received_, payload_size, kProgressDownloadWeight)),
144 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800145 else
146 actual_operations_weight += kProgressDownloadWeight;
147
148 // Only add completed operations if their total number is known; we definitely
149 // expect an update to have at least one operation, so the expectation is that
150 // this will eventually reach |actual_operations_weight|.
151 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800152 new_overall_progress += IntRatio(
153 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800154
155 // Progress ratio cannot recede, unless our assumptions about the total
156 // payload size, total number of operations, or the monotonicity of progress
157 // is breached.
158 if (new_overall_progress < overall_progress_) {
159 LOG(WARNING) << "progress counter receded from " << overall_progress_
160 << "% down to " << new_overall_progress << "%; this is a bug";
161 force_log = true;
162 }
163 overall_progress_ = new_overall_progress;
164
165 // Update chunk index, log as needed: if forced by called, or we completed a
166 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800167 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800168 unsigned curr_progress_chunk =
169 overall_progress_ * kProgressLogMaxChunks / 100;
170 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
171 curr_time > forced_progress_log_time_) {
172 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
173 LogProgress(message_prefix);
174 }
175 last_progress_chunk_ = curr_progress_chunk;
176}
177
Amin Hassani008c4582019-01-13 16:22:47 -0800178size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
179 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800180 size_t max) {
181 const size_t count = *count_p;
182 if (!count)
183 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700184 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800185 const char* bytes_start = *bytes_p;
186 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800187 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800188 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
189 *bytes_p = bytes_end;
190 *count_p = count - read_len;
191 return read_len;
192}
193
Amin Hassani008c4582019-01-13 16:22:47 -0800194bool DeltaPerformer::HandleOpResult(bool op_result,
195 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800196 ErrorCode* error) {
197 if (op_result)
198 return true;
199
Alex Deymo3d009062016-05-13 15:51:25 -0700200 size_t partition_first_op_num =
201 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800202 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700203 << next_operation_num_ << ", which is the operation "
204 << next_operation_num_ - partition_first_op_num
205 << " in partition \""
206 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700207 if (*error == ErrorCode::kSuccess)
208 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800209 return false;
210}
211
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700212int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700213 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800214 LOG_IF(ERROR,
215 !payload_hash_calculator_.Finalize() ||
216 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800217 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800218 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700219 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
220 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800221 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800222 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700223 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700224}
225
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700226int DeltaPerformer::CloseCurrentPartition() {
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400227 if (!partition_writer_) {
228 return 0;
229 }
230 int err = partition_writer_->Close();
231 partition_writer_ = nullptr;
232 return err;
233}
234
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700235bool DeltaPerformer::OpenCurrentPartition() {
236 if (current_partition_ >= partitions_.size())
237 return false;
238
239 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700240 size_t num_previous_partitions =
241 install_plan_->partitions.size() - partitions_.size();
242 const InstallPlan::Partition& install_part =
243 install_plan_->partitions[num_previous_partitions + current_partition_];
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400244 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
245 partition_writer_ = partition_writer::CreatePartitionWriter(
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400246 partition,
247 install_part,
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400248 dynamic_control,
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400249 block_size_,
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400250 interactive_,
251 IsDynamicPartition(install_part.name));
Tianjie55abd3c2020-06-19 00:22:59 -0700252 // Open source fds if we have a delta payload, or for partitions in the
253 // partial update.
Tianjied3865d12020-06-03 15:25:17 -0700254 bool source_may_exist = manifest_.partial_update() ||
Tianjie55abd3c2020-06-19 00:22:59 -0700255 payload_->type == InstallPayloadType::kDelta;
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400256 return partition_writer_->Init(install_plan_, source_may_exist);
257}
258
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700259namespace {
260
261void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700262 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800263 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
264 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700265}
266
Alex Deymo39910dc2015-11-09 17:04:30 -0800267void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700268 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800269 if (partition.has_old_partition_info()) {
270 LogPartitionInfoHash(partition.old_partition_info(),
271 "old " + partition.partition_name());
272 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700273 LogPartitionInfoHash(partition.new_partition_info(),
274 "new " + partition.partition_name());
275 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700276}
277
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700278} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700279
Sen Jiangb8060e42015-09-24 17:30:50 -0700280bool DeltaPerformer::IsHeaderParsed() const {
281 return metadata_size_ != 0;
282}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700283
Sen Jiang9c89e842018-02-02 13:51:21 -0800284MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700285 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700286 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700287
Sen Jiangb8060e42015-09-24 17:30:50 -0700288 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700289 MetadataParseResult result =
290 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800291 if (result != MetadataParseResult::kSuccess)
292 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700293
Sen Jiang9c89e842018-02-02 13:51:21 -0800294 metadata_size_ = payload_metadata_.GetMetadataSize();
295 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
296 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800297
298 // If the metadata size is present in install plan, check for it immediately
299 // even before waiting for that many number of bytes to be downloaded in the
300 // payload. This will prevent any attack which relies on us downloading data
301 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800302 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800303 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800304 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800305 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800306 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700307 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800308 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800309 }
310 }
Andrew3a7dc262019-12-19 11:38:08 -0800311
312 // Check that the |metadata signature size_| and |metadata_size_| are not
313 // very big numbers. This is necessary since |update_engine| needs to write
314 // these values into the buffer before being able to use them, and if an
315 // attacker sets these values to a very big number, the buffer will overflow
316 // and |update_engine| will crash. A simple way of solving this is to check
317 // that the size of both values is smaller than the payload itself.
318 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
319 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
320 << " or metadata signature(" << metadata_signature_size_ << ")"
321 << " is greater than the size of the payload"
322 << "(" << payload_->size << ")";
323 *error = ErrorCode::kDownloadInvalidMetadataSize;
324 return MetadataParseResult::kError;
325 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700326 }
327
328 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700329 // metadata and its signature (if exist) to be read in before we can parse it.
330 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800331 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700332
333 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700334 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700335 // that we just log once (instead of logging n times) if it takes n
336 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800337 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700338 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800339 } else {
340 // For mandatory-cases, we'd have already returned a kMetadataParseError
341 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
342 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800343 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800344 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800345 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800346 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700347
Amin Hassaniec7bc112020-10-29 16:47:58 -0700348 // NOLINTNEXTLINE(whitespace/braces)
Tianjie Xu7a78d632019-10-08 16:32:39 -0700349 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
350 if (!payload_verifier) {
351 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800352 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700353 if (perform_verification) {
354 return MetadataParseResult::kError;
355 }
356 } else {
357 // We have the full metadata in |payload|. Verify its integrity
358 // and authenticity based on the information we have in Omaha response.
359 *error = payload_metadata_.ValidateMetadataSignature(
360 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800361 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700362 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800363 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800364 // The autoupdate_CatchBadSignatures test checks for this string
365 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800366 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800367 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800368 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700369
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800370 // For non-mandatory cases, just send a UMA stat.
371 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700372 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700373 }
374
Gilad Arnolddaa27402014-01-23 11:56:17 -0800375 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800376 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800377 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700378 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800379 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800380 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800381
382 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800383 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800384}
385
Amin Hassani008c4582019-01-13 16:22:47 -0800386#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
387 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
388 "UpdateEngine.DownloadAction.InstallOperation::" _op_name ".Duration", \
Andrew9d5a61d2020-03-26 13:40:37 -0700389 (base::TimeTicks::Now() - _start_time), \
Amin Hassani008c4582019-01-13 16:22:47 -0800390 base::TimeDelta::FromMilliseconds(10), \
391 base::TimeDelta::FromMinutes(5), \
392 20);
Lann Martin39f57142017-07-14 09:18:42 -0600393
Don Garrette410e0f2011-11-10 15:39:01 -0800394// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800395// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800397bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700398 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700399 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800400
401 // Update the total byte downloaded count and the progress logs.
402 total_bytes_received_ += count;
403 UpdateOverallProgress(false, "Completed ");
404
Gilad Arnoldfe133932014-01-14 12:25:50 -0800405 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700406 // Read data up to the needed limit; this is either maximium payload header
407 // size, or the full metadata size (once it becomes known).
408 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800409 CopyDataToBuffer(
410 &c_bytes,
411 &count,
412 (do_read_header ? kMaxPayloadHeaderSize
413 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800414
Gilad Arnolddaa27402014-01-23 11:56:17 -0800415 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800416 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800417 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800418 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800419 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700420 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800421 continue;
422
Don Garrette410e0f2011-11-10 15:39:01 -0800423 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800424 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700425
426 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700427 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700428 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800429 manifest_valid_ = true;
Kelvin Zhangcc011d32020-07-10 18:20:08 -0400430 if (!install_plan_->is_resume) {
431 prefs_->SetString(kPrefsManifestBytes, {buffer_.begin(), buffer_.end()});
432 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700433
Gilad Arnoldfe133932014-01-14 12:25:50 -0800434 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800435 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700436
Sen Jiang57f91802017-11-14 17:42:13 -0800437 block_size_ = manifest_.block_size();
438
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700439 // This populates |partitions_| and the |install_plan.partitions| with the
440 // list of partitions from the manifest.
441 if (!ParseManifestPartitions(error))
442 return false;
443
Sen Jiang5ae865b2017-04-18 14:24:40 -0700444 // |install_plan.partitions| was filled in, nothing need to be done here if
445 // the payload was already applied, returns false to terminate http fetcher,
446 // but keep |error| as ErrorCode::kSuccess.
447 if (payload_->already_applied)
448 return false;
449
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700450 num_total_operations_ = 0;
451 for (const auto& partition : partitions_) {
452 num_total_operations_ += partition.operations_size();
453 acc_num_operations_.push_back(num_total_operations_);
454 }
455
Amin Hassani008c4582019-01-13 16:22:47 -0800456 LOG_IF(WARNING,
457 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700458 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800459 LOG_IF(WARNING,
460 !prefs_->SetInt64(kPrefsManifestSignatureSize,
461 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800462 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700463
Darin Petkov9b230572010-10-08 10:20:09 -0700464 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700465 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700466 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800467 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700468 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800469
Yifan Hong537802d2018-08-15 13:15:42 -0700470 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
471 if (!OpenCurrentPartition()) {
472 *error = ErrorCode::kInstallDeviceOpenError;
473 return false;
474 }
Allie Woodfdf00512015-03-02 13:34:55 -0800475 }
476
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800477 if (next_operation_num_ > 0)
478 UpdateOverallProgress(true, "Resuming after ");
479 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700480 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800481
482 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700483 // Check if we should cancel the current attempt for any reason.
484 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700485 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300486 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700487 return false;
488
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700489 // We know there are more operations to perform because we didn't reach the
490 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700491 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700492 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700493 // Skip until there are operations for current_partition_.
494 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
495 current_partition_++;
496 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700497 if (!OpenCurrentPartition()) {
498 *error = ErrorCode::kInstallDeviceOpenError;
499 return false;
500 }
501 }
Amin Hassani008c4582019-01-13 16:22:47 -0800502 const size_t partition_operation_num =
503 next_operation_num_ -
504 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700505
Alex Deymoa12ee112015-08-12 22:19:32 -0700506 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700507 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800508
509 CopyDataToBuffer(&c_bytes, &count, op.data_length());
510
511 // Check whether we received all of the next operation's data payload.
512 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700513 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700514
Jay Srinivasanf4318702012-09-24 11:56:24 -0700515 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700516 // Otherwise, keep the old behavior. This serves as a knob to disable
517 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800518 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
519 // we would have already failed in ParsePayloadMetadata method and thus not
520 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800521 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700522 // Note: Validate must be called only if CanPerformInstallOperation is
523 // called. Otherwise, we might be failing operations before even if there
524 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800525 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700526 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800527 if (install_plan_->hash_checks_mandatory) {
528 LOG(ERROR) << "Mandatory operation hash check failed";
529 return false;
530 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700531
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800532 // For non-mandatory cases, just send a UMA stat.
533 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700534 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700535 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700536 }
537
Darin Petkov45580e42010-10-08 14:02:40 -0700538 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700539 ScopedTerminatorExitUnblocker exit_unblocker =
540 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800541
Lann Martin39f57142017-07-14 09:18:42 -0600542 base::TimeTicks op_start_time = base::TimeTicks::Now();
543
Gilad Arnoldfe133932014-01-14 12:25:50 -0800544 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700545 switch (op.type()) {
546 case InstallOperation::REPLACE:
547 case InstallOperation::REPLACE_BZ:
548 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700549 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600550 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700551 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700552 case InstallOperation::ZERO:
553 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700554 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600555 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700556 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700557 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700558 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600559 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700560 break;
561 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800562 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700563 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600564 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700565 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700566 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700567 op_result = PerformPuffDiffOperation(op, error);
568 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800569 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700570 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700571 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700572 }
573 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800574 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800575
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700576 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800577 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800578 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700579 }
Sen Jiangf6813802015-11-03 21:27:29 -0800580
Saint Chou0a92a622020-07-29 14:25:35 +0000581 // In major version 2, we don't add unused operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800582 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000583 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800584 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800585 if (manifest_.signatures_offset() != buffer_offset_) {
586 LOG(ERROR) << "Payload signatures offset points to blob offset "
587 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800588 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800589 *error = ErrorCode::kDownloadPayloadVerificationError;
590 return false;
591 }
592 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
593 // Needs more data to cover entire signature.
594 if (buffer_.size() < manifest_.signatures_size())
595 return true;
596 if (!ExtractSignatureMessage()) {
597 LOG(ERROR) << "Extract payload signature failed.";
598 *error = ErrorCode::kDownloadPayloadVerificationError;
599 return false;
600 }
601 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800602 // Since we extracted the SignatureMessage we need to advance the
603 // checkpoint, otherwise we would reload the signature and try to extract
604 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800605 // This is the last checkpoint for an update, force this checkpoint to be
606 // saved.
607 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800608 }
609
Don Garrette410e0f2011-11-10 15:39:01 -0800610 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700611}
612
David Zeuthen8f191b22013-08-06 12:27:50 -0700613bool DeltaPerformer::IsManifestValid() {
614 return manifest_valid_;
615}
616
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700617bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Amin Hassani822d4852020-03-10 01:50:42 +0000618 partitions_.clear();
619 for (const PartitionUpdate& partition : manifest_.partitions()) {
620 partitions_.push_back(partition);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700621 }
622
Tianjied3865d12020-06-03 15:25:17 -0700623 // For VAB and partial updates, the partition preparation will copy the
624 // dynamic partitions metadata to the target metadata slot, and rename the
625 // slot suffix of the partitions in the metadata.
626 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
627 uint64_t required_size = 0;
628 if (!PreparePartitionsForUpdate(&required_size)) {
629 if (required_size > 0) {
630 *error = ErrorCode::kNotEnoughSpace;
631 } else {
632 *error = ErrorCode::kInstallDeviceOpenError;
633 }
634 return false;
635 }
636 }
637
Kelvin Zhang94f51cc2020-09-25 11:34:49 -0400638 auto dynamic_control = boot_control_->GetDynamicPartitionControl();
639 CHECK_NE(dynamic_control, nullptr);
640 TEST_AND_RETURN_FALSE(dynamic_control->ListDynamicPartitionsForSlot(
641 install_plan_->target_slot, &dynamic_partitions_));
642
Tianjie55abd3c2020-06-19 00:22:59 -0700643 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000644 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700645 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
646 // partition.
647 if (manifest_.partial_update()) {
648 std::set<std::string> touched_partitions;
649 for (const auto& partition_update : partitions_) {
650 touched_partitions.insert(partition_update.partition_name());
651 }
652
Tianjie99d570d2020-06-04 14:57:19 -0700653 auto generator = partition_update_generator::Create(boot_control_,
654 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700655 std::vector<PartitionUpdate> untouched_static_partitions;
Tianjied3865d12020-06-03 15:25:17 -0700656 TEST_AND_RETURN_FALSE(
657 generator->GenerateOperationsForPartitionsNotInPayload(
658 install_plan_->source_slot,
659 install_plan_->target_slot,
660 touched_partitions,
Tianjie24f96092020-06-30 12:26:25 -0700661 &untouched_static_partitions));
662 partitions_.insert(partitions_.end(),
663 untouched_static_partitions.begin(),
664 untouched_static_partitions.end());
665
666 // Save the untouched dynamic partitions in install plan.
667 std::vector<std::string> dynamic_partitions;
668 if (!boot_control_->GetDynamicPartitionControl()
669 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
670 &dynamic_partitions)) {
671 LOG(ERROR) << "Failed to load dynamic partitions from slot "
672 << install_plan_->source_slot;
673 return false;
674 }
675 install_plan_->untouched_dynamic_partitions.clear();
676 for (const auto& name : dynamic_partitions) {
677 if (touched_partitions.find(name) == touched_partitions.end()) {
678 install_plan_->untouched_dynamic_partitions.push_back(name);
679 }
680 }
Tianjied3865d12020-06-03 15:25:17 -0700681 }
682
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700683 // Fill in the InstallPlan::partitions based on the partitions from the
684 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700685 for (const auto& partition : partitions_) {
686 InstallPlan::Partition install_part;
687 install_part.name = partition.partition_name();
688 install_part.run_postinstall =
689 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800690 if (install_part.run_postinstall) {
691 install_part.postinstall_path =
692 (partition.has_postinstall_path() ? partition.postinstall_path()
693 : kPostinstallDefaultScript);
694 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700695 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800696 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700697
698 if (partition.has_old_partition_info()) {
699 const PartitionInfo& info = partition.old_partition_info();
700 install_part.source_size = info.size();
701 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
702 }
703
704 if (!partition.has_new_partition_info()) {
705 LOG(ERROR) << "Unable to get new partition hash info on partition "
706 << install_part.name << ".";
707 *error = ErrorCode::kDownloadNewPartitionInfoError;
708 return false;
709 }
710 const PartitionInfo& info = partition.new_partition_info();
711 install_part.target_size = info.size();
712 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
713
Sen Jiang57f91802017-11-14 17:42:13 -0800714 install_part.block_size = block_size_;
715 if (partition.has_hash_tree_extent()) {
716 Extent extent = partition.hash_tree_data_extent();
717 install_part.hash_tree_data_offset = extent.start_block() * block_size_;
718 install_part.hash_tree_data_size = extent.num_blocks() * block_size_;
719 extent = partition.hash_tree_extent();
720 install_part.hash_tree_offset = extent.start_block() * block_size_;
721 install_part.hash_tree_size = extent.num_blocks() * block_size_;
722 uint64_t hash_tree_data_end =
723 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
724 if (install_part.hash_tree_offset < hash_tree_data_end) {
725 LOG(ERROR) << "Invalid hash tree extents, hash tree data ends at "
726 << hash_tree_data_end << ", but hash tree starts at "
727 << install_part.hash_tree_offset;
728 *error = ErrorCode::kDownloadNewPartitionInfoError;
729 return false;
730 }
731 install_part.hash_tree_algorithm = partition.hash_tree_algorithm();
732 install_part.hash_tree_salt.assign(partition.hash_tree_salt().begin(),
733 partition.hash_tree_salt().end());
734 }
735 if (partition.has_fec_extent()) {
736 Extent extent = partition.fec_data_extent();
737 install_part.fec_data_offset = extent.start_block() * block_size_;
738 install_part.fec_data_size = extent.num_blocks() * block_size_;
739 extent = partition.fec_extent();
740 install_part.fec_offset = extent.start_block() * block_size_;
741 install_part.fec_size = extent.num_blocks() * block_size_;
742 uint64_t fec_data_end =
743 install_part.fec_data_offset + install_part.fec_data_size;
744 if (install_part.fec_offset < fec_data_end) {
745 LOG(ERROR) << "Invalid fec extents, fec data ends at " << fec_data_end
746 << ", but fec starts at " << install_part.fec_offset;
747 *error = ErrorCode::kDownloadNewPartitionInfoError;
748 return false;
749 }
750 install_part.fec_roots = partition.fec_roots();
751 }
752
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700753 install_plan_->partitions.push_back(install_part);
754 }
755
Tianjied3865d12020-06-03 15:25:17 -0700756 // TODO(xunchang) only need to load the partitions for those in payload.
757 // Because we have already loaded the other once when generating SOURCE_COPY
758 // operations.
Alex Deymo542c19b2015-12-03 07:43:31 -0300759 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700760 LOG(ERROR) << "Unable to determine all the partition devices.";
761 *error = ErrorCode::kInstallDeviceOpenError;
762 return false;
763 }
764 LogPartitionInfo(partitions_);
765 return true;
766}
767
Yifan Hongb9d63572020-01-09 17:50:46 -0800768bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
769 // Call static PreparePartitionsForUpdate with hash from
770 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
771 // preallocated for is the same as the hash of payload being applied.
772 string update_check_response_hash;
773 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
774 &update_check_response_hash));
775 return PreparePartitionsForUpdate(prefs_,
776 boot_control_,
777 install_plan_->target_slot,
778 manifest_,
779 update_check_response_hash,
780 required_size);
781}
782
783bool DeltaPerformer::PreparePartitionsForUpdate(
784 PrefsInterface* prefs,
785 BootControlInterface* boot_control,
786 BootControlInterface::Slot target_slot,
787 const DeltaArchiveManifest& manifest,
788 const std::string& update_check_response_hash,
789 uint64_t* required_size) {
790 string last_hash;
791 ignore_result(
792 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
793
794 bool is_resume = !update_check_response_hash.empty() &&
795 last_hash == update_check_response_hash;
796
797 if (is_resume) {
798 LOG(INFO) << "Using previously prepared partitions for update. hash = "
799 << last_hash;
800 } else {
801 LOG(INFO) << "Preparing partitions for new update. last hash = "
802 << last_hash << ", new hash = " << update_check_response_hash;
803 }
804
805 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
806 boot_control->GetCurrentSlot(),
807 target_slot,
808 manifest,
809 !is_resume /* should update */,
810 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700811 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -0800812 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700813 return false;
814 }
Yifan Hongb9d63572020-01-09 17:50:46 -0800815
816 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
817 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -0700818 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700819
820 return true;
821}
822
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700823bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700824 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700825 // If we don't have a data blob we can apply it right away.
826 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700827 return true;
828
829 // See if we have the entire data blob in the buffer
830 if (operation.data_offset() < buffer_offset_) {
831 LOG(ERROR) << "we threw away data it seems?";
832 return false;
833 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700834
Gilad Arnoldfe133932014-01-14 12:25:50 -0800835 return (operation.data_offset() + operation.data_length() <=
836 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700837}
838
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700839bool DeltaPerformer::PerformReplaceOperation(
840 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700841 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700842 operation.type() == InstallOperation::REPLACE_BZ ||
843 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700844
845 // Since we delete data off the beginning of the buffer as we use it,
846 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700847 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700848
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400849 TEST_AND_RETURN_FALSE(partition_writer_->PerformReplaceOperation(
850 operation, buffer_.data(), buffer_.size()));
851 // Update buffer
852 DiscardBuffer(true, buffer_.size());
853 return true;
854}
855
Alex Deymo79715ad2015-10-02 14:27:53 -0700856bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700857 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700858 CHECK(operation.type() == InstallOperation::DISCARD ||
859 operation.type() == InstallOperation::ZERO);
860
861 // These operations have no blob.
862 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
863 TEST_AND_RETURN_FALSE(!operation.has_data_length());
Kelvin Zhang50bac652020-09-28 15:51:41 -0400864
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400865 return partition_writer_->PerformZeroOrDiscardOperation(operation);
866}
Alex Deymo79715ad2015-10-02 14:27:53 -0700867
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400868bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
869 const InstallOperation& operation,
870 const FileDescriptorPtr source_fd,
871 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800872 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
873 operation.src_sha256_hash().end());
874 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -0700875 LOG(ERROR) << "The hash of the source data on disk for this operation "
876 << "doesn't match the expected value. This could mean that the "
877 << "delta update payload was targeted for another version, or "
878 << "that the source partition was modified after it was "
879 << "installed, for example, by mounting a filesystem.";
880 LOG(ERROR) << "Expected: sha256|hex = "
881 << base::HexEncode(expected_source_hash.data(),
882 expected_source_hash.size());
883 LOG(ERROR) << "Calculated: sha256|hex = "
884 << base::HexEncode(calculated_hash.data(),
885 calculated_hash.size());
886
887 vector<string> source_extents;
888 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100889 source_extents.push_back(
890 base::StringPrintf("%" PRIu64 ":%" PRIu64,
891 static_cast<uint64_t>(ext.start_block()),
892 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -0700893 }
894 LOG(ERROR) << "Operation source (offset:size) in blocks: "
895 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700896
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +0100897 // Log remount history if this device is an ext4 partition.
898 LogMountHistory(source_fd);
899
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700900 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800901 return false;
902 }
903 return true;
904}
905
Allie Wood9f6f0a52015-03-30 11:25:47 -0700906bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700907 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700908 if (operation.has_src_length())
909 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
910 if (operation.has_dst_length())
911 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400912 return partition_writer_->PerformSourceCopyOperation(operation, error);
913}
Allie Wood9f6f0a52015-03-30 11:25:47 -0700914
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700915bool DeltaPerformer::ExtentsToBsdiffPositionsString(
916 const RepeatedPtrField<Extent>& extents,
917 uint64_t block_size,
918 uint64_t full_length,
919 string* positions_string) {
920 string ret;
921 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700922 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700923 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +0100924 uint64_t this_length =
925 min(full_length - length,
926 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700927 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700928 length += this_length;
929 }
930 TEST_AND_RETURN_FALSE(length == full_length);
931 if (!ret.empty())
932 ret.resize(ret.size() - 1); // Strip trailing comma off
933 *positions_string = ret;
934 return true;
935}
936
Allie Wood9f6f0a52015-03-30 11:25:47 -0700937bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700938 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700939 // Since we delete data off the beginning of the buffer as we use it,
940 // the data we need should be exactly at the beginning of the buffer.
941 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
942 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
943 if (operation.has_src_length())
944 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
945 if (operation.has_dst_length())
946 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
947
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400948 TEST_AND_RETURN_FALSE(partition_writer_->PerformSourceBsdiffOperation(
949 operation, error, buffer_.data(), buffer_.size()));
950 DiscardBuffer(true, buffer_.size());
951 return true;
952}
953
Amin Hassani02855c22017-09-06 22:34:50 -0700954bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
955 ErrorCode* error) {
956 // Since we delete data off the beginning of the buffer as we use it,
957 // the data we need should be exactly at the beginning of the buffer.
958 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
959 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400960 TEST_AND_RETURN_FALSE(partition_writer_->PerformPuffDiffOperation(
961 operation, error, buffer_.data(), buffer_.size()));
962 DiscardBuffer(true, buffer_.size());
963 return true;
964}
Amin Hassani02855c22017-09-06 22:34:50 -0700965
Sen Jiangf6813802015-11-03 21:27:29 -0800966bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700967 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
968 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
969 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700970 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -0800971 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700972
973 // Save the signature blob because if the update is interrupted after the
Kelvin Zhang50bac652020-09-28 15:51:41 -0400974 // download phase we don't go through this path anymore. Some alternatives
975 // to consider:
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700976 //
Kelvin Zhang50bac652020-09-28 15:51:41 -0400977 // 1. On resume, re-download the signature blob from the server and
978 // re-verify it.
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700979 //
980 // 2. Verify the signature as soon as it's received and don't checkpoint the
981 // blob and the signed sha-256 context.
Amin Hassani008c4582019-01-13 16:22:47 -0800982 LOG_IF(WARNING,
983 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Sen Jiang9b2f1782019-01-24 14:27:50 -0800984 signatures_message_data_))
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700985 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -0800986
Darin Petkovd7061ab2010-10-06 14:37:09 -0700987 LOG(INFO) << "Extracted signature data of size "
988 << manifest_.signatures_size() << " at "
989 << manifest_.signatures_offset();
990 return true;
991}
992
Sen Jiang08c6da12019-01-07 18:28:56 -0800993bool DeltaPerformer::GetPublicKey(string* out_public_key) {
994 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -0700995
Sen Jiang08c6da12019-01-07 18:28:56 -0800996 if (utils::FileExists(public_key_path_.c_str())) {
997 LOG(INFO) << "Verifying using public key: " << public_key_path_;
998 return utils::ReadFile(public_key_path_, out_public_key);
999 }
1000
Kelvin Zhang50bac652020-09-28 15:51:41 -04001001 // If this is an official build then we are not allowed to use public key
1002 // from Omaha response.
Sen Jiang08c6da12019-01-07 18:28:56 -08001003 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
1004 LOG(INFO) << "Verifying using public key from Omaha response.";
1005 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1006 out_public_key);
1007 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001008 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001009 return true;
1010}
1011
Tianjie Xu7a78d632019-10-08 16:32:39 -07001012std::pair<std::unique_ptr<PayloadVerifier>, bool>
1013DeltaPerformer::CreatePayloadVerifier() {
1014 if (utils::FileExists(update_certificates_path_.c_str())) {
1015 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1016 return {
1017 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1018 true};
1019 }
1020
1021 string public_key;
1022 if (!GetPublicKey(&public_key)) {
1023 LOG(ERROR) << "Failed to read public key";
1024 return {nullptr, true};
1025 }
1026
1027 // Skips the verification if the public key is empty.
1028 if (public_key.empty()) {
1029 return {nullptr, false};
1030 }
1031 return {PayloadVerifier::CreateInstance(public_key), true};
1032}
1033
Gilad Arnold21504f02013-05-24 08:51:22 -07001034ErrorCode DeltaPerformer::ValidateManifest() {
Saint Chou0a92a622020-07-29 14:25:35 +00001035 // Perform assorted checks to validation check the manifest, make sure it
Don Garrettb8dd1d92013-11-22 17:40:02 -08001036 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +00001037 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
1038 manifest_.partitions().end(),
1039 [](const PartitionUpdate& partition) {
1040 return partition.has_old_partition_info();
1041 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001042
Alex Deymo64d98782016-02-05 18:03:48 -08001043 // The presence of an old partition hash is the sole indicator for a delta
Tianjief5baff42020-07-17 21:43:22 -07001044 // update. Also, always treat the partial update as delta so that we can
1045 // perform the minor version check correctly.
Alex Deymo64d98782016-02-05 18:03:48 -08001046 InstallPayloadType actual_payload_type =
Tianjief5baff42020-07-17 21:43:22 -07001047 (has_old_fields || manifest_.partial_update())
1048 ? InstallPayloadType::kDelta
1049 : InstallPayloadType::kFull;
Alex Deymo64d98782016-02-05 18:03:48 -08001050
Sen Jiangcdd52062017-05-18 15:33:10 -07001051 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001052 LOG(INFO) << "Detected a '"
1053 << InstallPayloadTypeToString(actual_payload_type)
1054 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001055 payload_->type = actual_payload_type;
1056 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001057 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001058 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001059 << "' payload but the downloaded manifest contains a '"
1060 << InstallPayloadTypeToString(actual_payload_type)
1061 << "' payload.";
1062 return ErrorCode::kPayloadMismatchedType;
1063 }
Alex Deymo64d98782016-02-05 18:03:48 -08001064 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001065 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001066 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001067 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1068 LOG(ERROR) << "Manifest contains minor version "
1069 << manifest_.minor_version()
1070 << ", but all full payloads should have version "
1071 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001073 }
1074 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001075 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1076 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001077 LOG(ERROR) << "Manifest contains minor version "
1078 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001079 << " not in the range of supported minor versions ["
1080 << kMinSupportedMinorPayloadVersion << ", "
1081 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001082 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001083 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001084 }
1085
Yifan Hong87029332020-09-01 17:20:08 -07001086 ErrorCode error_code = CheckTimestampError();
1087 if (error_code != ErrorCode::kSuccess) {
1088 if (error_code == ErrorCode::kPayloadTimestampError) {
1089 if (!hardware_->AllowDowngrade()) {
1090 return ErrorCode::kPayloadTimestampError;
1091 }
1092 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1093 " the payload with an older timestamp.";
1094 } else {
1095 LOG(ERROR) << "Timestamp check returned "
1096 << utils::ErrorCodeToString(error_code);
1097 return error_code;
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001098 }
Sen Jiang8e768e92017-06-28 17:13:19 -07001099 }
1100
Amin Hassani55c75412019-10-07 11:20:39 -07001101 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1102 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001103
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001105}
1106
Yifan Hong87029332020-09-01 17:20:08 -07001107ErrorCode DeltaPerformer::CheckTimestampError() const {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001108 bool is_partial_update =
1109 manifest_.has_partial_update() && manifest_.partial_update();
1110 const auto& partitions = manifest_.partitions();
Yifan Hong87029332020-09-01 17:20:08 -07001111
1112 // Check version field for a given PartitionUpdate object. If an error
1113 // is encountered, set |error_code| accordingly. If downgrade is detected,
Kelvin Zhang50bac652020-09-28 15:51:41 -04001114 // |downgrade_detected| is set. Return true if the program should continue
1115 // to check the next partition or not, or false if it should exit early due
1116 // to errors.
Yifan Hong87029332020-09-01 17:20:08 -07001117 auto&& timestamp_valid = [this](const PartitionUpdate& partition,
1118 bool allow_empty_version,
1119 bool* downgrade_detected) -> ErrorCode {
Tianjie19e55292020-10-19 21:49:37 -07001120 const auto& partition_name = partition.partition_name();
Yifan Hong87029332020-09-01 17:20:08 -07001121 if (!partition.has_version()) {
Tianjie19e55292020-10-19 21:49:37 -07001122 if (hardware_->GetVersionForLogging(partition_name).empty()) {
1123 LOG(INFO) << partition_name << " does't have version, skipping "
1124 << "downgrade check.";
1125 return ErrorCode::kSuccess;
1126 }
1127
Yifan Hong87029332020-09-01 17:20:08 -07001128 if (allow_empty_version) {
1129 return ErrorCode::kSuccess;
1130 }
1131 LOG(ERROR)
Tianjie19e55292020-10-19 21:49:37 -07001132 << "PartitionUpdate " << partition_name
1133 << " doesn't have a version field. Not allowed in partial updates.";
Yifan Hong87029332020-09-01 17:20:08 -07001134 return ErrorCode::kDownloadManifestParseError;
1135 }
1136
Tianjie19e55292020-10-19 21:49:37 -07001137 auto error_code =
1138 hardware_->IsPartitionUpdateValid(partition_name, partition.version());
Yifan Hong87029332020-09-01 17:20:08 -07001139 switch (error_code) {
1140 case ErrorCode::kSuccess:
1141 break;
1142 case ErrorCode::kPayloadTimestampError:
1143 *downgrade_detected = true;
Tianjie19e55292020-10-19 21:49:37 -07001144 LOG(WARNING) << "PartitionUpdate " << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001145 << " has an older version than partition on device.";
1146 break;
1147 default:
Tianjie19e55292020-10-19 21:49:37 -07001148 LOG(ERROR) << "IsPartitionUpdateValid(" << partition_name
Yifan Hong87029332020-09-01 17:20:08 -07001149 << ") returned" << utils::ErrorCodeToString(error_code);
1150 break;
1151 }
1152 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001153 };
Yifan Hong87029332020-09-01 17:20:08 -07001154
1155 bool downgrade_detected = false;
1156
Kelvin Zhangd7191032020-08-11 10:48:16 -04001157 if (is_partial_update) {
1158 // for partial updates, all partition MUST have valid timestamps
1159 // But max_timestamp can be empty
1160 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001161 auto error_code = timestamp_valid(
1162 partition, false /* allow_empty_version */, &downgrade_detected);
1163 if (error_code != ErrorCode::kSuccess &&
1164 error_code != ErrorCode::kPayloadTimestampError) {
1165 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001166 }
1167 }
Yifan Hong87029332020-09-01 17:20:08 -07001168 if (downgrade_detected) {
1169 return ErrorCode::kPayloadTimestampError;
1170 }
1171 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001172 }
Yifan Hong87029332020-09-01 17:20:08 -07001173
1174 // For non-partial updates, check max_timestamp first.
Kelvin Zhangd7191032020-08-11 10:48:16 -04001175 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1176 LOG(ERROR) << "The current OS build timestamp ("
1177 << hardware_->GetBuildTimestamp()
1178 << ") is newer than the maximum timestamp in the manifest ("
1179 << manifest_.max_timestamp() << ")";
Yifan Hong87029332020-09-01 17:20:08 -07001180 return ErrorCode::kPayloadTimestampError;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001181 }
1182 // Otherwise... partitions can have empty timestamps.
1183 for (const auto& partition : partitions) {
Yifan Hong87029332020-09-01 17:20:08 -07001184 auto error_code = timestamp_valid(
1185 partition, true /* allow_empty_version */, &downgrade_detected);
1186 if (error_code != ErrorCode::kSuccess &&
1187 error_code != ErrorCode::kPayloadTimestampError) {
1188 return error_code;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001189 }
1190 }
Yifan Hong87029332020-09-01 17:20:08 -07001191 if (downgrade_detected) {
1192 return ErrorCode::kPayloadTimestampError;
1193 }
1194 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001195}
1196
David Zeuthena99981f2013-04-29 13:42:47 -07001197ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001198 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001199 if (!operation.data_sha256_hash().size()) {
1200 if (!operation.data_length()) {
Kelvin Zhang50bac652020-09-28 15:51:41 -04001201 // Operations that do not have any data blob won't have any operation
1202 // hash either. So, these operations are always considered validated
1203 // since the metadata that contains all the non-data-blob portions of
1204 // the operation has already been validated. This is true for both HTTP
1205 // and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001206 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001207 }
1208
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001209 // No hash is present for an operation that has data blobs. This shouldn't
1210 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001211 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001212 // hashes. So if it happens it means either we've turned operation hash
1213 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Saint Chou0a92a622020-07-29 14:25:35 +00001214 // One caveat though: The last operation is a unused signature operation
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001215 // that doesn't have a hash at the time the manifest is created. So we
1216 // should not complaint about that operation. This operation can be
1217 // recognized by the fact that it's offset is mentioned in the manifest.
1218 if (manifest_.signatures_offset() &&
1219 manifest_.signatures_offset() == operation.data_offset()) {
1220 LOG(INFO) << "Skipping hash verification for signature operation "
1221 << next_operation_num_ + 1;
1222 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001223 if (install_plan_->hash_checks_mandatory) {
1224 LOG(ERROR) << "Missing mandatory operation hash for operation "
1225 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001226 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001227 }
1228
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001229 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1230 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001233 }
1234
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001235 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001236 expected_op_hash.assign(operation.data_sha256_hash().data(),
1237 (operation.data_sha256_hash().data() +
1238 operation.data_sha256_hash().size()));
1239
Sen Jiang2703ef42017-03-16 13:36:21 -07001240 brillo::Blob calculated_op_hash;
1241 if (!HashCalculator::RawHashOfBytes(
1242 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001243 LOG(ERROR) << "Unable to compute actual hash of operation "
1244 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001245 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001246 }
1247
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001248 if (calculated_op_hash != expected_op_hash) {
1249 LOG(ERROR) << "Hash verification failed for operation "
1250 << next_operation_num_ << ". Expected hash = ";
1251 utils::HexDumpVector(expected_op_hash);
1252 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1253 << " bytes at offset: " << operation.data_offset() << " = ";
1254 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001255 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001256 }
1257
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001258 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001259}
1260
Amin Hassani008c4582019-01-13 16:22:47 -08001261#define TEST_AND_RETURN_VAL(_retval, _condition) \
1262 do { \
1263 if (!(_condition)) { \
1264 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1265 return _retval; \
1266 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001267 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001268
David Zeuthena99981f2013-04-29 13:42:47 -07001269ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001270 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001271 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001272 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001273 if (update_check_response_size !=
1274 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1275 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1276 << ") doesn't match metadata_size (" << metadata_size_
1277 << ") + metadata_signature_size (" << metadata_signature_size_
1278 << ") + buffer_offset (" << buffer_offset_ << ").";
1279 return ErrorCode::kPayloadSizeMismatchError;
1280 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001281
Amin Hassanie331f5a2020-10-06 15:53:29 -07001282 // Verifies the payload hash.
1283 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
1284 !payload_hash_calculator_.raw_hash().empty());
1285 TEST_AND_RETURN_VAL(
1286 ErrorCode::kPayloadHashMismatchError,
1287 payload_hash_calculator_.raw_hash() == update_check_response_hash);
1288
Amin Hassaniec7bc112020-10-29 16:47:58 -07001289 // NOLINTNEXTLINE(whitespace/braces)
Amin Hassanif624e112020-09-15 15:30:08 -07001290 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1291 if (!perform_verification) {
1292 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1293 return ErrorCode::kSuccess;
1294 }
1295 if (!payload_verifier) {
1296 LOG(ERROR) << "Failed to create the payload verifier.";
1297 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1298 }
1299
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001300 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001301 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001302 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001303 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001304 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001305
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001306 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001307 // The autoupdate_CatchBadSignatures test checks for this string
1308 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001309 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001310 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001311 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001312
David Zeuthene7f89172013-10-31 10:21:04 -07001313 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001314 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001315}
1316
Sen Jiangf6813802015-11-03 21:27:29 -08001317void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1318 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001319 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001320 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001321 buffer_offset_ += buffer_.size();
1322
1323 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001324 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1325 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001326
1327 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001328 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001329}
1330
Darin Petkov0406e402010-10-06 21:33:11 -07001331bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001332 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001333 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001334 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Amin Hassani008c4582019-01-13 16:22:47 -08001335 next_operation != kUpdateStateOperationInvalid && next_operation > 0))
Alex Deymo3310b222015-03-30 15:59:07 -07001336 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001337
1338 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001339 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1340 !interrupted_hash.empty() &&
1341 interrupted_hash == update_check_response_hash))
1342 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001343
Darin Petkov61426142010-10-08 11:04:55 -07001344 int64_t resumed_update_failures;
Kelvin Zhang50bac652020-09-28 15:51:41 -04001345 // Note that storing this value is optional, but if it is there it should
1346 // not be more than the limit.
Alex Deymof25eb492016-02-26 00:20:08 -08001347 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1348 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001349 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001350
Saint Chou0a92a622020-07-29 14:25:35 +00001351 // Validation check the rest.
Darin Petkov0406e402010-10-06 21:33:11 -07001352 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001353 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1354 next_data_offset >= 0))
1355 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001356
Darin Petkov437adc42010-10-07 13:12:24 -07001357 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001358 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1359 !sha256_context.empty()))
1360 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001361
1362 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001363 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1364 manifest_metadata_size > 0))
1365 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001366
Alex Deymof25eb492016-02-26 00:20:08 -08001367 int64_t manifest_signature_size = 0;
1368 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1369 &manifest_signature_size) &&
1370 manifest_signature_size >= 0))
1371 return false;
1372
Darin Petkov0406e402010-10-06 21:33:11 -07001373 return true;
1374}
1375
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001376bool DeltaPerformer::ResetUpdateProgress(
1377 PrefsInterface* prefs,
1378 bool quick,
1379 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07001380 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1381 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001382 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001383 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001384 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001385 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1386 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001387 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001388 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001389 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001390 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001391 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001392 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001393
1394 if (!skip_dynamic_partititon_metadata_updated) {
1395 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1396 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
1397 }
Darin Petkov9b230572010-10-08 10:20:09 -07001398 }
Darin Petkov73058b42010-10-06 16:32:19 -07001399 return true;
1400}
1401
Sen Jiang3a25dc22019-01-10 14:14:41 -08001402bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001403 base::TimeTicks curr_time = base::TimeTicks::Now();
Sen Jiang3a25dc22019-01-10 14:14:41 -08001404 if (force || curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001405 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
1406 } else {
1407 return false;
1408 }
1409
Darin Petkov9c0baf82010-10-07 13:44:48 -07001410 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001411 if (last_updated_buffer_offset_ != buffer_offset_) {
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);
Amin Hassani008c4582019-01-13 16:22:47 -08001414 TEST_AND_RETURN_FALSE(prefs_->SetString(
1415 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001416 TEST_AND_RETURN_FALSE(
1417 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1418 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001419 TEST_AND_RETURN_FALSE(
1420 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Darin Petkov0406e402010-10-06 21:33:11 -07001421 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001422
1423 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001424 size_t partition_index = current_partition_;
1425 while (next_operation_num_ >= acc_num_operations_[partition_index])
1426 partition_index++;
Amin Hassani008c4582019-01-13 16:22:47 -08001427 const size_t partition_operation_num =
1428 next_operation_num_ -
1429 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001430 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001431 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001432 TEST_AND_RETURN_FALSE(
1433 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001434 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001435 TEST_AND_RETURN_FALSE(
1436 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001437 }
Darin Petkov0406e402010-10-06 21:33:11 -07001438 }
Amin Hassani008c4582019-01-13 16:22:47 -08001439 TEST_AND_RETURN_FALSE(
1440 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07001441 return true;
1442}
1443
Darin Petkov9b230572010-10-08 10:20:09 -07001444bool DeltaPerformer::PrimeUpdateState() {
1445 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001446
1447 int64_t next_operation = kUpdateStateOperationInvalid;
1448 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001449 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001450 // Initiating a new update, no more state needs to be initialized.
1451 return true;
1452 }
1453 next_operation_num_ = next_operation;
1454
1455 // Resuming an update -- load the rest of the update state.
1456 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001457 TEST_AND_RETURN_FALSE(
1458 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1459 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001460 buffer_offset_ = next_data_offset;
1461
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001462 // The signed hash context and the signature blob may be empty if the
1463 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001464 string signed_hash_context;
1465 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1466 &signed_hash_context)) {
1467 TEST_AND_RETURN_FALSE(
1468 signed_hash_calculator_.SetContext(signed_hash_context));
1469 }
1470
Sen Jiang9b2f1782019-01-24 14:27:50 -08001471 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001472
1473 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001474 TEST_AND_RETURN_FALSE(
1475 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1476 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001477
1478 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001479 TEST_AND_RETURN_FALSE(
1480 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1481 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001482 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001483
Alex Deymof25eb492016-02-26 00:20:08 -08001484 int64_t manifest_signature_size = 0;
1485 TEST_AND_RETURN_FALSE(
1486 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1487 manifest_signature_size >= 0);
1488 metadata_signature_size_ = manifest_signature_size;
1489
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001490 // Advance the download progress to reflect what doesn't need to be
1491 // re-downloaded.
1492 total_bytes_received_ += buffer_offset_;
1493
Darin Petkov61426142010-10-08 11:04:55 -07001494 // Speculatively count the resume as a failure.
1495 int64_t resumed_update_failures;
1496 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1497 resumed_update_failures++;
1498 } else {
1499 resumed_update_failures = 1;
1500 }
1501 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001502 return true;
1503}
1504
Kelvin Zhang94f51cc2020-09-25 11:34:49 -04001505bool DeltaPerformer::IsDynamicPartition(const std::string& part_name) {
1506 return std::find(dynamic_partitions_.begin(),
1507 dynamic_partitions_.end(),
1508 part_name) != dynamic_partitions_.end();
1509}
1510
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001511} // namespace chromeos_update_engine