blob: 8aff6349aae7a86b0d9daa74e36f74efd6400fa2 [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
17#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <endian.h>
20#include <errno.h>
Alex Deymo79715ad2015-10-02 14:27:53 -070021#include <linux/fs.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070022
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include <algorithm>
24#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include <string>
27#include <vector>
28
Ben Chan06c76a42014-09-05 08:21:06 -070029#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070030#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_util.h>
32#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080033#include <chromeos/data_encoding.h>
Alex Deymo05322872015-09-30 09:50:24 -070034#include <chromeos/make_unique_ptr.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035#include <google/protobuf/repeated_field.h>
36
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070037#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070038#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070039#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070040#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080041#if USE_MTD
42#include "update_engine/mtd_file_descriptor.h"
43#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070044#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080045#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070046#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070047#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070048#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070049#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070050#include "update_engine/update_attempter.h"
Alex Deymo2d621a32015-10-01 11:09:01 -070051#include "update_engine/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052
Alex Deymo161c4a12014-05-16 15:56:21 -070053using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070054using std::min;
55using std::string;
56using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070057
58namespace chromeos_update_engine {
59
Sen Jiangb8060e42015-09-24 17:30:50 -070060const uint64_t DeltaPerformer::kDeltaVersionOffset = sizeof(kDeltaMagic);
Jay Srinivasanf4318702012-09-24 11:56:24 -070061const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070062const uint64_t DeltaPerformer::kDeltaManifestSizeOffset =
63 kDeltaVersionOffset + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -070064const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070065const uint64_t DeltaPerformer::kDeltaMetadataSignatureSizeSize = 4;
66const uint64_t DeltaPerformer::kMaxPayloadHeaderSize = 24;
Don Garrett4d039442013-10-28 18:40:06 -070067const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Allie Wood6eeec902015-04-15 10:40:52 -070068const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 2;
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
82FileDescriptorPtr CreateFileDescriptor(const char* path) {
83 FileDescriptorPtr ret;
84#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080085 if (strstr(path, "/dev/ubi") == path) {
86 if (!UbiFileDescriptor::IsUbi(path)) {
87 // The volume might not have been attached at boot time.
88 int volume_no;
89 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
90 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
91 }
92 }
93 if (UbiFileDescriptor::IsUbi(path)) {
94 LOG(INFO) << path << " is a UBI device.";
95 ret.reset(new UbiFileDescriptor);
96 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080097 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080098 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080099 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800100 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800101 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800102#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800104#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700105 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800106#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800107 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700108}
109
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800110// Opens path for read/write. On success returns an open FileDescriptor
111// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
112FileDescriptorPtr OpenFile(const char* path, int* err) {
113 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800114 int mode = O_RDWR;
115#if USE_MTD
116 // On NAND devices, we can either read, or write, but not both. So here we
117 // use O_WRONLY.
118 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
119 mode = O_WRONLY;
120 }
121#endif
122 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800123 *err = errno;
124 PLOG(ERROR) << "Unable to open file " << path;
125 return nullptr;
126 }
127 *err = 0;
128 return fd;
129}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700130} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700131
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800132
133// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
134// arithmetic.
135static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
136 return part * norm / total;
137}
138
139void DeltaPerformer::LogProgress(const char* message_prefix) {
140 // Format operations total count and percentage.
141 string total_operations_str("?");
142 string completed_percentage_str("");
143 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700144 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800145 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
146 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700147 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700148 IntRatio(next_operation_num_, num_total_operations_,
149 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800150 }
151
152 // Format download total count and percentage.
153 size_t payload_size = install_plan_->payload_size;
154 string payload_size_str("?");
155 string downloaded_percentage_str("");
156 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700157 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800158 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
159 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700160 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700161 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800162 }
163
164 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
165 << "/" << total_operations_str << " operations"
166 << completed_percentage_str << ", " << total_bytes_received_
167 << "/" << payload_size_str << " bytes downloaded"
168 << downloaded_percentage_str << ", overall progress "
169 << overall_progress_ << "%";
170}
171
172void DeltaPerformer::UpdateOverallProgress(bool force_log,
173 const char* message_prefix) {
174 // Compute our download and overall progress.
175 unsigned new_overall_progress = 0;
176 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
177 progress_weight_dont_add_up);
178 // Only consider download progress if its total size is known; otherwise
179 // adjust the operations weight to compensate for the absence of download
180 // progress. Also, make sure to cap the download portion at
181 // kProgressDownloadWeight, in case we end up downloading more than we
182 // initially expected (this indicates a problem, but could generally happen).
183 // TODO(garnold) the correction of operations weight when we do not have the
184 // total payload size, as well as the conditional guard below, should both be
185 // eliminated once we ensure that the payload_size in the install plan is
186 // always given and is non-zero. This currently isn't the case during unit
187 // tests (see chromium-os:37969).
188 size_t payload_size = install_plan_->payload_size;
189 unsigned actual_operations_weight = kProgressOperationsWeight;
190 if (payload_size)
191 new_overall_progress += min(
192 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
193 kProgressDownloadWeight)),
194 kProgressDownloadWeight);
195 else
196 actual_operations_weight += kProgressDownloadWeight;
197
198 // Only add completed operations if their total number is known; we definitely
199 // expect an update to have at least one operation, so the expectation is that
200 // this will eventually reach |actual_operations_weight|.
201 if (num_total_operations_)
202 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
203 actual_operations_weight);
204
205 // Progress ratio cannot recede, unless our assumptions about the total
206 // payload size, total number of operations, or the monotonicity of progress
207 // is breached.
208 if (new_overall_progress < overall_progress_) {
209 LOG(WARNING) << "progress counter receded from " << overall_progress_
210 << "% down to " << new_overall_progress << "%; this is a bug";
211 force_log = true;
212 }
213 overall_progress_ = new_overall_progress;
214
215 // Update chunk index, log as needed: if forced by called, or we completed a
216 // progress chunk, or a timeout has expired.
217 base::Time curr_time = base::Time::Now();
218 unsigned curr_progress_chunk =
219 overall_progress_ * kProgressLogMaxChunks / 100;
220 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
221 curr_time > forced_progress_log_time_) {
222 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
223 LogProgress(message_prefix);
224 }
225 last_progress_chunk_ = curr_progress_chunk;
226}
227
228
Gilad Arnoldfe133932014-01-14 12:25:50 -0800229size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
230 size_t max) {
231 const size_t count = *count_p;
232 if (!count)
233 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700234 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800235 const char* bytes_start = *bytes_p;
236 const char* bytes_end = bytes_start + read_len;
237 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
238 *bytes_p = bytes_end;
239 *count_p = count - read_len;
240 return read_len;
241}
242
243
244bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
245 ErrorCode* error) {
246 if (op_result)
247 return true;
248
249 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
250 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700251 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800252 return false;
253}
254
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700255int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700256 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800257 fd_ = OpenFile(path, &err);
258 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700259 path_ = path;
260 return -err;
261}
262
263bool DeltaPerformer::OpenKernel(const char* kernel_path) {
264 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800265 kernel_fd_ = OpenFile(kernel_path, &err);
266 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700267 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800268 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700269}
270
Alex Deymo1beda782015-06-07 23:01:25 +0200271bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800272 int err;
273 source_fd_ = OpenFile(source_path.c_str(), &err);
274 return static_cast<bool>(source_fd_);
275}
276
Alex Deymo1beda782015-06-07 23:01:25 +0200277bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800278 int err;
279 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
280 return static_cast<bool>(source_kernel_fd_);
281}
282
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700283int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700284 int err = 0;
Sen Jiang2d528b42015-09-25 11:18:12 -0700285 if (kernel_fd_ && !kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700286 err = errno;
287 PLOG(ERROR) << "Unable to close kernel fd:";
288 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800289 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700290 err = errno;
291 PLOG(ERROR) << "Unable to close rootfs fd:";
292 }
Allie Woodfdf00512015-03-02 13:34:55 -0800293 if (source_fd_ && !source_fd_->Close()) {
294 err = errno;
295 PLOG(ERROR) << "Unable to close source rootfs fd:";
296 }
297 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
298 err = errno;
299 PLOG(ERROR) << "Unable to close source kernel fd:";
300 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700301 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800302 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800303 kernel_fd_.reset();
304 source_fd_.reset();
305 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700306 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800307 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700308 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
309 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800310 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800311 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700312 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313}
314
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700315namespace {
316
317void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800318 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800319 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
320 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700321}
322
323void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
324 if (manifest.has_old_kernel_info())
325 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
326 if (manifest.has_old_rootfs_info())
327 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
328 if (manifest.has_new_kernel_info())
329 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
330 if (manifest.has_new_rootfs_info())
331 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
332}
333
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700334} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700335
Sen Jiangb8060e42015-09-24 17:30:50 -0700336bool DeltaPerformer::GetMetadataSignatureSizeOffset(
337 uint64_t* out_offset) const {
338 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
339 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
340 return true;
341 }
342 return false;
Don Garrett4d039442013-10-28 18:40:06 -0700343}
344
Sen Jiangb8060e42015-09-24 17:30:50 -0700345bool DeltaPerformer::GetManifestOffset(uint64_t* out_offset) const {
346 // Actual manifest begins right after the manifest size field or
347 // metadata signature size field if major version >= 2.
348 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
349 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
350 return true;
351 }
352 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
353 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize +
354 kDeltaMetadataSignatureSizeSize;
355 return true;
356 }
357 LOG(ERROR) << "Unknown major payload version: " << major_payload_version_;
358 return false;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700359}
360
Gilad Arnoldfe133932014-01-14 12:25:50 -0800361uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800362 return metadata_size_;
363}
364
Sen Jiangb8060e42015-09-24 17:30:50 -0700365uint64_t DeltaPerformer::GetMajorVersion() const {
366 return major_payload_version_;
367}
368
Allie Woodfdf00512015-03-02 13:34:55 -0800369uint32_t DeltaPerformer::GetMinorVersion() const {
370 if (manifest_.has_minor_version()) {
371 return manifest_.minor_version();
372 } else {
373 return (install_plan_->is_full_update ?
374 kFullPayloadMinorVersion :
375 kSupportedMinorPayloadVersion);
376 }
377}
378
Gilad Arnolddaa27402014-01-23 11:56:17 -0800379bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
380 if (!manifest_parsed_)
381 return false;
382 *out_manifest_p = manifest_;
383 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800384}
385
Sen Jiangb8060e42015-09-24 17:30:50 -0700386bool DeltaPerformer::IsHeaderParsed() const {
387 return metadata_size_ != 0;
388}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700389
Darin Petkov9574f7e2011-01-13 10:48:12 -0800390DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800391 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700392 *error = ErrorCode::kSuccess;
Sen Jiangb8060e42015-09-24 17:30:50 -0700393 uint64_t manifest_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700394
Sen Jiangb8060e42015-09-24 17:30:50 -0700395 if (!IsHeaderParsed()) {
396 // Ensure we have data to cover the major payload version.
397 if (payload.size() < kDeltaManifestSizeOffset)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800398 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700399
Gilad Arnoldfe133932014-01-14 12:25:50 -0800400 // Validate the magic string.
Sen Jiangb8060e42015-09-24 17:30:50 -0700401 if (memcmp(payload.data(), kDeltaMagic, sizeof(kDeltaMagic)) != 0) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800402 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700403 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800404 return kMetadataParseError;
405 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800406
407 // Extract the payload version from the metadata.
Sen Jiangb8060e42015-09-24 17:30:50 -0700408 COMPILE_ASSERT(sizeof(major_payload_version_) == kDeltaVersionSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800409 major_payload_version_size_mismatch);
Sen Jiangb8060e42015-09-24 17:30:50 -0700410 memcpy(&major_payload_version_,
411 &payload[kDeltaVersionOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800412 kDeltaVersionSize);
413 // switch big endian to host
Sen Jiangb8060e42015-09-24 17:30:50 -0700414 major_payload_version_ = be64toh(major_payload_version_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800415
Sen Jiangb8060e42015-09-24 17:30:50 -0700416 if (major_payload_version_ != supported_major_version_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800417 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
Sen Jiangb8060e42015-09-24 17:30:50 -0700418 << major_payload_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700419 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800420 return kMetadataParseError;
421 }
422
Sen Jiangb8060e42015-09-24 17:30:50 -0700423 // Get the manifest offset now that we have payload version.
424 if (!GetManifestOffset(&manifest_offset)) {
425 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
426 return kMetadataParseError;
427 }
428 // Check again with the manifest offset.
429 if (payload.size() < manifest_offset)
430 return kMetadataParseInsufficientData;
431
Gilad Arnoldfe133932014-01-14 12:25:50 -0800432 // Next, parse the manifest size.
Sen Jiangb8060e42015-09-24 17:30:50 -0700433 COMPILE_ASSERT(sizeof(manifest_size_) == kDeltaManifestSizeSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800434 manifest_size_size_mismatch);
Sen Jiangb8060e42015-09-24 17:30:50 -0700435 memcpy(&manifest_size_,
436 &payload[kDeltaManifestSizeOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800437 kDeltaManifestSizeSize);
Sen Jiangb8060e42015-09-24 17:30:50 -0700438 manifest_size_ = be64toh(manifest_size_); // switch big endian to host
439
440 uint32_t metadata_signature_size = 0;
441 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
442 // Parse the metadata signature size.
443 COMPILE_ASSERT(sizeof(metadata_signature_size) ==
444 kDeltaMetadataSignatureSizeSize,
445 metadata_signature_size_size_mismatch);
446 uint64_t metadata_signature_size_offset;
447 if (!GetMetadataSignatureSizeOffset(&metadata_signature_size_offset)) {
448 *error = ErrorCode::kError;
449 return kMetadataParseError;
450 }
451 memcpy(&metadata_signature_size,
452 &payload[metadata_signature_size_offset],
453 kDeltaMetadataSignatureSizeSize);
454 metadata_signature_size = be32toh(metadata_signature_size);
455 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800456
457 // If the metadata size is present in install plan, check for it immediately
458 // even before waiting for that many number of bytes to be downloaded in the
459 // payload. This will prevent any attack which relies on us downloading data
460 // beyond the expected metadata size.
Sen Jiangb8060e42015-09-24 17:30:50 -0700461 metadata_size_ = manifest_offset + manifest_size_ + metadata_signature_size;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800462 if (install_plan_->hash_checks_mandatory) {
463 if (install_plan_->metadata_size != metadata_size_) {
464 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
465 << install_plan_->metadata_size
466 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700467 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800468 return kMetadataParseError;
469 }
470 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700471 }
472
473 // Now that we have validated the metadata size, we should wait for the full
474 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800475 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800476 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700477
478 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700479 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700480 // that we just log once (instead of logging n times) if it takes n
481 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800482 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700483 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800484 } else {
485 // For mandatory-cases, we'd have already returned a kMetadataParseError
486 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
487 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
488 << install_plan_->metadata_size
489 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800490 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800491 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700492
Jay Srinivasanf4318702012-09-24 11:56:24 -0700493 // We have the full metadata in |payload|. Verify its integrity
494 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800495 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700496 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800497 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800498 // The autoupdate_CatchBadSignatures test checks for this string
499 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800500 LOG(ERROR) << "Mandatory metadata signature validation failed";
501 return kMetadataParseError;
502 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700503
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800504 // For non-mandatory cases, just send a UMA stat.
505 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700506 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700507 }
508
Sen Jiangb8060e42015-09-24 17:30:50 -0700509 if (!GetManifestOffset(&manifest_offset)) {
510 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
511 return kMetadataParseError;
512 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800513 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb8060e42015-09-24 17:30:50 -0700514 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800515 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700516 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800517 return kMetadataParseError;
518 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800519
520 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800521 return kMetadataParseSuccess;
522}
523
Don Garrette410e0f2011-11-10 15:39:01 -0800524// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800525// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700526// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800527bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700528 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700529
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700530 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800531 system_state_->payload_state()->DownloadProgress(count);
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 :
Gilad Arnoldfe133932014-01-14 12:25:50 -0800543 metadata_size_));
544
Gilad Arnolddaa27402014-01-23 11:56:17 -0800545 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700546 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800547 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800548 if (result == kMetadataParseInsufficientData) {
549 // 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.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800562 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700563 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800564 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700565 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700566
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700567 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700568 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700569 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700570 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800571 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700572 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800573
Allie Woodfdf00512015-03-02 13:34:55 -0800574 // Open source fds if we have a delta payload with minor version 2.
575 if (!install_plan_->is_full_update &&
576 GetMinorVersion() == kSourceMinorPayloadVersion) {
577 if (!OpenSourceRootfs(install_plan_->source_path)) {
578 LOG(ERROR) << "Unable to open source rootfs partition file "
579 << install_plan_->source_path;
580 Close();
581 return false;
582 }
583 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
584 LOG(ERROR) << "Unable to open source kernel partition file "
585 << install_plan_->kernel_source_path;
586 Close();
587 return false;
588 }
589 }
590
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800591 num_rootfs_operations_ = manifest_.install_operations_size();
592 num_total_operations_ =
593 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
594 if (next_operation_num_ > 0)
595 UpdateOverallProgress(true, "Resuming after ");
596 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700597 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800598
599 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700600 // Check if we should cancel the current attempt for any reason.
601 // In this case, *error will have already been populated with the reason
602 // why we're cancelling.
603 if (system_state_->update_attempter()->ShouldCancel(error))
604 return false;
605
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800606 const bool is_kernel_partition =
607 (next_operation_num_ >= num_rootfs_operations_);
Alex Deymoa12ee112015-08-12 22:19:32 -0700608 const InstallOperation& op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800609 is_kernel_partition ?
Alex Deymoa12ee112015-08-12 22:19:32 -0700610 manifest_.kernel_install_operations(next_operation_num_ -
611 num_rootfs_operations_) :
612 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800613
614 CopyDataToBuffer(&c_bytes, &count, op.data_length());
615
616 // Check whether we received all of the next operation's data payload.
617 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700618 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700619
Jay Srinivasanf4318702012-09-24 11:56:24 -0700620 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700621 // Otherwise, keep the old behavior. This serves as a knob to disable
622 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800623 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
624 // we would have already failed in ParsePayloadMetadata method and thus not
625 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700626 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700627 // Note: Validate must be called only if CanPerformInstallOperation is
628 // called. Otherwise, we might be failing operations before even if there
629 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800630 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700631 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800632 if (install_plan_->hash_checks_mandatory) {
633 LOG(ERROR) << "Mandatory operation hash check failed";
634 return false;
635 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700636
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800637 // For non-mandatory cases, just send a UMA stat.
638 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700639 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700640 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700641 }
642
Darin Petkov45580e42010-10-08 14:02:40 -0700643 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700644 ScopedTerminatorExitUnblocker exit_unblocker =
645 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800646
647 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700648 switch (op.type()) {
649 case InstallOperation::REPLACE:
650 case InstallOperation::REPLACE_BZ:
651 case InstallOperation::REPLACE_XZ:
652 op_result = PerformReplaceOperation(op, is_kernel_partition);
653 break;
Alex Deymo79715ad2015-10-02 14:27:53 -0700654 case InstallOperation::ZERO:
655 case InstallOperation::DISCARD:
656 op_result = PerformZeroOrDiscardOperation(op, is_kernel_partition);
657 break;
Alex Deymo2d621a32015-10-01 11:09:01 -0700658 case InstallOperation::MOVE:
659 op_result = PerformMoveOperation(op, is_kernel_partition);
660 break;
661 case InstallOperation::BSDIFF:
662 op_result = PerformBsdiffOperation(op, is_kernel_partition);
663 break;
664 case InstallOperation::SOURCE_COPY:
665 op_result = PerformSourceCopyOperation(op, is_kernel_partition);
666 break;
667 case InstallOperation::SOURCE_BSDIFF:
668 op_result = PerformSourceBsdiffOperation(op, is_kernel_partition);
669 break;
670 default:
671 op_result = false;
672 }
673 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800674 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800675
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700676 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800677 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700678 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700679 }
Don Garrette410e0f2011-11-10 15:39:01 -0800680 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700681}
682
David Zeuthen8f191b22013-08-06 12:27:50 -0700683bool DeltaPerformer::IsManifestValid() {
684 return manifest_valid_;
685}
686
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700687bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700688 const chromeos_update_engine::InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700689 // Move and source_copy operations don't require any data blob, so they can
690 // always be performed.
Alex Deymoa12ee112015-08-12 22:19:32 -0700691 if (operation.type() == InstallOperation::MOVE ||
692 operation.type() == InstallOperation::SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700693 return true;
694
695 // See if we have the entire data blob in the buffer
696 if (operation.data_offset() < buffer_offset_) {
697 LOG(ERROR) << "we threw away data it seems?";
698 return false;
699 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700700
Gilad Arnoldfe133932014-01-14 12:25:50 -0800701 return (operation.data_offset() + operation.data_length() <=
702 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700703}
704
Alex Deymoa12ee112015-08-12 22:19:32 -0700705bool DeltaPerformer::PerformReplaceOperation(const InstallOperation& operation,
706 bool is_kernel_partition) {
707 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700708 operation.type() == InstallOperation::REPLACE_BZ ||
709 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700710
711 // Since we delete data off the beginning of the buffer as we use it,
712 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700713 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
714 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700715
Darin Petkov437adc42010-10-07 13:12:24 -0700716 // Extract the signature message if it's in this operation.
717 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700718
Alex Deymo05322872015-09-30 09:50:24 -0700719 // Setup the ExtentWriter stack based on the operation type.
720 std::unique_ptr<ExtentWriter> writer =
721 chromeos::make_unique_ptr(new ZeroPadExtentWriter(
722 chromeos::make_unique_ptr(new DirectExtentWriter())));
Darin Petkovd7061ab2010-10-06 14:37:09 -0700723
Alex Deymo2d621a32015-10-01 11:09:01 -0700724 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700725 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700726 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
727 writer.reset(new XzExtentWriter(std::move(writer)));
728 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700729
730 // Create a vector of extents to pass to the ExtentWriter.
731 vector<Extent> extents;
732 for (int i = 0; i < operation.dst_extents_size(); i++) {
733 extents.push_back(operation.dst_extents(i));
734 }
735
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800736 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700737
738 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800739 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700740 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700741
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700742 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800743 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700744 return true;
745}
746
Alex Deymo79715ad2015-10-02 14:27:53 -0700747bool DeltaPerformer::PerformZeroOrDiscardOperation(
748 const InstallOperation& operation,
749 bool is_kernel_partition) {
750 CHECK(operation.type() == InstallOperation::DISCARD ||
751 operation.type() == InstallOperation::ZERO);
752
753 // These operations have no blob.
754 TEST_AND_RETURN_FALSE(!operation.has_data_offset());
755 TEST_AND_RETURN_FALSE(!operation.has_data_length());
756
757 int request =
758 (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
759
760 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
761 bool attempt_ioctl = true;
762 chromeos::Blob zeros;
763 for (int i = 0; i < operation.dst_extents_size(); i++) {
764 Extent extent = operation.dst_extents(i);
765 const uint64_t start = extent.start_block() * block_size_;
766 const uint64_t length = extent.num_blocks() * block_size_;
767 if (attempt_ioctl) {
768 int result = 0;
769 if (fd->BlkIoctl(request, start, length, &result) && result == 0)
770 continue;
771 attempt_ioctl = false;
772 zeros.resize(16 * block_size_);
773 }
774 // In case of failure, we fall back to writing 0 to the selected region.
775 for (uint64_t offset = 0; offset < length; offset += zeros.size()) {
Alex Deymo42791782015-10-08 11:01:28 -0700776 uint64_t chunk_length = min(length - offset,
777 static_cast<uint64_t>(zeros.size()));
Alex Deymo79715ad2015-10-02 14:27:53 -0700778 TEST_AND_RETURN_FALSE(
779 utils::PWriteAll(fd, zeros.data(), chunk_length, start + offset));
780 }
781 }
782 return true;
783}
784
Alex Deymoa12ee112015-08-12 22:19:32 -0700785bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
786 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700787 // Calculate buffer size. Note, this function doesn't do a sliding
788 // window to copy in case the source and destination blocks overlap.
789 // If we wanted to do a sliding window, we could program the server
790 // to generate deltas that effectively did a sliding window.
791
792 uint64_t blocks_to_read = 0;
793 for (int i = 0; i < operation.src_extents_size(); i++)
794 blocks_to_read += operation.src_extents(i).num_blocks();
795
796 uint64_t blocks_to_write = 0;
797 for (int i = 0; i < operation.dst_extents_size(); i++)
798 blocks_to_write += operation.dst_extents(i).num_blocks();
799
800 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800801 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700802
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800803 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700804
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700805 // Read in bytes.
806 ssize_t bytes_read = 0;
807 for (int i = 0; i < operation.src_extents_size(); i++) {
808 ssize_t bytes_read_this_iteration = 0;
809 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200810 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700811 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
812 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
813 &buf[bytes_read],
814 bytes,
815 extent.start_block() * block_size_,
816 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700817 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200818 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700819 bytes_read += bytes_read_this_iteration;
820 }
821
822 // Write bytes out.
823 ssize_t bytes_written = 0;
824 for (int i = 0; i < operation.dst_extents_size(); i++) {
825 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200826 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700827 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
828 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
829 &buf[bytes_written],
830 bytes,
831 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200832 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700833 }
834 DCHECK_EQ(bytes_written, bytes_read);
835 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
836 return true;
837}
838
Allie Wood9f6f0a52015-03-30 11:25:47 -0700839namespace {
840
841// Takes |extents| and fills an empty vector |blocks| with a block index for
842// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
843void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
844 vector<uint64_t>* blocks) {
845 for (Extent ext : extents) {
846 for (uint64_t j = 0; j < ext.num_blocks(); j++)
847 blocks->push_back(ext.start_block() + j);
848 }
849}
850
851// Takes |extents| and returns the number of blocks in those extents.
852uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
853 uint64_t sum = 0;
854 for (Extent ext : extents) {
855 sum += ext.num_blocks();
856 }
857 return sum;
858}
859
860} // namespace
861
862bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700863 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700864 bool is_kernel_partition) {
865 if (operation.has_src_length())
866 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
867 if (operation.has_dst_length())
868 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
869
870 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
871 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
872 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
873
874 // Create vectors of all the individual src/dst blocks.
875 vector<uint64_t> src_blocks;
876 vector<uint64_t> dst_blocks;
877 ExtentsToBlocks(operation.src_extents(), &src_blocks);
878 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
879 DCHECK_EQ(src_blocks.size(), blocks_to_read);
880 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
881
882 FileDescriptorPtr src_fd =
883 is_kernel_partition ? source_kernel_fd_ : source_fd_;
884 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
885
886 chromeos::Blob buf(block_size_);
887 ssize_t bytes_read = 0;
888 // Read/write one block at a time.
889 for (uint64_t i = 0; i < blocks_to_read; i++) {
890 ssize_t bytes_read_this_iteration = 0;
891 uint64_t src_block = src_blocks[i];
892 uint64_t dst_block = dst_blocks[i];
893
894 // Read in bytes.
895 TEST_AND_RETURN_FALSE(
896 utils::PReadAll(src_fd,
897 buf.data(),
898 block_size_,
899 src_block * block_size_,
900 &bytes_read_this_iteration));
901
902 // Write bytes out.
903 TEST_AND_RETURN_FALSE(
904 utils::PWriteAll(dst_fd,
905 buf.data(),
906 block_size_,
907 dst_block * block_size_));
908
909 bytes_read += bytes_read_this_iteration;
910 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
911 static_cast<ssize_t>(block_size_));
912 }
913 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
914 return true;
915}
916
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700917bool DeltaPerformer::ExtentsToBsdiffPositionsString(
918 const RepeatedPtrField<Extent>& extents,
919 uint64_t block_size,
920 uint64_t full_length,
921 string* positions_string) {
922 string ret;
923 uint64_t length = 0;
924 for (int i = 0; i < extents.size(); i++) {
925 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700926 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700927 uint64_t this_length = min(full_length - length,
928 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700929 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700930 length += this_length;
931 }
932 TEST_AND_RETURN_FALSE(length == full_length);
933 if (!ret.empty())
934 ret.resize(ret.size() - 1); // Strip trailing comma off
935 *positions_string = ret;
936 return true;
937}
938
Alex Deymoa12ee112015-08-12 22:19:32 -0700939bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
940 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700941 // Since we delete data off the beginning of the buffer as we use it,
942 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700943 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
944 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700945
946 string input_positions;
947 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
948 block_size_,
949 operation.src_length(),
950 &input_positions));
951 string output_positions;
952 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
953 block_size_,
954 operation.dst_length(),
955 &output_positions));
956
957 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700958 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700959 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700960 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700961 ScopedPathUnlinker path_unlinker(temp_filename);
962 {
963 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
964 ScopedFdCloser fd_closer(&fd);
965 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800966 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700967 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700968
Darin Petkov7f2ec752013-04-03 14:45:19 +0200969 // Update the buffer to release the patch data memory as soon as the patch
970 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800971 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200972
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800973 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700974 vector<string> cmd{kBspatchPath, path, path, temp_filename,
975 input_positions, output_positions};
976
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700977 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700978 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700979 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
980 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700981 TEST_AND_RETURN_FALSE(return_code == 0);
982
983 if (operation.dst_length() % block_size_) {
984 // Zero out rest of final block.
985 // TODO(adlr): build this into bspatch; it's more efficient that way.
986 const Extent& last_extent =
987 operation.dst_extents(operation.dst_extents_size() - 1);
988 const uint64_t end_byte =
989 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
990 const uint64_t begin_byte =
991 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800992 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800993 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700994 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800995 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700996 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700997 return true;
998}
999
Allie Wood9f6f0a52015-03-30 11:25:47 -07001000bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001001 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001002 bool is_kernel_partition) {
1003 // Since we delete data off the beginning of the buffer as we use it,
1004 // the data we need should be exactly at the beginning of the buffer.
1005 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1006 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1007 if (operation.has_src_length())
1008 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1009 if (operation.has_dst_length())
1010 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1011
1012 string input_positions;
1013 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1014 block_size_,
1015 operation.src_length(),
1016 &input_positions));
1017 string output_positions;
1018 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1019 block_size_,
1020 operation.dst_length(),
1021 &output_positions));
1022
1023 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -07001024 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Allie Wood9f6f0a52015-03-30 11:25:47 -07001025 &temp_filename,
1026 nullptr));
1027 ScopedPathUnlinker path_unlinker(temp_filename);
1028 {
1029 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
1030 ScopedFdCloser fd_closer(&fd);
1031 TEST_AND_RETURN_FALSE(
1032 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
1033 }
1034
1035 // Update the buffer to release the patch data memory as soon as the patch
1036 // file is written out.
1037 DiscardBuffer(true);
1038
1039 const string& src_path = is_kernel_partition ?
1040 install_plan_->kernel_source_path :
1041 install_plan_->source_path;
1042 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
1043 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
1044 input_positions, output_positions};
1045
1046 int return_code = 0;
1047 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -07001048 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
1049 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001050 TEST_AND_RETURN_FALSE(return_code == 0);
1051 return true;
1052}
1053
Darin Petkovd7061ab2010-10-06 14:37:09 -07001054bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -07001055 const InstallOperation& operation) {
1056 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001057 !manifest_.has_signatures_offset() ||
1058 manifest_.signatures_offset() != operation.data_offset()) {
1059 return false;
1060 }
1061 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1062 manifest_.signatures_size() == operation.data_length());
1063 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1064 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1065 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001066 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001067 buffer_.begin(),
1068 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001069
1070 // Save the signature blob because if the update is interrupted after the
1071 // download phase we don't go through this path anymore. Some alternatives to
1072 // consider:
1073 //
1074 // 1. On resume, re-download the signature blob from the server and re-verify
1075 // it.
1076 //
1077 // 2. Verify the signature as soon as it's received and don't checkpoint the
1078 // blob and the signed sha-256 context.
1079 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001080 string(signatures_message_data_.begin(),
1081 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001082 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001083 // The hash of all data consumed so far should be verified against the signed
1084 // hash.
1085 signed_hash_context_ = hash_calculator_.GetContext();
1086 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1087 signed_hash_context_))
1088 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001089 LOG(INFO) << "Extracted signature data of size "
1090 << manifest_.signatures_size() << " at "
1091 << manifest_.signatures_offset();
1092 return true;
1093}
1094
David Zeuthene7f89172013-10-31 10:21:04 -07001095bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1096 if (system_state_->hardware()->IsOfficialBuild() ||
1097 utils::FileExists(public_key_path_.c_str()) ||
1098 install_plan_->public_key_rsa.empty())
1099 return false;
1100
1101 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1102 out_tmp_key))
1103 return false;
1104
1105 return true;
1106}
1107
David Zeuthena99981f2013-04-29 13:42:47 -07001108ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001109 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001110
Jay Srinivasanf4318702012-09-24 11:56:24 -07001111 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001112 if (install_plan_->hash_checks_mandatory) {
1113 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001114 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001115 }
1116
Jay Srinivasanf4318702012-09-24 11:56:24 -07001117 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001119 }
1120
1121 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001122 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001123 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001124 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001125 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1126 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001127 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001128 }
1129
David Zeuthene7f89172013-10-31 10:21:04 -07001130 // See if we should use the public RSA key in the Omaha response.
1131 base::FilePath path_to_public_key(public_key_path_);
1132 base::FilePath tmp_key;
1133 if (GetPublicKeyFromResponse(&tmp_key))
1134 path_to_public_key = tmp_key;
1135 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1136 if (tmp_key.empty())
1137 tmp_key_remover.set_should_remove(false);
1138
1139 LOG(INFO) << "Verifying metadata hash signature using public key: "
1140 << path_to_public_key.value();
1141
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001142 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001143 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1144 path_to_public_key.value(),
1145 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001146 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001147 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001148 }
1149
Jay Srinivasanf4318702012-09-24 11:56:24 -07001150 OmahaHashCalculator metadata_hasher;
1151 metadata_hasher.Update(metadata, metadata_size);
1152 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001153 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001154 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001155 }
1156
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001157 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001158 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001159 if (calculated_metadata_hash.empty()) {
1160 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001161 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001162 }
1163
Jay Srinivasanf4318702012-09-24 11:56:24 -07001164 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001165 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001166 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001167 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001168 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001169 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001170 }
1171
David Zeuthenbc27aac2013-11-26 11:17:48 -08001172 // The autoupdate_CatchBadSignatures test checks for this string in
1173 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001174 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001175 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001176}
1177
Gilad Arnold21504f02013-05-24 08:51:22 -07001178ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001179 // Perform assorted checks to sanity check the manifest, make sure it
1180 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001181 //
1182 // TODO(garnold) in general, the presence of an old partition hash should be
1183 // the sole indicator for a delta update, as we would generally like update
1184 // payloads to be self contained and not assume an Omaha response to tell us
1185 // that. However, since this requires some massive reengineering of the update
1186 // flow (making filesystem copying happen conditionally only *after*
1187 // downloading and parsing of the update manifest) we'll put it off for now.
1188 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001189 if (install_plan_->is_full_update) {
1190 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1191 LOG(ERROR) << "Purported full payload contains old partition "
1192 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001193 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001194 }
1195
1196 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1197 LOG(ERROR) << "Manifest contains minor version "
1198 << manifest_.minor_version()
1199 << ", but all full payloads should have version "
1200 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001201 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001202 }
1203 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001204 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001205 LOG(ERROR) << "Manifest contains minor version "
1206 << manifest_.minor_version()
1207 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001208 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001209 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001210 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001211 }
1212
1213 // TODO(garnold) we should be adding more and more manifest checks, such as
1214 // partition boundaries etc (see chromium-os:37661).
1215
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001216 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001217}
1218
David Zeuthena99981f2013-04-29 13:42:47 -07001219ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001220 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001221 if (!operation.data_sha256_hash().size()) {
1222 if (!operation.data_length()) {
1223 // Operations that do not have any data blob won't have any operation hash
1224 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001225 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001226 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001227 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001228 }
1229
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001230 // No hash is present for an operation that has data blobs. This shouldn't
1231 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001232 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001233 // hashes. So if it happens it means either we've turned operation hash
1234 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001235 // One caveat though: The last operation is a dummy signature operation
1236 // that doesn't have a hash at the time the manifest is created. So we
1237 // should not complaint about that operation. This operation can be
1238 // recognized by the fact that it's offset is mentioned in the manifest.
1239 if (manifest_.signatures_offset() &&
1240 manifest_.signatures_offset() == operation.data_offset()) {
1241 LOG(INFO) << "Skipping hash verification for signature operation "
1242 << next_operation_num_ + 1;
1243 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001244 if (install_plan_->hash_checks_mandatory) {
1245 LOG(ERROR) << "Missing mandatory operation hash for operation "
1246 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001247 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001248 }
1249
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001250 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1251 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001252 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001253 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001254 }
1255
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001256 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001257 expected_op_hash.assign(operation.data_sha256_hash().data(),
1258 (operation.data_sha256_hash().data() +
1259 operation.data_sha256_hash().size()));
1260
1261 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001262 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001263 if (!operation_hasher.Finalize()) {
1264 LOG(ERROR) << "Unable to compute actual hash of operation "
1265 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001266 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001267 }
1268
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001269 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001270 if (calculated_op_hash != expected_op_hash) {
1271 LOG(ERROR) << "Hash verification failed for operation "
1272 << next_operation_num_ << ". Expected hash = ";
1273 utils::HexDumpVector(expected_op_hash);
1274 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1275 << " bytes at offset: " << operation.data_offset() << " = ";
1276 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001277 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001278 }
1279
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001280 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001281}
1282
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001283#define TEST_AND_RETURN_VAL(_retval, _condition) \
1284 do { \
1285 if (!(_condition)) { \
1286 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1287 return _retval; \
1288 } \
1289 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001290
David Zeuthena99981f2013-04-29 13:42:47 -07001291ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001292 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001293 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001294
1295 // See if we should use the public RSA key in the Omaha response.
1296 base::FilePath path_to_public_key(public_key_path_);
1297 base::FilePath tmp_key;
1298 if (GetPublicKeyFromResponse(&tmp_key))
1299 path_to_public_key = tmp_key;
1300 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1301 if (tmp_key.empty())
1302 tmp_key_remover.set_should_remove(false);
1303
1304 LOG(INFO) << "Verifying payload using public key: "
1305 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001306
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001307 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001308 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001309 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001310 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001311
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001312 // Verifies the payload hash.
1313 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001314 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001315 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001316 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001317 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001318
Darin Petkov437adc42010-10-07 13:12:24 -07001319 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001320 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001321 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001322 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001323 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001324 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001325 !signatures_message_data_.empty());
Darin Petkov437adc42010-10-07 13:12:24 -07001326 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001327 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001328 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001329 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001330 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001331 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001332 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1333 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001334 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001335 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001336
1337 if (!PayloadVerifier::VerifySignature(
1338 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001339 // The autoupdate_CatchBadSignatures test checks for this string
1340 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001341 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001342 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001343 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001344
David Zeuthene7f89172013-10-31 10:21:04 -07001345 LOG(INFO) << "Payload hash matches value in payload.";
1346
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001347 // At this point, we are guaranteed to have downloaded a full payload, i.e
1348 // the one whose size matches the size mentioned in Omaha response. If any
1349 // errors happen after this, it's likely a problem with the payload itself or
1350 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001351 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001352 system_state_->payload_state()->DownloadComplete();
1353
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001354 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001355}
1356
Darin Petkov3aefa862010-12-07 14:45:00 -08001357bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001358 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001359 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001360 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001361 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1362 manifest_.has_new_kernel_info() &&
1363 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001364 *kernel_size = manifest_.new_kernel_info().size();
1365 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001366 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1367 manifest_.new_kernel_info().hash().end());
1368 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1369 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001370 kernel_hash->swap(new_kernel_hash);
1371 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001372 return true;
1373}
1374
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001375namespace {
1376void LogVerifyError(bool is_kern,
1377 const string& local_hash,
1378 const string& expected_hash) {
1379 const char* type = is_kern ? "kernel" : "rootfs";
1380 LOG(ERROR) << "This is a server-side error due to "
1381 << "mismatched delta update image!";
1382 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1383 << "update that must be applied over a " << type << " with "
1384 << "a specific checksum, but the " << type << " we're starting "
1385 << "with doesn't have that checksum! This means that "
1386 << "the delta I've been given doesn't match my existing "
1387 << "system. The " << type << " partition I have has hash: "
1388 << local_hash << " but the update expected me to have "
1389 << expected_hash << " .";
1390 if (is_kern) {
1391 LOG(INFO) << "To get the checksum of a kernel partition on a "
1392 << "booted machine, run this command (change /dev/sda2 "
1393 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1394 << "openssl dgst -sha256 -binary | openssl base64";
1395 } else {
1396 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1397 << "booted machine, run this command (change /dev/sda3 "
1398 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1399 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1400 << "| sed 's/[^0-9]*//') / 256 )) | "
1401 << "openssl dgst -sha256 -binary | openssl base64";
1402 }
1403 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1404 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1405}
1406
1407string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001408 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001409}
1410} // namespace
1411
Darin Petkov698d0412010-10-13 10:59:44 -07001412bool DeltaPerformer::VerifySourcePartitions() {
1413 LOG(INFO) << "Verifying source partitions.";
1414 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001415 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001416 if (manifest_.has_old_kernel_info()) {
1417 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001418 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001419 !install_plan_->source_kernel_hash.empty() &&
1420 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1421 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001422 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001423 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001424 if (!valid) {
1425 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001426 StringForHashBytes(
1427 install_plan_->source_kernel_hash.data(),
1428 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001429 StringForHashBytes(info.hash().data(),
1430 info.hash().size()));
1431 }
1432 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001433 }
1434 if (manifest_.has_old_rootfs_info()) {
1435 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001436 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001437 !install_plan_->source_rootfs_hash.empty() &&
1438 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1439 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001440 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001441 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001442 if (!valid) {
1443 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001444 StringForHashBytes(
1445 install_plan_->source_rootfs_hash.data(),
1446 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001447 StringForHashBytes(info.hash().data(),
1448 info.hash().size()));
1449 }
1450 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001451 }
1452 return true;
1453}
1454
Gilad Arnolddaa27402014-01-23 11:56:17 -08001455void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001456 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001457 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001458 buffer_offset_ += buffer_.size();
1459
1460 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001461 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001462
1463 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001464 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001465}
1466
Darin Petkov0406e402010-10-06 21:33:11 -07001467bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1468 string update_check_response_hash) {
1469 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001470 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1471 next_operation != kUpdateStateOperationInvalid &&
1472 next_operation > 0))
1473 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001474
1475 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001476 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1477 !interrupted_hash.empty() &&
1478 interrupted_hash == update_check_response_hash))
1479 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001480
Darin Petkov61426142010-10-08 11:04:55 -07001481 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001482 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1483 && resumed_update_failures > kMaxResumedUpdateFailures))
1484 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001485
Darin Petkov0406e402010-10-06 21:33:11 -07001486 // Sanity check the rest.
1487 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001488 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1489 next_data_offset >= 0))
1490 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001491
Darin Petkov437adc42010-10-07 13:12:24 -07001492 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001493 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1494 !sha256_context.empty()))
1495 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001496
1497 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001498 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1499 manifest_metadata_size > 0))
1500 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001501
1502 return true;
1503}
1504
Darin Petkov9b230572010-10-08 10:20:09 -07001505bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001506 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1507 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001508 if (!quick) {
1509 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1510 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001511 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001512 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1513 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001514 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001515 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001516 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001517 }
Darin Petkov73058b42010-10-06 16:32:19 -07001518 return true;
1519}
1520
1521bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001522 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001523 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001524 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001525 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001526 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001527 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001528 hash_calculator_.GetContext()));
1529 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1530 buffer_offset_));
1531 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001532
1533 if (next_operation_num_ < num_total_operations_) {
1534 const bool is_kernel_partition =
1535 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001536 const InstallOperation& op =
1537 is_kernel_partition
1538 ? manifest_.kernel_install_operations(next_operation_num_ -
1539 num_rootfs_operations_)
1540 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001541 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1542 op.data_length()));
1543 } else {
1544 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1545 0));
1546 }
Darin Petkov0406e402010-10-06 21:33:11 -07001547 }
Darin Petkov73058b42010-10-06 16:32:19 -07001548 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1549 next_operation_num_));
1550 return true;
1551}
1552
Darin Petkov9b230572010-10-08 10:20:09 -07001553bool DeltaPerformer::PrimeUpdateState() {
1554 CHECK(manifest_valid_);
1555 block_size_ = manifest_.block_size();
1556
1557 int64_t next_operation = kUpdateStateOperationInvalid;
1558 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1559 next_operation == kUpdateStateOperationInvalid ||
1560 next_operation <= 0) {
1561 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001562 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001563 return true;
1564 }
1565 next_operation_num_ = next_operation;
1566
1567 // Resuming an update -- load the rest of the update state.
1568 int64_t next_data_offset = -1;
1569 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1570 &next_data_offset) &&
1571 next_data_offset >= 0);
1572 buffer_offset_ = next_data_offset;
1573
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001574 // The signed hash context and the signature blob may be empty if the
1575 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001576 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1577 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001578 string signature_blob;
1579 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1580 signatures_message_data_.assign(signature_blob.begin(),
1581 signature_blob.end());
1582 }
Darin Petkov9b230572010-10-08 10:20:09 -07001583
1584 string hash_context;
1585 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1586 &hash_context) &&
1587 hash_calculator_.SetContext(hash_context));
1588
1589 int64_t manifest_metadata_size = 0;
1590 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1591 &manifest_metadata_size) &&
1592 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001593 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001594
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001595 // Advance the download progress to reflect what doesn't need to be
1596 // re-downloaded.
1597 total_bytes_received_ += buffer_offset_;
1598
Darin Petkov61426142010-10-08 11:04:55 -07001599 // Speculatively count the resume as a failure.
1600 int64_t resumed_update_failures;
1601 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1602 resumed_update_failures++;
1603 } else {
1604 resumed_update_failures = 1;
1605 }
1606 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001607 return true;
1608}
1609
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001610} // namespace chromeos_update_engine