blob: 7d837db46d034dd6dac76dc08534f5636fdf7f49 [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"
44#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030045#include "update_engine/common/prefs_interface.h"
46#include "update_engine/common/subprocess.h"
47#include "update_engine/common/terminator.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080048#include "update_engine/payload_consumer/bzip_extent_writer.h"
Amin Hassania3fc20a2017-09-19 17:19:34 -070049#include "update_engine/payload_consumer/cached_file_descriptor.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070050#include "update_engine/payload_consumer/certificate_parser_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030051#include "update_engine/payload_consumer/download_action.h"
Amin Hassanidb56be92017-09-06 12:41:23 -070052#include "update_engine/payload_consumer/extent_reader.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080053#include "update_engine/payload_consumer/extent_writer.h"
Tianjied3865d12020-06-03 15:25:17 -070054#include "update_engine/payload_consumer/partition_update_generator_interface.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070055#if USE_FEC
56#include "update_engine/payload_consumer/fec_file_descriptor.h"
57#endif // USE_FEC
Alex Deymoa48f6302016-11-04 15:49:53 -070058#include "update_engine/payload_consumer/file_descriptor_utils.h"
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +010059#include "update_engine/payload_consumer/mount_history.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/payload_consumer/payload_constants.h"
61#include "update_engine/payload_consumer/payload_verifier.h"
62#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070063
Alex Deymo161c4a12014-05-16 15:56:21 -070064using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070065using std::min;
66using std::string;
67using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068
69namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080070const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
71const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
72const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
73const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070074const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080075
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070077const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070078const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080079
Amin Hassania3fc20a2017-09-19 17:19:34 -070080const uint64_t kCacheSize = 1024 * 1024; // 1MB
81
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080082// Opens path for read/write. On success returns an open FileDescriptor
83// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Amin Hassania3fc20a2017-09-19 17:19:34 -070084FileDescriptorPtr OpenFile(const char* path,
85 int mode,
86 bool cache_writes,
87 int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -070088 // Try to mark the block device read-only based on the mode. Ignore any
89 // failure since this won't work when passing regular files.
Amin Hassania3fc20a2017-09-19 17:19:34 -070090 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
91 utils::SetBlockDeviceReadOnly(path, read_only);
Alex Deymo5fb356c2016-03-25 18:48:22 -070092
Brian Norris7b428f52019-06-26 10:03:35 -070093 FileDescriptorPtr fd(new EintrSafeFileDescriptor());
Amin Hassania3fc20a2017-09-19 17:19:34 -070094 if (cache_writes && !read_only) {
95 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
96 LOG(INFO) << "Caching writes.";
97 }
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080098 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080099 *err = errno;
100 PLOG(ERROR) << "Unable to open file " << path;
101 return nullptr;
102 }
103 *err = 0;
104 return fd;
105}
Alex Deymob86787c2016-05-12 18:46:25 -0700106
107// Discard the tail of the block device referenced by |fd|, from the offset
108// |data_size| until the end of the block device. Returns whether the data was
109// discarded.
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700110bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
Alex Deymob86787c2016-05-12 18:46:25 -0700111 uint64_t part_size = fd->BlockDevSize();
112 if (!part_size || part_size <= data_size)
113 return false;
114
Alex Deymo72a68d82016-06-15 16:31:04 -0700115 struct blkioctl_request {
116 int number;
117 const char* name;
118 };
119 const vector<blkioctl_request> blkioctl_requests = {
Alex Deymo72a68d82016-06-15 16:31:04 -0700120 {BLKDISCARD, "BLKDISCARD"},
Amin Hassani41555202017-06-23 12:42:00 -0700121 {BLKSECDISCARD, "BLKSECDISCARD"},
Alex Deymob86787c2016-05-12 18:46:25 -0700122#ifdef BLKZEROOUT
Alex Deymo72a68d82016-06-15 16:31:04 -0700123 {BLKZEROOUT, "BLKZEROOUT"},
Alex Deymob86787c2016-05-12 18:46:25 -0700124#endif
125 };
Alex Deymo72a68d82016-06-15 16:31:04 -0700126 for (const auto& req : blkioctl_requests) {
Alex Deymob86787c2016-05-12 18:46:25 -0700127 int error = 0;
Alex Deymo72a68d82016-06-15 16:31:04 -0700128 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
Alex Deymob86787c2016-05-12 18:46:25 -0700129 error == 0) {
130 return true;
131 }
132 LOG(WARNING) << "Error discarding the last "
133 << (part_size - data_size) / 1024 << " KiB using ioctl("
Alex Deymo72a68d82016-06-15 16:31:04 -0700134 << req.name << ")";
Alex Deymob86787c2016-05-12 18:46:25 -0700135 }
136 return false;
137}
138
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700139} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700140
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800141// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
142// arithmetic.
143static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
144 return part * norm / total;
145}
146
147void DeltaPerformer::LogProgress(const char* message_prefix) {
148 // Format operations total count and percentage.
149 string total_operations_str("?");
150 string completed_percentage_str("");
151 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700152 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800153 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800154 completed_percentage_str = base::StringPrintf(
155 " (%" PRIu64 "%%)",
156 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800157 }
158
159 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800160 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800161 string payload_size_str("?");
162 string downloaded_percentage_str("");
163 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700164 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800165 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800166 downloaded_percentage_str = base::StringPrintf(
167 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800168 }
169
170 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
171 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800172 << completed_percentage_str << ", " << total_bytes_received_ << "/"
173 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800174 << downloaded_percentage_str << ", overall progress "
175 << overall_progress_ << "%";
176}
177
178void DeltaPerformer::UpdateOverallProgress(bool force_log,
179 const char* message_prefix) {
180 // Compute our download and overall progress.
181 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800182 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
183 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800184 // Only consider download progress if its total size is known; otherwise
185 // adjust the operations weight to compensate for the absence of download
186 // progress. Also, make sure to cap the download portion at
187 // kProgressDownloadWeight, in case we end up downloading more than we
188 // initially expected (this indicates a problem, but could generally happen).
189 // TODO(garnold) the correction of operations weight when we do not have the
190 // total payload size, as well as the conditional guard below, should both be
191 // eliminated once we ensure that the payload_size in the install plan is
192 // always given and is non-zero. This currently isn't the case during unit
193 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800194 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800195 unsigned actual_operations_weight = kProgressOperationsWeight;
196 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800197 new_overall_progress +=
198 min(static_cast<unsigned>(IntRatio(
199 total_bytes_received_, payload_size, kProgressDownloadWeight)),
200 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800201 else
202 actual_operations_weight += kProgressDownloadWeight;
203
204 // Only add completed operations if their total number is known; we definitely
205 // expect an update to have at least one operation, so the expectation is that
206 // this will eventually reach |actual_operations_weight|.
207 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800208 new_overall_progress += IntRatio(
209 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800210
211 // Progress ratio cannot recede, unless our assumptions about the total
212 // payload size, total number of operations, or the monotonicity of progress
213 // is breached.
214 if (new_overall_progress < overall_progress_) {
215 LOG(WARNING) << "progress counter receded from " << overall_progress_
216 << "% down to " << new_overall_progress << "%; this is a bug";
217 force_log = true;
218 }
219 overall_progress_ = new_overall_progress;
220
221 // Update chunk index, log as needed: if forced by called, or we completed a
222 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800223 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800224 unsigned curr_progress_chunk =
225 overall_progress_ * kProgressLogMaxChunks / 100;
226 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
227 curr_time > forced_progress_log_time_) {
228 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
229 LogProgress(message_prefix);
230 }
231 last_progress_chunk_ = curr_progress_chunk;
232}
233
Amin Hassani008c4582019-01-13 16:22:47 -0800234size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
235 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800236 size_t max) {
237 const size_t count = *count_p;
238 if (!count)
239 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700240 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800241 const char* bytes_start = *bytes_p;
242 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800243 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800244 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
245 *bytes_p = bytes_end;
246 *count_p = count - read_len;
247 return read_len;
248}
249
Amin Hassani008c4582019-01-13 16:22:47 -0800250bool DeltaPerformer::HandleOpResult(bool op_result,
251 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800252 ErrorCode* error) {
253 if (op_result)
254 return true;
255
Alex Deymo3d009062016-05-13 15:51:25 -0700256 size_t partition_first_op_num =
257 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800258 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700259 << next_operation_num_ << ", which is the operation "
260 << next_operation_num_ - partition_first_op_num
261 << " in partition \""
262 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700263 if (*error == ErrorCode::kSuccess)
264 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800265 return false;
266}
267
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700269 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800270 LOG_IF(ERROR,
271 !payload_hash_calculator_.Finalize() ||
272 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800273 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800274 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700275 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
276 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800277 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800278 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700279 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700280}
281
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700282int DeltaPerformer::CloseCurrentPartition() {
283 int err = 0;
284 if (source_fd_ && !source_fd_->Close()) {
285 err = errno;
286 PLOG(ERROR) << "Error closing source partition";
287 if (!err)
288 err = 1;
289 }
290 source_fd_.reset();
Alex Deymo51c264e2016-11-04 15:49:53 -0700291 if (source_ecc_fd_ && !source_ecc_fd_->Close()) {
292 err = errno;
293 PLOG(ERROR) << "Error closing ECC source partition";
294 if (!err)
295 err = 1;
296 }
297 source_ecc_fd_.reset();
298 source_ecc_open_failure_ = false;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700299 source_path_.clear();
300
301 if (target_fd_ && !target_fd_->Close()) {
302 err = errno;
303 PLOG(ERROR) << "Error closing target partition";
304 if (!err)
305 err = 1;
306 }
307 target_fd_.reset();
308 target_path_.clear();
309 return -err;
310}
311
312bool DeltaPerformer::OpenCurrentPartition() {
313 if (current_partition_ >= partitions_.size())
314 return false;
315
316 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700317 size_t num_previous_partitions =
318 install_plan_->partitions.size() - partitions_.size();
319 const InstallPlan::Partition& install_part =
320 install_plan_->partitions[num_previous_partitions + current_partition_];
Tianjie55abd3c2020-06-19 00:22:59 -0700321 // Open source fds if we have a delta payload, or for partitions in the
322 // partial update.
Tianjied3865d12020-06-03 15:25:17 -0700323 bool source_may_exist = manifest_.partial_update() ||
Tianjie55abd3c2020-06-19 00:22:59 -0700324 payload_->type == InstallPayloadType::kDelta;
Tianjied3865d12020-06-03 15:25:17 -0700325 // We shouldn't open the source partition in certain cases, e.g. some dynamic
326 // partitions in delta payload, partitions included in the full payload for
327 // partial updates. Use the source size as the indicator.
328 if (source_may_exist && install_part.source_size > 0) {
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700329 source_path_ = install_part.source_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700330 int err;
Amin Hassania3fc20a2017-09-19 17:19:34 -0700331 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, false, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700332 if (!source_fd_) {
333 LOG(ERROR) << "Unable to open source partition "
334 << partition.partition_name() << " on slot "
335 << BootControlInterface::SlotName(install_plan_->source_slot)
336 << ", file " << source_path_;
337 return false;
338 }
339 }
340
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700341 target_path_ = install_part.target_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700342 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700343
Amin Hassani7ecda262017-07-11 17:10:50 -0700344 int flags = O_RDWR;
Amin Hassanied37d682018-04-06 13:22:00 -0700345 if (!interactive_)
Amin Hassani7ecda262017-07-11 17:10:50 -0700346 flags |= O_DSYNC;
347
348 LOG(INFO) << "Opening " << target_path_ << " partition with"
Amin Hassanied37d682018-04-06 13:22:00 -0700349 << (interactive_ ? "out" : "") << " O_DSYNC";
Amin Hassani7ecda262017-07-11 17:10:50 -0700350
Amin Hassania3fc20a2017-09-19 17:19:34 -0700351 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700352 if (!target_fd_) {
353 LOG(ERROR) << "Unable to open target partition "
354 << partition.partition_name() << " on slot "
355 << BootControlInterface::SlotName(install_plan_->target_slot)
356 << ", file " << target_path_;
357 return false;
358 }
Alex Deymob86787c2016-05-12 18:46:25 -0700359
360 LOG(INFO) << "Applying " << partition.operations().size()
361 << " operations to partition \"" << partition.partition_name()
362 << "\"";
363
364 // Discard the end of the partition, but ignore failures.
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700365 DiscardPartitionTail(target_fd_, install_part.target_size);
Alex Deymob86787c2016-05-12 18:46:25 -0700366
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700367 return true;
368}
369
Alex Deymo51c264e2016-11-04 15:49:53 -0700370bool DeltaPerformer::OpenCurrentECCPartition() {
371 if (source_ecc_fd_)
372 return true;
373
374 if (source_ecc_open_failure_)
375 return false;
376
377 if (current_partition_ >= partitions_.size())
378 return false;
379
Amin Hassani0f59a9a2019-09-27 10:24:31 -0700380 // No support for ECC for full payloads.
381 if (payload_->type == InstallPayloadType::kFull)
Alex Deymo51c264e2016-11-04 15:49:53 -0700382 return false;
383
384#if USE_FEC
385 const PartitionUpdate& partition = partitions_[current_partition_];
386 size_t num_previous_partitions =
387 install_plan_->partitions.size() - partitions_.size();
388 const InstallPlan::Partition& install_part =
389 install_plan_->partitions[num_previous_partitions + current_partition_];
390 string path = install_part.source_path;
391 FileDescriptorPtr fd(new FecFileDescriptor());
392 if (!fd->Open(path.c_str(), O_RDONLY, 0)) {
393 PLOG(ERROR) << "Unable to open ECC source partition "
394 << partition.partition_name() << " on slot "
395 << BootControlInterface::SlotName(install_plan_->source_slot)
396 << ", file " << path;
397 source_ecc_open_failure_ = true;
398 return false;
399 }
400 source_ecc_fd_ = fd;
401#else
402 // No support for ECC compiled.
403 source_ecc_open_failure_ = true;
404#endif // USE_FEC
405
406 return !source_ecc_open_failure_;
407}
408
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700409namespace {
410
411void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700412 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800413 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
414 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700415}
416
Alex Deymo39910dc2015-11-09 17:04:30 -0800417void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700418 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800419 if (partition.has_old_partition_info()) {
420 LogPartitionInfoHash(partition.old_partition_info(),
421 "old " + partition.partition_name());
422 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700423 LogPartitionInfoHash(partition.new_partition_info(),
424 "new " + partition.partition_name());
425 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700426}
427
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700428} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700429
Allie Woodfdf00512015-03-02 13:34:55 -0800430uint32_t DeltaPerformer::GetMinorVersion() const {
431 if (manifest_.has_minor_version()) {
432 return manifest_.minor_version();
Allie Woodfdf00512015-03-02 13:34:55 -0800433 }
Sen Jiangf1236632018-05-11 16:03:23 -0700434 return payload_->type == InstallPayloadType::kDelta
435 ? kMaxSupportedMinorPayloadVersion
436 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800437}
438
Sen Jiangb8060e42015-09-24 17:30:50 -0700439bool DeltaPerformer::IsHeaderParsed() const {
440 return metadata_size_ != 0;
441}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700442
Sen Jiang9c89e842018-02-02 13:51:21 -0800443MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700444 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700445 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700446
Sen Jiangb8060e42015-09-24 17:30:50 -0700447 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700448 MetadataParseResult result =
449 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800450 if (result != MetadataParseResult::kSuccess)
451 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700452
Sen Jiang9c89e842018-02-02 13:51:21 -0800453 metadata_size_ = payload_metadata_.GetMetadataSize();
454 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
455 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800456
457 // If the metadata size is present in install plan, check for it immediately
458 // even before waiting for that many number of bytes to be downloaded in the
459 // payload. This will prevent any attack which relies on us downloading data
460 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800461 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800462 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800463 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800464 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800465 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700466 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800467 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800468 }
469 }
Andrew3a7dc262019-12-19 11:38:08 -0800470
471 // Check that the |metadata signature size_| and |metadata_size_| are not
472 // very big numbers. This is necessary since |update_engine| needs to write
473 // these values into the buffer before being able to use them, and if an
474 // attacker sets these values to a very big number, the buffer will overflow
475 // and |update_engine| will crash. A simple way of solving this is to check
476 // that the size of both values is smaller than the payload itself.
477 if (metadata_size_ + metadata_signature_size_ > payload_->size) {
478 LOG(ERROR) << "The size of the metadata_size(" << metadata_size_ << ")"
479 << " or metadata signature(" << metadata_signature_size_ << ")"
480 << " is greater than the size of the payload"
481 << "(" << payload_->size << ")";
482 *error = ErrorCode::kDownloadInvalidMetadataSize;
483 return MetadataParseResult::kError;
484 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700485 }
486
487 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700488 // metadata and its signature (if exist) to be read in before we can parse it.
489 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800490 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700491
492 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700493 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700494 // that we just log once (instead of logging n times) if it takes n
495 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800496 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700497 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800498 } else {
499 // For mandatory-cases, we'd have already returned a kMetadataParseError
500 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
501 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800502 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800503 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800504 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800505 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700506
Tianjie Xu7a78d632019-10-08 16:32:39 -0700507 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
508 if (!payload_verifier) {
509 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800510 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700511 if (perform_verification) {
512 return MetadataParseResult::kError;
513 }
514 } else {
515 // We have the full metadata in |payload|. Verify its integrity
516 // and authenticity based on the information we have in Omaha response.
517 *error = payload_metadata_.ValidateMetadataSignature(
518 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800519 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700520 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800521 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800522 // The autoupdate_CatchBadSignatures test checks for this string
523 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800524 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800525 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800526 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700527
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800528 // For non-mandatory cases, just send a UMA stat.
529 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700530 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700531 }
532
Gilad Arnolddaa27402014-01-23 11:56:17 -0800533 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800534 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800535 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700536 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800537 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800538 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800539
540 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800541 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800542}
543
Amin Hassani008c4582019-01-13 16:22:47 -0800544#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
545 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
546 "UpdateEngine.DownloadAction.InstallOperation::" _op_name ".Duration", \
Andrew9d5a61d2020-03-26 13:40:37 -0700547 (base::TimeTicks::Now() - _start_time), \
Amin Hassani008c4582019-01-13 16:22:47 -0800548 base::TimeDelta::FromMilliseconds(10), \
549 base::TimeDelta::FromMinutes(5), \
550 20);
Lann Martin39f57142017-07-14 09:18:42 -0600551
Don Garrette410e0f2011-11-10 15:39:01 -0800552// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800553// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700554// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800555bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700556 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700557 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800558
559 // Update the total byte downloaded count and the progress logs.
560 total_bytes_received_ += count;
561 UpdateOverallProgress(false, "Completed ");
562
Gilad Arnoldfe133932014-01-14 12:25:50 -0800563 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700564 // Read data up to the needed limit; this is either maximium payload header
565 // size, or the full metadata size (once it becomes known).
566 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800567 CopyDataToBuffer(
568 &c_bytes,
569 &count,
570 (do_read_header ? kMaxPayloadHeaderSize
571 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800572
Gilad Arnolddaa27402014-01-23 11:56:17 -0800573 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800574 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800575 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800576 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800577 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700578 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800579 continue;
580
Don Garrette410e0f2011-11-10 15:39:01 -0800581 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800582 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700583
584 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700585 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700586 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800587 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700588
Gilad Arnoldfe133932014-01-14 12:25:50 -0800589 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800590 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700591
Sen Jiang57f91802017-11-14 17:42:13 -0800592 block_size_ = manifest_.block_size();
593
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700594 // This populates |partitions_| and the |install_plan.partitions| with the
595 // list of partitions from the manifest.
596 if (!ParseManifestPartitions(error))
597 return false;
598
Sen Jiang5ae865b2017-04-18 14:24:40 -0700599 // |install_plan.partitions| was filled in, nothing need to be done here if
600 // the payload was already applied, returns false to terminate http fetcher,
601 // but keep |error| as ErrorCode::kSuccess.
602 if (payload_->already_applied)
603 return false;
604
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700605 num_total_operations_ = 0;
606 for (const auto& partition : partitions_) {
607 num_total_operations_ += partition.operations_size();
608 acc_num_operations_.push_back(num_total_operations_);
609 }
610
Amin Hassani008c4582019-01-13 16:22:47 -0800611 LOG_IF(WARNING,
612 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700613 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800614 LOG_IF(WARNING,
615 !prefs_->SetInt64(kPrefsManifestSignatureSize,
616 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800617 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700618
Darin Petkov9b230572010-10-08 10:20:09 -0700619 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700620 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700621 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800622 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700623 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800624
Yifan Hong537802d2018-08-15 13:15:42 -0700625 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
626 if (!OpenCurrentPartition()) {
627 *error = ErrorCode::kInstallDeviceOpenError;
628 return false;
629 }
Allie Woodfdf00512015-03-02 13:34:55 -0800630 }
631
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800632 if (next_operation_num_ > 0)
633 UpdateOverallProgress(true, "Resuming after ");
634 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800636
637 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700638 // Check if we should cancel the current attempt for any reason.
639 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700640 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300641 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700642 return false;
643
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700644 // We know there are more operations to perform because we didn't reach the
645 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700646 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700647 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700648 // Skip until there are operations for current_partition_.
649 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
650 current_partition_++;
651 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700652 if (!OpenCurrentPartition()) {
653 *error = ErrorCode::kInstallDeviceOpenError;
654 return false;
655 }
656 }
Amin Hassani008c4582019-01-13 16:22:47 -0800657 const size_t partition_operation_num =
658 next_operation_num_ -
659 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700660
Alex Deymoa12ee112015-08-12 22:19:32 -0700661 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700662 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800663
664 CopyDataToBuffer(&c_bytes, &count, op.data_length());
665
666 // Check whether we received all of the next operation's data payload.
667 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700668 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700669
Jay Srinivasanf4318702012-09-24 11:56:24 -0700670 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700671 // Otherwise, keep the old behavior. This serves as a knob to disable
672 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800673 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
674 // we would have already failed in ParsePayloadMetadata method and thus not
675 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800676 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700677 // Note: Validate must be called only if CanPerformInstallOperation is
678 // called. Otherwise, we might be failing operations before even if there
679 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800680 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700681 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800682 if (install_plan_->hash_checks_mandatory) {
683 LOG(ERROR) << "Mandatory operation hash check failed";
684 return false;
685 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700686
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800687 // For non-mandatory cases, just send a UMA stat.
688 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700689 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700690 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700691 }
692
Darin Petkov45580e42010-10-08 14:02:40 -0700693 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700694 ScopedTerminatorExitUnblocker exit_unblocker =
695 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800696
Lann Martin39f57142017-07-14 09:18:42 -0600697 base::TimeTicks op_start_time = base::TimeTicks::Now();
698
Gilad Arnoldfe133932014-01-14 12:25:50 -0800699 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700700 switch (op.type()) {
701 case InstallOperation::REPLACE:
702 case InstallOperation::REPLACE_BZ:
703 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700704 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600705 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700706 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700707 case InstallOperation::ZERO:
708 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700709 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600710 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700711 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700712 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700713 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600714 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700715 break;
716 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800717 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700718 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600719 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700720 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700721 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700722 op_result = PerformPuffDiffOperation(op, error);
723 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800724 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700725 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700726 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700727 }
728 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800729 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800730
Amin Hassani5192fe52017-08-28 10:28:46 -0700731 if (!target_fd_->Flush()) {
732 return false;
733 }
734
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700735 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800736 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800737 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700738 }
Sen Jiangf6813802015-11-03 21:27:29 -0800739
740 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800741 // If we already extracted the signature we should skip this step.
Amin Hassani822d4852020-03-10 01:50:42 +0000742 if (manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
Alex Deymof25eb492016-02-26 00:20:08 -0800743 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800744 if (manifest_.signatures_offset() != buffer_offset_) {
745 LOG(ERROR) << "Payload signatures offset points to blob offset "
746 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800747 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800748 *error = ErrorCode::kDownloadPayloadVerificationError;
749 return false;
750 }
751 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
752 // Needs more data to cover entire signature.
753 if (buffer_.size() < manifest_.signatures_size())
754 return true;
755 if (!ExtractSignatureMessage()) {
756 LOG(ERROR) << "Extract payload signature failed.";
757 *error = ErrorCode::kDownloadPayloadVerificationError;
758 return false;
759 }
760 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800761 // Since we extracted the SignatureMessage we need to advance the
762 // checkpoint, otherwise we would reload the signature and try to extract
763 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800764 // This is the last checkpoint for an update, force this checkpoint to be
765 // saved.
766 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800767 }
768
Don Garrette410e0f2011-11-10 15:39:01 -0800769 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700770}
771
David Zeuthen8f191b22013-08-06 12:27:50 -0700772bool DeltaPerformer::IsManifestValid() {
773 return manifest_valid_;
774}
775
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700776bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
Amin Hassani822d4852020-03-10 01:50:42 +0000777 partitions_.clear();
778 for (const PartitionUpdate& partition : manifest_.partitions()) {
779 partitions_.push_back(partition);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700780 }
781
Tianjied3865d12020-06-03 15:25:17 -0700782 // For VAB and partial updates, the partition preparation will copy the
783 // dynamic partitions metadata to the target metadata slot, and rename the
784 // slot suffix of the partitions in the metadata.
785 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
786 uint64_t required_size = 0;
787 if (!PreparePartitionsForUpdate(&required_size)) {
788 if (required_size > 0) {
789 *error = ErrorCode::kNotEnoughSpace;
790 } else {
791 *error = ErrorCode::kInstallDeviceOpenError;
792 }
793 return false;
794 }
795 }
796
Tianjie55abd3c2020-06-19 00:22:59 -0700797 // Partitions in manifest are no longer needed after preparing partitions.
Amin Hassani822d4852020-03-10 01:50:42 +0000798 manifest_.clear_partitions();
Tianjied3865d12020-06-03 15:25:17 -0700799 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
800 // partition.
801 if (manifest_.partial_update()) {
802 std::set<std::string> touched_partitions;
803 for (const auto& partition_update : partitions_) {
804 touched_partitions.insert(partition_update.partition_name());
805 }
806
Tianjie99d570d2020-06-04 14:57:19 -0700807 auto generator = partition_update_generator::Create(boot_control_,
808 manifest_.block_size());
Tianjie24f96092020-06-30 12:26:25 -0700809 std::vector<PartitionUpdate> untouched_static_partitions;
Tianjied3865d12020-06-03 15:25:17 -0700810 TEST_AND_RETURN_FALSE(
811 generator->GenerateOperationsForPartitionsNotInPayload(
812 install_plan_->source_slot,
813 install_plan_->target_slot,
814 touched_partitions,
Tianjie24f96092020-06-30 12:26:25 -0700815 &untouched_static_partitions));
816 partitions_.insert(partitions_.end(),
817 untouched_static_partitions.begin(),
818 untouched_static_partitions.end());
819
820 // Save the untouched dynamic partitions in install plan.
821 std::vector<std::string> dynamic_partitions;
822 if (!boot_control_->GetDynamicPartitionControl()
823 ->ListDynamicPartitionsForSlot(install_plan_->source_slot,
824 &dynamic_partitions)) {
825 LOG(ERROR) << "Failed to load dynamic partitions from slot "
826 << install_plan_->source_slot;
827 return false;
828 }
829 install_plan_->untouched_dynamic_partitions.clear();
830 for (const auto& name : dynamic_partitions) {
831 if (touched_partitions.find(name) == touched_partitions.end()) {
832 install_plan_->untouched_dynamic_partitions.push_back(name);
833 }
834 }
Tianjied3865d12020-06-03 15:25:17 -0700835 }
836
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700837 // Fill in the InstallPlan::partitions based on the partitions from the
838 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700839 for (const auto& partition : partitions_) {
840 InstallPlan::Partition install_part;
841 install_part.name = partition.partition_name();
842 install_part.run_postinstall =
843 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800844 if (install_part.run_postinstall) {
845 install_part.postinstall_path =
846 (partition.has_postinstall_path() ? partition.postinstall_path()
847 : kPostinstallDefaultScript);
848 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700849 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800850 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700851
852 if (partition.has_old_partition_info()) {
853 const PartitionInfo& info = partition.old_partition_info();
854 install_part.source_size = info.size();
855 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
856 }
857
858 if (!partition.has_new_partition_info()) {
859 LOG(ERROR) << "Unable to get new partition hash info on partition "
860 << install_part.name << ".";
861 *error = ErrorCode::kDownloadNewPartitionInfoError;
862 return false;
863 }
864 const PartitionInfo& info = partition.new_partition_info();
865 install_part.target_size = info.size();
866 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
867
Sen Jiang57f91802017-11-14 17:42:13 -0800868 install_part.block_size = block_size_;
869 if (partition.has_hash_tree_extent()) {
870 Extent extent = partition.hash_tree_data_extent();
871 install_part.hash_tree_data_offset = extent.start_block() * block_size_;
872 install_part.hash_tree_data_size = extent.num_blocks() * block_size_;
873 extent = partition.hash_tree_extent();
874 install_part.hash_tree_offset = extent.start_block() * block_size_;
875 install_part.hash_tree_size = extent.num_blocks() * block_size_;
876 uint64_t hash_tree_data_end =
877 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
878 if (install_part.hash_tree_offset < hash_tree_data_end) {
879 LOG(ERROR) << "Invalid hash tree extents, hash tree data ends at "
880 << hash_tree_data_end << ", but hash tree starts at "
881 << install_part.hash_tree_offset;
882 *error = ErrorCode::kDownloadNewPartitionInfoError;
883 return false;
884 }
885 install_part.hash_tree_algorithm = partition.hash_tree_algorithm();
886 install_part.hash_tree_salt.assign(partition.hash_tree_salt().begin(),
887 partition.hash_tree_salt().end());
888 }
889 if (partition.has_fec_extent()) {
890 Extent extent = partition.fec_data_extent();
891 install_part.fec_data_offset = extent.start_block() * block_size_;
892 install_part.fec_data_size = extent.num_blocks() * block_size_;
893 extent = partition.fec_extent();
894 install_part.fec_offset = extent.start_block() * block_size_;
895 install_part.fec_size = extent.num_blocks() * block_size_;
896 uint64_t fec_data_end =
897 install_part.fec_data_offset + install_part.fec_data_size;
898 if (install_part.fec_offset < fec_data_end) {
899 LOG(ERROR) << "Invalid fec extents, fec data ends at " << fec_data_end
900 << ", but fec starts at " << install_part.fec_offset;
901 *error = ErrorCode::kDownloadNewPartitionInfoError;
902 return false;
903 }
904 install_part.fec_roots = partition.fec_roots();
905 }
906
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700907 install_plan_->partitions.push_back(install_part);
908 }
909
Tianjied3865d12020-06-03 15:25:17 -0700910 // TODO(xunchang) only need to load the partitions for those in payload.
911 // Because we have already loaded the other once when generating SOURCE_COPY
912 // operations.
Alex Deymo542c19b2015-12-03 07:43:31 -0300913 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700914 LOG(ERROR) << "Unable to determine all the partition devices.";
915 *error = ErrorCode::kInstallDeviceOpenError;
916 return false;
917 }
918 LogPartitionInfo(partitions_);
919 return true;
920}
921
Yifan Hongb9d63572020-01-09 17:50:46 -0800922bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
923 // Call static PreparePartitionsForUpdate with hash from
924 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
925 // preallocated for is the same as the hash of payload being applied.
926 string update_check_response_hash;
927 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
928 &update_check_response_hash));
929 return PreparePartitionsForUpdate(prefs_,
930 boot_control_,
931 install_plan_->target_slot,
932 manifest_,
933 update_check_response_hash,
934 required_size);
935}
936
937bool DeltaPerformer::PreparePartitionsForUpdate(
938 PrefsInterface* prefs,
939 BootControlInterface* boot_control,
940 BootControlInterface::Slot target_slot,
941 const DeltaArchiveManifest& manifest,
942 const std::string& update_check_response_hash,
943 uint64_t* required_size) {
944 string last_hash;
945 ignore_result(
946 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
947
948 bool is_resume = !update_check_response_hash.empty() &&
949 last_hash == update_check_response_hash;
950
951 if (is_resume) {
952 LOG(INFO) << "Using previously prepared partitions for update. hash = "
953 << last_hash;
954 } else {
955 LOG(INFO) << "Preparing partitions for new update. last hash = "
956 << last_hash << ", new hash = " << update_check_response_hash;
957 }
958
959 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
960 boot_control->GetCurrentSlot(),
961 target_slot,
962 manifest,
963 !is_resume /* should update */,
964 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700965 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -0800966 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700967 return false;
968 }
Yifan Hongb9d63572020-01-09 17:50:46 -0800969
970 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
971 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -0700972 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700973
974 return true;
975}
976
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700977bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700978 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700979 // If we don't have a data blob we can apply it right away.
980 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700981 return true;
982
983 // See if we have the entire data blob in the buffer
984 if (operation.data_offset() < buffer_offset_) {
985 LOG(ERROR) << "we threw away data it seems?";
986 return false;
987 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700988
Gilad Arnoldfe133932014-01-14 12:25:50 -0800989 return (operation.data_offset() + operation.data_length() <=
990 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700991}
992
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700993bool DeltaPerformer::PerformReplaceOperation(
994 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700995 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700996 operation.type() == InstallOperation::REPLACE_BZ ||
997 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700998
999 // Since we delete data off the beginning of the buffer as we use it,
1000 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001001 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1002 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001003
Alex Deymo05322872015-09-30 09:50:24 -07001004 // Setup the ExtentWriter stack based on the operation type.
Sen Jiang5e1af982018-11-01 15:01:45 -07001005 std::unique_ptr<ExtentWriter> writer = std::make_unique<DirectExtentWriter>();
Darin Petkovd7061ab2010-10-06 14:37:09 -07001006
Alex Deymo2d621a32015-10-01 11:09:01 -07001007 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -07001008 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -07001009 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
1010 writer.reset(new XzExtentWriter(std::move(writer)));
1011 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001012
Amin Hassanicd7edbe2017-09-18 17:05:02 -07001013 TEST_AND_RETURN_FALSE(
1014 writer->Init(target_fd_, operation.dst_extents(), block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001015 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Darin Petkovd7061ab2010-10-06 14:37:09 -07001016
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001017 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -08001018 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001019 return true;
1020}
1021
Alex Deymo79715ad2015-10-02 14:27:53 -07001022bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001023 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001024 CHECK(operation.type() == InstallOperation::DISCARD ||
1025 operation.type() == InstallOperation::ZERO);
1026
1027 // These operations have no blob.
1028 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
1029 TEST_AND_RETURN_FALSE(!operation.has_data_length());
1030
Alex Deymo05e0e382015-12-07 20:18:16 -08001031#ifdef BLKZEROOUT
1032 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -07001033 int request =
1034 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Amin Hassani008c4582019-01-13 16:22:47 -08001035#else // !defined(BLKZEROOUT)
Alex Deymo05e0e382015-12-07 20:18:16 -08001036 bool attempt_ioctl = false;
1037 int request = 0;
1038#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -07001039
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001040 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001041 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001042 const uint64_t start = extent.start_block() * block_size_;
1043 const uint64_t length = extent.num_blocks() * block_size_;
1044 if (attempt_ioctl) {
1045 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001046 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -07001047 continue;
1048 attempt_ioctl = false;
Alex Deymo79715ad2015-10-02 14:27:53 -07001049 }
1050 // In case of failure, we fall back to writing 0 to the selected region.
Tianjie Xu06bbe492018-01-12 12:37:48 -08001051 zeros.resize(16 * block_size_);
Alex Deymo79715ad2015-10-02 14:27:53 -07001052 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Amin Hassani008c4582019-01-13 16:22:47 -08001053 uint64_t chunk_length =
1054 min(length - offset, static_cast<uint64_t>(zeros.size()));
Amin Hassanid87304c2017-08-29 11:40:03 -07001055 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1056 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -07001057 }
1058 }
1059 return true;
1060}
1061
Sen Jiang8371c1c2018-02-01 13:46:39 -08001062bool DeltaPerformer::ValidateSourceHash(const brillo::Blob& calculated_hash,
1063 const InstallOperation& operation,
1064 const FileDescriptorPtr source_fd,
1065 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001066 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1067 operation.src_sha256_hash().end());
1068 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001069 LOG(ERROR) << "The hash of the source data on disk for this operation "
1070 << "doesn't match the expected value. This could mean that the "
1071 << "delta update payload was targeted for another version, or "
1072 << "that the source partition was modified after it was "
1073 << "installed, for example, by mounting a filesystem.";
1074 LOG(ERROR) << "Expected: sha256|hex = "
1075 << base::HexEncode(expected_source_hash.data(),
1076 expected_source_hash.size());
1077 LOG(ERROR) << "Calculated: sha256|hex = "
1078 << base::HexEncode(calculated_hash.data(),
1079 calculated_hash.size());
1080
1081 vector<string> source_extents;
1082 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001083 source_extents.push_back(
1084 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1085 static_cast<uint64_t>(ext.start_block()),
1086 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001087 }
1088 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1089 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001090
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001091 // Log remount history if this device is an ext4 partition.
1092 LogMountHistory(source_fd);
1093
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001094 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001095 return false;
1096 }
1097 return true;
1098}
1099
Allie Wood9f6f0a52015-03-30 11:25:47 -07001100bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001101 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001102 if (operation.has_src_length())
1103 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1104 if (operation.has_dst_length())
1105 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1106
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001107 TEST_AND_RETURN_FALSE(source_fd_ != nullptr);
1108
Alessio Balsini8d384312019-11-26 11:46:33 +00001109 // The device may optimize the SOURCE_COPY operation.
1110 // Being this a device-specific optimization let DynamicPartitionController
1111 // decide it the operation should be skipped.
Yifan Hong6eec9952019-12-04 13:12:01 -08001112 const PartitionUpdate& partition = partitions_[current_partition_];
Alessio Balsini8d384312019-11-26 11:46:33 +00001113 const auto& partition_control = boot_control_->GetDynamicPartitionControl();
Yifan Hongf5261562020-03-10 10:28:10 -07001114
1115 InstallOperation buf;
1116 bool should_optimize = partition_control->OptimizeOperation(
1117 partition.partition_name(), operation, &buf);
1118 const InstallOperation& optimized = should_optimize ? buf : operation;
Alessio Balsini8d384312019-11-26 11:46:33 +00001119
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001120 if (operation.has_src_sha256_hash()) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001121 bool read_ok;
Alex Deymo51c264e2016-11-04 15:49:53 -07001122 brillo::Blob source_hash;
1123 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1124 operation.src_sha256_hash().end());
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001125
Alex Deymo51c264e2016-11-04 15:49:53 -07001126 // We fall back to use the error corrected device if the hash of the raw
1127 // device doesn't match or there was an error reading the source partition.
1128 // Note that this code will also fall back if writing the target partition
1129 // fails.
Yifan Hongf5261562020-03-10 10:28:10 -07001130 if (should_optimize) {
1131 // Hash operation.src_extents(), then copy optimized.src_extents to
1132 // optimized.dst_extents.
1133 read_ok =
1134 fd_utils::ReadAndHashExtents(
1135 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1136 fd_utils::CopyAndHashExtents(source_fd_,
1137 optimized.src_extents(),
1138 target_fd_,
1139 optimized.dst_extents(),
1140 block_size_,
1141 nullptr /* skip hashing */);
Alessio Balsini8d384312019-11-26 11:46:33 +00001142 } else {
1143 read_ok = fd_utils::CopyAndHashExtents(source_fd_,
1144 operation.src_extents(),
1145 target_fd_,
1146 operation.dst_extents(),
1147 block_size_,
1148 &source_hash);
1149 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001150 if (read_ok && expected_source_hash == source_hash)
1151 return true;
1152
1153 if (!OpenCurrentECCPartition()) {
1154 // The following function call will return false since the source hash
1155 // mismatches, but we still want to call it so it prints the appropriate
1156 // log message.
1157 return ValidateSourceHash(source_hash, operation, source_fd_, error);
1158 }
1159
1160 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1161 << base::HexEncode(source_hash.data(), source_hash.size())
1162 << ", expected "
1163 << base::HexEncode(expected_source_hash.data(),
1164 expected_source_hash.size());
1165
Yifan Hongf5261562020-03-10 10:28:10 -07001166 if (should_optimize) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001167 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
1168 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash));
Yifan Hongf5261562020-03-10 10:28:10 -07001169 TEST_AND_RETURN_FALSE(
1170 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1171 optimized.src_extents(),
1172 target_fd_,
1173 optimized.dst_extents(),
1174 block_size_,
1175 nullptr /* skip hashing */));
Alessio Balsini8d384312019-11-26 11:46:33 +00001176 } else {
1177 TEST_AND_RETURN_FALSE(
1178 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1179 operation.src_extents(),
1180 target_fd_,
1181 operation.dst_extents(),
1182 block_size_,
1183 &source_hash));
1184 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001185 TEST_AND_RETURN_FALSE(
1186 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error));
1187 // At this point reading from the the error corrected device worked, but
1188 // reading from the raw device failed, so this is considered a recovered
1189 // failure.
1190 source_ecc_recovered_failures_++;
1191 } else {
1192 // When the operation doesn't include a source hash, we attempt the error
1193 // corrected device first since we can't verify the block in the raw device
1194 // at this point, but we fall back to the raw device since the error
1195 // corrected device can be shorter or not available.
Alessio Balsini8d384312019-11-26 11:46:33 +00001196
Alex Deymo51c264e2016-11-04 15:49:53 -07001197 if (OpenCurrentECCPartition() &&
1198 fd_utils::CopyAndHashExtents(source_ecc_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001199 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001200 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001201 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001202 block_size_,
1203 nullptr)) {
1204 return true;
1205 }
1206 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001207 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001208 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001209 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001210 block_size_,
1211 nullptr));
1212 }
Allie Wood9f6f0a52015-03-30 11:25:47 -07001213 return true;
1214}
1215
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001216FileDescriptorPtr DeltaPerformer::ChooseSourceFD(
1217 const InstallOperation& operation, ErrorCode* error) {
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001218 if (source_fd_ == nullptr) {
1219 LOG(ERROR) << "ChooseSourceFD fail: source_fd_ == nullptr";
1220 return nullptr;
1221 }
1222
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001223 if (!operation.has_src_sha256_hash()) {
1224 // When the operation doesn't include a source hash, we attempt the error
1225 // corrected device first since we can't verify the block in the raw device
1226 // at this point, but we first need to make sure all extents are readable
1227 // since the error corrected device can be shorter or not available.
1228 if (OpenCurrentECCPartition() &&
1229 fd_utils::ReadAndHashExtents(
1230 source_ecc_fd_, operation.src_extents(), block_size_, nullptr)) {
1231 return source_ecc_fd_;
1232 }
1233 return source_fd_;
1234 }
1235
1236 brillo::Blob source_hash;
1237 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1238 operation.src_sha256_hash().end());
1239 if (fd_utils::ReadAndHashExtents(
1240 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1241 source_hash == expected_source_hash) {
1242 return source_fd_;
1243 }
1244 // We fall back to use the error corrected device if the hash of the raw
1245 // device doesn't match or there was an error reading the source partition.
1246 if (!OpenCurrentECCPartition()) {
1247 // The following function call will return false since the source hash
1248 // mismatches, but we still want to call it so it prints the appropriate
1249 // log message.
1250 ValidateSourceHash(source_hash, operation, source_fd_, error);
1251 return nullptr;
1252 }
1253 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1254 << base::HexEncode(source_hash.data(), source_hash.size())
1255 << ", expected "
1256 << base::HexEncode(expected_source_hash.data(),
1257 expected_source_hash.size());
1258
1259 if (fd_utils::ReadAndHashExtents(
1260 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash) &&
1261 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error)) {
1262 // At this point reading from the the error corrected device worked, but
1263 // reading from the raw device failed, so this is considered a recovered
1264 // failure.
1265 source_ecc_recovered_failures_++;
1266 return source_ecc_fd_;
1267 }
1268 return nullptr;
1269}
1270
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001271bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1272 const RepeatedPtrField<Extent>& extents,
1273 uint64_t block_size,
1274 uint64_t full_length,
1275 string* positions_string) {
1276 string ret;
1277 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001278 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001279 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001280 uint64_t this_length =
1281 min(full_length - length,
1282 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001283 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001284 length += this_length;
1285 }
1286 TEST_AND_RETURN_FALSE(length == full_length);
1287 if (!ret.empty())
1288 ret.resize(ret.size() - 1); // Strip trailing comma off
1289 *positions_string = ret;
1290 return true;
1291}
1292
Amin Hassanid9cb2902017-09-20 12:11:39 -07001293namespace {
1294
1295class BsdiffExtentFile : public bsdiff::FileInterface {
1296 public:
1297 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader, size_t size)
1298 : BsdiffExtentFile(std::move(reader), nullptr, size) {}
1299 BsdiffExtentFile(std::unique_ptr<ExtentWriter> writer, size_t size)
1300 : BsdiffExtentFile(nullptr, std::move(writer), size) {}
1301
1302 ~BsdiffExtentFile() override = default;
1303
1304 bool Read(void* buf, size_t count, size_t* bytes_read) override {
1305 TEST_AND_RETURN_FALSE(reader_->Read(buf, count));
1306 *bytes_read = count;
1307 offset_ += count;
1308 return true;
1309 }
1310
1311 bool Write(const void* buf, size_t count, size_t* bytes_written) override {
1312 TEST_AND_RETURN_FALSE(writer_->Write(buf, count));
1313 *bytes_written = count;
1314 offset_ += count;
1315 return true;
1316 }
1317
1318 bool Seek(off_t pos) override {
1319 if (reader_ != nullptr) {
1320 TEST_AND_RETURN_FALSE(reader_->Seek(pos));
1321 offset_ = pos;
1322 } else {
1323 // For writes technically there should be no change of position, or it
1324 // should be equivalent of current offset.
1325 TEST_AND_RETURN_FALSE(offset_ == static_cast<uint64_t>(pos));
1326 }
1327 return true;
1328 }
1329
Sen Jiang5e1af982018-11-01 15:01:45 -07001330 bool Close() override { return true; }
Amin Hassanid9cb2902017-09-20 12:11:39 -07001331
1332 bool GetSize(uint64_t* size) override {
1333 *size = size_;
1334 return true;
1335 }
1336
1337 private:
1338 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader,
1339 std::unique_ptr<ExtentWriter> writer,
1340 size_t size)
1341 : reader_(std::move(reader)),
1342 writer_(std::move(writer)),
1343 size_(size),
1344 offset_(0) {}
1345
1346 std::unique_ptr<ExtentReader> reader_;
1347 std::unique_ptr<ExtentWriter> writer_;
1348 uint64_t size_;
1349 uint64_t offset_;
1350
1351 DISALLOW_COPY_AND_ASSIGN(BsdiffExtentFile);
1352};
1353
1354} // namespace
1355
Allie Wood9f6f0a52015-03-30 11:25:47 -07001356bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001357 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001358 // Since we delete data off the beginning of the buffer as we use it,
1359 // the data we need should be exactly at the beginning of the buffer.
1360 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1361 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1362 if (operation.has_src_length())
1363 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1364 if (operation.has_dst_length())
1365 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1366
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001367 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1368 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001369
Amin Hassanid9cb2902017-09-20 12:11:39 -07001370 auto reader = std::make_unique<DirectExtentReader>();
1371 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001372 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassanid9cb2902017-09-20 12:11:39 -07001373 auto src_file = std::make_unique<BsdiffExtentFile>(
1374 std::move(reader),
1375 utils::BlocksInExtents(operation.src_extents()) * block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001376
Amin Hassanid9cb2902017-09-20 12:11:39 -07001377 auto writer = std::make_unique<DirectExtentWriter>();
1378 TEST_AND_RETURN_FALSE(
1379 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1380 auto dst_file = std::make_unique<BsdiffExtentFile>(
1381 std::move(writer),
1382 utils::BlocksInExtents(operation.dst_extents()) * block_size_);
1383
1384 TEST_AND_RETURN_FALSE(bsdiff::bspatch(std::move(src_file),
1385 std::move(dst_file),
Sen Jiang7a659092016-05-10 15:31:46 -07001386 buffer_.data(),
Amin Hassanid9cb2902017-09-20 12:11:39 -07001387 buffer_.size()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001388 DiscardBuffer(true, buffer_.size());
1389 return true;
1390}
1391
Amin Hassani02855c22017-09-06 22:34:50 -07001392namespace {
1393
1394// A class to be passed to |puffpatch| for reading from |source_fd_| and writing
1395// into |target_fd_|.
1396class PuffinExtentStream : public puffin::StreamInterface {
1397 public:
1398 // Constructor for creating a stream for reading from an |ExtentReader|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001399 PuffinExtentStream(std::unique_ptr<ExtentReader> reader, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001400 : PuffinExtentStream(std::move(reader), nullptr, size) {}
1401
1402 // Constructor for creating a stream for writing to an |ExtentWriter|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001403 PuffinExtentStream(std::unique_ptr<ExtentWriter> writer, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001404 : PuffinExtentStream(nullptr, std::move(writer), size) {}
1405
1406 ~PuffinExtentStream() override = default;
1407
Amin Hassani678a68f2018-02-28 11:54:47 -08001408 bool GetSize(uint64_t* size) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001409 *size = size_;
1410 return true;
1411 }
1412
Amin Hassani678a68f2018-02-28 11:54:47 -08001413 bool GetOffset(uint64_t* offset) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001414 *offset = offset_;
1415 return true;
1416 }
1417
Amin Hassani678a68f2018-02-28 11:54:47 -08001418 bool Seek(uint64_t offset) override {
Amin Hassani02855c22017-09-06 22:34:50 -07001419 if (is_read_) {
1420 TEST_AND_RETURN_FALSE(reader_->Seek(offset));
1421 offset_ = offset;
1422 } else {
1423 // For writes technically there should be no change of position, or it
1424 // should equivalent of current offset.
1425 TEST_AND_RETURN_FALSE(offset_ == offset);
1426 }
1427 return true;
1428 }
1429
1430 bool Read(void* buffer, size_t count) override {
1431 TEST_AND_RETURN_FALSE(is_read_);
1432 TEST_AND_RETURN_FALSE(reader_->Read(buffer, count));
1433 offset_ += count;
1434 return true;
1435 }
1436
1437 bool Write(const void* buffer, size_t count) override {
1438 TEST_AND_RETURN_FALSE(!is_read_);
1439 TEST_AND_RETURN_FALSE(writer_->Write(buffer, count));
1440 offset_ += count;
1441 return true;
1442 }
1443
Sen Jiang5e1af982018-11-01 15:01:45 -07001444 bool Close() override { return true; }
Amin Hassani02855c22017-09-06 22:34:50 -07001445
1446 private:
1447 PuffinExtentStream(std::unique_ptr<ExtentReader> reader,
1448 std::unique_ptr<ExtentWriter> writer,
Amin Hassani678a68f2018-02-28 11:54:47 -08001449 uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001450 : reader_(std::move(reader)),
1451 writer_(std::move(writer)),
1452 size_(size),
1453 offset_(0),
1454 is_read_(reader_ ? true : false) {}
1455
1456 std::unique_ptr<ExtentReader> reader_;
1457 std::unique_ptr<ExtentWriter> writer_;
1458 uint64_t size_;
1459 uint64_t offset_;
1460 bool is_read_;
1461
1462 DISALLOW_COPY_AND_ASSIGN(PuffinExtentStream);
1463};
1464
1465} // namespace
1466
1467bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
1468 ErrorCode* error) {
1469 // Since we delete data off the beginning of the buffer as we use it,
1470 // the data we need should be exactly at the beginning of the buffer.
1471 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1472 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1473
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001474 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1475 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Amin Hassani02855c22017-09-06 22:34:50 -07001476
1477 auto reader = std::make_unique<DirectExtentReader>();
1478 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001479 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassani02855c22017-09-06 22:34:50 -07001480 puffin::UniqueStreamPtr src_stream(new PuffinExtentStream(
1481 std::move(reader),
1482 utils::BlocksInExtents(operation.src_extents()) * block_size_));
1483
1484 auto writer = std::make_unique<DirectExtentWriter>();
1485 TEST_AND_RETURN_FALSE(
1486 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1487 puffin::UniqueStreamPtr dst_stream(new PuffinExtentStream(
1488 std::move(writer),
1489 utils::BlocksInExtents(operation.dst_extents()) * block_size_));
1490
1491 const size_t kMaxCacheSize = 5 * 1024 * 1024; // Total 5MB cache.
1492 TEST_AND_RETURN_FALSE(puffin::PuffPatch(std::move(src_stream),
1493 std::move(dst_stream),
1494 buffer_.data(),
1495 buffer_.size(),
1496 kMaxCacheSize));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001497 DiscardBuffer(true, buffer_.size());
Alex Deymoa12ee112015-08-12 22:19:32 -07001498 return true;
1499}
Darin Petkovd7061ab2010-10-06 14:37:09 -07001500
Sen Jiangf6813802015-11-03 21:27:29 -08001501bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001502 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1503 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1504 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001505 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -08001506 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001507
1508 // Save the signature blob because if the update is interrupted after the
1509 // download phase we don't go through this path anymore. Some alternatives to
1510 // consider:
1511 //
1512 // 1. On resume, re-download the signature blob from the server and re-verify
1513 // it.
1514 //
1515 // 2. Verify the signature as soon as it's received and don't checkpoint the
1516 // blob and the signed sha-256 context.
Amin Hassani008c4582019-01-13 16:22:47 -08001517 LOG_IF(WARNING,
1518 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Sen Jiang9b2f1782019-01-24 14:27:50 -08001519 signatures_message_data_))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001520 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001521
Darin Petkovd7061ab2010-10-06 14:37:09 -07001522 LOG(INFO) << "Extracted signature data of size "
1523 << manifest_.signatures_size() << " at "
1524 << manifest_.signatures_offset();
1525 return true;
1526}
1527
Sen Jiang08c6da12019-01-07 18:28:56 -08001528bool DeltaPerformer::GetPublicKey(string* out_public_key) {
1529 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -07001530
Sen Jiang08c6da12019-01-07 18:28:56 -08001531 if (utils::FileExists(public_key_path_.c_str())) {
1532 LOG(INFO) << "Verifying using public key: " << public_key_path_;
1533 return utils::ReadFile(public_key_path_, out_public_key);
1534 }
1535
1536 // If this is an official build then we are not allowed to use public key from
1537 // Omaha response.
1538 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
1539 LOG(INFO) << "Verifying using public key from Omaha response.";
1540 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1541 out_public_key);
1542 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001543 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001544 return true;
1545}
1546
Tianjie Xu7a78d632019-10-08 16:32:39 -07001547std::pair<std::unique_ptr<PayloadVerifier>, bool>
1548DeltaPerformer::CreatePayloadVerifier() {
1549 if (utils::FileExists(update_certificates_path_.c_str())) {
1550 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1551 return {
1552 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1553 true};
1554 }
1555
1556 string public_key;
1557 if (!GetPublicKey(&public_key)) {
1558 LOG(ERROR) << "Failed to read public key";
1559 return {nullptr, true};
1560 }
1561
1562 // Skips the verification if the public key is empty.
1563 if (public_key.empty()) {
1564 return {nullptr, false};
1565 }
1566 return {PayloadVerifier::CreateInstance(public_key), true};
1567}
1568
Gilad Arnold21504f02013-05-24 08:51:22 -07001569ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001570 // Perform assorted checks to sanity check the manifest, make sure it
1571 // matches data from other sources, and that it is a supported version.
Amin Hassani822d4852020-03-10 01:50:42 +00001572 bool has_old_fields = std::any_of(manifest_.partitions().begin(),
1573 manifest_.partitions().end(),
1574 [](const PartitionUpdate& partition) {
1575 return partition.has_old_partition_info();
1576 });
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001577
Alex Deymo64d98782016-02-05 18:03:48 -08001578 // The presence of an old partition hash is the sole indicator for a delta
1579 // update.
1580 InstallPayloadType actual_payload_type =
1581 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1582
Sen Jiangcdd52062017-05-18 15:33:10 -07001583 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001584 LOG(INFO) << "Detected a '"
1585 << InstallPayloadTypeToString(actual_payload_type)
1586 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001587 payload_->type = actual_payload_type;
1588 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001589 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001590 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001591 << "' payload but the downloaded manifest contains a '"
1592 << InstallPayloadTypeToString(actual_payload_type)
1593 << "' payload.";
1594 return ErrorCode::kPayloadMismatchedType;
1595 }
Alex Deymo64d98782016-02-05 18:03:48 -08001596 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001597 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001598 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001599 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1600 LOG(ERROR) << "Manifest contains minor version "
1601 << manifest_.minor_version()
1602 << ", but all full payloads should have version "
1603 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001604 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001605 }
1606 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001607 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1608 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001609 LOG(ERROR) << "Manifest contains minor version "
1610 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001611 << " not in the range of supported minor versions ["
1612 << kMinSupportedMinorPayloadVersion << ", "
1613 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001614 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001615 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001616 }
1617
Amin Hassani822d4852020-03-10 01:50:42 +00001618 if (manifest_.has_old_rootfs_info() || manifest_.has_new_rootfs_info() ||
1619 manifest_.has_old_kernel_info() || manifest_.has_new_kernel_info() ||
1620 manifest_.install_operations_size() != 0 ||
1621 manifest_.kernel_install_operations_size() != 0) {
1622 LOG(ERROR) << "Manifest contains deprecated fields.";
1623 return ErrorCode::kPayloadMismatchedType;
Sen Jiang3e728fe2015-11-05 11:37:23 -08001624 }
1625
Sen Jiang8e768e92017-06-28 17:13:19 -07001626 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1627 LOG(ERROR) << "The current OS build timestamp ("
1628 << hardware_->GetBuildTimestamp()
1629 << ") is newer than the maximum timestamp in the manifest ("
1630 << manifest_.max_timestamp() << ")";
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001631 if (!hardware_->AllowDowngrade()) {
1632 return ErrorCode::kPayloadTimestampError;
1633 }
1634 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1635 " the payload with an older timestamp.";
Sen Jiang8e768e92017-06-28 17:13:19 -07001636 }
1637
Amin Hassani55c75412019-10-07 11:20:39 -07001638 // TODO(crbug.com/37661) we should be adding more and more manifest checks,
1639 // such as partition boundaries, etc.
Gilad Arnold21504f02013-05-24 08:51:22 -07001640
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001641 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001642}
1643
David Zeuthena99981f2013-04-29 13:42:47 -07001644ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001645 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001646 if (!operation.data_sha256_hash().size()) {
1647 if (!operation.data_length()) {
1648 // Operations that do not have any data blob won't have any operation hash
1649 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001650 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001651 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001652 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001653 }
1654
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001655 // No hash is present for an operation that has data blobs. This shouldn't
1656 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001657 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001658 // hashes. So if it happens it means either we've turned operation hash
1659 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001660 // One caveat though: The last operation is a dummy signature operation
1661 // that doesn't have a hash at the time the manifest is created. So we
1662 // should not complaint about that operation. This operation can be
1663 // recognized by the fact that it's offset is mentioned in the manifest.
1664 if (manifest_.signatures_offset() &&
1665 manifest_.signatures_offset() == operation.data_offset()) {
1666 LOG(INFO) << "Skipping hash verification for signature operation "
1667 << next_operation_num_ + 1;
1668 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001669 if (install_plan_->hash_checks_mandatory) {
1670 LOG(ERROR) << "Missing mandatory operation hash for operation "
1671 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001672 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001673 }
1674
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001675 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1676 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001677 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001678 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001679 }
1680
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001681 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001682 expected_op_hash.assign(operation.data_sha256_hash().data(),
1683 (operation.data_sha256_hash().data() +
1684 operation.data_sha256_hash().size()));
1685
Sen Jiang2703ef42017-03-16 13:36:21 -07001686 brillo::Blob calculated_op_hash;
1687 if (!HashCalculator::RawHashOfBytes(
1688 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001689 LOG(ERROR) << "Unable to compute actual hash of operation "
1690 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001691 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001692 }
1693
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001694 if (calculated_op_hash != expected_op_hash) {
1695 LOG(ERROR) << "Hash verification failed for operation "
1696 << next_operation_num_ << ". Expected hash = ";
1697 utils::HexDumpVector(expected_op_hash);
1698 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1699 << " bytes at offset: " << operation.data_offset() << " = ";
1700 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001701 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001702 }
1703
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001704 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001705}
1706
Amin Hassani008c4582019-01-13 16:22:47 -08001707#define TEST_AND_RETURN_VAL(_retval, _condition) \
1708 do { \
1709 if (!(_condition)) { \
1710 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1711 return _retval; \
1712 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001713 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001714
David Zeuthena99981f2013-04-29 13:42:47 -07001715ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001716 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001717 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001718 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001719 if (update_check_response_size !=
1720 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1721 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1722 << ") doesn't match metadata_size (" << metadata_size_
1723 << ") + metadata_signature_size (" << metadata_signature_size_
1724 << ") + buffer_offset (" << buffer_offset_ << ").";
1725 return ErrorCode::kPayloadSizeMismatchError;
1726 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001727
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001728 // Verifies the payload hash.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001729 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Sen Jiang2703ef42017-03-16 13:36:21 -07001730 !payload_hash_calculator_.raw_hash().empty());
1731 TEST_AND_RETURN_VAL(
1732 ErrorCode::kPayloadHashMismatchError,
1733 payload_hash_calculator_.raw_hash() == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001734
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001735 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001736 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001737 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001738 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001739 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001740
Tianjie Xu7a78d632019-10-08 16:32:39 -07001741 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1742 if (!perform_verification) {
1743 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1744 return ErrorCode::kSuccess;
1745 }
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001746 if (!payload_verifier) {
Tianjie Xu7a78d632019-10-08 16:32:39 -07001747 LOG(ERROR) << "Failed to create the payload verifier.";
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001748 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1749 }
1750 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001751 // The autoupdate_CatchBadSignatures test checks for this string
1752 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001753 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001754 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001755 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001756
David Zeuthene7f89172013-10-31 10:21:04 -07001757 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001758 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001759}
1760
Sen Jiangf6813802015-11-03 21:27:29 -08001761void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1762 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001763 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001764 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001765 buffer_offset_ += buffer_.size();
1766
1767 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001768 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1769 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001770
1771 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001772 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001773}
1774
Darin Petkov0406e402010-10-06 21:33:11 -07001775bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001776 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001777 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001778 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Amin Hassani008c4582019-01-13 16:22:47 -08001779 next_operation != kUpdateStateOperationInvalid && next_operation > 0))
Alex Deymo3310b222015-03-30 15:59:07 -07001780 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001781
1782 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001783 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1784 !interrupted_hash.empty() &&
1785 interrupted_hash == update_check_response_hash))
1786 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001787
Darin Petkov61426142010-10-08 11:04:55 -07001788 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001789 // Note that storing this value is optional, but if it is there it should not
1790 // be more than the limit.
1791 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1792 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001793 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001794
Darin Petkov0406e402010-10-06 21:33:11 -07001795 // Sanity check the rest.
1796 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001797 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1798 next_data_offset >= 0))
1799 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001800
Darin Petkov437adc42010-10-07 13:12:24 -07001801 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001802 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1803 !sha256_context.empty()))
1804 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001805
1806 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001807 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1808 manifest_metadata_size > 0))
1809 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001810
Alex Deymof25eb492016-02-26 00:20:08 -08001811 int64_t manifest_signature_size = 0;
1812 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1813 &manifest_signature_size) &&
1814 manifest_signature_size >= 0))
1815 return false;
1816
Darin Petkov0406e402010-10-06 21:33:11 -07001817 return true;
1818}
1819
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001820bool DeltaPerformer::ResetUpdateProgress(
1821 PrefsInterface* prefs,
1822 bool quick,
1823 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07001824 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1825 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001826 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001827 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001828 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001829 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1830 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001831 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001832 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001833 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001834 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001835 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07001836 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08001837
1838 if (!skip_dynamic_partititon_metadata_updated) {
1839 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
1840 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
1841 }
Darin Petkov9b230572010-10-08 10:20:09 -07001842 }
Darin Petkov73058b42010-10-06 16:32:19 -07001843 return true;
1844}
1845
Sen Jiang3a25dc22019-01-10 14:14:41 -08001846bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
Sen Jiang53c2ec52019-01-10 15:27:59 -08001847 base::TimeTicks curr_time = base::TimeTicks::Now();
Sen Jiang3a25dc22019-01-10 14:14:41 -08001848 if (force || curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07001849 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
1850 } else {
1851 return false;
1852 }
1853
Darin Petkov9c0baf82010-10-07 13:44:48 -07001854 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001855 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001856 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001857 ResetUpdateProgress(prefs_, true);
Amin Hassani008c4582019-01-13 16:22:47 -08001858 TEST_AND_RETURN_FALSE(prefs_->SetString(
1859 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08001860 TEST_AND_RETURN_FALSE(
1861 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1862 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08001863 TEST_AND_RETURN_FALSE(
1864 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Darin Petkov0406e402010-10-06 21:33:11 -07001865 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001866
1867 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001868 size_t partition_index = current_partition_;
1869 while (next_operation_num_ >= acc_num_operations_[partition_index])
1870 partition_index++;
Amin Hassani008c4582019-01-13 16:22:47 -08001871 const size_t partition_operation_num =
1872 next_operation_num_ -
1873 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001874 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001875 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08001876 TEST_AND_RETURN_FALSE(
1877 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07001878 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08001879 TEST_AND_RETURN_FALSE(
1880 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07001881 }
Darin Petkov0406e402010-10-06 21:33:11 -07001882 }
Amin Hassani008c4582019-01-13 16:22:47 -08001883 TEST_AND_RETURN_FALSE(
1884 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07001885 return true;
1886}
1887
Darin Petkov9b230572010-10-08 10:20:09 -07001888bool DeltaPerformer::PrimeUpdateState() {
1889 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07001890
1891 int64_t next_operation = kUpdateStateOperationInvalid;
1892 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08001893 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07001894 // Initiating a new update, no more state needs to be initialized.
1895 return true;
1896 }
1897 next_operation_num_ = next_operation;
1898
1899 // Resuming an update -- load the rest of the update state.
1900 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08001901 TEST_AND_RETURN_FALSE(
1902 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1903 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001904 buffer_offset_ = next_data_offset;
1905
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001906 // The signed hash context and the signature blob may be empty if the
1907 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001908 string signed_hash_context;
1909 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1910 &signed_hash_context)) {
1911 TEST_AND_RETURN_FALSE(
1912 signed_hash_calculator_.SetContext(signed_hash_context));
1913 }
1914
Sen Jiang9b2f1782019-01-24 14:27:50 -08001915 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07001916
1917 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08001918 TEST_AND_RETURN_FALSE(
1919 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
1920 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001921
1922 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08001923 TEST_AND_RETURN_FALSE(
1924 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1925 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001926 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001927
Alex Deymof25eb492016-02-26 00:20:08 -08001928 int64_t manifest_signature_size = 0;
1929 TEST_AND_RETURN_FALSE(
1930 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1931 manifest_signature_size >= 0);
1932 metadata_signature_size_ = manifest_signature_size;
1933
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001934 // Advance the download progress to reflect what doesn't need to be
1935 // re-downloaded.
1936 total_bytes_received_ += buffer_offset_;
1937
Darin Petkov61426142010-10-08 11:04:55 -07001938 // Speculatively count the resume as a failure.
1939 int64_t resumed_update_failures;
1940 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1941 resumed_update_failures++;
1942 } else {
1943 resumed_update_failures = 1;
1944 }
1945 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001946 return true;
1947}
1948
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001949} // namespace chromeos_update_engine