blob: 4025b1fe9764aa7019c38ad05900a8af826352e3 [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>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include <algorithm>
23#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070024#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025#include <string>
26#include <vector>
27
Ben Chan06c76a42014-09-05 08:21:06 -070028#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070029#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070030#include <base/strings/string_util.h>
31#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080032#include <chromeos/data_encoding.h>
Alex Deymo05322872015-09-30 09:50:24 -070033#include <chromeos/make_unique_ptr.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034#include <google/protobuf/repeated_field.h>
35
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070036#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070037#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070039#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080040#if USE_MTD
41#include "update_engine/mtd_file_descriptor.h"
42#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070043#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080044#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070045#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070046#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070048#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070049#include "update_engine/update_attempter.h"
Alex Deymo2d621a32015-10-01 11:09:01 -070050#include "update_engine/xz_extent_writer.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070051
Alex Deymo161c4a12014-05-16 15:56:21 -070052using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070053using std::min;
54using std::string;
55using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070056
57namespace chromeos_update_engine {
58
Sen Jiangb8060e42015-09-24 17:30:50 -070059const uint64_t DeltaPerformer::kDeltaVersionOffset = sizeof(kDeltaMagic);
Jay Srinivasanf4318702012-09-24 11:56:24 -070060const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070061const uint64_t DeltaPerformer::kDeltaManifestSizeOffset =
62 kDeltaVersionOffset + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -070063const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Sen Jiangb8060e42015-09-24 17:30:50 -070064const uint64_t DeltaPerformer::kDeltaMetadataSignatureSizeSize = 4;
65const uint64_t DeltaPerformer::kMaxPayloadHeaderSize = 24;
Don Garrett4d039442013-10-28 18:40:06 -070066const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Allie Wood6eeec902015-04-15 10:40:52 -070067const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 2;
Don Garrett4d039442013-10-28 18:40:06 -070068
Gilad Arnold8a86fa52013-01-15 12:35:05 -080069const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
70const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
71const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
72const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080073
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070074namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070075const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070076const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080077#if USE_MTD
78const int kUbiVolumeAttachTimeout = 5 * 60;
79#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080080
81FileDescriptorPtr CreateFileDescriptor(const char* path) {
82 FileDescriptorPtr ret;
83#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080084 if (strstr(path, "/dev/ubi") == path) {
85 if (!UbiFileDescriptor::IsUbi(path)) {
86 // The volume might not have been attached at boot time.
87 int volume_no;
88 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
89 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
90 }
91 }
92 if (UbiFileDescriptor::IsUbi(path)) {
93 LOG(INFO) << path << " is a UBI device.";
94 ret.reset(new UbiFileDescriptor);
95 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080096 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080097 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080098 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080099 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800100 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800101#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800102 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800103#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700104 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800105#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800106 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700107}
108
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800109// Opens path for read/write. On success returns an open FileDescriptor
110// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
111FileDescriptorPtr OpenFile(const char* path, int* err) {
112 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800113 int mode = O_RDWR;
114#if USE_MTD
115 // On NAND devices, we can either read, or write, but not both. So here we
116 // use O_WRONLY.
117 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
118 mode = O_WRONLY;
119 }
120#endif
121 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800122 *err = errno;
123 PLOG(ERROR) << "Unable to open file " << path;
124 return nullptr;
125 }
126 *err = 0;
127 return fd;
128}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700129} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800131
132// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
133// arithmetic.
134static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
135 return part * norm / total;
136}
137
138void DeltaPerformer::LogProgress(const char* message_prefix) {
139 // Format operations total count and percentage.
140 string total_operations_str("?");
141 string completed_percentage_str("");
142 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700143 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800144 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
145 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700146 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700147 IntRatio(next_operation_num_, num_total_operations_,
148 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800149 }
150
151 // Format download total count and percentage.
152 size_t payload_size = install_plan_->payload_size;
153 string payload_size_str("?");
154 string downloaded_percentage_str("");
155 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700156 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800157 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
158 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700159 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700160 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800161 }
162
163 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
164 << "/" << total_operations_str << " operations"
165 << completed_percentage_str << ", " << total_bytes_received_
166 << "/" << payload_size_str << " bytes downloaded"
167 << downloaded_percentage_str << ", overall progress "
168 << overall_progress_ << "%";
169}
170
171void DeltaPerformer::UpdateOverallProgress(bool force_log,
172 const char* message_prefix) {
173 // Compute our download and overall progress.
174 unsigned new_overall_progress = 0;
175 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
176 progress_weight_dont_add_up);
177 // Only consider download progress if its total size is known; otherwise
178 // adjust the operations weight to compensate for the absence of download
179 // progress. Also, make sure to cap the download portion at
180 // kProgressDownloadWeight, in case we end up downloading more than we
181 // initially expected (this indicates a problem, but could generally happen).
182 // TODO(garnold) the correction of operations weight when we do not have the
183 // total payload size, as well as the conditional guard below, should both be
184 // eliminated once we ensure that the payload_size in the install plan is
185 // always given and is non-zero. This currently isn't the case during unit
186 // tests (see chromium-os:37969).
187 size_t payload_size = install_plan_->payload_size;
188 unsigned actual_operations_weight = kProgressOperationsWeight;
189 if (payload_size)
190 new_overall_progress += min(
191 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
192 kProgressDownloadWeight)),
193 kProgressDownloadWeight);
194 else
195 actual_operations_weight += kProgressDownloadWeight;
196
197 // Only add completed operations if their total number is known; we definitely
198 // expect an update to have at least one operation, so the expectation is that
199 // this will eventually reach |actual_operations_weight|.
200 if (num_total_operations_)
201 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
202 actual_operations_weight);
203
204 // Progress ratio cannot recede, unless our assumptions about the total
205 // payload size, total number of operations, or the monotonicity of progress
206 // is breached.
207 if (new_overall_progress < overall_progress_) {
208 LOG(WARNING) << "progress counter receded from " << overall_progress_
209 << "% down to " << new_overall_progress << "%; this is a bug";
210 force_log = true;
211 }
212 overall_progress_ = new_overall_progress;
213
214 // Update chunk index, log as needed: if forced by called, or we completed a
215 // progress chunk, or a timeout has expired.
216 base::Time curr_time = base::Time::Now();
217 unsigned curr_progress_chunk =
218 overall_progress_ * kProgressLogMaxChunks / 100;
219 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
220 curr_time > forced_progress_log_time_) {
221 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
222 LogProgress(message_prefix);
223 }
224 last_progress_chunk_ = curr_progress_chunk;
225}
226
227
Gilad Arnoldfe133932014-01-14 12:25:50 -0800228size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
229 size_t max) {
230 const size_t count = *count_p;
231 if (!count)
232 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700233 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800234 const char* bytes_start = *bytes_p;
235 const char* bytes_end = bytes_start + read_len;
236 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
237 *bytes_p = bytes_end;
238 *count_p = count - read_len;
239 return read_len;
240}
241
242
243bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
244 ErrorCode* error) {
245 if (op_result)
246 return true;
247
248 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
249 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700250 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800251 return false;
252}
253
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700254int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700255 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800256 fd_ = OpenFile(path, &err);
257 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700258 path_ = path;
259 return -err;
260}
261
262bool DeltaPerformer::OpenKernel(const char* kernel_path) {
263 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800264 kernel_fd_ = OpenFile(kernel_path, &err);
265 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700266 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800267 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268}
269
Alex Deymo1beda782015-06-07 23:01:25 +0200270bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800271 int err;
272 source_fd_ = OpenFile(source_path.c_str(), &err);
273 return static_cast<bool>(source_fd_);
274}
275
Alex Deymo1beda782015-06-07 23:01:25 +0200276bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800277 int err;
278 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
279 return static_cast<bool>(source_kernel_fd_);
280}
281
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700282int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700283 int err = 0;
Sen Jiang2d528b42015-09-25 11:18:12 -0700284 if (kernel_fd_ && !kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700285 err = errno;
286 PLOG(ERROR) << "Unable to close kernel fd:";
287 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800288 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700289 err = errno;
290 PLOG(ERROR) << "Unable to close rootfs fd:";
291 }
Allie Woodfdf00512015-03-02 13:34:55 -0800292 if (source_fd_ && !source_fd_->Close()) {
293 err = errno;
294 PLOG(ERROR) << "Unable to close source rootfs fd:";
295 }
296 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
297 err = errno;
298 PLOG(ERROR) << "Unable to close source kernel fd:";
299 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700300 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800301 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800302 kernel_fd_.reset();
303 source_fd_.reset();
304 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700305 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800306 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700307 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
308 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800309 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800310 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700311 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700312}
313
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700314namespace {
315
316void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800317 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800318 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
319 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700320}
321
322void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
323 if (manifest.has_old_kernel_info())
324 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
325 if (manifest.has_old_rootfs_info())
326 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
327 if (manifest.has_new_kernel_info())
328 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
329 if (manifest.has_new_rootfs_info())
330 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
331}
332
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700333} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700334
Sen Jiangb8060e42015-09-24 17:30:50 -0700335bool DeltaPerformer::GetMetadataSignatureSizeOffset(
336 uint64_t* out_offset) const {
337 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
338 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
339 return true;
340 }
341 return false;
Don Garrett4d039442013-10-28 18:40:06 -0700342}
343
Sen Jiangb8060e42015-09-24 17:30:50 -0700344bool DeltaPerformer::GetManifestOffset(uint64_t* out_offset) const {
345 // Actual manifest begins right after the manifest size field or
346 // metadata signature size field if major version >= 2.
347 if (major_payload_version_ == kChromeOSMajorPayloadVersion) {
348 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize;
349 return true;
350 }
351 if (major_payload_version_ == kBrilloMajorPayloadVersion) {
352 *out_offset = kDeltaManifestSizeOffset + kDeltaManifestSizeSize +
353 kDeltaMetadataSignatureSizeSize;
354 return true;
355 }
356 LOG(ERROR) << "Unknown major payload version: " << major_payload_version_;
357 return false;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700358}
359
Gilad Arnoldfe133932014-01-14 12:25:50 -0800360uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800361 return metadata_size_;
362}
363
Sen Jiangb8060e42015-09-24 17:30:50 -0700364uint64_t DeltaPerformer::GetMajorVersion() const {
365 return major_payload_version_;
366}
367
Allie Woodfdf00512015-03-02 13:34:55 -0800368uint32_t DeltaPerformer::GetMinorVersion() const {
369 if (manifest_.has_minor_version()) {
370 return manifest_.minor_version();
371 } else {
372 return (install_plan_->is_full_update ?
373 kFullPayloadMinorVersion :
374 kSupportedMinorPayloadVersion);
375 }
376}
377
Gilad Arnolddaa27402014-01-23 11:56:17 -0800378bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
379 if (!manifest_parsed_)
380 return false;
381 *out_manifest_p = manifest_;
382 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800383}
384
Sen Jiangb8060e42015-09-24 17:30:50 -0700385bool DeltaPerformer::IsHeaderParsed() const {
386 return metadata_size_ != 0;
387}
Jay Srinivasanf4318702012-09-24 11:56:24 -0700388
Darin Petkov9574f7e2011-01-13 10:48:12 -0800389DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800390 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700391 *error = ErrorCode::kSuccess;
Sen Jiangb8060e42015-09-24 17:30:50 -0700392 uint64_t manifest_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700393
Sen Jiangb8060e42015-09-24 17:30:50 -0700394 if (!IsHeaderParsed()) {
395 // Ensure we have data to cover the major payload version.
396 if (payload.size() < kDeltaManifestSizeOffset)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800397 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700398
Gilad Arnoldfe133932014-01-14 12:25:50 -0800399 // Validate the magic string.
Sen Jiangb8060e42015-09-24 17:30:50 -0700400 if (memcmp(payload.data(), kDeltaMagic, sizeof(kDeltaMagic)) != 0) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800401 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700402 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800403 return kMetadataParseError;
404 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800405
406 // Extract the payload version from the metadata.
Sen Jiangb8060e42015-09-24 17:30:50 -0700407 COMPILE_ASSERT(sizeof(major_payload_version_) == kDeltaVersionSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800408 major_payload_version_size_mismatch);
Sen Jiangb8060e42015-09-24 17:30:50 -0700409 memcpy(&major_payload_version_,
410 &payload[kDeltaVersionOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800411 kDeltaVersionSize);
412 // switch big endian to host
Sen Jiangb8060e42015-09-24 17:30:50 -0700413 major_payload_version_ = be64toh(major_payload_version_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800414
Sen Jiangb8060e42015-09-24 17:30:50 -0700415 if (major_payload_version_ != supported_major_version_) {
Gilad Arnoldfe133932014-01-14 12:25:50 -0800416 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
Sen Jiangb8060e42015-09-24 17:30:50 -0700417 << major_payload_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700418 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800419 return kMetadataParseError;
420 }
421
Sen Jiangb8060e42015-09-24 17:30:50 -0700422 // Get the manifest offset now that we have payload version.
423 if (!GetManifestOffset(&manifest_offset)) {
424 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
425 return kMetadataParseError;
426 }
427 // Check again with the manifest offset.
428 if (payload.size() < manifest_offset)
429 return kMetadataParseInsufficientData;
430
Gilad Arnoldfe133932014-01-14 12:25:50 -0800431 // Next, parse the manifest size.
Sen Jiangb8060e42015-09-24 17:30:50 -0700432 COMPILE_ASSERT(sizeof(manifest_size_) == kDeltaManifestSizeSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800433 manifest_size_size_mismatch);
Sen Jiangb8060e42015-09-24 17:30:50 -0700434 memcpy(&manifest_size_,
435 &payload[kDeltaManifestSizeOffset],
Gilad Arnoldfe133932014-01-14 12:25:50 -0800436 kDeltaManifestSizeSize);
Sen Jiangb8060e42015-09-24 17:30:50 -0700437 manifest_size_ = be64toh(manifest_size_); // switch big endian to host
438
439 uint32_t metadata_signature_size = 0;
440 if (GetMajorVersion() == kBrilloMajorPayloadVersion) {
441 // Parse the metadata signature size.
442 COMPILE_ASSERT(sizeof(metadata_signature_size) ==
443 kDeltaMetadataSignatureSizeSize,
444 metadata_signature_size_size_mismatch);
445 uint64_t metadata_signature_size_offset;
446 if (!GetMetadataSignatureSizeOffset(&metadata_signature_size_offset)) {
447 *error = ErrorCode::kError;
448 return kMetadataParseError;
449 }
450 memcpy(&metadata_signature_size,
451 &payload[metadata_signature_size_offset],
452 kDeltaMetadataSignatureSizeSize);
453 metadata_signature_size = be32toh(metadata_signature_size);
454 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800455
456 // If the metadata size is present in install plan, check for it immediately
457 // even before waiting for that many number of bytes to be downloaded in the
458 // payload. This will prevent any attack which relies on us downloading data
459 // beyond the expected metadata size.
Sen Jiangb8060e42015-09-24 17:30:50 -0700460 metadata_size_ = manifest_offset + manifest_size_ + metadata_signature_size;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800461 if (install_plan_->hash_checks_mandatory) {
462 if (install_plan_->metadata_size != metadata_size_) {
463 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
464 << install_plan_->metadata_size
465 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700466 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800467 return kMetadataParseError;
468 }
469 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700470 }
471
472 // Now that we have validated the metadata size, we should wait for the full
473 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800474 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800475 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700476
477 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700478 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700479 // that we just log once (instead of logging n times) if it takes n
480 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800481 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700482 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800483 } else {
484 // For mandatory-cases, we'd have already returned a kMetadataParseError
485 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
486 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
487 << install_plan_->metadata_size
488 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800489 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800490 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700491
Jay Srinivasanf4318702012-09-24 11:56:24 -0700492 // We have the full metadata in |payload|. Verify its integrity
493 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800494 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700495 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800496 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800497 // The autoupdate_CatchBadSignatures test checks for this string
498 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800499 LOG(ERROR) << "Mandatory metadata signature validation failed";
500 return kMetadataParseError;
501 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700502
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800503 // For non-mandatory cases, just send a UMA stat.
504 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700505 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700506 }
507
Sen Jiangb8060e42015-09-24 17:30:50 -0700508 if (!GetManifestOffset(&manifest_offset)) {
509 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
510 return kMetadataParseError;
511 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800512 // The payload metadata is deemed valid, it's safe to parse the protobuf.
Sen Jiangb8060e42015-09-24 17:30:50 -0700513 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size_)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800514 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700515 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800516 return kMetadataParseError;
517 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800518
519 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800520 return kMetadataParseSuccess;
521}
522
Don Garrette410e0f2011-11-10 15:39:01 -0800523// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800524// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700525// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800526bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700527 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700528
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700529 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800530 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800531
532 // Update the total byte downloaded count and the progress logs.
533 total_bytes_received_ += count;
534 UpdateOverallProgress(false, "Completed ");
535
Gilad Arnoldfe133932014-01-14 12:25:50 -0800536 while (!manifest_valid_) {
Sen Jiangb8060e42015-09-24 17:30:50 -0700537 // Read data up to the needed limit; this is either maximium payload header
538 // size, or the full metadata size (once it becomes known).
539 const bool do_read_header = !IsHeaderParsed();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800540 CopyDataToBuffer(&c_bytes, &count,
Sen Jiangb8060e42015-09-24 17:30:50 -0700541 (do_read_header ? kMaxPayloadHeaderSize :
Gilad Arnoldfe133932014-01-14 12:25:50 -0800542 metadata_size_));
543
Gilad Arnolddaa27402014-01-23 11:56:17 -0800544 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700545 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800546 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800547 if (result == kMetadataParseInsufficientData) {
548 // If we just processed the header, make an attempt on the manifest.
Sen Jiangb8060e42015-09-24 17:30:50 -0700549 if (do_read_header && IsHeaderParsed())
Gilad Arnoldfe133932014-01-14 12:25:50 -0800550 continue;
551
Don Garrette410e0f2011-11-10 15:39:01 -0800552 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800553 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700554
555 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700556 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700557 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800558 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700559
Gilad Arnoldfe133932014-01-14 12:25:50 -0800560 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800561 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700562 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800563 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700564 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700565
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700566 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700567 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700568 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700569 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800570 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700571 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800572
Allie Woodfdf00512015-03-02 13:34:55 -0800573 // Open source fds if we have a delta payload with minor version 2.
574 if (!install_plan_->is_full_update &&
575 GetMinorVersion() == kSourceMinorPayloadVersion) {
576 if (!OpenSourceRootfs(install_plan_->source_path)) {
577 LOG(ERROR) << "Unable to open source rootfs partition file "
578 << install_plan_->source_path;
579 Close();
580 return false;
581 }
582 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
583 LOG(ERROR) << "Unable to open source kernel partition file "
584 << install_plan_->kernel_source_path;
585 Close();
586 return false;
587 }
588 }
589
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800590 num_rootfs_operations_ = manifest_.install_operations_size();
591 num_total_operations_ =
592 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
593 if (next_operation_num_ > 0)
594 UpdateOverallProgress(true, "Resuming after ");
595 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700596 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800597
598 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700599 // Check if we should cancel the current attempt for any reason.
600 // In this case, *error will have already been populated with the reason
601 // why we're cancelling.
602 if (system_state_->update_attempter()->ShouldCancel(error))
603 return false;
604
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800605 const bool is_kernel_partition =
606 (next_operation_num_ >= num_rootfs_operations_);
Alex Deymoa12ee112015-08-12 22:19:32 -0700607 const InstallOperation& op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800608 is_kernel_partition ?
Alex Deymoa12ee112015-08-12 22:19:32 -0700609 manifest_.kernel_install_operations(next_operation_num_ -
610 num_rootfs_operations_) :
611 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800612
613 CopyDataToBuffer(&c_bytes, &count, op.data_length());
614
615 // Check whether we received all of the next operation's data payload.
616 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700617 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700618
Jay Srinivasanf4318702012-09-24 11:56:24 -0700619 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700620 // Otherwise, keep the old behavior. This serves as a knob to disable
621 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800622 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
623 // we would have already failed in ParsePayloadMetadata method and thus not
624 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700625 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700626 // Note: Validate must be called only if CanPerformInstallOperation is
627 // called. Otherwise, we might be failing operations before even if there
628 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800629 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700630 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800631 if (install_plan_->hash_checks_mandatory) {
632 LOG(ERROR) << "Mandatory operation hash check failed";
633 return false;
634 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700635
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800636 // For non-mandatory cases, just send a UMA stat.
637 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700638 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700639 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700640 }
641
Darin Petkov45580e42010-10-08 14:02:40 -0700642 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700643 ScopedTerminatorExitUnblocker exit_unblocker =
644 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800645
646 bool op_result;
Alex Deymo2d621a32015-10-01 11:09:01 -0700647 switch (op.type()) {
648 case InstallOperation::REPLACE:
649 case InstallOperation::REPLACE_BZ:
650 case InstallOperation::REPLACE_XZ:
651 op_result = PerformReplaceOperation(op, is_kernel_partition);
652 break;
653 case InstallOperation::MOVE:
654 op_result = PerformMoveOperation(op, is_kernel_partition);
655 break;
656 case InstallOperation::BSDIFF:
657 op_result = PerformBsdiffOperation(op, is_kernel_partition);
658 break;
659 case InstallOperation::SOURCE_COPY:
660 op_result = PerformSourceCopyOperation(op, is_kernel_partition);
661 break;
662 case InstallOperation::SOURCE_BSDIFF:
663 op_result = PerformSourceBsdiffOperation(op, is_kernel_partition);
664 break;
665 default:
666 op_result = false;
667 }
668 if (!HandleOpResult(op_result, InstallOperationTypeName(op.type()), error))
Gilad Arnoldfe133932014-01-14 12:25:50 -0800669 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800670
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700671 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800672 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700673 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700674 }
Don Garrette410e0f2011-11-10 15:39:01 -0800675 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700676}
677
David Zeuthen8f191b22013-08-06 12:27:50 -0700678bool DeltaPerformer::IsManifestValid() {
679 return manifest_valid_;
680}
681
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700682bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700683 const chromeos_update_engine::InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700684 // Move and source_copy operations don't require any data blob, so they can
685 // always be performed.
Alex Deymoa12ee112015-08-12 22:19:32 -0700686 if (operation.type() == InstallOperation::MOVE ||
687 operation.type() == InstallOperation::SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700688 return true;
689
690 // See if we have the entire data blob in the buffer
691 if (operation.data_offset() < buffer_offset_) {
692 LOG(ERROR) << "we threw away data it seems?";
693 return false;
694 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700695
Gilad Arnoldfe133932014-01-14 12:25:50 -0800696 return (operation.data_offset() + operation.data_length() <=
697 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700698}
699
Alex Deymoa12ee112015-08-12 22:19:32 -0700700bool DeltaPerformer::PerformReplaceOperation(const InstallOperation& operation,
701 bool is_kernel_partition) {
702 CHECK(operation.type() == InstallOperation::REPLACE ||
Alex Deymo2d621a32015-10-01 11:09:01 -0700703 operation.type() == InstallOperation::REPLACE_BZ ||
704 operation.type() == InstallOperation::REPLACE_XZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700705
706 // Since we delete data off the beginning of the buffer as we use it,
707 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700708 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
709 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700710
Darin Petkov437adc42010-10-07 13:12:24 -0700711 // Extract the signature message if it's in this operation.
712 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700713
Alex Deymo05322872015-09-30 09:50:24 -0700714 // Setup the ExtentWriter stack based on the operation type.
715 std::unique_ptr<ExtentWriter> writer =
716 chromeos::make_unique_ptr(new ZeroPadExtentWriter(
717 chromeos::make_unique_ptr(new DirectExtentWriter())));
Darin Petkovd7061ab2010-10-06 14:37:09 -0700718
Alex Deymo2d621a32015-10-01 11:09:01 -0700719 if (operation.type() == InstallOperation::REPLACE_BZ) {
Alex Deymo05322872015-09-30 09:50:24 -0700720 writer.reset(new BzipExtentWriter(std::move(writer)));
Alex Deymo2d621a32015-10-01 11:09:01 -0700721 } else if (operation.type() == InstallOperation::REPLACE_XZ) {
722 writer.reset(new XzExtentWriter(std::move(writer)));
723 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700724
725 // Create a vector of extents to pass to the ExtentWriter.
726 vector<Extent> extents;
727 for (int i = 0; i < operation.dst_extents_size(); i++) {
728 extents.push_back(operation.dst_extents(i));
729 }
730
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800731 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700732
733 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800734 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700735 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700736
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700737 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800738 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700739 return true;
740}
741
Alex Deymoa12ee112015-08-12 22:19:32 -0700742bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
743 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700744 // Calculate buffer size. Note, this function doesn't do a sliding
745 // window to copy in case the source and destination blocks overlap.
746 // If we wanted to do a sliding window, we could program the server
747 // to generate deltas that effectively did a sliding window.
748
749 uint64_t blocks_to_read = 0;
750 for (int i = 0; i < operation.src_extents_size(); i++)
751 blocks_to_read += operation.src_extents(i).num_blocks();
752
753 uint64_t blocks_to_write = 0;
754 for (int i = 0; i < operation.dst_extents_size(); i++)
755 blocks_to_write += operation.dst_extents(i).num_blocks();
756
757 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800758 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700759
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800760 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700761
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700762 // Read in bytes.
763 ssize_t bytes_read = 0;
764 for (int i = 0; i < operation.src_extents_size(); i++) {
765 ssize_t bytes_read_this_iteration = 0;
766 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200767 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700768 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
769 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
770 &buf[bytes_read],
771 bytes,
772 extent.start_block() * block_size_,
773 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700774 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200775 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700776 bytes_read += bytes_read_this_iteration;
777 }
778
779 // Write bytes out.
780 ssize_t bytes_written = 0;
781 for (int i = 0; i < operation.dst_extents_size(); i++) {
782 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200783 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700784 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
785 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
786 &buf[bytes_written],
787 bytes,
788 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200789 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700790 }
791 DCHECK_EQ(bytes_written, bytes_read);
792 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
793 return true;
794}
795
Allie Wood9f6f0a52015-03-30 11:25:47 -0700796namespace {
797
798// Takes |extents| and fills an empty vector |blocks| with a block index for
799// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
800void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
801 vector<uint64_t>* blocks) {
802 for (Extent ext : extents) {
803 for (uint64_t j = 0; j < ext.num_blocks(); j++)
804 blocks->push_back(ext.start_block() + j);
805 }
806}
807
808// Takes |extents| and returns the number of blocks in those extents.
809uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
810 uint64_t sum = 0;
811 for (Extent ext : extents) {
812 sum += ext.num_blocks();
813 }
814 return sum;
815}
816
817} // namespace
818
819bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700820 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700821 bool is_kernel_partition) {
822 if (operation.has_src_length())
823 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
824 if (operation.has_dst_length())
825 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
826
827 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
828 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
829 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
830
831 // Create vectors of all the individual src/dst blocks.
832 vector<uint64_t> src_blocks;
833 vector<uint64_t> dst_blocks;
834 ExtentsToBlocks(operation.src_extents(), &src_blocks);
835 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
836 DCHECK_EQ(src_blocks.size(), blocks_to_read);
837 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
838
839 FileDescriptorPtr src_fd =
840 is_kernel_partition ? source_kernel_fd_ : source_fd_;
841 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
842
843 chromeos::Blob buf(block_size_);
844 ssize_t bytes_read = 0;
845 // Read/write one block at a time.
846 for (uint64_t i = 0; i < blocks_to_read; i++) {
847 ssize_t bytes_read_this_iteration = 0;
848 uint64_t src_block = src_blocks[i];
849 uint64_t dst_block = dst_blocks[i];
850
851 // Read in bytes.
852 TEST_AND_RETURN_FALSE(
853 utils::PReadAll(src_fd,
854 buf.data(),
855 block_size_,
856 src_block * block_size_,
857 &bytes_read_this_iteration));
858
859 // Write bytes out.
860 TEST_AND_RETURN_FALSE(
861 utils::PWriteAll(dst_fd,
862 buf.data(),
863 block_size_,
864 dst_block * block_size_));
865
866 bytes_read += bytes_read_this_iteration;
867 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
868 static_cast<ssize_t>(block_size_));
869 }
870 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
871 return true;
872}
873
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700874bool DeltaPerformer::ExtentsToBsdiffPositionsString(
875 const RepeatedPtrField<Extent>& extents,
876 uint64_t block_size,
877 uint64_t full_length,
878 string* positions_string) {
879 string ret;
880 uint64_t length = 0;
881 for (int i = 0; i < extents.size(); i++) {
882 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700883 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700884 uint64_t this_length = min(full_length - length,
885 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700886 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700887 length += this_length;
888 }
889 TEST_AND_RETURN_FALSE(length == full_length);
890 if (!ret.empty())
891 ret.resize(ret.size() - 1); // Strip trailing comma off
892 *positions_string = ret;
893 return true;
894}
895
Alex Deymoa12ee112015-08-12 22:19:32 -0700896bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
897 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700898 // Since we delete data off the beginning of the buffer as we use it,
899 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700900 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
901 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700902
903 string input_positions;
904 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
905 block_size_,
906 operation.src_length(),
907 &input_positions));
908 string output_positions;
909 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
910 block_size_,
911 operation.dst_length(),
912 &output_positions));
913
914 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700915 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700916 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700917 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700918 ScopedPathUnlinker path_unlinker(temp_filename);
919 {
920 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
921 ScopedFdCloser fd_closer(&fd);
922 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800923 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700924 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700925
Darin Petkov7f2ec752013-04-03 14:45:19 +0200926 // Update the buffer to release the patch data memory as soon as the patch
927 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800928 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200929
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800930 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700931 vector<string> cmd{kBspatchPath, path, path, temp_filename,
932 input_positions, output_positions};
933
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700934 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700935 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700936 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
937 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700938 TEST_AND_RETURN_FALSE(return_code == 0);
939
940 if (operation.dst_length() % block_size_) {
941 // Zero out rest of final block.
942 // TODO(adlr): build this into bspatch; it's more efficient that way.
943 const Extent& last_extent =
944 operation.dst_extents(operation.dst_extents_size() - 1);
945 const uint64_t end_byte =
946 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
947 const uint64_t begin_byte =
948 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800949 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800950 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700951 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800952 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700953 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700954 return true;
955}
956
Allie Wood9f6f0a52015-03-30 11:25:47 -0700957bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700958 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700959 bool is_kernel_partition) {
960 // Since we delete data off the beginning of the buffer as we use it,
961 // the data we need should be exactly at the beginning of the buffer.
962 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
963 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
964 if (operation.has_src_length())
965 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
966 if (operation.has_dst_length())
967 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
968
969 string input_positions;
970 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
971 block_size_,
972 operation.src_length(),
973 &input_positions));
974 string output_positions;
975 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
976 block_size_,
977 operation.dst_length(),
978 &output_positions));
979
980 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700981 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Allie Wood9f6f0a52015-03-30 11:25:47 -0700982 &temp_filename,
983 nullptr));
984 ScopedPathUnlinker path_unlinker(temp_filename);
985 {
986 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
987 ScopedFdCloser fd_closer(&fd);
988 TEST_AND_RETURN_FALSE(
989 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
990 }
991
992 // Update the buffer to release the patch data memory as soon as the patch
993 // file is written out.
994 DiscardBuffer(true);
995
996 const string& src_path = is_kernel_partition ?
997 install_plan_->kernel_source_path :
998 install_plan_->source_path;
999 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
1000 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
1001 input_positions, output_positions};
1002
1003 int return_code = 0;
1004 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -07001005 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
1006 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -07001007 TEST_AND_RETURN_FALSE(return_code == 0);
1008 return true;
1009}
1010
Darin Petkovd7061ab2010-10-06 14:37:09 -07001011bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -07001012 const InstallOperation& operation) {
1013 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -07001014 !manifest_.has_signatures_offset() ||
1015 manifest_.signatures_offset() != operation.data_offset()) {
1016 return false;
1017 }
1018 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1019 manifest_.signatures_size() == operation.data_length());
1020 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1021 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1022 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001023 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001024 buffer_.begin(),
1025 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001026
1027 // Save the signature blob because if the update is interrupted after the
1028 // download phase we don't go through this path anymore. Some alternatives to
1029 // consider:
1030 //
1031 // 1. On resume, re-download the signature blob from the server and re-verify
1032 // it.
1033 //
1034 // 2. Verify the signature as soon as it's received and don't checkpoint the
1035 // blob and the signed sha-256 context.
1036 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001037 string(signatures_message_data_.begin(),
1038 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001039 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001040 // The hash of all data consumed so far should be verified against the signed
1041 // hash.
1042 signed_hash_context_ = hash_calculator_.GetContext();
1043 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1044 signed_hash_context_))
1045 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001046 LOG(INFO) << "Extracted signature data of size "
1047 << manifest_.signatures_size() << " at "
1048 << manifest_.signatures_offset();
1049 return true;
1050}
1051
David Zeuthene7f89172013-10-31 10:21:04 -07001052bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1053 if (system_state_->hardware()->IsOfficialBuild() ||
1054 utils::FileExists(public_key_path_.c_str()) ||
1055 install_plan_->public_key_rsa.empty())
1056 return false;
1057
1058 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1059 out_tmp_key))
1060 return false;
1061
1062 return true;
1063}
1064
David Zeuthena99981f2013-04-29 13:42:47 -07001065ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001066 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001067
Jay Srinivasanf4318702012-09-24 11:56:24 -07001068 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001069 if (install_plan_->hash_checks_mandatory) {
1070 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001071 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001072 }
1073
Jay Srinivasanf4318702012-09-24 11:56:24 -07001074 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001075 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001076 }
1077
1078 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001079 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001080 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001081 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001082 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1083 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001085 }
1086
David Zeuthene7f89172013-10-31 10:21:04 -07001087 // See if we should use the public RSA key in the Omaha response.
1088 base::FilePath path_to_public_key(public_key_path_);
1089 base::FilePath tmp_key;
1090 if (GetPublicKeyFromResponse(&tmp_key))
1091 path_to_public_key = tmp_key;
1092 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1093 if (tmp_key.empty())
1094 tmp_key_remover.set_should_remove(false);
1095
1096 LOG(INFO) << "Verifying metadata hash signature using public key: "
1097 << path_to_public_key.value();
1098
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001099 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001100 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1101 path_to_public_key.value(),
1102 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001103 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001105 }
1106
Jay Srinivasanf4318702012-09-24 11:56:24 -07001107 OmahaHashCalculator metadata_hasher;
1108 metadata_hasher.Update(metadata, metadata_size);
1109 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001110 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001111 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001112 }
1113
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001114 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001115 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001116 if (calculated_metadata_hash.empty()) {
1117 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001119 }
1120
Jay Srinivasanf4318702012-09-24 11:56:24 -07001121 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001122 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001123 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001124 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001125 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001126 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001127 }
1128
David Zeuthenbc27aac2013-11-26 11:17:48 -08001129 // The autoupdate_CatchBadSignatures test checks for this string in
1130 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001131 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001132 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001133}
1134
Gilad Arnold21504f02013-05-24 08:51:22 -07001135ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001136 // Perform assorted checks to sanity check the manifest, make sure it
1137 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001138 //
1139 // TODO(garnold) in general, the presence of an old partition hash should be
1140 // the sole indicator for a delta update, as we would generally like update
1141 // payloads to be self contained and not assume an Omaha response to tell us
1142 // that. However, since this requires some massive reengineering of the update
1143 // flow (making filesystem copying happen conditionally only *after*
1144 // downloading and parsing of the update manifest) we'll put it off for now.
1145 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001146 if (install_plan_->is_full_update) {
1147 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1148 LOG(ERROR) << "Purported full payload contains old partition "
1149 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001150 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001151 }
1152
1153 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1154 LOG(ERROR) << "Manifest contains minor version "
1155 << manifest_.minor_version()
1156 << ", but all full payloads should have version "
1157 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001158 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001159 }
1160 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001161 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001162 LOG(ERROR) << "Manifest contains minor version "
1163 << manifest_.minor_version()
1164 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001165 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001166 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001167 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001168 }
1169
1170 // TODO(garnold) we should be adding more and more manifest checks, such as
1171 // partition boundaries etc (see chromium-os:37661).
1172
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001173 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001174}
1175
David Zeuthena99981f2013-04-29 13:42:47 -07001176ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001177 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001178 if (!operation.data_sha256_hash().size()) {
1179 if (!operation.data_length()) {
1180 // Operations that do not have any data blob won't have any operation hash
1181 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001182 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001183 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001184 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001185 }
1186
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001187 // No hash is present for an operation that has data blobs. This shouldn't
1188 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001189 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001190 // hashes. So if it happens it means either we've turned operation hash
1191 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001192 // One caveat though: The last operation is a dummy signature operation
1193 // that doesn't have a hash at the time the manifest is created. So we
1194 // should not complaint about that operation. This operation can be
1195 // recognized by the fact that it's offset is mentioned in the manifest.
1196 if (manifest_.signatures_offset() &&
1197 manifest_.signatures_offset() == operation.data_offset()) {
1198 LOG(INFO) << "Skipping hash verification for signature operation "
1199 << next_operation_num_ + 1;
1200 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001201 if (install_plan_->hash_checks_mandatory) {
1202 LOG(ERROR) << "Missing mandatory operation hash for operation "
1203 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001204 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001205 }
1206
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001207 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1208 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001209 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001210 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001211 }
1212
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001213 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001214 expected_op_hash.assign(operation.data_sha256_hash().data(),
1215 (operation.data_sha256_hash().data() +
1216 operation.data_sha256_hash().size()));
1217
1218 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001219 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001220 if (!operation_hasher.Finalize()) {
1221 LOG(ERROR) << "Unable to compute actual hash of operation "
1222 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001223 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001224 }
1225
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001226 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001227 if (calculated_op_hash != expected_op_hash) {
1228 LOG(ERROR) << "Hash verification failed for operation "
1229 << next_operation_num_ << ". Expected hash = ";
1230 utils::HexDumpVector(expected_op_hash);
1231 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1232 << " bytes at offset: " << operation.data_offset() << " = ";
1233 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001234 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001235 }
1236
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001237 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001238}
1239
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001240#define TEST_AND_RETURN_VAL(_retval, _condition) \
1241 do { \
1242 if (!(_condition)) { \
1243 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1244 return _retval; \
1245 } \
1246 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001247
David Zeuthena99981f2013-04-29 13:42:47 -07001248ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001249 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001250 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001251
1252 // See if we should use the public RSA key in the Omaha response.
1253 base::FilePath path_to_public_key(public_key_path_);
1254 base::FilePath tmp_key;
1255 if (GetPublicKeyFromResponse(&tmp_key))
1256 path_to_public_key = tmp_key;
1257 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1258 if (tmp_key.empty())
1259 tmp_key_remover.set_should_remove(false);
1260
1261 LOG(INFO) << "Verifying payload using public key: "
1262 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001263
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001264 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001266 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001267 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001268
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001269 // Verifies the payload hash.
1270 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001271 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001272 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001273 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001274 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001275
Darin Petkov437adc42010-10-07 13:12:24 -07001276 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001277 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001278 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001279 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001280 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001281 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001282 !signatures_message_data_.empty());
Darin Petkov437adc42010-10-07 13:12:24 -07001283 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001284 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001285 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001286 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001287 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001288 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001289 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1290 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001291 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001292 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001293
1294 if (!PayloadVerifier::VerifySignature(
1295 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001296 // The autoupdate_CatchBadSignatures test checks for this string
1297 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001298 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001299 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001300 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001301
David Zeuthene7f89172013-10-31 10:21:04 -07001302 LOG(INFO) << "Payload hash matches value in payload.";
1303
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001304 // At this point, we are guaranteed to have downloaded a full payload, i.e
1305 // the one whose size matches the size mentioned in Omaha response. If any
1306 // errors happen after this, it's likely a problem with the payload itself or
1307 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001308 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001309 system_state_->payload_state()->DownloadComplete();
1310
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001311 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001312}
1313
Darin Petkov3aefa862010-12-07 14:45:00 -08001314bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001315 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001316 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001317 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001318 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1319 manifest_.has_new_kernel_info() &&
1320 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001321 *kernel_size = manifest_.new_kernel_info().size();
1322 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001323 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1324 manifest_.new_kernel_info().hash().end());
1325 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1326 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001327 kernel_hash->swap(new_kernel_hash);
1328 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001329 return true;
1330}
1331
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001332namespace {
1333void LogVerifyError(bool is_kern,
1334 const string& local_hash,
1335 const string& expected_hash) {
1336 const char* type = is_kern ? "kernel" : "rootfs";
1337 LOG(ERROR) << "This is a server-side error due to "
1338 << "mismatched delta update image!";
1339 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1340 << "update that must be applied over a " << type << " with "
1341 << "a specific checksum, but the " << type << " we're starting "
1342 << "with doesn't have that checksum! This means that "
1343 << "the delta I've been given doesn't match my existing "
1344 << "system. The " << type << " partition I have has hash: "
1345 << local_hash << " but the update expected me to have "
1346 << expected_hash << " .";
1347 if (is_kern) {
1348 LOG(INFO) << "To get the checksum of a kernel partition on a "
1349 << "booted machine, run this command (change /dev/sda2 "
1350 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1351 << "openssl dgst -sha256 -binary | openssl base64";
1352 } else {
1353 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1354 << "booted machine, run this command (change /dev/sda3 "
1355 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1356 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1357 << "| sed 's/[^0-9]*//') / 256 )) | "
1358 << "openssl dgst -sha256 -binary | openssl base64";
1359 }
1360 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1361 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1362}
1363
1364string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001365 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001366}
1367} // namespace
1368
Darin Petkov698d0412010-10-13 10:59:44 -07001369bool DeltaPerformer::VerifySourcePartitions() {
1370 LOG(INFO) << "Verifying source partitions.";
1371 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001372 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001373 if (manifest_.has_old_kernel_info()) {
1374 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001375 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001376 !install_plan_->source_kernel_hash.empty() &&
1377 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1378 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001379 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001380 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001381 if (!valid) {
1382 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001383 StringForHashBytes(
1384 install_plan_->source_kernel_hash.data(),
1385 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001386 StringForHashBytes(info.hash().data(),
1387 info.hash().size()));
1388 }
1389 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001390 }
1391 if (manifest_.has_old_rootfs_info()) {
1392 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001393 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001394 !install_plan_->source_rootfs_hash.empty() &&
1395 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1396 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001397 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001398 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001399 if (!valid) {
1400 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001401 StringForHashBytes(
1402 install_plan_->source_rootfs_hash.data(),
1403 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001404 StringForHashBytes(info.hash().data(),
1405 info.hash().size()));
1406 }
1407 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001408 }
1409 return true;
1410}
1411
Gilad Arnolddaa27402014-01-23 11:56:17 -08001412void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001413 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001414 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001415 buffer_offset_ += buffer_.size();
1416
1417 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001418 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001419
1420 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001421 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001422}
1423
Darin Petkov0406e402010-10-06 21:33:11 -07001424bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1425 string update_check_response_hash) {
1426 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001427 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1428 next_operation != kUpdateStateOperationInvalid &&
1429 next_operation > 0))
1430 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001431
1432 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001433 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1434 !interrupted_hash.empty() &&
1435 interrupted_hash == update_check_response_hash))
1436 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001437
Darin Petkov61426142010-10-08 11:04:55 -07001438 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001439 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1440 && resumed_update_failures > kMaxResumedUpdateFailures))
1441 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001442
Darin Petkov0406e402010-10-06 21:33:11 -07001443 // Sanity check the rest.
1444 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001445 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1446 next_data_offset >= 0))
1447 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001448
Darin Petkov437adc42010-10-07 13:12:24 -07001449 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001450 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1451 !sha256_context.empty()))
1452 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001453
1454 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001455 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1456 manifest_metadata_size > 0))
1457 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001458
1459 return true;
1460}
1461
Darin Petkov9b230572010-10-08 10:20:09 -07001462bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001463 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1464 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001465 if (!quick) {
1466 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1467 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001468 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001469 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1470 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001471 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001472 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001473 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001474 }
Darin Petkov73058b42010-10-06 16:32:19 -07001475 return true;
1476}
1477
1478bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001479 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001480 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001481 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001482 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001483 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001484 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001485 hash_calculator_.GetContext()));
1486 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1487 buffer_offset_));
1488 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001489
1490 if (next_operation_num_ < num_total_operations_) {
1491 const bool is_kernel_partition =
1492 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001493 const InstallOperation& op =
1494 is_kernel_partition
1495 ? manifest_.kernel_install_operations(next_operation_num_ -
1496 num_rootfs_operations_)
1497 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001498 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1499 op.data_length()));
1500 } else {
1501 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1502 0));
1503 }
Darin Petkov0406e402010-10-06 21:33:11 -07001504 }
Darin Petkov73058b42010-10-06 16:32:19 -07001505 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1506 next_operation_num_));
1507 return true;
1508}
1509
Darin Petkov9b230572010-10-08 10:20:09 -07001510bool DeltaPerformer::PrimeUpdateState() {
1511 CHECK(manifest_valid_);
1512 block_size_ = manifest_.block_size();
1513
1514 int64_t next_operation = kUpdateStateOperationInvalid;
1515 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1516 next_operation == kUpdateStateOperationInvalid ||
1517 next_operation <= 0) {
1518 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001519 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001520 return true;
1521 }
1522 next_operation_num_ = next_operation;
1523
1524 // Resuming an update -- load the rest of the update state.
1525 int64_t next_data_offset = -1;
1526 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1527 &next_data_offset) &&
1528 next_data_offset >= 0);
1529 buffer_offset_ = next_data_offset;
1530
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001531 // The signed hash context and the signature blob may be empty if the
1532 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001533 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1534 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001535 string signature_blob;
1536 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1537 signatures_message_data_.assign(signature_blob.begin(),
1538 signature_blob.end());
1539 }
Darin Petkov9b230572010-10-08 10:20:09 -07001540
1541 string hash_context;
1542 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1543 &hash_context) &&
1544 hash_calculator_.SetContext(hash_context));
1545
1546 int64_t manifest_metadata_size = 0;
1547 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1548 &manifest_metadata_size) &&
1549 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001550 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001551
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001552 // Advance the download progress to reflect what doesn't need to be
1553 // re-downloaded.
1554 total_bytes_received_ += buffer_offset_;
1555
Darin Petkov61426142010-10-08 11:04:55 -07001556 // Speculatively count the resume as a failure.
1557 int64_t resumed_update_failures;
1558 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1559 resumed_update_failures++;
1560 } else {
1561 resumed_update_failures = 1;
1562 }
1563 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001564 return true;
1565}
1566
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001567} // namespace chromeos_update_engine