blob: 96850df3456b980f5363205409c8b357b5fcd1f7 [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()) {
776 uint64_t chunk_length = min(length - offset, zeros.size());
777 TEST_AND_RETURN_FALSE(
778 utils::PWriteAll(fd, zeros.data(), chunk_length, start + offset));
779 }
780 }
781 return true;
782}
783
Alex Deymoa12ee112015-08-12 22:19:32 -0700784bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
785 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700786 // Calculate buffer size. Note, this function doesn't do a sliding
787 // window to copy in case the source and destination blocks overlap.
788 // If we wanted to do a sliding window, we could program the server
789 // to generate deltas that effectively did a sliding window.
790
791 uint64_t blocks_to_read = 0;
792 for (int i = 0; i < operation.src_extents_size(); i++)
793 blocks_to_read += operation.src_extents(i).num_blocks();
794
795 uint64_t blocks_to_write = 0;
796 for (int i = 0; i < operation.dst_extents_size(); i++)
797 blocks_to_write += operation.dst_extents(i).num_blocks();
798
799 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800800 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700801
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800802 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700803
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700804 // Read in bytes.
805 ssize_t bytes_read = 0;
806 for (int i = 0; i < operation.src_extents_size(); i++) {
807 ssize_t bytes_read_this_iteration = 0;
808 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200809 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700810 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
811 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
812 &buf[bytes_read],
813 bytes,
814 extent.start_block() * block_size_,
815 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700816 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200817 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700818 bytes_read += bytes_read_this_iteration;
819 }
820
821 // Write bytes out.
822 ssize_t bytes_written = 0;
823 for (int i = 0; i < operation.dst_extents_size(); i++) {
824 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200825 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700826 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
827 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
828 &buf[bytes_written],
829 bytes,
830 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200831 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700832 }
833 DCHECK_EQ(bytes_written, bytes_read);
834 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
835 return true;
836}
837
Allie Wood9f6f0a52015-03-30 11:25:47 -0700838namespace {
839
840// Takes |extents| and fills an empty vector |blocks| with a block index for
841// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
842void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
843 vector<uint64_t>* blocks) {
844 for (Extent ext : extents) {
845 for (uint64_t j = 0; j < ext.num_blocks(); j++)
846 blocks->push_back(ext.start_block() + j);
847 }
848}
849
850// Takes |extents| and returns the number of blocks in those extents.
851uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
852 uint64_t sum = 0;
853 for (Extent ext : extents) {
854 sum += ext.num_blocks();
855 }
856 return sum;
857}
858
859} // namespace
860
861bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700862 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700863 bool is_kernel_partition) {
864 if (operation.has_src_length())
865 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
866 if (operation.has_dst_length())
867 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
868
869 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
870 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
871 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
872
873 // Create vectors of all the individual src/dst blocks.
874 vector<uint64_t> src_blocks;
875 vector<uint64_t> dst_blocks;
876 ExtentsToBlocks(operation.src_extents(), &src_blocks);
877 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
878 DCHECK_EQ(src_blocks.size(), blocks_to_read);
879 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
880
881 FileDescriptorPtr src_fd =
882 is_kernel_partition ? source_kernel_fd_ : source_fd_;
883 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
884
885 chromeos::Blob buf(block_size_);
886 ssize_t bytes_read = 0;
887 // Read/write one block at a time.
888 for (uint64_t i = 0; i < blocks_to_read; i++) {
889 ssize_t bytes_read_this_iteration = 0;
890 uint64_t src_block = src_blocks[i];
891 uint64_t dst_block = dst_blocks[i];
892
893 // Read in bytes.
894 TEST_AND_RETURN_FALSE(
895 utils::PReadAll(src_fd,
896 buf.data(),
897 block_size_,
898 src_block * block_size_,
899 &bytes_read_this_iteration));
900
901 // Write bytes out.
902 TEST_AND_RETURN_FALSE(
903 utils::PWriteAll(dst_fd,
904 buf.data(),
905 block_size_,
906 dst_block * block_size_));
907
908 bytes_read += bytes_read_this_iteration;
909 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
910 static_cast<ssize_t>(block_size_));
911 }
912 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
913 return true;
914}
915
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700916bool DeltaPerformer::ExtentsToBsdiffPositionsString(
917 const RepeatedPtrField<Extent>& extents,
918 uint64_t block_size,
919 uint64_t full_length,
920 string* positions_string) {
921 string ret;
922 uint64_t length = 0;
923 for (int i = 0; i < extents.size(); i++) {
924 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700925 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700926 uint64_t this_length = min(full_length - length,
927 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700928 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700929 length += this_length;
930 }
931 TEST_AND_RETURN_FALSE(length == full_length);
932 if (!ret.empty())
933 ret.resize(ret.size() - 1); // Strip trailing comma off
934 *positions_string = ret;
935 return true;
936}
937
Alex Deymoa12ee112015-08-12 22:19:32 -0700938bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
939 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700940 // Since we delete data off the beginning of the buffer as we use it,
941 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700942 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
943 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700944
945 string input_positions;
946 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
947 block_size_,
948 operation.src_length(),
949 &input_positions));
950 string output_positions;
951 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
952 block_size_,
953 operation.dst_length(),
954 &output_positions));
955
956 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700957 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700958 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700959 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700960 ScopedPathUnlinker path_unlinker(temp_filename);
961 {
962 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
963 ScopedFdCloser fd_closer(&fd);
964 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800965 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700966 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700967
Darin Petkov7f2ec752013-04-03 14:45:19 +0200968 // Update the buffer to release the patch data memory as soon as the patch
969 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800970 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200971
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800972 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700973 vector<string> cmd{kBspatchPath, path, path, temp_filename,
974 input_positions, output_positions};
975
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700976 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700977 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700978 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
979 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700980 TEST_AND_RETURN_FALSE(return_code == 0);
981
982 if (operation.dst_length() % block_size_) {
983 // Zero out rest of final block.
984 // TODO(adlr): build this into bspatch; it's more efficient that way.
985 const Extent& last_extent =
986 operation.dst_extents(operation.dst_extents_size() - 1);
987 const uint64_t end_byte =
988 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
989 const uint64_t begin_byte =
990 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800991 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800992 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700993 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800994 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700995 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700996 return true;
997}
998
Allie Wood9f6f0a52015-03-30 11:25:47 -0700999bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -07001000 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -07001001 bool is_kernel_partition) {
1002 // Since we delete data off the beginning of the buffer as we use it,
1003 // the data we need should be exactly at the beginning of the buffer.
1004 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
1005 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
1006 if (operation.has_src_length())
1007 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
1008 if (operation.has_dst_length())
1009 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
1010
1011 string input_positions;
1012 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
1013 block_size_,
1014 operation.src_length(),
1015 &input_positions));
1016 string output_positions;
1017 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
1018 block_size_,
1019 operation.dst_length(),
1020 &output_positions));
1021
1022 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -07001023 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Allie Wood9f6f0a52015-03-30 11:25:47 -07001024 &temp_filename,
1025 nullptr));
1026 ScopedPathUnlinker path_unlinker(temp_filename);
1027 {
1028 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
1029 ScopedFdCloser fd_closer(&fd);
1030 TEST_AND_RETURN_FALSE(
1031 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
1032 }
1033
1034 // Update the buffer to release the patch data memory as soon as the patch
1035 // file is written out.
1036 DiscardBuffer(true);
1037
1038 const string& src_path = is_kernel_partition ?
1039 install_plan_->kernel_source_path :
1040 install_plan_->source_path;
1041 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
1042 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
1043 input_positions, output_positions};
1044
1045 int return_code = 0;
1046 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -07001047 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
1048 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001049 TEST_AND_RETURN_FALSE(return_code == 0);
1050 return true;
1051}
1052
Darin Petkovd7061ab2010-10-06 14:37:09 -07001053bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -07001054 const InstallOperation& operation) {
1055 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001056 !manifest_.has_signatures_offset() ||
1057 manifest_.signatures_offset() != operation.data_offset()) {
1058 return false;
1059 }
1060 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1061 manifest_.signatures_size() == operation.data_length());
1062 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1063 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1064 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001065 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001066 buffer_.begin(),
1067 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001068
1069 // Save the signature blob because if the update is interrupted after the
1070 // download phase we don't go through this path anymore. Some alternatives to
1071 // consider:
1072 //
1073 // 1. On resume, re-download the signature blob from the server and re-verify
1074 // it.
1075 //
1076 // 2. Verify the signature as soon as it's received and don't checkpoint the
1077 // blob and the signed sha-256 context.
1078 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001079 string(signatures_message_data_.begin(),
1080 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001081 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001082 // The hash of all data consumed so far should be verified against the signed
1083 // hash.
1084 signed_hash_context_ = hash_calculator_.GetContext();
1085 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1086 signed_hash_context_))
1087 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001088 LOG(INFO) << "Extracted signature data of size "
1089 << manifest_.signatures_size() << " at "
1090 << manifest_.signatures_offset();
1091 return true;
1092}
1093
David Zeuthene7f89172013-10-31 10:21:04 -07001094bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1095 if (system_state_->hardware()->IsOfficialBuild() ||
1096 utils::FileExists(public_key_path_.c_str()) ||
1097 install_plan_->public_key_rsa.empty())
1098 return false;
1099
1100 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1101 out_tmp_key))
1102 return false;
1103
1104 return true;
1105}
1106
David Zeuthena99981f2013-04-29 13:42:47 -07001107ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001108 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001109
Jay Srinivasanf4318702012-09-24 11:56:24 -07001110 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001111 if (install_plan_->hash_checks_mandatory) {
1112 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001113 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001114 }
1115
Jay Srinivasanf4318702012-09-24 11:56:24 -07001116 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001117 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001118 }
1119
1120 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001121 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001122 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001123 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001124 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1125 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001126 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001127 }
1128
David Zeuthene7f89172013-10-31 10:21:04 -07001129 // See if we should use the public RSA key in the Omaha response.
1130 base::FilePath path_to_public_key(public_key_path_);
1131 base::FilePath tmp_key;
1132 if (GetPublicKeyFromResponse(&tmp_key))
1133 path_to_public_key = tmp_key;
1134 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1135 if (tmp_key.empty())
1136 tmp_key_remover.set_should_remove(false);
1137
1138 LOG(INFO) << "Verifying metadata hash signature using public key: "
1139 << path_to_public_key.value();
1140
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001141 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001142 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1143 path_to_public_key.value(),
1144 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001145 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001146 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001147 }
1148
Jay Srinivasanf4318702012-09-24 11:56:24 -07001149 OmahaHashCalculator metadata_hasher;
1150 metadata_hasher.Update(metadata, metadata_size);
1151 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001152 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001153 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001154 }
1155
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001156 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001157 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001158 if (calculated_metadata_hash.empty()) {
1159 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001160 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001161 }
1162
Jay Srinivasanf4318702012-09-24 11:56:24 -07001163 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001164 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001165 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001166 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001167 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001168 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001169 }
1170
David Zeuthenbc27aac2013-11-26 11:17:48 -08001171 // The autoupdate_CatchBadSignatures test checks for this string in
1172 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001173 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001174 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001175}
1176
Gilad Arnold21504f02013-05-24 08:51:22 -07001177ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001178 // Perform assorted checks to sanity check the manifest, make sure it
1179 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001180 //
1181 // TODO(garnold) in general, the presence of an old partition hash should be
1182 // the sole indicator for a delta update, as we would generally like update
1183 // payloads to be self contained and not assume an Omaha response to tell us
1184 // that. However, since this requires some massive reengineering of the update
1185 // flow (making filesystem copying happen conditionally only *after*
1186 // downloading and parsing of the update manifest) we'll put it off for now.
1187 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001188 if (install_plan_->is_full_update) {
1189 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1190 LOG(ERROR) << "Purported full payload contains old partition "
1191 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001192 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001193 }
1194
1195 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1196 LOG(ERROR) << "Manifest contains minor version "
1197 << manifest_.minor_version()
1198 << ", but all full payloads should have version "
1199 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001200 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001201 }
1202 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001203 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001204 LOG(ERROR) << "Manifest contains minor version "
1205 << manifest_.minor_version()
1206 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001207 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001208 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001209 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001210 }
1211
1212 // TODO(garnold) we should be adding more and more manifest checks, such as
1213 // partition boundaries etc (see chromium-os:37661).
1214
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001215 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001216}
1217
David Zeuthena99981f2013-04-29 13:42:47 -07001218ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001219 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001220 if (!operation.data_sha256_hash().size()) {
1221 if (!operation.data_length()) {
1222 // Operations that do not have any data blob won't have any operation hash
1223 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001224 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001225 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001226 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001227 }
1228
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001229 // No hash is present for an operation that has data blobs. This shouldn't
1230 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001232 // hashes. So if it happens it means either we've turned operation hash
1233 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001234 // One caveat though: The last operation is a dummy signature operation
1235 // that doesn't have a hash at the time the manifest is created. So we
1236 // should not complaint about that operation. This operation can be
1237 // recognized by the fact that it's offset is mentioned in the manifest.
1238 if (manifest_.signatures_offset() &&
1239 manifest_.signatures_offset() == operation.data_offset()) {
1240 LOG(INFO) << "Skipping hash verification for signature operation "
1241 << next_operation_num_ + 1;
1242 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001243 if (install_plan_->hash_checks_mandatory) {
1244 LOG(ERROR) << "Missing mandatory operation hash for operation "
1245 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001246 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001247 }
1248
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001249 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1250 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001251 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001252 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001253 }
1254
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001255 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001256 expected_op_hash.assign(operation.data_sha256_hash().data(),
1257 (operation.data_sha256_hash().data() +
1258 operation.data_sha256_hash().size()));
1259
1260 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001261 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001262 if (!operation_hasher.Finalize()) {
1263 LOG(ERROR) << "Unable to compute actual hash of operation "
1264 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001266 }
1267
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001268 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001269 if (calculated_op_hash != expected_op_hash) {
1270 LOG(ERROR) << "Hash verification failed for operation "
1271 << next_operation_num_ << ". Expected hash = ";
1272 utils::HexDumpVector(expected_op_hash);
1273 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1274 << " bytes at offset: " << operation.data_offset() << " = ";
1275 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001276 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001277 }
1278
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001279 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001280}
1281
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001282#define TEST_AND_RETURN_VAL(_retval, _condition) \
1283 do { \
1284 if (!(_condition)) { \
1285 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1286 return _retval; \
1287 } \
1288 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001289
David Zeuthena99981f2013-04-29 13:42:47 -07001290ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001291 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001292 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001293
1294 // See if we should use the public RSA key in the Omaha response.
1295 base::FilePath path_to_public_key(public_key_path_);
1296 base::FilePath tmp_key;
1297 if (GetPublicKeyFromResponse(&tmp_key))
1298 path_to_public_key = tmp_key;
1299 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1300 if (tmp_key.empty())
1301 tmp_key_remover.set_should_remove(false);
1302
1303 LOG(INFO) << "Verifying payload using public key: "
1304 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001305
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001306 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001307 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001308 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001309 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001310
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001311 // Verifies the payload hash.
1312 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001313 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001314 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001315 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001316 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001317
Darin Petkov437adc42010-10-07 13:12:24 -07001318 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001319 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001320 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001321 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001322 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001323 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001324 !signatures_message_data_.empty());
Darin Petkov437adc42010-10-07 13:12:24 -07001325 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001326 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001327 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001328 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001329 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001330 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001331 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1332 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001333 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001334 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001335
1336 if (!PayloadVerifier::VerifySignature(
1337 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001338 // The autoupdate_CatchBadSignatures test checks for this string
1339 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001340 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001341 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001342 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001343
David Zeuthene7f89172013-10-31 10:21:04 -07001344 LOG(INFO) << "Payload hash matches value in payload.";
1345
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001346 // At this point, we are guaranteed to have downloaded a full payload, i.e
1347 // the one whose size matches the size mentioned in Omaha response. If any
1348 // errors happen after this, it's likely a problem with the payload itself or
1349 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001350 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001351 system_state_->payload_state()->DownloadComplete();
1352
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001353 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001354}
1355
Darin Petkov3aefa862010-12-07 14:45:00 -08001356bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001357 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001358 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001359 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001360 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1361 manifest_.has_new_kernel_info() &&
1362 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001363 *kernel_size = manifest_.new_kernel_info().size();
1364 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001365 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1366 manifest_.new_kernel_info().hash().end());
1367 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1368 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001369 kernel_hash->swap(new_kernel_hash);
1370 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001371 return true;
1372}
1373
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001374namespace {
1375void LogVerifyError(bool is_kern,
1376 const string& local_hash,
1377 const string& expected_hash) {
1378 const char* type = is_kern ? "kernel" : "rootfs";
1379 LOG(ERROR) << "This is a server-side error due to "
1380 << "mismatched delta update image!";
1381 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1382 << "update that must be applied over a " << type << " with "
1383 << "a specific checksum, but the " << type << " we're starting "
1384 << "with doesn't have that checksum! This means that "
1385 << "the delta I've been given doesn't match my existing "
1386 << "system. The " << type << " partition I have has hash: "
1387 << local_hash << " but the update expected me to have "
1388 << expected_hash << " .";
1389 if (is_kern) {
1390 LOG(INFO) << "To get the checksum of a kernel partition on a "
1391 << "booted machine, run this command (change /dev/sda2 "
1392 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1393 << "openssl dgst -sha256 -binary | openssl base64";
1394 } else {
1395 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1396 << "booted machine, run this command (change /dev/sda3 "
1397 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1398 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1399 << "| sed 's/[^0-9]*//') / 256 )) | "
1400 << "openssl dgst -sha256 -binary | openssl base64";
1401 }
1402 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1403 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1404}
1405
1406string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001407 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001408}
1409} // namespace
1410
Darin Petkov698d0412010-10-13 10:59:44 -07001411bool DeltaPerformer::VerifySourcePartitions() {
1412 LOG(INFO) << "Verifying source partitions.";
1413 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001414 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001415 if (manifest_.has_old_kernel_info()) {
1416 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001417 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001418 !install_plan_->source_kernel_hash.empty() &&
1419 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1420 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001421 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001422 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001423 if (!valid) {
1424 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001425 StringForHashBytes(
1426 install_plan_->source_kernel_hash.data(),
1427 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001428 StringForHashBytes(info.hash().data(),
1429 info.hash().size()));
1430 }
1431 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001432 }
1433 if (manifest_.has_old_rootfs_info()) {
1434 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001435 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001436 !install_plan_->source_rootfs_hash.empty() &&
1437 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1438 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001439 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001440 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001441 if (!valid) {
1442 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001443 StringForHashBytes(
1444 install_plan_->source_rootfs_hash.data(),
1445 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001446 StringForHashBytes(info.hash().data(),
1447 info.hash().size()));
1448 }
1449 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001450 }
1451 return true;
1452}
1453
Gilad Arnolddaa27402014-01-23 11:56:17 -08001454void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001455 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001456 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001457 buffer_offset_ += buffer_.size();
1458
1459 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001460 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001461
1462 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001463 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001464}
1465
Darin Petkov0406e402010-10-06 21:33:11 -07001466bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1467 string update_check_response_hash) {
1468 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001469 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1470 next_operation != kUpdateStateOperationInvalid &&
1471 next_operation > 0))
1472 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001473
1474 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001475 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1476 !interrupted_hash.empty() &&
1477 interrupted_hash == update_check_response_hash))
1478 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001479
Darin Petkov61426142010-10-08 11:04:55 -07001480 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001481 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1482 && resumed_update_failures > kMaxResumedUpdateFailures))
1483 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001484
Darin Petkov0406e402010-10-06 21:33:11 -07001485 // Sanity check the rest.
1486 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001487 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1488 next_data_offset >= 0))
1489 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001490
Darin Petkov437adc42010-10-07 13:12:24 -07001491 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001492 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1493 !sha256_context.empty()))
1494 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001495
1496 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001497 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1498 manifest_metadata_size > 0))
1499 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001500
1501 return true;
1502}
1503
Darin Petkov9b230572010-10-08 10:20:09 -07001504bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001505 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1506 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001507 if (!quick) {
1508 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1509 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001510 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001511 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1512 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001513 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001514 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001515 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001516 }
Darin Petkov73058b42010-10-06 16:32:19 -07001517 return true;
1518}
1519
1520bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001521 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001522 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001523 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001524 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001525 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001526 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001527 hash_calculator_.GetContext()));
1528 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1529 buffer_offset_));
1530 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001531
1532 if (next_operation_num_ < num_total_operations_) {
1533 const bool is_kernel_partition =
1534 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001535 const InstallOperation& op =
1536 is_kernel_partition
1537 ? manifest_.kernel_install_operations(next_operation_num_ -
1538 num_rootfs_operations_)
1539 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001540 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1541 op.data_length()));
1542 } else {
1543 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1544 0));
1545 }
Darin Petkov0406e402010-10-06 21:33:11 -07001546 }
Darin Petkov73058b42010-10-06 16:32:19 -07001547 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1548 next_operation_num_));
1549 return true;
1550}
1551
Darin Petkov9b230572010-10-08 10:20:09 -07001552bool DeltaPerformer::PrimeUpdateState() {
1553 CHECK(manifest_valid_);
1554 block_size_ = manifest_.block_size();
1555
1556 int64_t next_operation = kUpdateStateOperationInvalid;
1557 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1558 next_operation == kUpdateStateOperationInvalid ||
1559 next_operation <= 0) {
1560 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001561 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001562 return true;
1563 }
1564 next_operation_num_ = next_operation;
1565
1566 // Resuming an update -- load the rest of the update state.
1567 int64_t next_data_offset = -1;
1568 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1569 &next_data_offset) &&
1570 next_data_offset >= 0);
1571 buffer_offset_ = next_data_offset;
1572
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001573 // The signed hash context and the signature blob may be empty if the
1574 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001575 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1576 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001577 string signature_blob;
1578 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1579 signatures_message_data_.assign(signature_blob.begin(),
1580 signature_blob.end());
1581 }
Darin Petkov9b230572010-10-08 10:20:09 -07001582
1583 string hash_context;
1584 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1585 &hash_context) &&
1586 hash_calculator_.SetContext(hash_context));
1587
1588 int64_t manifest_metadata_size = 0;
1589 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1590 &manifest_metadata_size) &&
1591 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001592 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001593
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001594 // Advance the download progress to reflect what doesn't need to be
1595 // re-downloaded.
1596 total_bytes_received_ += buffer_offset_;
1597
Darin Petkov61426142010-10-08 11:04:55 -07001598 // Speculatively count the resume as a failure.
1599 int64_t resumed_update_failures;
1600 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1601 resumed_update_failures++;
1602 } else {
1603 resumed_update_failures = 1;
1604 }
1605 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001606 return true;
1607}
1608
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001609} // namespace chromeos_update_engine