blob: 1006f178637653bef704b871fbf5cd657b3de616 [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 Reyes09e56d62010-04-23 13:45:53 -070025#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070026#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080027#if USE_MTD
28#include "update_engine/mtd_file_descriptor.h"
29#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070030#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080031#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070032#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070033#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070035#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070036#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070037
Alex Deymo161c4a12014-05-16 15:56:21 -070038using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070039using std::min;
40using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070041using std::unique_ptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070042using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043
44namespace chromeos_update_engine {
45
Jay Srinivasanf4318702012-09-24 11:56:24 -070046const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
47const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070048const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Allie Wood6eeec902015-04-15 10:40:52 -070049const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 2;
Don Garrettb8dd1d92013-11-22 17:40:02 -080050const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070051
Darin Petkovabc7bc02011-02-23 14:39:43 -080052const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
53 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080054const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
55const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
56const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
57const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080058
Allie Woodfdf00512015-03-02 13:34:55 -080059const uint32_t kInPlaceMinorPayloadVersion = 1;
60const uint32_t kSourceMinorPayloadVersion = 2;
Gilad Arnold41e34742015-05-11 11:31:50 -070061const size_t kDefaultChunkSize = 1024 * 1024;
Allie Woodfdf00512015-03-02 13:34:55 -080062
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
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700243int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700244 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800245 fd_ = OpenFile(path, &err);
246 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700247 path_ = path;
248 return -err;
249}
250
251bool DeltaPerformer::OpenKernel(const char* kernel_path) {
252 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800253 kernel_fd_ = OpenFile(kernel_path, &err);
254 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700255 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800256 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700257}
258
Alex Deymo1beda782015-06-07 23:01:25 +0200259bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800260 int err;
261 source_fd_ = OpenFile(source_path.c_str(), &err);
262 return static_cast<bool>(source_fd_);
263}
264
Alex Deymo1beda782015-06-07 23:01:25 +0200265bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800266 int err;
267 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
268 return static_cast<bool>(source_kernel_fd_);
269}
270
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700271int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700272 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800273 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700274 err = errno;
275 PLOG(ERROR) << "Unable to close kernel fd:";
276 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800277 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700278 err = errno;
279 PLOG(ERROR) << "Unable to close rootfs fd:";
280 }
Allie Woodfdf00512015-03-02 13:34:55 -0800281 if (source_fd_ && !source_fd_->Close()) {
282 err = errno;
283 PLOG(ERROR) << "Unable to close source rootfs fd:";
284 }
285 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
286 err = errno;
287 PLOG(ERROR) << "Unable to close source kernel fd:";
288 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700289 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800290 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800291 kernel_fd_.reset();
292 source_fd_.reset();
293 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700294 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800295 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700296 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
297 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800298 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800299 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700300 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301}
302
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700303namespace {
304
305void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800306 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800307 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
308 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700309}
310
311void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
312 if (manifest.has_old_kernel_info())
313 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
314 if (manifest.has_old_rootfs_info())
315 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
316 if (manifest.has_new_kernel_info())
317 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
318 if (manifest.has_new_rootfs_info())
319 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
320}
321
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700322} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700323
Don Garrett4d039442013-10-28 18:40:06 -0700324uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800325 // Manifest size is stored right after the magic string and the version.
326 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700327}
328
Jay Srinivasanf4318702012-09-24 11:56:24 -0700329uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800330 // Manifest size is stored right after the magic string and the version.
331 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700332}
333
334uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800335 // Actual manifest begins right after the manifest size field.
336 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700337}
338
Gilad Arnoldfe133932014-01-14 12:25:50 -0800339uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800340 return metadata_size_;
341}
342
Allie Woodfdf00512015-03-02 13:34:55 -0800343uint32_t DeltaPerformer::GetMinorVersion() const {
344 if (manifest_.has_minor_version()) {
345 return manifest_.minor_version();
346 } else {
347 return (install_plan_->is_full_update ?
348 kFullPayloadMinorVersion :
349 kSupportedMinorPayloadVersion);
350 }
351}
352
Gilad Arnolddaa27402014-01-23 11:56:17 -0800353bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
354 if (!manifest_parsed_)
355 return false;
356 *out_manifest_p = manifest_;
357 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800358}
359
Jay Srinivasanf4318702012-09-24 11:56:24 -0700360
Darin Petkov9574f7e2011-01-13 10:48:12 -0800361DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800362 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700363 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700364 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800365 uint64_t manifest_size = (metadata_size_ ?
366 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700367
Gilad Arnoldfe133932014-01-14 12:25:50 -0800368 if (!manifest_size) {
369 // Ensure we have data to cover the payload header.
370 if (payload.size() < manifest_offset)
371 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700372
Gilad Arnoldfe133932014-01-14 12:25:50 -0800373 // Validate the magic string.
374 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
375 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700376 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800377 return kMetadataParseError;
378 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800379
380 // Extract the payload version from the metadata.
381 uint64_t major_payload_version;
382 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
383 major_payload_version_size_mismatch);
384 memcpy(&major_payload_version,
385 &payload[GetVersionOffset()],
386 kDeltaVersionSize);
387 // switch big endian to host
388 major_payload_version = be64toh(major_payload_version);
389
390 if (major_payload_version != kSupportedMajorPayloadVersion) {
391 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
392 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700393 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800394 return kMetadataParseError;
395 }
396
397 // Next, parse the manifest size.
398 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
399 manifest_size_size_mismatch);
400 memcpy(&manifest_size,
401 &payload[GetManifestSizeOffset()],
402 kDeltaManifestSizeSize);
403 manifest_size = be64toh(manifest_size); // switch big endian to host
404
405 // If the metadata size is present in install plan, check for it immediately
406 // even before waiting for that many number of bytes to be downloaded in the
407 // payload. This will prevent any attack which relies on us downloading data
408 // beyond the expected metadata size.
409 metadata_size_ = manifest_offset + manifest_size;
410 if (install_plan_->hash_checks_mandatory) {
411 if (install_plan_->metadata_size != metadata_size_) {
412 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
413 << install_plan_->metadata_size
414 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700415 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800416 return kMetadataParseError;
417 }
418 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700419 }
420
421 // Now that we have validated the metadata size, we should wait for the full
422 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800423 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800424 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700425
426 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700427 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700428 // that we just log once (instead of logging n times) if it takes n
429 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800430 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700431 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800432 } else {
433 // For mandatory-cases, we'd have already returned a kMetadataParseError
434 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
435 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
436 << install_plan_->metadata_size
437 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800438 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700439 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800440 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700441
Jay Srinivasanf4318702012-09-24 11:56:24 -0700442 // We have the full metadata in |payload|. Verify its integrity
443 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800444 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700445 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800446 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800447 // The autoupdate_CatchBadSignatures test checks for this string
448 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800449 LOG(ERROR) << "Mandatory metadata signature validation failed";
450 return kMetadataParseError;
451 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700452
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800453 // For non-mandatory cases, just send a UMA stat.
454 LOG(WARNING) << "Ignoring metadata signature validation failures";
455 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700456 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700457 }
458
Gilad Arnolddaa27402014-01-23 11:56:17 -0800459 // The payload metadata is deemed valid, it's safe to parse the protobuf.
460 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800461 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700462 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800463 return kMetadataParseError;
464 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800465
466 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800467 return kMetadataParseSuccess;
468}
469
Don Garrette410e0f2011-11-10 15:39:01 -0800470// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800471// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700472// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800473bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700474 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700475
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700476 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800477 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800478
479 // Update the total byte downloaded count and the progress logs.
480 total_bytes_received_ += count;
481 UpdateOverallProgress(false, "Completed ");
482
Gilad Arnoldfe133932014-01-14 12:25:50 -0800483 while (!manifest_valid_) {
484 // Read data up to the needed limit; this is either the payload header size,
485 // or the full metadata size (once it becomes known).
486 const bool do_read_header = !metadata_size_;
487 CopyDataToBuffer(&c_bytes, &count,
488 (do_read_header ? GetManifestOffset() :
489 metadata_size_));
490
Gilad Arnolddaa27402014-01-23 11:56:17 -0800491 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700492 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800493 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800494 if (result == kMetadataParseInsufficientData) {
495 // If we just processed the header, make an attempt on the manifest.
496 if (do_read_header && metadata_size_)
497 continue;
498
Don Garrette410e0f2011-11-10 15:39:01 -0800499 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800500 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700501
502 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700503 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700504 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800505 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700506
Gilad Arnoldfe133932014-01-14 12:25:50 -0800507 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800508 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700509 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800510 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700511 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700512
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700513 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700514 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700515 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700516 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800517 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700518 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800519
Allie Woodfdf00512015-03-02 13:34:55 -0800520 // Open source fds if we have a delta payload with minor version 2.
521 if (!install_plan_->is_full_update &&
522 GetMinorVersion() == kSourceMinorPayloadVersion) {
523 if (!OpenSourceRootfs(install_plan_->source_path)) {
524 LOG(ERROR) << "Unable to open source rootfs partition file "
525 << install_plan_->source_path;
526 Close();
527 return false;
528 }
529 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
530 LOG(ERROR) << "Unable to open source kernel partition file "
531 << install_plan_->kernel_source_path;
532 Close();
533 return false;
534 }
535 }
536
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800537 num_rootfs_operations_ = manifest_.install_operations_size();
538 num_total_operations_ =
539 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
540 if (next_operation_num_ > 0)
541 UpdateOverallProgress(true, "Resuming after ");
542 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700543 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800544
545 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700546 // Check if we should cancel the current attempt for any reason.
547 // In this case, *error will have already been populated with the reason
548 // why we're cancelling.
549 if (system_state_->update_attempter()->ShouldCancel(error))
550 return false;
551
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800552 const bool is_kernel_partition =
553 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700554 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800555 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700556 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800557 next_operation_num_ - num_rootfs_operations_) :
558 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800559
560 CopyDataToBuffer(&c_bytes, &count, op.data_length());
561
562 // Check whether we received all of the next operation's data payload.
563 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700564 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700565
Jay Srinivasanf4318702012-09-24 11:56:24 -0700566 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700567 // Otherwise, keep the old behavior. This serves as a knob to disable
568 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800569 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
570 // we would have already failed in ParsePayloadMetadata method and thus not
571 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700572 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700573 // Note: Validate must be called only if CanPerformInstallOperation is
574 // called. Otherwise, we might be failing operations before even if there
575 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800576 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700577 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800578 if (install_plan_->hash_checks_mandatory) {
579 LOG(ERROR) << "Mandatory operation hash check failed";
580 return false;
581 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700582
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800583 // For non-mandatory cases, just send a UMA stat.
584 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700585 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700586 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700587 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700588 }
589
Darin Petkov45580e42010-10-08 14:02:40 -0700590 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700591 ScopedTerminatorExitUnblocker exit_unblocker =
592 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800593
594 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700595 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800596 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
597 op_result = HandleOpResult(
598 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
599 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
600 op_result = HandleOpResult(
601 PerformMoveOperation(op, is_kernel_partition), "move", error);
602 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
603 op_result = HandleOpResult(
604 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Allie Wood9f6f0a52015-03-30 11:25:47 -0700605 else if (op.type() ==
606 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
607 op_result =
608 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
609 "source_copy", error);
610 else if (op.type() ==
611 DeltaArchiveManifest_InstallOperation_Type_SOURCE_BSDIFF)
612 op_result =
613 HandleOpResult(PerformSourceBsdiffOperation(op, is_kernel_partition),
614 "source_bsdiff", error);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800615 else
616 op_result = HandleOpResult(false, "unknown", error);
617
618 if (!op_result)
619 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800620
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700621 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800622 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700623 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700624 }
Don Garrette410e0f2011-11-10 15:39:01 -0800625 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700626}
627
David Zeuthen8f191b22013-08-06 12:27:50 -0700628bool DeltaPerformer::IsManifestValid() {
629 return manifest_valid_;
630}
631
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632bool DeltaPerformer::CanPerformInstallOperation(
633 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
634 operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700635 // Move and source_copy operations don't require any data blob, so they can
636 // always be performed.
637 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
638 operation.type() ==
639 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700640 return true;
641
642 // See if we have the entire data blob in the buffer
643 if (operation.data_offset() < buffer_offset_) {
644 LOG(ERROR) << "we threw away data it seems?";
645 return false;
646 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700647
Gilad Arnoldfe133932014-01-14 12:25:50 -0800648 return (operation.data_offset() + operation.data_length() <=
649 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700650}
651
652bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700653 const DeltaArchiveManifest_InstallOperation& operation,
654 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700655 CHECK(operation.type() == \
656 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
657 operation.type() == \
658 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
659
660 // Since we delete data off the beginning of the buffer as we use it,
661 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700662 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
663 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700664
Darin Petkov437adc42010-10-07 13:12:24 -0700665 // Extract the signature message if it's in this operation.
666 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700667
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700668 DirectExtentWriter direct_writer;
669 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700670 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700671
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 // Since bzip decompression is optional, we have a variable writer that will
673 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700674 ExtentWriter* writer = nullptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700675 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
676 writer = &zero_pad_writer;
677 } else if (operation.type() ==
678 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
679 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
680 writer = bzip_writer.get();
681 } else {
682 NOTREACHED();
683 }
684
685 // Create a vector of extents to pass to the ExtentWriter.
686 vector<Extent> extents;
687 for (int i = 0; i < operation.dst_extents_size(); i++) {
688 extents.push_back(operation.dst_extents(i));
689 }
690
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800691 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700692
693 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800694 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700695 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700696
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700697 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800698 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700699 return true;
700}
701
702bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700703 const DeltaArchiveManifest_InstallOperation& operation,
704 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700705 // Calculate buffer size. Note, this function doesn't do a sliding
706 // window to copy in case the source and destination blocks overlap.
707 // If we wanted to do a sliding window, we could program the server
708 // to generate deltas that effectively did a sliding window.
709
710 uint64_t blocks_to_read = 0;
711 for (int i = 0; i < operation.src_extents_size(); i++)
712 blocks_to_read += operation.src_extents(i).num_blocks();
713
714 uint64_t blocks_to_write = 0;
715 for (int i = 0; i < operation.dst_extents_size(); i++)
716 blocks_to_write += operation.dst_extents(i).num_blocks();
717
718 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800719 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700720
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800721 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700722
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700723 // Read in bytes.
724 ssize_t bytes_read = 0;
725 for (int i = 0; i < operation.src_extents_size(); i++) {
726 ssize_t bytes_read_this_iteration = 0;
727 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200728 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700729 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
730 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
731 &buf[bytes_read],
732 bytes,
733 extent.start_block() * block_size_,
734 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700735 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200736 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700737 bytes_read += bytes_read_this_iteration;
738 }
739
740 // Write bytes out.
741 ssize_t bytes_written = 0;
742 for (int i = 0; i < operation.dst_extents_size(); i++) {
743 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200744 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700745 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
746 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
747 &buf[bytes_written],
748 bytes,
749 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200750 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700751 }
752 DCHECK_EQ(bytes_written, bytes_read);
753 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
754 return true;
755}
756
Allie Wood9f6f0a52015-03-30 11:25:47 -0700757namespace {
758
759// Takes |extents| and fills an empty vector |blocks| with a block index for
760// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
761void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
762 vector<uint64_t>* blocks) {
763 for (Extent ext : extents) {
764 for (uint64_t j = 0; j < ext.num_blocks(); j++)
765 blocks->push_back(ext.start_block() + j);
766 }
767}
768
769// Takes |extents| and returns the number of blocks in those extents.
770uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
771 uint64_t sum = 0;
772 for (Extent ext : extents) {
773 sum += ext.num_blocks();
774 }
775 return sum;
776}
777
778} // namespace
779
780bool DeltaPerformer::PerformSourceCopyOperation(
781 const DeltaArchiveManifest_InstallOperation& operation,
782 bool is_kernel_partition) {
783 if (operation.has_src_length())
784 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
785 if (operation.has_dst_length())
786 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
787
788 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
789 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
790 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
791
792 // Create vectors of all the individual src/dst blocks.
793 vector<uint64_t> src_blocks;
794 vector<uint64_t> dst_blocks;
795 ExtentsToBlocks(operation.src_extents(), &src_blocks);
796 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
797 DCHECK_EQ(src_blocks.size(), blocks_to_read);
798 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
799
800 FileDescriptorPtr src_fd =
801 is_kernel_partition ? source_kernel_fd_ : source_fd_;
802 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
803
804 chromeos::Blob buf(block_size_);
805 ssize_t bytes_read = 0;
806 // Read/write one block at a time.
807 for (uint64_t i = 0; i < blocks_to_read; i++) {
808 ssize_t bytes_read_this_iteration = 0;
809 uint64_t src_block = src_blocks[i];
810 uint64_t dst_block = dst_blocks[i];
811
812 // Read in bytes.
813 TEST_AND_RETURN_FALSE(
814 utils::PReadAll(src_fd,
815 buf.data(),
816 block_size_,
817 src_block * block_size_,
818 &bytes_read_this_iteration));
819
820 // Write bytes out.
821 TEST_AND_RETURN_FALSE(
822 utils::PWriteAll(dst_fd,
823 buf.data(),
824 block_size_,
825 dst_block * block_size_));
826
827 bytes_read += bytes_read_this_iteration;
828 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
829 static_cast<ssize_t>(block_size_));
830 }
831 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
832 return true;
833}
834
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700835bool DeltaPerformer::ExtentsToBsdiffPositionsString(
836 const RepeatedPtrField<Extent>& extents,
837 uint64_t block_size,
838 uint64_t full_length,
839 string* positions_string) {
840 string ret;
841 uint64_t length = 0;
842 for (int i = 0; i < extents.size(); i++) {
843 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700844 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700845 uint64_t this_length = min(full_length - length,
846 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700847 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700848 length += this_length;
849 }
850 TEST_AND_RETURN_FALSE(length == full_length);
851 if (!ret.empty())
852 ret.resize(ret.size() - 1); // Strip trailing comma off
853 *positions_string = ret;
854 return true;
855}
856
857bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700858 const DeltaArchiveManifest_InstallOperation& operation,
859 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700860 // Since we delete data off the beginning of the buffer as we use it,
861 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700862 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
863 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700864
865 string input_positions;
866 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
867 block_size_,
868 operation.src_length(),
869 &input_positions));
870 string output_positions;
871 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
872 block_size_,
873 operation.dst_length(),
874 &output_positions));
875
876 string temp_filename;
877 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
878 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700879 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700880 ScopedPathUnlinker path_unlinker(temp_filename);
881 {
882 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
883 ScopedFdCloser fd_closer(&fd);
884 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800885 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700886 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700887
Darin Petkov7f2ec752013-04-03 14:45:19 +0200888 // Update the buffer to release the patch data memory as soon as the patch
889 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800890 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200891
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800892 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700893 vector<string> cmd{kBspatchPath, path, path, temp_filename,
894 input_positions, output_positions};
895
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700896 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700897 TEST_AND_RETURN_FALSE(
898 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700899 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700900 &return_code,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700901 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700902 TEST_AND_RETURN_FALSE(return_code == 0);
903
904 if (operation.dst_length() % block_size_) {
905 // Zero out rest of final block.
906 // TODO(adlr): build this into bspatch; it's more efficient that way.
907 const Extent& last_extent =
908 operation.dst_extents(operation.dst_extents_size() - 1);
909 const uint64_t end_byte =
910 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
911 const uint64_t begin_byte =
912 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800913 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800914 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700915 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800916 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700917 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700918 return true;
919}
920
Allie Wood9f6f0a52015-03-30 11:25:47 -0700921bool DeltaPerformer::PerformSourceBsdiffOperation(
922 const DeltaArchiveManifest_InstallOperation& operation,
923 bool is_kernel_partition) {
924 // Since we delete data off the beginning of the buffer as we use it,
925 // the data we need should be exactly at the beginning of the buffer.
926 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
927 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
928 if (operation.has_src_length())
929 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
930 if (operation.has_dst_length())
931 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
932
933 string input_positions;
934 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
935 block_size_,
936 operation.src_length(),
937 &input_positions));
938 string output_positions;
939 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
940 block_size_,
941 operation.dst_length(),
942 &output_positions));
943
944 string temp_filename;
945 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
946 &temp_filename,
947 nullptr));
948 ScopedPathUnlinker path_unlinker(temp_filename);
949 {
950 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
951 ScopedFdCloser fd_closer(&fd);
952 TEST_AND_RETURN_FALSE(
953 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
954 }
955
956 // Update the buffer to release the patch data memory as soon as the patch
957 // file is written out.
958 DiscardBuffer(true);
959
960 const string& src_path = is_kernel_partition ?
961 install_plan_->kernel_source_path :
962 install_plan_->source_path;
963 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
964 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
965 input_positions, output_positions};
966
967 int return_code = 0;
968 TEST_AND_RETURN_FALSE(
969 Subprocess::SynchronousExecFlags(cmd,
970 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
971 &return_code,
972 nullptr));
973 TEST_AND_RETURN_FALSE(return_code == 0);
974 return true;
975}
976
Darin Petkovd7061ab2010-10-06 14:37:09 -0700977bool DeltaPerformer::ExtractSignatureMessage(
978 const DeltaArchiveManifest_InstallOperation& operation) {
979 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
980 !manifest_.has_signatures_offset() ||
981 manifest_.signatures_offset() != operation.data_offset()) {
982 return false;
983 }
984 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
985 manifest_.signatures_size() == operation.data_length());
986 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
987 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
988 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700989 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700990 buffer_.begin(),
991 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700992
993 // Save the signature blob because if the update is interrupted after the
994 // download phase we don't go through this path anymore. Some alternatives to
995 // consider:
996 //
997 // 1. On resume, re-download the signature blob from the server and re-verify
998 // it.
999 //
1000 // 2. Verify the signature as soon as it's received and don't checkpoint the
1001 // blob and the signed sha-256 context.
1002 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001003 string(signatures_message_data_.begin(),
1004 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001005 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001006 // The hash of all data consumed so far should be verified against the signed
1007 // hash.
1008 signed_hash_context_ = hash_calculator_.GetContext();
1009 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1010 signed_hash_context_))
1011 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001012 LOG(INFO) << "Extracted signature data of size "
1013 << manifest_.signatures_size() << " at "
1014 << manifest_.signatures_offset();
1015 return true;
1016}
1017
David Zeuthene7f89172013-10-31 10:21:04 -07001018bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1019 if (system_state_->hardware()->IsOfficialBuild() ||
1020 utils::FileExists(public_key_path_.c_str()) ||
1021 install_plan_->public_key_rsa.empty())
1022 return false;
1023
1024 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1025 out_tmp_key))
1026 return false;
1027
1028 return true;
1029}
1030
David Zeuthena99981f2013-04-29 13:42:47 -07001031ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001032 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001033
Jay Srinivasanf4318702012-09-24 11:56:24 -07001034 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001035 if (install_plan_->hash_checks_mandatory) {
1036 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001037 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001038 }
1039
1040 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -07001041 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001042 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
1043 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001044 }
1045
1046 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001047 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001048 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001049 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001050 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1051 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001052 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001053 }
1054
David Zeuthene7f89172013-10-31 10:21:04 -07001055 // See if we should use the public RSA key in the Omaha response.
1056 base::FilePath path_to_public_key(public_key_path_);
1057 base::FilePath tmp_key;
1058 if (GetPublicKeyFromResponse(&tmp_key))
1059 path_to_public_key = tmp_key;
1060 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1061 if (tmp_key.empty())
1062 tmp_key_remover.set_should_remove(false);
1063
1064 LOG(INFO) << "Verifying metadata hash signature using public key: "
1065 << path_to_public_key.value();
1066
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001067 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001068 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1069 path_to_public_key.value(),
1070 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001071 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001073 }
1074
Jay Srinivasanf4318702012-09-24 11:56:24 -07001075 OmahaHashCalculator metadata_hasher;
1076 metadata_hasher.Update(metadata, metadata_size);
1077 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001078 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001079 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001080 }
1081
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001082 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001083 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001084 if (calculated_metadata_hash.empty()) {
1085 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001086 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001087 }
1088
Jay Srinivasanf4318702012-09-24 11:56:24 -07001089 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001090 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001091 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001092 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001093 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001094 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001095 }
1096
David Zeuthenbc27aac2013-11-26 11:17:48 -08001097 // The autoupdate_CatchBadSignatures test checks for this string in
1098 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001099 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001100 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001101}
1102
Gilad Arnold21504f02013-05-24 08:51:22 -07001103ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001104 // Perform assorted checks to sanity check the manifest, make sure it
1105 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001106 //
1107 // TODO(garnold) in general, the presence of an old partition hash should be
1108 // the sole indicator for a delta update, as we would generally like update
1109 // payloads to be self contained and not assume an Omaha response to tell us
1110 // that. However, since this requires some massive reengineering of the update
1111 // flow (making filesystem copying happen conditionally only *after*
1112 // downloading and parsing of the update manifest) we'll put it off for now.
1113 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001114 if (install_plan_->is_full_update) {
1115 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1116 LOG(ERROR) << "Purported full payload contains old partition "
1117 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001119 }
1120
1121 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1122 LOG(ERROR) << "Manifest contains minor version "
1123 << manifest_.minor_version()
1124 << ", but all full payloads should have version "
1125 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001126 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001127 }
1128 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001129 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001130 LOG(ERROR) << "Manifest contains minor version "
1131 << manifest_.minor_version()
1132 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001133 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001134 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001135 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001136 }
1137
1138 // TODO(garnold) we should be adding more and more manifest checks, such as
1139 // partition boundaries etc (see chromium-os:37661).
1140
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001141 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001142}
1143
David Zeuthena99981f2013-04-29 13:42:47 -07001144ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001145 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001146
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001147 if (!operation.data_sha256_hash().size()) {
1148 if (!operation.data_length()) {
1149 // Operations that do not have any data blob won't have any operation hash
1150 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001151 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001152 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001153 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001154 }
1155
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001156 // No hash is present for an operation that has data blobs. This shouldn't
1157 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001158 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001159 // hashes. So if it happens it means either we've turned operation hash
1160 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001161 // One caveat though: The last operation is a dummy signature operation
1162 // that doesn't have a hash at the time the manifest is created. So we
1163 // should not complaint about that operation. This operation can be
1164 // recognized by the fact that it's offset is mentioned in the manifest.
1165 if (manifest_.signatures_offset() &&
1166 manifest_.signatures_offset() == operation.data_offset()) {
1167 LOG(INFO) << "Skipping hash verification for signature operation "
1168 << next_operation_num_ + 1;
1169 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001170 if (install_plan_->hash_checks_mandatory) {
1171 LOG(ERROR) << "Missing mandatory operation hash for operation "
1172 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001173 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001174 }
1175
1176 // For non-mandatory cases, just send a UMA stat.
1177 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1178 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001179 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001180 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001181 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001182 }
1183
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001184 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001185 expected_op_hash.assign(operation.data_sha256_hash().data(),
1186 (operation.data_sha256_hash().data() +
1187 operation.data_sha256_hash().size()));
1188
1189 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001190 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001191 if (!operation_hasher.Finalize()) {
1192 LOG(ERROR) << "Unable to compute actual hash of operation "
1193 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001194 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001195 }
1196
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001197 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001198 if (calculated_op_hash != expected_op_hash) {
1199 LOG(ERROR) << "Hash verification failed for operation "
1200 << next_operation_num_ << ". Expected hash = ";
1201 utils::HexDumpVector(expected_op_hash);
1202 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1203 << " bytes at offset: " << operation.data_offset() << " = ";
1204 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001205 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001206 }
1207
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001208 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001209}
1210
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001211#define TEST_AND_RETURN_VAL(_retval, _condition) \
1212 do { \
1213 if (!(_condition)) { \
1214 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1215 return _retval; \
1216 } \
1217 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001218
David Zeuthena99981f2013-04-29 13:42:47 -07001219ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001220 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001221 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001222
1223 // See if we should use the public RSA key in the Omaha response.
1224 base::FilePath path_to_public_key(public_key_path_);
1225 base::FilePath tmp_key;
1226 if (GetPublicKeyFromResponse(&tmp_key))
1227 path_to_public_key = tmp_key;
1228 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1229 if (tmp_key.empty())
1230 tmp_key_remover.set_should_remove(false);
1231
1232 LOG(INFO) << "Verifying payload using public key: "
1233 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001234
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001235 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001236 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001237 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001238 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001239
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001240 // Verifies the payload hash.
1241 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001242 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001243 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001244 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001245 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001246
Darin Petkov437adc42010-10-07 13:12:24 -07001247 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001248 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001249 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001251 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001252 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001253 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001254 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001255 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001256 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001257 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001258 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001259 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001260 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001261 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001262 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001263 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001264 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001265 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001266 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001267 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001268 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001269 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001270 // The autoupdate_CatchBadSignatures test checks for this string
1271 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001272 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001273 "Attached Signature:";
1274 utils::HexDumpVector(signed_hash_data);
1275 LOG(ERROR) << "Computed Signature:";
1276 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001277 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001278 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001279
David Zeuthene7f89172013-10-31 10:21:04 -07001280 LOG(INFO) << "Payload hash matches value in payload.";
1281
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001282 // At this point, we are guaranteed to have downloaded a full payload, i.e
1283 // the one whose size matches the size mentioned in Omaha response. If any
1284 // errors happen after this, it's likely a problem with the payload itself or
1285 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001286 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001287 system_state_->payload_state()->DownloadComplete();
1288
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001289 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001290}
1291
Darin Petkov3aefa862010-12-07 14:45:00 -08001292bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001293 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001294 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001295 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001296 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1297 manifest_.has_new_kernel_info() &&
1298 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001299 *kernel_size = manifest_.new_kernel_info().size();
1300 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001301 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1302 manifest_.new_kernel_info().hash().end());
1303 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1304 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001305 kernel_hash->swap(new_kernel_hash);
1306 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001307 return true;
1308}
1309
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001310namespace {
1311void LogVerifyError(bool is_kern,
1312 const string& local_hash,
1313 const string& expected_hash) {
1314 const char* type = is_kern ? "kernel" : "rootfs";
1315 LOG(ERROR) << "This is a server-side error due to "
1316 << "mismatched delta update image!";
1317 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1318 << "update that must be applied over a " << type << " with "
1319 << "a specific checksum, but the " << type << " we're starting "
1320 << "with doesn't have that checksum! This means that "
1321 << "the delta I've been given doesn't match my existing "
1322 << "system. The " << type << " partition I have has hash: "
1323 << local_hash << " but the update expected me to have "
1324 << expected_hash << " .";
1325 if (is_kern) {
1326 LOG(INFO) << "To get the checksum of a kernel partition on a "
1327 << "booted machine, run this command (change /dev/sda2 "
1328 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1329 << "openssl dgst -sha256 -binary | openssl base64";
1330 } else {
1331 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1332 << "booted machine, run this command (change /dev/sda3 "
1333 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1334 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1335 << "| sed 's/[^0-9]*//') / 256 )) | "
1336 << "openssl dgst -sha256 -binary | openssl base64";
1337 }
1338 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1339 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1340}
1341
1342string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001343 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001344}
1345} // namespace
1346
Darin Petkov698d0412010-10-13 10:59:44 -07001347bool DeltaPerformer::VerifySourcePartitions() {
1348 LOG(INFO) << "Verifying source partitions.";
1349 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001350 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001351 if (manifest_.has_old_kernel_info()) {
1352 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001353 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001354 !install_plan_->source_kernel_hash.empty() &&
1355 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1356 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001357 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001358 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001359 if (!valid) {
1360 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001361 StringForHashBytes(
1362 install_plan_->source_kernel_hash.data(),
1363 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001364 StringForHashBytes(info.hash().data(),
1365 info.hash().size()));
1366 }
1367 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001368 }
1369 if (manifest_.has_old_rootfs_info()) {
1370 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001371 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001372 !install_plan_->source_rootfs_hash.empty() &&
1373 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1374 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001375 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001376 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001377 if (!valid) {
1378 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001379 StringForHashBytes(
1380 install_plan_->source_rootfs_hash.data(),
1381 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001382 StringForHashBytes(info.hash().data(),
1383 info.hash().size()));
1384 }
1385 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001386 }
1387 return true;
1388}
1389
Gilad Arnolddaa27402014-01-23 11:56:17 -08001390void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001391 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001392 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001393 buffer_offset_ += buffer_.size();
1394
1395 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001396 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001397
1398 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001399 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001400}
1401
Darin Petkov0406e402010-10-06 21:33:11 -07001402bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1403 string update_check_response_hash) {
1404 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001405 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1406 next_operation != kUpdateStateOperationInvalid &&
1407 next_operation > 0))
1408 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001409
1410 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001411 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1412 !interrupted_hash.empty() &&
1413 interrupted_hash == update_check_response_hash))
1414 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001415
Darin Petkov61426142010-10-08 11:04:55 -07001416 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001417 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1418 && resumed_update_failures > kMaxResumedUpdateFailures))
1419 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001420
Darin Petkov0406e402010-10-06 21:33:11 -07001421 // Sanity check the rest.
1422 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001423 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1424 next_data_offset >= 0))
1425 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001426
Darin Petkov437adc42010-10-07 13:12:24 -07001427 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001428 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1429 !sha256_context.empty()))
1430 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001431
1432 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001433 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1434 manifest_metadata_size > 0))
1435 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001436
1437 return true;
1438}
1439
Darin Petkov9b230572010-10-08 10:20:09 -07001440bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001441 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1442 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001443 if (!quick) {
1444 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1445 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001446 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001447 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1448 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001449 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001450 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001451 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001452 }
Darin Petkov73058b42010-10-06 16:32:19 -07001453 return true;
1454}
1455
1456bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001457 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001458 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001459 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001460 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001461 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001462 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001463 hash_calculator_.GetContext()));
1464 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1465 buffer_offset_));
1466 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001467
1468 if (next_operation_num_ < num_total_operations_) {
1469 const bool is_kernel_partition =
1470 next_operation_num_ >= num_rootfs_operations_;
1471 const DeltaArchiveManifest_InstallOperation &op =
1472 is_kernel_partition ?
1473 manifest_.kernel_install_operations(
1474 next_operation_num_ - num_rootfs_operations_) :
1475 manifest_.install_operations(next_operation_num_);
1476 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1477 op.data_length()));
1478 } else {
1479 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1480 0));
1481 }
Darin Petkov0406e402010-10-06 21:33:11 -07001482 }
Darin Petkov73058b42010-10-06 16:32:19 -07001483 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1484 next_operation_num_));
1485 return true;
1486}
1487
Darin Petkov9b230572010-10-08 10:20:09 -07001488bool DeltaPerformer::PrimeUpdateState() {
1489 CHECK(manifest_valid_);
1490 block_size_ = manifest_.block_size();
1491
1492 int64_t next_operation = kUpdateStateOperationInvalid;
1493 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1494 next_operation == kUpdateStateOperationInvalid ||
1495 next_operation <= 0) {
1496 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001497 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001498 return true;
1499 }
1500 next_operation_num_ = next_operation;
1501
1502 // Resuming an update -- load the rest of the update state.
1503 int64_t next_data_offset = -1;
1504 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1505 &next_data_offset) &&
1506 next_data_offset >= 0);
1507 buffer_offset_ = next_data_offset;
1508
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001509 // The signed hash context and the signature blob may be empty if the
1510 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001511 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1512 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001513 string signature_blob;
1514 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1515 signatures_message_data_.assign(signature_blob.begin(),
1516 signature_blob.end());
1517 }
Darin Petkov9b230572010-10-08 10:20:09 -07001518
1519 string hash_context;
1520 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1521 &hash_context) &&
1522 hash_calculator_.SetContext(hash_context));
1523
1524 int64_t manifest_metadata_size = 0;
1525 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1526 &manifest_metadata_size) &&
1527 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001528 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001529
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001530 // Advance the download progress to reflect what doesn't need to be
1531 // re-downloaded.
1532 total_bytes_received_ += buffer_offset_;
1533
Darin Petkov61426142010-10-08 11:04:55 -07001534 // Speculatively count the resume as a failure.
1535 int64_t resumed_update_failures;
1536 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1537 resumed_update_failures++;
1538 } else {
1539 resumed_update_failures = 1;
1540 }
1541 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001542 return true;
1543}
1544
David Zeuthena99981f2013-04-29 13:42:47 -07001545void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001546 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001547}
1548
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001549} // namespace chromeos_update_engine