blob: 5377ee37dcc4a9406dfc2d840ea6d5527164c30b [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 <endian.h>
20#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070021#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070022
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include <algorithm>
24#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include <string>
27#include <vector>
28
Ben Chan06c76a42014-09-05 08:21:06 -070029#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070030#include <base/format_macros.h>
Ben Chan5c02c132017-06-27 07:10:36 -070031#include <base/memory/ptr_util.h>
Lann Martin39f57142017-07-14 09:18:42 -060032#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070033#include <base/strings/string_number_conversions.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070034#include <base/strings/string_util.h>
35#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060036#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070037#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070038#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070039#include <google/protobuf/repeated_field.h>
40
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/constants.h"
42#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030043#include "update_engine/common/prefs_interface.h"
44#include "update_engine/common/subprocess.h"
45#include "update_engine/common/terminator.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080046#include "update_engine/payload_consumer/bzip_extent_writer.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030047#include "update_engine/payload_consumer/download_action.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080048#include "update_engine/payload_consumer/extent_writer.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080049#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080050#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080051#endif
Alex Deymo39910dc2015-11-09 17:04:30 -080052#include "update_engine/payload_consumer/payload_constants.h"
53#include "update_engine/payload_consumer/payload_verifier.h"
54#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070055
Alex Deymo161c4a12014-05-16 15:56:21 -070056using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070057using std::min;
58using std::string;
59using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070060
61namespace chromeos_update_engine {
62
Sen Jiangb8060e42015-09-24 17:30:50 -070063const uint64_t DeltaPerformer::kDeltaVersionOffset = sizeof(kDeltaMagic);
Jay Srinivasanf4318702012-09-24 11:56:24 -070064const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070065const uint64_t DeltaPerformer::kDeltaManifestSizeOffset =
66 kDeltaVersionOffset + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -070067const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070068const uint64_t DeltaPerformer::kDeltaMetadataSignatureSizeSize = 4;
69const uint64_t DeltaPerformer::kMaxPayloadHeaderSize = 24;
Alex Deymo7a2c47e2015-11-04 00:47:12 -080070const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 2;
Sen Jiang889c65d2015-11-17 15:04:02 -080071const uint32_t DeltaPerformer::kSupportedMinorPayloadVersion = 3;
Don Garrett4d039442013-10-28 18:40:06 -070072
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;
Darin Petkovabc7bc02011-02-23 14:39:43 -080077
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070079const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070080const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080081#if USE_MTD
82const int kUbiVolumeAttachTimeout = 5 * 60;
83#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080084
85FileDescriptorPtr CreateFileDescriptor(const char* path) {
86 FileDescriptorPtr ret;
87#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080088 if (strstr(path, "/dev/ubi") == path) {
89 if (!UbiFileDescriptor::IsUbi(path)) {
90 // The volume might not have been attached at boot time.
91 int volume_no;
92 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
93 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
94 }
95 }
96 if (UbiFileDescriptor::IsUbi(path)) {
97 LOG(INFO) << path << " is a UBI device.";
98 ret.reset(new UbiFileDescriptor);
99 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800100 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800101 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800102 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800103 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800104 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800105#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800106 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800107#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700108 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800109#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800110 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700111}
112
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800113// Opens path for read/write. On success returns an open FileDescriptor
114// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700115FileDescriptorPtr OpenFile(const char* path, int mode, int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -0700116 // Try to mark the block device read-only based on the mode. Ignore any
117 // failure since this won't work when passing regular files.
118 utils::SetBlockDeviceReadOnly(path, (mode & O_ACCMODE) == O_RDONLY);
119
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800120 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800121#if USE_MTD
122 // On NAND devices, we can either read, or write, but not both. So here we
123 // use O_WRONLY.
124 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
125 mode = O_WRONLY;
126 }
127#endif
128 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800129 *err = errno;
130 PLOG(ERROR) << "Unable to open file " << path;
131 return nullptr;
132 }
133 *err = 0;
134 return fd;
135}
Alex Deymob86787c2016-05-12 18:46:25 -0700136
137// Discard the tail of the block device referenced by |fd|, from the offset
138// |data_size| until the end of the block device. Returns whether the data was
139// discarded.
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700140bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
Alex Deymob86787c2016-05-12 18:46:25 -0700141 uint64_t part_size = fd->BlockDevSize();
142 if (!part_size || part_size <= data_size)
143 return false;
144
Alex Deymo72a68d82016-06-15 16:31:04 -0700145 struct blkioctl_request {
146 int number;
147 const char* name;
148 };
149 const vector<blkioctl_request> blkioctl_requests = {
Alex Deymo72a68d82016-06-15 16:31:04 -0700150 {BLKDISCARD, "BLKDISCARD"},
Amin Hassani8f08cfc2017-06-23 12:42:00 -0700151 {BLKSECDISCARD, "BLKSECDISCARD"},
Alex Deymob86787c2016-05-12 18:46:25 -0700152#ifdef BLKZEROOUT
Alex Deymo72a68d82016-06-15 16:31:04 -0700153 {BLKZEROOUT, "BLKZEROOUT"},
Alex Deymob86787c2016-05-12 18:46:25 -0700154#endif
155 };
Alex Deymo72a68d82016-06-15 16:31:04 -0700156 for (const auto& req : blkioctl_requests) {
Alex Deymob86787c2016-05-12 18:46:25 -0700157 int error = 0;
Alex Deymo72a68d82016-06-15 16:31:04 -0700158 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
Alex Deymob86787c2016-05-12 18:46:25 -0700159 error == 0) {
160 return true;
161 }
162 LOG(WARNING) << "Error discarding the last "
163 << (part_size - data_size) / 1024 << " KiB using ioctl("
Alex Deymo72a68d82016-06-15 16:31:04 -0700164 << req.name << ")";
Alex Deymob86787c2016-05-12 18:46:25 -0700165 }
166 return false;
167}
168
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700169} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800171
172// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
173// arithmetic.
174static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
175 return part * norm / total;
176}
177
178void DeltaPerformer::LogProgress(const char* message_prefix) {
179 // Format operations total count and percentage.
180 string total_operations_str("?");
181 string completed_percentage_str("");
182 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700183 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800184 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
185 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700186 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700187 IntRatio(next_operation_num_, num_total_operations_,
188 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800189 }
190
191 // Format download total count and percentage.
192 size_t payload_size = install_plan_->payload_size;
193 string payload_size_str("?");
194 string downloaded_percentage_str("");
195 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700196 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800197 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
198 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700199 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700200 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800201 }
202
203 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
204 << "/" << total_operations_str << " operations"
205 << completed_percentage_str << ", " << total_bytes_received_
206 << "/" << payload_size_str << " bytes downloaded"
207 << downloaded_percentage_str << ", overall progress "
208 << overall_progress_ << "%";
209}
210
211void DeltaPerformer::UpdateOverallProgress(bool force_log,
212 const char* message_prefix) {
213 // Compute our download and overall progress.
214 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800215 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
216 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800217 // Only consider download progress if its total size is known; otherwise
218 // adjust the operations weight to compensate for the absence of download
219 // progress. Also, make sure to cap the download portion at
220 // kProgressDownloadWeight, in case we end up downloading more than we
221 // initially expected (this indicates a problem, but could generally happen).
222 // TODO(garnold) the correction of operations weight when we do not have the
223 // total payload size, as well as the conditional guard below, should both be
224 // eliminated once we ensure that the payload_size in the install plan is
225 // always given and is non-zero. This currently isn't the case during unit
226 // tests (see chromium-os:37969).
227 size_t payload_size = install_plan_->payload_size;
228 unsigned actual_operations_weight = kProgressOperationsWeight;
229 if (payload_size)
230 new_overall_progress += min(
231 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
232 kProgressDownloadWeight)),
233 kProgressDownloadWeight);
234 else
235 actual_operations_weight += kProgressDownloadWeight;
236
237 // Only add completed operations if their total number is known; we definitely
238 // expect an update to have at least one operation, so the expectation is that
239 // this will eventually reach |actual_operations_weight|.
240 if (num_total_operations_)
241 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
242 actual_operations_weight);
243
244 // Progress ratio cannot recede, unless our assumptions about the total
245 // payload size, total number of operations, or the monotonicity of progress
246 // is breached.
247 if (new_overall_progress < overall_progress_) {
248 LOG(WARNING) << "progress counter receded from " << overall_progress_
249 << "% down to " << new_overall_progress << "%; this is a bug";
250 force_log = true;
251 }
252 overall_progress_ = new_overall_progress;
253
254 // Update chunk index, log as needed: if forced by called, or we completed a
255 // progress chunk, or a timeout has expired.
256 base::Time curr_time = base::Time::Now();
257 unsigned curr_progress_chunk =
258 overall_progress_ * kProgressLogMaxChunks / 100;
259 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
260 curr_time > forced_progress_log_time_) {
261 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
262 LogProgress(message_prefix);
263 }
264 last_progress_chunk_ = curr_progress_chunk;
265}
266
267
Gilad Arnoldfe133932014-01-14 12:25:50 -0800268size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
269 size_t max) {
270 const size_t count = *count_p;
271 if (!count)
272 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700273 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800274 const char* bytes_start = *bytes_p;
275 const char* bytes_end = bytes_start + read_len;
276 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
277 *bytes_p = bytes_end;
278 *count_p = count - read_len;
279 return read_len;
280}
281
282
283bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
284 ErrorCode* error) {
285 if (op_result)
286 return true;
287
Alex Deymo3d009062016-05-13 15:51:25 -0700288 size_t partition_first_op_num =
289 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800290 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700291 << next_operation_num_ << ", which is the operation "
292 << next_operation_num_ - partition_first_op_num
293 << " in partition \""
294 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700295 if (*error == ErrorCode::kSuccess)
296 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800297 return false;
298}
299
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700300int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700301 int err = -CloseCurrentPartition();
Sen Jiangf6813802015-11-03 21:27:29 -0800302 LOG_IF(ERROR, !payload_hash_calculator_.Finalize() ||
303 !signed_hash_calculator_.Finalize())
304 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800305 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700306 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
307 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800308 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800309 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700310 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700311}
312
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700313int DeltaPerformer::CloseCurrentPartition() {
314 int err = 0;
315 if (source_fd_ && !source_fd_->Close()) {
316 err = errno;
317 PLOG(ERROR) << "Error closing source partition";
318 if (!err)
319 err = 1;
320 }
321 source_fd_.reset();
322 source_path_.clear();
323
324 if (target_fd_ && !target_fd_->Close()) {
325 err = errno;
326 PLOG(ERROR) << "Error closing target partition";
327 if (!err)
328 err = 1;
329 }
330 target_fd_.reset();
331 target_path_.clear();
332 return -err;
333}
334
335bool DeltaPerformer::OpenCurrentPartition() {
336 if (current_partition_ >= partitions_.size())
337 return false;
338
339 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiang889c65d2015-11-17 15:04:02 -0800340 // Open source fds if we have a delta payload with minor version >= 2.
Alex Deymo64d98782016-02-05 18:03:48 -0800341 if (install_plan_->payload_type == InstallPayloadType::kDelta &&
Sen Jiang889c65d2015-11-17 15:04:02 -0800342 GetMinorVersion() != kInPlaceMinorPayloadVersion) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700343 source_path_ = install_plan_->partitions[current_partition_].source_path;
344 int err;
345 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, &err);
346 if (!source_fd_) {
347 LOG(ERROR) << "Unable to open source partition "
348 << partition.partition_name() << " on slot "
349 << BootControlInterface::SlotName(install_plan_->source_slot)
350 << ", file " << source_path_;
351 return false;
352 }
353 }
354
355 target_path_ = install_plan_->partitions[current_partition_].target_path;
356 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700357
Amin Hassani7ecda262017-07-11 17:10:50 -0700358 int flags = O_RDWR;
359 if (!is_interactive_)
360 flags |= O_DSYNC;
361
362 LOG(INFO) << "Opening " << target_path_ << " partition with"
363 << (is_interactive_ ? "out" : "") << " O_DSYNC";
364
365 target_fd_ = OpenFile(target_path_.c_str(), flags, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700366 if (!target_fd_) {
367 LOG(ERROR) << "Unable to open target partition "
368 << partition.partition_name() << " on slot "
369 << BootControlInterface::SlotName(install_plan_->target_slot)
370 << ", file " << target_path_;
371 return false;
372 }
Alex Deymob86787c2016-05-12 18:46:25 -0700373
374 LOG(INFO) << "Applying " << partition.operations().size()
375 << " operations to partition \"" << partition.partition_name()
376 << "\"";
377
378 // Discard the end of the partition, but ignore failures.
379 DiscardPartitionTail(
380 target_fd_, install_plan_->partitions[current_partition_].target_size);
381
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700382 return true;
383}
384
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700385namespace {
386
387void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700388 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800389 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
390 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700391}
392
Alex Deymo39910dc2015-11-09 17:04:30 -0800393void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700394 for (const PartitionUpdate& partition : partitions) {
395 LogPartitionInfoHash(partition.old_partition_info(),
396 "old " + partition.partition_name());
397 LogPartitionInfoHash(partition.new_partition_info(),
398 "new " + partition.partition_name());
399 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700400}
401
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700402} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700403
Sen Jiangb8060e42015-09-24 17:30:50 -0700404bool DeltaPerformer::GetMetadataSignatureSizeOffset(
405 uint64_t* out_offset) const {
406 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
407 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
408 return true;
409 }
410 return false;
Don Garrett4d039442013-10-28 18:40:06 -0700411}
412
Sen Jiangb8060e42015-09-24 17:30:50 -0700413bool DeltaPerformer::GetManifestOffset(uint64_t* out_offset) const {
414 // Actual manifest begins right after the manifest size field or
415 // metadata signature size field if major version >= 2.
416 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
417 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
418 return true;
419 }
420 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
421 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize +
422 kDeltaMetadataSignatureSizeSize;
423 return true;
424 }
425 LOG(ERROR) << "Unknown major payload version: " << major_payload_version_;
426 return false;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700427}
428
Gilad Arnoldfe133932014-01-14 12:25:50 -0800429uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800430 return metadata_size_;
431}
432
Sen Jiangb8060e42015-09-24 17:30:50 -0700433uint64_t DeltaPerformer::GetMajorVersion() const {
434 return major_payload_version_;
435}
436
Allie Woodfdf00512015-03-02 13:34:55 -0800437uint32_t DeltaPerformer::GetMinorVersion() const {
438 if (manifest_.has_minor_version()) {
439 return manifest_.minor_version();
440 } else {
Alex Deymo64d98782016-02-05 18:03:48 -0800441 return install_plan_->payload_type == InstallPayloadType::kDelta
442 ? kSupportedMinorPayloadVersion
443 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800444 }
445}
446
Gilad Arnolddaa27402014-01-23 11:56:17 -0800447bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
448 if (!manifest_parsed_)
449 return false;
450 *out_manifest_p = manifest_;
451 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800452}
453
Sen Jiangb8060e42015-09-24 17:30:50 -0700454bool DeltaPerformer::IsHeaderParsed() const {
455 return metadata_size_ != 0;
456}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700457
Darin Petkov9574f7e2011-01-13 10:48:12 -0800458DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700459 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700460 *error = ErrorCode::kSuccess;
Sen Jiangb8060e42015-09-24 17:30:50 -0700461 uint64_t manifest_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700462
Sen Jiangb8060e42015-09-24 17:30:50 -0700463 if (!IsHeaderParsed()) {
464 // Ensure we have data to cover the major payload version.
465 if (payload.size() < kDeltaManifestSizeOffset)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800466 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700467
Gilad Arnoldfe133932014-01-14 12:25:50 -0800468 // Validate the magic string.
Sen Jiangb8060e42015-09-24 17:30:50 -0700469 if (memcmp(payload.data(), kDeltaMagic, sizeof(kDeltaMagic)) != 0) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800470 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700471 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800472 return kMetadataParseError;
473 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800474
475 // Extract the payload version from the metadata.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800476 static_assert(sizeof(major_payload_version_) == kDeltaVersionSize,
477 "Major payload version size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700478 memcpy(&major_payload_version_,
479 &payload[kDeltaVersionOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800480 kDeltaVersionSize);
481 // switch big endian to host
Sen Jiangb8060e42015-09-24 17:30:50 -0700482 major_payload_version_ = be64toh(major_payload_version_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800483
Alex Deymo7a2c47e2015-11-04 00:47:12 -0800484 if (major_payload_version_ != supported_major_version_ &&
485 major_payload_version_ != kChromeOSMajorPayloadVersion) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800486 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
Sen Jiangb8060e42015-09-24 17:30:50 -0700487 << major_payload_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700488 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800489 return kMetadataParseError;
490 }
491
Sen Jiangb8060e42015-09-24 17:30:50 -0700492 // Get the manifest offset now that we have payload version.
493 if (!GetManifestOffset(&manifest_offset)) {
494 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
495 return kMetadataParseError;
496 }
497 // Check again with the manifest offset.
498 if (payload.size() < manifest_offset)
499 return kMetadataParseInsufficientData;
500
Gilad Arnoldfe133932014-01-14 12:25:50 -0800501 // Next, parse the manifest size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800502 static_assert(sizeof(manifest_size_) == kDeltaManifestSizeSize,
503 "manifest_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700504 memcpy(&manifest_size_,
505 &payload[kDeltaManifestSizeOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800506 kDeltaManifestSizeSize);
Sen Jiangb8060e42015-09-24 17:30:50 -0700507 manifest_size_ = be64toh(manifest_size_); // switch big endian to host
508
Sen Jiangb8060e42015-09-24 17:30:50 -0700509 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
510 // Parse the metadata signature size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800511 static_assert(sizeof(metadata_signature_size_) ==
512 kDeltaMetadataSignatureSizeSize,
513 "metadata_signature_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700514 uint64_t metadata_signature_size_offset;
515 if (!GetMetadataSignatureSizeOffset(&metadata_signature_size_offset)) {
516 *error = ErrorCode::kError;
517 return kMetadataParseError;
518 }
Sen Jiang76bfa742015-10-12 17:13:26 -0700519 memcpy(&metadata_signature_size_,
Sen Jiangb8060e42015-09-24 17:30:50 -0700520 &payload[metadata_signature_size_offset],
521 kDeltaMetadataSignatureSizeSize);
Sen Jiang76bfa742015-10-12 17:13:26 -0700522 metadata_signature_size_ = be32toh(metadata_signature_size_);
Sen Jiangb8060e42015-09-24 17:30:50 -0700523 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800524
525 // If the metadata size is present in install plan, check for it immediately
526 // even before waiting for that many number of bytes to be downloaded in the
527 // payload. This will prevent any attack which relies on us downloading data
528 // beyond the expected metadata size.
Sen Jiang76bfa742015-10-12 17:13:26 -0700529 metadata_size_ = manifest_offset + manifest_size_;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800530 if (install_plan_->hash_checks_mandatory) {
531 if (install_plan_->metadata_size != metadata_size_) {
532 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
533 << install_plan_->metadata_size
534 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700535 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800536 return kMetadataParseError;
537 }
538 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700539 }
540
541 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700542 // metadata and its signature (if exist) to be read in before we can parse it.
543 if (payload.size() < metadata_size_ + metadata_signature_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800544 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700545
546 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700547 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700548 // that we just log once (instead of logging n times) if it takes n
549 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800550 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700551 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800552 } else {
553 // For mandatory-cases, we'd have already returned a kMetadataParseError
554 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
555 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
556 << install_plan_->metadata_size
557 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800558 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800559 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700560
Jay Srinivasanf4318702012-09-24 11:56:24 -0700561 // We have the full metadata in |payload|. Verify its integrity
562 // and authenticity based on the information we have in Omaha response.
Sen Jiang76bfa742015-10-12 17:13:26 -0700563 *error = ValidateMetadataSignature(payload);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700564 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800565 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800566 // The autoupdate_CatchBadSignatures test checks for this string
567 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800568 LOG(ERROR) << "Mandatory metadata signature validation failed";
569 return kMetadataParseError;
570 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700571
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800572 // For non-mandatory cases, just send a UMA stat.
573 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700574 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700575 }
576
Sen Jiangb8060e42015-09-24 17:30:50 -0700577 if (!GetManifestOffset(&manifest_offset)) {
578 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
579 return kMetadataParseError;
580 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800581 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb8060e42015-09-24 17:30:50 -0700582 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800583 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700584 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800585 return kMetadataParseError;
586 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800587
588 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800589 return kMetadataParseSuccess;
590}
591
Lann Martin39f57142017-07-14 09:18:42 -0600592#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
593 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
594 "UpdateEngine.DownloadAction.InstallOperation::" \
595 _op_name ".Duration", \
596 base::TimeTicks::Now() - _start_time, \
597 base::TimeDelta::FromMilliseconds(10), \
598 base::TimeDelta::FromMinutes(5), \
599 20);
600
Don Garrette410e0f2011-11-10 15:39:01 -0800601// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800602// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700603// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800604bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700605 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700606 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800607
608 // Update the total byte downloaded count and the progress logs.
609 total_bytes_received_ += count;
610 UpdateOverallProgress(false, "Completed ");
611
Gilad Arnoldfe133932014-01-14 12:25:50 -0800612 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700613 // Read data up to the needed limit; this is either maximium payload header
614 // size, or the full metadata size (once it becomes known).
615 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800616 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700617 (do_read_header ? kMaxPayloadHeaderSize :
Sen Jiang76bfa742015-10-12 17:13:26 -0700618 metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800619
Gilad Arnolddaa27402014-01-23 11:56:17 -0800620 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700621 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800622 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800623 if (result == kMetadataParseInsufficientData) {
624 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700625 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800626 continue;
627
Don Garrette410e0f2011-11-10 15:39:01 -0800628 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800629 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700630
631 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700632 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700633 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800634 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700635
Gilad Arnoldfe133932014-01-14 12:25:50 -0800636 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800637 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700638
639 // This populates |partitions_| and the |install_plan.partitions| with the
640 // list of partitions from the manifest.
641 if (!ParseManifestPartitions(error))
642 return false;
643
644 num_total_operations_ = 0;
645 for (const auto& partition : partitions_) {
646 num_total_operations_ += partition.operations_size();
647 acc_num_operations_.push_back(num_total_operations_);
648 }
649
Darin Petkov73058b42010-10-06 16:32:19 -0700650 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800651 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700652 << "Unable to save the manifest metadata size.";
Alex Deymof25eb492016-02-26 00:20:08 -0800653 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestSignatureSize,
654 metadata_signature_size_))
655 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700656
Darin Petkov9b230572010-10-08 10:20:09 -0700657 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700658 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700659 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800660 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700661 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800662
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700663 if (!OpenCurrentPartition()) {
664 *error = ErrorCode::kInstallDeviceOpenError;
665 return false;
Allie Woodfdf00512015-03-02 13:34:55 -0800666 }
667
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800668 if (next_operation_num_ > 0)
669 UpdateOverallProgress(true, "Resuming after ");
670 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700671 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800672
673 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700674 // Check if we should cancel the current attempt for any reason.
675 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700676 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300677 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700678 return false;
679
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700680 // We know there are more operations to perform because we didn't reach the
681 // |num_total_operations_| limit yet.
682 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
683 CloseCurrentPartition();
684 current_partition_++;
685 if (!OpenCurrentPartition()) {
686 *error = ErrorCode::kInstallDeviceOpenError;
687 return false;
688 }
689 }
690 const size_t partition_operation_num = next_operation_num_ - (
691 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
692
Alex Deymoa12ee112015-08-12 22:19:32 -0700693 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700694 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800695
696 CopyDataToBuffer(&c_bytes, &count, op.data_length());
697
698 // Check whether we received all of the next operation's data payload.
699 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700700 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700701
Jay Srinivasanf4318702012-09-24 11:56:24 -0700702 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700703 // Otherwise, keep the old behavior. This serves as a knob to disable
704 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800705 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
706 // we would have already failed in ParsePayloadMetadata method and thus not
707 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700708 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700709 // Note: Validate must be called only if CanPerformInstallOperation is
710 // called. Otherwise, we might be failing operations before even if there
711 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800712 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700713 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800714 if (install_plan_->hash_checks_mandatory) {
715 LOG(ERROR) << "Mandatory operation hash check failed";
716 return false;
717 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700718
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800719 // For non-mandatory cases, just send a UMA stat.
720 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700721 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700722 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700723 }
724
Darin Petkov45580e42010-10-08 14:02:40 -0700725 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700726 ScopedTerminatorExitUnblocker exit_unblocker =
727 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800728
Lann Martin39f57142017-07-14 09:18:42 -0600729 base::TimeTicks op_start_time = base::TimeTicks::Now();
730
Gilad Arnoldfe133932014-01-14 12:25:50 -0800731 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700732 switch (op.type()) {
733 case InstallOperation::REPLACE:
734 case InstallOperation::REPLACE_BZ:
735 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700736 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600737 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700738 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700739 case InstallOperation::ZERO:
740 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700741 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600742 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700743 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700744 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700745 op_result = PerformMoveOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600746 OP_DURATION_HISTOGRAM("MOVE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700747 break;
748 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700749 op_result = PerformBsdiffOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600750 OP_DURATION_HISTOGRAM("BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700751 break;
752 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700753 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600754 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700755 break;
756 case InstallOperation::SOURCE_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700757 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600758 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700759 break;
Amin Hassani5ef5d452017-08-04 13:10:59 -0700760 case InstallOperation::PUFFDIFF:
761 // TODO(ahassani): Later add PerformPuffdiffOperation(op, error);
Alex Deymoeecb0a52017-05-19 15:15:08 -0700762 op_result = false;
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800763 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700764 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700765 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700766 }
767 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800768 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800769
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700770 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800771 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700772 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700773 }
Sen Jiangf6813802015-11-03 21:27:29 -0800774
775 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800776 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800777 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800778 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
779 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800780 if (manifest_.signatures_offset() != buffer_offset_) {
781 LOG(ERROR) << "Payload signatures offset points to blob offset "
782 << manifest_.signatures_offset()
783 << " but signatures are expected at offset "
784 << buffer_offset_;
785 *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.
801 CheckpointUpdateProgress();
Sen Jiangf6813802015-11-03 21:27:29 -0800802 }
803
Don Garrette410e0f2011-11-10 15:39:01 -0800804 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700805}
806
David Zeuthen8f191b22013-08-06 12:27:50 -0700807bool DeltaPerformer::IsManifestValid() {
808 return manifest_valid_;
809}
810
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700811bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
812 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
813 partitions_.clear();
814 for (const PartitionUpdate& partition : manifest_.partitions()) {
815 partitions_.push_back(partition);
816 }
817 manifest_.clear_partitions();
818 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
819 LOG(INFO) << "Converting update information from old format.";
820 PartitionUpdate root_part;
821 root_part.set_partition_name(kLegacyPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700822#ifdef __ANDROID__
823 LOG(WARNING) << "Legacy payload major version provided to an Android "
824 "build. Assuming no post-install. Please use major version "
825 "2 or newer.";
826 root_part.set_run_postinstall(false);
827#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700828 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700829#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700830 if (manifest_.has_old_rootfs_info()) {
831 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
832 manifest_.clear_old_rootfs_info();
833 }
834 if (manifest_.has_new_rootfs_info()) {
835 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
836 manifest_.clear_new_rootfs_info();
837 }
838 *root_part.mutable_operations() = manifest_.install_operations();
839 manifest_.clear_install_operations();
840 partitions_.push_back(std::move(root_part));
841
842 PartitionUpdate kern_part;
843 kern_part.set_partition_name(kLegacyPartitionNameKernel);
844 kern_part.set_run_postinstall(false);
845 if (manifest_.has_old_kernel_info()) {
846 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
847 manifest_.clear_old_kernel_info();
848 }
849 if (manifest_.has_new_kernel_info()) {
850 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
851 manifest_.clear_new_kernel_info();
852 }
853 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
854 manifest_.clear_kernel_install_operations();
855 partitions_.push_back(std::move(kern_part));
856 }
857
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700858 // Fill in the InstallPlan::partitions based on the partitions from the
859 // payload.
860 install_plan_->partitions.clear();
861 for (const auto& partition : partitions_) {
862 InstallPlan::Partition install_part;
863 install_part.name = partition.partition_name();
864 install_part.run_postinstall =
865 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800866 if (install_part.run_postinstall) {
867 install_part.postinstall_path =
868 (partition.has_postinstall_path() ? partition.postinstall_path()
869 : kPostinstallDefaultScript);
870 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700871 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800872 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700873
874 if (partition.has_old_partition_info()) {
875 const PartitionInfo& info = partition.old_partition_info();
876 install_part.source_size = info.size();
877 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
878 }
879
880 if (!partition.has_new_partition_info()) {
881 LOG(ERROR) << "Unable to get new partition hash info on partition "
882 << install_part.name << ".";
883 *error = ErrorCode::kDownloadNewPartitionInfoError;
884 return false;
885 }
886 const PartitionInfo& info = partition.new_partition_info();
887 install_part.target_size = info.size();
888 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
889
890 install_plan_->partitions.push_back(install_part);
891 }
892
Alex Deymo542c19b2015-12-03 07:43:31 -0300893 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700894 LOG(ERROR) << "Unable to determine all the partition devices.";
895 *error = ErrorCode::kInstallDeviceOpenError;
896 return false;
897 }
898 LogPartitionInfo(partitions_);
899 return true;
900}
901
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700902bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700903 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700904 // If we don't have a data blob we can apply it right away.
905 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700906 return true;
907
908 // See if we have the entire data blob in the buffer
909 if (operation.data_offset() < buffer_offset_) {
910 LOG(ERROR) << "we threw away data it seems?";
911 return false;
912 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700913
Gilad Arnoldfe133932014-01-14 12:25:50 -0800914 return (operation.data_offset() + operation.data_length() <=
915 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700916}
917
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700918bool DeltaPerformer::PerformReplaceOperation(
919 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700920 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700921 operation.type() == InstallOperation::REPLACE_BZ ||
922 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700923
924 // Since we delete data off the beginning of the buffer as we use it,
925 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700926 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
927 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700928
Darin Petkov437adc42010-10-07 13:12:24 -0700929 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -0800930 if (ExtractSignatureMessageFromOperation(operation)) {
931 // If this is dummy replace operation, we ignore it after extracting the
932 // signature.
933 DiscardBuffer(true, 0);
934 return true;
935 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700936
Alex Deymo05322872015-09-30 09:50:24 -0700937 // Setup the ExtentWriter stack based on the operation type.
Ben Chan5c02c132017-06-27 07:10:36 -0700938 std::unique_ptr<ExtentWriter> writer = base::MakeUnique<ZeroPadExtentWriter>(
939 base::MakeUnique<DirectExtentWriter>());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700940
Alex Deymo2d621a32015-10-01 11:09:01 -0700941 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700942 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700943 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
944 writer.reset(new XzExtentWriter(std::move(writer)));
945 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700946
947 // Create a vector of extents to pass to the ExtentWriter.
948 vector<Extent> extents;
949 for (int i = 0; i < operation.dst_extents_size(); i++) {
950 extents.push_back(operation.dst_extents(i));
951 }
952
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700953 TEST_AND_RETURN_FALSE(writer->Init(target_fd_, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800954 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700955 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700956
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700957 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -0800958 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700959 return true;
960}
961
Alex Deymo79715ad2015-10-02 14:27:53 -0700962bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700963 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700964 CHECK(operation.type() == InstallOperation::DISCARD ||
965 operation.type() == InstallOperation::ZERO);
966
967 // These operations have no blob.
968 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
969 TEST_AND_RETURN_FALSE(!operation.has_data_length());
970
Alex Deymo05e0e382015-12-07 20:18:16 -0800971#ifdef BLKZEROOUT
972 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -0700973 int request =
974 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Alex Deymo05e0e382015-12-07 20:18:16 -0800975#else // !defined(BLKZEROOUT)
976 bool attempt_ioctl = false;
977 int request = 0;
978#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -0700979
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700980 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700981 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700982 const uint64_t start = extent.start_block() * block_size_;
983 const uint64_t length = extent.num_blocks() * block_size_;
984 if (attempt_ioctl) {
985 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700986 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -0700987 continue;
988 attempt_ioctl = false;
989 zeros.resize(16 * block_size_);
990 }
991 // In case of failure, we fall back to writing 0 to the selected region.
992 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700993 uint64_t chunk_length = min(length - offset,
994 static_cast<uint64_t>(zeros.size()));
Alex Deymo79715ad2015-10-02 14:27:53 -0700995 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700996 utils::PWriteAll(target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -0700997 }
998 }
999 return true;
1000}
1001
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001002bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001003 // Calculate buffer size. Note, this function doesn't do a sliding
1004 // window to copy in case the source and destination blocks overlap.
1005 // If we wanted to do a sliding window, we could program the server
1006 // to generate deltas that effectively did a sliding window.
1007
1008 uint64_t blocks_to_read = 0;
1009 for (int i = 0; i < operation.src_extents_size(); i++)
1010 blocks_to_read += operation.src_extents(i).num_blocks();
1011
1012 uint64_t blocks_to_write = 0;
1013 for (int i = 0; i < operation.dst_extents_size(); i++)
1014 blocks_to_write += operation.dst_extents(i).num_blocks();
1015
1016 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001017 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001019 // Read in bytes.
1020 ssize_t bytes_read = 0;
1021 for (int i = 0; i < operation.src_extents_size(); i++) {
1022 ssize_t bytes_read_this_iteration = 0;
1023 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001024 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001025 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001026 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001027 &buf[bytes_read],
1028 bytes,
1029 extent.start_block() * block_size_,
1030 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001031 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +02001032 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001033 bytes_read += bytes_read_this_iteration;
1034 }
1035
1036 // Write bytes out.
1037 ssize_t bytes_written = 0;
1038 for (int i = 0; i < operation.dst_extents_size(); i++) {
1039 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001040 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001041 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001042 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001043 &buf[bytes_written],
1044 bytes,
1045 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001046 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001047 }
1048 DCHECK_EQ(bytes_written, bytes_read);
1049 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1050 return true;
1051}
1052
Allie Wood9f6f0a52015-03-30 11:25:47 -07001053namespace {
1054
1055// Takes |extents| and fills an empty vector |blocks| with a block index for
1056// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
1057void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
1058 vector<uint64_t>* blocks) {
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001059 for (const Extent& ext : extents) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001060 for (uint64_t j = 0; j < ext.num_blocks(); j++)
1061 blocks->push_back(ext.start_block() + j);
1062 }
1063}
1064
1065// Takes |extents| and returns the number of blocks in those extents.
1066uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
1067 uint64_t sum = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001068 for (const Extent& ext : extents) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001069 sum += ext.num_blocks();
1070 }
1071 return sum;
1072}
1073
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001074// Compare |calculated_hash| with source hash in |operation|, return false and
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001075// dump hash and set |error| if don't match.
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001076bool ValidateSourceHash(const brillo::Blob& calculated_hash,
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001077 const InstallOperation& operation,
1078 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001079 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1080 operation.src_sha256_hash().end());
1081 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001082 LOG(ERROR) << "The hash of the source data on disk for this operation "
1083 << "doesn't match the expected value. This could mean that the "
1084 << "delta update payload was targeted for another version, or "
1085 << "that the source partition was modified after it was "
1086 << "installed, for example, by mounting a filesystem.";
1087 LOG(ERROR) << "Expected: sha256|hex = "
1088 << base::HexEncode(expected_source_hash.data(),
1089 expected_source_hash.size());
1090 LOG(ERROR) << "Calculated: sha256|hex = "
1091 << base::HexEncode(calculated_hash.data(),
1092 calculated_hash.size());
1093
1094 vector<string> source_extents;
1095 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001096 source_extents.push_back(
1097 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1098 static_cast<uint64_t>(ext.start_block()),
1099 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001100 }
1101 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1102 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001103
1104 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001105 return false;
1106 }
1107 return true;
1108}
1109
Allie Wood9f6f0a52015-03-30 11:25:47 -07001110} // namespace
1111
1112bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001113 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001114 if (operation.has_src_length())
1115 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1116 if (operation.has_dst_length())
1117 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1118
1119 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
1120 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
1121 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
1122
1123 // Create vectors of all the individual src/dst blocks.
1124 vector<uint64_t> src_blocks;
1125 vector<uint64_t> dst_blocks;
1126 ExtentsToBlocks(operation.src_extents(), &src_blocks);
1127 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
1128 DCHECK_EQ(src_blocks.size(), blocks_to_read);
1129 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
1130
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001131 brillo::Blob buf(block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001132 ssize_t bytes_read = 0;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001133 HashCalculator source_hasher;
Allie Wood9f6f0a52015-03-30 11:25:47 -07001134 // Read/write one block at a time.
1135 for (uint64_t i = 0; i < blocks_to_read; i++) {
1136 ssize_t bytes_read_this_iteration = 0;
1137 uint64_t src_block = src_blocks[i];
1138 uint64_t dst_block = dst_blocks[i];
1139
1140 // Read in bytes.
1141 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001142 utils::PReadAll(source_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001143 buf.data(),
1144 block_size_,
1145 src_block * block_size_,
1146 &bytes_read_this_iteration));
1147
1148 // Write bytes out.
1149 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001150 utils::PWriteAll(target_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001151 buf.data(),
1152 block_size_,
1153 dst_block * block_size_));
1154
1155 bytes_read += bytes_read_this_iteration;
1156 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
1157 static_cast<ssize_t>(block_size_));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001158
1159 if (operation.has_src_sha256_hash())
1160 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), buf.size()));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001161 }
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001162
1163 if (operation.has_src_sha256_hash()) {
1164 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1165 TEST_AND_RETURN_FALSE(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001166 ValidateSourceHash(source_hasher.raw_hash(), operation, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001167 }
1168
Allie Wood9f6f0a52015-03-30 11:25:47 -07001169 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
1170 return true;
1171}
1172
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001173bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1174 const RepeatedPtrField<Extent>& extents,
1175 uint64_t block_size,
1176 uint64_t full_length,
1177 string* positions_string) {
1178 string ret;
1179 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001180 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001181 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001182 uint64_t this_length =
1183 min(full_length - length,
1184 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001185 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001186 length += this_length;
1187 }
1188 TEST_AND_RETURN_FALSE(length == full_length);
1189 if (!ret.empty())
1190 ret.resize(ret.size() - 1); // Strip trailing comma off
1191 *positions_string = ret;
1192 return true;
1193}
1194
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001195bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001196 // Since we delete data off the beginning of the buffer as we use it,
1197 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001198 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1199 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001200
1201 string input_positions;
1202 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1203 block_size_,
1204 operation.src_length(),
1205 &input_positions));
1206 string output_positions;
1207 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1208 block_size_,
1209 operation.dst_length(),
1210 &output_positions));
1211
Sen Jiang7a659092016-05-10 15:31:46 -07001212 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1213 target_path_.c_str(),
1214 buffer_.data(),
1215 buffer_.size(),
1216 input_positions.c_str(),
1217 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001218 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001219
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001220 if (operation.dst_length() % block_size_) {
1221 // Zero out rest of final block.
1222 // TODO(adlr): build this into bspatch; it's more efficient that way.
1223 const Extent& last_extent =
1224 operation.dst_extents(operation.dst_extents_size() - 1);
1225 const uint64_t end_byte =
1226 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1227 const uint64_t begin_byte =
1228 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001229 brillo::Blob zeros(end_byte - begin_byte);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001230 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001231 utils::PWriteAll(target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001232 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001233 return true;
1234}
1235
Allie Wood9f6f0a52015-03-30 11:25:47 -07001236bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001237 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001238 // Since we delete data off the beginning of the buffer as we use it,
1239 // the data we need should be exactly at the beginning of the buffer.
1240 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1241 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1242 if (operation.has_src_length())
1243 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1244 if (operation.has_dst_length())
1245 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1246
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001247 if (operation.has_src_sha256_hash()) {
1248 HashCalculator source_hasher;
1249 const uint64_t kMaxBlocksToRead = 512; // 2MB if block size is 4KB
1250 brillo::Blob buf(kMaxBlocksToRead * block_size_);
1251 for (const Extent& extent : operation.src_extents()) {
1252 for (uint64_t i = 0; i < extent.num_blocks(); i += kMaxBlocksToRead) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001253 uint64_t blocks_to_read = min(
1254 kMaxBlocksToRead, static_cast<uint64_t>(extent.num_blocks()) - i);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001255 ssize_t bytes_to_read = blocks_to_read * block_size_;
1256 ssize_t bytes_read_this_iteration = 0;
1257 TEST_AND_RETURN_FALSE(
1258 utils::PReadAll(source_fd_, buf.data(), bytes_to_read,
1259 (extent.start_block() + i) * block_size_,
1260 &bytes_read_this_iteration));
1261 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes_to_read);
1262 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), bytes_to_read));
1263 }
1264 }
1265 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1266 TEST_AND_RETURN_FALSE(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001267 ValidateSourceHash(source_hasher.raw_hash(), operation, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001268 }
1269
Allie Wood9f6f0a52015-03-30 11:25:47 -07001270 string input_positions;
1271 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1272 block_size_,
1273 operation.src_length(),
1274 &input_positions));
1275 string output_positions;
1276 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1277 block_size_,
1278 operation.dst_length(),
1279 &output_positions));
1280
Sen Jiang7a659092016-05-10 15:31:46 -07001281 TEST_AND_RETURN_FALSE(bsdiff::bspatch(source_path_.c_str(),
1282 target_path_.c_str(),
1283 buffer_.data(),
1284 buffer_.size(),
1285 input_positions.c_str(),
1286 output_positions.c_str()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001287 DiscardBuffer(true, buffer_.size());
1288 return true;
1289}
1290
Sen Jiangf6813802015-11-03 21:27:29 -08001291bool DeltaPerformer::ExtractSignatureMessageFromOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001292 const InstallOperation& operation) {
1293 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001294 !manifest_.has_signatures_offset() ||
1295 manifest_.signatures_offset() != operation.data_offset()) {
1296 return false;
1297 }
1298 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1299 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001300 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1301 return true;
1302}
1303
1304bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001305 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1306 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1307 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001308 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001309 buffer_.begin(),
1310 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001311
1312 // Save the signature blob because if the update is interrupted after the
1313 // download phase we don't go through this path anymore. Some alternatives to
1314 // consider:
1315 //
1316 // 1. On resume, re-download the signature blob from the server and re-verify
1317 // it.
1318 //
1319 // 2. Verify the signature as soon as it's received and don't checkpoint the
1320 // blob and the signed sha-256 context.
1321 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001322 string(signatures_message_data_.begin(),
1323 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001324 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001325
Darin Petkovd7061ab2010-10-06 14:37:09 -07001326 LOG(INFO) << "Extracted signature data of size "
1327 << manifest_.signatures_size() << " at "
1328 << manifest_.signatures_offset();
1329 return true;
1330}
1331
David Zeuthene7f89172013-10-31 10:21:04 -07001332bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
Alex Deymo542c19b2015-12-03 07:43:31 -03001333 if (hardware_->IsOfficialBuild() ||
David Zeuthene7f89172013-10-31 10:21:04 -07001334 utils::FileExists(public_key_path_.c_str()) ||
1335 install_plan_->public_key_rsa.empty())
1336 return false;
1337
1338 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1339 out_tmp_key))
1340 return false;
1341
1342 return true;
1343}
1344
David Zeuthena99981f2013-04-29 13:42:47 -07001345ErrorCode DeltaPerformer::ValidateMetadataSignature(
Sen Jiang76bfa742015-10-12 17:13:26 -07001346 const brillo::Blob& payload) {
1347 if (payload.size() < metadata_size_ + metadata_signature_size_)
1348 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001349
Sen Jiang76bfa742015-10-12 17:13:26 -07001350 brillo::Blob metadata_signature_blob, metadata_signature_protobuf_blob;
1351 if (!install_plan_->metadata_signature.empty()) {
1352 // Convert base64-encoded signature to raw bytes.
1353 if (!brillo::data_encoding::Base64Decode(
1354 install_plan_->metadata_signature, &metadata_signature_blob)) {
1355 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1356 << install_plan_->metadata_signature;
1357 return ErrorCode::kDownloadMetadataSignatureError;
1358 }
1359 } else if (major_payload_version_ == kBrilloMajorPayloadVersion) {
1360 metadata_signature_protobuf_blob.assign(payload.begin() + metadata_size_,
1361 payload.begin() + metadata_size_ +
1362 metadata_signature_size_);
1363 }
1364
1365 if (metadata_signature_blob.empty() &&
1366 metadata_signature_protobuf_blob.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001367 if (install_plan_->hash_checks_mandatory) {
Sen Jiang76bfa742015-10-12 17:13:26 -07001368 LOG(ERROR) << "Missing mandatory metadata signature in both Omaha "
1369 << "response and payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001370 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001371 }
1372
Jay Srinivasanf4318702012-09-24 11:56:24 -07001373 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001374 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001375 }
1376
David Zeuthene7f89172013-10-31 10:21:04 -07001377 // See if we should use the public RSA key in the Omaha response.
1378 base::FilePath path_to_public_key(public_key_path_);
1379 base::FilePath tmp_key;
1380 if (GetPublicKeyFromResponse(&tmp_key))
1381 path_to_public_key = tmp_key;
1382 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1383 if (tmp_key.empty())
1384 tmp_key_remover.set_should_remove(false);
1385
1386 LOG(INFO) << "Verifying metadata hash signature using public key: "
1387 << path_to_public_key.value();
1388
Alex Deymo39910dc2015-11-09 17:04:30 -08001389 HashCalculator metadata_hasher;
Sen Jiang76bfa742015-10-12 17:13:26 -07001390 metadata_hasher.Update(payload.data(), metadata_size_);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001391 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001392 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001393 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001394 }
1395
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001396 brillo::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001397 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001398 if (calculated_metadata_hash.empty()) {
1399 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001400 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001401 }
1402
Sen Jiang76bfa742015-10-12 17:13:26 -07001403 if (!metadata_signature_blob.empty()) {
1404 brillo::Blob expected_metadata_hash;
1405 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature_blob,
1406 path_to_public_key.value(),
1407 &expected_metadata_hash)) {
1408 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
1409 return ErrorCode::kDownloadMetadataSignatureError;
1410 }
1411 if (calculated_metadata_hash != expected_metadata_hash) {
1412 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
1413 utils::HexDumpVector(expected_metadata_hash);
1414 LOG(ERROR) << "Calculated hash = ";
1415 utils::HexDumpVector(calculated_metadata_hash);
1416 return ErrorCode::kDownloadMetadataSignatureMismatch;
1417 }
1418 } else {
1419 if (!PayloadVerifier::VerifySignature(metadata_signature_protobuf_blob,
1420 path_to_public_key.value(),
1421 calculated_metadata_hash)) {
1422 LOG(ERROR) << "Manifest hash verification failed.";
1423 return ErrorCode::kDownloadMetadataSignatureMismatch;
1424 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001425 }
1426
David Zeuthenbc27aac2013-11-26 11:17:48 -08001427 // The autoupdate_CatchBadSignatures test checks for this string in
1428 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001429 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001430 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001431}
1432
Gilad Arnold21504f02013-05-24 08:51:22 -07001433ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001434 // Perform assorted checks to sanity check the manifest, make sure it
1435 // matches data from other sources, and that it is a supported version.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001436
Alex Deymo64d98782016-02-05 18:03:48 -08001437 bool has_old_fields =
1438 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1439 for (const PartitionUpdate& partition : manifest_.partitions()) {
1440 has_old_fields = has_old_fields || partition.has_old_partition_info();
1441 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001442
Alex Deymo64d98782016-02-05 18:03:48 -08001443 // The presence of an old partition hash is the sole indicator for a delta
1444 // update.
1445 InstallPayloadType actual_payload_type =
1446 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1447
1448 if (install_plan_->payload_type == InstallPayloadType::kUnknown) {
1449 LOG(INFO) << "Detected a '"
1450 << InstallPayloadTypeToString(actual_payload_type)
1451 << "' payload.";
1452 install_plan_->payload_type = actual_payload_type;
1453 } else if (install_plan_->payload_type != actual_payload_type) {
1454 LOG(ERROR) << "InstallPlan expected a '"
1455 << InstallPayloadTypeToString(install_plan_->payload_type)
1456 << "' payload but the downloaded manifest contains a '"
1457 << InstallPayloadTypeToString(actual_payload_type)
1458 << "' payload.";
1459 return ErrorCode::kPayloadMismatchedType;
1460 }
1461
1462 // Check that the minor version is compatible.
1463 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001464 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1465 LOG(ERROR) << "Manifest contains minor version "
1466 << manifest_.minor_version()
1467 << ", but all full payloads should have version "
1468 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001469 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001470 }
1471 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001472 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001473 LOG(ERROR) << "Manifest contains minor version "
1474 << manifest_.minor_version()
1475 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001476 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001477 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001478 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001479 }
1480
Sen Jiang3e728fe2015-11-05 11:37:23 -08001481 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
1482 if (manifest_.has_old_rootfs_info() ||
1483 manifest_.has_new_rootfs_info() ||
1484 manifest_.has_old_kernel_info() ||
1485 manifest_.has_new_kernel_info() ||
1486 manifest_.install_operations_size() != 0 ||
1487 manifest_.kernel_install_operations_size() != 0) {
1488 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1489 << "major payload version 1, but the payload major version is "
1490 << major_payload_version_;
1491 return ErrorCode::kPayloadMismatchedType;
1492 }
1493 }
1494
Gilad Arnold21504f02013-05-24 08:51:22 -07001495 // TODO(garnold) we should be adding more and more manifest checks, such as
1496 // partition boundaries etc (see chromium-os:37661).
1497
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001498 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001499}
1500
David Zeuthena99981f2013-04-29 13:42:47 -07001501ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001502 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001503 if (!operation.data_sha256_hash().size()) {
1504 if (!operation.data_length()) {
1505 // Operations that do not have any data blob won't have any operation hash
1506 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001507 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001508 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001509 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001510 }
1511
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001512 // No hash is present for an operation that has data blobs. This shouldn't
1513 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001514 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001515 // hashes. So if it happens it means either we've turned operation hash
1516 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001517 // One caveat though: The last operation is a dummy signature operation
1518 // that doesn't have a hash at the time the manifest is created. So we
1519 // should not complaint about that operation. This operation can be
1520 // recognized by the fact that it's offset is mentioned in the manifest.
1521 if (manifest_.signatures_offset() &&
1522 manifest_.signatures_offset() == operation.data_offset()) {
1523 LOG(INFO) << "Skipping hash verification for signature operation "
1524 << next_operation_num_ + 1;
1525 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001526 if (install_plan_->hash_checks_mandatory) {
1527 LOG(ERROR) << "Missing mandatory operation hash for operation "
1528 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001529 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001530 }
1531
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001532 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1533 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001534 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001535 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001536 }
1537
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001538 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001539 expected_op_hash.assign(operation.data_sha256_hash().data(),
1540 (operation.data_sha256_hash().data() +
1541 operation.data_sha256_hash().size()));
1542
Alex Deymo39910dc2015-11-09 17:04:30 -08001543 HashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001544 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001545 if (!operation_hasher.Finalize()) {
1546 LOG(ERROR) << "Unable to compute actual hash of operation "
1547 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001548 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001549 }
1550
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001551 brillo::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001552 if (calculated_op_hash != expected_op_hash) {
1553 LOG(ERROR) << "Hash verification failed for operation "
1554 << next_operation_num_ << ". Expected hash = ";
1555 utils::HexDumpVector(expected_op_hash);
1556 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1557 << " bytes at offset: " << operation.data_offset() << " = ";
1558 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001559 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001560 }
1561
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001562 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001563}
1564
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001565#define TEST_AND_RETURN_VAL(_retval, _condition) \
1566 do { \
1567 if (!(_condition)) { \
1568 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1569 return _retval; \
1570 } \
1571 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001572
David Zeuthena99981f2013-04-29 13:42:47 -07001573ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001574 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001575 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001576
1577 // See if we should use the public RSA key in the Omaha response.
1578 base::FilePath path_to_public_key(public_key_path_);
1579 base::FilePath tmp_key;
1580 if (GetPublicKeyFromResponse(&tmp_key))
1581 path_to_public_key = tmp_key;
1582 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1583 if (tmp_key.empty())
1584 tmp_key_remover.set_should_remove(false);
1585
1586 LOG(INFO) << "Verifying payload using public key: "
1587 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001588
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001589 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001590 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001591 update_check_response_size ==
Sen Jiang76bfa742015-10-12 17:13:26 -07001592 metadata_size_ + metadata_signature_size_ +
1593 buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001594
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001595 // Verifies the payload hash.
Sen Jiangf6813802015-11-03 21:27:29 -08001596 const string& payload_hash_data = payload_hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001597 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001598 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001599 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001600 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001601
Darin Petkov437adc42010-10-07 13:12:24 -07001602 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001603 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001604 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001605 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001606 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001607 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001608 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001609 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001610 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1611 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001612 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001613 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001614
1615 if (!PayloadVerifier::VerifySignature(
1616 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001617 // The autoupdate_CatchBadSignatures test checks for this string
1618 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001619 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001620 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001621 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001622
David Zeuthene7f89172013-10-31 10:21:04 -07001623 LOG(INFO) << "Payload hash matches value in payload.";
1624
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001625 // At this point, we are guaranteed to have downloaded a full payload, i.e
1626 // the one whose size matches the size mentioned in Omaha response. If any
1627 // errors happen after this, it's likely a problem with the payload itself or
1628 // the state of the system and not a problem with the URL or network. So,
Alex Deymo542c19b2015-12-03 07:43:31 -03001629 // indicate that to the download delegate so that AU can backoff
1630 // appropriately.
1631 if (download_delegate_)
1632 download_delegate_->DownloadComplete();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001633
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001634 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001635}
1636
Sen Jiangf6813802015-11-03 21:27:29 -08001637void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1638 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001639 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001640 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001641 buffer_offset_ += buffer_.size();
1642
1643 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001644 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1645 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001646
1647 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001648 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001649}
1650
Darin Petkov0406e402010-10-06 21:33:11 -07001651bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001652 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001653 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001654 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1655 next_operation != kUpdateStateOperationInvalid &&
1656 next_operation > 0))
1657 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001658
1659 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001660 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1661 !interrupted_hash.empty() &&
1662 interrupted_hash == update_check_response_hash))
1663 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001664
Darin Petkov61426142010-10-08 11:04:55 -07001665 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001666 // Note that storing this value is optional, but if it is there it should not
1667 // be more than the limit.
1668 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1669 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001670 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001671
Darin Petkov0406e402010-10-06 21:33:11 -07001672 // Sanity check the rest.
1673 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001674 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1675 next_data_offset >= 0))
1676 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001677
Darin Petkov437adc42010-10-07 13:12:24 -07001678 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001679 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1680 !sha256_context.empty()))
1681 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001682
1683 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001684 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1685 manifest_metadata_size > 0))
1686 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001687
Alex Deymof25eb492016-02-26 00:20:08 -08001688 int64_t manifest_signature_size = 0;
1689 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1690 &manifest_signature_size) &&
1691 manifest_signature_size >= 0))
1692 return false;
1693
Darin Petkov0406e402010-10-06 21:33:11 -07001694 return true;
1695}
1696
Darin Petkov9b230572010-10-08 10:20:09 -07001697bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001698 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1699 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001700 if (!quick) {
1701 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1702 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001703 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001704 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1705 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001706 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001707 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001708 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001709 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001710 }
Darin Petkov73058b42010-10-06 16:32:19 -07001711 return true;
1712}
1713
1714bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001715 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001716 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001717 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001718 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001719 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001720 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Sen Jiangf6813802015-11-03 21:27:29 -08001721 payload_hash_calculator_.GetContext()));
1722 TEST_AND_RETURN_FALSE(
1723 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1724 signed_hash_calculator_.GetContext()));
Darin Petkov0406e402010-10-06 21:33:11 -07001725 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1726 buffer_offset_));
1727 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001728
1729 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001730 size_t partition_index = current_partition_;
1731 while (next_operation_num_ >= acc_num_operations_[partition_index])
1732 partition_index++;
1733 const size_t partition_operation_num = next_operation_num_ - (
1734 partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001735 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001736 partitions_[partition_index].operations(partition_operation_num);
David Zeuthen41996ad2013-09-24 15:43:24 -07001737 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1738 op.data_length()));
1739 } else {
1740 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1741 0));
1742 }
Darin Petkov0406e402010-10-06 21:33:11 -07001743 }
Darin Petkov73058b42010-10-06 16:32:19 -07001744 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1745 next_operation_num_));
1746 return true;
1747}
1748
Darin Petkov9b230572010-10-08 10:20:09 -07001749bool DeltaPerformer::PrimeUpdateState() {
1750 CHECK(manifest_valid_);
1751 block_size_ = manifest_.block_size();
1752
1753 int64_t next_operation = kUpdateStateOperationInvalid;
1754 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1755 next_operation == kUpdateStateOperationInvalid ||
1756 next_operation <= 0) {
1757 // Initiating a new update, no more state needs to be initialized.
1758 return true;
1759 }
1760 next_operation_num_ = next_operation;
1761
1762 // Resuming an update -- load the rest of the update state.
1763 int64_t next_data_offset = -1;
1764 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1765 &next_data_offset) &&
1766 next_data_offset >= 0);
1767 buffer_offset_ = next_data_offset;
1768
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001769 // The signed hash context and the signature blob may be empty if the
1770 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001771 string signed_hash_context;
1772 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1773 &signed_hash_context)) {
1774 TEST_AND_RETURN_FALSE(
1775 signed_hash_calculator_.SetContext(signed_hash_context));
1776 }
1777
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001778 string signature_blob;
1779 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1780 signatures_message_data_.assign(signature_blob.begin(),
1781 signature_blob.end());
1782 }
Darin Petkov9b230572010-10-08 10:20:09 -07001783
1784 string hash_context;
1785 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1786 &hash_context) &&
Sen Jiangf6813802015-11-03 21:27:29 -08001787 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001788
1789 int64_t manifest_metadata_size = 0;
1790 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1791 &manifest_metadata_size) &&
1792 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001793 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001794
Alex Deymof25eb492016-02-26 00:20:08 -08001795 int64_t manifest_signature_size = 0;
1796 TEST_AND_RETURN_FALSE(
1797 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1798 manifest_signature_size >= 0);
1799 metadata_signature_size_ = manifest_signature_size;
1800
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001801 // Advance the download progress to reflect what doesn't need to be
1802 // re-downloaded.
1803 total_bytes_received_ += buffer_offset_;
1804
Darin Petkov61426142010-10-08 11:04:55 -07001805 // Speculatively count the resume as a failure.
1806 int64_t resumed_update_failures;
1807 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1808 resumed_update_failures++;
1809 } else {
1810 resumed_update_failures = 1;
1811 }
1812 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001813 return true;
1814}
1815
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001816} // namespace chromeos_update_engine