blob: 0544e127e0518096ee5c03abe370a36bd9fa3b39 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070012#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070013#include <string>
14#include <vector>
15
Ben Chan06c76a42014-09-05 08:21:06 -070016#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070017#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070018#include <base/strings/string_util.h>
19#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080020#include <chromeos/data_encoding.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070021#include <google/protobuf/repeated_field.h>
22
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070024#include "update_engine/constants.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070025#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070027#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080028#if USE_MTD
29#include "update_engine/mtd_file_descriptor.h"
30#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070031#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080032#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070033#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070034#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070036#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070037#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038
Alex Deymo161c4a12014-05-16 15:56:21 -070039using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040using std::min;
41using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070042using std::unique_ptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070044
45namespace chromeos_update_engine {
46
Jay Srinivasanf4318702012-09-24 11:56:24 -070047const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
48const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070049const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Don Garrettb8dd1d92013-11-22 17:40:02 -080050const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 1;
51const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070052
Darin Petkovabc7bc02011-02-23 14:39:43 -080053const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
54 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080055const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
56const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
57const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
58const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080059
Allie Woodfdf00512015-03-02 13:34:55 -080060const uint32_t kInPlaceMinorPayloadVersion = 1;
61const uint32_t kSourceMinorPayloadVersion = 2;
62
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070063namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070064const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070065const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080066#if USE_MTD
67const int kUbiVolumeAttachTimeout = 5 * 60;
68#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080069
70FileDescriptorPtr CreateFileDescriptor(const char* path) {
71 FileDescriptorPtr ret;
72#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080073 if (strstr(path, "/dev/ubi") == path) {
74 if (!UbiFileDescriptor::IsUbi(path)) {
75 // The volume might not have been attached at boot time.
76 int volume_no;
77 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
78 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
79 }
80 }
81 if (UbiFileDescriptor::IsUbi(path)) {
82 LOG(INFO) << path << " is a UBI device.";
83 ret.reset(new UbiFileDescriptor);
84 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080085 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080086 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080087 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080088 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080089 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080090#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080091 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080092#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070093 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080094#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080095 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070096}
97
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080098// Opens path for read/write. On success returns an open FileDescriptor
99// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
100FileDescriptorPtr OpenFile(const char* path, int* err) {
101 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800102 int mode = O_RDWR;
103#if USE_MTD
104 // On NAND devices, we can either read, or write, but not both. So here we
105 // use O_WRONLY.
106 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
107 mode = O_WRONLY;
108 }
109#endif
110 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800111 *err = errno;
112 PLOG(ERROR) << "Unable to open file " << path;
113 return nullptr;
114 }
115 *err = 0;
116 return fd;
117}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700118} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700119
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800120
121// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
122// arithmetic.
123static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
124 return part * norm / total;
125}
126
127void DeltaPerformer::LogProgress(const char* message_prefix) {
128 // Format operations total count and percentage.
129 string total_operations_str("?");
130 string completed_percentage_str("");
131 if (num_total_operations_) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700132 total_operations_str = base::StringPrintf("%zu", num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800133 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
134 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700135 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800136 IntRatio(next_operation_num_, num_total_operations_,
137 100));
138 }
139
140 // Format download total count and percentage.
141 size_t payload_size = install_plan_->payload_size;
142 string payload_size_str("?");
143 string downloaded_percentage_str("");
144 if (payload_size) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700145 payload_size_str = base::StringPrintf("%zu", payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800146 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
147 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700148 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800149 IntRatio(total_bytes_received_, payload_size, 100));
150 }
151
152 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
153 << "/" << total_operations_str << " operations"
154 << completed_percentage_str << ", " << total_bytes_received_
155 << "/" << payload_size_str << " bytes downloaded"
156 << downloaded_percentage_str << ", overall progress "
157 << overall_progress_ << "%";
158}
159
160void DeltaPerformer::UpdateOverallProgress(bool force_log,
161 const char* message_prefix) {
162 // Compute our download and overall progress.
163 unsigned new_overall_progress = 0;
164 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
165 progress_weight_dont_add_up);
166 // Only consider download progress if its total size is known; otherwise
167 // adjust the operations weight to compensate for the absence of download
168 // progress. Also, make sure to cap the download portion at
169 // kProgressDownloadWeight, in case we end up downloading more than we
170 // initially expected (this indicates a problem, but could generally happen).
171 // TODO(garnold) the correction of operations weight when we do not have the
172 // total payload size, as well as the conditional guard below, should both be
173 // eliminated once we ensure that the payload_size in the install plan is
174 // always given and is non-zero. This currently isn't the case during unit
175 // tests (see chromium-os:37969).
176 size_t payload_size = install_plan_->payload_size;
177 unsigned actual_operations_weight = kProgressOperationsWeight;
178 if (payload_size)
179 new_overall_progress += min(
180 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
181 kProgressDownloadWeight)),
182 kProgressDownloadWeight);
183 else
184 actual_operations_weight += kProgressDownloadWeight;
185
186 // Only add completed operations if their total number is known; we definitely
187 // expect an update to have at least one operation, so the expectation is that
188 // this will eventually reach |actual_operations_weight|.
189 if (num_total_operations_)
190 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
191 actual_operations_weight);
192
193 // Progress ratio cannot recede, unless our assumptions about the total
194 // payload size, total number of operations, or the monotonicity of progress
195 // is breached.
196 if (new_overall_progress < overall_progress_) {
197 LOG(WARNING) << "progress counter receded from " << overall_progress_
198 << "% down to " << new_overall_progress << "%; this is a bug";
199 force_log = true;
200 }
201 overall_progress_ = new_overall_progress;
202
203 // Update chunk index, log as needed: if forced by called, or we completed a
204 // progress chunk, or a timeout has expired.
205 base::Time curr_time = base::Time::Now();
206 unsigned curr_progress_chunk =
207 overall_progress_ * kProgressLogMaxChunks / 100;
208 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
209 curr_time > forced_progress_log_time_) {
210 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
211 LogProgress(message_prefix);
212 }
213 last_progress_chunk_ = curr_progress_chunk;
214}
215
216
Gilad Arnoldfe133932014-01-14 12:25:50 -0800217size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
218 size_t max) {
219 const size_t count = *count_p;
220 if (!count)
221 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700222 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800223 const char* bytes_start = *bytes_p;
224 const char* bytes_end = bytes_start + read_len;
225 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
226 *bytes_p = bytes_end;
227 *count_p = count - read_len;
228 return read_len;
229}
230
231
232bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
233 ErrorCode* error) {
234 if (op_result)
235 return true;
236
237 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
238 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700239 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800240 return false;
241}
242
243
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700244// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
245// it safely. Returns false otherwise.
246bool DeltaPerformer::IsIdempotentOperation(
247 const DeltaArchiveManifest_InstallOperation& op) {
248 if (op.src_extents_size() == 0) {
249 return true;
250 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700251 // When in doubt, it's safe to declare an op non-idempotent. Note that we
252 // could detect other types of idempotent operations here such as a MOVE that
253 // moves blocks onto themselves. However, we rely on the server to not send
254 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700255 ExtentRanges src_ranges;
256 src_ranges.AddRepeatedExtents(op.src_extents());
257 const uint64_t block_count = src_ranges.blocks();
258 src_ranges.SubtractRepeatedExtents(op.dst_extents());
259 return block_count == src_ranges.blocks();
260}
261
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700262int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700263 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800264 fd_ = OpenFile(path, &err);
265 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700266 path_ = path;
267 return -err;
268}
269
270bool DeltaPerformer::OpenKernel(const char* kernel_path) {
271 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800272 kernel_fd_ = OpenFile(kernel_path, &err);
273 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700274 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800275 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700276}
277
Allie Woodfdf00512015-03-02 13:34:55 -0800278bool DeltaPerformer::OpenSourceRootfs(const std::string& source_path) {
279 int err;
280 source_fd_ = OpenFile(source_path.c_str(), &err);
281 return static_cast<bool>(source_fd_);
282}
283
284bool DeltaPerformer::OpenSourceKernel(const std::string& source_kernel_path) {
285 int err;
286 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
287 return static_cast<bool>(source_kernel_fd_);
288}
289
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700290int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700291 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800292 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700293 err = errno;
294 PLOG(ERROR) << "Unable to close kernel fd:";
295 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800296 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700297 err = errno;
298 PLOG(ERROR) << "Unable to close rootfs fd:";
299 }
Allie Woodfdf00512015-03-02 13:34:55 -0800300 if (source_fd_ && !source_fd_->Close()) {
301 err = errno;
302 PLOG(ERROR) << "Unable to close source rootfs fd:";
303 }
304 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
305 err = errno;
306 PLOG(ERROR) << "Unable to close source kernel fd:";
307 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700308 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800309 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800310 kernel_fd_.reset();
311 source_fd_.reset();
312 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800314 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700315 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
316 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800317 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800318 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700319 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700320}
321
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700322namespace {
323
324void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800325 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800326 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
327 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700328}
329
330void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
331 if (manifest.has_old_kernel_info())
332 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
333 if (manifest.has_old_rootfs_info())
334 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
335 if (manifest.has_new_kernel_info())
336 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
337 if (manifest.has_new_rootfs_info())
338 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
339}
340
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700341} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700342
Don Garrett4d039442013-10-28 18:40:06 -0700343uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800344 // Manifest size is stored right after the magic string and the version.
345 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700346}
347
Jay Srinivasanf4318702012-09-24 11:56:24 -0700348uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800349 // Manifest size is stored right after the magic string and the version.
350 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700351}
352
353uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800354 // Actual manifest begins right after the manifest size field.
355 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700356}
357
Gilad Arnoldfe133932014-01-14 12:25:50 -0800358uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800359 return metadata_size_;
360}
361
Allie Woodfdf00512015-03-02 13:34:55 -0800362uint32_t DeltaPerformer::GetMinorVersion() const {
363 if (manifest_.has_minor_version()) {
364 return manifest_.minor_version();
365 } else {
366 return (install_plan_->is_full_update ?
367 kFullPayloadMinorVersion :
368 kSupportedMinorPayloadVersion);
369 }
370}
371
Gilad Arnolddaa27402014-01-23 11:56:17 -0800372bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
373 if (!manifest_parsed_)
374 return false;
375 *out_manifest_p = manifest_;
376 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800377}
378
Jay Srinivasanf4318702012-09-24 11:56:24 -0700379
Darin Petkov9574f7e2011-01-13 10:48:12 -0800380DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800381 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700382 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700383 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800384 uint64_t manifest_size = (metadata_size_ ?
385 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700386
Gilad Arnoldfe133932014-01-14 12:25:50 -0800387 if (!manifest_size) {
388 // Ensure we have data to cover the payload header.
389 if (payload.size() < manifest_offset)
390 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700391
Gilad Arnoldfe133932014-01-14 12:25:50 -0800392 // Validate the magic string.
393 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
394 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700395 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800396 return kMetadataParseError;
397 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800398
399 // Extract the payload version from the metadata.
400 uint64_t major_payload_version;
401 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
402 major_payload_version_size_mismatch);
403 memcpy(&major_payload_version,
404 &payload[GetVersionOffset()],
405 kDeltaVersionSize);
406 // switch big endian to host
407 major_payload_version = be64toh(major_payload_version);
408
409 if (major_payload_version != kSupportedMajorPayloadVersion) {
410 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
411 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700412 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800413 return kMetadataParseError;
414 }
415
416 // Next, parse the manifest size.
417 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
418 manifest_size_size_mismatch);
419 memcpy(&manifest_size,
420 &payload[GetManifestSizeOffset()],
421 kDeltaManifestSizeSize);
422 manifest_size = be64toh(manifest_size); // switch big endian to host
423
424 // If the metadata size is present in install plan, check for it immediately
425 // even before waiting for that many number of bytes to be downloaded in the
426 // payload. This will prevent any attack which relies on us downloading data
427 // beyond the expected metadata size.
428 metadata_size_ = manifest_offset + manifest_size;
429 if (install_plan_->hash_checks_mandatory) {
430 if (install_plan_->metadata_size != metadata_size_) {
431 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
432 << install_plan_->metadata_size
433 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700434 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800435 return kMetadataParseError;
436 }
437 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700438 }
439
440 // Now that we have validated the metadata size, we should wait for the full
441 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800442 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800443 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700444
445 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700446 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700447 // that we just log once (instead of logging n times) if it takes n
448 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800449 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700450 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800451 } else {
452 // For mandatory-cases, we'd have already returned a kMetadataParseError
453 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
454 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
455 << install_plan_->metadata_size
456 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800457 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700458 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800459 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700460
Jay Srinivasanf4318702012-09-24 11:56:24 -0700461 // We have the full metadata in |payload|. Verify its integrity
462 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800463 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700464 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800465 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800466 // The autoupdate_CatchBadSignatures test checks for this string
467 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800468 LOG(ERROR) << "Mandatory metadata signature validation failed";
469 return kMetadataParseError;
470 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700471
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800472 // For non-mandatory cases, just send a UMA stat.
473 LOG(WARNING) << "Ignoring metadata signature validation failures";
474 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700475 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700476 }
477
Gilad Arnolddaa27402014-01-23 11:56:17 -0800478 // The payload metadata is deemed valid, it's safe to parse the protobuf.
479 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800480 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700481 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800482 return kMetadataParseError;
483 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800484
485 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800486 return kMetadataParseSuccess;
487}
488
Don Garrette410e0f2011-11-10 15:39:01 -0800489// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800490// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700491// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800492bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700493 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700494
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700495 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800496 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800497
498 // Update the total byte downloaded count and the progress logs.
499 total_bytes_received_ += count;
500 UpdateOverallProgress(false, "Completed ");
501
Gilad Arnoldfe133932014-01-14 12:25:50 -0800502 while (!manifest_valid_) {
503 // Read data up to the needed limit; this is either the payload header size,
504 // or the full metadata size (once it becomes known).
505 const bool do_read_header = !metadata_size_;
506 CopyDataToBuffer(&c_bytes, &count,
507 (do_read_header ? GetManifestOffset() :
508 metadata_size_));
509
Gilad Arnolddaa27402014-01-23 11:56:17 -0800510 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700511 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800512 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800513 if (result == kMetadataParseInsufficientData) {
514 // If we just processed the header, make an attempt on the manifest.
515 if (do_read_header && metadata_size_)
516 continue;
517
Don Garrette410e0f2011-11-10 15:39:01 -0800518 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800519 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700520
521 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700522 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700523 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800524 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700525
Gilad Arnoldfe133932014-01-14 12:25:50 -0800526 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800527 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700528 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800529 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700530 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700531
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700532 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700533 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700534 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700535 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800536 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700537 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800538
Allie Woodfdf00512015-03-02 13:34:55 -0800539 // Open source fds if we have a delta payload with minor version 2.
540 if (!install_plan_->is_full_update &&
541 GetMinorVersion() == kSourceMinorPayloadVersion) {
542 if (!OpenSourceRootfs(install_plan_->source_path)) {
543 LOG(ERROR) << "Unable to open source rootfs partition file "
544 << install_plan_->source_path;
545 Close();
546 return false;
547 }
548 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
549 LOG(ERROR) << "Unable to open source kernel partition file "
550 << install_plan_->kernel_source_path;
551 Close();
552 return false;
553 }
554 }
555
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800556 num_rootfs_operations_ = manifest_.install_operations_size();
557 num_total_operations_ =
558 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
559 if (next_operation_num_ > 0)
560 UpdateOverallProgress(true, "Resuming after ");
561 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700562 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800563
564 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700565 // Check if we should cancel the current attempt for any reason.
566 // In this case, *error will have already been populated with the reason
567 // why we're cancelling.
568 if (system_state_->update_attempter()->ShouldCancel(error))
569 return false;
570
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800571 const bool is_kernel_partition =
572 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700573 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800574 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700575 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800576 next_operation_num_ - num_rootfs_operations_) :
577 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800578
579 CopyDataToBuffer(&c_bytes, &count, op.data_length());
580
581 // Check whether we received all of the next operation's data payload.
582 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700583 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700584
Jay Srinivasanf4318702012-09-24 11:56:24 -0700585 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700586 // Otherwise, keep the old behavior. This serves as a knob to disable
587 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800588 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
589 // we would have already failed in ParsePayloadMetadata method and thus not
590 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700591 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700592 // Note: Validate must be called only if CanPerformInstallOperation is
593 // called. Otherwise, we might be failing operations before even if there
594 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800595 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700596 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800597 if (install_plan_->hash_checks_mandatory) {
598 LOG(ERROR) << "Mandatory operation hash check failed";
599 return false;
600 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700601
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800602 // For non-mandatory cases, just send a UMA stat.
603 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700604 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700605 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700606 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700607 }
608
Darin Petkov45580e42010-10-08 14:02:40 -0700609 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700610 ScopedTerminatorExitUnblocker exit_unblocker =
611 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800612
613 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700614 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800615 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
616 op_result = HandleOpResult(
617 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
618 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
619 op_result = HandleOpResult(
620 PerformMoveOperation(op, is_kernel_partition), "move", error);
621 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
622 op_result = HandleOpResult(
623 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
624 else
625 op_result = HandleOpResult(false, "unknown", error);
626
627 if (!op_result)
628 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800629
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700630 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800631 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700632 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700633 }
Don Garrette410e0f2011-11-10 15:39:01 -0800634 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635}
636
David Zeuthen8f191b22013-08-06 12:27:50 -0700637bool DeltaPerformer::IsManifestValid() {
638 return manifest_valid_;
639}
640
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641bool DeltaPerformer::CanPerformInstallOperation(
642 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
643 operation) {
644 // Move operations don't require any data blob, so they can always
Allie Woodfdf00512015-03-02 13:34:55 -0800645 // be performed.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700646 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
647 return true;
648
649 // See if we have the entire data blob in the buffer
650 if (operation.data_offset() < buffer_offset_) {
651 LOG(ERROR) << "we threw away data it seems?";
652 return false;
653 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700654
Gilad Arnoldfe133932014-01-14 12:25:50 -0800655 return (operation.data_offset() + operation.data_length() <=
656 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657}
658
659bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700660 const DeltaArchiveManifest_InstallOperation& operation,
661 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700662 CHECK(operation.type() == \
663 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
664 operation.type() == \
665 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
666
667 // Since we delete data off the beginning of the buffer as we use it,
668 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700669 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
670 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700671
Darin Petkov437adc42010-10-07 13:12:24 -0700672 // Extract the signature message if it's in this operation.
673 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700674
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700675 DirectExtentWriter direct_writer;
676 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700677 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700678
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700679 // Since bzip decompression is optional, we have a variable writer that will
680 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700681 ExtentWriter* writer = nullptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700682 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
683 writer = &zero_pad_writer;
684 } else if (operation.type() ==
685 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
686 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
687 writer = bzip_writer.get();
688 } else {
689 NOTREACHED();
690 }
691
692 // Create a vector of extents to pass to the ExtentWriter.
693 vector<Extent> extents;
694 for (int i = 0; i < operation.dst_extents_size(); i++) {
695 extents.push_back(operation.dst_extents(i));
696 }
697
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800698 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700699
700 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800701 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700702 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700703
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700704 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800705 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700706 return true;
707}
708
709bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700710 const DeltaArchiveManifest_InstallOperation& operation,
711 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700712 // Calculate buffer size. Note, this function doesn't do a sliding
713 // window to copy in case the source and destination blocks overlap.
714 // If we wanted to do a sliding window, we could program the server
715 // to generate deltas that effectively did a sliding window.
716
717 uint64_t blocks_to_read = 0;
718 for (int i = 0; i < operation.src_extents_size(); i++)
719 blocks_to_read += operation.src_extents(i).num_blocks();
720
721 uint64_t blocks_to_write = 0;
722 for (int i = 0; i < operation.dst_extents_size(); i++)
723 blocks_to_write += operation.dst_extents(i).num_blocks();
724
725 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800726 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700727
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800728 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700729
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700730 // Read in bytes.
731 ssize_t bytes_read = 0;
732 for (int i = 0; i < operation.src_extents_size(); i++) {
733 ssize_t bytes_read_this_iteration = 0;
734 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200735 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700736 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
737 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
738 &buf[bytes_read],
739 bytes,
740 extent.start_block() * block_size_,
741 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700742 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200743 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700744 bytes_read += bytes_read_this_iteration;
745 }
746
Darin Petkov45580e42010-10-08 14:02:40 -0700747 // If this is a non-idempotent operation, request a delayed exit and clear the
748 // update state in case the operation gets interrupted. Do this as late as
749 // possible.
750 if (!IsIdempotentOperation(operation)) {
751 Terminator::set_exit_blocked(true);
752 ResetUpdateProgress(prefs_, true);
753 }
754
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700755 // Write bytes out.
756 ssize_t bytes_written = 0;
757 for (int i = 0; i < operation.dst_extents_size(); i++) {
758 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200759 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700760 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
761 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
762 &buf[bytes_written],
763 bytes,
764 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200765 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700766 }
767 DCHECK_EQ(bytes_written, bytes_read);
768 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
769 return true;
770}
771
772bool DeltaPerformer::ExtentsToBsdiffPositionsString(
773 const RepeatedPtrField<Extent>& extents,
774 uint64_t block_size,
775 uint64_t full_length,
776 string* positions_string) {
777 string ret;
778 uint64_t length = 0;
779 for (int i = 0; i < extents.size(); i++) {
780 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700781 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700782 uint64_t this_length = min(full_length - length,
783 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700784 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700785 length += this_length;
786 }
787 TEST_AND_RETURN_FALSE(length == full_length);
788 if (!ret.empty())
789 ret.resize(ret.size() - 1); // Strip trailing comma off
790 *positions_string = ret;
791 return true;
792}
793
794bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700795 const DeltaArchiveManifest_InstallOperation& operation,
796 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700797 // Since we delete data off the beginning of the buffer as we use it,
798 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700799 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
800 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700801
802 string input_positions;
803 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
804 block_size_,
805 operation.src_length(),
806 &input_positions));
807 string output_positions;
808 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
809 block_size_,
810 operation.dst_length(),
811 &output_positions));
812
813 string temp_filename;
814 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
815 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700816 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700817 ScopedPathUnlinker path_unlinker(temp_filename);
818 {
819 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
820 ScopedFdCloser fd_closer(&fd);
821 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800822 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700823 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700824
Darin Petkov7f2ec752013-04-03 14:45:19 +0200825 // Update the buffer to release the patch data memory as soon as the patch
826 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800827 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200828
Darin Petkov45580e42010-10-08 14:02:40 -0700829 // If this is a non-idempotent operation, request a delayed exit and clear the
830 // update state in case the operation gets interrupted. Do this as late as
831 // possible.
832 if (!IsIdempotentOperation(operation)) {
833 Terminator::set_exit_blocked(true);
834 ResetUpdateProgress(prefs_, true);
835 }
836
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700837 vector<string> cmd;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800838 const string& path = is_kernel_partition ? kernel_path_ : path_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700839 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700840 cmd.push_back(path);
841 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700842 cmd.push_back(temp_filename);
843 cmd.push_back(input_positions);
844 cmd.push_back(output_positions);
845 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700846 TEST_AND_RETURN_FALSE(
847 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700848 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700849 &return_code,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700850 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700851 TEST_AND_RETURN_FALSE(return_code == 0);
852
853 if (operation.dst_length() % block_size_) {
854 // Zero out rest of final block.
855 // TODO(adlr): build this into bspatch; it's more efficient that way.
856 const Extent& last_extent =
857 operation.dst_extents(operation.dst_extents_size() - 1);
858 const uint64_t end_byte =
859 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
860 const uint64_t begin_byte =
861 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800862 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800863 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700864 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800865 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700866 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700867 return true;
868}
869
Darin Petkovd7061ab2010-10-06 14:37:09 -0700870bool DeltaPerformer::ExtractSignatureMessage(
871 const DeltaArchiveManifest_InstallOperation& operation) {
872 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
873 !manifest_.has_signatures_offset() ||
874 manifest_.signatures_offset() != operation.data_offset()) {
875 return false;
876 }
877 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
878 manifest_.signatures_size() == operation.data_length());
879 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
880 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
881 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700882 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700883 buffer_.begin(),
884 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700885
886 // Save the signature blob because if the update is interrupted after the
887 // download phase we don't go through this path anymore. Some alternatives to
888 // consider:
889 //
890 // 1. On resume, re-download the signature blob from the server and re-verify
891 // it.
892 //
893 // 2. Verify the signature as soon as it's received and don't checkpoint the
894 // blob and the signed sha-256 context.
895 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800896 string(signatures_message_data_.begin(),
897 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700898 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700899 // The hash of all data consumed so far should be verified against the signed
900 // hash.
901 signed_hash_context_ = hash_calculator_.GetContext();
902 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
903 signed_hash_context_))
904 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700905 LOG(INFO) << "Extracted signature data of size "
906 << manifest_.signatures_size() << " at "
907 << manifest_.signatures_offset();
908 return true;
909}
910
David Zeuthene7f89172013-10-31 10:21:04 -0700911bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
912 if (system_state_->hardware()->IsOfficialBuild() ||
913 utils::FileExists(public_key_path_.c_str()) ||
914 install_plan_->public_key_rsa.empty())
915 return false;
916
917 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
918 out_tmp_key))
919 return false;
920
921 return true;
922}
923
David Zeuthena99981f2013-04-29 13:42:47 -0700924ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800925 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700926
Jay Srinivasanf4318702012-09-24 11:56:24 -0700927 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800928 if (install_plan_->hash_checks_mandatory) {
929 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700930 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800931 }
932
933 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700934 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700935 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
936 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700937 }
938
939 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800940 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800941 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800942 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -0700943 LOG(ERROR) << "Unable to decode base64 metadata signature: "
944 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700945 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700946 }
947
David Zeuthene7f89172013-10-31 10:21:04 -0700948 // See if we should use the public RSA key in the Omaha response.
949 base::FilePath path_to_public_key(public_key_path_);
950 base::FilePath tmp_key;
951 if (GetPublicKeyFromResponse(&tmp_key))
952 path_to_public_key = tmp_key;
953 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
954 if (tmp_key.empty())
955 tmp_key_remover.set_should_remove(false);
956
957 LOG(INFO) << "Verifying metadata hash signature using public key: "
958 << path_to_public_key.value();
959
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800960 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -0700961 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
962 path_to_public_key.value(),
963 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -0700964 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700965 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700966 }
967
Jay Srinivasanf4318702012-09-24 11:56:24 -0700968 OmahaHashCalculator metadata_hasher;
969 metadata_hasher.Update(metadata, metadata_size);
970 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700971 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700972 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700973 }
974
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800975 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -0700976 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -0700977 if (calculated_metadata_hash.empty()) {
978 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700979 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700980 }
981
Jay Srinivasanf4318702012-09-24 11:56:24 -0700982 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700983 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700984 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700985 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700986 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700987 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700988 }
989
David Zeuthenbc27aac2013-11-26 11:17:48 -0800990 // The autoupdate_CatchBadSignatures test checks for this string in
991 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -0700992 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700993 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700994}
995
Gilad Arnold21504f02013-05-24 08:51:22 -0700996ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -0800997 // Perform assorted checks to sanity check the manifest, make sure it
998 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -0700999 //
1000 // TODO(garnold) in general, the presence of an old partition hash should be
1001 // the sole indicator for a delta update, as we would generally like update
1002 // payloads to be self contained and not assume an Omaha response to tell us
1003 // that. However, since this requires some massive reengineering of the update
1004 // flow (making filesystem copying happen conditionally only *after*
1005 // downloading and parsing of the update manifest) we'll put it off for now.
1006 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001007 if (install_plan_->is_full_update) {
1008 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1009 LOG(ERROR) << "Purported full payload contains old partition "
1010 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001011 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001012 }
1013
1014 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1015 LOG(ERROR) << "Manifest contains minor version "
1016 << manifest_.minor_version()
1017 << ", but all full payloads should have version "
1018 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001019 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001020 }
1021 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001022 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001023 LOG(ERROR) << "Manifest contains minor version "
1024 << manifest_.minor_version()
1025 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001026 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001027 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001028 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001029 }
1030
1031 // TODO(garnold) we should be adding more and more manifest checks, such as
1032 // partition boundaries etc (see chromium-os:37661).
1033
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001034 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001035}
1036
David Zeuthena99981f2013-04-29 13:42:47 -07001037ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001038 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001039
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001040 if (!operation.data_sha256_hash().size()) {
1041 if (!operation.data_length()) {
1042 // Operations that do not have any data blob won't have any operation hash
1043 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001044 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001045 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001047 }
1048
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001049 // No hash is present for an operation that has data blobs. This shouldn't
1050 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001051 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001052 // hashes. So if it happens it means either we've turned operation hash
1053 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001054 // One caveat though: The last operation is a dummy signature operation
1055 // that doesn't have a hash at the time the manifest is created. So we
1056 // should not complaint about that operation. This operation can be
1057 // recognized by the fact that it's offset is mentioned in the manifest.
1058 if (manifest_.signatures_offset() &&
1059 manifest_.signatures_offset() == operation.data_offset()) {
1060 LOG(INFO) << "Skipping hash verification for signature operation "
1061 << next_operation_num_ + 1;
1062 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001063 if (install_plan_->hash_checks_mandatory) {
1064 LOG(ERROR) << "Missing mandatory operation hash for operation "
1065 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001066 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001067 }
1068
1069 // For non-mandatory cases, just send a UMA stat.
1070 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1071 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001073 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001074 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001075 }
1076
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001077 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001078 expected_op_hash.assign(operation.data_sha256_hash().data(),
1079 (operation.data_sha256_hash().data() +
1080 operation.data_sha256_hash().size()));
1081
1082 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001083 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001084 if (!operation_hasher.Finalize()) {
1085 LOG(ERROR) << "Unable to compute actual hash of operation "
1086 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001088 }
1089
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001090 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001091 if (calculated_op_hash != expected_op_hash) {
1092 LOG(ERROR) << "Hash verification failed for operation "
1093 << next_operation_num_ << ". Expected hash = ";
1094 utils::HexDumpVector(expected_op_hash);
1095 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1096 << " bytes at offset: " << operation.data_offset() << " = ";
1097 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001098 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001099 }
1100
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001101 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001102}
1103
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001104#define TEST_AND_RETURN_VAL(_retval, _condition) \
1105 do { \
1106 if (!(_condition)) { \
1107 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1108 return _retval; \
1109 } \
1110 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001111
David Zeuthena99981f2013-04-29 13:42:47 -07001112ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001113 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001114 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001115
1116 // See if we should use the public RSA key in the Omaha response.
1117 base::FilePath path_to_public_key(public_key_path_);
1118 base::FilePath tmp_key;
1119 if (GetPublicKeyFromResponse(&tmp_key))
1120 path_to_public_key = tmp_key;
1121 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1122 if (tmp_key.empty())
1123 tmp_key_remover.set_should_remove(false);
1124
1125 LOG(INFO) << "Verifying payload using public key: "
1126 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001127
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001128 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001129 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001130 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001131 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001132
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001133 // Verifies the payload hash.
1134 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001135 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001136 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001137 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001138 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001139
Darin Petkov437adc42010-10-07 13:12:24 -07001140 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001141 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001142 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001143 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001144 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001145 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001146 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001147 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001148 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001149 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001150 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001151 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001152 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001153 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001154 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001155 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001156 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001157 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001158 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001159 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001160 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001161 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001162 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001163 // The autoupdate_CatchBadSignatures test checks for this string
1164 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001165 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001166 "Attached Signature:";
1167 utils::HexDumpVector(signed_hash_data);
1168 LOG(ERROR) << "Computed Signature:";
1169 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001170 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001171 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001172
David Zeuthene7f89172013-10-31 10:21:04 -07001173 LOG(INFO) << "Payload hash matches value in payload.";
1174
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001175 // At this point, we are guaranteed to have downloaded a full payload, i.e
1176 // the one whose size matches the size mentioned in Omaha response. If any
1177 // errors happen after this, it's likely a problem with the payload itself or
1178 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001179 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001180 system_state_->payload_state()->DownloadComplete();
1181
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001182 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001183}
1184
Darin Petkov3aefa862010-12-07 14:45:00 -08001185bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001186 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001187 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001188 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001189 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1190 manifest_.has_new_kernel_info() &&
1191 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001192 *kernel_size = manifest_.new_kernel_info().size();
1193 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001194 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1195 manifest_.new_kernel_info().hash().end());
1196 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1197 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001198 kernel_hash->swap(new_kernel_hash);
1199 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001200 return true;
1201}
1202
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001203namespace {
1204void LogVerifyError(bool is_kern,
1205 const string& local_hash,
1206 const string& expected_hash) {
1207 const char* type = is_kern ? "kernel" : "rootfs";
1208 LOG(ERROR) << "This is a server-side error due to "
1209 << "mismatched delta update image!";
1210 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1211 << "update that must be applied over a " << type << " with "
1212 << "a specific checksum, but the " << type << " we're starting "
1213 << "with doesn't have that checksum! This means that "
1214 << "the delta I've been given doesn't match my existing "
1215 << "system. The " << type << " partition I have has hash: "
1216 << local_hash << " but the update expected me to have "
1217 << expected_hash << " .";
1218 if (is_kern) {
1219 LOG(INFO) << "To get the checksum of a kernel partition on a "
1220 << "booted machine, run this command (change /dev/sda2 "
1221 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1222 << "openssl dgst -sha256 -binary | openssl base64";
1223 } else {
1224 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1225 << "booted machine, run this command (change /dev/sda3 "
1226 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1227 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1228 << "| sed 's/[^0-9]*//') / 256 )) | "
1229 << "openssl dgst -sha256 -binary | openssl base64";
1230 }
1231 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1232 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1233}
1234
1235string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001236 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001237}
1238} // namespace
1239
Darin Petkov698d0412010-10-13 10:59:44 -07001240bool DeltaPerformer::VerifySourcePartitions() {
1241 LOG(INFO) << "Verifying source partitions.";
1242 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001243 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001244 if (manifest_.has_old_kernel_info()) {
1245 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001246 bool valid =
1247 !install_plan_->kernel_hash.empty() &&
1248 install_plan_->kernel_hash.size() == info.hash().size() &&
1249 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001250 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001251 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001252 if (!valid) {
1253 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001254 StringForHashBytes(install_plan_->kernel_hash.data(),
1255 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001256 StringForHashBytes(info.hash().data(),
1257 info.hash().size()));
1258 }
1259 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001260 }
1261 if (manifest_.has_old_rootfs_info()) {
1262 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001263 bool valid =
1264 !install_plan_->rootfs_hash.empty() &&
1265 install_plan_->rootfs_hash.size() == info.hash().size() &&
1266 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001267 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001268 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001269 if (!valid) {
1270 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001271 StringForHashBytes(install_plan_->rootfs_hash.data(),
1272 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001273 StringForHashBytes(info.hash().data(),
1274 info.hash().size()));
1275 }
1276 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001277 }
1278 return true;
1279}
1280
Gilad Arnolddaa27402014-01-23 11:56:17 -08001281void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001282 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001283 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001284 buffer_offset_ += buffer_.size();
1285
1286 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001287 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001288
1289 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001290 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001291}
1292
Darin Petkov0406e402010-10-06 21:33:11 -07001293bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1294 string update_check_response_hash) {
1295 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001296 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1297 next_operation != kUpdateStateOperationInvalid &&
1298 next_operation > 0))
1299 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001300
1301 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001302 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1303 !interrupted_hash.empty() &&
1304 interrupted_hash == update_check_response_hash))
1305 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001306
Darin Petkov61426142010-10-08 11:04:55 -07001307 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001308 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1309 && resumed_update_failures > kMaxResumedUpdateFailures))
1310 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001311
Darin Petkov0406e402010-10-06 21:33:11 -07001312 // Sanity check the rest.
1313 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001314 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1315 next_data_offset >= 0))
1316 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001317
Darin Petkov437adc42010-10-07 13:12:24 -07001318 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001319 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1320 !sha256_context.empty()))
1321 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001322
1323 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001324 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1325 manifest_metadata_size > 0))
1326 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001327
1328 return true;
1329}
1330
Darin Petkov9b230572010-10-08 10:20:09 -07001331bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001332 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1333 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001334 if (!quick) {
1335 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1336 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001337 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001338 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1339 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001340 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001341 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001342 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001343 }
Darin Petkov73058b42010-10-06 16:32:19 -07001344 return true;
1345}
1346
1347bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001348 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001349 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001350 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001351 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001352 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001353 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001354 hash_calculator_.GetContext()));
1355 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1356 buffer_offset_));
1357 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001358
1359 if (next_operation_num_ < num_total_operations_) {
1360 const bool is_kernel_partition =
1361 next_operation_num_ >= num_rootfs_operations_;
1362 const DeltaArchiveManifest_InstallOperation &op =
1363 is_kernel_partition ?
1364 manifest_.kernel_install_operations(
1365 next_operation_num_ - num_rootfs_operations_) :
1366 manifest_.install_operations(next_operation_num_);
1367 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1368 op.data_length()));
1369 } else {
1370 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1371 0));
1372 }
Darin Petkov0406e402010-10-06 21:33:11 -07001373 }
Darin Petkov73058b42010-10-06 16:32:19 -07001374 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1375 next_operation_num_));
1376 return true;
1377}
1378
Darin Petkov9b230572010-10-08 10:20:09 -07001379bool DeltaPerformer::PrimeUpdateState() {
1380 CHECK(manifest_valid_);
1381 block_size_ = manifest_.block_size();
1382
1383 int64_t next_operation = kUpdateStateOperationInvalid;
1384 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1385 next_operation == kUpdateStateOperationInvalid ||
1386 next_operation <= 0) {
1387 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001388 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001389 return true;
1390 }
1391 next_operation_num_ = next_operation;
1392
1393 // Resuming an update -- load the rest of the update state.
1394 int64_t next_data_offset = -1;
1395 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1396 &next_data_offset) &&
1397 next_data_offset >= 0);
1398 buffer_offset_ = next_data_offset;
1399
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001400 // The signed hash context and the signature blob may be empty if the
1401 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001402 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1403 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001404 string signature_blob;
1405 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1406 signatures_message_data_.assign(signature_blob.begin(),
1407 signature_blob.end());
1408 }
Darin Petkov9b230572010-10-08 10:20:09 -07001409
1410 string hash_context;
1411 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1412 &hash_context) &&
1413 hash_calculator_.SetContext(hash_context));
1414
1415 int64_t manifest_metadata_size = 0;
1416 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1417 &manifest_metadata_size) &&
1418 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001419 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001420
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001421 // Advance the download progress to reflect what doesn't need to be
1422 // re-downloaded.
1423 total_bytes_received_ += buffer_offset_;
1424
Darin Petkov61426142010-10-08 11:04:55 -07001425 // Speculatively count the resume as a failure.
1426 int64_t resumed_update_failures;
1427 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1428 resumed_update_failures++;
1429 } else {
1430 resumed_update_failures = 1;
1431 }
1432 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001433 return true;
1434}
1435
David Zeuthena99981f2013-04-29 13:42:47 -07001436void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001437 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001438}
1439
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001440} // namespace chromeos_update_engine