blob: aadbef08e6bb4ddce9eb5b5fffce0b6bac245b66 [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>
Amin Hassani69583ba2017-08-29 11:40:03 -070027#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028#include <vector>
29
Ben Chan06c76a42014-09-05 08:21:06 -070030#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070031#include <base/format_macros.h>
Ben Chan5c02c132017-06-27 07:10:36 -070032#include <base/memory/ptr_util.h>
Lann Martin39f57142017-07-14 09:18:42 -060033#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070034#include <base/strings/string_number_conversions.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/string_util.h>
36#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060037#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070038#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070039#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040#include <google/protobuf/repeated_field.h>
41
Alex Deymo39910dc2015-11-09 17:04:30 -080042#include "update_engine/common/constants.h"
43#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030044#include "update_engine/common/prefs_interface.h"
45#include "update_engine/common/subprocess.h"
46#include "update_engine/common/terminator.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/payload_consumer/bzip_extent_writer.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030048#include "update_engine/payload_consumer/download_action.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/payload_consumer/extent_writer.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080050#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080051#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080052#endif
Alex Deymo39910dc2015-11-09 17:04:30 -080053#include "update_engine/payload_consumer/payload_constants.h"
54#include "update_engine/payload_consumer/payload_verifier.h"
55#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070056
Alex Deymo161c4a12014-05-16 15:56:21 -070057using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070058using std::min;
59using std::string;
60using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070061
62namespace chromeos_update_engine {
63
Sen Jiangb8060e42015-09-24 17:30:50 -070064const uint64_t DeltaPerformer::kDeltaVersionOffset = sizeof(kDeltaMagic);
Jay Srinivasanf4318702012-09-24 11:56:24 -070065const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070066const uint64_t DeltaPerformer::kDeltaManifestSizeOffset =
67 kDeltaVersionOffset + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -070068const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070069const uint64_t DeltaPerformer::kDeltaMetadataSignatureSizeSize = 4;
70const uint64_t DeltaPerformer::kMaxPayloadHeaderSize = 24;
Alex Deymo7a2c47e2015-11-04 00:47:12 -080071const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 2;
Sen Jiang889c65d2015-11-17 15:04:02 -080072const uint32_t DeltaPerformer::kSupportedMinorPayloadVersion = 3;
Don Garrett4d039442013-10-28 18:40:06 -070073
Gilad Arnold8a86fa52013-01-15 12:35:05 -080074const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
75const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
76const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
77const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080078
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070080const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070081const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080082#if USE_MTD
83const int kUbiVolumeAttachTimeout = 5 * 60;
84#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080085
86FileDescriptorPtr CreateFileDescriptor(const char* path) {
87 FileDescriptorPtr ret;
88#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080089 if (strstr(path, "/dev/ubi") == path) {
90 if (!UbiFileDescriptor::IsUbi(path)) {
91 // The volume might not have been attached at boot time.
92 int volume_no;
93 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
94 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
95 }
96 }
97 if (UbiFileDescriptor::IsUbi(path)) {
98 LOG(INFO) << path << " is a UBI device.";
99 ret.reset(new UbiFileDescriptor);
100 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800101 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800102 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800104 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800105 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800106#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800107 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800108#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700109 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800110#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800111 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700112}
113
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800114// Opens path for read/write. On success returns an open FileDescriptor
115// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700116FileDescriptorPtr OpenFile(const char* path, int mode, int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -0700117 // Try to mark the block device read-only based on the mode. Ignore any
118 // failure since this won't work when passing regular files.
119 utils::SetBlockDeviceReadOnly(path, (mode & O_ACCMODE) == O_RDONLY);
120
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800121 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800122#if USE_MTD
123 // On NAND devices, we can either read, or write, but not both. So here we
124 // use O_WRONLY.
125 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
126 mode = O_WRONLY;
127 }
128#endif
129 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800130 *err = errno;
131 PLOG(ERROR) << "Unable to open file " << path;
132 return nullptr;
133 }
134 *err = 0;
135 return fd;
136}
Alex Deymob86787c2016-05-12 18:46:25 -0700137
138// Discard the tail of the block device referenced by |fd|, from the offset
139// |data_size| until the end of the block device. Returns whether the data was
140// discarded.
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700141bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
Alex Deymob86787c2016-05-12 18:46:25 -0700142 uint64_t part_size = fd->BlockDevSize();
143 if (!part_size || part_size <= data_size)
144 return false;
145
Alex Deymo72a68d82016-06-15 16:31:04 -0700146 struct blkioctl_request {
147 int number;
148 const char* name;
149 };
150 const vector<blkioctl_request> blkioctl_requests = {
Alex Deymo72a68d82016-06-15 16:31:04 -0700151 {BLKDISCARD, "BLKDISCARD"},
Amin Hassani8f08cfc2017-06-23 12:42:00 -0700152 {BLKSECDISCARD, "BLKSECDISCARD"},
Alex Deymob86787c2016-05-12 18:46:25 -0700153#ifdef BLKZEROOUT
Alex Deymo72a68d82016-06-15 16:31:04 -0700154 {BLKZEROOUT, "BLKZEROOUT"},
Alex Deymob86787c2016-05-12 18:46:25 -0700155#endif
156 };
Alex Deymo72a68d82016-06-15 16:31:04 -0700157 for (const auto& req : blkioctl_requests) {
Alex Deymob86787c2016-05-12 18:46:25 -0700158 int error = 0;
Alex Deymo72a68d82016-06-15 16:31:04 -0700159 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
Alex Deymob86787c2016-05-12 18:46:25 -0700160 error == 0) {
161 return true;
162 }
163 LOG(WARNING) << "Error discarding the last "
164 << (part_size - data_size) / 1024 << " KiB using ioctl("
Alex Deymo72a68d82016-06-15 16:31:04 -0700165 << req.name << ")";
Alex Deymob86787c2016-05-12 18:46:25 -0700166 }
167 return false;
168}
169
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700170} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700171
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800172
173// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
174// arithmetic.
175static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
176 return part * norm / total;
177}
178
179void DeltaPerformer::LogProgress(const char* message_prefix) {
180 // Format operations total count and percentage.
181 string total_operations_str("?");
182 string completed_percentage_str("");
183 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700184 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800185 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
186 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700187 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700188 IntRatio(next_operation_num_, num_total_operations_,
189 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800190 }
191
192 // Format download total count and percentage.
193 size_t payload_size = install_plan_->payload_size;
194 string payload_size_str("?");
195 string downloaded_percentage_str("");
196 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700197 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800198 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
199 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700200 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700201 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800202 }
203
204 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
205 << "/" << total_operations_str << " operations"
206 << completed_percentage_str << ", " << total_bytes_received_
207 << "/" << payload_size_str << " bytes downloaded"
208 << downloaded_percentage_str << ", overall progress "
209 << overall_progress_ << "%";
210}
211
212void DeltaPerformer::UpdateOverallProgress(bool force_log,
213 const char* message_prefix) {
214 // Compute our download and overall progress.
215 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800216 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
217 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800218 // Only consider download progress if its total size is known; otherwise
219 // adjust the operations weight to compensate for the absence of download
220 // progress. Also, make sure to cap the download portion at
221 // kProgressDownloadWeight, in case we end up downloading more than we
222 // initially expected (this indicates a problem, but could generally happen).
223 // TODO(garnold) the correction of operations weight when we do not have the
224 // total payload size, as well as the conditional guard below, should both be
225 // eliminated once we ensure that the payload_size in the install plan is
226 // always given and is non-zero. This currently isn't the case during unit
227 // tests (see chromium-os:37969).
228 size_t payload_size = install_plan_->payload_size;
229 unsigned actual_operations_weight = kProgressOperationsWeight;
230 if (payload_size)
231 new_overall_progress += min(
232 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
233 kProgressDownloadWeight)),
234 kProgressDownloadWeight);
235 else
236 actual_operations_weight += kProgressDownloadWeight;
237
238 // Only add completed operations if their total number is known; we definitely
239 // expect an update to have at least one operation, so the expectation is that
240 // this will eventually reach |actual_operations_weight|.
241 if (num_total_operations_)
242 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
243 actual_operations_weight);
244
245 // Progress ratio cannot recede, unless our assumptions about the total
246 // payload size, total number of operations, or the monotonicity of progress
247 // is breached.
248 if (new_overall_progress < overall_progress_) {
249 LOG(WARNING) << "progress counter receded from " << overall_progress_
250 << "% down to " << new_overall_progress << "%; this is a bug";
251 force_log = true;
252 }
253 overall_progress_ = new_overall_progress;
254
255 // Update chunk index, log as needed: if forced by called, or we completed a
256 // progress chunk, or a timeout has expired.
257 base::Time curr_time = base::Time::Now();
258 unsigned curr_progress_chunk =
259 overall_progress_ * kProgressLogMaxChunks / 100;
260 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
261 curr_time > forced_progress_log_time_) {
262 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
263 LogProgress(message_prefix);
264 }
265 last_progress_chunk_ = curr_progress_chunk;
266}
267
268
Gilad Arnoldfe133932014-01-14 12:25:50 -0800269size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
270 size_t max) {
271 const size_t count = *count_p;
272 if (!count)
273 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700274 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800275 const char* bytes_start = *bytes_p;
276 const char* bytes_end = bytes_start + read_len;
277 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
278 *bytes_p = bytes_end;
279 *count_p = count - read_len;
280 return read_len;
281}
282
283
284bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
285 ErrorCode* error) {
286 if (op_result)
287 return true;
288
Alex Deymo3d009062016-05-13 15:51:25 -0700289 size_t partition_first_op_num =
290 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800291 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700292 << next_operation_num_ << ", which is the operation "
293 << next_operation_num_ - partition_first_op_num
294 << " in partition \""
295 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700296 if (*error == ErrorCode::kSuccess)
297 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800298 return false;
299}
300
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700302 int err = -CloseCurrentPartition();
Sen Jiangf6813802015-11-03 21:27:29 -0800303 LOG_IF(ERROR, !payload_hash_calculator_.Finalize() ||
304 !signed_hash_calculator_.Finalize())
305 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800306 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700307 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
308 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800309 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800310 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700311 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700312}
313
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700314int DeltaPerformer::CloseCurrentPartition() {
315 int err = 0;
316 if (source_fd_ && !source_fd_->Close()) {
317 err = errno;
318 PLOG(ERROR) << "Error closing source partition";
319 if (!err)
320 err = 1;
321 }
322 source_fd_.reset();
323 source_path_.clear();
324
325 if (target_fd_ && !target_fd_->Close()) {
326 err = errno;
327 PLOG(ERROR) << "Error closing target partition";
328 if (!err)
329 err = 1;
330 }
331 target_fd_.reset();
332 target_path_.clear();
333 return -err;
334}
335
336bool DeltaPerformer::OpenCurrentPartition() {
337 if (current_partition_ >= partitions_.size())
338 return false;
339
340 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiang889c65d2015-11-17 15:04:02 -0800341 // Open source fds if we have a delta payload with minor version >= 2.
Alex Deymo64d98782016-02-05 18:03:48 -0800342 if (install_plan_->payload_type == InstallPayloadType::kDelta &&
Sen Jiang889c65d2015-11-17 15:04:02 -0800343 GetMinorVersion() != kInPlaceMinorPayloadVersion) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700344 source_path_ = install_plan_->partitions[current_partition_].source_path;
345 int err;
346 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, &err);
347 if (!source_fd_) {
348 LOG(ERROR) << "Unable to open source partition "
349 << partition.partition_name() << " on slot "
350 << BootControlInterface::SlotName(install_plan_->source_slot)
351 << ", file " << source_path_;
352 return false;
353 }
354 }
355
356 target_path_ = install_plan_->partitions[current_partition_].target_path;
357 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700358
Amin Hassani7ecda262017-07-11 17:10:50 -0700359 int flags = O_RDWR;
360 if (!is_interactive_)
361 flags |= O_DSYNC;
362
363 LOG(INFO) << "Opening " << target_path_ << " partition with"
364 << (is_interactive_ ? "out" : "") << " O_DSYNC";
365
366 target_fd_ = OpenFile(target_path_.c_str(), flags, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700367 if (!target_fd_) {
368 LOG(ERROR) << "Unable to open target partition "
369 << partition.partition_name() << " on slot "
370 << BootControlInterface::SlotName(install_plan_->target_slot)
371 << ", file " << target_path_;
372 return false;
373 }
Alex Deymob86787c2016-05-12 18:46:25 -0700374
375 LOG(INFO) << "Applying " << partition.operations().size()
376 << " operations to partition \"" << partition.partition_name()
377 << "\"";
378
379 // Discard the end of the partition, but ignore failures.
380 DiscardPartitionTail(
381 target_fd_, install_plan_->partitions[current_partition_].target_size);
382
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700383 return true;
384}
385
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700386namespace {
387
388void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700389 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800390 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
391 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700392}
393
Alex Deymo39910dc2015-11-09 17:04:30 -0800394void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700395 for (const PartitionUpdate& partition : partitions) {
396 LogPartitionInfoHash(partition.old_partition_info(),
397 "old " + partition.partition_name());
398 LogPartitionInfoHash(partition.new_partition_info(),
399 "new " + partition.partition_name());
400 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700401}
402
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700403} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700404
Sen Jiangb8060e42015-09-24 17:30:50 -0700405bool DeltaPerformer::GetMetadataSignatureSizeOffset(
406 uint64_t* out_offset) const {
407 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
408 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
409 return true;
410 }
411 return false;
Don Garrett4d039442013-10-28 18:40:06 -0700412}
413
Sen Jiangb8060e42015-09-24 17:30:50 -0700414bool DeltaPerformer::GetManifestOffset(uint64_t* out_offset) const {
415 // Actual manifest begins right after the manifest size field or
416 // metadata signature size field if major version >= 2.
417 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
418 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
419 return true;
420 }
421 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
422 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize +
423 kDeltaMetadataSignatureSizeSize;
424 return true;
425 }
426 LOG(ERROR) << "Unknown major payload version: " << major_payload_version_;
427 return false;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700428}
429
Gilad Arnoldfe133932014-01-14 12:25:50 -0800430uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800431 return metadata_size_;
432}
433
Sen Jiangb8060e42015-09-24 17:30:50 -0700434uint64_t DeltaPerformer::GetMajorVersion() const {
435 return major_payload_version_;
436}
437
Allie Woodfdf00512015-03-02 13:34:55 -0800438uint32_t DeltaPerformer::GetMinorVersion() const {
439 if (manifest_.has_minor_version()) {
440 return manifest_.minor_version();
441 } else {
Alex Deymo64d98782016-02-05 18:03:48 -0800442 return install_plan_->payload_type == InstallPayloadType::kDelta
443 ? kSupportedMinorPayloadVersion
444 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800445 }
446}
447
Gilad Arnolddaa27402014-01-23 11:56:17 -0800448bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
449 if (!manifest_parsed_)
450 return false;
451 *out_manifest_p = manifest_;
452 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800453}
454
Sen Jiangb8060e42015-09-24 17:30:50 -0700455bool DeltaPerformer::IsHeaderParsed() const {
456 return metadata_size_ != 0;
457}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700458
Darin Petkov9574f7e2011-01-13 10:48:12 -0800459DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700460 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700461 *error = ErrorCode::kSuccess;
Sen Jiangb8060e42015-09-24 17:30:50 -0700462 uint64_t manifest_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700463
Sen Jiangb8060e42015-09-24 17:30:50 -0700464 if (!IsHeaderParsed()) {
465 // Ensure we have data to cover the major payload version.
466 if (payload.size() < kDeltaManifestSizeOffset)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800467 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700468
Gilad Arnoldfe133932014-01-14 12:25:50 -0800469 // Validate the magic string.
Sen Jiangb8060e42015-09-24 17:30:50 -0700470 if (memcmp(payload.data(), kDeltaMagic, sizeof(kDeltaMagic)) != 0) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800471 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700472 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800473 return kMetadataParseError;
474 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800475
476 // Extract the payload version from the metadata.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800477 static_assert(sizeof(major_payload_version_) == kDeltaVersionSize,
478 "Major payload version size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700479 memcpy(&major_payload_version_,
480 &payload[kDeltaVersionOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800481 kDeltaVersionSize);
482 // switch big endian to host
Sen Jiangb8060e42015-09-24 17:30:50 -0700483 major_payload_version_ = be64toh(major_payload_version_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800484
Alex Deymo7a2c47e2015-11-04 00:47:12 -0800485 if (major_payload_version_ != supported_major_version_ &&
486 major_payload_version_ != kChromeOSMajorPayloadVersion) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800487 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
Sen Jiangb8060e42015-09-24 17:30:50 -0700488 << major_payload_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700489 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800490 return kMetadataParseError;
491 }
492
Sen Jiangb8060e42015-09-24 17:30:50 -0700493 // Get the manifest offset now that we have payload version.
494 if (!GetManifestOffset(&manifest_offset)) {
495 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
496 return kMetadataParseError;
497 }
498 // Check again with the manifest offset.
499 if (payload.size() < manifest_offset)
500 return kMetadataParseInsufficientData;
501
Gilad Arnoldfe133932014-01-14 12:25:50 -0800502 // Next, parse the manifest size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800503 static_assert(sizeof(manifest_size_) == kDeltaManifestSizeSize,
504 "manifest_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700505 memcpy(&manifest_size_,
506 &payload[kDeltaManifestSizeOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800507 kDeltaManifestSizeSize);
Sen Jiangb8060e42015-09-24 17:30:50 -0700508 manifest_size_ = be64toh(manifest_size_); // switch big endian to host
509
Sen Jiangb8060e42015-09-24 17:30:50 -0700510 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
511 // Parse the metadata signature size.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800512 static_assert(sizeof(metadata_signature_size_) ==
513 kDeltaMetadataSignatureSizeSize,
514 "metadata_signature_size size mismatch");
Sen Jiangb8060e42015-09-24 17:30:50 -0700515 uint64_t metadata_signature_size_offset;
516 if (!GetMetadataSignatureSizeOffset(&metadata_signature_size_offset)) {
517 *error = ErrorCode::kError;
518 return kMetadataParseError;
519 }
Sen Jiang76bfa742015-10-12 17:13:26 -0700520 memcpy(&metadata_signature_size_,
Sen Jiangb8060e42015-09-24 17:30:50 -0700521 &payload[metadata_signature_size_offset],
522 kDeltaMetadataSignatureSizeSize);
Sen Jiang76bfa742015-10-12 17:13:26 -0700523 metadata_signature_size_ = be32toh(metadata_signature_size_);
Sen Jiangb8060e42015-09-24 17:30:50 -0700524 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800525
526 // If the metadata size is present in install plan, check for it immediately
527 // even before waiting for that many number of bytes to be downloaded in the
528 // payload. This will prevent any attack which relies on us downloading data
529 // beyond the expected metadata size.
Sen Jiang76bfa742015-10-12 17:13:26 -0700530 metadata_size_ = manifest_offset + manifest_size_;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800531 if (install_plan_->hash_checks_mandatory) {
532 if (install_plan_->metadata_size != metadata_size_) {
533 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
534 << install_plan_->metadata_size
535 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700536 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800537 return kMetadataParseError;
538 }
539 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700540 }
541
542 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700543 // metadata and its signature (if exist) to be read in before we can parse it.
544 if (payload.size() < metadata_size_ + metadata_signature_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800545 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700546
547 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700548 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700549 // that we just log once (instead of logging n times) if it takes n
550 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800551 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700552 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800553 } else {
554 // For mandatory-cases, we'd have already returned a kMetadataParseError
555 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
556 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
557 << install_plan_->metadata_size
558 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800559 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800560 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700561
Jay Srinivasanf4318702012-09-24 11:56:24 -0700562 // We have the full metadata in |payload|. Verify its integrity
563 // and authenticity based on the information we have in Omaha response.
Sen Jiang76bfa742015-10-12 17:13:26 -0700564 *error = ValidateMetadataSignature(payload);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700565 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800566 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800567 // The autoupdate_CatchBadSignatures test checks for this string
568 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800569 LOG(ERROR) << "Mandatory metadata signature validation failed";
570 return kMetadataParseError;
571 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700572
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800573 // For non-mandatory cases, just send a UMA stat.
574 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700575 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700576 }
577
Sen Jiangb8060e42015-09-24 17:30:50 -0700578 if (!GetManifestOffset(&manifest_offset)) {
579 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
580 return kMetadataParseError;
581 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800582 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb8060e42015-09-24 17:30:50 -0700583 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800584 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700585 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800586 return kMetadataParseError;
587 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800588
589 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800590 return kMetadataParseSuccess;
591}
592
Lann Martin39f57142017-07-14 09:18:42 -0600593#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
594 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
595 "UpdateEngine.DownloadAction.InstallOperation::" \
596 _op_name ".Duration", \
597 base::TimeTicks::Now() - _start_time, \
598 base::TimeDelta::FromMilliseconds(10), \
599 base::TimeDelta::FromMinutes(5), \
600 20);
601
Don Garrette410e0f2011-11-10 15:39:01 -0800602// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800603// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700604// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800605bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700606 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700607 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800608
609 // Update the total byte downloaded count and the progress logs.
610 total_bytes_received_ += count;
611 UpdateOverallProgress(false, "Completed ");
612
Gilad Arnoldfe133932014-01-14 12:25:50 -0800613 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700614 // Read data up to the needed limit; this is either maximium payload header
615 // size, or the full metadata size (once it becomes known).
616 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800617 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700618 (do_read_header ? kMaxPayloadHeaderSize :
Sen Jiang76bfa742015-10-12 17:13:26 -0700619 metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800620
Gilad Arnolddaa27402014-01-23 11:56:17 -0800621 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700622 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800623 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800624 if (result == kMetadataParseInsufficientData) {
625 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700626 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800627 continue;
628
Don Garrette410e0f2011-11-10 15:39:01 -0800629 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800630 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700631
632 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700633 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700634 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800635 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700636
Gilad Arnoldfe133932014-01-14 12:25:50 -0800637 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800638 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700639
640 // This populates |partitions_| and the |install_plan.partitions| with the
641 // list of partitions from the manifest.
642 if (!ParseManifestPartitions(error))
643 return false;
644
645 num_total_operations_ = 0;
646 for (const auto& partition : partitions_) {
647 num_total_operations_ += partition.operations_size();
648 acc_num_operations_.push_back(num_total_operations_);
649 }
650
Darin Petkov73058b42010-10-06 16:32:19 -0700651 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800652 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700653 << "Unable to save the manifest metadata size.";
Alex Deymof25eb492016-02-26 00:20:08 -0800654 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestSignatureSize,
655 metadata_signature_size_))
656 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700657
Darin Petkov9b230572010-10-08 10:20:09 -0700658 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700659 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700660 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800661 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700662 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800663
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700664 if (!OpenCurrentPartition()) {
665 *error = ErrorCode::kInstallDeviceOpenError;
666 return false;
Allie Woodfdf00512015-03-02 13:34:55 -0800667 }
668
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800669 if (next_operation_num_ > 0)
670 UpdateOverallProgress(true, "Resuming after ");
671 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800673
674 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700675 // Check if we should cancel the current attempt for any reason.
676 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700677 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300678 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700679 return false;
680
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700681 // We know there are more operations to perform because we didn't reach the
682 // |num_total_operations_| limit yet.
683 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
684 CloseCurrentPartition();
685 current_partition_++;
686 if (!OpenCurrentPartition()) {
687 *error = ErrorCode::kInstallDeviceOpenError;
688 return false;
689 }
690 }
691 const size_t partition_operation_num = next_operation_num_ - (
692 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
693
Alex Deymoa12ee112015-08-12 22:19:32 -0700694 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700695 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800696
697 CopyDataToBuffer(&c_bytes, &count, op.data_length());
698
699 // Check whether we received all of the next operation's data payload.
700 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700701 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700702
Jay Srinivasanf4318702012-09-24 11:56:24 -0700703 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700704 // Otherwise, keep the old behavior. This serves as a knob to disable
705 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800706 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
707 // we would have already failed in ParsePayloadMetadata method and thus not
708 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700709 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700710 // Note: Validate must be called only if CanPerformInstallOperation is
711 // called. Otherwise, we might be failing operations before even if there
712 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800713 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700714 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800715 if (install_plan_->hash_checks_mandatory) {
716 LOG(ERROR) << "Mandatory operation hash check failed";
717 return false;
718 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700719
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800720 // For non-mandatory cases, just send a UMA stat.
721 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700722 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700723 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700724 }
725
Darin Petkov45580e42010-10-08 14:02:40 -0700726 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700727 ScopedTerminatorExitUnblocker exit_unblocker =
728 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800729
Lann Martin39f57142017-07-14 09:18:42 -0600730 base::TimeTicks op_start_time = base::TimeTicks::Now();
731
Gilad Arnoldfe133932014-01-14 12:25:50 -0800732 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700733 switch (op.type()) {
734 case InstallOperation::REPLACE:
735 case InstallOperation::REPLACE_BZ:
736 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700737 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600738 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700739 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700740 case InstallOperation::ZERO:
741 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700742 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600743 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700744 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700745 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700746 op_result = PerformMoveOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600747 OP_DURATION_HISTOGRAM("MOVE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700748 break;
749 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700750 op_result = PerformBsdiffOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600751 OP_DURATION_HISTOGRAM("BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700752 break;
753 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700754 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600755 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700756 break;
757 case InstallOperation::SOURCE_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700758 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600759 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700760 break;
Amin Hassani5ef5d452017-08-04 13:10:59 -0700761 case InstallOperation::PUFFDIFF:
762 // TODO(ahassani): Later add PerformPuffdiffOperation(op, error);
Alex Deymoeecb0a52017-05-19 15:15:08 -0700763 op_result = false;
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800764 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700765 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700766 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700767 }
768 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800769 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800770
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700771 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800772 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700773 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700774 }
Sen Jiangf6813802015-11-03 21:27:29 -0800775
776 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800777 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800778 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800779 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
780 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800781 if (manifest_.signatures_offset() != buffer_offset_) {
782 LOG(ERROR) << "Payload signatures offset points to blob offset "
783 << manifest_.signatures_offset()
784 << " but signatures are expected at offset "
785 << buffer_offset_;
786 *error = ErrorCode::kDownloadPayloadVerificationError;
787 return false;
788 }
789 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
790 // Needs more data to cover entire signature.
791 if (buffer_.size() < manifest_.signatures_size())
792 return true;
793 if (!ExtractSignatureMessage()) {
794 LOG(ERROR) << "Extract payload signature failed.";
795 *error = ErrorCode::kDownloadPayloadVerificationError;
796 return false;
797 }
798 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800799 // Since we extracted the SignatureMessage we need to advance the
800 // checkpoint, otherwise we would reload the signature and try to extract
801 // it again.
802 CheckpointUpdateProgress();
Sen Jiangf6813802015-11-03 21:27:29 -0800803 }
804
Don Garrette410e0f2011-11-10 15:39:01 -0800805 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700806}
807
David Zeuthen8f191b22013-08-06 12:27:50 -0700808bool DeltaPerformer::IsManifestValid() {
809 return manifest_valid_;
810}
811
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700812bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
813 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
814 partitions_.clear();
815 for (const PartitionUpdate& partition : manifest_.partitions()) {
816 partitions_.push_back(partition);
817 }
818 manifest_.clear_partitions();
819 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
820 LOG(INFO) << "Converting update information from old format.";
821 PartitionUpdate root_part;
822 root_part.set_partition_name(kLegacyPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700823#ifdef __ANDROID__
824 LOG(WARNING) << "Legacy payload major version provided to an Android "
825 "build. Assuming no post-install. Please use major version "
826 "2 or newer.";
827 root_part.set_run_postinstall(false);
828#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700829 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700830#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700831 if (manifest_.has_old_rootfs_info()) {
832 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
833 manifest_.clear_old_rootfs_info();
834 }
835 if (manifest_.has_new_rootfs_info()) {
836 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
837 manifest_.clear_new_rootfs_info();
838 }
839 *root_part.mutable_operations() = manifest_.install_operations();
840 manifest_.clear_install_operations();
841 partitions_.push_back(std::move(root_part));
842
843 PartitionUpdate kern_part;
844 kern_part.set_partition_name(kLegacyPartitionNameKernel);
845 kern_part.set_run_postinstall(false);
846 if (manifest_.has_old_kernel_info()) {
847 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
848 manifest_.clear_old_kernel_info();
849 }
850 if (manifest_.has_new_kernel_info()) {
851 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
852 manifest_.clear_new_kernel_info();
853 }
854 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
855 manifest_.clear_kernel_install_operations();
856 partitions_.push_back(std::move(kern_part));
857 }
858
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700859 // Fill in the InstallPlan::partitions based on the partitions from the
860 // payload.
861 install_plan_->partitions.clear();
862 for (const auto& partition : partitions_) {
863 InstallPlan::Partition install_part;
864 install_part.name = partition.partition_name();
865 install_part.run_postinstall =
866 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800867 if (install_part.run_postinstall) {
868 install_part.postinstall_path =
869 (partition.has_postinstall_path() ? partition.postinstall_path()
870 : kPostinstallDefaultScript);
871 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700872 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800873 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700874
875 if (partition.has_old_partition_info()) {
876 const PartitionInfo& info = partition.old_partition_info();
877 install_part.source_size = info.size();
878 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
879 }
880
881 if (!partition.has_new_partition_info()) {
882 LOG(ERROR) << "Unable to get new partition hash info on partition "
883 << install_part.name << ".";
884 *error = ErrorCode::kDownloadNewPartitionInfoError;
885 return false;
886 }
887 const PartitionInfo& info = partition.new_partition_info();
888 install_part.target_size = info.size();
889 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
890
891 install_plan_->partitions.push_back(install_part);
892 }
893
Alex Deymo542c19b2015-12-03 07:43:31 -0300894 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700895 LOG(ERROR) << "Unable to determine all the partition devices.";
896 *error = ErrorCode::kInstallDeviceOpenError;
897 return false;
898 }
899 LogPartitionInfo(partitions_);
900 return true;
901}
902
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700903bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700904 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700905 // If we don't have a data blob we can apply it right away.
906 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700907 return true;
908
909 // See if we have the entire data blob in the buffer
910 if (operation.data_offset() < buffer_offset_) {
911 LOG(ERROR) << "we threw away data it seems?";
912 return false;
913 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700914
Gilad Arnoldfe133932014-01-14 12:25:50 -0800915 return (operation.data_offset() + operation.data_length() <=
916 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700917}
918
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700919bool DeltaPerformer::PerformReplaceOperation(
920 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700921 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700922 operation.type() == InstallOperation::REPLACE_BZ ||
923 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700924
925 // Since we delete data off the beginning of the buffer as we use it,
926 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700927 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
928 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700929
Darin Petkov437adc42010-10-07 13:12:24 -0700930 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -0800931 if (ExtractSignatureMessageFromOperation(operation)) {
932 // If this is dummy replace operation, we ignore it after extracting the
933 // signature.
934 DiscardBuffer(true, 0);
935 return true;
936 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700937
Alex Deymo05322872015-09-30 09:50:24 -0700938 // Setup the ExtentWriter stack based on the operation type.
Ben Chan5c02c132017-06-27 07:10:36 -0700939 std::unique_ptr<ExtentWriter> writer = base::MakeUnique<ZeroPadExtentWriter>(
940 base::MakeUnique<DirectExtentWriter>());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700941
Alex Deymo2d621a32015-10-01 11:09:01 -0700942 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700943 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700944 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
945 writer.reset(new XzExtentWriter(std::move(writer)));
946 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700947
948 // Create a vector of extents to pass to the ExtentWriter.
949 vector<Extent> extents;
950 for (int i = 0; i < operation.dst_extents_size(); i++) {
951 extents.push_back(operation.dst_extents(i));
952 }
953
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700954 TEST_AND_RETURN_FALSE(writer->Init(target_fd_, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800955 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700956 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700957
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700958 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -0800959 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700960 return true;
961}
962
Alex Deymo79715ad2015-10-02 14:27:53 -0700963bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700964 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700965 CHECK(operation.type() == InstallOperation::DISCARD ||
966 operation.type() == InstallOperation::ZERO);
967
968 // These operations have no blob.
969 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
970 TEST_AND_RETURN_FALSE(!operation.has_data_length());
971
Alex Deymo05e0e382015-12-07 20:18:16 -0800972#ifdef BLKZEROOUT
973 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -0700974 int request =
975 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Alex Deymo05e0e382015-12-07 20:18:16 -0800976#else // !defined(BLKZEROOUT)
977 bool attempt_ioctl = false;
978 int request = 0;
979#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -0700980
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700981 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700982 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700983 const uint64_t start = extent.start_block() * block_size_;
984 const uint64_t length = extent.num_blocks() * block_size_;
985 if (attempt_ioctl) {
986 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700987 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -0700988 continue;
989 attempt_ioctl = false;
990 zeros.resize(16 * block_size_);
991 }
992 // In case of failure, we fall back to writing 0 to the selected region.
993 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700994 uint64_t chunk_length = min(length - offset,
995 static_cast<uint64_t>(zeros.size()));
Amin Hassani69583ba2017-08-29 11:40:03 -0700996 TEST_AND_RETURN_FALSE(utils::PWriteAll(
997 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -0700998 }
999 }
1000 return true;
1001}
1002
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001003bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001004 // Calculate buffer size. Note, this function doesn't do a sliding
1005 // window to copy in case the source and destination blocks overlap.
1006 // If we wanted to do a sliding window, we could program the server
1007 // to generate deltas that effectively did a sliding window.
1008
1009 uint64_t blocks_to_read = 0;
1010 for (int i = 0; i < operation.src_extents_size(); i++)
1011 blocks_to_read += operation.src_extents(i).num_blocks();
1012
1013 uint64_t blocks_to_write = 0;
1014 for (int i = 0; i < operation.dst_extents_size(); i++)
1015 blocks_to_write += operation.dst_extents(i).num_blocks();
1016
1017 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001018 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -07001019
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001020 // Read in bytes.
1021 ssize_t bytes_read = 0;
1022 for (int i = 0; i < operation.src_extents_size(); i++) {
1023 ssize_t bytes_read_this_iteration = 0;
1024 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001025 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001026 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001027 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001028 &buf[bytes_read],
1029 bytes,
1030 extent.start_block() * block_size_,
1031 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001032 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +02001033 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001034 bytes_read += bytes_read_this_iteration;
1035 }
1036
1037 // Write bytes out.
1038 ssize_t bytes_written = 0;
1039 for (int i = 0; i < operation.dst_extents_size(); i++) {
1040 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001041 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001042 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001043 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001044 &buf[bytes_written],
1045 bytes,
1046 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001047 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001048 }
1049 DCHECK_EQ(bytes_written, bytes_read);
1050 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1051 return true;
1052}
1053
Allie Wood9f6f0a52015-03-30 11:25:47 -07001054namespace {
1055
1056// Takes |extents| and fills an empty vector |blocks| with a block index for
1057// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
1058void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
1059 vector<uint64_t>* blocks) {
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001060 for (const Extent& ext : extents) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001061 for (uint64_t j = 0; j < ext.num_blocks(); j++)
1062 blocks->push_back(ext.start_block() + j);
1063 }
1064}
1065
1066// Takes |extents| and returns the number of blocks in those extents.
1067uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
1068 uint64_t sum = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001069 for (const Extent& ext : extents) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001070 sum += ext.num_blocks();
1071 }
1072 return sum;
1073}
1074
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001075// Compare |calculated_hash| with source hash in |operation|, return false and
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001076// dump hash and set |error| if don't match.
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001077bool ValidateSourceHash(const brillo::Blob& calculated_hash,
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001078 const InstallOperation& operation,
1079 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001080 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1081 operation.src_sha256_hash().end());
1082 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001083 LOG(ERROR) << "The hash of the source data on disk for this operation "
1084 << "doesn't match the expected value. This could mean that the "
1085 << "delta update payload was targeted for another version, or "
1086 << "that the source partition was modified after it was "
1087 << "installed, for example, by mounting a filesystem.";
1088 LOG(ERROR) << "Expected: sha256|hex = "
1089 << base::HexEncode(expected_source_hash.data(),
1090 expected_source_hash.size());
1091 LOG(ERROR) << "Calculated: sha256|hex = "
1092 << base::HexEncode(calculated_hash.data(),
1093 calculated_hash.size());
1094
1095 vector<string> source_extents;
1096 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001097 source_extents.push_back(
1098 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1099 static_cast<uint64_t>(ext.start_block()),
1100 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001101 }
1102 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1103 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001104
1105 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001106 return false;
1107 }
1108 return true;
1109}
1110
Allie Wood9f6f0a52015-03-30 11:25:47 -07001111} // namespace
1112
1113bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001114 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001115 if (operation.has_src_length())
1116 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1117 if (operation.has_dst_length())
1118 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1119
1120 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
1121 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
1122 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
1123
1124 // Create vectors of all the individual src/dst blocks.
1125 vector<uint64_t> src_blocks;
1126 vector<uint64_t> dst_blocks;
1127 ExtentsToBlocks(operation.src_extents(), &src_blocks);
1128 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
1129 DCHECK_EQ(src_blocks.size(), blocks_to_read);
1130 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
1131
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001132 brillo::Blob buf(block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001133 ssize_t bytes_read = 0;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001134 HashCalculator source_hasher;
Allie Wood9f6f0a52015-03-30 11:25:47 -07001135 // Read/write one block at a time.
1136 for (uint64_t i = 0; i < blocks_to_read; i++) {
1137 ssize_t bytes_read_this_iteration = 0;
1138 uint64_t src_block = src_blocks[i];
1139 uint64_t dst_block = dst_blocks[i];
1140
1141 // Read in bytes.
1142 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001143 utils::PReadAll(source_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001144 buf.data(),
1145 block_size_,
1146 src_block * block_size_,
1147 &bytes_read_this_iteration));
1148
1149 // Write bytes out.
1150 TEST_AND_RETURN_FALSE(
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001151 utils::PWriteAll(target_fd_,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001152 buf.data(),
1153 block_size_,
1154 dst_block * block_size_));
1155
1156 bytes_read += bytes_read_this_iteration;
1157 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
1158 static_cast<ssize_t>(block_size_));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001159
1160 if (operation.has_src_sha256_hash())
1161 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), buf.size()));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001162 }
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001163
1164 if (operation.has_src_sha256_hash()) {
1165 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1166 TEST_AND_RETURN_FALSE(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001167 ValidateSourceHash(source_hasher.raw_hash(), operation, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001168 }
1169
Allie Wood9f6f0a52015-03-30 11:25:47 -07001170 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
1171 return true;
1172}
1173
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001174bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1175 const RepeatedPtrField<Extent>& extents,
1176 uint64_t block_size,
1177 uint64_t full_length,
1178 string* positions_string) {
1179 string ret;
1180 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001181 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001182 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001183 uint64_t this_length =
1184 min(full_length - length,
1185 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001186 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001187 length += this_length;
1188 }
1189 TEST_AND_RETURN_FALSE(length == full_length);
1190 if (!ret.empty())
1191 ret.resize(ret.size() - 1); // Strip trailing comma off
1192 *positions_string = ret;
1193 return true;
1194}
1195
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001196bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001197 // Since we delete data off the beginning of the buffer as we use it,
1198 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001199 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1200 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001201
1202 string input_positions;
1203 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1204 block_size_,
1205 operation.src_length(),
1206 &input_positions));
1207 string output_positions;
1208 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1209 block_size_,
1210 operation.dst_length(),
1211 &output_positions));
1212
Sen Jiang7a659092016-05-10 15:31:46 -07001213 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1214 target_path_.c_str(),
1215 buffer_.data(),
1216 buffer_.size(),
1217 input_positions.c_str(),
1218 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001219 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001220
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001221 if (operation.dst_length() % block_size_) {
1222 // Zero out rest of final block.
1223 // TODO(adlr): build this into bspatch; it's more efficient that way.
1224 const Extent& last_extent =
1225 operation.dst_extents(operation.dst_extents_size() - 1);
1226 const uint64_t end_byte =
1227 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1228 const uint64_t begin_byte =
1229 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001230 brillo::Blob zeros(end_byte - begin_byte);
Amin Hassani69583ba2017-08-29 11:40:03 -07001231 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1232 target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001233 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001234 return true;
1235}
1236
Allie Wood9f6f0a52015-03-30 11:25:47 -07001237bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001238 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001239 // Since we delete data off the beginning of the buffer as we use it,
1240 // the data we need should be exactly at the beginning of the buffer.
1241 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1242 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1243 if (operation.has_src_length())
1244 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1245 if (operation.has_dst_length())
1246 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1247
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001248 if (operation.has_src_sha256_hash()) {
1249 HashCalculator source_hasher;
1250 const uint64_t kMaxBlocksToRead = 512; // 2MB if block size is 4KB
1251 brillo::Blob buf(kMaxBlocksToRead * block_size_);
1252 for (const Extent& extent : operation.src_extents()) {
1253 for (uint64_t i = 0; i < extent.num_blocks(); i += kMaxBlocksToRead) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001254 uint64_t blocks_to_read = min(
1255 kMaxBlocksToRead, static_cast<uint64_t>(extent.num_blocks()) - i);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001256 ssize_t bytes_to_read = blocks_to_read * block_size_;
1257 ssize_t bytes_read_this_iteration = 0;
1258 TEST_AND_RETURN_FALSE(
1259 utils::PReadAll(source_fd_, buf.data(), bytes_to_read,
1260 (extent.start_block() + i) * block_size_,
1261 &bytes_read_this_iteration));
1262 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes_to_read);
1263 TEST_AND_RETURN_FALSE(source_hasher.Update(buf.data(), bytes_to_read));
1264 }
1265 }
1266 TEST_AND_RETURN_FALSE(source_hasher.Finalize());
1267 TEST_AND_RETURN_FALSE(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001268 ValidateSourceHash(source_hasher.raw_hash(), operation, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001269 }
1270
Allie Wood9f6f0a52015-03-30 11:25:47 -07001271 string input_positions;
1272 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1273 block_size_,
1274 operation.src_length(),
1275 &input_positions));
1276 string output_positions;
1277 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1278 block_size_,
1279 operation.dst_length(),
1280 &output_positions));
1281
Sen Jiang7a659092016-05-10 15:31:46 -07001282 TEST_AND_RETURN_FALSE(bsdiff::bspatch(source_path_.c_str(),
1283 target_path_.c_str(),
1284 buffer_.data(),
1285 buffer_.size(),
1286 input_positions.c_str(),
1287 output_positions.c_str()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001288 DiscardBuffer(true, buffer_.size());
1289 return true;
1290}
1291
Sen Jiangf6813802015-11-03 21:27:29 -08001292bool DeltaPerformer::ExtractSignatureMessageFromOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001293 const InstallOperation& operation) {
1294 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001295 !manifest_.has_signatures_offset() ||
1296 manifest_.signatures_offset() != operation.data_offset()) {
1297 return false;
1298 }
1299 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1300 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001301 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1302 return true;
1303}
1304
1305bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001306 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1307 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1308 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001309 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001310 buffer_.begin(),
1311 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001312
1313 // Save the signature blob because if the update is interrupted after the
1314 // download phase we don't go through this path anymore. Some alternatives to
1315 // consider:
1316 //
1317 // 1. On resume, re-download the signature blob from the server and re-verify
1318 // it.
1319 //
1320 // 2. Verify the signature as soon as it's received and don't checkpoint the
1321 // blob and the signed sha-256 context.
1322 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001323 string(signatures_message_data_.begin(),
1324 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001325 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001326
Darin Petkovd7061ab2010-10-06 14:37:09 -07001327 LOG(INFO) << "Extracted signature data of size "
1328 << manifest_.signatures_size() << " at "
1329 << manifest_.signatures_offset();
1330 return true;
1331}
1332
David Zeuthene7f89172013-10-31 10:21:04 -07001333bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
Alex Deymo542c19b2015-12-03 07:43:31 -03001334 if (hardware_->IsOfficialBuild() ||
David Zeuthene7f89172013-10-31 10:21:04 -07001335 utils::FileExists(public_key_path_.c_str()) ||
1336 install_plan_->public_key_rsa.empty())
1337 return false;
1338
1339 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1340 out_tmp_key))
1341 return false;
1342
1343 return true;
1344}
1345
David Zeuthena99981f2013-04-29 13:42:47 -07001346ErrorCode DeltaPerformer::ValidateMetadataSignature(
Sen Jiang76bfa742015-10-12 17:13:26 -07001347 const brillo::Blob& payload) {
1348 if (payload.size() < metadata_size_ + metadata_signature_size_)
1349 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001350
Sen Jiang76bfa742015-10-12 17:13:26 -07001351 brillo::Blob metadata_signature_blob, metadata_signature_protobuf_blob;
1352 if (!install_plan_->metadata_signature.empty()) {
1353 // Convert base64-encoded signature to raw bytes.
1354 if (!brillo::data_encoding::Base64Decode(
1355 install_plan_->metadata_signature, &metadata_signature_blob)) {
1356 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1357 << install_plan_->metadata_signature;
1358 return ErrorCode::kDownloadMetadataSignatureError;
1359 }
1360 } else if (major_payload_version_ == kBrilloMajorPayloadVersion) {
1361 metadata_signature_protobuf_blob.assign(payload.begin() + metadata_size_,
1362 payload.begin() + metadata_size_ +
1363 metadata_signature_size_);
1364 }
1365
1366 if (metadata_signature_blob.empty() &&
1367 metadata_signature_protobuf_blob.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001368 if (install_plan_->hash_checks_mandatory) {
Sen Jiang76bfa742015-10-12 17:13:26 -07001369 LOG(ERROR) << "Missing mandatory metadata signature in both Omaha "
1370 << "response and payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001371 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001372 }
1373
Jay Srinivasanf4318702012-09-24 11:56:24 -07001374 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001375 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001376 }
1377
David Zeuthene7f89172013-10-31 10:21:04 -07001378 // See if we should use the public RSA key in the Omaha response.
1379 base::FilePath path_to_public_key(public_key_path_);
1380 base::FilePath tmp_key;
1381 if (GetPublicKeyFromResponse(&tmp_key))
1382 path_to_public_key = tmp_key;
1383 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1384 if (tmp_key.empty())
1385 tmp_key_remover.set_should_remove(false);
1386
1387 LOG(INFO) << "Verifying metadata hash signature using public key: "
1388 << path_to_public_key.value();
1389
Alex Deymo39910dc2015-11-09 17:04:30 -08001390 HashCalculator metadata_hasher;
Sen Jiang76bfa742015-10-12 17:13:26 -07001391 metadata_hasher.Update(payload.data(), metadata_size_);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001392 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001393 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001394 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001395 }
1396
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001397 brillo::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001398 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001399 if (calculated_metadata_hash.empty()) {
1400 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001401 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001402 }
1403
Sen Jiang76bfa742015-10-12 17:13:26 -07001404 if (!metadata_signature_blob.empty()) {
1405 brillo::Blob expected_metadata_hash;
1406 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature_blob,
1407 path_to_public_key.value(),
1408 &expected_metadata_hash)) {
1409 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
1410 return ErrorCode::kDownloadMetadataSignatureError;
1411 }
1412 if (calculated_metadata_hash != expected_metadata_hash) {
1413 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
1414 utils::HexDumpVector(expected_metadata_hash);
1415 LOG(ERROR) << "Calculated hash = ";
1416 utils::HexDumpVector(calculated_metadata_hash);
1417 return ErrorCode::kDownloadMetadataSignatureMismatch;
1418 }
1419 } else {
1420 if (!PayloadVerifier::VerifySignature(metadata_signature_protobuf_blob,
1421 path_to_public_key.value(),
1422 calculated_metadata_hash)) {
1423 LOG(ERROR) << "Manifest hash verification failed.";
1424 return ErrorCode::kDownloadMetadataSignatureMismatch;
1425 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001426 }
1427
David Zeuthenbc27aac2013-11-26 11:17:48 -08001428 // The autoupdate_CatchBadSignatures test checks for this string in
1429 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001430 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001431 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001432}
1433
Gilad Arnold21504f02013-05-24 08:51:22 -07001434ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001435 // Perform assorted checks to sanity check the manifest, make sure it
1436 // matches data from other sources, and that it is a supported version.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001437
Alex Deymo64d98782016-02-05 18:03:48 -08001438 bool has_old_fields =
1439 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1440 for (const PartitionUpdate& partition : manifest_.partitions()) {
1441 has_old_fields = has_old_fields || partition.has_old_partition_info();
1442 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001443
Alex Deymo64d98782016-02-05 18:03:48 -08001444 // The presence of an old partition hash is the sole indicator for a delta
1445 // update.
1446 InstallPayloadType actual_payload_type =
1447 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1448
1449 if (install_plan_->payload_type == InstallPayloadType::kUnknown) {
1450 LOG(INFO) << "Detected a '"
1451 << InstallPayloadTypeToString(actual_payload_type)
1452 << "' payload.";
1453 install_plan_->payload_type = actual_payload_type;
1454 } else if (install_plan_->payload_type != actual_payload_type) {
1455 LOG(ERROR) << "InstallPlan expected a '"
1456 << InstallPayloadTypeToString(install_plan_->payload_type)
1457 << "' payload but the downloaded manifest contains a '"
1458 << InstallPayloadTypeToString(actual_payload_type)
1459 << "' payload.";
1460 return ErrorCode::kPayloadMismatchedType;
1461 }
1462
1463 // Check that the minor version is compatible.
1464 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001465 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1466 LOG(ERROR) << "Manifest contains minor version "
1467 << manifest_.minor_version()
1468 << ", but all full payloads should have version "
1469 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001470 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001471 }
1472 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001473 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001474 LOG(ERROR) << "Manifest contains minor version "
1475 << manifest_.minor_version()
1476 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001477 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001478 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001479 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001480 }
1481
Sen Jiang3e728fe2015-11-05 11:37:23 -08001482 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
1483 if (manifest_.has_old_rootfs_info() ||
1484 manifest_.has_new_rootfs_info() ||
1485 manifest_.has_old_kernel_info() ||
1486 manifest_.has_new_kernel_info() ||
1487 manifest_.install_operations_size() != 0 ||
1488 manifest_.kernel_install_operations_size() != 0) {
1489 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1490 << "major payload version 1, but the payload major version is "
1491 << major_payload_version_;
1492 return ErrorCode::kPayloadMismatchedType;
1493 }
1494 }
1495
Gilad Arnold21504f02013-05-24 08:51:22 -07001496 // TODO(garnold) we should be adding more and more manifest checks, such as
1497 // partition boundaries etc (see chromium-os:37661).
1498
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001499 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001500}
1501
David Zeuthena99981f2013-04-29 13:42:47 -07001502ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001503 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001504 if (!operation.data_sha256_hash().size()) {
1505 if (!operation.data_length()) {
1506 // Operations that do not have any data blob won't have any operation hash
1507 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001508 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001509 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001510 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001511 }
1512
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001513 // No hash is present for an operation that has data blobs. This shouldn't
1514 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001515 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001516 // hashes. So if it happens it means either we've turned operation hash
1517 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001518 // One caveat though: The last operation is a dummy signature operation
1519 // that doesn't have a hash at the time the manifest is created. So we
1520 // should not complaint about that operation. This operation can be
1521 // recognized by the fact that it's offset is mentioned in the manifest.
1522 if (manifest_.signatures_offset() &&
1523 manifest_.signatures_offset() == operation.data_offset()) {
1524 LOG(INFO) << "Skipping hash verification for signature operation "
1525 << next_operation_num_ + 1;
1526 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001527 if (install_plan_->hash_checks_mandatory) {
1528 LOG(ERROR) << "Missing mandatory operation hash for operation "
1529 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001530 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001531 }
1532
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001533 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1534 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001535 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001536 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001537 }
1538
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001539 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001540 expected_op_hash.assign(operation.data_sha256_hash().data(),
1541 (operation.data_sha256_hash().data() +
1542 operation.data_sha256_hash().size()));
1543
Alex Deymo39910dc2015-11-09 17:04:30 -08001544 HashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001545 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001546 if (!operation_hasher.Finalize()) {
1547 LOG(ERROR) << "Unable to compute actual hash of operation "
1548 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001549 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001550 }
1551
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001552 brillo::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001553 if (calculated_op_hash != expected_op_hash) {
1554 LOG(ERROR) << "Hash verification failed for operation "
1555 << next_operation_num_ << ". Expected hash = ";
1556 utils::HexDumpVector(expected_op_hash);
1557 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1558 << " bytes at offset: " << operation.data_offset() << " = ";
1559 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001560 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001561 }
1562
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001563 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001564}
1565
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001566#define TEST_AND_RETURN_VAL(_retval, _condition) \
1567 do { \
1568 if (!(_condition)) { \
1569 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1570 return _retval; \
1571 } \
1572 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001573
David Zeuthena99981f2013-04-29 13:42:47 -07001574ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001575 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001576 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001577
1578 // See if we should use the public RSA key in the Omaha response.
1579 base::FilePath path_to_public_key(public_key_path_);
1580 base::FilePath tmp_key;
1581 if (GetPublicKeyFromResponse(&tmp_key))
1582 path_to_public_key = tmp_key;
1583 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1584 if (tmp_key.empty())
1585 tmp_key_remover.set_should_remove(false);
1586
1587 LOG(INFO) << "Verifying payload using public key: "
1588 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001589
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001590 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001591 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001592 update_check_response_size ==
Sen Jiang76bfa742015-10-12 17:13:26 -07001593 metadata_size_ + metadata_signature_size_ +
1594 buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001595
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001596 // Verifies the payload hash.
Sen Jiangf6813802015-11-03 21:27:29 -08001597 const string& payload_hash_data = payload_hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001598 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001599 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001600 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001601 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001602
Darin Petkov437adc42010-10-07 13:12:24 -07001603 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001604 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001605 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001606 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001607 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001608 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001609 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001610 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001611 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1612 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001613 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001614 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001615
1616 if (!PayloadVerifier::VerifySignature(
1617 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001618 // The autoupdate_CatchBadSignatures test checks for this string
1619 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001620 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001621 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001622 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001623
David Zeuthene7f89172013-10-31 10:21:04 -07001624 LOG(INFO) << "Payload hash matches value in payload.";
1625
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001626 // At this point, we are guaranteed to have downloaded a full payload, i.e
1627 // the one whose size matches the size mentioned in Omaha response. If any
1628 // errors happen after this, it's likely a problem with the payload itself or
1629 // the state of the system and not a problem with the URL or network. So,
Alex Deymo542c19b2015-12-03 07:43:31 -03001630 // indicate that to the download delegate so that AU can backoff
1631 // appropriately.
1632 if (download_delegate_)
1633 download_delegate_->DownloadComplete();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001634
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001635 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001636}
1637
Sen Jiangf6813802015-11-03 21:27:29 -08001638void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1639 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001640 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001641 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001642 buffer_offset_ += buffer_.size();
1643
1644 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001645 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1646 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001647
1648 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001649 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001650}
1651
Darin Petkov0406e402010-10-06 21:33:11 -07001652bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001653 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001654 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001655 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1656 next_operation != kUpdateStateOperationInvalid &&
1657 next_operation > 0))
1658 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001659
1660 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001661 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1662 !interrupted_hash.empty() &&
1663 interrupted_hash == update_check_response_hash))
1664 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001665
Darin Petkov61426142010-10-08 11:04:55 -07001666 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001667 // Note that storing this value is optional, but if it is there it should not
1668 // be more than the limit.
1669 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1670 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001671 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001672
Darin Petkov0406e402010-10-06 21:33:11 -07001673 // Sanity check the rest.
1674 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001675 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1676 next_data_offset >= 0))
1677 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001678
Darin Petkov437adc42010-10-07 13:12:24 -07001679 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001680 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1681 !sha256_context.empty()))
1682 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001683
1684 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001685 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1686 manifest_metadata_size > 0))
1687 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001688
Alex Deymof25eb492016-02-26 00:20:08 -08001689 int64_t manifest_signature_size = 0;
1690 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1691 &manifest_signature_size) &&
1692 manifest_signature_size >= 0))
1693 return false;
1694
Darin Petkov0406e402010-10-06 21:33:11 -07001695 return true;
1696}
1697
Darin Petkov9b230572010-10-08 10:20:09 -07001698bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001699 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1700 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001701 if (!quick) {
1702 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1703 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001704 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001705 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1706 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001707 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001708 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001709 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001710 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001711 }
Darin Petkov73058b42010-10-06 16:32:19 -07001712 return true;
1713}
1714
1715bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001716 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001717 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001718 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001719 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001720 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001721 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Sen Jiangf6813802015-11-03 21:27:29 -08001722 payload_hash_calculator_.GetContext()));
1723 TEST_AND_RETURN_FALSE(
1724 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1725 signed_hash_calculator_.GetContext()));
Darin Petkov0406e402010-10-06 21:33:11 -07001726 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1727 buffer_offset_));
1728 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001729
1730 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001731 size_t partition_index = current_partition_;
1732 while (next_operation_num_ >= acc_num_operations_[partition_index])
1733 partition_index++;
1734 const size_t partition_operation_num = next_operation_num_ - (
1735 partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001736 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001737 partitions_[partition_index].operations(partition_operation_num);
David Zeuthen41996ad2013-09-24 15:43:24 -07001738 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1739 op.data_length()));
1740 } else {
1741 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1742 0));
1743 }
Darin Petkov0406e402010-10-06 21:33:11 -07001744 }
Darin Petkov73058b42010-10-06 16:32:19 -07001745 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1746 next_operation_num_));
1747 return true;
1748}
1749
Darin Petkov9b230572010-10-08 10:20:09 -07001750bool DeltaPerformer::PrimeUpdateState() {
1751 CHECK(manifest_valid_);
1752 block_size_ = manifest_.block_size();
1753
1754 int64_t next_operation = kUpdateStateOperationInvalid;
1755 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1756 next_operation == kUpdateStateOperationInvalid ||
1757 next_operation <= 0) {
1758 // Initiating a new update, no more state needs to be initialized.
1759 return true;
1760 }
1761 next_operation_num_ = next_operation;
1762
1763 // Resuming an update -- load the rest of the update state.
1764 int64_t next_data_offset = -1;
1765 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1766 &next_data_offset) &&
1767 next_data_offset >= 0);
1768 buffer_offset_ = next_data_offset;
1769
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001770 // The signed hash context and the signature blob may be empty if the
1771 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001772 string signed_hash_context;
1773 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1774 &signed_hash_context)) {
1775 TEST_AND_RETURN_FALSE(
1776 signed_hash_calculator_.SetContext(signed_hash_context));
1777 }
1778
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001779 string signature_blob;
1780 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1781 signatures_message_data_.assign(signature_blob.begin(),
1782 signature_blob.end());
1783 }
Darin Petkov9b230572010-10-08 10:20:09 -07001784
1785 string hash_context;
1786 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1787 &hash_context) &&
Sen Jiangf6813802015-11-03 21:27:29 -08001788 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001789
1790 int64_t manifest_metadata_size = 0;
1791 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1792 &manifest_metadata_size) &&
1793 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001794 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001795
Alex Deymof25eb492016-02-26 00:20:08 -08001796 int64_t manifest_signature_size = 0;
1797 TEST_AND_RETURN_FALSE(
1798 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1799 manifest_signature_size >= 0);
1800 metadata_signature_size_ = manifest_signature_size;
1801
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001802 // Advance the download progress to reflect what doesn't need to be
1803 // re-downloaded.
1804 total_bytes_received_ += buffer_offset_;
1805
Darin Petkov61426142010-10-08 11:04:55 -07001806 // Speculatively count the resume as a failure.
1807 int64_t resumed_update_failures;
1808 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1809 resumed_update_failures++;
1810 } else {
1811 resumed_update_failures = 1;
1812 }
1813 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001814 return true;
1815}
1816
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001817} // namespace chromeos_update_engine