blob: d1de9f4d778912bd29bc9c2966ccbfe2b4068d3c [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
882 auto generator = partition_update_generator::Create(boot_control_);
883 std::vector<PartitionUpdate> other_partitions;
884 TEST_AND_RETURN_FALSE(
885 generator->GenerateOperationsForPartitionsNotInPayload(
886 install_plan_->source_slot,
887 install_plan_->target_slot,
888 touched_partitions,
889 &other_partitions));
890 partitions_.insert(
891 partitions_.end(), other_partitions.begin(), other_partitions.end());
892 }
893
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700894 // Fill in the InstallPlan::partitions based on the partitions from the
895 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700896 for (const auto& partition : partitions_) {
897 InstallPlan::Partition install_part;
898 install_part.name = partition.partition_name();
899 install_part.run_postinstall =
900 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800901 if (install_part.run_postinstall) {
902 install_part.postinstall_path =
903 (partition.has_postinstall_path() ? partition.postinstall_path()
904 : kPostinstallDefaultScript);
905 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700906 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800907 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700908
909 if (partition.has_old_partition_info()) {
910 const PartitionInfo& info = partition.old_partition_info();
911 install_part.source_size = info.size();
912 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
913 }
914
915 if (!partition.has_new_partition_info()) {
916 LOG(ERROR) << "Unable to get new partition hash info on partition "
917 << install_part.name << ".";
918 *error = ErrorCode::kDownloadNewPartitionInfoError;
919 return false;
920 }
921 const PartitionInfo& info = partition.new_partition_info();
922 install_part.target_size = info.size();
923 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
924
Sen Jiang57f91802017-11-14 17:42:13 -0800925 install_part.block_size = block_size_;
926 if (partition.has_hash_tree_extent()) {
927 Extent extent = partition.hash_tree_data_extent();
928 install_part.hash_tree_data_offset = extent.start_block() * block_size_;
929 install_part.hash_tree_data_size = extent.num_blocks() * block_size_;
930 extent = partition.hash_tree_extent();
931 install_part.hash_tree_offset = extent.start_block() * block_size_;
932 install_part.hash_tree_size = extent.num_blocks() * block_size_;
933 uint64_t hash_tree_data_end =
934 install_part.hash_tree_data_offset + install_part.hash_tree_data_size;
935 if (install_part.hash_tree_offset < hash_tree_data_end) {
936 LOG(ERROR) << "Invalid hash tree extents, hash tree data ends at "
937 << hash_tree_data_end << ", but hash tree starts at "
938 << install_part.hash_tree_offset;
939 *error = ErrorCode::kDownloadNewPartitionInfoError;
940 return false;
941 }
942 install_part.hash_tree_algorithm = partition.hash_tree_algorithm();
943 install_part.hash_tree_salt.assign(partition.hash_tree_salt().begin(),
944 partition.hash_tree_salt().end());
945 }
946 if (partition.has_fec_extent()) {
947 Extent extent = partition.fec_data_extent();
948 install_part.fec_data_offset = extent.start_block() * block_size_;
949 install_part.fec_data_size = extent.num_blocks() * block_size_;
950 extent = partition.fec_extent();
951 install_part.fec_offset = extent.start_block() * block_size_;
952 install_part.fec_size = extent.num_blocks() * block_size_;
953 uint64_t fec_data_end =
954 install_part.fec_data_offset + install_part.fec_data_size;
955 if (install_part.fec_offset < fec_data_end) {
956 LOG(ERROR) << "Invalid fec extents, fec data ends at " << fec_data_end
957 << ", but fec starts at " << install_part.fec_offset;
958 *error = ErrorCode::kDownloadNewPartitionInfoError;
959 return false;
960 }
961 install_part.fec_roots = partition.fec_roots();
962 }
963
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700964 install_plan_->partitions.push_back(install_part);
965 }
966
Yifan Hong13d41cb2019-09-16 13:18:22 -0700967 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
968 manifest_.clear_partitions();
969 }
970
Tianjied3865d12020-06-03 15:25:17 -0700971 // TODO(xunchang) only need to load the partitions for those in payload.
972 // Because we have already loaded the other once when generating SOURCE_COPY
973 // operations.
Alex Deymo542c19b2015-12-03 07:43:31 -0300974 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700975 LOG(ERROR) << "Unable to determine all the partition devices.";
976 *error = ErrorCode::kInstallDeviceOpenError;
977 return false;
978 }
979 LogPartitionInfo(partitions_);
980 return true;
981}
982
Yifan Hongb9d63572020-01-09 17:50:46 -0800983bool DeltaPerformer::PreparePartitionsForUpdate(uint64_t* required_size) {
984 // Call static PreparePartitionsForUpdate with hash from
985 // kPrefsUpdateCheckResponseHash to ensure hash of payload that space is
986 // preallocated for is the same as the hash of payload being applied.
987 string update_check_response_hash;
988 ignore_result(prefs_->GetString(kPrefsUpdateCheckResponseHash,
989 &update_check_response_hash));
990 return PreparePartitionsForUpdate(prefs_,
991 boot_control_,
992 install_plan_->target_slot,
993 manifest_,
994 update_check_response_hash,
995 required_size);
996}
997
998bool DeltaPerformer::PreparePartitionsForUpdate(
999 PrefsInterface* prefs,
1000 BootControlInterface* boot_control,
1001 BootControlInterface::Slot target_slot,
1002 const DeltaArchiveManifest& manifest,
1003 const std::string& update_check_response_hash,
1004 uint64_t* required_size) {
1005 string last_hash;
1006 ignore_result(
1007 prefs->GetString(kPrefsDynamicPartitionMetadataUpdated, &last_hash));
1008
1009 bool is_resume = !update_check_response_hash.empty() &&
1010 last_hash == update_check_response_hash;
1011
1012 if (is_resume) {
1013 LOG(INFO) << "Using previously prepared partitions for update. hash = "
1014 << last_hash;
1015 } else {
1016 LOG(INFO) << "Preparing partitions for new update. last hash = "
1017 << last_hash << ", new hash = " << update_check_response_hash;
1018 }
1019
1020 if (!boot_control->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1021 boot_control->GetCurrentSlot(),
1022 target_slot,
1023 manifest,
1024 !is_resume /* should update */,
1025 required_size)) {
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001026 LOG(ERROR) << "Unable to initialize partition metadata for slot "
Yifan Hongb9d63572020-01-09 17:50:46 -08001027 << BootControlInterface::SlotName(target_slot);
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001028 return false;
1029 }
Yifan Hongb9d63572020-01-09 17:50:46 -08001030
1031 TEST_AND_RETURN_FALSE(prefs->SetString(kPrefsDynamicPartitionMetadataUpdated,
1032 update_check_response_hash));
Yifan Hong13d41cb2019-09-16 13:18:22 -07001033 LOG(INFO) << "PreparePartitionsForUpdate done.";
Yifan Hong9acd9cb2018-10-19 14:52:45 -07001034
1035 return true;
1036}
1037
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001038bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001039 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -07001040 // If we don't have a data blob we can apply it right away.
1041 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001042 return true;
1043
1044 // See if we have the entire data blob in the buffer
1045 if (operation.data_offset() < buffer_offset_) {
1046 LOG(ERROR) << "we threw away data it seems?";
1047 return false;
1048 }
Darin Petkovd7061ab2010-10-06 14:37:09 -07001049
Gilad Arnoldfe133932014-01-14 12:25:50 -08001050 return (operation.data_offset() + operation.data_length() <=
1051 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001052}
1053
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001054bool DeltaPerformer::PerformReplaceOperation(
1055 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -07001056 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -07001057 operation.type() == InstallOperation::REPLACE_BZ ||
1058 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001059
1060 // Since we delete data off the beginning of the buffer as we use it,
1061 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001062 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1063 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001064
Darin Petkov437adc42010-10-07 13:12:24 -07001065 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -08001066 if (ExtractSignatureMessageFromOperation(operation)) {
1067 // If this is dummy replace operation, we ignore it after extracting the
1068 // signature.
1069 DiscardBuffer(true, 0);
1070 return true;
1071 }
Darin Petkovd7061ab2010-10-06 14:37:09 -07001072
Alex Deymo05322872015-09-30 09:50:24 -07001073 // Setup the ExtentWriter stack based on the operation type.
Sen Jiang5e1af982018-11-01 15:01:45 -07001074 std::unique_ptr<ExtentWriter> writer = std::make_unique<DirectExtentWriter>();
Darin Petkovd7061ab2010-10-06 14:37:09 -07001075
Alex Deymo2d621a32015-10-01 11:09:01 -07001076 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -07001077 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -07001078 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
1079 writer.reset(new XzExtentWriter(std::move(writer)));
1080 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001081
Amin Hassanicd7edbe2017-09-18 17:05:02 -07001082 TEST_AND_RETURN_FALSE(
1083 writer->Init(target_fd_, operation.dst_extents(), block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001084 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Darin Petkovd7061ab2010-10-06 14:37:09 -07001085
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001086 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -08001087 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001088 return true;
1089}
1090
Alex Deymo79715ad2015-10-02 14:27:53 -07001091bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001092 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001093 CHECK(operation.type() == InstallOperation::DISCARD ||
1094 operation.type() == InstallOperation::ZERO);
1095
1096 // These operations have no blob.
1097 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
1098 TEST_AND_RETURN_FALSE(!operation.has_data_length());
1099
Alex Deymo05e0e382015-12-07 20:18:16 -08001100#ifdef BLKZEROOUT
1101 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -07001102 int request =
1103 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Amin Hassani008c4582019-01-13 16:22:47 -08001104#else // !defined(BLKZEROOUT)
Alex Deymo05e0e382015-12-07 20:18:16 -08001105 bool attempt_ioctl = false;
1106 int request = 0;
1107#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -07001108
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001109 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001110 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -07001111 const uint64_t start = extent.start_block() * block_size_;
1112 const uint64_t length = extent.num_blocks() * block_size_;
1113 if (attempt_ioctl) {
1114 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001115 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -07001116 continue;
1117 attempt_ioctl = false;
Alex Deymo79715ad2015-10-02 14:27:53 -07001118 }
1119 // In case of failure, we fall back to writing 0 to the selected region.
Tianjie Xu06bbe492018-01-12 12:37:48 -08001120 zeros.resize(16 * block_size_);
Alex Deymo79715ad2015-10-02 14:27:53 -07001121 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Amin Hassani008c4582019-01-13 16:22:47 -08001122 uint64_t chunk_length =
1123 min(length - offset, static_cast<uint64_t>(zeros.size()));
Amin Hassanid87304c2017-08-29 11:40:03 -07001124 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1125 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -07001126 }
1127 }
1128 return true;
1129}
1130
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001131bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001132 // Calculate buffer size. Note, this function doesn't do a sliding
1133 // window to copy in case the source and destination blocks overlap.
1134 // If we wanted to do a sliding window, we could program the server
1135 // to generate deltas that effectively did a sliding window.
1136
1137 uint64_t blocks_to_read = 0;
1138 for (int i = 0; i < operation.src_extents_size(); i++)
1139 blocks_to_read += operation.src_extents(i).num_blocks();
1140
1141 uint64_t blocks_to_write = 0;
1142 for (int i = 0; i < operation.dst_extents_size(); i++)
1143 blocks_to_write += operation.dst_extents(i).num_blocks();
1144
1145 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001146 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001147
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001148 // Read in bytes.
1149 ssize_t bytes_read = 0;
1150 for (int i = 0; i < operation.src_extents_size(); i++) {
1151 ssize_t bytes_read_this_iteration = 0;
1152 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001153 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001154 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001155 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001156 &buf[bytes_read],
1157 bytes,
1158 extent.start_block() * block_size_,
1159 &bytes_read_this_iteration));
Amin Hassani008c4582019-01-13 16:22:47 -08001160 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
1161 static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001162 bytes_read += bytes_read_this_iteration;
1163 }
1164
1165 // Write bytes out.
1166 ssize_t bytes_written = 0;
1167 for (int i = 0; i < operation.dst_extents_size(); i++) {
1168 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001169 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001170 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001171 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001172 &buf[bytes_written],
1173 bytes,
1174 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001175 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001176 }
1177 DCHECK_EQ(bytes_written, bytes_read);
1178 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1179 return true;
1180}
1181
Sen Jiang8371c1c2018-02-01 13:46:39 -08001182bool DeltaPerformer::ValidateSourceHash(const brillo::Blob& calculated_hash,
1183 const InstallOperation& operation,
1184 const FileDescriptorPtr source_fd,
1185 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001186 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1187 operation.src_sha256_hash().end());
1188 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001189 LOG(ERROR) << "The hash of the source data on disk for this operation "
1190 << "doesn't match the expected value. This could mean that the "
1191 << "delta update payload was targeted for another version, or "
1192 << "that the source partition was modified after it was "
1193 << "installed, for example, by mounting a filesystem.";
1194 LOG(ERROR) << "Expected: sha256|hex = "
1195 << base::HexEncode(expected_source_hash.data(),
1196 expected_source_hash.size());
1197 LOG(ERROR) << "Calculated: sha256|hex = "
1198 << base::HexEncode(calculated_hash.data(),
1199 calculated_hash.size());
1200
1201 vector<string> source_extents;
1202 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001203 source_extents.push_back(
1204 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1205 static_cast<uint64_t>(ext.start_block()),
1206 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001207 }
1208 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1209 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001210
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001211 // Log remount history if this device is an ext4 partition.
1212 LogMountHistory(source_fd);
1213
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001214 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001215 return false;
1216 }
1217 return true;
1218}
1219
Allie Wood9f6f0a52015-03-30 11:25:47 -07001220bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001221 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001222 if (operation.has_src_length())
1223 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1224 if (operation.has_dst_length())
1225 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1226
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001227 TEST_AND_RETURN_FALSE(source_fd_ != nullptr);
1228
Alessio Balsini8d384312019-11-26 11:46:33 +00001229 // The device may optimize the SOURCE_COPY operation.
1230 // Being this a device-specific optimization let DynamicPartitionController
1231 // decide it the operation should be skipped.
Yifan Hong6eec9952019-12-04 13:12:01 -08001232 const PartitionUpdate& partition = partitions_[current_partition_];
Alessio Balsini8d384312019-11-26 11:46:33 +00001233 const auto& partition_control = boot_control_->GetDynamicPartitionControl();
Yifan Hongf5261562020-03-10 10:28:10 -07001234
1235 InstallOperation buf;
1236 bool should_optimize = partition_control->OptimizeOperation(
1237 partition.partition_name(), operation, &buf);
1238 const InstallOperation& optimized = should_optimize ? buf : operation;
Alessio Balsini8d384312019-11-26 11:46:33 +00001239
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001240 if (operation.has_src_sha256_hash()) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001241 bool read_ok;
Alex Deymo51c264e2016-11-04 15:49:53 -07001242 brillo::Blob source_hash;
1243 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1244 operation.src_sha256_hash().end());
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001245
Alex Deymo51c264e2016-11-04 15:49:53 -07001246 // We fall back to use the error corrected device if the hash of the raw
1247 // device doesn't match or there was an error reading the source partition.
1248 // Note that this code will also fall back if writing the target partition
1249 // fails.
Yifan Hongf5261562020-03-10 10:28:10 -07001250 if (should_optimize) {
1251 // Hash operation.src_extents(), then copy optimized.src_extents to
1252 // optimized.dst_extents.
1253 read_ok =
1254 fd_utils::ReadAndHashExtents(
1255 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1256 fd_utils::CopyAndHashExtents(source_fd_,
1257 optimized.src_extents(),
1258 target_fd_,
1259 optimized.dst_extents(),
1260 block_size_,
1261 nullptr /* skip hashing */);
Alessio Balsini8d384312019-11-26 11:46:33 +00001262 } else {
1263 read_ok = fd_utils::CopyAndHashExtents(source_fd_,
1264 operation.src_extents(),
1265 target_fd_,
1266 operation.dst_extents(),
1267 block_size_,
1268 &source_hash);
1269 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001270 if (read_ok && expected_source_hash == source_hash)
1271 return true;
1272
1273 if (!OpenCurrentECCPartition()) {
1274 // The following function call will return false since the source hash
1275 // mismatches, but we still want to call it so it prints the appropriate
1276 // log message.
1277 return ValidateSourceHash(source_hash, operation, source_fd_, error);
1278 }
1279
1280 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1281 << base::HexEncode(source_hash.data(), source_hash.size())
1282 << ", expected "
1283 << base::HexEncode(expected_source_hash.data(),
1284 expected_source_hash.size());
1285
Yifan Hongf5261562020-03-10 10:28:10 -07001286 if (should_optimize) {
Alessio Balsini8d384312019-11-26 11:46:33 +00001287 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
1288 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash));
Yifan Hongf5261562020-03-10 10:28:10 -07001289 TEST_AND_RETURN_FALSE(
1290 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1291 optimized.src_extents(),
1292 target_fd_,
1293 optimized.dst_extents(),
1294 block_size_,
1295 nullptr /* skip hashing */));
Alessio Balsini8d384312019-11-26 11:46:33 +00001296 } else {
1297 TEST_AND_RETURN_FALSE(
1298 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1299 operation.src_extents(),
1300 target_fd_,
1301 operation.dst_extents(),
1302 block_size_,
1303 &source_hash));
1304 }
Alex Deymo51c264e2016-11-04 15:49:53 -07001305 TEST_AND_RETURN_FALSE(
1306 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error));
1307 // At this point reading from the the error corrected device worked, but
1308 // reading from the raw device failed, so this is considered a recovered
1309 // failure.
1310 source_ecc_recovered_failures_++;
1311 } else {
1312 // When the operation doesn't include a source hash, we attempt the error
1313 // corrected device first since we can't verify the block in the raw device
1314 // at this point, but we fall back to the raw device since the error
1315 // corrected device can be shorter or not available.
Alessio Balsini8d384312019-11-26 11:46:33 +00001316
Alex Deymo51c264e2016-11-04 15:49:53 -07001317 if (OpenCurrentECCPartition() &&
1318 fd_utils::CopyAndHashExtents(source_ecc_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001319 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001320 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001321 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001322 block_size_,
1323 nullptr)) {
1324 return true;
1325 }
1326 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001327 optimized.src_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001328 target_fd_,
Yifan Hongf5261562020-03-10 10:28:10 -07001329 optimized.dst_extents(),
Alex Deymo51c264e2016-11-04 15:49:53 -07001330 block_size_,
1331 nullptr));
1332 }
Allie Wood9f6f0a52015-03-30 11:25:47 -07001333 return true;
1334}
1335
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001336FileDescriptorPtr DeltaPerformer::ChooseSourceFD(
1337 const InstallOperation& operation, ErrorCode* error) {
Hridya Valsarajue69ca5f2019-02-25 22:33:56 -08001338 if (source_fd_ == nullptr) {
1339 LOG(ERROR) << "ChooseSourceFD fail: source_fd_ == nullptr";
1340 return nullptr;
1341 }
1342
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001343 if (!operation.has_src_sha256_hash()) {
1344 // When the operation doesn't include a source hash, we attempt the error
1345 // corrected device first since we can't verify the block in the raw device
1346 // at this point, but we first need to make sure all extents are readable
1347 // since the error corrected device can be shorter or not available.
1348 if (OpenCurrentECCPartition() &&
1349 fd_utils::ReadAndHashExtents(
1350 source_ecc_fd_, operation.src_extents(), block_size_, nullptr)) {
1351 return source_ecc_fd_;
1352 }
1353 return source_fd_;
1354 }
1355
1356 brillo::Blob source_hash;
1357 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1358 operation.src_sha256_hash().end());
1359 if (fd_utils::ReadAndHashExtents(
1360 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1361 source_hash == expected_source_hash) {
1362 return source_fd_;
1363 }
1364 // We fall back to use the error corrected device if the hash of the raw
1365 // device doesn't match or there was an error reading the source partition.
1366 if (!OpenCurrentECCPartition()) {
1367 // The following function call will return false since the source hash
1368 // mismatches, but we still want to call it so it prints the appropriate
1369 // log message.
1370 ValidateSourceHash(source_hash, operation, source_fd_, error);
1371 return nullptr;
1372 }
1373 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1374 << base::HexEncode(source_hash.data(), source_hash.size())
1375 << ", expected "
1376 << base::HexEncode(expected_source_hash.data(),
1377 expected_source_hash.size());
1378
1379 if (fd_utils::ReadAndHashExtents(
1380 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash) &&
1381 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error)) {
1382 // At this point reading from the the error corrected device worked, but
1383 // reading from the raw device failed, so this is considered a recovered
1384 // failure.
1385 source_ecc_recovered_failures_++;
1386 return source_ecc_fd_;
1387 }
1388 return nullptr;
1389}
1390
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001391bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1392 const RepeatedPtrField<Extent>& extents,
1393 uint64_t block_size,
1394 uint64_t full_length,
1395 string* positions_string) {
1396 string ret;
1397 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001398 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001399 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001400 uint64_t this_length =
1401 min(full_length - length,
1402 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001403 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001404 length += this_length;
1405 }
1406 TEST_AND_RETURN_FALSE(length == full_length);
1407 if (!ret.empty())
1408 ret.resize(ret.size() - 1); // Strip trailing comma off
1409 *positions_string = ret;
1410 return true;
1411}
1412
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001413bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001414 // Since we delete data off the beginning of the buffer as we use it,
1415 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001416 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1417 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001418
1419 string input_positions;
1420 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1421 block_size_,
1422 operation.src_length(),
1423 &input_positions));
1424 string output_positions;
1425 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1426 block_size_,
1427 operation.dst_length(),
1428 &output_positions));
1429
Sen Jiang7a659092016-05-10 15:31:46 -07001430 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1431 target_path_.c_str(),
1432 buffer_.data(),
1433 buffer_.size(),
1434 input_positions.c_str(),
1435 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001436 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001437
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001438 if (operation.dst_length() % block_size_) {
1439 // Zero out rest of final block.
1440 // TODO(adlr): build this into bspatch; it's more efficient that way.
1441 const Extent& last_extent =
1442 operation.dst_extents(operation.dst_extents_size() - 1);
1443 const uint64_t end_byte =
1444 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1445 const uint64_t begin_byte =
1446 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001447 brillo::Blob zeros(end_byte - begin_byte);
Amin Hassanid87304c2017-08-29 11:40:03 -07001448 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1449 target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001450 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001451 return true;
1452}
1453
Amin Hassanid9cb2902017-09-20 12:11:39 -07001454namespace {
1455
1456class BsdiffExtentFile : public bsdiff::FileInterface {
1457 public:
1458 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader, size_t size)
1459 : BsdiffExtentFile(std::move(reader), nullptr, size) {}
1460 BsdiffExtentFile(std::unique_ptr<ExtentWriter> writer, size_t size)
1461 : BsdiffExtentFile(nullptr, std::move(writer), size) {}
1462
1463 ~BsdiffExtentFile() override = default;
1464
1465 bool Read(void* buf, size_t count, size_t* bytes_read) override {
1466 TEST_AND_RETURN_FALSE(reader_->Read(buf, count));
1467 *bytes_read = count;
1468 offset_ += count;
1469 return true;
1470 }
1471
1472 bool Write(const void* buf, size_t count, size_t* bytes_written) override {
1473 TEST_AND_RETURN_FALSE(writer_->Write(buf, count));
1474 *bytes_written = count;
1475 offset_ += count;
1476 return true;
1477 }
1478
1479 bool Seek(off_t pos) override {
1480 if (reader_ != nullptr) {
1481 TEST_AND_RETURN_FALSE(reader_->Seek(pos));
1482 offset_ = pos;
1483 } else {
1484 // For writes technically there should be no change of position, or it
1485 // should be equivalent of current offset.
1486 TEST_AND_RETURN_FALSE(offset_ == static_cast<uint64_t>(pos));
1487 }
1488 return true;
1489 }
1490
Sen Jiang5e1af982018-11-01 15:01:45 -07001491 bool Close() override { return true; }
Amin Hassanid9cb2902017-09-20 12:11:39 -07001492
1493 bool GetSize(uint64_t* size) override {
1494 *size = size_;
1495 return true;
1496 }
1497
1498 private:
1499 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader,
1500 std::unique_ptr<ExtentWriter> writer,
1501 size_t size)
1502 : reader_(std::move(reader)),
1503 writer_(std::move(writer)),
1504 size_(size),
1505 offset_(0) {}
1506
1507 std::unique_ptr<ExtentReader> reader_;
1508 std::unique_ptr<ExtentWriter> writer_;
1509 uint64_t size_;
1510 uint64_t offset_;
1511
1512 DISALLOW_COPY_AND_ASSIGN(BsdiffExtentFile);
1513};
1514
1515} // namespace
1516
Allie Wood9f6f0a52015-03-30 11:25:47 -07001517bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001518 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001519 // Since we delete data off the beginning of the buffer as we use it,
1520 // the data we need should be exactly at the beginning of the buffer.
1521 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1522 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1523 if (operation.has_src_length())
1524 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1525 if (operation.has_dst_length())
1526 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1527
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001528 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1529 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001530
Amin Hassanid9cb2902017-09-20 12:11:39 -07001531 auto reader = std::make_unique<DirectExtentReader>();
1532 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001533 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassanid9cb2902017-09-20 12:11:39 -07001534 auto src_file = std::make_unique<BsdiffExtentFile>(
1535 std::move(reader),
1536 utils::BlocksInExtents(operation.src_extents()) * block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001537
Amin Hassanid9cb2902017-09-20 12:11:39 -07001538 auto writer = std::make_unique<DirectExtentWriter>();
1539 TEST_AND_RETURN_FALSE(
1540 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1541 auto dst_file = std::make_unique<BsdiffExtentFile>(
1542 std::move(writer),
1543 utils::BlocksInExtents(operation.dst_extents()) * block_size_);
1544
1545 TEST_AND_RETURN_FALSE(bsdiff::bspatch(std::move(src_file),
1546 std::move(dst_file),
Sen Jiang7a659092016-05-10 15:31:46 -07001547 buffer_.data(),
Amin Hassanid9cb2902017-09-20 12:11:39 -07001548 buffer_.size()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001549 DiscardBuffer(true, buffer_.size());
1550 return true;
1551}
1552
Amin Hassani02855c22017-09-06 22:34:50 -07001553namespace {
1554
1555// A class to be passed to |puffpatch| for reading from |source_fd_| and writing
1556// into |target_fd_|.
1557class PuffinExtentStream : public puffin::StreamInterface {
1558 public:
1559 // Constructor for creating a stream for reading from an |ExtentReader|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001560 PuffinExtentStream(std::unique_ptr<ExtentReader> reader, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001561 : PuffinExtentStream(std::move(reader), nullptr, size) {}
1562
1563 // Constructor for creating a stream for writing to an |ExtentWriter|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001564 PuffinExtentStream(std::unique_ptr<ExtentWriter> writer, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001565 : PuffinExtentStream(nullptr, std::move(writer), size) {}
1566
1567 ~PuffinExtentStream() override = default;
1568
Amin Hassani678a68f2018-02-28 11:54:47 -08001569 bool GetSize(uint64_t* size) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001570 *size = size_;
1571 return true;
1572 }
1573
Amin Hassani678a68f2018-02-28 11:54:47 -08001574 bool GetOffset(uint64_t* offset) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001575 *offset = offset_;
1576 return true;
1577 }
1578
Amin Hassani678a68f2018-02-28 11:54:47 -08001579 bool Seek(uint64_t offset) override {
Amin Hassani02855c22017-09-06 22:34:50 -07001580 if (is_read_) {
1581 TEST_AND_RETURN_FALSE(reader_->Seek(offset));
1582 offset_ = offset;
1583 } else {
1584 // For writes technically there should be no change of position, or it
1585 // should equivalent of current offset.
1586 TEST_AND_RETURN_FALSE(offset_ == offset);
1587 }
1588 return true;
1589 }
1590
1591 bool Read(void* buffer, size_t count) override {
1592 TEST_AND_RETURN_FALSE(is_read_);
1593 TEST_AND_RETURN_FALSE(reader_->Read(buffer, count));
1594 offset_ += count;
1595 return true;
1596 }
1597
1598 bool Write(const void* buffer, size_t count) override {
1599 TEST_AND_RETURN_FALSE(!is_read_);
1600 TEST_AND_RETURN_FALSE(writer_->Write(buffer, count));
1601 offset_ += count;
1602 return true;
1603 }
1604
Sen Jiang5e1af982018-11-01 15:01:45 -07001605 bool Close() override { return true; }
Amin Hassani02855c22017-09-06 22:34:50 -07001606
1607 private:
1608 PuffinExtentStream(std::unique_ptr<ExtentReader> reader,
1609 std::unique_ptr<ExtentWriter> writer,
Amin Hassani678a68f2018-02-28 11:54:47 -08001610 uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001611 : reader_(std::move(reader)),
1612 writer_(std::move(writer)),
1613 size_(size),
1614 offset_(0),
1615 is_read_(reader_ ? true : false) {}
1616
1617 std::unique_ptr<ExtentReader> reader_;
1618 std::unique_ptr<ExtentWriter> writer_;
1619 uint64_t size_;
1620 uint64_t offset_;
1621 bool is_read_;
1622
1623 DISALLOW_COPY_AND_ASSIGN(PuffinExtentStream);
1624};
1625
1626} // namespace
1627
1628bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
1629 ErrorCode* error) {
1630 // Since we delete data off the beginning of the buffer as we use it,
1631 // the data we need should be exactly at the beginning of the buffer.
1632 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1633 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1634
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001635 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1636 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Amin Hassani02855c22017-09-06 22:34:50 -07001637
1638 auto reader = std::make_unique<DirectExtentReader>();
1639 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001640 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassani02855c22017-09-06 22:34:50 -07001641 puffin::UniqueStreamPtr src_stream(new PuffinExtentStream(
1642 std::move(reader),
1643 utils::BlocksInExtents(operation.src_extents()) * block_size_));
1644
1645 auto writer = std::make_unique<DirectExtentWriter>();
1646 TEST_AND_RETURN_FALSE(
1647 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1648 puffin::UniqueStreamPtr dst_stream(new PuffinExtentStream(
1649 std::move(writer),
1650 utils::BlocksInExtents(operation.dst_extents()) * block_size_));
1651
1652 const size_t kMaxCacheSize = 5 * 1024 * 1024; // Total 5MB cache.
1653 TEST_AND_RETURN_FALSE(puffin::PuffPatch(std::move(src_stream),
1654 std::move(dst_stream),
1655 buffer_.data(),
1656 buffer_.size(),
1657 kMaxCacheSize));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001658 DiscardBuffer(true, buffer_.size());
Alex Deymoa12ee112015-08-12 22:19:32 -07001659 return true;
1660}
Darin Petkovd7061ab2010-10-06 14:37:09 -07001661
Darin Petkovd7061ab2010-10-06 14:37:09 -07001662bool DeltaPerformer::ExtractSignatureMessageFromOperation(
1663 const InstallOperation& operation) {
1664 if (operation.type() != InstallOperation::REPLACE ||
1665 !manifest_.has_signatures_offset() ||
1666 manifest_.signatures_offset() != operation.data_offset()) {
1667 return false;
1668 }
1669 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1670 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001671 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1672 return true;
1673}
1674
1675bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001676 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1677 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1678 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001679 signatures_message_data_.assign(
Amin Hassani008c4582019-01-13 16:22:47 -08001680 buffer_.begin(), buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001681
1682 // Save the signature blob because if the update is interrupted after the
1683 // download phase we don't go through this path anymore. Some alternatives to
1684 // consider:
1685 //
1686 // 1. On resume, re-download the signature blob from the server and re-verify
1687 // it.
1688 //
1689 // 2. Verify the signature as soon as it's received and don't checkpoint the
1690 // blob and the signed sha-256 context.
Amin Hassani008c4582019-01-13 16:22:47 -08001691 LOG_IF(WARNING,
1692 !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Sen Jiang9b2f1782019-01-24 14:27:50 -08001693 signatures_message_data_))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001694 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001695
Darin Petkovd7061ab2010-10-06 14:37:09 -07001696 LOG(INFO) << "Extracted signature data of size "
1697 << manifest_.signatures_size() << " at "
1698 << manifest_.signatures_offset();
1699 return true;
1700}
1701
Sen Jiang08c6da12019-01-07 18:28:56 -08001702bool DeltaPerformer::GetPublicKey(string* out_public_key) {
1703 out_public_key->clear();
David Zeuthene7f89172013-10-31 10:21:04 -07001704
Sen Jiang08c6da12019-01-07 18:28:56 -08001705 if (utils::FileExists(public_key_path_.c_str())) {
1706 LOG(INFO) << "Verifying using public key: " << public_key_path_;
1707 return utils::ReadFile(public_key_path_, out_public_key);
1708 }
1709
1710 // If this is an official build then we are not allowed to use public key from
1711 // Omaha response.
1712 if (!hardware_->IsOfficialBuild() && !install_plan_->public_key_rsa.empty()) {
1713 LOG(INFO) << "Verifying using public key from Omaha response.";
1714 return brillo::data_encoding::Base64Decode(install_plan_->public_key_rsa,
1715 out_public_key);
1716 }
Tianjie Xu7a78d632019-10-08 16:32:39 -07001717 LOG(INFO) << "No public keys found for verification.";
David Zeuthene7f89172013-10-31 10:21:04 -07001718 return true;
1719}
1720
Tianjie Xu7a78d632019-10-08 16:32:39 -07001721std::pair<std::unique_ptr<PayloadVerifier>, bool>
1722DeltaPerformer::CreatePayloadVerifier() {
1723 if (utils::FileExists(update_certificates_path_.c_str())) {
1724 LOG(INFO) << "Verifying using certificates: " << update_certificates_path_;
1725 return {
1726 PayloadVerifier::CreateInstanceFromZipPath(update_certificates_path_),
1727 true};
1728 }
1729
1730 string public_key;
1731 if (!GetPublicKey(&public_key)) {
1732 LOG(ERROR) << "Failed to read public key";
1733 return {nullptr, true};
1734 }
1735
1736 // Skips the verification if the public key is empty.
1737 if (public_key.empty()) {
1738 return {nullptr, false};
1739 }
1740 return {PayloadVerifier::CreateInstance(public_key), true};
1741}
1742
Gilad Arnold21504f02013-05-24 08:51:22 -07001743ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001744 // Perform assorted checks to sanity check the manifest, make sure it
1745 // matches data from other sources, and that it is a supported version.
Alex Deymo64d98782016-02-05 18:03:48 -08001746 bool has_old_fields =
1747 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1748 for (const PartitionUpdate& partition : manifest_.partitions()) {
1749 has_old_fields = has_old_fields || partition.has_old_partition_info();
1750 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001751
Alex Deymo64d98782016-02-05 18:03:48 -08001752 // The presence of an old partition hash is the sole indicator for a delta
1753 // update.
1754 InstallPayloadType actual_payload_type =
1755 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1756
Sen Jiangcdd52062017-05-18 15:33:10 -07001757 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001758 LOG(INFO) << "Detected a '"
1759 << InstallPayloadTypeToString(actual_payload_type)
1760 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001761 payload_->type = actual_payload_type;
1762 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001763 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001764 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001765 << "' payload but the downloaded manifest contains a '"
1766 << InstallPayloadTypeToString(actual_payload_type)
1767 << "' payload.";
1768 return ErrorCode::kPayloadMismatchedType;
1769 }
Alex Deymo64d98782016-02-05 18:03:48 -08001770 // Check that the minor version is compatible.
Tianjied3865d12020-06-03 15:25:17 -07001771 // TODO(xunchang) increment minor version & add check for partial update
Alex Deymo64d98782016-02-05 18:03:48 -08001772 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001773 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1774 LOG(ERROR) << "Manifest contains minor version "
1775 << manifest_.minor_version()
1776 << ", but all full payloads should have version "
1777 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001778 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001779 }
1780 } else {
Sen Jiangf1236632018-05-11 16:03:23 -07001781 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1782 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001783 LOG(ERROR) << "Manifest contains minor version "
1784 << manifest_.minor_version()
Sen Jiangf1236632018-05-11 16:03:23 -07001785 << " not in the range of supported minor versions ["
1786 << kMinSupportedMinorPayloadVersion << ", "
1787 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001788 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001789 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001790 }
1791
Sen Jiang3e728fe2015-11-05 11:37:23 -08001792 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
Amin Hassani008c4582019-01-13 16:22:47 -08001793 if (manifest_.has_old_rootfs_info() || manifest_.has_new_rootfs_info() ||
1794 manifest_.has_old_kernel_info() || manifest_.has_new_kernel_info() ||
Sen Jiang3e728fe2015-11-05 11:37:23 -08001795 manifest_.install_operations_size() != 0 ||
1796 manifest_.kernel_install_operations_size() != 0) {
1797 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1798 << "major payload version 1, but the payload major version is "
1799 << major_payload_version_;
1800 return ErrorCode::kPayloadMismatchedType;
1801 }
1802 }
1803
Sen Jiang8e768e92017-06-28 17:13:19 -07001804 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1805 LOG(ERROR) << "The current OS build timestamp ("
1806 << hardware_->GetBuildTimestamp()
1807 << ") is newer than the maximum timestamp in the manifest ("
1808 << manifest_.max_timestamp() << ")";
Tianjie Xu4ad3af62019-10-30 11:59:45 -07001809 if (!hardware_->AllowDowngrade()) {
1810 return ErrorCode::kPayloadTimestampError;
1811 }
1812 LOG(INFO) << "The current OS build allows downgrade, continuing to apply"
1813 " the payload with an older timestamp.";
Sen Jiang8e768e92017-06-28 17:13:19 -07001814 }
1815
Yifan Hongd4db07e2018-10-18 17:46:27 -07001816 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
1817 if (manifest_.has_dynamic_partition_metadata()) {
1818 LOG(ERROR)
1819 << "Should not contain dynamic_partition_metadata for major version "
1820 << kChromeOSMajorPayloadVersion
1821 << ". Please use major version 2 or above.";
1822 return ErrorCode::kPayloadMismatchedType;
1823 }
1824 }
1825
Gilad Arnold21504f02013-05-24 08:51:22 -07001826 // TODO(garnold) we should be adding more and more manifest checks, such as
1827 // partition boundaries etc (see chromium-os:37661).
1828
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001829 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001830}
1831
David Zeuthena99981f2013-04-29 13:42:47 -07001832ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001833 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001834 if (!operation.data_sha256_hash().size()) {
1835 if (!operation.data_length()) {
1836 // Operations that do not have any data blob won't have any operation hash
1837 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001838 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001839 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001840 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001841 }
1842
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001843 // No hash is present for an operation that has data blobs. This shouldn't
1844 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001845 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001846 // hashes. So if it happens it means either we've turned operation hash
1847 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001848 // One caveat though: The last operation is a dummy signature operation
1849 // that doesn't have a hash at the time the manifest is created. So we
1850 // should not complaint about that operation. This operation can be
1851 // recognized by the fact that it's offset is mentioned in the manifest.
1852 if (manifest_.signatures_offset() &&
1853 manifest_.signatures_offset() == operation.data_offset()) {
1854 LOG(INFO) << "Skipping hash verification for signature operation "
1855 << next_operation_num_ + 1;
1856 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001857 if (install_plan_->hash_checks_mandatory) {
1858 LOG(ERROR) << "Missing mandatory operation hash for operation "
1859 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001860 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001861 }
1862
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001863 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1864 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001865 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001866 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001867 }
1868
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001869 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001870 expected_op_hash.assign(operation.data_sha256_hash().data(),
1871 (operation.data_sha256_hash().data() +
1872 operation.data_sha256_hash().size()));
1873
Sen Jiang2703ef42017-03-16 13:36:21 -07001874 brillo::Blob calculated_op_hash;
1875 if (!HashCalculator::RawHashOfBytes(
1876 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001877 LOG(ERROR) << "Unable to compute actual hash of operation "
1878 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001879 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001880 }
1881
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001882 if (calculated_op_hash != expected_op_hash) {
1883 LOG(ERROR) << "Hash verification failed for operation "
1884 << next_operation_num_ << ". Expected hash = ";
1885 utils::HexDumpVector(expected_op_hash);
1886 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1887 << " bytes at offset: " << operation.data_offset() << " = ";
1888 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001889 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001890 }
1891
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001892 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001893}
1894
Amin Hassani008c4582019-01-13 16:22:47 -08001895#define TEST_AND_RETURN_VAL(_retval, _condition) \
1896 do { \
1897 if (!(_condition)) { \
1898 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1899 return _retval; \
1900 } \
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001901 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001902
David Zeuthena99981f2013-04-29 13:42:47 -07001903ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001904 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001905 const uint64_t update_check_response_size) {
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001906 // Verifies the download size.
Sen Jiang3a25dc22019-01-10 14:14:41 -08001907 if (update_check_response_size !=
1908 metadata_size_ + metadata_signature_size_ + buffer_offset_) {
1909 LOG(ERROR) << "update_check_response_size (" << update_check_response_size
1910 << ") doesn't match metadata_size (" << metadata_size_
1911 << ") + metadata_signature_size (" << metadata_signature_size_
1912 << ") + buffer_offset (" << buffer_offset_ << ").";
1913 return ErrorCode::kPayloadSizeMismatchError;
1914 }
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001915
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001916 // Verifies the payload hash.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001917 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Sen Jiang2703ef42017-03-16 13:36:21 -07001918 !payload_hash_calculator_.raw_hash().empty());
1919 TEST_AND_RETURN_VAL(
1920 ErrorCode::kPayloadHashMismatchError,
1921 payload_hash_calculator_.raw_hash() == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001922
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001923 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001924 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001925 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001926 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
xunchangcda3c032019-03-26 15:41:14 -07001927 hash_data.size() == kSHA256Size);
Alex Deymob552a682015-09-30 09:36:49 -07001928
Tianjie Xu7a78d632019-10-08 16:32:39 -07001929 auto [payload_verifier, perform_verification] = CreatePayloadVerifier();
1930 if (!perform_verification) {
1931 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
1932 return ErrorCode::kSuccess;
1933 }
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001934 if (!payload_verifier) {
Tianjie Xu7a78d632019-10-08 16:32:39 -07001935 LOG(ERROR) << "Failed to create the payload verifier.";
Tianjie Xu6cf830b2019-09-30 11:31:49 -07001936 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
1937 }
1938 if (!payload_verifier->VerifySignature(signatures_message_data_, hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001939 // The autoupdate_CatchBadSignatures test checks for this string
1940 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001941 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001942 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001943 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001944
David Zeuthene7f89172013-10-31 10:21:04 -07001945 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001946 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001947}
1948
Sen Jiangf6813802015-11-03 21:27:29 -08001949void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1950 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001951 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001952 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001953 buffer_offset_ += buffer_.size();
1954
1955 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001956 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1957 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001958
1959 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001960 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001961}
1962
Darin Petkov0406e402010-10-06 21:33:11 -07001963bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001964 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001965 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001966 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
Amin Hassani008c4582019-01-13 16:22:47 -08001967 next_operation != kUpdateStateOperationInvalid && next_operation > 0))
Alex Deymo3310b222015-03-30 15:59:07 -07001968 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001969
1970 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001971 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1972 !interrupted_hash.empty() &&
1973 interrupted_hash == update_check_response_hash))
1974 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001975
Darin Petkov61426142010-10-08 11:04:55 -07001976 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001977 // Note that storing this value is optional, but if it is there it should not
1978 // be more than the limit.
1979 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1980 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001981 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001982
Darin Petkov0406e402010-10-06 21:33:11 -07001983 // Sanity check the rest.
1984 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001985 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1986 next_data_offset >= 0))
1987 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001988
Darin Petkov437adc42010-10-07 13:12:24 -07001989 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001990 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1991 !sha256_context.empty()))
1992 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001993
1994 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001995 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1996 manifest_metadata_size > 0))
1997 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001998
Alex Deymof25eb492016-02-26 00:20:08 -08001999 int64_t manifest_signature_size = 0;
2000 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
2001 &manifest_signature_size) &&
2002 manifest_signature_size >= 0))
2003 return false;
2004
Darin Petkov0406e402010-10-06 21:33:11 -07002005 return true;
2006}
2007
Yifan Hong55c2bfe2020-01-13 17:01:19 -08002008bool DeltaPerformer::ResetUpdateProgress(
2009 PrefsInterface* prefs,
2010 bool quick,
2011 bool skip_dynamic_partititon_metadata_updated) {
Darin Petkov0406e402010-10-06 21:33:11 -07002012 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
2013 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07002014 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07002015 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07002016 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07002017 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
2018 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07002019 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07002020 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08002021 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07002022 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07002023 prefs->Delete(kPrefsPostInstallSucceeded);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -07002024 prefs->Delete(kPrefsVerityWritten);
Yifan Hong55c2bfe2020-01-13 17:01:19 -08002025
2026 if (!skip_dynamic_partititon_metadata_updated) {
2027 LOG(INFO) << "Resetting recorded hash for prepared partitions.";
2028 prefs->Delete(kPrefsDynamicPartitionMetadataUpdated);
2029 }
Darin Petkov9b230572010-10-08 10:20:09 -07002030 }
Darin Petkov73058b42010-10-06 16:32:19 -07002031 return true;
2032}
2033
Sen Jiang3a25dc22019-01-10 14:14:41 -08002034bool DeltaPerformer::CheckpointUpdateProgress(bool force) {
Sen Jiang53c2ec52019-01-10 15:27:59 -08002035 base::TimeTicks curr_time = base::TimeTicks::Now();
Sen Jiang3a25dc22019-01-10 14:14:41 -08002036 if (force || curr_time > update_checkpoint_time_) {
Colin Howes0e452c92018-11-02 13:18:44 -07002037 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
2038 } else {
2039 return false;
2040 }
2041
Darin Petkov9c0baf82010-10-07 13:44:48 -07002042 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07002043 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07002044 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07002045 ResetUpdateProgress(prefs_, true);
Amin Hassani008c4582019-01-13 16:22:47 -08002046 TEST_AND_RETURN_FALSE(prefs_->SetString(
2047 kPrefsUpdateStateSHA256Context, payload_hash_calculator_.GetContext()));
Sen Jiangf6813802015-11-03 21:27:29 -08002048 TEST_AND_RETURN_FALSE(
2049 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
2050 signed_hash_calculator_.GetContext()));
Amin Hassani008c4582019-01-13 16:22:47 -08002051 TEST_AND_RETURN_FALSE(
2052 prefs_->SetInt64(kPrefsUpdateStateNextDataOffset, buffer_offset_));
Darin Petkov0406e402010-10-06 21:33:11 -07002053 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07002054
2055 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07002056 size_t partition_index = current_partition_;
2057 while (next_operation_num_ >= acc_num_operations_[partition_index])
2058 partition_index++;
Amin Hassani008c4582019-01-13 16:22:47 -08002059 const size_t partition_operation_num =
2060 next_operation_num_ -
2061 (partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07002062 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07002063 partitions_[partition_index].operations(partition_operation_num);
Amin Hassani008c4582019-01-13 16:22:47 -08002064 TEST_AND_RETURN_FALSE(
2065 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, op.data_length()));
David Zeuthen41996ad2013-09-24 15:43:24 -07002066 } else {
Amin Hassani008c4582019-01-13 16:22:47 -08002067 TEST_AND_RETURN_FALSE(
2068 prefs_->SetInt64(kPrefsUpdateStateNextDataLength, 0));
David Zeuthen41996ad2013-09-24 15:43:24 -07002069 }
Darin Petkov0406e402010-10-06 21:33:11 -07002070 }
Amin Hassani008c4582019-01-13 16:22:47 -08002071 TEST_AND_RETURN_FALSE(
2072 prefs_->SetInt64(kPrefsUpdateStateNextOperation, next_operation_num_));
Darin Petkov73058b42010-10-06 16:32:19 -07002073 return true;
2074}
2075
Darin Petkov9b230572010-10-08 10:20:09 -07002076bool DeltaPerformer::PrimeUpdateState() {
2077 CHECK(manifest_valid_);
Darin Petkov9b230572010-10-08 10:20:09 -07002078
2079 int64_t next_operation = kUpdateStateOperationInvalid;
2080 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
Amin Hassani008c4582019-01-13 16:22:47 -08002081 next_operation == kUpdateStateOperationInvalid || next_operation <= 0) {
Darin Petkov9b230572010-10-08 10:20:09 -07002082 // Initiating a new update, no more state needs to be initialized.
2083 return true;
2084 }
2085 next_operation_num_ = next_operation;
2086
2087 // Resuming an update -- load the rest of the update state.
2088 int64_t next_data_offset = -1;
Amin Hassani008c4582019-01-13 16:22:47 -08002089 TEST_AND_RETURN_FALSE(
2090 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
2091 next_data_offset >= 0);
Darin Petkov9b230572010-10-08 10:20:09 -07002092 buffer_offset_ = next_data_offset;
2093
Darin Petkov4f0a07b2011-05-25 16:47:20 -07002094 // The signed hash context and the signature blob may be empty if the
2095 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08002096 string signed_hash_context;
2097 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
2098 &signed_hash_context)) {
2099 TEST_AND_RETURN_FALSE(
2100 signed_hash_calculator_.SetContext(signed_hash_context));
2101 }
2102
Sen Jiang9b2f1782019-01-24 14:27:50 -08002103 prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signatures_message_data_);
Darin Petkov9b230572010-10-08 10:20:09 -07002104
2105 string hash_context;
Amin Hassani008c4582019-01-13 16:22:47 -08002106 TEST_AND_RETURN_FALSE(
2107 prefs_->GetString(kPrefsUpdateStateSHA256Context, &hash_context) &&
2108 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07002109
2110 int64_t manifest_metadata_size = 0;
Amin Hassani008c4582019-01-13 16:22:47 -08002111 TEST_AND_RETURN_FALSE(
2112 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
2113 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08002114 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07002115
Alex Deymof25eb492016-02-26 00:20:08 -08002116 int64_t manifest_signature_size = 0;
2117 TEST_AND_RETURN_FALSE(
2118 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
2119 manifest_signature_size >= 0);
2120 metadata_signature_size_ = manifest_signature_size;
2121
Gilad Arnold8a86fa52013-01-15 12:35:05 -08002122 // Advance the download progress to reflect what doesn't need to be
2123 // re-downloaded.
2124 total_bytes_received_ += buffer_offset_;
2125
Darin Petkov61426142010-10-08 11:04:55 -07002126 // Speculatively count the resume as a failure.
2127 int64_t resumed_update_failures;
2128 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
2129 resumed_update_failures++;
2130 } else {
2131 resumed_update_failures = 1;
2132 }
2133 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07002134 return true;
2135}
2136
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002137} // namespace chromeos_update_engine