blob: 50b95a0e5ebd9f7b31682e28266ec165c6bcdea3 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/payload_consumer/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070020#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include <algorithm>
23#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070024#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025#include <string>
Amin Hassanid87304c2017-08-29 11:40:03 -070026#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027#include <vector>
28
Ben Chan06c76a42014-09-05 08:21:06 -070029#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070030#include <base/format_macros.h>
Lann Martin39f57142017-07-14 09:18:42 -060031#include <base/metrics/histogram_macros.h>
Alex Deymo67140842016-06-15 13:28:59 -070032#include <base/strings/string_number_conversions.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
Lann Martin39f57142017-07-14 09:18:42 -060035#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070036#include <brillo/data_encoding.h>
Alex Deymo6765a682017-05-19 13:13:54 -070037#include <bsdiff/bspatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038#include <google/protobuf/repeated_field.h>
Amin Hassani02855c22017-09-06 22:34:50 -070039#include <puffin/puffpatch.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/constants.h"
42#include "update_engine/common/hardware_interface.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030043#include "update_engine/common/prefs_interface.h"
44#include "update_engine/common/subprocess.h"
45#include "update_engine/common/terminator.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080046#include "update_engine/payload_consumer/bzip_extent_writer.h"
Amin Hassania3fc20a2017-09-19 17:19:34 -070047#include "update_engine/payload_consumer/cached_file_descriptor.h"
Alex Deymo542c19b2015-12-03 07:43:31 -030048#include "update_engine/payload_consumer/download_action.h"
Amin Hassanidb56be92017-09-06 12:41:23 -070049#include "update_engine/payload_consumer/extent_reader.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080050#include "update_engine/payload_consumer/extent_writer.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070051#if USE_FEC
52#include "update_engine/payload_consumer/fec_file_descriptor.h"
53#endif // USE_FEC
Alex Deymoa48f6302016-11-04 15:49:53 -070054#include "update_engine/payload_consumer/file_descriptor_utils.h"
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +010055#include "update_engine/payload_consumer/mount_history.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080056#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Alex Deymo51c264e2016-11-04 15:49:53 -070058#endif // USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/payload_consumer/payload_constants.h"
60#include "update_engine/payload_consumer/payload_verifier.h"
61#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070062
Alex Deymo161c4a12014-05-16 15:56:21 -070063using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070064using std::min;
65using std::string;
66using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070067
68namespace chromeos_update_engine {
Gilad Arnold8a86fa52013-01-15 12:35:05 -080069const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
70const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
71const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
72const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Colin Howes0e452c92018-11-02 13:18:44 -070073const uint64_t DeltaPerformer::kCheckpointFrequencySeconds = 1;
Darin Petkovabc7bc02011-02-23 14:39:43 -080074
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070075namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070076const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070077const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080078#if USE_MTD
79const int kUbiVolumeAttachTimeout = 5 * 60;
80#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080081
Amin Hassania3fc20a2017-09-19 17:19:34 -070082const uint64_t kCacheSize = 1024 * 1024; // 1MB
83
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080084FileDescriptorPtr CreateFileDescriptor(const char* path) {
85 FileDescriptorPtr ret;
86#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080087 if (strstr(path, "/dev/ubi") == path) {
88 if (!UbiFileDescriptor::IsUbi(path)) {
89 // The volume might not have been attached at boot time.
90 int volume_no;
91 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
92 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
93 }
94 }
95 if (UbiFileDescriptor::IsUbi(path)) {
96 LOG(INFO) << path << " is a UBI device.";
97 ret.reset(new UbiFileDescriptor);
98 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080099 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800100 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800101 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800102 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800103 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800104#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800105 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800106#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700107 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800108#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800109 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700110}
111
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800112// Opens path for read/write. On success returns an open FileDescriptor
113// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
Amin Hassania3fc20a2017-09-19 17:19:34 -0700114FileDescriptorPtr OpenFile(const char* path,
115 int mode,
116 bool cache_writes,
117 int* err) {
Alex Deymo5fb356c2016-03-25 18:48:22 -0700118 // Try to mark the block device read-only based on the mode. Ignore any
119 // failure since this won't work when passing regular files.
Amin Hassania3fc20a2017-09-19 17:19:34 -0700120 bool read_only = (mode & O_ACCMODE) == O_RDONLY;
121 utils::SetBlockDeviceReadOnly(path, read_only);
Alex Deymo5fb356c2016-03-25 18:48:22 -0700122
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800123 FileDescriptorPtr fd = CreateFileDescriptor(path);
Amin Hassania3fc20a2017-09-19 17:19:34 -0700124 if (cache_writes && !read_only) {
125 fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
126 LOG(INFO) << "Caching writes.";
127 }
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800128#if USE_MTD
129 // On NAND devices, we can either read, or write, but not both. So here we
130 // use O_WRONLY.
131 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
132 mode = O_WRONLY;
133 }
134#endif
135 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800136 *err = errno;
137 PLOG(ERROR) << "Unable to open file " << path;
138 return nullptr;
139 }
140 *err = 0;
141 return fd;
142}
Alex Deymob86787c2016-05-12 18:46:25 -0700143
144// Discard the tail of the block device referenced by |fd|, from the offset
145// |data_size| until the end of the block device. Returns whether the data was
146// discarded.
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700147bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
Alex Deymob86787c2016-05-12 18:46:25 -0700148 uint64_t part_size = fd->BlockDevSize();
149 if (!part_size || part_size <= data_size)
150 return false;
151
Alex Deymo72a68d82016-06-15 16:31:04 -0700152 struct blkioctl_request {
153 int number;
154 const char* name;
155 };
156 const vector<blkioctl_request> blkioctl_requests = {
Alex Deymo72a68d82016-06-15 16:31:04 -0700157 {BLKDISCARD, "BLKDISCARD"},
Amin Hassani41555202017-06-23 12:42:00 -0700158 {BLKSECDISCARD, "BLKSECDISCARD"},
Alex Deymob86787c2016-05-12 18:46:25 -0700159#ifdef BLKZEROOUT
Alex Deymo72a68d82016-06-15 16:31:04 -0700160 {BLKZEROOUT, "BLKZEROOUT"},
Alex Deymob86787c2016-05-12 18:46:25 -0700161#endif
162 };
Alex Deymo72a68d82016-06-15 16:31:04 -0700163 for (const auto& req : blkioctl_requests) {
Alex Deymob86787c2016-05-12 18:46:25 -0700164 int error = 0;
Alex Deymo72a68d82016-06-15 16:31:04 -0700165 if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
Alex Deymob86787c2016-05-12 18:46:25 -0700166 error == 0) {
167 return true;
168 }
169 LOG(WARNING) << "Error discarding the last "
170 << (part_size - data_size) / 1024 << " KiB using ioctl("
Alex Deymo72a68d82016-06-15 16:31:04 -0700171 << req.name << ")";
Alex Deymob86787c2016-05-12 18:46:25 -0700172 }
173 return false;
174}
175
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700176} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700177
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800178
179// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
180// arithmetic.
181static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
182 return part * norm / total;
183}
184
185void DeltaPerformer::LogProgress(const char* message_prefix) {
186 // Format operations total count and percentage.
187 string total_operations_str("?");
188 string completed_percentage_str("");
189 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700190 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800191 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
192 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700193 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700194 IntRatio(next_operation_num_, num_total_operations_,
195 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800196 }
197
198 // Format download total count and percentage.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800199 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800200 string payload_size_str("?");
201 string downloaded_percentage_str("");
202 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700203 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800204 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
205 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700206 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700207 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800208 }
209
210 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
211 << "/" << total_operations_str << " operations"
212 << completed_percentage_str << ", " << total_bytes_received_
213 << "/" << payload_size_str << " bytes downloaded"
214 << downloaded_percentage_str << ", overall progress "
215 << overall_progress_ << "%";
216}
217
218void DeltaPerformer::UpdateOverallProgress(bool force_log,
219 const char* message_prefix) {
220 // Compute our download and overall progress.
221 unsigned new_overall_progress = 0;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800222 static_assert(kProgressDownloadWeight + kProgressOperationsWeight == 100,
223 "Progress weights don't add up");
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800224 // Only consider download progress if its total size is known; otherwise
225 // adjust the operations weight to compensate for the absence of download
226 // progress. Also, make sure to cap the download portion at
227 // kProgressDownloadWeight, in case we end up downloading more than we
228 // initially expected (this indicates a problem, but could generally happen).
229 // TODO(garnold) the correction of operations weight when we do not have the
230 // total payload size, as well as the conditional guard below, should both be
231 // eliminated once we ensure that the payload_size in the install plan is
232 // always given and is non-zero. This currently isn't the case during unit
233 // tests (see chromium-os:37969).
Sen Jiang0affc2c2017-02-10 15:55:05 -0800234 size_t payload_size = payload_->size;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800235 unsigned actual_operations_weight = kProgressOperationsWeight;
236 if (payload_size)
237 new_overall_progress += min(
238 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
239 kProgressDownloadWeight)),
240 kProgressDownloadWeight);
241 else
242 actual_operations_weight += kProgressDownloadWeight;
243
244 // Only add completed operations if their total number is known; we definitely
245 // expect an update to have at least one operation, so the expectation is that
246 // this will eventually reach |actual_operations_weight|.
247 if (num_total_operations_)
248 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
249 actual_operations_weight);
250
251 // Progress ratio cannot recede, unless our assumptions about the total
252 // payload size, total number of operations, or the monotonicity of progress
253 // is breached.
254 if (new_overall_progress < overall_progress_) {
255 LOG(WARNING) << "progress counter receded from " << overall_progress_
256 << "% down to " << new_overall_progress << "%; this is a bug";
257 force_log = true;
258 }
259 overall_progress_ = new_overall_progress;
260
261 // Update chunk index, log as needed: if forced by called, or we completed a
262 // progress chunk, or a timeout has expired.
263 base::Time curr_time = base::Time::Now();
264 unsigned curr_progress_chunk =
265 overall_progress_ * kProgressLogMaxChunks / 100;
266 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
267 curr_time > forced_progress_log_time_) {
268 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
269 LogProgress(message_prefix);
270 }
271 last_progress_chunk_ = curr_progress_chunk;
272}
273
274
Gilad Arnoldfe133932014-01-14 12:25:50 -0800275size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
276 size_t max) {
277 const size_t count = *count_p;
278 if (!count)
279 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700280 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800281 const char* bytes_start = *bytes_p;
282 const char* bytes_end = bytes_start + read_len;
Sen Jiangbe19a242017-11-17 11:48:17 -0800283 buffer_.reserve(max);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800284 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
285 *bytes_p = bytes_end;
286 *count_p = count - read_len;
287 return read_len;
288}
289
290
291bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
292 ErrorCode* error) {
293 if (op_result)
294 return true;
295
Alex Deymo3d009062016-05-13 15:51:25 -0700296 size_t partition_first_op_num =
297 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800298 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
Alex Deymo3d009062016-05-13 15:51:25 -0700299 << next_operation_num_ << ", which is the operation "
300 << next_operation_num_ - partition_first_op_num
301 << " in partition \""
302 << partitions_[current_partition_].partition_name() << "\"";
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700303 if (*error == ErrorCode::kSuccess)
304 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800305 return false;
306}
307
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700308int DeltaPerformer::Close() {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700309 int err = -CloseCurrentPartition();
Sen Jiangf6813802015-11-03 21:27:29 -0800310 LOG_IF(ERROR, !payload_hash_calculator_.Finalize() ||
311 !signed_hash_calculator_.Finalize())
312 << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800313 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700314 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
315 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800316 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800317 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700318 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700319}
320
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700321int DeltaPerformer::CloseCurrentPartition() {
322 int err = 0;
323 if (source_fd_ && !source_fd_->Close()) {
324 err = errno;
325 PLOG(ERROR) << "Error closing source partition";
326 if (!err)
327 err = 1;
328 }
329 source_fd_.reset();
Alex Deymo51c264e2016-11-04 15:49:53 -0700330 if (source_ecc_fd_ && !source_ecc_fd_->Close()) {
331 err = errno;
332 PLOG(ERROR) << "Error closing ECC source partition";
333 if (!err)
334 err = 1;
335 }
336 source_ecc_fd_.reset();
337 source_ecc_open_failure_ = false;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700338 source_path_.clear();
339
340 if (target_fd_ && !target_fd_->Close()) {
341 err = errno;
342 PLOG(ERROR) << "Error closing target partition";
343 if (!err)
344 err = 1;
345 }
346 target_fd_.reset();
347 target_path_.clear();
348 return -err;
349}
350
351bool DeltaPerformer::OpenCurrentPartition() {
352 if (current_partition_ >= partitions_.size())
353 return false;
354
355 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700356 size_t num_previous_partitions =
357 install_plan_->partitions.size() - partitions_.size();
358 const InstallPlan::Partition& install_part =
359 install_plan_->partitions[num_previous_partitions + current_partition_];
Sen Jiang889c65d2015-11-17 15:04:02 -0800360 // Open source fds if we have a delta payload with minor version >= 2.
Sen Jiangcdd52062017-05-18 15:33:10 -0700361 if (payload_->type == InstallPayloadType::kDelta &&
Sen Jiang889c65d2015-11-17 15:04:02 -0800362 GetMinorVersion() != kInPlaceMinorPayloadVersion) {
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700363 source_path_ = install_part.source_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700364 int err;
Amin Hassania3fc20a2017-09-19 17:19:34 -0700365 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, false, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700366 if (!source_fd_) {
367 LOG(ERROR) << "Unable to open source partition "
368 << partition.partition_name() << " on slot "
369 << BootControlInterface::SlotName(install_plan_->source_slot)
370 << ", file " << source_path_;
371 return false;
372 }
373 }
374
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700375 target_path_ = install_part.target_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700376 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700377
Amin Hassani7ecda262017-07-11 17:10:50 -0700378 int flags = O_RDWR;
Amin Hassanied37d682018-04-06 13:22:00 -0700379 if (!interactive_)
Amin Hassani7ecda262017-07-11 17:10:50 -0700380 flags |= O_DSYNC;
381
382 LOG(INFO) << "Opening " << target_path_ << " partition with"
Amin Hassanied37d682018-04-06 13:22:00 -0700383 << (interactive_ ? "out" : "") << " O_DSYNC";
Amin Hassani7ecda262017-07-11 17:10:50 -0700384
Amin Hassania3fc20a2017-09-19 17:19:34 -0700385 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700386 if (!target_fd_) {
387 LOG(ERROR) << "Unable to open target partition "
388 << partition.partition_name() << " on slot "
389 << BootControlInterface::SlotName(install_plan_->target_slot)
390 << ", file " << target_path_;
391 return false;
392 }
Alex Deymob86787c2016-05-12 18:46:25 -0700393
394 LOG(INFO) << "Applying " << partition.operations().size()
395 << " operations to partition \"" << partition.partition_name()
396 << "\"";
397
398 // Discard the end of the partition, but ignore failures.
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700399 DiscardPartitionTail(target_fd_, install_part.target_size);
Alex Deymob86787c2016-05-12 18:46:25 -0700400
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700401 return true;
402}
403
Alex Deymo51c264e2016-11-04 15:49:53 -0700404bool DeltaPerformer::OpenCurrentECCPartition() {
405 if (source_ecc_fd_)
406 return true;
407
408 if (source_ecc_open_failure_)
409 return false;
410
411 if (current_partition_ >= partitions_.size())
412 return false;
413
414 // No support for ECC in minor version 1 or full payloads.
415 if (payload_->type == InstallPayloadType::kFull ||
416 GetMinorVersion() == kInPlaceMinorPayloadVersion)
417 return false;
418
419#if USE_FEC
420 const PartitionUpdate& partition = partitions_[current_partition_];
421 size_t num_previous_partitions =
422 install_plan_->partitions.size() - partitions_.size();
423 const InstallPlan::Partition& install_part =
424 install_plan_->partitions[num_previous_partitions + current_partition_];
425 string path = install_part.source_path;
426 FileDescriptorPtr fd(new FecFileDescriptor());
427 if (!fd->Open(path.c_str(), O_RDONLY, 0)) {
428 PLOG(ERROR) << "Unable to open ECC source partition "
429 << partition.partition_name() << " on slot "
430 << BootControlInterface::SlotName(install_plan_->source_slot)
431 << ", file " << path;
432 source_ecc_open_failure_ = true;
433 return false;
434 }
435 source_ecc_fd_ = fd;
436#else
437 // No support for ECC compiled.
438 source_ecc_open_failure_ = true;
439#endif // USE_FEC
440
441 return !source_ecc_open_failure_;
442}
443
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700444namespace {
445
446void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700447 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800448 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
449 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700450}
451
Alex Deymo39910dc2015-11-09 17:04:30 -0800452void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700453 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800454 if (partition.has_old_partition_info()) {
455 LogPartitionInfoHash(partition.old_partition_info(),
456 "old " + partition.partition_name());
457 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700458 LogPartitionInfoHash(partition.new_partition_info(),
459 "new " + partition.partition_name());
460 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700461}
462
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700463} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700464
Allie Woodfdf00512015-03-02 13:34:55 -0800465uint32_t DeltaPerformer::GetMinorVersion() const {
466 if (manifest_.has_minor_version()) {
467 return manifest_.minor_version();
Allie Woodfdf00512015-03-02 13:34:55 -0800468 }
Sen Jiangdcaf7972018-05-11 16:03:23 -0700469 return payload_->type == InstallPayloadType::kDelta
470 ? kMaxSupportedMinorPayloadVersion
471 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800472}
473
Sen Jiangb8060e42015-09-24 17:30:50 -0700474bool DeltaPerformer::IsHeaderParsed() const {
475 return metadata_size_ != 0;
476}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700477
Sen Jiangb5f601d2018-02-02 13:51:21 -0800478MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700479 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700480 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700481
Sen Jiangb8060e42015-09-24 17:30:50 -0700482 if (!IsHeaderParsed()) {
Sen Jiangdcaf7972018-05-11 16:03:23 -0700483 MetadataParseResult result =
484 payload_metadata_.ParsePayloadHeader(payload, error);
Sen Jiangb5f601d2018-02-02 13:51:21 -0800485 if (result != MetadataParseResult::kSuccess)
486 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700487
Sen Jiangb5f601d2018-02-02 13:51:21 -0800488 metadata_size_ = payload_metadata_.GetMetadataSize();
489 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
490 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800491
492 // If the metadata size is present in install plan, check for it immediately
493 // even before waiting for that many number of bytes to be downloaded in the
494 // payload. This will prevent any attack which relies on us downloading data
495 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800496 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800497 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800498 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800499 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800500 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700501 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiangb5f601d2018-02-02 13:51:21 -0800502 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800503 }
504 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700505 }
506
507 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700508 // metadata and its signature (if exist) to be read in before we can parse it.
509 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiangb5f601d2018-02-02 13:51:21 -0800510 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700511
512 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700513 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700514 // that we just log once (instead of logging n times) if it takes n
515 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800516 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700517 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800518 } else {
519 // For mandatory-cases, we'd have already returned a kMetadataParseError
520 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
521 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800522 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800523 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800524 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800525 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700526
Sen Jiangb5f601d2018-02-02 13:51:21 -0800527 // See if we should use the public RSA key in the Omaha response.
528 base::FilePath path_to_public_key(public_key_path_);
529 base::FilePath tmp_key;
530 if (GetPublicKeyFromResponse(&tmp_key))
531 path_to_public_key = tmp_key;
532 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
533 if (tmp_key.empty())
534 tmp_key_remover.set_should_remove(false);
535
Jay Srinivasanf4318702012-09-24 11:56:24 -0700536 // We have the full metadata in |payload|. Verify its integrity
537 // and authenticity based on the information we have in Omaha response.
Sen Jiangb5f601d2018-02-02 13:51:21 -0800538 *error = payload_metadata_.ValidateMetadataSignature(
539 payload, payload_->metadata_signature, path_to_public_key);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700540 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800541 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800542 // The autoupdate_CatchBadSignatures test checks for this string
543 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800544 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiangb5f601d2018-02-02 13:51:21 -0800545 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800546 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700547
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800548 // For non-mandatory cases, just send a UMA stat.
549 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700550 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700551 }
552
Gilad Arnolddaa27402014-01-23 11:56:17 -0800553 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb5f601d2018-02-02 13:51:21 -0800554 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800555 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700556 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiangb5f601d2018-02-02 13:51:21 -0800557 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800558 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800559
560 manifest_parsed_ = true;
Sen Jiangb5f601d2018-02-02 13:51:21 -0800561 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800562}
563
Lann Martin39f57142017-07-14 09:18:42 -0600564#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
565 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
566 "UpdateEngine.DownloadAction.InstallOperation::" \
567 _op_name ".Duration", \
568 base::TimeTicks::Now() - _start_time, \
569 base::TimeDelta::FromMilliseconds(10), \
570 base::TimeDelta::FromMinutes(5), \
571 20);
572
Don Garrette410e0f2011-11-10 15:39:01 -0800573// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800574// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700575// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800576bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700577 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700578 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800579
580 // Update the total byte downloaded count and the progress logs.
581 total_bytes_received_ += count;
582 UpdateOverallProgress(false, "Completed ");
583
Gilad Arnoldfe133932014-01-14 12:25:50 -0800584 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700585 // Read data up to the needed limit; this is either maximium payload header
586 // size, or the full metadata size (once it becomes known).
587 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800588 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700589 (do_read_header ? kMaxPayloadHeaderSize :
Sen Jiang76bfa742015-10-12 17:13:26 -0700590 metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800591
Gilad Arnolddaa27402014-01-23 11:56:17 -0800592 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiangb5f601d2018-02-02 13:51:21 -0800593 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800594 return false;
Sen Jiangb5f601d2018-02-02 13:51:21 -0800595 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800596 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700597 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800598 continue;
599
Don Garrette410e0f2011-11-10 15:39:01 -0800600 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800601 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700602
603 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700604 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700605 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800606 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700607
Gilad Arnoldfe133932014-01-14 12:25:50 -0800608 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800609 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700610
611 // This populates |partitions_| and the |install_plan.partitions| with the
612 // list of partitions from the manifest.
613 if (!ParseManifestPartitions(error))
614 return false;
615
Sen Jiang5ae865b2017-04-18 14:24:40 -0700616 // |install_plan.partitions| was filled in, nothing need to be done here if
617 // the payload was already applied, returns false to terminate http fetcher,
618 // but keep |error| as ErrorCode::kSuccess.
619 if (payload_->already_applied)
620 return false;
621
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700622 num_total_operations_ = 0;
623 for (const auto& partition : partitions_) {
624 num_total_operations_ += partition.operations_size();
625 acc_num_operations_.push_back(num_total_operations_);
626 }
627
Darin Petkov73058b42010-10-06 16:32:19 -0700628 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800629 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700630 << "Unable to save the manifest metadata size.";
Alex Deymof25eb492016-02-26 00:20:08 -0800631 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestSignatureSize,
632 metadata_signature_size_))
633 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700634
Darin Petkov9b230572010-10-08 10:20:09 -0700635 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700636 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700637 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800638 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700639 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800640
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700641 if (!OpenCurrentPartition()) {
642 *error = ErrorCode::kInstallDeviceOpenError;
643 return false;
Allie Woodfdf00512015-03-02 13:34:55 -0800644 }
645
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800646 if (next_operation_num_ > 0)
647 UpdateOverallProgress(true, "Resuming after ");
648 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800650
651 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700652 // Check if we should cancel the current attempt for any reason.
653 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700654 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300655 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700656 return false;
657
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700658 // We know there are more operations to perform because we didn't reach the
659 // |num_total_operations_| limit yet.
660 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
661 CloseCurrentPartition();
662 current_partition_++;
663 if (!OpenCurrentPartition()) {
664 *error = ErrorCode::kInstallDeviceOpenError;
665 return false;
666 }
667 }
668 const size_t partition_operation_num = next_operation_num_ - (
669 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
670
Alex Deymoa12ee112015-08-12 22:19:32 -0700671 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700672 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800673
674 CopyDataToBuffer(&c_bytes, &count, op.data_length());
675
676 // Check whether we received all of the next operation's data payload.
677 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700678 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700679
Jay Srinivasanf4318702012-09-24 11:56:24 -0700680 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700681 // Otherwise, keep the old behavior. This serves as a knob to disable
682 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800683 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
684 // we would have already failed in ParsePayloadMetadata method and thus not
685 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800686 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700687 // Note: Validate must be called only if CanPerformInstallOperation is
688 // called. Otherwise, we might be failing operations before even if there
689 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800690 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700691 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800692 if (install_plan_->hash_checks_mandatory) {
693 LOG(ERROR) << "Mandatory operation hash check failed";
694 return false;
695 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700696
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800697 // For non-mandatory cases, just send a UMA stat.
698 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700699 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700700 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700701 }
702
Darin Petkov45580e42010-10-08 14:02:40 -0700703 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700704 ScopedTerminatorExitUnblocker exit_unblocker =
705 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800706
Lann Martin39f57142017-07-14 09:18:42 -0600707 base::TimeTicks op_start_time = base::TimeTicks::Now();
708
Gilad Arnoldfe133932014-01-14 12:25:50 -0800709 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700710 switch (op.type()) {
711 case InstallOperation::REPLACE:
712 case InstallOperation::REPLACE_BZ:
713 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700714 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600715 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700716 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700717 case InstallOperation::ZERO:
718 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700719 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600720 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700721 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700722 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700723 op_result = PerformMoveOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600724 OP_DURATION_HISTOGRAM("MOVE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700725 break;
726 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700727 op_result = PerformBsdiffOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600728 OP_DURATION_HISTOGRAM("BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700729 break;
730 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700731 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600732 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700733 break;
734 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800735 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700736 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600737 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700738 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700739 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700740 op_result = PerformPuffDiffOperation(op, error);
741 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800742 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700743 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700744 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700745 }
746 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800747 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800748
Amin Hassani5192fe52017-08-28 10:28:46 -0700749 if (!target_fd_->Flush()) {
750 return false;
751 }
752
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700753 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800754 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700755 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700756 }
Sen Jiangf6813802015-11-03 21:27:29 -0800757
758 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800759 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800760 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800761 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
762 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800763 if (manifest_.signatures_offset() != buffer_offset_) {
764 LOG(ERROR) << "Payload signatures offset points to blob offset "
765 << manifest_.signatures_offset()
766 << " but signatures are expected at offset "
767 << buffer_offset_;
768 *error = ErrorCode::kDownloadPayloadVerificationError;
769 return false;
770 }
771 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
772 // Needs more data to cover entire signature.
773 if (buffer_.size() < manifest_.signatures_size())
774 return true;
775 if (!ExtractSignatureMessage()) {
776 LOG(ERROR) << "Extract payload signature failed.";
777 *error = ErrorCode::kDownloadPayloadVerificationError;
778 return false;
779 }
780 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800781 // Since we extracted the SignatureMessage we need to advance the
782 // checkpoint, otherwise we would reload the signature and try to extract
783 // it again.
784 CheckpointUpdateProgress();
Sen Jiangf6813802015-11-03 21:27:29 -0800785 }
786
Don Garrette410e0f2011-11-10 15:39:01 -0800787 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700788}
789
David Zeuthen8f191b22013-08-06 12:27:50 -0700790bool DeltaPerformer::IsManifestValid() {
791 return manifest_valid_;
792}
793
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700794bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
795 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
796 partitions_.clear();
797 for (const PartitionUpdate& partition : manifest_.partitions()) {
798 partitions_.push_back(partition);
799 }
800 manifest_.clear_partitions();
801 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
802 LOG(INFO) << "Converting update information from old format.";
803 PartitionUpdate root_part;
Tudor Brindusdda79e22018-06-28 18:03:21 -0700804 root_part.set_partition_name(kPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700805#ifdef __ANDROID__
806 LOG(WARNING) << "Legacy payload major version provided to an Android "
807 "build. Assuming no post-install. Please use major version "
808 "2 or newer.";
809 root_part.set_run_postinstall(false);
810#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700811 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700812#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700813 if (manifest_.has_old_rootfs_info()) {
814 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
815 manifest_.clear_old_rootfs_info();
816 }
817 if (manifest_.has_new_rootfs_info()) {
818 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
819 manifest_.clear_new_rootfs_info();
820 }
821 *root_part.mutable_operations() = manifest_.install_operations();
822 manifest_.clear_install_operations();
823 partitions_.push_back(std::move(root_part));
824
825 PartitionUpdate kern_part;
Tudor Brindusdda79e22018-06-28 18:03:21 -0700826 kern_part.set_partition_name(kPartitionNameKernel);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700827 kern_part.set_run_postinstall(false);
828 if (manifest_.has_old_kernel_info()) {
829 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
830 manifest_.clear_old_kernel_info();
831 }
832 if (manifest_.has_new_kernel_info()) {
833 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
834 manifest_.clear_new_kernel_info();
835 }
836 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
837 manifest_.clear_kernel_install_operations();
838 partitions_.push_back(std::move(kern_part));
839 }
840
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700841 // Fill in the InstallPlan::partitions based on the partitions from the
842 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700843 for (const auto& partition : partitions_) {
844 InstallPlan::Partition install_part;
845 install_part.name = partition.partition_name();
846 install_part.run_postinstall =
847 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800848 if (install_part.run_postinstall) {
849 install_part.postinstall_path =
850 (partition.has_postinstall_path() ? partition.postinstall_path()
851 : kPostinstallDefaultScript);
852 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700853 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800854 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700855
856 if (partition.has_old_partition_info()) {
857 const PartitionInfo& info = partition.old_partition_info();
858 install_part.source_size = info.size();
859 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
860 }
861
862 if (!partition.has_new_partition_info()) {
863 LOG(ERROR) << "Unable to get new partition hash info on partition "
864 << install_part.name << ".";
865 *error = ErrorCode::kDownloadNewPartitionInfoError;
866 return false;
867 }
868 const PartitionInfo& info = partition.new_partition_info();
869 install_part.target_size = info.size();
870 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
871
872 install_plan_->partitions.push_back(install_part);
873 }
874
Alex Deymo542c19b2015-12-03 07:43:31 -0300875 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700876 LOG(ERROR) << "Unable to determine all the partition devices.";
877 *error = ErrorCode::kInstallDeviceOpenError;
878 return false;
879 }
880 LogPartitionInfo(partitions_);
881 return true;
882}
883
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700884bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700885 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700886 // If we don't have a data blob we can apply it right away.
887 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700888 return true;
889
890 // See if we have the entire data blob in the buffer
891 if (operation.data_offset() < buffer_offset_) {
892 LOG(ERROR) << "we threw away data it seems?";
893 return false;
894 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700895
Gilad Arnoldfe133932014-01-14 12:25:50 -0800896 return (operation.data_offset() + operation.data_length() <=
897 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700898}
899
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700900bool DeltaPerformer::PerformReplaceOperation(
901 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700902 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700903 operation.type() == InstallOperation::REPLACE_BZ ||
904 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700905
906 // Since we delete data off the beginning of the buffer as we use it,
907 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700908 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
909 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700910
Darin Petkov437adc42010-10-07 13:12:24 -0700911 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -0800912 if (ExtractSignatureMessageFromOperation(operation)) {
913 // If this is dummy replace operation, we ignore it after extracting the
914 // signature.
915 DiscardBuffer(true, 0);
916 return true;
917 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700918
Alex Deymo05322872015-09-30 09:50:24 -0700919 // Setup the ExtentWriter stack based on the operation type.
Ben Chanab5a0af2017-10-12 14:57:50 -0700920 std::unique_ptr<ExtentWriter> writer = std::make_unique<ZeroPadExtentWriter>(
921 std::make_unique<DirectExtentWriter>());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700922
Alex Deymo2d621a32015-10-01 11:09:01 -0700923 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700924 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700925 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
926 writer.reset(new XzExtentWriter(std::move(writer)));
927 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700928
Amin Hassanicd7edbe2017-09-18 17:05:02 -0700929 TEST_AND_RETURN_FALSE(
930 writer->Init(target_fd_, operation.dst_extents(), block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800931 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700932 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700933
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700934 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -0800935 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700936 return true;
937}
938
Alex Deymo79715ad2015-10-02 14:27:53 -0700939bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700940 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700941 CHECK(operation.type() == InstallOperation::DISCARD ||
942 operation.type() == InstallOperation::ZERO);
943
944 // These operations have no blob.
945 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
946 TEST_AND_RETURN_FALSE(!operation.has_data_length());
947
Alex Deymo05e0e382015-12-07 20:18:16 -0800948#ifdef BLKZEROOUT
949 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -0700950 int request =
951 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Alex Deymo05e0e382015-12-07 20:18:16 -0800952#else // !defined(BLKZEROOUT)
953 bool attempt_ioctl = false;
954 int request = 0;
955#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -0700956
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700957 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700958 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700959 const uint64_t start = extent.start_block() * block_size_;
960 const uint64_t length = extent.num_blocks() * block_size_;
961 if (attempt_ioctl) {
962 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700963 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -0700964 continue;
965 attempt_ioctl = false;
Alex Deymo79715ad2015-10-02 14:27:53 -0700966 }
967 // In case of failure, we fall back to writing 0 to the selected region.
Tianjie Xu06bbe492018-01-12 12:37:48 -0800968 zeros.resize(16 * block_size_);
Alex Deymo79715ad2015-10-02 14:27:53 -0700969 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700970 uint64_t chunk_length = min(length - offset,
971 static_cast<uint64_t>(zeros.size()));
Amin Hassanid87304c2017-08-29 11:40:03 -0700972 TEST_AND_RETURN_FALSE(utils::PWriteAll(
973 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -0700974 }
975 }
976 return true;
977}
978
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700979bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700980 // Calculate buffer size. Note, this function doesn't do a sliding
981 // window to copy in case the source and destination blocks overlap.
982 // If we wanted to do a sliding window, we could program the server
983 // to generate deltas that effectively did a sliding window.
984
985 uint64_t blocks_to_read = 0;
986 for (int i = 0; i < operation.src_extents_size(); i++)
987 blocks_to_read += operation.src_extents(i).num_blocks();
988
989 uint64_t blocks_to_write = 0;
990 for (int i = 0; i < operation.dst_extents_size(); i++)
991 blocks_to_write += operation.dst_extents(i).num_blocks();
992
993 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700994 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700995
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700996 // Read in bytes.
997 ssize_t bytes_read = 0;
998 for (int i = 0; i < operation.src_extents_size(); i++) {
999 ssize_t bytes_read_this_iteration = 0;
1000 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001001 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001002 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001003 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001004 &buf[bytes_read],
1005 bytes,
1006 extent.start_block() * block_size_,
1007 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001008 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +02001009 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001010 bytes_read += bytes_read_this_iteration;
1011 }
1012
1013 // Write bytes out.
1014 ssize_t bytes_written = 0;
1015 for (int i = 0; i < operation.dst_extents_size(); i++) {
1016 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +02001017 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -07001018 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001019 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -07001020 &buf[bytes_written],
1021 bytes,
1022 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +02001023 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001024 }
1025 DCHECK_EQ(bytes_written, bytes_read);
1026 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
1027 return true;
1028}
1029
Sen Jiang28d8ed92018-02-01 13:46:39 -08001030bool DeltaPerformer::ValidateSourceHash(const brillo::Blob& calculated_hash,
1031 const InstallOperation& operation,
1032 const FileDescriptorPtr source_fd,
1033 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001034 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1035 operation.src_sha256_hash().end());
1036 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -07001037 LOG(ERROR) << "The hash of the source data on disk for this operation "
1038 << "doesn't match the expected value. This could mean that the "
1039 << "delta update payload was targeted for another version, or "
1040 << "that the source partition was modified after it was "
1041 << "installed, for example, by mounting a filesystem.";
1042 LOG(ERROR) << "Expected: sha256|hex = "
1043 << base::HexEncode(expected_source_hash.data(),
1044 expected_source_hash.size());
1045 LOG(ERROR) << "Calculated: sha256|hex = "
1046 << base::HexEncode(calculated_hash.data(),
1047 calculated_hash.size());
1048
1049 vector<string> source_extents;
1050 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001051 source_extents.push_back(
1052 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1053 static_cast<uint64_t>(ext.start_block()),
1054 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001055 }
1056 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1057 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001058
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001059 // Log remount history if this device is an ext4 partition.
1060 LogMountHistory(source_fd);
1061
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001062 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001063 return false;
1064 }
1065 return true;
1066}
1067
Allie Wood9f6f0a52015-03-30 11:25:47 -07001068bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001069 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001070 if (operation.has_src_length())
1071 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1072 if (operation.has_dst_length())
1073 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1074
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001075 if (operation.has_src_sha256_hash()) {
Alex Deymo51c264e2016-11-04 15:49:53 -07001076 brillo::Blob source_hash;
1077 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1078 operation.src_sha256_hash().end());
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001079
Alex Deymo51c264e2016-11-04 15:49:53 -07001080 // We fall back to use the error corrected device if the hash of the raw
1081 // device doesn't match or there was an error reading the source partition.
1082 // Note that this code will also fall back if writing the target partition
1083 // fails.
1084 bool read_ok = fd_utils::CopyAndHashExtents(source_fd_,
1085 operation.src_extents(),
1086 target_fd_,
1087 operation.dst_extents(),
1088 block_size_,
1089 &source_hash);
1090 if (read_ok && expected_source_hash == source_hash)
1091 return true;
1092
1093 if (!OpenCurrentECCPartition()) {
1094 // The following function call will return false since the source hash
1095 // mismatches, but we still want to call it so it prints the appropriate
1096 // log message.
1097 return ValidateSourceHash(source_hash, operation, source_fd_, error);
1098 }
1099
1100 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1101 << base::HexEncode(source_hash.data(), source_hash.size())
1102 << ", expected "
1103 << base::HexEncode(expected_source_hash.data(),
1104 expected_source_hash.size());
1105
1106 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_ecc_fd_,
1107 operation.src_extents(),
1108 target_fd_,
1109 operation.dst_extents(),
1110 block_size_,
1111 &source_hash));
1112 TEST_AND_RETURN_FALSE(
1113 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error));
1114 // At this point reading from the the error corrected device worked, but
1115 // reading from the raw device failed, so this is considered a recovered
1116 // failure.
1117 source_ecc_recovered_failures_++;
1118 } else {
1119 // When the operation doesn't include a source hash, we attempt the error
1120 // corrected device first since we can't verify the block in the raw device
1121 // at this point, but we fall back to the raw device since the error
1122 // corrected device can be shorter or not available.
1123 if (OpenCurrentECCPartition() &&
1124 fd_utils::CopyAndHashExtents(source_ecc_fd_,
1125 operation.src_extents(),
1126 target_fd_,
1127 operation.dst_extents(),
1128 block_size_,
1129 nullptr)) {
1130 return true;
1131 }
1132 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_fd_,
1133 operation.src_extents(),
1134 target_fd_,
1135 operation.dst_extents(),
1136 block_size_,
1137 nullptr));
1138 }
Allie Wood9f6f0a52015-03-30 11:25:47 -07001139 return true;
1140}
1141
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001142FileDescriptorPtr DeltaPerformer::ChooseSourceFD(
1143 const InstallOperation& operation, ErrorCode* error) {
1144 if (!operation.has_src_sha256_hash()) {
1145 // When the operation doesn't include a source hash, we attempt the error
1146 // corrected device first since we can't verify the block in the raw device
1147 // at this point, but we first need to make sure all extents are readable
1148 // since the error corrected device can be shorter or not available.
1149 if (OpenCurrentECCPartition() &&
1150 fd_utils::ReadAndHashExtents(
1151 source_ecc_fd_, operation.src_extents(), block_size_, nullptr)) {
1152 return source_ecc_fd_;
1153 }
1154 return source_fd_;
1155 }
1156
1157 brillo::Blob source_hash;
1158 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
1159 operation.src_sha256_hash().end());
1160 if (fd_utils::ReadAndHashExtents(
1161 source_fd_, operation.src_extents(), block_size_, &source_hash) &&
1162 source_hash == expected_source_hash) {
1163 return source_fd_;
1164 }
1165 // We fall back to use the error corrected device if the hash of the raw
1166 // device doesn't match or there was an error reading the source partition.
1167 if (!OpenCurrentECCPartition()) {
1168 // The following function call will return false since the source hash
1169 // mismatches, but we still want to call it so it prints the appropriate
1170 // log message.
1171 ValidateSourceHash(source_hash, operation, source_fd_, error);
1172 return nullptr;
1173 }
1174 LOG(WARNING) << "Source hash from RAW device mismatched: found "
1175 << base::HexEncode(source_hash.data(), source_hash.size())
1176 << ", expected "
1177 << base::HexEncode(expected_source_hash.data(),
1178 expected_source_hash.size());
1179
1180 if (fd_utils::ReadAndHashExtents(
1181 source_ecc_fd_, operation.src_extents(), block_size_, &source_hash) &&
1182 ValidateSourceHash(source_hash, operation, source_ecc_fd_, error)) {
1183 // At this point reading from the the error corrected device worked, but
1184 // reading from the raw device failed, so this is considered a recovered
1185 // failure.
1186 source_ecc_recovered_failures_++;
1187 return source_ecc_fd_;
1188 }
1189 return nullptr;
1190}
1191
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001192bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1193 const RepeatedPtrField<Extent>& extents,
1194 uint64_t block_size,
1195 uint64_t full_length,
1196 string* positions_string) {
1197 string ret;
1198 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001199 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001200 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001201 uint64_t this_length =
1202 min(full_length - length,
1203 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001204 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001205 length += this_length;
1206 }
1207 TEST_AND_RETURN_FALSE(length == full_length);
1208 if (!ret.empty())
1209 ret.resize(ret.size() - 1); // Strip trailing comma off
1210 *positions_string = ret;
1211 return true;
1212}
1213
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001214bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001215 // Since we delete data off the beginning of the buffer as we use it,
1216 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001217 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1218 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001219
1220 string input_positions;
1221 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1222 block_size_,
1223 operation.src_length(),
1224 &input_positions));
1225 string output_positions;
1226 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1227 block_size_,
1228 operation.dst_length(),
1229 &output_positions));
1230
Sen Jiang7a659092016-05-10 15:31:46 -07001231 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1232 target_path_.c_str(),
1233 buffer_.data(),
1234 buffer_.size(),
1235 input_positions.c_str(),
1236 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001237 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001238
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001239 if (operation.dst_length() % block_size_) {
1240 // Zero out rest of final block.
1241 // TODO(adlr): build this into bspatch; it's more efficient that way.
1242 const Extent& last_extent =
1243 operation.dst_extents(operation.dst_extents_size() - 1);
1244 const uint64_t end_byte =
1245 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1246 const uint64_t begin_byte =
1247 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001248 brillo::Blob zeros(end_byte - begin_byte);
Amin Hassanid87304c2017-08-29 11:40:03 -07001249 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1250 target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001251 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001252 return true;
1253}
1254
Amin Hassanid9cb2902017-09-20 12:11:39 -07001255namespace {
1256
1257class BsdiffExtentFile : public bsdiff::FileInterface {
1258 public:
1259 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader, size_t size)
1260 : BsdiffExtentFile(std::move(reader), nullptr, size) {}
1261 BsdiffExtentFile(std::unique_ptr<ExtentWriter> writer, size_t size)
1262 : BsdiffExtentFile(nullptr, std::move(writer), size) {}
1263
1264 ~BsdiffExtentFile() override = default;
1265
1266 bool Read(void* buf, size_t count, size_t* bytes_read) override {
1267 TEST_AND_RETURN_FALSE(reader_->Read(buf, count));
1268 *bytes_read = count;
1269 offset_ += count;
1270 return true;
1271 }
1272
1273 bool Write(const void* buf, size_t count, size_t* bytes_written) override {
1274 TEST_AND_RETURN_FALSE(writer_->Write(buf, count));
1275 *bytes_written = count;
1276 offset_ += count;
1277 return true;
1278 }
1279
1280 bool Seek(off_t pos) override {
1281 if (reader_ != nullptr) {
1282 TEST_AND_RETURN_FALSE(reader_->Seek(pos));
1283 offset_ = pos;
1284 } else {
1285 // For writes technically there should be no change of position, or it
1286 // should be equivalent of current offset.
1287 TEST_AND_RETURN_FALSE(offset_ == static_cast<uint64_t>(pos));
1288 }
1289 return true;
1290 }
1291
1292 bool Close() override {
1293 if (writer_ != nullptr) {
1294 TEST_AND_RETURN_FALSE(writer_->End());
1295 }
1296 return true;
1297 }
1298
1299 bool GetSize(uint64_t* size) override {
1300 *size = size_;
1301 return true;
1302 }
1303
1304 private:
1305 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader,
1306 std::unique_ptr<ExtentWriter> writer,
1307 size_t size)
1308 : reader_(std::move(reader)),
1309 writer_(std::move(writer)),
1310 size_(size),
1311 offset_(0) {}
1312
1313 std::unique_ptr<ExtentReader> reader_;
1314 std::unique_ptr<ExtentWriter> writer_;
1315 uint64_t size_;
1316 uint64_t offset_;
1317
1318 DISALLOW_COPY_AND_ASSIGN(BsdiffExtentFile);
1319};
1320
1321} // namespace
1322
Allie Wood9f6f0a52015-03-30 11:25:47 -07001323bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001324 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001325 // Since we delete data off the beginning of the buffer as we use it,
1326 // the data we need should be exactly at the beginning of the buffer.
1327 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1328 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1329 if (operation.has_src_length())
1330 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1331 if (operation.has_dst_length())
1332 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1333
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001334 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1335 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001336
Amin Hassanid9cb2902017-09-20 12:11:39 -07001337 auto reader = std::make_unique<DirectExtentReader>();
1338 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001339 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassanid9cb2902017-09-20 12:11:39 -07001340 auto src_file = std::make_unique<BsdiffExtentFile>(
1341 std::move(reader),
1342 utils::BlocksInExtents(operation.src_extents()) * block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001343
Amin Hassanid9cb2902017-09-20 12:11:39 -07001344 auto writer = std::make_unique<DirectExtentWriter>();
1345 TEST_AND_RETURN_FALSE(
1346 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1347 auto dst_file = std::make_unique<BsdiffExtentFile>(
1348 std::move(writer),
1349 utils::BlocksInExtents(operation.dst_extents()) * block_size_);
1350
1351 TEST_AND_RETURN_FALSE(bsdiff::bspatch(std::move(src_file),
1352 std::move(dst_file),
Sen Jiang7a659092016-05-10 15:31:46 -07001353 buffer_.data(),
Amin Hassanid9cb2902017-09-20 12:11:39 -07001354 buffer_.size()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001355 DiscardBuffer(true, buffer_.size());
1356 return true;
1357}
1358
Amin Hassani02855c22017-09-06 22:34:50 -07001359namespace {
1360
1361// A class to be passed to |puffpatch| for reading from |source_fd_| and writing
1362// into |target_fd_|.
1363class PuffinExtentStream : public puffin::StreamInterface {
1364 public:
1365 // Constructor for creating a stream for reading from an |ExtentReader|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001366 PuffinExtentStream(std::unique_ptr<ExtentReader> reader, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001367 : PuffinExtentStream(std::move(reader), nullptr, size) {}
1368
1369 // Constructor for creating a stream for writing to an |ExtentWriter|.
Amin Hassani678a68f2018-02-28 11:54:47 -08001370 PuffinExtentStream(std::unique_ptr<ExtentWriter> writer, uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001371 : PuffinExtentStream(nullptr, std::move(writer), size) {}
1372
1373 ~PuffinExtentStream() override = default;
1374
Amin Hassani678a68f2018-02-28 11:54:47 -08001375 bool GetSize(uint64_t* size) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001376 *size = size_;
1377 return true;
1378 }
1379
Amin Hassani678a68f2018-02-28 11:54:47 -08001380 bool GetOffset(uint64_t* offset) const override {
Amin Hassani02855c22017-09-06 22:34:50 -07001381 *offset = offset_;
1382 return true;
1383 }
1384
Amin Hassani678a68f2018-02-28 11:54:47 -08001385 bool Seek(uint64_t offset) override {
Amin Hassani02855c22017-09-06 22:34:50 -07001386 if (is_read_) {
1387 TEST_AND_RETURN_FALSE(reader_->Seek(offset));
1388 offset_ = offset;
1389 } else {
1390 // For writes technically there should be no change of position, or it
1391 // should equivalent of current offset.
1392 TEST_AND_RETURN_FALSE(offset_ == offset);
1393 }
1394 return true;
1395 }
1396
1397 bool Read(void* buffer, size_t count) override {
1398 TEST_AND_RETURN_FALSE(is_read_);
1399 TEST_AND_RETURN_FALSE(reader_->Read(buffer, count));
1400 offset_ += count;
1401 return true;
1402 }
1403
1404 bool Write(const void* buffer, size_t count) override {
1405 TEST_AND_RETURN_FALSE(!is_read_);
1406 TEST_AND_RETURN_FALSE(writer_->Write(buffer, count));
1407 offset_ += count;
1408 return true;
1409 }
1410
1411 bool Close() override {
1412 if (!is_read_) {
1413 TEST_AND_RETURN_FALSE(writer_->End());
1414 }
1415 return true;
1416 }
1417
1418 private:
1419 PuffinExtentStream(std::unique_ptr<ExtentReader> reader,
1420 std::unique_ptr<ExtentWriter> writer,
Amin Hassani678a68f2018-02-28 11:54:47 -08001421 uint64_t size)
Amin Hassani02855c22017-09-06 22:34:50 -07001422 : reader_(std::move(reader)),
1423 writer_(std::move(writer)),
1424 size_(size),
1425 offset_(0),
1426 is_read_(reader_ ? true : false) {}
1427
1428 std::unique_ptr<ExtentReader> reader_;
1429 std::unique_ptr<ExtentWriter> writer_;
1430 uint64_t size_;
1431 uint64_t offset_;
1432 bool is_read_;
1433
1434 DISALLOW_COPY_AND_ASSIGN(PuffinExtentStream);
1435};
1436
1437} // namespace
1438
1439bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
1440 ErrorCode* error) {
1441 // Since we delete data off the beginning of the buffer as we use it,
1442 // the data we need should be exactly at the beginning of the buffer.
1443 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1444 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1445
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001446 FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
1447 TEST_AND_RETURN_FALSE(source_fd != nullptr);
Amin Hassani02855c22017-09-06 22:34:50 -07001448
1449 auto reader = std::make_unique<DirectExtentReader>();
1450 TEST_AND_RETURN_FALSE(
Sen Jiang77ab7bd2018-05-22 17:24:23 -07001451 reader->Init(source_fd, operation.src_extents(), block_size_));
Amin Hassani02855c22017-09-06 22:34:50 -07001452 puffin::UniqueStreamPtr src_stream(new PuffinExtentStream(
1453 std::move(reader),
1454 utils::BlocksInExtents(operation.src_extents()) * block_size_));
1455
1456 auto writer = std::make_unique<DirectExtentWriter>();
1457 TEST_AND_RETURN_FALSE(
1458 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1459 puffin::UniqueStreamPtr dst_stream(new PuffinExtentStream(
1460 std::move(writer),
1461 utils::BlocksInExtents(operation.dst_extents()) * block_size_));
1462
1463 const size_t kMaxCacheSize = 5 * 1024 * 1024; // Total 5MB cache.
1464 TEST_AND_RETURN_FALSE(puffin::PuffPatch(std::move(src_stream),
1465 std::move(dst_stream),
1466 buffer_.data(),
1467 buffer_.size(),
1468 kMaxCacheSize));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001469 DiscardBuffer(true, buffer_.size());
Alex Deymoa12ee112015-08-12 22:19:32 -07001470 return true;
1471}
Darin Petkovd7061ab2010-10-06 14:37:09 -07001472
Darin Petkovd7061ab2010-10-06 14:37:09 -07001473bool DeltaPerformer::ExtractSignatureMessageFromOperation(
1474 const InstallOperation& operation) {
1475 if (operation.type() != InstallOperation::REPLACE ||
1476 !manifest_.has_signatures_offset() ||
1477 manifest_.signatures_offset() != operation.data_offset()) {
1478 return false;
1479 }
1480 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1481 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001482 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1483 return true;
1484}
1485
1486bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001487 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1488 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1489 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001490 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001491 buffer_.begin(),
1492 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001493
1494 // Save the signature blob because if the update is interrupted after the
1495 // download phase we don't go through this path anymore. Some alternatives to
1496 // consider:
1497 //
1498 // 1. On resume, re-download the signature blob from the server and re-verify
1499 // it.
1500 //
1501 // 2. Verify the signature as soon as it's received and don't checkpoint the
1502 // blob and the signed sha-256 context.
1503 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001504 string(signatures_message_data_.begin(),
1505 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001506 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001507
Darin Petkovd7061ab2010-10-06 14:37:09 -07001508 LOG(INFO) << "Extracted signature data of size "
1509 << manifest_.signatures_size() << " at "
1510 << manifest_.signatures_offset();
1511 return true;
1512}
1513
David Zeuthene7f89172013-10-31 10:21:04 -07001514bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
Alex Deymo542c19b2015-12-03 07:43:31 -03001515 if (hardware_->IsOfficialBuild() ||
David Zeuthene7f89172013-10-31 10:21:04 -07001516 utils::FileExists(public_key_path_.c_str()) ||
1517 install_plan_->public_key_rsa.empty())
1518 return false;
1519
1520 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1521 out_tmp_key))
1522 return false;
1523
1524 return true;
1525}
1526
Gilad Arnold21504f02013-05-24 08:51:22 -07001527ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001528 // Perform assorted checks to sanity check the manifest, make sure it
1529 // matches data from other sources, and that it is a supported version.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001530
Alex Deymo64d98782016-02-05 18:03:48 -08001531 bool has_old_fields =
1532 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1533 for (const PartitionUpdate& partition : manifest_.partitions()) {
1534 has_old_fields = has_old_fields || partition.has_old_partition_info();
1535 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001536
Alex Deymo64d98782016-02-05 18:03:48 -08001537 // The presence of an old partition hash is the sole indicator for a delta
1538 // update.
1539 InstallPayloadType actual_payload_type =
1540 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1541
Sen Jiangcdd52062017-05-18 15:33:10 -07001542 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001543 LOG(INFO) << "Detected a '"
1544 << InstallPayloadTypeToString(actual_payload_type)
1545 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001546 payload_->type = actual_payload_type;
1547 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001548 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001549 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001550 << "' payload but the downloaded manifest contains a '"
1551 << InstallPayloadTypeToString(actual_payload_type)
1552 << "' payload.";
1553 return ErrorCode::kPayloadMismatchedType;
1554 }
1555
1556 // Check that the minor version is compatible.
1557 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001558 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1559 LOG(ERROR) << "Manifest contains minor version "
1560 << manifest_.minor_version()
1561 << ", but all full payloads should have version "
1562 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001563 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001564 }
1565 } else {
Sen Jiangdcaf7972018-05-11 16:03:23 -07001566 if (manifest_.minor_version() < kMinSupportedMinorPayloadVersion ||
1567 manifest_.minor_version() > kMaxSupportedMinorPayloadVersion) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001568 LOG(ERROR) << "Manifest contains minor version "
1569 << manifest_.minor_version()
Sen Jiangdcaf7972018-05-11 16:03:23 -07001570 << " not in the range of supported minor versions ["
1571 << kMinSupportedMinorPayloadVersion << ", "
1572 << kMaxSupportedMinorPayloadVersion << "].";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001573 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001574 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001575 }
1576
Sen Jiang3e728fe2015-11-05 11:37:23 -08001577 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
1578 if (manifest_.has_old_rootfs_info() ||
1579 manifest_.has_new_rootfs_info() ||
1580 manifest_.has_old_kernel_info() ||
1581 manifest_.has_new_kernel_info() ||
1582 manifest_.install_operations_size() != 0 ||
1583 manifest_.kernel_install_operations_size() != 0) {
1584 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1585 << "major payload version 1, but the payload major version is "
1586 << major_payload_version_;
1587 return ErrorCode::kPayloadMismatchedType;
1588 }
1589 }
1590
Gilad Arnold21504f02013-05-24 08:51:22 -07001591 // TODO(garnold) we should be adding more and more manifest checks, such as
1592 // partition boundaries etc (see chromium-os:37661).
1593
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001594 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001595}
1596
David Zeuthena99981f2013-04-29 13:42:47 -07001597ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001598 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001599 if (!operation.data_sha256_hash().size()) {
1600 if (!operation.data_length()) {
1601 // Operations that do not have any data blob won't have any operation hash
1602 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001603 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001604 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001605 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001606 }
1607
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001608 // No hash is present for an operation that has data blobs. This shouldn't
1609 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001610 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001611 // hashes. So if it happens it means either we've turned operation hash
1612 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001613 // One caveat though: The last operation is a dummy signature operation
1614 // that doesn't have a hash at the time the manifest is created. So we
1615 // should not complaint about that operation. This operation can be
1616 // recognized by the fact that it's offset is mentioned in the manifest.
1617 if (manifest_.signatures_offset() &&
1618 manifest_.signatures_offset() == operation.data_offset()) {
1619 LOG(INFO) << "Skipping hash verification for signature operation "
1620 << next_operation_num_ + 1;
1621 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001622 if (install_plan_->hash_checks_mandatory) {
1623 LOG(ERROR) << "Missing mandatory operation hash for operation "
1624 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001625 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001626 }
1627
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001628 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1629 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001630 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001631 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001632 }
1633
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001634 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001635 expected_op_hash.assign(operation.data_sha256_hash().data(),
1636 (operation.data_sha256_hash().data() +
1637 operation.data_sha256_hash().size()));
1638
Sen Jiang2703ef42017-03-16 13:36:21 -07001639 brillo::Blob calculated_op_hash;
1640 if (!HashCalculator::RawHashOfBytes(
1641 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001642 LOG(ERROR) << "Unable to compute actual hash of operation "
1643 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001644 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001645 }
1646
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001647 if (calculated_op_hash != expected_op_hash) {
1648 LOG(ERROR) << "Hash verification failed for operation "
1649 << next_operation_num_ << ". Expected hash = ";
1650 utils::HexDumpVector(expected_op_hash);
1651 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1652 << " bytes at offset: " << operation.data_offset() << " = ";
1653 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001654 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001655 }
1656
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001657 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001658}
1659
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001660#define TEST_AND_RETURN_VAL(_retval, _condition) \
1661 do { \
1662 if (!(_condition)) { \
1663 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1664 return _retval; \
1665 } \
1666 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001667
David Zeuthena99981f2013-04-29 13:42:47 -07001668ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001669 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001670 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001671
1672 // See if we should use the public RSA key in the Omaha response.
1673 base::FilePath path_to_public_key(public_key_path_);
1674 base::FilePath tmp_key;
1675 if (GetPublicKeyFromResponse(&tmp_key))
1676 path_to_public_key = tmp_key;
1677 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1678 if (tmp_key.empty())
1679 tmp_key_remover.set_should_remove(false);
1680
1681 LOG(INFO) << "Verifying payload using public key: "
1682 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001683
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001684 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001685 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001686 update_check_response_size ==
Sen Jiang76bfa742015-10-12 17:13:26 -07001687 metadata_size_ + metadata_signature_size_ +
1688 buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001689
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001690 // Verifies the payload hash.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001691 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Sen Jiang2703ef42017-03-16 13:36:21 -07001692 !payload_hash_calculator_.raw_hash().empty());
1693 TEST_AND_RETURN_VAL(
1694 ErrorCode::kPayloadHashMismatchError,
1695 payload_hash_calculator_.raw_hash() == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001696
Darin Petkov437adc42010-10-07 13:12:24 -07001697 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001698 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001699 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001700 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001701 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001702 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001703 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001704 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001705 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1706 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001707 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001708 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001709
1710 if (!PayloadVerifier::VerifySignature(
1711 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001712 // The autoupdate_CatchBadSignatures test checks for this string
1713 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001714 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001715 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001716 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001717
David Zeuthene7f89172013-10-31 10:21:04 -07001718 LOG(INFO) << "Payload hash matches value in payload.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001719 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001720}
1721
Sen Jiangf6813802015-11-03 21:27:29 -08001722void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1723 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001724 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001725 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001726 buffer_offset_ += buffer_.size();
1727
1728 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001729 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1730 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001731
1732 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001733 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001734}
1735
Darin Petkov0406e402010-10-06 21:33:11 -07001736bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001737 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001738 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001739 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1740 next_operation != kUpdateStateOperationInvalid &&
1741 next_operation > 0))
1742 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001743
1744 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001745 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1746 !interrupted_hash.empty() &&
1747 interrupted_hash == update_check_response_hash))
1748 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001749
Darin Petkov61426142010-10-08 11:04:55 -07001750 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001751 // Note that storing this value is optional, but if it is there it should not
1752 // be more than the limit.
1753 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1754 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001755 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001756
Darin Petkov0406e402010-10-06 21:33:11 -07001757 // Sanity check the rest.
1758 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001759 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1760 next_data_offset >= 0))
1761 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001762
Darin Petkov437adc42010-10-07 13:12:24 -07001763 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001764 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1765 !sha256_context.empty()))
1766 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001767
1768 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001769 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1770 manifest_metadata_size > 0))
1771 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001772
Alex Deymof25eb492016-02-26 00:20:08 -08001773 int64_t manifest_signature_size = 0;
1774 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1775 &manifest_signature_size) &&
1776 manifest_signature_size >= 0))
1777 return false;
1778
Darin Petkov0406e402010-10-06 21:33:11 -07001779 return true;
1780}
1781
Darin Petkov9b230572010-10-08 10:20:09 -07001782bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001783 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1784 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001785 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001786 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001787 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001788 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1789 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001790 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001791 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001792 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001793 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiang02c49422017-10-31 15:14:11 -07001794 prefs->Delete(kPrefsPostInstallSucceeded);
Darin Petkov9b230572010-10-08 10:20:09 -07001795 }
Darin Petkov73058b42010-10-06 16:32:19 -07001796 return true;
1797}
1798
1799bool DeltaPerformer::CheckpointUpdateProgress() {
Colin Howes0e452c92018-11-02 13:18:44 -07001800 base::Time curr_time = base::Time::Now();
1801 if (curr_time > update_checkpoint_time_) {
1802 update_checkpoint_time_ = curr_time + update_checkpoint_wait_;
1803 } else {
1804 return false;
1805 }
1806
Darin Petkov9c0baf82010-10-07 13:44:48 -07001807 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001808 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001809 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001810 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001811 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001812 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Sen Jiangf6813802015-11-03 21:27:29 -08001813 payload_hash_calculator_.GetContext()));
1814 TEST_AND_RETURN_FALSE(
1815 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1816 signed_hash_calculator_.GetContext()));
Darin Petkov0406e402010-10-06 21:33:11 -07001817 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1818 buffer_offset_));
1819 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001820
1821 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001822 size_t partition_index = current_partition_;
1823 while (next_operation_num_ >= acc_num_operations_[partition_index])
1824 partition_index++;
1825 const size_t partition_operation_num = next_operation_num_ - (
1826 partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001827 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001828 partitions_[partition_index].operations(partition_operation_num);
David Zeuthen41996ad2013-09-24 15:43:24 -07001829 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1830 op.data_length()));
1831 } else {
1832 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1833 0));
1834 }
Darin Petkov0406e402010-10-06 21:33:11 -07001835 }
Darin Petkov73058b42010-10-06 16:32:19 -07001836 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1837 next_operation_num_));
1838 return true;
1839}
1840
Darin Petkov9b230572010-10-08 10:20:09 -07001841bool DeltaPerformer::PrimeUpdateState() {
1842 CHECK(manifest_valid_);
1843 block_size_ = manifest_.block_size();
1844
1845 int64_t next_operation = kUpdateStateOperationInvalid;
1846 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1847 next_operation == kUpdateStateOperationInvalid ||
1848 next_operation <= 0) {
1849 // Initiating a new update, no more state needs to be initialized.
1850 return true;
1851 }
1852 next_operation_num_ = next_operation;
1853
1854 // Resuming an update -- load the rest of the update state.
1855 int64_t next_data_offset = -1;
1856 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1857 &next_data_offset) &&
1858 next_data_offset >= 0);
1859 buffer_offset_ = next_data_offset;
1860
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001861 // The signed hash context and the signature blob may be empty if the
1862 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001863 string signed_hash_context;
1864 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1865 &signed_hash_context)) {
1866 TEST_AND_RETURN_FALSE(
1867 signed_hash_calculator_.SetContext(signed_hash_context));
1868 }
1869
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001870 string signature_blob;
1871 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1872 signatures_message_data_.assign(signature_blob.begin(),
1873 signature_blob.end());
1874 }
Darin Petkov9b230572010-10-08 10:20:09 -07001875
1876 string hash_context;
1877 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1878 &hash_context) &&
Sen Jiangf6813802015-11-03 21:27:29 -08001879 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001880
1881 int64_t manifest_metadata_size = 0;
1882 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1883 &manifest_metadata_size) &&
1884 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001885 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001886
Alex Deymof25eb492016-02-26 00:20:08 -08001887 int64_t manifest_signature_size = 0;
1888 TEST_AND_RETURN_FALSE(
1889 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1890 manifest_signature_size >= 0);
1891 metadata_signature_size_ = manifest_signature_size;
1892
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001893 // Advance the download progress to reflect what doesn't need to be
1894 // re-downloaded.
1895 total_bytes_received_ += buffer_offset_;
1896
Darin Petkov61426142010-10-08 11:04:55 -07001897 // Speculatively count the resume as a failure.
1898 int64_t resumed_update_failures;
1899 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1900 resumed_update_failures++;
1901 } else {
1902 resumed_update_failures = 1;
1903 }
1904 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001905 return true;
1906}
1907
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001908} // namespace chromeos_update_engine