blob: d9b739de16b3d5f7fcdb2a30351be859e238231a [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"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080060#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080061#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070062#endif // USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080063#include "update_engine/payload_consumer/payload_constants.h"
64#include "update_engine/payload_consumer/payload_verifier.h"
65#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066
Alex Deymo161c4a12014-05-16 15:56:21 -070067using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068using std::min;
69using std::string;
70using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070071
72namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080073const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
74const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
75const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
76const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070077const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080078
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070080const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070081const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080082#if USE_MTD
83const int kUbiVolumeAttachTimeout = 5 * 60;
84#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080085
Amin Hassania3fc20a2017-09-19 17:19:34 -070086const uint64_t kCacheSize = 1024 * 1024; // 1MB
87
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080088FileDescriptorPtr CreateFileDescriptor(const char* path) {
89 FileDescriptorPtr ret;
90#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080091 if (strstr(path, "/dev/ubi") == path) {
92 if (!UbiFileDescriptor::IsUbi(path)) {
93 // The volume might not have been attached at boot time.
94 int volume_no;
95 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
96 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
97 }
98 }
99 if (UbiFileDescriptor::IsUbi(path)) {
100 LOG(INFO) << path << " is a UBI device.";
101 ret.reset(new UbiFileDescriptor);
102 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800104 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800105 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800106 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800107 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800108#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800109 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800110#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700111 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800112#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800113 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700114}
115
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800116// Opens path for read/write. On success returns an open FileDescriptor
117// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Amin Hassania3fc20a2017-09-19 17:19:34 -0700118FileDescriptorPtr OpenFile(const char* path,
119 int mode,
120 bool cache_writes,
121 int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -0700122 // Try to mark the block device read-only based on the mode. Ignore any
123 // failure since this won't work when passing regular files.
Amin Hassania3fc20a2017-09-19 17:19:34 -0700124 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
125 utils::SetBlockDeviceReadOnly(path, read_only);
Alex Deymo5fb356c2016-03-25 18:48:22 -0700126
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800127 FileDescriptorPtr fd = CreateFileDescriptor(path);
Amin Hassania3fc20a2017-09-19 17:19:34 -0700128 if (cache_writes && !read_only) {
129 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
130 LOG(INFO) << "Caching writes.";
131 }
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800132#if USE_MTD
133 // On NAND devices, we can either read, or write, but not both. So here we
134 // use O_WRONLY.
135 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
136 mode = O_WRONLY;
137 }
138#endif
139 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800140 *err = errno;
141 PLOG(ERROR) << "Unable to open file " << path;
142 return nullptr;
143 }
144 *err = 0;
145 return fd;
146}
Alex Deymob86787c2016-05-12 18:46:25 -0700147
148// Discard the tail of the block device referenced by |fd|, from the offset
149// |data_size| until the end of the block device. Returns whether the data was
150// discarded.
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700151bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
Alex Deymob86787c2016-05-12 18:46:25 -0700152 uint64_t part_size = fd->BlockDevSize();
153 if (!part_size || part_size <= data_size)
154 return false;
155
Alex Deymo72a68d82016-06-15 16:31:04 -0700156 struct blkioctl_request {
157 int number;
158 const char* name;
159 };
160 const vector<blkioctl_request> blkioctl_requests = {
Alex Deymo72a68d82016-06-15 16:31:04 -0700161 {BLKDISCARD, "BLKDISCARD"},
Amin Hassani41555202017-06-23 12:42:00 -0700162 {BLKSECDISCARD, "BLKSECDISCARD"},
Alex Deymob86787c2016-05-12 18:46:25 -0700163#ifdef BLKZEROOUT
Alex Deymo72a68d82016-06-15 16:31:04 -0700164 {BLKZEROOUT, "BLKZEROOUT"},
Alex Deymob86787c2016-05-12 18:46:25 -0700165#endif
166 };
Alex Deymo72a68d82016-06-15 16:31:04 -0700167 for (const auto& req : blkioctl_requests) {
Alex Deymob86787c2016-05-12 18:46:25 -0700168 int error = 0;
Alex Deymo72a68d82016-06-15 16:31:04 -0700169 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
Alex Deymob86787c2016-05-12 18:46:25 -0700170 error == 0) {
171 return true;
172 }
173 LOG(WARNING) << "Error discarding the last "
174 << (part_size - data_size) / 1024 << " KiB using ioctl("
Alex Deymo72a68d82016-06-15 16:31:04 -0700175 << req.name << ")";
Alex Deymob86787c2016-05-12 18:46:25 -0700176 }
177 return false;
178}
179
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700180} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700181
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800182// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
183// arithmetic.
184static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
185 return part * norm / total;
186}
187
188void DeltaPerformer::LogProgress(const char* message_prefix) {
189 // Format operations total count and percentage.
190 string total_operations_str("?");
191 string completed_percentage_str("");
192 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700193 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800194 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800195 completed_percentage_str = base::StringPrintf(
196 " (%" PRIu64 "%%)",
197 IntRatio(next_operation_num_, num_total_operations_, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800198 }
199
200 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800201 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800202 string payload_size_str("?");
203 string downloaded_percentage_str("");
204 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700205 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800206 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
Amin Hassani008c4582019-01-13 16:22:47 -0800207 downloaded_percentage_str = base::StringPrintf(
208 " (%" PRIu64 "%%)", IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800209 }
210
211 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
212 << "/" << total_operations_str << " operations"
Amin Hassani008c4582019-01-13 16:22:47 -0800213 << completed_percentage_str << ", " << total_bytes_received_ << "/"
214 << payload_size_str << " bytes downloaded"
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800215 << downloaded_percentage_str << ", overall progress "
216 << overall_progress_ << "%";
217}
218
219void DeltaPerformer::UpdateOverallProgress(bool force_log,
220 const char* message_prefix) {
221 // Compute our download and overall progress.
222 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800223 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
224 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800225 // Only consider download progress if its total size is known; otherwise
226 // adjust the operations weight to compensate for the absence of download
227 // progress. Also, make sure to cap the download portion at
228 // kProgressDownloadWeight, in case we end up downloading more than we
229 // initially expected (this indicates a problem, but could generally happen).
230 // TODO(garnold) the correction of operations weight when we do not have the
231 // total payload size, as well as the conditional guard below, should both be
232 // eliminated once we ensure that the payload_size in the install plan is
233 // always given and is non-zero. This currently isn't the case during unit
234 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800235 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800236 unsigned actual_operations_weight = kProgressOperationsWeight;
237 if (payload_size)
Amin Hassani008c4582019-01-13 16:22:47 -0800238 new_overall_progress +=
239 min(static_cast<unsigned>(IntRatio(
240 total_bytes_received_, payload_size, kProgressDownloadWeight)),
241 kProgressDownloadWeight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800242 else
243 actual_operations_weight += kProgressDownloadWeight;
244
245 // Only add completed operations if their total number is known; we definitely
246 // expect an update to have at least one operation, so the expectation is that
247 // this will eventually reach |actual_operations_weight|.
248 if (num_total_operations_)
Amin Hassani008c4582019-01-13 16:22:47 -0800249 new_overall_progress += IntRatio(
250 next_operation_num_, num_total_operations_, actual_operations_weight);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800251
252 // Progress ratio cannot recede, unless our assumptions about the total
253 // payload size, total number of operations, or the monotonicity of progress
254 // is breached.
255 if (new_overall_progress < overall_progress_) {
256 LOG(WARNING) << "progress counter receded from " << overall_progress_
257 << "% down to " << new_overall_progress << "%; this is a bug";
258 force_log = true;
259 }
260 overall_progress_ = new_overall_progress;
261
262 // Update chunk index, log as needed: if forced by called, or we completed a
263 // progress chunk, or a timeout has expired.
Sen Jiang53c2ec52019-01-10 15:27:59 -0800264 base::TimeTicks curr_time = base::TimeTicks::Now();
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800265 unsigned curr_progress_chunk =
266 overall_progress_ * kProgressLogMaxChunks / 100;
267 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
268 curr_time > forced_progress_log_time_) {
269 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
270 LogProgress(message_prefix);
271 }
272 last_progress_chunk_ = curr_progress_chunk;
273}
274
Amin Hassani008c4582019-01-13 16:22:47 -0800275size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p,
276 size_t* count_p,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800277 size_t max) {
278 const size_t count = *count_p;
279 if (!count)
280 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700281 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800282 const char* bytes_start = *bytes_p;
283 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800284 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800285 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
286 *bytes_p = bytes_end;
287 *count_p = count - read_len;
288 return read_len;
289}
290
Amin Hassani008c4582019-01-13 16:22:47 -0800291bool DeltaPerformer::HandleOpResult(bool op_result,
292 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800293 ErrorCode* error) {
294 if (op_result)
295 return true;
296
Alex Deymo3d009062016-05-13 15:51:25 -0700297 size_t partition_first_op_num =
298 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800299 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700300 << next_operation_num_ << ", which is the operation "
301 << next_operation_num_ - partition_first_op_num
302 << " in partition \""
303 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700304 if (*error == ErrorCode::kSuccess)
305 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800306 return false;
307}
308
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700309int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700310 int err = -CloseCurrentPartition();
Amin Hassani008c4582019-01-13 16:22:47 -0800311 LOG_IF(ERROR,
312 !payload_hash_calculator_.Finalize() ||
313 !signed_hash_calculator_.Finalize())
Sen Jiangf6813802015-11-03 21:27:29 -0800314 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800315 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700316 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
317 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800318 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800319 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700320 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700321}
322
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700323int DeltaPerformer::CloseCurrentPartition() {
324 int err = 0;
325 if (source_fd_ && !source_fd_->Close()) {
326 err = errno;
327 PLOG(ERROR) << "Error closing source partition";
328 if (!err)
329 err = 1;
330 }
331 source_fd_.reset();
Alex Deymo51c264e2016-11-04 15:49:53 -0700332 if (source_ecc_fd_ && !source_ecc_fd_->Close()) {
333 err = errno;
334 PLOG(ERROR) << "Error closing ECC source partition";
335 if (!err)
336 err = 1;
337 }
338 source_ecc_fd_.reset();
339 source_ecc_open_failure_ = false;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700340 source_path_.clear();
341
342 if (target_fd_ && !target_fd_->Close()) {
343 err = errno;
344 PLOG(ERROR) << "Error closing target partition";
345 if (!err)
346 err = 1;
347 }
348 target_fd_.reset();
349 target_path_.clear();
350 return -err;
351}
352
353bool DeltaPerformer::OpenCurrentPartition() {
354 if (current_partition_ >= partitions_.size())
355 return false;
356
357 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700358 size_t num_previous_partitions =
359 install_plan_->partitions.size() - partitions_.size();
360 const InstallPlan::Partition& install_part =
361 install_plan_->partitions[num_previous_partitions + current_partition_];
Tianjied3865d12020-06-03 15:25:17 -0700362 // Open source fds if we have a delta payload with minor version >= 2, or for
363 // partitions in the partial update.
364 bool source_may_exist = manifest_.partial_update() ||
365 (payload_->type == InstallPayloadType::kDelta &&
366 GetMinorVersion() != kInPlaceMinorPayloadVersion);
367 // We shouldn't open the source partition in certain cases, e.g. some dynamic
368 // partitions in delta payload, partitions included in the full payload for
369 // partial updates. Use the source size as the indicator.
370 if (source_may_exist && install_part.source_size > 0) {
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700371 source_path_ = install_part.source_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700372 int err;
Amin Hassania3fc20a2017-09-19 17:19:34 -0700373 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, false, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700374 if (!source_fd_) {
375 LOG(ERROR) << "Unable to open source partition "
376 << partition.partition_name() << " on slot "
377 << BootControlInterface::SlotName(install_plan_->source_slot)
378 << ", file " << source_path_;
379 return false;
380 }
381 }
382
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700383 target_path_ = install_part.target_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700384 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700385
Amin Hassani7ecda262017-07-11 17:10:50 -0700386 int flags = O_RDWR;
Amin Hassanied37d682018-04-06 13:22:00 -0700387 if (!interactive_)
Amin Hassani7ecda262017-07-11 17:10:50 -0700388 flags |= O_DSYNC;
389
390 LOG(INFO) << "Opening " << target_path_ << " partition with"
Amin Hassanied37d682018-04-06 13:22:00 -0700391 << (interactive_ ? "out" : "") << " O_DSYNC";
Amin Hassani7ecda262017-07-11 17:10:50 -0700392
Amin Hassania3fc20a2017-09-19 17:19:34 -0700393 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700394 if (!target_fd_) {
395 LOG(ERROR) << "Unable to open target partition "
396 << partition.partition_name() << " on slot "
397 << BootControlInterface::SlotName(install_plan_->target_slot)
398 << ", file " << target_path_;
399 return false;
400 }
Alex Deymob86787c2016-05-12 18:46:25 -0700401
402 LOG(INFO) << "Applying " << partition.operations().size()
403 << " operations to partition \"" << partition.partition_name()
404 << "\"";
405
406 // Discard the end of the partition, but ignore failures.
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700407 DiscardPartitionTail(target_fd_, install_part.target_size);
Alex Deymob86787c2016-05-12 18:46:25 -0700408
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700409 return true;
410}
411
Alex Deymo51c264e2016-11-04 15:49:53 -0700412bool DeltaPerformer::OpenCurrentECCPartition() {
413 if (source_ecc_fd_)
414 return true;
415
416 if (source_ecc_open_failure_)
417 return false;
418
419 if (current_partition_ >= partitions_.size())
420 return false;
421
422 // No support for ECC in minor version 1 or full payloads.
423 if (payload_->type == InstallPayloadType::kFull ||
424 GetMinorVersion() == kInPlaceMinorPayloadVersion)
425 return false;
426
427#if USE_FEC
428 const PartitionUpdate& partition = partitions_[current_partition_];
429 size_t num_previous_partitions =
430 install_plan_->partitions.size() - partitions_.size();
431 const InstallPlan::Partition& install_part =
432 install_plan_->partitions[num_previous_partitions + current_partition_];
433 string path = install_part.source_path;
434 FileDescriptorPtr fd(new FecFileDescriptor());
435 if (!fd->Open(path.c_str(), O_RDONLY, 0)) {
436 PLOG(ERROR) << "Unable to open ECC source partition "
437 << partition.partition_name() << " on slot "
438 << BootControlInterface::SlotName(install_plan_->source_slot)
439 << ", file " << path;
440 source_ecc_open_failure_ = true;
441 return false;
442 }
443 source_ecc_fd_ = fd;
444#else
445 // No support for ECC compiled.
446 source_ecc_open_failure_ = true;
447#endif // USE_FEC
448
449 return !source_ecc_open_failure_;
450}
451
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700452namespace {
453
454void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700455 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800456 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
457 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700458}
459
Alex Deymo39910dc2015-11-09 17:04:30 -0800460void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700461 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800462 if (partition.has_old_partition_info()) {
463 LogPartitionInfoHash(partition.old_partition_info(),
464 "old " + partition.partition_name());
465 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700466 LogPartitionInfoHash(partition.new_partition_info(),
467 "new " + partition.partition_name());
468 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700469}
470
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700471} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700472
Allie Woodfdf00512015-03-02 13:34:55 -0800473uint32_t DeltaPerformer::GetMinorVersion() const {
474 if (manifest_.has_minor_version()) {
475 return manifest_.minor_version();
Allie Woodfdf00512015-03-02 13:34:55 -0800476 }
Sen Jiangf1236632018-05-11 16:03:23 -0700477 return payload_->type == InstallPayloadType::kDelta
478 ? kMaxSupportedMinorPayloadVersion
479 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800480}
481
Sen Jiangb8060e42015-09-24 17:30:50 -0700482bool DeltaPerformer::IsHeaderParsed() const {
483 return metadata_size_ != 0;
484}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700485
Sen Jiang9c89e842018-02-02 13:51:21 -0800486MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700487 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700488 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700489
Sen Jiangb8060e42015-09-24 17:30:50 -0700490 if (!IsHeaderParsed()) {
Sen Jiangf1236632018-05-11 16:03:23 -0700491 MetadataParseResult result =
492 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800493 if (result != MetadataParseResult::kSuccess)
494 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700495
Sen Jiang9c89e842018-02-02 13:51:21 -0800496 metadata_size_ = payload_metadata_.GetMetadataSize();
497 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
498 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800499
500 // If the metadata size is present in install plan, check for it immediately
501 // even before waiting for that many number of bytes to be downloaded in the
502 // payload. This will prevent any attack which relies on us downloading data
503 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800504 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800505 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800506 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800507 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800508 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700509 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800510 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800511 }
512 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700513 }
514
515 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700516 // metadata and its signature (if exist) to be read in before we can parse it.
517 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800518 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700519
520 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700521 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700522 // that we just log once (instead of logging n times) if it takes n
523 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800524 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700525 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800526 } else {
527 // For mandatory-cases, we'd have already returned a kMetadataParseError
528 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
529 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800530 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800531 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800532 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800533 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700534
Tianjie Xu7a78d632019-10-08 16:32:39 -0700535 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
536 if (!payload_verifier) {
537 LOG(ERROR) << "Failed to create payload verifier.";
Sen Jiang08c6da12019-01-07 18:28:56 -0800538 *error = ErrorCode::kDownloadMetadataSignatureVerificationError;
Tianjie Xu6c70b932019-10-22 16:46:00 -0700539 if (perform_verification) {
540 return MetadataParseResult::kError;
541 }
542 } else {
543 // We have the full metadata in |payload|. Verify its integrity
544 // and authenticity based on the information we have in Omaha response.
545 *error = payload_metadata_.ValidateMetadataSignature(
546 payload, payload_->metadata_signature, *payload_verifier);
Sen Jiang08c6da12019-01-07 18:28:56 -0800547 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700548 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800549 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800550 // The autoupdate_CatchBadSignatures test checks for this string
551 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800552 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800553 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800554 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700555
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800556 // For non-mandatory cases, just send a UMA stat.
557 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700558 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700559 }
560
Gilad Arnolddaa27402014-01-23 11:56:17 -0800561 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800562 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800563 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700564 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800565 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800566 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800567
568 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800569 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800570}
571
Amin Hassani008c4582019-01-13 16:22:47 -0800572#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
573 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
574 "UpdateEngine.DownloadAction.InstallOperation::" _op_name ".Duration", \
575 base::TimeTicks::Now() - _start_time, \
576 base::TimeDelta::FromMilliseconds(10), \
577 base::TimeDelta::FromMinutes(5), \
578 20);
Lann Martin39f57142017-07-14 09:18:42 -0600579
Don Garrette410e0f2011-11-10 15:39:01 -0800580// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800581// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700582// and stores an action exit code in |error|.
Amin Hassani008c4582019-01-13 16:22:47 -0800583bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700584 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700585 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800586
587 // Update the total byte downloaded count and the progress logs.
588 total_bytes_received_ += count;
589 UpdateOverallProgress(false, "Completed ");
590
Gilad Arnoldfe133932014-01-14 12:25:50 -0800591 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700592 // Read data up to the needed limit; this is either maximium payload header
593 // size, or the full metadata size (once it becomes known).
594 const bool do_read_header = !IsHeaderParsed();
Amin Hassani008c4582019-01-13 16:22:47 -0800595 CopyDataToBuffer(
596 &c_bytes,
597 &count,
598 (do_read_header ? kMaxPayloadHeaderSize
599 : metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800600
Gilad Arnolddaa27402014-01-23 11:56:17 -0800601 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800602 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800603 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800604 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800605 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700606 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800607 continue;
608
Don Garrette410e0f2011-11-10 15:39:01 -0800609 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800610 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700611
612 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700613 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700614 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800615 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700616
Gilad Arnoldfe133932014-01-14 12:25:50 -0800617 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800618 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700619
Sen Jiang57f91802017-11-14 17:42:13 -0800620 block_size_ = manifest_.block_size();
621
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700622 // This populates |partitions_| and the |install_plan.partitions| with the
623 // list of partitions from the manifest.
624 if (!ParseManifestPartitions(error))
625 return false;
626
Sen Jiang5ae865b2017-04-18 14:24:40 -0700627 // |install_plan.partitions| was filled in, nothing need to be done here if
628 // the payload was already applied, returns false to terminate http fetcher,
629 // but keep |error| as ErrorCode::kSuccess.
630 if (payload_->already_applied)
631 return false;
632
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700633 num_total_operations_ = 0;
634 for (const auto& partition : partitions_) {
635 num_total_operations_ += partition.operations_size();
636 acc_num_operations_.push_back(num_total_operations_);
637 }
638
Amin Hassani008c4582019-01-13 16:22:47 -0800639 LOG_IF(WARNING,
640 !prefs_->SetInt64(kPrefsManifestMetadataSize, metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700641 << "Unable to save the manifest metadata size.";
Amin Hassani008c4582019-01-13 16:22:47 -0800642 LOG_IF(WARNING,
643 !prefs_->SetInt64(kPrefsManifestSignatureSize,
644 metadata_signature_size_))
Alex Deymof25eb492016-02-26 00:20:08 -0800645 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700646
Darin Petkov9b230572010-10-08 10:20:09 -0700647 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700648 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700649 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800650 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700651 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800652
Yifan Hong537802d2018-08-15 13:15:42 -0700653 if (next_operation_num_ < acc_num_operations_[current_partition_]) {
654 if (!OpenCurrentPartition()) {
655 *error = ErrorCode::kInstallDeviceOpenError;
656 return false;
657 }
Allie Woodfdf00512015-03-02 13:34:55 -0800658 }
659
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800660 if (next_operation_num_ > 0)
661 UpdateOverallProgress(true, "Resuming after ");
662 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700663 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800664
665 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700666 // Check if we should cancel the current attempt for any reason.
667 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700668 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300669 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700670 return false;
671
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700672 // We know there are more operations to perform because we didn't reach the
673 // |num_total_operations_| limit yet.
Yifan Hong537802d2018-08-15 13:15:42 -0700674 if (next_operation_num_ >= acc_num_operations_[current_partition_]) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700675 CloseCurrentPartition();
Yifan Hong537802d2018-08-15 13:15:42 -0700676 // Skip until there are operations for current_partition_.
677 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
678 current_partition_++;
679 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700680 if (!OpenCurrentPartition()) {
681 *error = ErrorCode::kInstallDeviceOpenError;
682 return false;
683 }
684 }
Amin Hassani008c4582019-01-13 16:22:47 -0800685 const size_t partition_operation_num =
686 next_operation_num_ -
687 (current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700688
Alex Deymoa12ee112015-08-12 22:19:32 -0700689 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700690 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800691
692 CopyDataToBuffer(&c_bytes, &count, op.data_length());
693
694 // Check whether we received all of the next operation's data payload.
695 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700696 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700697
Jay Srinivasanf4318702012-09-24 11:56:24 -0700698 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700699 // Otherwise, keep the old behavior. This serves as a knob to disable
700 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800701 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
702 // we would have already failed in ParsePayloadMetadata method and thus not
703 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800704 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700705 // Note: Validate must be called only if CanPerformInstallOperation is
706 // called. Otherwise, we might be failing operations before even if there
707 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800708 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700709 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800710 if (install_plan_->hash_checks_mandatory) {
711 LOG(ERROR) << "Mandatory operation hash check failed";
712 return false;
713 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700714
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800715 // For non-mandatory cases, just send a UMA stat.
716 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700717 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700718 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700719 }
720
Darin Petkov45580e42010-10-08 14:02:40 -0700721 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700722 ScopedTerminatorExitUnblocker exit_unblocker =
723 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800724
Lann Martin39f57142017-07-14 09:18:42 -0600725 base::TimeTicks op_start_time = base::TimeTicks::Now();
726
Gilad Arnoldfe133932014-01-14 12:25:50 -0800727 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700728 switch (op.type()) {
729 case InstallOperation::REPLACE:
730 case InstallOperation::REPLACE_BZ:
731 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700732 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600733 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700734 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700735 case InstallOperation::ZERO:
736 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700737 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600738 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700739 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700740 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700741 op_result = PerformMoveOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600742 OP_DURATION_HISTOGRAM("MOVE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700743 break;
744 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700745 op_result = PerformBsdiffOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600746 OP_DURATION_HISTOGRAM("BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700747 break;
748 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700749 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600750 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700751 break;
752 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800753 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700754 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600755 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700756 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700757 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700758 op_result = PerformPuffDiffOperation(op, error);
759 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800760 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700761 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700762 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700763 }
764 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800765 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800766
Amin Hassani5192fe52017-08-28 10:28:46 -0700767 if (!target_fd_->Flush()) {
768 return false;
769 }
770
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700771 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800772 UpdateOverallProgress(false, "Completed ");
Sen Jiang3a25dc22019-01-10 14:14:41 -0800773 CheckpointUpdateProgress(false);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700774 }
Sen Jiangf6813802015-11-03 21:27:29 -0800775
776 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800777 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800778 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800779 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
780 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800781 if (manifest_.signatures_offset() != buffer_offset_) {
782 LOG(ERROR) << "Payload signatures offset points to blob offset "
783 << manifest_.signatures_offset()
Amin Hassani008c4582019-01-13 16:22:47 -0800784 << " but signatures are expected at offset " << buffer_offset_;
Sen Jiangf6813802015-11-03 21:27:29 -0800785 *error = ErrorCode::kDownloadPayloadVerificationError;
786 return false;
787 }
788 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
789 // Needs more data to cover entire signature.
790 if (buffer_.size() < manifest_.signatures_size())
791 return true;
792 if (!ExtractSignatureMessage()) {
793 LOG(ERROR) << "Extract payload signature failed.";
794 *error = ErrorCode::kDownloadPayloadVerificationError;
795 return false;
796 }
797 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800798 // Since we extracted the SignatureMessage we need to advance the
799 // checkpoint, otherwise we would reload the signature and try to extract
800 // it again.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800801 // This is the last checkpoint for an update, force this checkpoint to be
802 // saved.
803 CheckpointUpdateProgress(true);
Sen Jiangf6813802015-11-03 21:27:29 -0800804 }
805
Don Garrette410e0f2011-11-10 15:39:01 -0800806 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700807}
808
David Zeuthen8f191b22013-08-06 12:27:50 -0700809bool DeltaPerformer::IsManifestValid() {
810 return manifest_valid_;
811}
812
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700813bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
814 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
815 partitions_.clear();
816 for (const PartitionUpdate& partition : manifest_.partitions()) {
817 partitions_.push_back(partition);
818 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700819 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
820 LOG(INFO) << "Converting update information from old format.";
821 PartitionUpdate root_part;
Tudor Brindusdda79e22018-06-28 18:03:21 -0700822 root_part.set_partition_name(kPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700823#ifdef __ANDROID__
824 LOG(WARNING) << "Legacy payload major version provided to an Android "
825 "build. Assuming no post-install. Please use major version "
826 "2 or newer.";
827 root_part.set_run_postinstall(false);
828#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700829 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700830#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700831 if (manifest_.has_old_rootfs_info()) {
832 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
833 manifest_.clear_old_rootfs_info();
834 }
835 if (manifest_.has_new_rootfs_info()) {
836 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
837 manifest_.clear_new_rootfs_info();
838 }
839 *root_part.mutable_operations() = manifest_.install_operations();
840 manifest_.clear_install_operations();
841 partitions_.push_back(std::move(root_part));
842
843 PartitionUpdate kern_part;
Tudor Brindusdda79e22018-06-28 18:03:21 -0700844 kern_part.set_partition_name(kPartitionNameKernel);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700845 kern_part.set_run_postinstall(false);
846 if (manifest_.has_old_kernel_info()) {
847 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
848 manifest_.clear_old_kernel_info();
849 }
850 if (manifest_.has_new_kernel_info()) {
851 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
852 manifest_.clear_new_kernel_info();
853 }
854 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
855 manifest_.clear_kernel_install_operations();
856 partitions_.push_back(std::move(kern_part));
857 }
858
Tianjied3865d12020-06-03 15:25:17 -0700859 // For VAB and partial updates, the partition preparation will copy the
860 // dynamic partitions metadata to the target metadata slot, and rename the
861 // slot suffix of the partitions in the metadata.
862 if (install_plan_->target_slot != BootControlInterface::kInvalidSlot) {
863 uint64_t required_size = 0;
864 if (!PreparePartitionsForUpdate(&required_size)) {
865 if (required_size > 0) {
866 *error = ErrorCode::kNotEnoughSpace;
867 } else {
868 *error = ErrorCode::kInstallDeviceOpenError;
869 }
870 return false;
871 }
872 }
873
874 // TODO(xunchang) TBD: allow partial update only on devices with dynamic
875 // partition.
876 if (manifest_.partial_update()) {
877 std::set<std::string> touched_partitions;
878 for (const auto& partition_update : partitions_) {
879 touched_partitions.insert(partition_update.partition_name());
880 }
881
Tianjie99d570d2020-06-04 14:57:19 -0700882 auto generator = partition_update_generator::Create(boot_control_,
883 manifest_.block_size());
Tianjied3865d12020-06-03 15:25:17 -0700884 std::vector<PartitionUpdate> other_partitions;
885 TEST_AND_RETURN_FALSE(
886 generator->GenerateOperationsForPartitionsNotInPayload(
887 install_plan_->source_slot,
888 install_plan_->target_slot,
889 touched_partitions,
890 &other_partitions));
891 partitions_.insert(
892 partitions_.end(), other_partitions.begin(), other_partitions.end());
893 }
894
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700895 // Fill in the InstallPlan::partitions based on the partitions from the
896 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700897 for (const auto& partition : partitions_) {
898 InstallPlan::Partition install_part;
899 install_part.name = partition.partition_name();
900 install_part.run_postinstall =
901 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800902 if (install_part.run_postinstall) {
903 install_part.postinstall_path =
904 (partition.has_postinstall_path() ? partition.postinstall_path()
905 : kPostinstallDefaultScript);
906 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700907 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800908 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700909
910 if (partition.has_old_partition_info()) {
911 const PartitionInfo& info = partition.old_partition_info();
912 install_part.source_size = info.size();
913 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
914 }
915
916 if (!partition.has_new_partition_info()) {
917 LOG(ERROR) << "Unable to get new partition hash info on partition "
918 << install_part.name << ".";
919 *error = ErrorCode::kDownloadNewPartitionInfoError;
920 return false;
921 }
922 const PartitionInfo& info = partition.new_partition_info();
923 install_part.target_size = info.size();
924 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
925
Sen Jiang57f91802017-11-14 17:42:13 -0800926 install_part.block_size = block_size_;
927 if (partition.has_hash_tree_extent()) {
928 Extent extent = partition.hash_tree_data_extent();
929 install_part.hash_tree_data_offset = extent.start_block() * block_size_;
930 install_part.hash_tree_data_size = extent.num_blocks() * block_size_;
931 extent = partition.hash_tree_extent();
932 install_part.hash_tree_offset = extent.start_block() * block_size_;
933 install_part.hash_tree_size = extent.num_blocks() * block_size_;
934 uint64_t hash_tree_data_end =
935 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
936 if (install_part.hash_tree_offset < hash_tree_data_end) {
937 LOG(ERROR) << "Invalid hash tree extents, hash tree data ends at "
938 << hash_tree_data_end << ", but hash tree starts at "
939 << install_part.hash_tree_offset;
940 *error = ErrorCode::kDownloadNewPartitionInfoError;
941 return false;
942 }
943 install_part.hash_tree_algorithm = partition.hash_tree_algorithm();
944 install_part.hash_tree_salt.assign(partition.hash_tree_salt().begin(),
945 partition.hash_tree_salt().end());
946 }
947 if (partition.has_fec_extent()) {
948 Extent extent = partition.fec_data_extent();
949 install_part.fec_data_offset = extent.start_block() * block_size_;
950 install_part.fec_data_size = extent.num_blocks() * block_size_;
951 extent = partition.fec_extent();
952 install_part.fec_offset = extent.start_block() * block_size_;
953 install_part.fec_size = extent.num_blocks() * block_size_;
954 uint64_t fec_data_end =
955 install_part.fec_data_offset + install_part.fec_data_size;
956 if (install_part.fec_offset < fec_data_end) {
957 LOG(ERROR) << "Invalid fec extents, fec data ends at " << fec_data_end
958 << ", but fec starts at " << install_part.fec_offset;
959 *error = ErrorCode::kDownloadNewPartitionInfoError;
960 return false;
961 }
962 install_part.fec_roots = partition.fec_roots();
963 }
964
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700965 install_plan_->partitions.push_back(install_part);
966 }
967
Yifan Hong13d41cb2019-09-16 13:18:22 -0700968 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
969 manifest_.clear_partitions();
970 }
971
Tianjied3865d12020-06-03 15:25:17 -0700972 // TODO(xunchang) only need to load the partitions for those in payload.
973 // Because we have already loaded the other once when generating SOURCE_COPY
974 // operations.
Alex Deymo542c19b2015-12-03 07:43:31 -0300975 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700976 LOG(ERROR) << "Unable to determine all the partition devices.";
977 *error = ErrorCode::kInstallDeviceOpenError;
978 return false;
979 }
980 LogPartitionInfo(partitions_);
981 return true;
982}
983
Yifan Hongb9d63572020-01-09 17:50:46 -0800984bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
985 // Call static PreparePartitionsForUpdate with hash from
986 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
987 // preallocated for is the same as the hash of payload being applied.
988 string update_check_response_hash;
989 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
990 &update_check_response_hash));
991 return PreparePartitionsForUpdate(prefs_,
992 boot_control_,
993 install_plan_->target_slot,
994 manifest_,
995 update_check_response_hash,
996 required_size);
997}
998
999bool DeltaPerformer::PreparePartitionsForUpdate(
1000 PrefsInterface* prefs,
1001 BootControlInterface* boot_control,
1002 BootControlInterface::Slot target_slot,
1003 const DeltaArchiveManifest& manifest,
1004 const std::string& update_check_response_hash,
1005 uint64_t* required_size) {
1006 string last_hash;
1007 ignore_result(
1008 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
1009
1010 bool is_resume = !update_check_response_hash.empty() &&
1011 last_hash == update_check_response_hash;
1012
1013 if (is_resume) {
1014 LOG(INFO) << "Using previously prepared partitions for update. hash = "
1015 << last_hash;
1016 } else {
1017 LOG(INFO) << "Preparing partitions for new update. last hash = "
1018 << last_hash << ", new hash = " << update_check_response_hash;
1019 }
1020
1021 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1022 boot_control->GetCurrentSlot(),
1023 target_slot,
1024 manifest,
1025 !is_resume /* should update */,
1026 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001027 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -08001028 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001029 return false;
1030 }
Yifan Hongb9d63572020-01-09 17:50:46 -08001031
1032 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
1033 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -07001034 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001035
1036 return true;
1037}
1038
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001039bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001040 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -07001041 // If we don't have a data blob we can apply it right away.
1042 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001043 return true;
1044
1045 // See if we have the entire data blob in the buffer
1046 if (operation.data_offset() < buffer_offset_) {
1047 LOG(ERROR) << "we threw away data it seems?";
1048 return false;
1049 }
Darin Petkovd7061ab2010-10-06 14:37:09 -07001050
Gilad Arnoldfe133932014-01-14 12:25:50 -08001051 return (operation.data_offset() + operation.data_length() <=
1052 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001053}
1054
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001055bool DeltaPerformer::PerformReplaceOperation(
1056 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -07001057 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -07001058 operation.type() == InstallOperation::REPLACE_BZ ||
1059 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001060
1061 // Since we delete data off the beginning of the buffer as we use it,
1062 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001063 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1064 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001065
Darin Petkov437adc42010-10-07 13:12:24 -07001066 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -08001067 if (ExtractSignatureMessageFromOperation(operation)) {
1068 // If this is dummy replace operation, we ignore it after extracting the
1069 // signature.
1070 DiscardBuffer(true, 0);
1071 return true;
1072 }
Darin Petkovd7061ab2010-10-06 14:37:09 -07001073
Alex Deymo05322872015-09-30 09:50:24 -07001074 // Setup the ExtentWriter stack based on the operation type.
Sen Jiang5e1af982018-11-01 15:01:45 -07001075 std::unique_ptr<ExtentWriter> writer = std::make_unique<DirectExtentWriter>();
Darin Petkovd7061ab2010-10-06 14:37:09 -07001076
Alex Deymo2d621a32015-10-01 11:09:01 -07001077 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -07001078 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -07001079 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
1080 writer.reset(new XzExtentWriter(std::move(writer)));
1081 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001082
Amin Hassanicd7edbe2017-09-18 17:05:02 -07001083 TEST_AND_RETURN_FALSE(
1084 writer->Init(target_fd_, operation.dst_extents(), block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001085 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Darin Petkovd7061ab2010-10-06 14:37:09 -07001086
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001087 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -08001088 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001089 return true;
1090}
1091
Alex Deymo79715ad2015-10-02 14:27:53 -07001092bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001093 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001094 CHECK(operation.type() == InstallOperation::DISCARD ||
1095 operation.type() == InstallOperation::ZERO);
1096
1097 // These operations have no blob.
1098 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
1099 TEST_AND_RETURN_FALSE(!operation.has_data_length());
1100
Alex Deymo05e0e382015-12-07 20:18:16 -08001101#ifdef BLKZEROOUT
1102 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -07001103 int request =
1104 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Amin Hassani008c4582019-01-13 16:22:47 -08001105#else // !defined(BLKZEROOUT)
Alex Deymo05e0e382015-12-07 20:18:16 -08001106 bool attempt_ioctl = false;
1107 int request = 0;
1108#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -07001109
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001110 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001111 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001112 const uint64_t start = extent.start_block() * block_size_;
1113 const uint64_t length = extent.num_blocks() * block_size_;
1114 if (attempt_ioctl) {
1115 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001116 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -07001117 continue;
1118 attempt_ioctl = false;
Alex Deymo79715ad2015-10-02 14:27:53 -07001119 }
1120 // In case of failure, we fall back to writing 0 to the selected region.
Tianjie Xu06bbe492018-01-12 12:37:48 -08001121 zeros.resize(16 * block_size_);
Alex Deymo79715ad2015-10-02 14:27:53 -07001122 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Amin Hassani008c4582019-01-13 16:22:47 -08001123 uint64_t chunk_length =
1124 min(length - offset, static_cast<uint64_t>(zeros.size()));
Amin Hassanid87304c2017-08-29 11:40:03 -07001125 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1126 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -07001127 }
1128 }
1129 return true;
1130}
1131
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001132bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001133 // Calculate buffer size. Note, this function doesn't do a sliding
1134 // window to copy in case the source and destination blocks overlap.
1135 // If we wanted to do a sliding window, we could program the server
1136 // to generate deltas that effectively did a sliding window.
1137
1138 uint64_t blocks_to_read = 0;
1139 for (int i = 0; i < operation.src_extents_size(); i++)
1140 blocks_to_read += operation.src_extents(i).num_blocks();
1141
1142 uint64_t blocks_to_write = 0;
1143 for (int i = 0; i < operation.dst_extents_size(); i++)
1144 blocks_to_write += operation.dst_extents(i).num_blocks();
1145
1146 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001147 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001148
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001149 // Read in bytes.
1150 ssize_t bytes_read = 0;
1151 for (int i = 0; i < operation.src_extents_size(); i++) {
1152 ssize_t bytes_read_this_iteration = 0;
1153 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001154 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001155 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001156 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001157 &buf[bytes_read],
1158 bytes,
1159 extent.start_block() * block_size_,
1160 &bytes_read_this_iteration));
Amin Hassani008c4582019-01-13 16:22:47 -08001161 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
1162 static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001163 bytes_read += bytes_read_this_iteration;
1164 }
1165
1166 // Write bytes out.
1167 ssize_t bytes_written = 0;
1168 for (int i = 0; i < operation.dst_extents_size(); i++) {
1169 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001170 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001171 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001172 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001173 &buf[bytes_written],
1174 bytes,
1175 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001176 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001177 }
1178 DCHECK_EQ(bytes_written, bytes_read);
1179 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1180 return true;
1181}
1182
Sen Jiang8371c1c2018-02-01 13:46:39 -08001183bool DeltaPerformer::ValidateSourceHash(const brillo::Blob& calculated_hash,
1184 const InstallOperation& operation,
1185 const FileDescriptorPtr source_fd,
1186 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001187 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1188 operation.src_sha256_hash().end());
1189 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001190 LOG(ERROR) << "The hash of the source data on disk for this operation "
1191 << "doesn't match the expected value. This could mean that the "
1192 << "delta update payload was targeted for another version, or "
1193 << "that the source partition was modified after it was "
1194 << "installed, for example, by mounting a filesystem.";
1195 LOG(ERROR) << "Expected: sha256|hex = "
1196 << base::HexEncode(expected_source_hash.data(),
1197 expected_source_hash.size());
1198 LOG(ERROR) << "Calculated: sha256|hex = "
1199 << base::HexEncode(calculated_hash.data(),
1200 calculated_hash.size());
1201
1202 vector<string> source_extents;
1203 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001204 source_extents.push_back(
1205 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1206 static_cast<uint64_t>(ext.start_block()),
1207 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001208 }
1209 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1210 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001211
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001212 // Log remount history if this device is an ext4 partition.
1213 LogMountHistory(source_fd);
1214
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001215 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001216 return false;
1217 }
1218 return true;
1219}
1220
Allie Wood9f6f0a52015-03-30 11:25:47 -07001221bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001222 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001223 if (operation.has_src_length())
1224 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1225 if (operation.has_dst_length())
1226 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1227
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001228 TEST_AND_RETURN_FALSE(source_fd_ != nullptr);
1229
Alessio Balsini8d384312019-11-26 11:46:33 +00001230 // The device may optimize the SOURCE_COPY operation.
1231 // Being this a device-specific optimization let DynamicPartitionController
1232 // decide it the operation should be skipped.
Yifan Hong6eec9952019-12-04 13:12:01 -08001233 const PartitionUpdate& partition = partitions_[current_partition_];
Alessio Balsini8d384312019-11-26 11:46:33 +00001234 const auto& partition_control = boot_control_->GetDynamicPartitionControl();
Yifan Hongf5261562020-03-10 10:28:10 -07001235
1236 InstallOperation buf;
1237 bool should_optimize = partition_control->OptimizeOperation(
1238 partition.partition_name(), operation, &buf);
1239 const InstallOperation& optimized = should_optimize ? buf : operation;
Alessio Balsini8d384312019-11-26 11:46:33 +00001240
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001241 if (operation.has_src_sha256_hash()) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001242 bool read_ok;
Alex Deymo51c264e2016-11-04 15:49:53 -07001243 brillo::Blob source_hash;
1244 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1245 operation.src_sha256_hash().end());
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001246
Alex Deymo51c264e2016-11-04 15:49:53 -07001247 // We fall back to use the error corrected device if the hash of the raw
1248 // device doesn't match or there was an error reading the source partition.
1249 // Note that this code will also fall back if writing the target partition
1250 // fails.
Yifan Hongf5261562020-03-10 10:28:10 -07001251 if (should_optimize) {
1252 // Hash operation.src_extents(), then copy optimized.src_extents to
1253 // optimized.dst_extents.
1254 read_ok =
1255 fd_utils::ReadAndHashExtents(
1256 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1257 fd_utils::CopyAndHashExtents(source_fd_,
1258 optimized.src_extents(),
1259 target_fd_,
1260 optimized.dst_extents(),
1261 block_size_,
1262 nullptr /* skip hashing */);
Alessio Balsini8d384312019-11-26 11:46:33 +00001263 } else {
1264 read_ok = fd_utils::CopyAndHashExtents(source_fd_,
1265 operation.src_extents(),
1266 target_fd_,
1267 operation.dst_extents(),
1268 block_size_,
1269 &source_hash);
1270 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001271 if (read_ok && expected_source_hash == source_hash)
1272 return true;
1273
1274 if (!OpenCurrentECCPartition()) {
1275 // The following function call will return false since the source hash
1276 // mismatches, but we still want to call it so it prints the appropriate
1277 // log message.
1278 return ValidateSourceHash(source_hash, operation, source_fd_, error);
1279 }
1280
1281 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1282 << base::HexEncode(source_hash.data(), source_hash.size())
1283 << ", expected "
1284 << base::HexEncode(expected_source_hash.data(),
1285 expected_source_hash.size());
1286
Yifan Hongf5261562020-03-10 10:28:10 -07001287 if (should_optimize) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001288 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
1289 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash));
Yifan Hongf5261562020-03-10 10:28:10 -07001290 TEST_AND_RETURN_FALSE(
1291 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1292 optimized.src_extents(),
1293 target_fd_,
1294 optimized.dst_extents(),
1295 block_size_,
1296 nullptr /* skip hashing */));
Alessio Balsini8d384312019-11-26 11:46:33 +00001297 } else {
1298 TEST_AND_RETURN_FALSE(
1299 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1300 operation.src_extents(),
1301 target_fd_,
1302 operation.dst_extents(),
1303 block_size_,
1304 &source_hash));
1305 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001306 TEST_AND_RETURN_FALSE(
1307 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error));
1308 // At this point reading from the the error corrected device worked, but
1309 // reading from the raw device failed, so this is considered a recovered
1310 // failure.
1311 source_ecc_recovered_failures_++;
1312 } else {
1313 // When the operation doesn't include a source hash, we attempt the error
1314 // corrected device first since we can't verify the block in the raw device
1315 // at this point, but we fall back to the raw device since the error
1316 // corrected device can be shorter or not available.
Alessio Balsini8d384312019-11-26 11:46:33 +00001317
Alex Deymo51c264e2016-11-04 15:49:53 -07001318 if (OpenCurrentECCPartition() &&
1319 fd_utils::CopyAndHashExtents(source_ecc_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001320 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001321 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001322 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001323 block_size_,
1324 nullptr)) {
1325 return true;
1326 }
1327 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001328 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001329 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001330 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001331 block_size_,
1332 nullptr));
1333 }
Allie Wood9f6f0a52015-03-30 11:25:47 -07001334 return true;
1335}
1336
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001337FileDescriptorPtr DeltaPerformer::ChooseSourceFD(
1338 const InstallOperation& operation, ErrorCode* error) {
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001339 if (source_fd_ == nullptr) {
1340 LOG(ERROR) << "ChooseSourceFD fail: source_fd_ == nullptr";
1341 return nullptr;
1342 }
1343
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001344 if (!operation.has_src_sha256_hash()) {
1345 // When the operation doesn't include a source hash, we attempt the error
1346 // corrected device first since we can't verify the block in the raw device
1347 // at this point, but we first need to make sure all extents are readable
1348 // since the error corrected device can be shorter or not available.
1349 if (OpenCurrentECCPartition() &&
1350 fd_utils::ReadAndHashExtents(
1351 source_ecc_fd_, operation.src_extents(), block_size_, nullptr)) {
1352 return source_ecc_fd_;
1353 }
1354 return source_fd_;
1355 }
1356
1357 brillo::Blob source_hash;
1358 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1359 operation.src_sha256_hash().end());
1360 if (fd_utils::ReadAndHashExtents(
1361 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1362 source_hash == expected_source_hash) {
1363 return source_fd_;
1364 }
1365 // We fall back to use the error corrected device if the hash of the raw
1366 // device doesn't match or there was an error reading the source partition.
1367 if (!OpenCurrentECCPartition()) {
1368 // The following function call will return false since the source hash
1369 // mismatches, but we still want to call it so it prints the appropriate
1370 // log message.
1371 ValidateSourceHash(source_hash, operation, source_fd_, error);
1372 return nullptr;
1373 }
1374 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1375 << base::HexEncode(source_hash.data(), source_hash.size())
1376 << ", expected "
1377 << base::HexEncode(expected_source_hash.data(),
1378 expected_source_hash.size());
1379
1380 if (fd_utils::ReadAndHashExtents(
1381 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash) &&
1382 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error)) {
1383 // At this point reading from the the error corrected device worked, but
1384 // reading from the raw device failed, so this is considered a recovered
1385 // failure.
1386 source_ecc_recovered_failures_++;
1387 return source_ecc_fd_;
1388 }
1389 return nullptr;
1390}
1391
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001392bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1393 const RepeatedPtrField<Extent>& extents,
1394 uint64_t block_size,
1395 uint64_t full_length,
1396 string* positions_string) {
1397 string ret;
1398 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001399 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001400 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001401 uint64_t this_length =
1402 min(full_length - length,
1403 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001404 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001405 length += this_length;
1406 }
1407 TEST_AND_RETURN_FALSE(length == full_length);
1408 if (!ret.empty())
1409 ret.resize(ret.size() - 1); // Strip trailing comma off
1410 *positions_string = ret;
1411 return true;
1412}
1413
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001414bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001415 // Since we delete data off the beginning of the buffer as we use it,
1416 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001417 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1418 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001419
1420 string input_positions;
1421 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1422 block_size_,
1423 operation.src_length(),
1424 &input_positions));
1425 string output_positions;
1426 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1427 block_size_,
1428 operation.dst_length(),
1429 &output_positions));
1430
Sen Jiang7a659092016-05-10 15:31:46 -07001431 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1432 target_path_.c_str(),
1433 buffer_.data(),
1434 buffer_.size(),
1435 input_positions.c_str(),
1436 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001437 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001438
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001439 if (operation.dst_length() % block_size_) {
1440 // Zero out rest of final block.
1441 // TODO(adlr): build this into bspatch; it's more efficient that way.
1442 const Extent& last_extent =
1443 operation.dst_extents(operation.dst_extents_size() - 1);
1444 const uint64_t end_byte =
1445 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1446 const uint64_t begin_byte =
1447 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001448 brillo::Blob zeros(end_byte - begin_byte);
Amin Hassanid87304c2017-08-29 11:40:03 -07001449 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1450 target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001451 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001452 return true;
1453}
1454
Amin Hassanid9cb2902017-09-20 12:11:39 -07001455namespace {
1456
1457class BsdiffExtentFile : public bsdiff::FileInterface {
1458 public:
1459 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader, size_t size)
1460 : BsdiffExtentFile(std::move(reader), nullptr, size) {}
1461 BsdiffExtentFile(std::unique_ptr<ExtentWriter> writer, size_t size)
1462 : BsdiffExtentFile(nullptr, std::move(writer), size) {}
1463
1464 ~BsdiffExtentFile() override = default;
1465
1466 bool Read(void* buf, size_t count, size_t* bytes_read) override {
1467 TEST_AND_RETURN_FALSE(reader_->Read(buf, count));
1468 *bytes_read = count;
1469 offset_ += count;
1470 return true;
1471 }
1472
1473 bool Write(const void* buf, size_t count, size_t* bytes_written) override {
1474 TEST_AND_RETURN_FALSE(writer_->Write(buf, count));
1475 *bytes_written = count;
1476 offset_ += count;
1477 return true;
1478 }
1479
1480 bool Seek(off_t pos) override {
1481 if (reader_ != nullptr) {
1482 TEST_AND_RETURN_FALSE(reader_->Seek(pos));
1483 offset_ = pos;
1484 } else {
1485 // For writes technically there should be no change of position, or it
1486 // should be equivalent of current offset.
1487 TEST_AND_RETURN_FALSE(offset_ == static_cast<uint64_t>(pos));
1488 }
1489 return true;
1490 }
1491
Sen Jiang5e1af982018-11-01 15:01:45 -07001492 bool Close() override { return true; }
Amin Hassanid9cb2902017-09-20 12:11:39 -07001493
1494 bool GetSize(uint64_t* size) override {
1495 *size = size_;
1496 return true;
1497 }
1498
1499 private:
1500 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader,
1501 std::unique_ptr<ExtentWriter> writer,
1502 size_t size)
1503 : reader_(std::move(reader)),
1504 writer_(std::move(writer)),
1505 size_(size),
1506 offset_(0) {}
1507
1508 std::unique_ptr<ExtentReader> reader_;
1509 std::unique_ptr<ExtentWriter> writer_;
1510 uint64_t size_;
1511 uint64_t offset_;
1512
1513 DISALLOW_COPY_AND_ASSIGN(BsdiffExtentFile);
1514};
1515
1516} // namespace
1517
Allie Wood9f6f0a52015-03-30 11:25:47 -07001518bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001519 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001520 // Since we delete data off the beginning of the buffer as we use it,
1521 // the data we need should be exactly at the beginning of the buffer.
1522 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1523 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1524 if (operation.has_src_length())
1525 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1526 if (operation.has_dst_length())
1527 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1528
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001529 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1530 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001531
Amin Hassanid9cb2902017-09-20 12:11:39 -07001532 auto reader = std::make_unique<DirectExtentReader>();
1533 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001534 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassanid9cb2902017-09-20 12:11:39 -07001535 auto src_file = std::make_unique<BsdiffExtentFile>(
1536 std::move(reader),
1537 utils::BlocksInExtents(operation.src_extents()) * block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001538
Amin Hassanid9cb2902017-09-20 12:11:39 -07001539 auto writer = std::make_unique<DirectExtentWriter>();
1540 TEST_AND_RETURN_FALSE(
1541 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1542 auto dst_file = std::make_unique<BsdiffExtentFile>(
1543 std::move(writer),
1544 utils::BlocksInExtents(operation.dst_extents()) * block_size_);
1545
1546 TEST_AND_RETURN_FALSE(bsdiff::bspatch(std::move(src_file),
1547 std::move(dst_file),
Sen Jiang7a659092016-05-10 15:31:46 -07001548 buffer_.data(),
Amin Hassanid9cb2902017-09-20 12:11:39 -07001549 buffer_.size()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001550 DiscardBuffer(true, buffer_.size());
1551 return true;
1552}
1553
Amin Hassani02855c22017-09-06 22:34:50 -07001554namespace {
1555
1556// A class to be passed to |puffpatch| for reading from |source_fd_| and writing
1557// into |target_fd_|.
1558class PuffinExtentStream : public puffin::StreamInterface {
1559 public:
1560 // Constructor for creating a stream for reading from an |ExtentReader|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001561 PuffinExtentStream(std::unique_ptr<ExtentReader> reader, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001562 : PuffinExtentStream(std::move(reader), nullptr, size) {}
1563
1564 // Constructor for creating a stream for writing to an |ExtentWriter|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001565 PuffinExtentStream(std::unique_ptr<ExtentWriter> writer, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001566 : PuffinExtentStream(nullptr, std::move(writer), size) {}
1567
1568 ~PuffinExtentStream() override = default;
1569
Amin Hassani678a68f2018-02-28 11:54:47 -08001570 bool GetSize(uint64_t* size) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001571 *size = size_;
1572 return true;
1573 }
1574
Amin Hassani678a68f2018-02-28 11:54:47 -08001575 bool GetOffset(uint64_t* offset) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001576 *offset = offset_;
1577 return true;
1578 }
1579
Amin Hassani678a68f2018-02-28 11:54:47 -08001580 bool Seek(uint64_t offset) override {
Amin Hassani02855c22017-09-06 22:34:50 -07001581 if (is_read_) {
1582 TEST_AND_RETURN_FALSE(reader_->Seek(offset));
1583 offset_ = offset;
1584 } else {
1585 // For writes technically there should be no change of position, or it
1586 // should equivalent of current offset.
1587 TEST_AND_RETURN_FALSE(offset_ == offset);
1588 }
1589 return true;
1590 }
1591
1592 bool Read(void* buffer, size_t count) override {
1593 TEST_AND_RETURN_FALSE(is_read_);
1594 TEST_AND_RETURN_FALSE(reader_->Read(buffer, count));
1595 offset_ += count;
1596 return true;
1597 }
1598
1599 bool Write(const void* buffer, size_t count) override {
1600 TEST_AND_RETURN_FALSE(!is_read_);
1601 TEST_AND_RETURN_FALSE(writer_->Write(buffer, count));
1602 offset_ += count;
1603 return true;
1604 }
1605
Sen Jiang5e1af982018-11-01 15:01:45 -07001606 bool Close() override { return true; }
Amin Hassani02855c22017-09-06 22:34:50 -07001607
1608 private:
1609 PuffinExtentStream(std::unique_ptr<ExtentReader> reader,
1610 std::unique_ptr<ExtentWriter> writer,
Amin Hassani678a68f2018-02-28 11:54:47 -08001611 uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001612 : reader_(std::move(reader)),
1613 writer_(std::move(writer)),
1614 size_(size),
1615 offset_(0),
1616 is_read_(reader_ ? true : false) {}
1617
1618 std::unique_ptr<ExtentReader> reader_;
1619 std::unique_ptr<ExtentWriter> writer_;
1620 uint64_t size_;
1621 uint64_t offset_;
1622 bool is_read_;
1623
1624 DISALLOW_COPY_AND_ASSIGN(PuffinExtentStream);
1625};
1626
1627} // namespace
1628
1629bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
1630 ErrorCode* error) {
1631 // Since we delete data off the beginning of the buffer as we use it,
1632 // the data we need should be exactly at the beginning of the buffer.
1633 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1634 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1635
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001636 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1637 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Amin Hassani02855c22017-09-06 22:34:50 -07001638
1639 auto reader = std::make_unique<DirectExtentReader>();
1640 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001641 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassani02855c22017-09-06 22:34:50 -07001642 puffin::UniqueStreamPtr src_stream(new PuffinExtentStream(
1643 std::move(reader),
1644 utils::BlocksInExtents(operation.src_extents()) * block_size_));
1645
1646 auto writer = std::make_unique<DirectExtentWriter>();
1647 TEST_AND_RETURN_FALSE(
1648 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1649 puffin::UniqueStreamPtr dst_stream(new PuffinExtentStream(
1650 std::move(writer),
1651 utils::BlocksInExtents(operation.dst_extents()) * block_size_));
1652
1653 const size_t kMaxCacheSize = 5 * 1024 * 1024; // Total 5MB cache.
1654 TEST_AND_RETURN_FALSE(puffin::PuffPatch(std::move(src_stream),
1655 std::move(dst_stream),
1656 buffer_.data(),
1657 buffer_.size(),
1658 kMaxCacheSize));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001659 DiscardBuffer(true, buffer_.size());
Alex Deymoa12ee112015-08-12 22:19:32 -07001660 return true;
1661}
Darin Petkovd7061ab2010-10-06 14:37:09 -07001662
Darin Petkovd7061ab2010-10-06 14:37:09 -07001663bool DeltaPerformer::ExtractSignatureMessageFromOperation(
1664 const InstallOperation& operation) {
1665 if (operation.type() != InstallOperation::REPLACE ||
1666 !manifest_.has_signatures_offset() ||
1667 manifest_.signatures_offset() != operation.data_offset()) {
1668 return false;
1669 }
1670 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1671 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001672 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1673 return true;
1674}
1675
1676bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001677 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1678 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1679 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001680 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -08001681 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001682
1683 // Save the signature blob because if the update is interrupted after the
1684 // download phase we don't go through this path anymore. Some alternatives to
1685 // consider:
1686 //
1687 // 1. On resume, re-download the signature blob from the server and re-verify
1688 // it.
1689 //
1690 // 2. Verify the signature as soon as it's received and don't checkpoint the
1691 // blob and the signed sha-256 context.
Amin Hassani008c4582019-01-13 16:22:47 -08001692 LOG_IF(WARNING,
1693 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Sen Jiang9b2f1782019-01-24 14:27:50 -08001694 signatures_message_data_))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001695 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001696
Darin Petkovd7061ab2010-10-06 14:37:09 -07001697 LOG(INFO) << "Extracted signature data of size "
1698 << manifest_.signatures_size() << " at "
1699 << manifest_.signatures_offset();
1700 return true;
1701}
1702
Sen Jiang08c6da12019-01-07 18:28:56 -08001703bool DeltaPerformer::GetPublicKey(string* out_public_key) {
1704 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -07001705
Sen Jiang08c6da12019-01-07 18:28:56 -08001706 if (utils::FileExists(public_key_path_.c_str())) {
1707 LOG(INFO) << "Verifying using public key: " << public_key_path_;
1708 return utils::ReadFile(public_key_path_, out_public_key);
1709 }
1710
1711 // If this is an official build then we are not allowed to use public key from
1712 // Omaha response.
1713 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
1714 LOG(INFO) << "Verifying using public key from Omaha response.";
1715 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1716 out_public_key);
1717 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001718 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001719 return true;
1720}
1721
Tianjie Xu7a78d632019-10-08 16:32:39 -07001722std::pair<std::unique_ptr<PayloadVerifier>, bool>
1723DeltaPerformer::CreatePayloadVerifier() {
1724 if (utils::FileExists(update_certificates_path_.c_str())) {
1725 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1726 return {
1727 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1728 true};
1729 }
1730
1731 string public_key;
1732 if (!GetPublicKey(&public_key)) {
1733 LOG(ERROR) << "Failed to read public key";
1734 return {nullptr, true};
1735 }
1736
1737 // Skips the verification if the public key is empty.
1738 if (public_key.empty()) {
1739 return {nullptr, false};
1740 }
1741 return {PayloadVerifier::CreateInstance(public_key), true};
1742}
1743
Gilad Arnold21504f02013-05-24 08:51:22 -07001744ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001745 // Perform assorted checks to sanity check the manifest, make sure it
1746 // matches data from other sources, and that it is a supported version.
Alex Deymo64d98782016-02-05 18:03:48 -08001747 bool has_old_fields =
1748 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1749 for (const PartitionUpdate& partition : manifest_.partitions()) {
1750 has_old_fields = has_old_fields || partition.has_old_partition_info();
1751 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001752
Alex Deymo64d98782016-02-05 18:03:48 -08001753 // The presence of an old partition hash is the sole indicator for a delta
1754 // update.
1755 InstallPayloadType actual_payload_type =
1756 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1757
Sen Jiangcdd52062017-05-18 15:33:10 -07001758 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001759 LOG(INFO) << "Detected a '"
1760 << InstallPayloadTypeToString(actual_payload_type)
1761 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001762 payload_->type = actual_payload_type;
1763 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001764 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001765 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001766 << "' payload but the downloaded manifest contains a '"
1767 << InstallPayloadTypeToString(actual_payload_type)
1768 << "' payload.";
1769 return ErrorCode::kPayloadMismatchedType;
1770 }
Alex Deymo64d98782016-02-05 18:03:48 -08001771 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001772 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001773 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001774 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1775 LOG(ERROR) << "Manifest contains minor version "
1776 << manifest_.minor_version()
1777 << ", but all full payloads should have version "
1778 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001779 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001780 }
1781 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001782 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1783 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001784 LOG(ERROR) << "Manifest contains minor version "
1785 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001786 << " not in the range of supported minor versions ["
1787 << kMinSupportedMinorPayloadVersion << ", "
1788 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001789 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001790 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001791 }
1792
Sen Jiang3e728fe2015-11-05 11:37:23 -08001793 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
Amin Hassani008c4582019-01-13 16:22:47 -08001794 if (manifest_.has_old_rootfs_info() || manifest_.has_new_rootfs_info() ||
1795 manifest_.has_old_kernel_info() || manifest_.has_new_kernel_info() ||
Sen Jiang3e728fe2015-11-05 11:37:23 -08001796 manifest_.install_operations_size() != 0 ||
1797 manifest_.kernel_install_operations_size() != 0) {
1798 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1799 << "major payload version 1, but the payload major version is "
1800 << major_payload_version_;
1801 return ErrorCode::kPayloadMismatchedType;
1802 }
1803 }
1804
Sen Jiang8e768e92017-06-28 17:13:19 -07001805 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1806 LOG(ERROR) << "The current OS build timestamp ("
1807 << hardware_->GetBuildTimestamp()
1808 << ") is newer than the maximum timestamp in the manifest ("
1809 << manifest_.max_timestamp() << ")";
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001810 if (!hardware_->AllowDowngrade()) {
1811 return ErrorCode::kPayloadTimestampError;
1812 }
1813 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1814 " the payload with an older timestamp.";
Sen Jiang8e768e92017-06-28 17:13:19 -07001815 }
1816
Yifan Hongd4db07e2018-10-18 17:46:27 -07001817 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
1818 if (manifest_.has_dynamic_partition_metadata()) {
1819 LOG(ERROR)
1820 << "Should not contain dynamic_partition_metadata for major version "
1821 << kChromeOSMajorPayloadVersion
1822 << ". Please use major version 2 or above.";
1823 return ErrorCode::kPayloadMismatchedType;
1824 }
1825 }
1826
Gilad Arnold21504f02013-05-24 08:51:22 -07001827 // TODO(garnold) we should be adding more and more manifest checks, such as
1828 // partition boundaries etc (see chromium-os:37661).
1829
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001830 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001831}
1832
David Zeuthena99981f2013-04-29 13:42:47 -07001833ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001834 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001835 if (!operation.data_sha256_hash().size()) {
1836 if (!operation.data_length()) {
1837 // Operations that do not have any data blob won't have any operation hash
1838 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001839 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001840 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001841 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001842 }
1843
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001844 // No hash is present for an operation that has data blobs. This shouldn't
1845 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001846 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001847 // hashes. So if it happens it means either we've turned operation hash
1848 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001849 // One caveat though: The last operation is a dummy signature operation
1850 // that doesn't have a hash at the time the manifest is created. So we
1851 // should not complaint about that operation. This operation can be
1852 // recognized by the fact that it's offset is mentioned in the manifest.
1853 if (manifest_.signatures_offset() &&
1854 manifest_.signatures_offset() == operation.data_offset()) {
1855 LOG(INFO) << "Skipping hash verification for signature operation "
1856 << next_operation_num_ + 1;
1857 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001858 if (install_plan_->hash_checks_mandatory) {
1859 LOG(ERROR) << "Missing mandatory operation hash for operation "
1860 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001861 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001862 }
1863
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001864 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1865 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001866 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001867 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001868 }
1869
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001870 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001871 expected_op_hash.assign(operation.data_sha256_hash().data(),
1872 (operation.data_sha256_hash().data() +
1873 operation.data_sha256_hash().size()));
1874
Sen Jiang2703ef42017-03-16 13:36:21 -07001875 brillo::Blob calculated_op_hash;
1876 if (!HashCalculator::RawHashOfBytes(
1877 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001878 LOG(ERROR) << "Unable to compute actual hash of operation "
1879 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001880 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001881 }
1882
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001883 if (calculated_op_hash != expected_op_hash) {
1884 LOG(ERROR) << "Hash verification failed for operation "
1885 << next_operation_num_ << ". Expected hash = ";
1886 utils::HexDumpVector(expected_op_hash);
1887 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1888 << " bytes at offset: " << operation.data_offset() << " = ";
1889 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001890 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001891 }
1892
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001893 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001894}
1895
Amin Hassani008c4582019-01-13 16:22:47 -08001896#define TEST_AND_RETURN_VAL(_retval, _condition) \
1897 do { \
1898 if (!(_condition)) { \
1899 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1900 return _retval; \
1901 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001902 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001903
David Zeuthena99981f2013-04-29 13:42:47 -07001904ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001905 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001906 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001907 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001908 if (update_check_response_size !=
1909 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1910 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1911 << ") doesn't match metadata_size (" << metadata_size_
1912 << ") + metadata_signature_size (" << metadata_signature_size_
1913 << ") + buffer_offset (" << buffer_offset_ << ").";
1914 return ErrorCode::kPayloadSizeMismatchError;
1915 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001916
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001917 // Verifies the payload hash.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001918 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Sen Jiang2703ef42017-03-16 13:36:21 -07001919 !payload_hash_calculator_.raw_hash().empty());
1920 TEST_AND_RETURN_VAL(
1921 ErrorCode::kPayloadHashMismatchError,
1922 payload_hash_calculator_.raw_hash() == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001923
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001924 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001925 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001926 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001927 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001928 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001929
Tianjie Xu7a78d632019-10-08 16:32:39 -07001930 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1931 if (!perform_verification) {
1932 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1933 return ErrorCode::kSuccess;
1934 }
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001935 if (!payload_verifier) {
Tianjie Xu7a78d632019-10-08 16:32:39 -07001936 LOG(ERROR) << "Failed to create the payload verifier.";
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001937 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1938 }
1939 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001940 // The autoupdate_CatchBadSignatures test checks for this string
1941 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001942 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001943 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001944 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001945
David Zeuthene7f89172013-10-31 10:21:04 -07001946 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001947 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001948}
1949
Sen Jiangf6813802015-11-03 21:27:29 -08001950void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1951 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001952 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001953 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001954 buffer_offset_ += buffer_.size();
1955
1956 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001957 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1958 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001959
1960 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001961 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001962}
1963
Darin Petkov0406e402010-10-06 21:33:11 -07001964bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001965 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001966 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001967 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Amin Hassani008c4582019-01-13 16:22:47 -08001968 next_operation != kUpdateStateOperationInvalid && next_operation > 0))
Alex Deymo3310b222015-03-30 15:59:07 -07001969 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001970
1971 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001972 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1973 !interrupted_hash.empty() &&
1974 interrupted_hash == update_check_response_hash))
1975 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001976
Darin Petkov61426142010-10-08 11:04:55 -07001977 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001978 // Note that storing this value is optional, but if it is there it should not
1979 // be more than the limit.
1980 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1981 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001982 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001983
Darin Petkov0406e402010-10-06 21:33:11 -07001984 // Sanity check the rest.
1985 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001986 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1987 next_data_offset >= 0))
1988 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001989
Darin Petkov437adc42010-10-07 13:12:24 -07001990 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001991 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1992 !sha256_context.empty()))
1993 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001994
1995 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001996 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1997 manifest_metadata_size > 0))
1998 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001999
Alex Deymof25eb492016-02-26 00:20:08 -08002000 int64_t manifest_signature_size = 0;
2001 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
2002 &manifest_signature_size) &&
2003 manifest_signature_size >= 0))
2004 return false;
2005
Darin Petkov0406e402010-10-06 21:33:11 -07002006 return true;
2007}
2008
Yifan Hong55c2bfe2020-01-13 17:01:19 -08002009bool DeltaPerformer::ResetUpdateProgress(
2010 PrefsInterface* prefs,
2011 bool quick,
2012 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07002013 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
2014 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07002015 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07002016 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07002017 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07002018 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
2019 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07002020 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07002021 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08002022 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07002023 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07002024 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07002025 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08002026
2027 if (!skip_dynamic_partititon_metadata_updated) {
2028 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
2029 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
2030 }
Darin Petkov9b230572010-10-08 10:20:09 -07002031 }
Darin Petkov73058b42010-10-06 16:32:19 -07002032 return true;
2033}
2034
Sen Jiang3a25dc22019-01-10 14:14:41 -08002035bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
Sen Jiang53c2ec52019-01-10 15:27:59 -08002036 base::TimeTicks curr_time = base::TimeTicks::Now();
Sen Jiang3a25dc22019-01-10 14:14:41 -08002037 if (force || curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07002038 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
2039 } else {
2040 return false;
2041 }
2042
Darin Petkov9c0baf82010-10-07 13:44:48 -07002043 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07002044 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07002045 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07002046 ResetUpdateProgress(prefs_, true);
Amin Hassani008c4582019-01-13 16:22:47 -08002047 TEST_AND_RETURN_FALSE(prefs_->SetString(
2048 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08002049 TEST_AND_RETURN_FALSE(
2050 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
2051 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08002052 TEST_AND_RETURN_FALSE(
2053 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Darin Petkov0406e402010-10-06 21:33:11 -07002054 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07002055
2056 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07002057 size_t partition_index = current_partition_;
2058 while (next_operation_num_ >= acc_num_operations_[partition_index])
2059 partition_index++;
Amin Hassani008c4582019-01-13 16:22:47 -08002060 const size_t partition_operation_num =
2061 next_operation_num_ -
2062 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07002063 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07002064 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08002065 TEST_AND_RETURN_FALSE(
2066 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07002067 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08002068 TEST_AND_RETURN_FALSE(
2069 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07002070 }
Darin Petkov0406e402010-10-06 21:33:11 -07002071 }
Amin Hassani008c4582019-01-13 16:22:47 -08002072 TEST_AND_RETURN_FALSE(
2073 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07002074 return true;
2075}
2076
Darin Petkov9b230572010-10-08 10:20:09 -07002077bool DeltaPerformer::PrimeUpdateState() {
2078 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07002079
2080 int64_t next_operation = kUpdateStateOperationInvalid;
2081 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08002082 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07002083 // Initiating a new update, no more state needs to be initialized.
2084 return true;
2085 }
2086 next_operation_num_ = next_operation;
2087
2088 // Resuming an update -- load the rest of the update state.
2089 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08002090 TEST_AND_RETURN_FALSE(
2091 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
2092 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07002093 buffer_offset_ = next_data_offset;
2094
Darin Petkov4f0a07b2011-05-25 16:47:20 -07002095 // The signed hash context and the signature blob may be empty if the
2096 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08002097 string signed_hash_context;
2098 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
2099 &signed_hash_context)) {
2100 TEST_AND_RETURN_FALSE(
2101 signed_hash_calculator_.SetContext(signed_hash_context));
2102 }
2103
Sen Jiang9b2f1782019-01-24 14:27:50 -08002104 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07002105
2106 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08002107 TEST_AND_RETURN_FALSE(
2108 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
2109 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07002110
2111 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08002112 TEST_AND_RETURN_FALSE(
2113 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
2114 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08002115 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07002116
Alex Deymof25eb492016-02-26 00:20:08 -08002117 int64_t manifest_signature_size = 0;
2118 TEST_AND_RETURN_FALSE(
2119 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
2120 manifest_signature_size >= 0);
2121 metadata_signature_size_ = manifest_signature_size;
2122
Gilad Arnold8a86fa52013-01-15 12:35:05 -08002123 // Advance the download progress to reflect what doesn't need to be
2124 // re-downloaded.
2125 total_bytes_received_ += buffer_offset_;
2126
Darin Petkov61426142010-10-08 11:04:55 -07002127 // Speculatively count the resume as a failure.
2128 int64_t resumed_update_failures;
2129 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
2130 resumed_update_failures++;
2131 } else {
2132 resumed_update_failures = 1;
2133 }
2134 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07002135 return true;
2136}
2137
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002138} // namespace chromeos_update_engine