blob: dee1daf25922f8860ed246455b356c0043885e06 [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 Deymoa48f6302016-11-04 15:49:53 -070051#include "update_engine/payload_consumer/file_descriptor_utils.h"
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +010052#include "update_engine/payload_consumer/mount_history.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080053#if USE_MTD
Alex Deymo39910dc2015-11-09 17:04:30 -080054#include "update_engine/payload_consumer/mtd_file_descriptor.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080055#endif
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/payload_consumer/payload_constants.h"
57#include "update_engine/payload_consumer/payload_verifier.h"
58#include "update_engine/payload_consumer/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070059
Alex Deymo161c4a12014-05-16 15:56:21 -070060using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070061using std::min;
62using std::string;
63using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070064
65namespace chromeos_update_engine {
66
Alex Deymo7a2c47e2015-11-04 00:47:12 -080067const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 2;
Amin Hassani7bc9c022017-11-07 14:01:39 -080068const uint32_t DeltaPerformer::kSupportedMinorPayloadVersion = 4;
Don Garrett4d039442013-10-28 18:40:06 -070069
Gilad Arnold8a86fa52013-01-15 12:35:05 -080070const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
71const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
72const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
73const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
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();
330 source_path_.clear();
331
332 if (target_fd_ && !target_fd_->Close()) {
333 err = errno;
334 PLOG(ERROR) << "Error closing target partition";
335 if (!err)
336 err = 1;
337 }
338 target_fd_.reset();
339 target_path_.clear();
340 return -err;
341}
342
343bool DeltaPerformer::OpenCurrentPartition() {
344 if (current_partition_ >= partitions_.size())
345 return false;
346
347 const PartitionUpdate& partition = partitions_[current_partition_];
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700348 size_t num_previous_partitions =
349 install_plan_->partitions.size() - partitions_.size();
350 const InstallPlan::Partition& install_part =
351 install_plan_->partitions[num_previous_partitions + current_partition_];
Sen Jiang889c65d2015-11-17 15:04:02 -0800352 // Open source fds if we have a delta payload with minor version >= 2.
Sen Jiangcdd52062017-05-18 15:33:10 -0700353 if (payload_->type == InstallPayloadType::kDelta &&
Sen Jiang889c65d2015-11-17 15:04:02 -0800354 GetMinorVersion() != kInPlaceMinorPayloadVersion) {
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700355 source_path_ = install_part.source_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700356 int err;
Amin Hassania3fc20a2017-09-19 17:19:34 -0700357 source_fd_ = OpenFile(source_path_.c_str(), O_RDONLY, false, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700358 if (!source_fd_) {
359 LOG(ERROR) << "Unable to open source partition "
360 << partition.partition_name() << " on slot "
361 << BootControlInterface::SlotName(install_plan_->source_slot)
362 << ", file " << source_path_;
363 return false;
364 }
365 }
366
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700367 target_path_ = install_part.target_path;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700368 int err;
Grant Grundlera763c2d2017-05-10 11:12:52 -0700369
Amin Hassani7ecda262017-07-11 17:10:50 -0700370 int flags = O_RDWR;
371 if (!is_interactive_)
372 flags |= O_DSYNC;
373
374 LOG(INFO) << "Opening " << target_path_ << " partition with"
375 << (is_interactive_ ? "out" : "") << " O_DSYNC";
376
Amin Hassania3fc20a2017-09-19 17:19:34 -0700377 target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700378 if (!target_fd_) {
379 LOG(ERROR) << "Unable to open target partition "
380 << partition.partition_name() << " on slot "
381 << BootControlInterface::SlotName(install_plan_->target_slot)
382 << ", file " << target_path_;
383 return false;
384 }
Alex Deymob86787c2016-05-12 18:46:25 -0700385
386 LOG(INFO) << "Applying " << partition.operations().size()
387 << " operations to partition \"" << partition.partition_name()
388 << "\"";
389
390 // Discard the end of the partition, but ignore failures.
Sen Jiangd2ff2a02017-04-06 14:53:31 -0700391 DiscardPartitionTail(target_fd_, install_part.target_size);
Alex Deymob86787c2016-05-12 18:46:25 -0700392
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700393 return true;
394}
395
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700396namespace {
397
398void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700399 string sha256 = brillo::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800400 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
401 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700402}
403
Alex Deymo39910dc2015-11-09 17:04:30 -0800404void LogPartitionInfo(const vector<PartitionUpdate>& partitions) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700405 for (const PartitionUpdate& partition : partitions) {
Sen Jiang7b9a5872018-01-17 13:25:06 -0800406 if (partition.has_old_partition_info()) {
407 LogPartitionInfoHash(partition.old_partition_info(),
408 "old " + partition.partition_name());
409 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700410 LogPartitionInfoHash(partition.new_partition_info(),
411 "new " + partition.partition_name());
412 }
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700413}
414
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700415} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700416
Allie Woodfdf00512015-03-02 13:34:55 -0800417uint32_t DeltaPerformer::GetMinorVersion() const {
418 if (manifest_.has_minor_version()) {
419 return manifest_.minor_version();
420 } else {
Sen Jiangcdd52062017-05-18 15:33:10 -0700421 return payload_->type == InstallPayloadType::kDelta
Alex Deymo64d98782016-02-05 18:03:48 -0800422 ? kSupportedMinorPayloadVersion
423 : kFullPayloadMinorVersion;
Allie Woodfdf00512015-03-02 13:34:55 -0800424 }
425}
426
Sen Jiangb8060e42015-09-24 17:30:50 -0700427bool DeltaPerformer::IsHeaderParsed() const {
428 return metadata_size_ != 0;
429}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700430
Sen Jiang9c89e842018-02-02 13:51:21 -0800431MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700432 const brillo::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700433 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700434
Sen Jiangb8060e42015-09-24 17:30:50 -0700435 if (!IsHeaderParsed()) {
Sen Jiang9c89e842018-02-02 13:51:21 -0800436 MetadataParseResult result = payload_metadata_.ParsePayloadHeader(
437 payload, supported_major_version_, error);
438 if (result != MetadataParseResult::kSuccess)
439 return result;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700440
Sen Jiang9c89e842018-02-02 13:51:21 -0800441 metadata_size_ = payload_metadata_.GetMetadataSize();
442 metadata_signature_size_ = payload_metadata_.GetMetadataSignatureSize();
443 major_payload_version_ = payload_metadata_.GetMajorVersion();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800444
445 // If the metadata size is present in install plan, check for it immediately
446 // even before waiting for that many number of bytes to be downloaded in the
447 // payload. This will prevent any attack which relies on us downloading data
448 // beyond the expected metadata size.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800449 if (install_plan_->hash_checks_mandatory) {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800450 if (payload_->metadata_size != metadata_size_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800451 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800452 << payload_->metadata_size
Gilad Arnoldfe133932014-01-14 12:25:50 -0800453 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700454 *error = ErrorCode::kDownloadInvalidMetadataSize;
Sen Jiang9c89e842018-02-02 13:51:21 -0800455 return MetadataParseResult::kError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800456 }
457 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700458 }
459
460 // Now that we have validated the metadata size, we should wait for the full
Sen Jiang76bfa742015-10-12 17:13:26 -0700461 // metadata and its signature (if exist) to be read in before we can parse it.
462 if (payload.size() < metadata_size_ + metadata_signature_size_)
Sen Jiang9c89e842018-02-02 13:51:21 -0800463 return MetadataParseResult::kInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700464
465 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700466 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700467 // that we just log once (instead of logging n times) if it takes n
468 // DeltaPerformer::Write calls to download the full manifest.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800469 if (payload_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700470 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800471 } else {
472 // For mandatory-cases, we'd have already returned a kMetadataParseError
473 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
474 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
Sen Jiang0affc2c2017-02-10 15:55:05 -0800475 << payload_->metadata_size
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800476 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800477 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800478 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700479
Sen Jiang9c89e842018-02-02 13:51:21 -0800480 // See if we should use the public RSA key in the Omaha response.
481 base::FilePath path_to_public_key(public_key_path_);
482 base::FilePath tmp_key;
483 if (GetPublicKeyFromResponse(&tmp_key))
484 path_to_public_key = tmp_key;
485 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
486 if (tmp_key.empty())
487 tmp_key_remover.set_should_remove(false);
488
Jay Srinivasanf4318702012-09-24 11:56:24 -0700489 // We have the full metadata in |payload|. Verify its integrity
490 // and authenticity based on the information we have in Omaha response.
Sen Jiang9c89e842018-02-02 13:51:21 -0800491 *error = payload_metadata_.ValidateMetadataSignature(
492 payload, payload_->metadata_signature, path_to_public_key);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700493 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800494 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800495 // The autoupdate_CatchBadSignatures test checks for this string
496 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800497 LOG(ERROR) << "Mandatory metadata signature validation failed";
Sen Jiang9c89e842018-02-02 13:51:21 -0800498 return MetadataParseResult::kError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800499 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700500
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800501 // For non-mandatory cases, just send a UMA stat.
502 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700503 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700504 }
505
Gilad Arnolddaa27402014-01-23 11:56:17 -0800506 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiang9c89e842018-02-02 13:51:21 -0800507 if (!payload_metadata_.GetManifest(payload, &manifest_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800508 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700509 *error = ErrorCode::kDownloadManifestParseError;
Sen Jiang9c89e842018-02-02 13:51:21 -0800510 return MetadataParseResult::kError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800511 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800512
513 manifest_parsed_ = true;
Sen Jiang9c89e842018-02-02 13:51:21 -0800514 return MetadataParseResult::kSuccess;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800515}
516
Lann Martin39f57142017-07-14 09:18:42 -0600517#define OP_DURATION_HISTOGRAM(_op_name, _start_time) \
518 LOCAL_HISTOGRAM_CUSTOM_TIMES( \
519 "UpdateEngine.DownloadAction.InstallOperation::" \
520 _op_name ".Duration", \
521 base::TimeTicks::Now() - _start_time, \
522 base::TimeDelta::FromMilliseconds(10), \
523 base::TimeDelta::FromMinutes(5), \
524 20);
525
Don Garrette410e0f2011-11-10 15:39:01 -0800526// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800527// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700528// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800529bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700530 *error = ErrorCode::kSuccess;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700531 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800532
533 // Update the total byte downloaded count and the progress logs.
534 total_bytes_received_ += count;
535 UpdateOverallProgress(false, "Completed ");
536
Gilad Arnoldfe133932014-01-14 12:25:50 -0800537 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700538 // Read data up to the needed limit; this is either maximium payload header
539 // size, or the full metadata size (once it becomes known).
540 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800541 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700542 (do_read_header ? kMaxPayloadHeaderSize :
Sen Jiang76bfa742015-10-12 17:13:26 -0700543 metadata_size_ + metadata_signature_size_));
Gilad Arnoldfe133932014-01-14 12:25:50 -0800544
Gilad Arnolddaa27402014-01-23 11:56:17 -0800545 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Sen Jiang9c89e842018-02-02 13:51:21 -0800546 if (result == MetadataParseResult::kError)
Don Garrette410e0f2011-11-10 15:39:01 -0800547 return false;
Sen Jiang9c89e842018-02-02 13:51:21 -0800548 if (result == MetadataParseResult::kInsufficientData) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800549 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700550 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800551 continue;
552
Don Garrette410e0f2011-11-10 15:39:01 -0800553 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800554 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700555
556 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700557 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700558 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800559 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700560
Gilad Arnoldfe133932014-01-14 12:25:50 -0800561 // Clear the download buffer.
Sen Jiangf6813802015-11-03 21:27:29 -0800562 DiscardBuffer(false, metadata_size_);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700563
564 // This populates |partitions_| and the |install_plan.partitions| with the
565 // list of partitions from the manifest.
566 if (!ParseManifestPartitions(error))
567 return false;
568
Sen Jiang5ae865b2017-04-18 14:24:40 -0700569 // |install_plan.partitions| was filled in, nothing need to be done here if
570 // the payload was already applied, returns false to terminate http fetcher,
571 // but keep |error| as ErrorCode::kSuccess.
572 if (payload_->already_applied)
573 return false;
574
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700575 num_total_operations_ = 0;
576 for (const auto& partition : partitions_) {
577 num_total_operations_ += partition.operations_size();
578 acc_num_operations_.push_back(num_total_operations_);
579 }
580
Darin Petkov73058b42010-10-06 16:32:19 -0700581 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800582 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700583 << "Unable to save the manifest metadata size.";
Alex Deymof25eb492016-02-26 00:20:08 -0800584 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestSignatureSize,
585 metadata_signature_size_))
586 << "Unable to save the manifest signature size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700587
Darin Petkov9b230572010-10-08 10:20:09 -0700588 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700589 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700590 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800591 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700592 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800593
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700594 if (!OpenCurrentPartition()) {
595 *error = ErrorCode::kInstallDeviceOpenError;
596 return false;
Allie Woodfdf00512015-03-02 13:34:55 -0800597 }
598
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800599 if (next_operation_num_ > 0)
600 UpdateOverallProgress(true, "Resuming after ");
601 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700602 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800603
604 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700605 // Check if we should cancel the current attempt for any reason.
606 // In this case, *error will have already been populated with the reason
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700607 // why we're canceling.
Alex Deymo542c19b2015-12-03 07:43:31 -0300608 if (download_delegate_ && download_delegate_->ShouldCancel(error))
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700609 return false;
610
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700611 // We know there are more operations to perform because we didn't reach the
612 // |num_total_operations_| limit yet.
613 while (next_operation_num_ >= acc_num_operations_[current_partition_]) {
614 CloseCurrentPartition();
615 current_partition_++;
616 if (!OpenCurrentPartition()) {
617 *error = ErrorCode::kInstallDeviceOpenError;
618 return false;
619 }
620 }
621 const size_t partition_operation_num = next_operation_num_ - (
622 current_partition_ ? acc_num_operations_[current_partition_ - 1] : 0);
623
Alex Deymoa12ee112015-08-12 22:19:32 -0700624 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700625 partitions_[current_partition_].operations(partition_operation_num);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800626
627 CopyDataToBuffer(&c_bytes, &count, op.data_length());
628
629 // Check whether we received all of the next operation's data payload.
630 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700631 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700632
Jay Srinivasanf4318702012-09-24 11:56:24 -0700633 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700634 // Otherwise, keep the old behavior. This serves as a knob to disable
635 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800636 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
637 // we would have already failed in ParsePayloadMetadata method and thus not
638 // even be here. So no need to handle that case again here.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800639 if (!payload_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700640 // Note: Validate must be called only if CanPerformInstallOperation is
641 // called. Otherwise, we might be failing operations before even if there
642 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800643 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700644 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800645 if (install_plan_->hash_checks_mandatory) {
646 LOG(ERROR) << "Mandatory operation hash check failed";
647 return false;
648 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700649
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800650 // For non-mandatory cases, just send a UMA stat.
651 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700652 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700653 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700654 }
655
Darin Petkov45580e42010-10-08 14:02:40 -0700656 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700657 ScopedTerminatorExitUnblocker exit_unblocker =
658 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800659
Lann Martin39f57142017-07-14 09:18:42 -0600660 base::TimeTicks op_start_time = base::TimeTicks::Now();
661
Gilad Arnoldfe133932014-01-14 12:25:50 -0800662 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700663 switch (op.type()) {
664 case InstallOperation::REPLACE:
665 case InstallOperation::REPLACE_BZ:
666 case InstallOperation::REPLACE_XZ:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700667 op_result = PerformReplaceOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600668 OP_DURATION_HISTOGRAM("REPLACE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700669 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700670 case InstallOperation::ZERO:
671 case InstallOperation::DISCARD:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700672 op_result = PerformZeroOrDiscardOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600673 OP_DURATION_HISTOGRAM("ZERO_OR_DISCARD", op_start_time);
Alex Deymo79715ad2015-10-02 14:27:53 -0700674 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700675 case InstallOperation::MOVE:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700676 op_result = PerformMoveOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600677 OP_DURATION_HISTOGRAM("MOVE", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700678 break;
679 case InstallOperation::BSDIFF:
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700680 op_result = PerformBsdiffOperation(op);
Lann Martin39f57142017-07-14 09:18:42 -0600681 OP_DURATION_HISTOGRAM("BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700682 break;
683 case InstallOperation::SOURCE_COPY:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700684 op_result = PerformSourceCopyOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600685 OP_DURATION_HISTOGRAM("SOURCE_COPY", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700686 break;
687 case InstallOperation::SOURCE_BSDIFF:
Amin Hassaniefa62d92017-11-09 13:46:56 -0800688 case InstallOperation::BROTLI_BSDIFF:
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700689 op_result = PerformSourceBsdiffOperation(op, error);
Lann Martin39f57142017-07-14 09:18:42 -0600690 OP_DURATION_HISTOGRAM("SOURCE_BSDIFF", op_start_time);
Alex Deymo2d621a32015-10-01 11:09:01 -0700691 break;
Amin Hassani49fdb092017-08-04 13:10:59 -0700692 case InstallOperation::PUFFDIFF:
Amin Hassani02855c22017-09-06 22:34:50 -0700693 op_result = PerformPuffDiffOperation(op, error);
694 OP_DURATION_HISTOGRAM("PUFFDIFF", op_start_time);
Sen Jiangbc3e6b02016-01-19 18:39:26 +0800695 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700696 default:
Alex Deymoeecb0a52017-05-19 15:15:08 -0700697 op_result = false;
Alex Deymo2d621a32015-10-01 11:09:01 -0700698 }
699 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800700 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800701
Amin Hassani5192fe52017-08-28 10:28:46 -0700702 if (!target_fd_->Flush()) {
703 return false;
704 }
705
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700706 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800707 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700708 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700709 }
Sen Jiangf6813802015-11-03 21:27:29 -0800710
711 // In major version 2, we don't add dummy operation to the payload.
Alex Deymof25eb492016-02-26 00:20:08 -0800712 // If we already extracted the signature we should skip this step.
Sen Jiangf6813802015-11-03 21:27:29 -0800713 if (major_payload_version_ == kBrilloMajorPayloadVersion &&
Alex Deymof25eb492016-02-26 00:20:08 -0800714 manifest_.has_signatures_offset() && manifest_.has_signatures_size() &&
715 signatures_message_data_.empty()) {
Sen Jiangf6813802015-11-03 21:27:29 -0800716 if (manifest_.signatures_offset() != buffer_offset_) {
717 LOG(ERROR) << "Payload signatures offset points to blob offset "
718 << manifest_.signatures_offset()
719 << " but signatures are expected at offset "
720 << buffer_offset_;
721 *error = ErrorCode::kDownloadPayloadVerificationError;
722 return false;
723 }
724 CopyDataToBuffer(&c_bytes, &count, manifest_.signatures_size());
725 // Needs more data to cover entire signature.
726 if (buffer_.size() < manifest_.signatures_size())
727 return true;
728 if (!ExtractSignatureMessage()) {
729 LOG(ERROR) << "Extract payload signature failed.";
730 *error = ErrorCode::kDownloadPayloadVerificationError;
731 return false;
732 }
733 DiscardBuffer(true, 0);
Alex Deymof25eb492016-02-26 00:20:08 -0800734 // Since we extracted the SignatureMessage we need to advance the
735 // checkpoint, otherwise we would reload the signature and try to extract
736 // it again.
737 CheckpointUpdateProgress();
Sen Jiangf6813802015-11-03 21:27:29 -0800738 }
739
Don Garrette410e0f2011-11-10 15:39:01 -0800740 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700741}
742
David Zeuthen8f191b22013-08-06 12:27:50 -0700743bool DeltaPerformer::IsManifestValid() {
744 return manifest_valid_;
745}
746
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700747bool DeltaPerformer::ParseManifestPartitions(ErrorCode* error) {
748 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
749 partitions_.clear();
750 for (const PartitionUpdate& partition : manifest_.partitions()) {
751 partitions_.push_back(partition);
752 }
753 manifest_.clear_partitions();
754 } else if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
755 LOG(INFO) << "Converting update information from old format.";
756 PartitionUpdate root_part;
757 root_part.set_partition_name(kLegacyPartitionNameRoot);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700758#ifdef __ANDROID__
759 LOG(WARNING) << "Legacy payload major version provided to an Android "
760 "build. Assuming no post-install. Please use major version "
761 "2 or newer.";
762 root_part.set_run_postinstall(false);
763#else
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700764 root_part.set_run_postinstall(true);
Alex Deymo5fa2c6d2015-10-15 17:31:23 -0700765#endif // __ANDROID__
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700766 if (manifest_.has_old_rootfs_info()) {
767 *root_part.mutable_old_partition_info() = manifest_.old_rootfs_info();
768 manifest_.clear_old_rootfs_info();
769 }
770 if (manifest_.has_new_rootfs_info()) {
771 *root_part.mutable_new_partition_info() = manifest_.new_rootfs_info();
772 manifest_.clear_new_rootfs_info();
773 }
774 *root_part.mutable_operations() = manifest_.install_operations();
775 manifest_.clear_install_operations();
776 partitions_.push_back(std::move(root_part));
777
778 PartitionUpdate kern_part;
779 kern_part.set_partition_name(kLegacyPartitionNameKernel);
780 kern_part.set_run_postinstall(false);
781 if (manifest_.has_old_kernel_info()) {
782 *kern_part.mutable_old_partition_info() = manifest_.old_kernel_info();
783 manifest_.clear_old_kernel_info();
784 }
785 if (manifest_.has_new_kernel_info()) {
786 *kern_part.mutable_new_partition_info() = manifest_.new_kernel_info();
787 manifest_.clear_new_kernel_info();
788 }
789 *kern_part.mutable_operations() = manifest_.kernel_install_operations();
790 manifest_.clear_kernel_install_operations();
791 partitions_.push_back(std::move(kern_part));
792 }
793
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700794 // Fill in the InstallPlan::partitions based on the partitions from the
795 // payload.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700796 for (const auto& partition : partitions_) {
797 InstallPlan::Partition install_part;
798 install_part.name = partition.partition_name();
799 install_part.run_postinstall =
800 partition.has_run_postinstall() && partition.run_postinstall();
Alex Deymo390efed2016-02-18 11:00:40 -0800801 if (install_part.run_postinstall) {
802 install_part.postinstall_path =
803 (partition.has_postinstall_path() ? partition.postinstall_path()
804 : kPostinstallDefaultScript);
805 install_part.filesystem_type = partition.filesystem_type();
Alex Deymo5b91c6b2016-08-04 20:33:36 -0700806 install_part.postinstall_optional = partition.postinstall_optional();
Alex Deymo390efed2016-02-18 11:00:40 -0800807 }
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700808
809 if (partition.has_old_partition_info()) {
810 const PartitionInfo& info = partition.old_partition_info();
811 install_part.source_size = info.size();
812 install_part.source_hash.assign(info.hash().begin(), info.hash().end());
813 }
814
815 if (!partition.has_new_partition_info()) {
816 LOG(ERROR) << "Unable to get new partition hash info on partition "
817 << install_part.name << ".";
818 *error = ErrorCode::kDownloadNewPartitionInfoError;
819 return false;
820 }
821 const PartitionInfo& info = partition.new_partition_info();
822 install_part.target_size = info.size();
823 install_part.target_hash.assign(info.hash().begin(), info.hash().end());
824
825 install_plan_->partitions.push_back(install_part);
826 }
827
Alex Deymo542c19b2015-12-03 07:43:31 -0300828 if (!install_plan_->LoadPartitionsFromSlots(boot_control_)) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700829 LOG(ERROR) << "Unable to determine all the partition devices.";
830 *error = ErrorCode::kInstallDeviceOpenError;
831 return false;
832 }
833 LogPartitionInfo(partitions_);
834 return true;
835}
836
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700837bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700838 const chromeos_update_engine::InstallOperation& operation) {
Alex Deymo0497d052016-03-23 09:16:59 -0700839 // If we don't have a data blob we can apply it right away.
840 if (!operation.has_data_offset() && !operation.has_data_length())
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700841 return true;
842
843 // See if we have the entire data blob in the buffer
844 if (operation.data_offset() < buffer_offset_) {
845 LOG(ERROR) << "we threw away data it seems?";
846 return false;
847 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700848
Gilad Arnoldfe133932014-01-14 12:25:50 -0800849 return (operation.data_offset() + operation.data_length() <=
850 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700851}
852
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700853bool DeltaPerformer::PerformReplaceOperation(
854 const InstallOperation& operation) {
Alex Deymoa12ee112015-08-12 22:19:32 -0700855 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700856 operation.type() == InstallOperation::REPLACE_BZ ||
857 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700858
859 // Since we delete data off the beginning of the buffer as we use it,
860 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700861 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
862 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700863
Darin Petkov437adc42010-10-07 13:12:24 -0700864 // Extract the signature message if it's in this operation.
Sen Jiangf6813802015-11-03 21:27:29 -0800865 if (ExtractSignatureMessageFromOperation(operation)) {
866 // If this is dummy replace operation, we ignore it after extracting the
867 // signature.
868 DiscardBuffer(true, 0);
869 return true;
870 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700871
Alex Deymo05322872015-09-30 09:50:24 -0700872 // Setup the ExtentWriter stack based on the operation type.
Ben Chanab5a0af2017-10-12 14:57:50 -0700873 std::unique_ptr<ExtentWriter> writer = std::make_unique<ZeroPadExtentWriter>(
874 std::make_unique<DirectExtentWriter>());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700875
Alex Deymo2d621a32015-10-01 11:09:01 -0700876 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700877 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700878 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
879 writer.reset(new XzExtentWriter(std::move(writer)));
880 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700881
Amin Hassanicd7edbe2017-09-18 17:05:02 -0700882 TEST_AND_RETURN_FALSE(
883 writer->Init(target_fd_, operation.dst_extents(), block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800884 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700885 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700886
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700887 // Update buffer
Sen Jiangf6813802015-11-03 21:27:29 -0800888 DiscardBuffer(true, buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700889 return true;
890}
891
Alex Deymo79715ad2015-10-02 14:27:53 -0700892bool DeltaPerformer::PerformZeroOrDiscardOperation(
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700893 const InstallOperation& operation) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700894 CHECK(operation.type() == InstallOperation::DISCARD ||
895 operation.type() == InstallOperation::ZERO);
896
897 // These operations have no blob.
898 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
899 TEST_AND_RETURN_FALSE(!operation.has_data_length());
900
Alex Deymo05e0e382015-12-07 20:18:16 -0800901#ifdef BLKZEROOUT
902 bool attempt_ioctl = true;
Alex Deymo79715ad2015-10-02 14:27:53 -0700903 int request =
904 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
Alex Deymo05e0e382015-12-07 20:18:16 -0800905#else // !defined(BLKZEROOUT)
906 bool attempt_ioctl = false;
907 int request = 0;
908#endif // !defined(BLKZEROOUT)
Alex Deymo79715ad2015-10-02 14:27:53 -0700909
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700910 brillo::Blob zeros;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700911 for (const Extent& extent : operation.dst_extents()) {
Alex Deymo79715ad2015-10-02 14:27:53 -0700912 const uint64_t start = extent.start_block() * block_size_;
913 const uint64_t length = extent.num_blocks() * block_size_;
914 if (attempt_ioctl) {
915 int result = 0;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700916 if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0)
Alex Deymo79715ad2015-10-02 14:27:53 -0700917 continue;
918 attempt_ioctl = false;
Alex Deymo79715ad2015-10-02 14:27:53 -0700919 }
920 // In case of failure, we fall back to writing 0 to the selected region.
Tianjie Xu06bbe492018-01-12 12:37:48 -0800921 zeros.resize(16 * block_size_);
Alex Deymo79715ad2015-10-02 14:27:53 -0700922 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700923 uint64_t chunk_length = min(length - offset,
924 static_cast<uint64_t>(zeros.size()));
Amin Hassanid87304c2017-08-29 11:40:03 -0700925 TEST_AND_RETURN_FALSE(utils::PWriteAll(
926 target_fd_, zeros.data(), chunk_length, start + offset));
Alex Deymo79715ad2015-10-02 14:27:53 -0700927 }
928 }
929 return true;
930}
931
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700932bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700933 // Calculate buffer size. Note, this function doesn't do a sliding
934 // window to copy in case the source and destination blocks overlap.
935 // If we wanted to do a sliding window, we could program the server
936 // to generate deltas that effectively did a sliding window.
937
938 uint64_t blocks_to_read = 0;
939 for (int i = 0; i < operation.src_extents_size(); i++)
940 blocks_to_read += operation.src_extents(i).num_blocks();
941
942 uint64_t blocks_to_write = 0;
943 for (int i = 0; i < operation.dst_extents_size(); i++)
944 blocks_to_write += operation.dst_extents(i).num_blocks();
945
946 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700947 brillo::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700948
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700949 // Read in bytes.
950 ssize_t bytes_read = 0;
951 for (int i = 0; i < operation.src_extents_size(); i++) {
952 ssize_t bytes_read_this_iteration = 0;
953 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200954 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700955 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700956 TEST_AND_RETURN_FALSE(utils::PReadAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -0700957 &buf[bytes_read],
958 bytes,
959 extent.start_block() * block_size_,
960 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700961 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200962 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700963 bytes_read += bytes_read_this_iteration;
964 }
965
966 // Write bytes out.
967 ssize_t bytes_written = 0;
968 for (int i = 0; i < operation.dst_extents_size(); i++) {
969 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200970 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700971 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700972 TEST_AND_RETURN_FALSE(utils::PWriteAll(target_fd_,
Allie Wood56873452015-03-27 17:48:40 -0700973 &buf[bytes_written],
974 bytes,
975 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200976 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700977 }
978 DCHECK_EQ(bytes_written, bytes_read);
979 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
980 return true;
981}
982
Allie Wood9f6f0a52015-03-30 11:25:47 -0700983namespace {
984
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800985// Compare |calculated_hash| with source hash in |operation|, return false and
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700986// dump hash and set |error| if don't match.
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +0100987// |source_fd| is the file descriptor of the source partition.
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800988bool ValidateSourceHash(const brillo::Blob& calculated_hash,
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700989 const InstallOperation& operation,
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +0100990 const FileDescriptorPtr source_fd,
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700991 ErrorCode* error) {
Sen Jiang2ec4aab2015-11-13 15:04:03 -0800992 brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
993 operation.src_sha256_hash().end());
994 if (calculated_hash != expected_source_hash) {
Alex Deymo67140842016-06-15 13:28:59 -0700995 LOG(ERROR) << "The hash of the source data on disk for this operation "
996 << "doesn't match the expected value. This could mean that the "
997 << "delta update payload was targeted for another version, or "
998 << "that the source partition was modified after it was "
999 << "installed, for example, by mounting a filesystem.";
1000 LOG(ERROR) << "Expected: sha256|hex = "
1001 << base::HexEncode(expected_source_hash.data(),
1002 expected_source_hash.size());
1003 LOG(ERROR) << "Calculated: sha256|hex = "
1004 << base::HexEncode(calculated_hash.data(),
1005 calculated_hash.size());
1006
1007 vector<string> source_extents;
1008 for (const Extent& ext : operation.src_extents()) {
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001009 source_extents.push_back(
1010 base::StringPrintf("%" PRIu64 ":%" PRIu64,
1011 static_cast<uint64_t>(ext.start_block()),
1012 static_cast<uint64_t>(ext.num_blocks())));
Alex Deymo67140842016-06-15 13:28:59 -07001013 }
1014 LOG(ERROR) << "Operation source (offset:size) in blocks: "
1015 << base::JoinString(source_extents, ",");
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001016
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001017 // Log remount history if this device is an ext4 partition.
1018 LogMountHistory(source_fd);
1019
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001020 *error = ErrorCode::kDownloadStateInitializationError;
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001021 return false;
1022 }
1023 return true;
1024}
1025
Allie Wood9f6f0a52015-03-30 11:25:47 -07001026} // namespace
1027
1028bool DeltaPerformer::PerformSourceCopyOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001029 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001030 if (operation.has_src_length())
1031 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1032 if (operation.has_dst_length())
1033 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1034
Alex Deymoa48f6302016-11-04 15:49:53 -07001035 brillo::Blob source_hash;
1036 TEST_AND_RETURN_FALSE(fd_utils::CopyAndHashExtents(source_fd_,
1037 operation.src_extents(),
1038 target_fd_,
1039 operation.dst_extents(),
1040 block_size_,
1041 &source_hash));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001042
1043 if (operation.has_src_sha256_hash()) {
HÃ¥kan Kvist4e13cf42018-01-23 12:57:55 +01001044 TEST_AND_RETURN_FALSE(
1045 ValidateSourceHash(source_hash, operation, source_fd_, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001046 }
1047
Allie Wood9f6f0a52015-03-30 11:25:47 -07001048 return true;
1049}
1050
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001051bool DeltaPerformer::ExtentsToBsdiffPositionsString(
1052 const RepeatedPtrField<Extent>& extents,
1053 uint64_t block_size,
1054 uint64_t full_length,
1055 string* positions_string) {
1056 string ret;
1057 uint64_t length = 0;
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001058 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001059 int64_t start = extent.start_block() * block_size;
Tamas Berghammer9d66d762016-07-15 14:19:04 +01001060 uint64_t this_length =
1061 min(full_length - length,
1062 static_cast<uint64_t>(extent.num_blocks()) * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001063 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001064 length += this_length;
1065 }
1066 TEST_AND_RETURN_FALSE(length == full_length);
1067 if (!ret.empty())
1068 ret.resize(ret.size() - 1); // Strip trailing comma off
1069 *positions_string = ret;
1070 return true;
1071}
1072
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001073bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001074 // Since we delete data off the beginning of the buffer as we use it,
1075 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -07001076 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1077 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001078
1079 string input_positions;
1080 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1081 block_size_,
1082 operation.src_length(),
1083 &input_positions));
1084 string output_positions;
1085 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1086 block_size_,
1087 operation.dst_length(),
1088 &output_positions));
1089
Sen Jiang7a659092016-05-10 15:31:46 -07001090 TEST_AND_RETURN_FALSE(bsdiff::bspatch(target_path_.c_str(),
1091 target_path_.c_str(),
1092 buffer_.data(),
1093 buffer_.size(),
1094 input_positions.c_str(),
1095 output_positions.c_str()) == 0);
Sen Jiangf6813802015-11-03 21:27:29 -08001096 DiscardBuffer(true, buffer_.size());
Darin Petkov7f2ec752013-04-03 14:45:19 +02001097
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001098 if (operation.dst_length() % block_size_) {
1099 // Zero out rest of final block.
1100 // TODO(adlr): build this into bspatch; it's more efficient that way.
1101 const Extent& last_extent =
1102 operation.dst_extents(operation.dst_extents_size() - 1);
1103 const uint64_t end_byte =
1104 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
1105 const uint64_t begin_byte =
1106 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001107 brillo::Blob zeros(end_byte - begin_byte);
Amin Hassanid87304c2017-08-29 11:40:03 -07001108 TEST_AND_RETURN_FALSE(utils::PWriteAll(
1109 target_fd_, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001110 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001111 return true;
1112}
1113
Amin Hassanid9cb2902017-09-20 12:11:39 -07001114namespace {
1115
1116class BsdiffExtentFile : public bsdiff::FileInterface {
1117 public:
1118 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader, size_t size)
1119 : BsdiffExtentFile(std::move(reader), nullptr, size) {}
1120 BsdiffExtentFile(std::unique_ptr<ExtentWriter> writer, size_t size)
1121 : BsdiffExtentFile(nullptr, std::move(writer), size) {}
1122
1123 ~BsdiffExtentFile() override = default;
1124
1125 bool Read(void* buf, size_t count, size_t* bytes_read) override {
1126 TEST_AND_RETURN_FALSE(reader_->Read(buf, count));
1127 *bytes_read = count;
1128 offset_ += count;
1129 return true;
1130 }
1131
1132 bool Write(const void* buf, size_t count, size_t* bytes_written) override {
1133 TEST_AND_RETURN_FALSE(writer_->Write(buf, count));
1134 *bytes_written = count;
1135 offset_ += count;
1136 return true;
1137 }
1138
1139 bool Seek(off_t pos) override {
1140 if (reader_ != nullptr) {
1141 TEST_AND_RETURN_FALSE(reader_->Seek(pos));
1142 offset_ = pos;
1143 } else {
1144 // For writes technically there should be no change of position, or it
1145 // should be equivalent of current offset.
1146 TEST_AND_RETURN_FALSE(offset_ == static_cast<uint64_t>(pos));
1147 }
1148 return true;
1149 }
1150
1151 bool Close() override {
1152 if (writer_ != nullptr) {
1153 TEST_AND_RETURN_FALSE(writer_->End());
1154 }
1155 return true;
1156 }
1157
1158 bool GetSize(uint64_t* size) override {
1159 *size = size_;
1160 return true;
1161 }
1162
1163 private:
1164 BsdiffExtentFile(std::unique_ptr<ExtentReader> reader,
1165 std::unique_ptr<ExtentWriter> writer,
1166 size_t size)
1167 : reader_(std::move(reader)),
1168 writer_(std::move(writer)),
1169 size_(size),
1170 offset_(0) {}
1171
1172 std::unique_ptr<ExtentReader> reader_;
1173 std::unique_ptr<ExtentWriter> writer_;
1174 uint64_t size_;
1175 uint64_t offset_;
1176
1177 DISALLOW_COPY_AND_ASSIGN(BsdiffExtentFile);
1178};
1179
1180} // namespace
1181
Allie Wood9f6f0a52015-03-30 11:25:47 -07001182bool DeltaPerformer::PerformSourceBsdiffOperation(
Sen Jiangbe2c47b2016-06-15 14:09:27 -07001183 const InstallOperation& operation, ErrorCode* error) {
Allie Wood9f6f0a52015-03-30 11:25:47 -07001184 // Since we delete data off the beginning of the buffer as we use it,
1185 // the data we need should be exactly at the beginning of the buffer.
1186 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1187 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1188 if (operation.has_src_length())
1189 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1190 if (operation.has_dst_length())
1191 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1192
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001193 if (operation.has_src_sha256_hash()) {
Amin Hassanib379d192017-12-06 15:31:17 -08001194 brillo::Blob source_hash;
1195 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
1196 source_fd_, operation.src_extents(), block_size_, &source_hash));
1197 TEST_AND_RETURN_FALSE(
1198 ValidateSourceHash(source_hash, operation, source_fd_, error));
Sen Jiang2ec4aab2015-11-13 15:04:03 -08001199 }
1200
Amin Hassanid9cb2902017-09-20 12:11:39 -07001201 auto reader = std::make_unique<DirectExtentReader>();
1202 TEST_AND_RETURN_FALSE(
1203 reader->Init(source_fd_, operation.src_extents(), block_size_));
1204 auto src_file = std::make_unique<BsdiffExtentFile>(
1205 std::move(reader),
1206 utils::BlocksInExtents(operation.src_extents()) * block_size_);
Allie Wood9f6f0a52015-03-30 11:25:47 -07001207
Amin Hassanid9cb2902017-09-20 12:11:39 -07001208 auto writer = std::make_unique<DirectExtentWriter>();
1209 TEST_AND_RETURN_FALSE(
1210 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1211 auto dst_file = std::make_unique<BsdiffExtentFile>(
1212 std::move(writer),
1213 utils::BlocksInExtents(operation.dst_extents()) * block_size_);
1214
1215 TEST_AND_RETURN_FALSE(bsdiff::bspatch(std::move(src_file),
1216 std::move(dst_file),
Sen Jiang7a659092016-05-10 15:31:46 -07001217 buffer_.data(),
Amin Hassanid9cb2902017-09-20 12:11:39 -07001218 buffer_.size()) == 0);
Sen Jiangbc3e6b02016-01-19 18:39:26 +08001219 DiscardBuffer(true, buffer_.size());
1220 return true;
1221}
1222
Amin Hassani02855c22017-09-06 22:34:50 -07001223namespace {
1224
1225// A class to be passed to |puffpatch| for reading from |source_fd_| and writing
1226// into |target_fd_|.
1227class PuffinExtentStream : public puffin::StreamInterface {
1228 public:
1229 // Constructor for creating a stream for reading from an |ExtentReader|.
1230 PuffinExtentStream(std::unique_ptr<ExtentReader> reader, size_t size)
1231 : PuffinExtentStream(std::move(reader), nullptr, size) {}
1232
1233 // Constructor for creating a stream for writing to an |ExtentWriter|.
1234 PuffinExtentStream(std::unique_ptr<ExtentWriter> writer, size_t size)
1235 : PuffinExtentStream(nullptr, std::move(writer), size) {}
1236
1237 ~PuffinExtentStream() override = default;
1238
1239 bool GetSize(size_t* size) const override {
1240 *size = size_;
1241 return true;
1242 }
1243
1244 bool GetOffset(size_t* offset) const override {
1245 *offset = offset_;
1246 return true;
1247 }
1248
1249 bool Seek(size_t offset) override {
1250 if (is_read_) {
1251 TEST_AND_RETURN_FALSE(reader_->Seek(offset));
1252 offset_ = offset;
1253 } else {
1254 // For writes technically there should be no change of position, or it
1255 // should equivalent of current offset.
1256 TEST_AND_RETURN_FALSE(offset_ == offset);
1257 }
1258 return true;
1259 }
1260
1261 bool Read(void* buffer, size_t count) override {
1262 TEST_AND_RETURN_FALSE(is_read_);
1263 TEST_AND_RETURN_FALSE(reader_->Read(buffer, count));
1264 offset_ += count;
1265 return true;
1266 }
1267
1268 bool Write(const void* buffer, size_t count) override {
1269 TEST_AND_RETURN_FALSE(!is_read_);
1270 TEST_AND_RETURN_FALSE(writer_->Write(buffer, count));
1271 offset_ += count;
1272 return true;
1273 }
1274
1275 bool Close() override {
1276 if (!is_read_) {
1277 TEST_AND_RETURN_FALSE(writer_->End());
1278 }
1279 return true;
1280 }
1281
1282 private:
1283 PuffinExtentStream(std::unique_ptr<ExtentReader> reader,
1284 std::unique_ptr<ExtentWriter> writer,
1285 size_t size)
1286 : reader_(std::move(reader)),
1287 writer_(std::move(writer)),
1288 size_(size),
1289 offset_(0),
1290 is_read_(reader_ ? true : false) {}
1291
1292 std::unique_ptr<ExtentReader> reader_;
1293 std::unique_ptr<ExtentWriter> writer_;
1294 uint64_t size_;
1295 uint64_t offset_;
1296 bool is_read_;
1297
1298 DISALLOW_COPY_AND_ASSIGN(PuffinExtentStream);
1299};
1300
1301} // namespace
1302
1303bool DeltaPerformer::PerformPuffDiffOperation(const InstallOperation& operation,
1304 ErrorCode* error) {
1305 // Since we delete data off the beginning of the buffer as we use it,
1306 // the data we need should be exactly at the beginning of the buffer.
1307 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1308 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1309
1310 if (operation.has_src_sha256_hash()) {
Amin Hassanib379d192017-12-06 15:31:17 -08001311 brillo::Blob source_hash;
1312 TEST_AND_RETURN_FALSE(fd_utils::ReadAndHashExtents(
1313 source_fd_, operation.src_extents(), block_size_, &source_hash));
1314 TEST_AND_RETURN_FALSE(
1315 ValidateSourceHash(source_hash, operation, source_fd_, error));
Amin Hassani02855c22017-09-06 22:34:50 -07001316 }
1317
1318 auto reader = std::make_unique<DirectExtentReader>();
1319 TEST_AND_RETURN_FALSE(
1320 reader->Init(source_fd_, operation.src_extents(), block_size_));
1321 puffin::UniqueStreamPtr src_stream(new PuffinExtentStream(
1322 std::move(reader),
1323 utils::BlocksInExtents(operation.src_extents()) * block_size_));
1324
1325 auto writer = std::make_unique<DirectExtentWriter>();
1326 TEST_AND_RETURN_FALSE(
1327 writer->Init(target_fd_, operation.dst_extents(), block_size_));
1328 puffin::UniqueStreamPtr dst_stream(new PuffinExtentStream(
1329 std::move(writer),
1330 utils::BlocksInExtents(operation.dst_extents()) * block_size_));
1331
1332 const size_t kMaxCacheSize = 5 * 1024 * 1024; // Total 5MB cache.
1333 TEST_AND_RETURN_FALSE(puffin::PuffPatch(std::move(src_stream),
1334 std::move(dst_stream),
1335 buffer_.data(),
1336 buffer_.size(),
1337 kMaxCacheSize));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001338 DiscardBuffer(true, buffer_.size());
Alex Deymoa12ee112015-08-12 22:19:32 -07001339 return true;
1340}
Darin Petkovd7061ab2010-10-06 14:37:09 -07001341
Darin Petkovd7061ab2010-10-06 14:37:09 -07001342bool DeltaPerformer::ExtractSignatureMessageFromOperation(
1343 const InstallOperation& operation) {
1344 if (operation.type() != InstallOperation::REPLACE ||
1345 !manifest_.has_signatures_offset() ||
1346 manifest_.signatures_offset() != operation.data_offset()) {
1347 return false;
1348 }
1349 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1350 manifest_.signatures_size() == operation.data_length());
Sen Jiangf6813802015-11-03 21:27:29 -08001351 TEST_AND_RETURN_FALSE(ExtractSignatureMessage());
1352 return true;
1353}
1354
1355bool DeltaPerformer::ExtractSignatureMessage() {
Darin Petkovd7061ab2010-10-06 14:37:09 -07001356 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1357 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1358 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001359 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001360 buffer_.begin(),
1361 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001362
1363 // Save the signature blob because if the update is interrupted after the
1364 // download phase we don't go through this path anymore. Some alternatives to
1365 // consider:
1366 //
1367 // 1. On resume, re-download the signature blob from the server and re-verify
1368 // it.
1369 //
1370 // 2. Verify the signature as soon as it's received and don't checkpoint the
1371 // blob and the signed sha-256 context.
1372 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001373 string(signatures_message_data_.begin(),
1374 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001375 << "Unable to store the signature blob.";
Sen Jiangf6813802015-11-03 21:27:29 -08001376
Darin Petkovd7061ab2010-10-06 14:37:09 -07001377 LOG(INFO) << "Extracted signature data of size "
1378 << manifest_.signatures_size() << " at "
1379 << manifest_.signatures_offset();
1380 return true;
1381}
1382
David Zeuthene7f89172013-10-31 10:21:04 -07001383bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
Alex Deymo542c19b2015-12-03 07:43:31 -03001384 if (hardware_->IsOfficialBuild() ||
David Zeuthene7f89172013-10-31 10:21:04 -07001385 utils::FileExists(public_key_path_.c_str()) ||
1386 install_plan_->public_key_rsa.empty())
1387 return false;
1388
1389 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1390 out_tmp_key))
1391 return false;
1392
1393 return true;
1394}
1395
Gilad Arnold21504f02013-05-24 08:51:22 -07001396ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001397 // Perform assorted checks to sanity check the manifest, make sure it
1398 // matches data from other sources, and that it is a supported version.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001399
Alex Deymo64d98782016-02-05 18:03:48 -08001400 bool has_old_fields =
1401 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info());
1402 for (const PartitionUpdate& partition : manifest_.partitions()) {
1403 has_old_fields = has_old_fields || partition.has_old_partition_info();
1404 }
Sen Jiangc8f6b7a2015-10-21 11:09:59 -07001405
Alex Deymo64d98782016-02-05 18:03:48 -08001406 // The presence of an old partition hash is the sole indicator for a delta
1407 // update.
1408 InstallPayloadType actual_payload_type =
1409 has_old_fields ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
1410
Sen Jiangcdd52062017-05-18 15:33:10 -07001411 if (payload_->type == InstallPayloadType::kUnknown) {
Alex Deymo64d98782016-02-05 18:03:48 -08001412 LOG(INFO) << "Detected a '"
1413 << InstallPayloadTypeToString(actual_payload_type)
1414 << "' payload.";
Sen Jiangcdd52062017-05-18 15:33:10 -07001415 payload_->type = actual_payload_type;
1416 } else if (payload_->type != actual_payload_type) {
Alex Deymo64d98782016-02-05 18:03:48 -08001417 LOG(ERROR) << "InstallPlan expected a '"
Sen Jiangcdd52062017-05-18 15:33:10 -07001418 << InstallPayloadTypeToString(payload_->type)
Alex Deymo64d98782016-02-05 18:03:48 -08001419 << "' payload but the downloaded manifest contains a '"
1420 << InstallPayloadTypeToString(actual_payload_type)
1421 << "' payload.";
1422 return ErrorCode::kPayloadMismatchedType;
1423 }
1424
1425 // Check that the minor version is compatible.
1426 if (actual_payload_type == InstallPayloadType::kFull) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001427 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1428 LOG(ERROR) << "Manifest contains minor version "
1429 << manifest_.minor_version()
1430 << ", but all full payloads should have version "
1431 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001432 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001433 }
1434 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001435 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001436 LOG(ERROR) << "Manifest contains minor version "
1437 << manifest_.minor_version()
1438 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001439 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001440 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001441 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001442 }
1443
Sen Jiang3e728fe2015-11-05 11:37:23 -08001444 if (major_payload_version_ != kChromeOSMajorPayloadVersion) {
1445 if (manifest_.has_old_rootfs_info() ||
1446 manifest_.has_new_rootfs_info() ||
1447 manifest_.has_old_kernel_info() ||
1448 manifest_.has_new_kernel_info() ||
1449 manifest_.install_operations_size() != 0 ||
1450 manifest_.kernel_install_operations_size() != 0) {
1451 LOG(ERROR) << "Manifest contains deprecated field only supported in "
1452 << "major payload version 1, but the payload major version is "
1453 << major_payload_version_;
1454 return ErrorCode::kPayloadMismatchedType;
1455 }
1456 }
1457
Sen Jiang8e768e92017-06-28 17:13:19 -07001458 if (manifest_.max_timestamp() < hardware_->GetBuildTimestamp()) {
1459 LOG(ERROR) << "The current OS build timestamp ("
1460 << hardware_->GetBuildTimestamp()
1461 << ") is newer than the maximum timestamp in the manifest ("
1462 << manifest_.max_timestamp() << ")";
1463 return ErrorCode::kPayloadTimestampError;
1464 }
1465
Gilad Arnold21504f02013-05-24 08:51:22 -07001466 // TODO(garnold) we should be adding more and more manifest checks, such as
1467 // partition boundaries etc (see chromium-os:37661).
1468
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001469 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001470}
1471
David Zeuthena99981f2013-04-29 13:42:47 -07001472ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001473 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001474 if (!operation.data_sha256_hash().size()) {
1475 if (!operation.data_length()) {
1476 // Operations that do not have any data blob won't have any operation hash
1477 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001478 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001479 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001480 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001481 }
1482
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001483 // No hash is present for an operation that has data blobs. This shouldn't
1484 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001485 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001486 // hashes. So if it happens it means either we've turned operation hash
1487 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001488 // One caveat though: The last operation is a dummy signature operation
1489 // that doesn't have a hash at the time the manifest is created. So we
1490 // should not complaint about that operation. This operation can be
1491 // recognized by the fact that it's offset is mentioned in the manifest.
1492 if (manifest_.signatures_offset() &&
1493 manifest_.signatures_offset() == operation.data_offset()) {
1494 LOG(INFO) << "Skipping hash verification for signature operation "
1495 << next_operation_num_ + 1;
1496 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001497 if (install_plan_->hash_checks_mandatory) {
1498 LOG(ERROR) << "Missing mandatory operation hash for operation "
1499 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001500 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001501 }
1502
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001503 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1504 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001505 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001506 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001507 }
1508
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001509 brillo::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001510 expected_op_hash.assign(operation.data_sha256_hash().data(),
1511 (operation.data_sha256_hash().data() +
1512 operation.data_sha256_hash().size()));
1513
Sen Jiang2703ef42017-03-16 13:36:21 -07001514 brillo::Blob calculated_op_hash;
1515 if (!HashCalculator::RawHashOfBytes(
1516 buffer_.data(), operation.data_length(), &calculated_op_hash)) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001517 LOG(ERROR) << "Unable to compute actual hash of operation "
1518 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001519 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001520 }
1521
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001522 if (calculated_op_hash != expected_op_hash) {
1523 LOG(ERROR) << "Hash verification failed for operation "
1524 << next_operation_num_ << ". Expected hash = ";
1525 utils::HexDumpVector(expected_op_hash);
1526 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1527 << " bytes at offset: " << operation.data_offset() << " = ";
1528 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001529 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001530 }
1531
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001532 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001533}
1534
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001535#define TEST_AND_RETURN_VAL(_retval, _condition) \
1536 do { \
1537 if (!(_condition)) { \
1538 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1539 return _retval; \
1540 } \
1541 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001542
David Zeuthena99981f2013-04-29 13:42:47 -07001543ErrorCode DeltaPerformer::VerifyPayload(
Sen Jiang2703ef42017-03-16 13:36:21 -07001544 const brillo::Blob& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001545 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001546
1547 // See if we should use the public RSA key in the Omaha response.
1548 base::FilePath path_to_public_key(public_key_path_);
1549 base::FilePath tmp_key;
1550 if (GetPublicKeyFromResponse(&tmp_key))
1551 path_to_public_key = tmp_key;
1552 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1553 if (tmp_key.empty())
1554 tmp_key_remover.set_should_remove(false);
1555
1556 LOG(INFO) << "Verifying payload using public key: "
1557 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001558
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001559 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001560 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001561 update_check_response_size ==
Sen Jiang76bfa742015-10-12 17:13:26 -07001562 metadata_size_ + metadata_signature_size_ +
1563 buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001564
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001565 // Verifies the payload hash.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001566 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Sen Jiang2703ef42017-03-16 13:36:21 -07001567 !payload_hash_calculator_.raw_hash().empty());
1568 TEST_AND_RETURN_VAL(
1569 ErrorCode::kPayloadHashMismatchError,
1570 payload_hash_calculator_.raw_hash() == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001571
Darin Petkov437adc42010-10-07 13:12:24 -07001572 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001573 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001574 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001575 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001576 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001577 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001578 !signatures_message_data_.empty());
Sen Jiangf6813802015-11-03 21:27:29 -08001579 brillo::Blob hash_data = signed_hash_calculator_.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001580 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1581 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001582 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001583 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001584
1585 if (!PayloadVerifier::VerifySignature(
1586 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001587 // The autoupdate_CatchBadSignatures test checks for this string
1588 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001589 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001590 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001591 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001592
David Zeuthene7f89172013-10-31 10:21:04 -07001593 LOG(INFO) << "Payload hash matches value in payload.";
1594
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001595 // At this point, we are guaranteed to have downloaded a full payload, i.e
1596 // the one whose size matches the size mentioned in Omaha response. If any
1597 // errors happen after this, it's likely a problem with the payload itself or
1598 // the state of the system and not a problem with the URL or network. So,
Alex Deymo542c19b2015-12-03 07:43:31 -03001599 // indicate that to the download delegate so that AU can backoff
1600 // appropriately.
1601 if (download_delegate_)
1602 download_delegate_->DownloadComplete();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001603
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001604 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001605}
1606
Sen Jiangf6813802015-11-03 21:27:29 -08001607void DeltaPerformer::DiscardBuffer(bool do_advance_offset,
1608 size_t signed_hash_buffer_size) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001609 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001610 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001611 buffer_offset_ += buffer_.size();
1612
1613 // Hash the content.
Sen Jiangf6813802015-11-03 21:27:29 -08001614 payload_hash_calculator_.Update(buffer_.data(), buffer_.size());
1615 signed_hash_calculator_.Update(buffer_.data(), signed_hash_buffer_size);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001616
1617 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001618 brillo::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001619}
1620
Darin Petkov0406e402010-10-06 21:33:11 -07001621bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -07001622 const string& update_check_response_hash) {
Darin Petkov0406e402010-10-06 21:33:11 -07001623 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001624 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1625 next_operation != kUpdateStateOperationInvalid &&
1626 next_operation > 0))
1627 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001628
1629 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001630 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1631 !interrupted_hash.empty() &&
1632 interrupted_hash == update_check_response_hash))
1633 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001634
Darin Petkov61426142010-10-08 11:04:55 -07001635 int64_t resumed_update_failures;
Alex Deymof25eb492016-02-26 00:20:08 -08001636 // Note that storing this value is optional, but if it is there it should not
1637 // be more than the limit.
1638 if (prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures) &&
1639 resumed_update_failures > kMaxResumedUpdateFailures)
Alex Deymo3310b222015-03-30 15:59:07 -07001640 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001641
Darin Petkov0406e402010-10-06 21:33:11 -07001642 // Sanity check the rest.
1643 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001644 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1645 next_data_offset >= 0))
1646 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001647
Darin Petkov437adc42010-10-07 13:12:24 -07001648 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001649 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1650 !sha256_context.empty()))
1651 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001652
1653 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001654 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1655 manifest_metadata_size > 0))
1656 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001657
Alex Deymof25eb492016-02-26 00:20:08 -08001658 int64_t manifest_signature_size = 0;
1659 if (!(prefs->GetInt64(kPrefsManifestSignatureSize,
1660 &manifest_signature_size) &&
1661 manifest_signature_size >= 0))
1662 return false;
1663
Darin Petkov0406e402010-10-06 21:33:11 -07001664 return true;
1665}
1666
Darin Petkov9b230572010-10-08 10:20:09 -07001667bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001668 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1669 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001670 if (!quick) {
Darin Petkov9b230572010-10-08 10:20:09 -07001671 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001672 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001673 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1674 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001675 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001676 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Alex Deymof25eb492016-02-26 00:20:08 -08001677 prefs->SetInt64(kPrefsManifestSignatureSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001678 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Sen Jiangfe522822017-10-31 15:14:11 -07001679 prefs->Delete(kPrefsPostInstallSucceeded);
Darin Petkov9b230572010-10-08 10:20:09 -07001680 }
Darin Petkov73058b42010-10-06 16:32:19 -07001681 return true;
1682}
1683
1684bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001685 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001686 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001687 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001688 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001689 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001690 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Sen Jiangf6813802015-11-03 21:27:29 -08001691 payload_hash_calculator_.GetContext()));
1692 TEST_AND_RETURN_FALSE(
1693 prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1694 signed_hash_calculator_.GetContext()));
Darin Petkov0406e402010-10-06 21:33:11 -07001695 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1696 buffer_offset_));
1697 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001698
1699 if (next_operation_num_ < num_total_operations_) {
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001700 size_t partition_index = current_partition_;
1701 while (next_operation_num_ >= acc_num_operations_[partition_index])
1702 partition_index++;
1703 const size_t partition_operation_num = next_operation_num_ - (
1704 partition_index ? acc_num_operations_[partition_index - 1] : 0);
Alex Deymoa12ee112015-08-12 22:19:32 -07001705 const InstallOperation& op =
Alex Deymoe5e5fe92015-10-05 09:28:19 -07001706 partitions_[partition_index].operations(partition_operation_num);
David Zeuthen41996ad2013-09-24 15:43:24 -07001707 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1708 op.data_length()));
1709 } else {
1710 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1711 0));
1712 }
Darin Petkov0406e402010-10-06 21:33:11 -07001713 }
Darin Petkov73058b42010-10-06 16:32:19 -07001714 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1715 next_operation_num_));
1716 return true;
1717}
1718
Darin Petkov9b230572010-10-08 10:20:09 -07001719bool DeltaPerformer::PrimeUpdateState() {
1720 CHECK(manifest_valid_);
1721 block_size_ = manifest_.block_size();
1722
1723 int64_t next_operation = kUpdateStateOperationInvalid;
1724 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1725 next_operation == kUpdateStateOperationInvalid ||
1726 next_operation <= 0) {
1727 // Initiating a new update, no more state needs to be initialized.
1728 return true;
1729 }
1730 next_operation_num_ = next_operation;
1731
1732 // Resuming an update -- load the rest of the update state.
1733 int64_t next_data_offset = -1;
1734 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1735 &next_data_offset) &&
1736 next_data_offset >= 0);
1737 buffer_offset_ = next_data_offset;
1738
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001739 // The signed hash context and the signature blob may be empty if the
1740 // interrupted update didn't reach the signature.
Sen Jiangf6813802015-11-03 21:27:29 -08001741 string signed_hash_context;
1742 if (prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1743 &signed_hash_context)) {
1744 TEST_AND_RETURN_FALSE(
1745 signed_hash_calculator_.SetContext(signed_hash_context));
1746 }
1747
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001748 string signature_blob;
1749 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1750 signatures_message_data_.assign(signature_blob.begin(),
1751 signature_blob.end());
1752 }
Darin Petkov9b230572010-10-08 10:20:09 -07001753
1754 string hash_context;
1755 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1756 &hash_context) &&
Sen Jiangf6813802015-11-03 21:27:29 -08001757 payload_hash_calculator_.SetContext(hash_context));
Darin Petkov9b230572010-10-08 10:20:09 -07001758
1759 int64_t manifest_metadata_size = 0;
1760 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1761 &manifest_metadata_size) &&
1762 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001763 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001764
Alex Deymof25eb492016-02-26 00:20:08 -08001765 int64_t manifest_signature_size = 0;
1766 TEST_AND_RETURN_FALSE(
1767 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size) &&
1768 manifest_signature_size >= 0);
1769 metadata_signature_size_ = manifest_signature_size;
1770
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001771 // Advance the download progress to reflect what doesn't need to be
1772 // re-downloaded.
1773 total_bytes_received_ += buffer_offset_;
1774
Darin Petkov61426142010-10-08 11:04:55 -07001775 // Speculatively count the resume as a failure.
1776 int64_t resumed_update_failures;
1777 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1778 resumed_update_failures++;
1779 } else {
1780 resumed_update_failures = 1;
1781 }
1782 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001783 return true;
1784}
1785
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001786} // namespace chromeos_update_engine